code stringlengths 4 1.01M | language stringclasses 2 values |
|---|---|
var baseClone = require('./_baseClone');
/**
* This method is like `_.clone` except that it accepts `customizer` which
* is invoked to produce the cloned value. If `customizer` returns `undefined`,
* cloning is handled by the method instead. The `customizer` is invoked with
* up to four arguments; (value [, index|key, object, stack]).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to clone.
* @param {Function} [customizer] The function to customize cloning.
* @returns {*} Returns the cloned value.
* @see _.cloneDeepWith
* @example
*
* function customizer(value) {
* if (_.isElement(value)) {
* return value.cloneNode(false);
* }
* }
*
* var el = _.cloneWith(document.body, customizer);
*
* console.log(el === document.body);
* // => false
* console.log(el.nodeName);
* // => 'BODY'
* console.log(el.childNodes.length);
* // => 0
*/
function cloneWith(value, customizer) {
customizer = typeof customizer == 'function' ? customizer : undefined;
return baseClone(value, false, true, customizer);
}
module.exports = cloneWith;
| Java |
# Copyright 2015 Google 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.
# ==============================================================================
"""Tests for tensorflow.ops.math_ops.matmul."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow.python.platform
import numpy as np
import tensorflow as tf
from tensorflow.python.kernel_tests import gradient_checker as gc
class MatMulTest(tf.test.TestCase):
def _testCpuMatmul(self, x, y, transpose_x=False, transpose_y=False):
x_mat = np.matrix(x).T if transpose_x else np.matrix(x)
y_mat = np.matrix(y).T if transpose_y else np.matrix(y)
np_ans = x_mat * y_mat
with self.test_session(use_gpu=False):
tf_ans = tf.matmul(x, y, transpose_x, transpose_y).eval()
self.assertAllClose(np_ans, tf_ans)
self.assertAllEqual(np_ans.shape, tf_ans.shape)
def _testGpuMatmul(self, x, y, transpose_x=False, transpose_y=False):
x_mat = np.matrix(x).T if transpose_x else np.matrix(x)
y_mat = np.matrix(y).T if transpose_y else np.matrix(y)
np_ans = x_mat * y_mat
with self.test_session(use_gpu=True):
tf_ans = tf.matmul(x, y, transpose_x, transpose_y).eval()
self.assertAllClose(np_ans, tf_ans)
self.assertAllEqual(np_ans.shape, tf_ans.shape)
def _randMatrix(self, rows, cols, dtype):
if dtype is np.complex64:
real = self._randMatrix(rows, cols, np.float32)
imag = self._randMatrix(rows, cols, np.float32)
return real + np.complex(0, 1) * imag
else:
return np.random.uniform(low=1.0, high=100.0, size=rows * cols).reshape(
[rows, cols]).astype(dtype)
# Basic test:
# [ [1],
# [2],
# [3], * [1, 2]
# [4] ]
def testFloatBasic(self):
x = np.arange(1., 5.).reshape([4, 1]).astype(np.float32)
y = np.arange(1., 3.).reshape([1, 2]).astype(np.float32)
self._testCpuMatmul(x, y)
self._testGpuMatmul(x, y)
def testDoubleBasic(self):
x = np.arange(1., 5.).reshape([4, 1]).astype(np.float64)
y = np.arange(1., 3.).reshape([1, 2]).astype(np.float64)
self._testCpuMatmul(x, y)
def testInt32Basic(self):
x = np.arange(1., 5.).reshape([4, 1]).astype(np.int32)
y = np.arange(1., 3.).reshape([1, 2]).astype(np.int32)
self._testCpuMatmul(x, y)
def testSComplexBasic(self):
x = np.arange(1., 5.).reshape([4, 1]).astype(np.complex64)
y = np.arange(1., 3.).reshape([1, 2]).astype(np.complex64)
self._testCpuMatmul(x, y)
# Tests testing random sized matrices.
def testFloatRandom(self):
for _ in range(10):
n, k, m = np.random.randint(1, 100, size=3)
x = self._randMatrix(n, k, np.float32)
y = self._randMatrix(k, m, np.float32)
self._testCpuMatmul(x, y)
self._testGpuMatmul(x, y)
def testDoubleRandom(self):
for _ in range(10):
n, k, m = np.random.randint(1, 100, size=3)
x = self._randMatrix(n, k, np.float64)
y = self._randMatrix(k, m, np.float64)
self._testCpuMatmul(x, y)
def testInt32Random(self):
for _ in range(10):
n, k, m = np.random.randint(1, 100, size=3)
x = self._randMatrix(n, k, np.int32)
y = self._randMatrix(k, m, np.int32)
self._testCpuMatmul(x, y)
def testSComplexRandom(self):
for _ in range(10):
n, k, m = np.random.randint(1, 100, size=3)
x = self._randMatrix(n, k, np.complex64)
y = self._randMatrix(k, m, np.complex64)
self._testCpuMatmul(x, y)
# Test the cases that transpose the matrices before multiplying.
# NOTE(keveman): The cases where only one of the inputs is
# transposed are covered by tf.matmul's gradient function.
def testFloatRandomTransposeBoth(self):
for _ in range(10):
n, k, m = np.random.randint(1, 100, size=3)
x = self._randMatrix(k, n, np.float32)
y = self._randMatrix(m, k, np.float32)
self._testCpuMatmul(x, y, True, True)
self._testGpuMatmul(x, y, True, True)
def testDoubleRandomTranposeBoth(self):
for _ in range(10):
n, k, m = np.random.randint(1, 100, size=3)
x = self._randMatrix(k, n, np.float64)
y = self._randMatrix(m, k, np.float64)
self._testCpuMatmul(x, y, True, True)
def testMatMul_OutEmpty_A(self):
n, k, m = 0, 8, 3
x = self._randMatrix(n, k, np.float32)
y = self._randMatrix(k, m, np.float32)
self._testCpuMatmul(x, y)
self._testGpuMatmul(x, y)
def testMatMul_OutEmpty_B(self):
n, k, m = 3, 8, 0
x = self._randMatrix(n, k, np.float32)
y = self._randMatrix(k, m, np.float32)
self._testCpuMatmul(x, y)
self._testGpuMatmul(x, y)
def testMatMul_Inputs_Empty(self):
n, k, m = 3, 0, 4
x = self._randMatrix(n, k, np.float32)
y = self._randMatrix(k, m, np.float32)
self._testCpuMatmul(x, y)
self._testGpuMatmul(x, y)
# TODO(zhifengc): Figures out how to test matmul gradients on GPU.
class MatMulGradientTest(tf.test.TestCase):
def testGradientInput0(self):
with self.test_session(use_gpu=False):
x = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[3, 2],
dtype=tf.float64, name="x")
y = tf.constant([1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7],
shape=[2, 4], dtype=tf.float64, name="y")
m = tf.matmul(x, y, name="matmul")
err = gc.ComputeGradientError(x, [3, 2], m, [3, 4])
print("matmul input0 gradient err = ", err)
self.assertLess(err, 1e-10)
def testGradientInput1(self):
with self.test_session(use_gpu=False):
x = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[3, 2],
dtype=tf.float64, name="x")
y = tf.constant([1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7],
shape=[2, 4], dtype=tf.float64, name="y")
m = tf.matmul(x, y, name="matmul")
err = gc.ComputeGradientError(y, [2, 4], m, [3, 4])
print("matmul input1 gradient err = ", err)
self.assertLess(err, 1e-10)
def _VerifyInput0(self, transpose_a, transpose_b):
shape_x = [3, 2]
shape_y = [2, 4]
if transpose_a:
shape_x = list(reversed(shape_x))
if transpose_b:
shape_y = list(reversed(shape_y))
with self.test_session(use_gpu=False):
x = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=shape_x,
dtype=tf.float64, name="x")
y = tf.constant([1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7],
shape=shape_y, dtype=tf.float64, name="y")
m = tf.matmul(x, y, transpose_a, transpose_b, name="matmul")
err = gc.ComputeGradientError(x, shape_x, m, [3, 4])
print("matmul input0 gradient err = ", err)
self.assertLess(err, 1e-10)
def testGradientInput0WithTranspose(self):
self._VerifyInput0(transpose_a=True, transpose_b=False)
self._VerifyInput0(transpose_a=False, transpose_b=True)
self._VerifyInput0(transpose_a=True, transpose_b=True)
def _VerifyInput1(self, transpose_a, transpose_b):
shape_x = [3, 2]
shape_y = [2, 4]
if transpose_a:
shape_x = list(reversed(shape_x))
if transpose_b:
shape_y = list(reversed(shape_y))
with self.test_session(use_gpu=False):
x = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=shape_x,
dtype=tf.float64, name="x")
y = tf.constant([1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7],
shape=shape_y, dtype=tf.float64, name="y")
m = tf.matmul(x, y, transpose_a, transpose_b, name="matmul")
err = gc.ComputeGradientError(y, shape_y, m, [3, 4])
print("matmul input1 gradient err = ", err)
self.assertLess(err, 1e-10)
def testGradientInput1WithTranspose(self):
self._VerifyInput1(transpose_a=True, transpose_b=False)
self._VerifyInput1(transpose_a=False, transpose_b=True)
self._VerifyInput1(transpose_a=True, transpose_b=True)
if __name__ == "__main__":
tf.test.main()
| Java |
/*
* #!
* Ontopoly Editor
* #-
* Copyright (C) 2001 - 2013 The Ontopia Project
* #-
* 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 ontopoly.components;
import java.util.Objects;
import net.ontopia.topicmaps.core.OccurrenceIF;
import ontopoly.model.FieldInstance;
import ontopoly.models.FieldValueModel;
import ontopoly.pages.AbstractOntopolyPage;
import ontopoly.validators.ExternalValidation;
import ontopoly.validators.RegexValidator;
import org.apache.wicket.markup.ComponentTag;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.model.Model;
public class FieldInstanceNumberField extends TextField<String> {
private FieldValueModel fieldValueModel;
private String oldValue;
private String cols = "20";
public FieldInstanceNumberField(String id, FieldValueModel fieldValueModel) {
super(id);
this.fieldValueModel = fieldValueModel;
OccurrenceIF occ = (OccurrenceIF)fieldValueModel.getObject();
this.oldValue = (occ == null ? null : occ.getValue());
setModel(new Model<String>(oldValue));
add(new RegexValidator(this, fieldValueModel.getFieldInstanceModel()) {
@Override
protected String getRegex() {
return "^[-+]?\\d+(\\.\\d+)?$";
}
@Override
protected String resourceKeyInvalidValue() {
return "validators.RegexValidator.number";
}
});
// validate field using registered validators
ExternalValidation.validate(this, oldValue);
}
public void setCols(int cols) {
this.cols = Integer.toString(cols);
}
@Override
protected void onComponentTag(ComponentTag tag) {
tag.setName("input");
tag.put("type", "text");
tag.put("size", cols);
super.onComponentTag(tag);
}
@Override
protected void onModelChanged() {
super.onModelChanged();
String newValue = (String)getModelObject();
if (Objects.equals(newValue, oldValue)) return;
AbstractOntopolyPage page = (AbstractOntopolyPage)getPage();
FieldInstance fieldInstance = fieldValueModel.getFieldInstanceModel().getFieldInstance();
if (fieldValueModel.isExistingValue() && oldValue != null)
fieldInstance.removeValue(oldValue, page.getListener());
if (newValue != null && !newValue.equals("")) {
fieldInstance.addValue(newValue, page.getListener());
fieldValueModel.setExistingValue(newValue);
}
oldValue = newValue;
}
}
| Java |
<!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_45) on Tue Jul 28 00:20:21 PDT 2015 -->
<title>Uses of Package org.apache.zookeeper.client (ZooKeeper 3.5.1-alpha API)</title>
<meta name="date" content="2015-07-28">
<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.apache.zookeeper.client (ZooKeeper 3.5.1-alpha 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>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/apache/zookeeper/client/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.apache.zookeeper.client" class="title">Uses of Package<br>org.apache.zookeeper.client</h1>
</div>
<div class="contentContainer">No usage of org.apache.zookeeper.client</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>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/apache/zookeeper/client/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 © 2015 The Apache Software Foundation</small></p>
</body>
</html>
| Java |
This quick start guide will teach you how to wire up TypeScript with [Knockout.js](http://knockoutjs.com/).
We assume that you're already using [Node.js](https://nodejs.org/) with [npm](https://www.npmjs.com/).
# Lay out the project
Let's start out with a new directory.
We'll name it `proj` for now, but you can change it to whatever you want.
```shell
mkdir proj
cd proj
```
To start, we're going to structure our project in the following way:
```text
proj/
+- src/
+- built/
```
TypeScript files will start out in your `src` folder, run through the TypeScript compiler, and end up in `built`.
Let's scaffold this out:
```shell
mkdir src
mkdir built
```
# Install our build dependencies
First ensure TypeScript and Typings are installed globally.
```shell
npm install -g typescript typings
```
You obviously know about TypeScript, but you might not know about Typings.
[Typings](https://www.npmjs.com/package/typings) is a package manager for grabbing definition files.
We'll now use Typings to grab declaration files for Knockout:
```shell
typings install --global --save dt~knockout
```
The `--global` flag will tell Typings to grab any declaration files from [DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped), a repository of community-authored `.d.ts` files.
This command will create a file called `typings.json` and a folder called `typings` in the current directory.
# Grab our runtime dependencies
We'll need to grab Knockout itself, as well as something called RequireJS.
[RequireJS](http://www.requirejs.org/) is a library that enables us to load modules at runtime asynchronously.
There are several ways we can go about this:
1. Download the files manually and host them.
2. Download the files through a package manager like [Bower](http://bower.io/) and host them.
3. Use a Content Delivery Network (CDN) to host both files.
We'll keep it simple and go with the first option, but Knockout's documentation has [details on using a CDN](http://knockoutjs.com/downloads/index.html), and more libraries like RequireJS can be searched for on [cdnjs](https://cdnjs.com/).
Let's create an `externals` folder in the root of our project.
```shell
mkdir externals
```
Now [download Knockout](http://knockoutjs.com/downloads/index.html) and [download RequireJS](http://www.requirejs.org/docs/download.html#latest) into that folder.
The latest and minified versions of the files should work just fine.
# Add a TypeScript configuration file
You'll want to bring your TypeScript files together - both the code you'll be writing as well as any necessary declaration files.
To do this, you'll need to create a `tsconfig.json` which contains a list of your input files as well as all your compilation settings.
Simply create a new file in your project root named `tsconfig.json` and fill it with the following contents:
```json
{
"compilerOptions": {
"outDir": "./built/",
"sourceMap": true,
"noImplicitAny": true,
"module": "amd",
"target": "es5"
},
"files": [
"./typings/index.d.ts",
"./src/require-config.ts",
"./src/hello.ts"
]
}
```
We're including `typings/index.d.ts`, which Typings created for us.
That file automatically includes all of your installed dependencies.
You can learn more about `tsconfig.json` files [here](../tsconfig.json.md).
# Write some code
Let's write our first TypeScript file using Knockout.
First, create a new file in your `src` directory named `hello.ts`.
```ts
import * as ko from "knockout";
class HelloViewModel {
language: KnockoutObservable<string>
framework: KnockoutObservable<string>
constructor(language: string, framework: string) {
this.language = ko.observable(language);
this.framework = ko.observable(framework);
}
}
ko.applyBindings(new HelloViewModel("TypeScript", "Knockout"));
```
Next, we'll create a file named `require-config.ts` in `src` as well.
```ts
declare var require: any;
require.config({
paths: {
"knockout": "externals/knockout-3.4.0",
}
});
```
This file will tell RequireJS where to find Knockout when we import it, just like we did in `hello.ts`.
Any page that you create should include this immediately after RequireJS, but before importing anything else.
To get a better understanding of this file and how to configure RequireJS, you can [read up on its documentation](http://requirejs.org/docs/api.html#config).
We'll also need a view to display our `HelloViewModel`.
Create a file at the root of `proj` named `index.html` with the following contents:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Hello Knockout!</title>
</head>
<body>
<p>
Hello from
<strong data-bind="text: language">todo</strong>
and
<strong data-bind="text: framework">todo</strong>!
</p>
<p>Language: <input data-bind="value: language" /></p>
<p>Framework: <input data-bind="value: framework" /></p>
<script src="./externals/require.js"></script>
<script src="./built/require-config.js"></script>
<script>
require(["built/hello"]);
</script>
</body>
</html>
```
Notice there are three script tags.
First, we're including RequireJS itself.
Then we're mapping the paths of our external dependencies in `require-config.js` so that RequireJS knows where to look for them.
Finally, we're calling `require` with a list of modules we'd like to load.
# Putting it all together
Just run:
```shell
tsc
```
Now open up `index.html` in your favorite browser and everything should be ready to use!
You should see a page that says "Hello from TypeScript and Knockout!"
Below that, you'll also see two input boxes.
As you modify their contents and switch focus, you'll see that the original message changes.
| Java |
/**********************************************************************
Copyright (c) 2006 Erik Bengtson and others. 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.
Contributors:
...
**********************************************************************/
package org.jpox.samples.types.stringbuffer;
/**
* Object with a StringBuffer.
*/
public class StringBufferHolder
{
StringBuffer sb = new StringBuffer();
public StringBuffer getStringBuffer()
{
return sb;
}
public void setStringBuffer(StringBuffer sb)
{
this.sb = sb;
}
public void appendText(String text)
{
// Since DataNucleus doesn't support updates to the contents of a StringBuffer we replace it
StringBuffer sb2 = new StringBuffer(sb.append(text));
sb = sb2;
}
public String getText()
{
return sb.toString();
}
} | Java |
/*
* 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.importexport.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.Request;
import com.amazonaws.DefaultRequest;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.importexport.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.util.StringUtils;
/**
* CancelJobRequest Marshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class CancelJobRequestMarshaller implements Marshaller<Request<CancelJobRequest>, CancelJobRequest> {
public Request<CancelJobRequest> marshall(CancelJobRequest cancelJobRequest) {
if (cancelJobRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
Request<CancelJobRequest> request = new DefaultRequest<CancelJobRequest>(cancelJobRequest, "AmazonImportExport");
request.addParameter("Action", "CancelJob");
request.addParameter("Version", "2010-06-01");
request.setHttpMethod(HttpMethodName.POST);
if (cancelJobRequest.getJobId() != null) {
request.addParameter("JobId", StringUtils.fromString(cancelJobRequest.getJobId()));
}
if (cancelJobRequest.getAPIVersion() != null) {
request.addParameter("APIVersion", StringUtils.fromString(cancelJobRequest.getAPIVersion()));
}
return request;
}
}
| Java |
/*
* 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.personalize.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.AmazonWebServiceRequest;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/personalize-2018-05-22/DescribeAlgorithm" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DescribeAlgorithmRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {
/**
* <p>
* The Amazon Resource Name (ARN) of the algorithm to describe.
* </p>
*/
private String algorithmArn;
/**
* <p>
* The Amazon Resource Name (ARN) of the algorithm to describe.
* </p>
*
* @param algorithmArn
* The Amazon Resource Name (ARN) of the algorithm to describe.
*/
public void setAlgorithmArn(String algorithmArn) {
this.algorithmArn = algorithmArn;
}
/**
* <p>
* The Amazon Resource Name (ARN) of the algorithm to describe.
* </p>
*
* @return The Amazon Resource Name (ARN) of the algorithm to describe.
*/
public String getAlgorithmArn() {
return this.algorithmArn;
}
/**
* <p>
* The Amazon Resource Name (ARN) of the algorithm to describe.
* </p>
*
* @param algorithmArn
* The Amazon Resource Name (ARN) of the algorithm to describe.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeAlgorithmRequest withAlgorithmArn(String algorithmArn) {
setAlgorithmArn(algorithmArn);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getAlgorithmArn() != null)
sb.append("AlgorithmArn: ").append(getAlgorithmArn());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof DescribeAlgorithmRequest == false)
return false;
DescribeAlgorithmRequest other = (DescribeAlgorithmRequest) obj;
if (other.getAlgorithmArn() == null ^ this.getAlgorithmArn() == null)
return false;
if (other.getAlgorithmArn() != null && other.getAlgorithmArn().equals(this.getAlgorithmArn()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getAlgorithmArn() == null) ? 0 : getAlgorithmArn().hashCode());
return hashCode;
}
@Override
public DescribeAlgorithmRequest clone() {
return (DescribeAlgorithmRequest) super.clone();
}
}
| Java |
package testPpermission;
import android.annotation.TargetApi;
import android.app.Application;
import android.os.Build;
/**
* Created by nubor on 13/02/2017.
*/
public class App extends Application {
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) @Override public void onCreate() {
super.onCreate();
this.registerActivityLifecycleCallbacks(new AppLifeCycle() );
}
}
| Java |
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="refresh" content="0;URL=type.U27.html">
</head>
<body>
<p>Redirecting to <a href="type.U27.html">type.U27.html</a>...</p>
<script>location.replace("type.U27.html" + location.search + location.hash);</script>
</body>
</html> | Java |
package com.couchbase.lite.testapp.ektorp.tests;
import org.ektorp.support.OpenCouchDbDocument;
import java.util.List;
import java.util.Set;
@SuppressWarnings("serial")
public class TestObject extends OpenCouchDbDocument {
private Integer foo;
private Boolean bar;
private String baz;
private String status;
private String key;
private List<String> stuff;
private Set<String> stuffSet;
public Set<String> getStuffSet() {
return stuffSet;
}
public void setStuffSet(Set<String> stuffSet) {
this.stuffSet = stuffSet;
}
public List<String> getStuff() {
return stuff;
}
public void setStuff(List<String> stuff) {
this.stuff = stuff;
}
public Integer getFoo() {
return foo;
}
public void setFoo(Integer foo) {
this.foo = foo;
}
public Boolean getBar() {
return bar;
}
public void setBar(Boolean bar) {
this.bar = bar;
}
public String getBaz() {
return baz;
}
public void setBaz(String baz) {
this.baz = baz;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public TestObject() {
}
public TestObject(Integer foo, Boolean bar, String baz) {
this.foo = foo;
this.bar = bar;
this.baz = baz;
this.status = null;
}
public TestObject(Integer foo, Boolean bar, String baz, String status) {
this.foo = foo;
this.bar = bar;
this.baz = baz;
this.status = status;
}
public TestObject(String id, String key) {
this.setId(id);
this.key = key;
}
@Override
public boolean equals(Object o) {
if(o instanceof TestObject) {
TestObject other = (TestObject)o;
if(getId() != null && other.getId() != null && getId().equals(other.getId())) {
return true;
}
}
return false;
}
}
| Java |
package libgbust
import (
"io/ioutil"
"net/http"
"net/url"
"unicode/utf8"
)
// CheckDir is used to execute a directory check
func (a *Attacker) CheckDir(word string) *Result {
end, err := url.Parse(word)
if err != nil {
return &Result{
Msg: "[!] failed to parse word",
Err: err,
}
}
fullURL := a.config.URL.ResolveReference(end)
req, err := http.NewRequest("GET", fullURL.String(), nil)
if err != nil {
return &Result{
Msg: "[!] failed to create new request",
Err: err,
}
}
for _, cookie := range a.config.Cookies {
req.Header.Set("Cookie", cookie)
}
resp, err := a.client.Do(req)
if err != nil {
return &Result{
Err: err,
Msg: "[!] failed to do request",
}
}
defer resp.Body.Close()
length := new(int64)
if resp.ContentLength <= 0 {
body, err := ioutil.ReadAll(resp.Body)
if err == nil {
*length = int64(utf8.RuneCountInString(string(body)))
}
} else {
*length = resp.ContentLength
}
return &Result{
StatusCode: resp.StatusCode,
Size: length,
URL: resp.Request.URL,
}
}
| Java |
# Uragoga erythrantha Kuntze SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | Java |
# Unona buchananii Engl. SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | Java |
# Stecchericium solomonense Corner, 1989 SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
Beih. Nova Hedwigia 96: 124 (1989)
#### Original name
Stecchericium solomonense Corner, 1989
### Remarks
null | Java |
# Tasmannia coriacea (Pulle) A.C.Sm. SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | Java |
# Carex diclina Phil. SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | Java |
# Otopappus pittieri (Greenm.) B.L.Turner SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
Zexmenia pittieri Greenm.
### Remarks
null | Java |
# Schima beccarii Warb. SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | Java |
# Amyridaceae Kunth FAMILY
#### Status
SYNONYM
#### According to
GRIN Taxonomy for Plants
#### Published in
null
#### Original name
null
### Remarks
null | Java |
# Eugenia turneri McVaugh SPECIES
#### Status
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | Java |
# Ebnerella moelleriana (Boed.) P.Buxb. SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | Java |
# Biophytum casiquiarense Knuth SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | Java |
# Gigotorcya Buc'hoz GENUS
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | Java |
/**
* 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.s4.comm.zk;
import org.apache.s4.comm.core.CommEventCallback;
import org.apache.s4.comm.core.DefaultWatcher;
import org.apache.s4.comm.core.TaskManager;
import org.apache.s4.comm.util.JSONUtil;
import org.apache.s4.comm.util.ConfigParser.Cluster.ClusterType;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import org.apache.log4j.Logger;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.data.Stat;
public class ZkTaskManager extends DefaultWatcher implements TaskManager {
static Logger logger = Logger.getLogger(ZkTaskManager.class);
String tasksListRoot;
String processListRoot;
public ZkTaskManager(String address, String ClusterName, ClusterType clusterType) {
this(address, ClusterName, clusterType, null);
}
/**
* Constructor of TaskManager
*
* @param address
* @param ClusterName
*/
public ZkTaskManager(String address, String ClusterName, ClusterType clusterType,
CommEventCallback callbackHandler) {
super(address, callbackHandler);
this.root = "/" + ClusterName + "/" + clusterType.toString();
this.tasksListRoot = root + "/task";
this.processListRoot = root + "/process";
}
/**
* This will block the process thread from starting the task, when it is
* unblocked it will return the data stored in the task node. This data can
* be used by the This call assumes that the tasks are already set up
*
* @return Object containing data related to the task
*/
@Override
public Object acquireTask(Map<String, String> customTaskData) {
while (true) {
synchronized (mutex) {
try {
Stat tExists = zk.exists(tasksListRoot, false);
if (tExists == null) {
logger.error("Tasks znode:" + tasksListRoot
+ " not setup.Going to wait");
tExists = zk.exists(tasksListRoot, true);
if (tExists == null) {
mutex.wait();
}
continue;
}
Stat pExists = zk.exists(processListRoot, false);
if (pExists == null) {
logger.error("Process root znode:" + processListRoot
+ " not setup.Going to wait");
pExists = zk.exists(processListRoot, true);
if (pExists == null) {
mutex.wait();
}
continue;
}
// setting watch true to tasks node will trigger call back
// if there is any change to task node,
// this is useful to add additional tasks
List<String> tasks = zk.getChildren(tasksListRoot, true);
List<String> processes = zk.getChildren(processListRoot,
true);
if (processes.size() < tasks.size()) {
ArrayList<String> tasksAvailable = new ArrayList<String>();
for (int i = 0; i < tasks.size(); i++) {
tasksAvailable.add("" + i);
}
if (processes != null) {
for (String s : processes) {
String taskId = s.split("-")[1];
tasksAvailable.remove(taskId);
}
}
// try pick up a random task
Random random = new Random();
int id = Integer.parseInt(tasksAvailable.get(random.nextInt(tasksAvailable.size())));
String pNode = processListRoot + "/" + "task-" + id;
String tNode = tasksListRoot + "/" + "task-" + id;
Stat pNodeStat = zk.exists(pNode, false);
if (pNodeStat == null) {
Stat tNodeStat = zk.exists(tNode, false);
byte[] bytes = zk.getData(tNode, false, tNodeStat);
Map<String, Object> map = (Map<String, Object>) JSONUtil.getMapFromJson(new String(bytes));
// if(!map.containsKey("address")){
// map.put("address",
// InetAddress.getLocalHost().getHostName());
// }
if (customTaskData != null) {
for (String key : customTaskData.keySet()) {
if (!map.containsKey(key)) {
map.put(key, customTaskData.get(key));
}
}
}
map.put("taskSize", "" + tasks.size());
map.put("tasksRootNode", tasksListRoot);
map.put("processRootNode", processListRoot);
String create = zk.create(pNode,
JSONUtil.toJsonString(map)
.getBytes(),
Ids.OPEN_ACL_UNSAFE,
CreateMode.EPHEMERAL);
logger.info("Created process Node:" + pNode + " :"
+ create);
return map;
}
} else {
// all the tasks are taken up, will wait for the
logger.info("No task available to take up. Going to wait");
mutex.wait();
}
} catch (KeeperException e) {
logger.info("Warn:mostly ignorable " + e.getMessage(), e);
} catch (InterruptedException e) {
logger.info("Warn:mostly ignorable " + e.getMessage(), e);
}
}
}
}
}
| Java |
package chatty.util.api;
import chatty.Helper;
import chatty.util.DateTime;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.logging.Logger;
/**
* Holds the current info (name, viewers, title, game) of a stream, as well
* as a history of the same information and stuff like when the info was
* last requested, whether it's currently waiting for an API response etc.
*
* @author tduva
*/
public class StreamInfo {
private static final Logger LOGGER = Logger.getLogger(StreamInfo.class.getName());
/**
* All lowercase name of the stream
*/
public final String stream;
/**
* Correctly capitalized name of the stream. May be null if no set.
*/
private String display_name;
private long lastUpdated = 0;
private long lastStatusChange = 0;
private String status = "";
private String game = "";
private int viewers = 0;
private long startedAt = -1;
private long lastOnline = -1;
private long startedAtWithPicnic = -1;
private boolean online = false;
private boolean updateSucceeded = false;
private int updateFailedCounter = 0;
private boolean requested = false;
private boolean followed = false;
/**
* The time the stream was changed from online -> offline, so recheck if
* that actually is correct after some time. If this is -1, then do nothing.
* Should be set to -1 with EVERY update (received data), except when it's
* not already -1 on the change from online -> offline (to avoid request
* spam if recheckOffline() is always true).
*/
private long recheckOffline = -1;
// When the viewer stats where last calculated
private long lastViewerStats;
// How long at least between viewer stats calculations
private static final int VIEWERSTATS_DELAY = 30*60*1000;
// How long a stats range can be at most
private static final int VIEWERSTATS_MAX_LENGTH = 35*60*1000;
private static final int RECHECK_OFFLINE_DELAY = 10*1000;
/**
* Maximum length in seconds of what should count as a PICNIC (short stream
* offline period), to set the online time with PICNICs correctly.
*/
private static final int MAX_PICNIC_LENGTH = 600;
/**
* The current full status (title + game), updated when new data is set.
*/
private String currentFullStatus;
private String prevFullStatus;
private final LinkedHashMap<Long,StreamInfoHistoryItem> history = new LinkedHashMap<>();
private int expiresAfter = 300;
private final StreamInfoListener listener;
public StreamInfo(String stream, StreamInfoListener listener) {
this.listener = listener;
this.stream = stream.toLowerCase(Locale.ENGLISH);
}
private void streamInfoUpdated() {
if (listener != null) {
listener.streamInfoUpdated(this);
}
}
public void setRequested() {
this.requested = true;
}
public boolean isRequested() {
return requested;
}
private void streamInfoStatusChanged() {
lastStatusChange = System.currentTimeMillis();
if (listener != null) {
listener.streamInfoStatusChanged(this, getFullStatus());
}
}
@Override
public String toString() {
return "Online: "+online+
" Status: "+status+
" Game: "+game+
" Viewers: "+viewers;
}
public String getFullStatus() {
return currentFullStatus;
}
private String makeFullStatus() {
if (online) {
String fullStatus = status;
if (status == null) {
fullStatus = "No stream title set";
}
if (game != null) {
fullStatus += " ("+game+")";
}
return fullStatus;
}
else if (!updateSucceeded) {
return "";
}
else {
return "Stream offline";
}
}
public String getStream() {
return stream;
}
/**
* The correctly capitalized name of the stream, or the all lowercase name
* if correctly capitalized name is not set.
*
* @return The correctly capitalized name or all lowercase name
*/
public String getDisplayName() {
return display_name != null ? display_name : stream;
}
/**
* Whether a correctly capitalized name is set, which if true is returned
* by {@see getDisplayName()}.
*
* @return true if a correctly capitalized name is set, false otherwise
*/
public boolean hasDisplayName() {
return display_name != null;
}
/**
* Sets the correctly capitalized name for this stream.
*
* @param name The correctly capitalized name
*/
public void setDisplayName(String name) {
this.display_name = name;
}
/**
* Set stream info from followed streams request.
*
* @param status The current stream title
* @param game The current game being played
* @param viewers The current viewercount
* @param startedAt The timestamp when the stream was started, -1 if not set
*/
public void setFollowed(String status, String game, int viewers, long startedAt) {
//System.out.println(status);
followed = true;
boolean saveToHistory = false;
if (hasExpired()) {
saveToHistory = true;
}
set(status, game, viewers, startedAt, saveToHistory);
}
/**
* Set stream info from a regular stream info request.
*
* @param status The current stream title
* @param game The current game being played
* @param viewers The current viewercount
* @param startedAt The timestamp when the stream was started, -1 if not set
*/
public void set(String status, String game, int viewers, long startedAt) {
set(status, game, viewers, startedAt, true);
}
/**
* This should only be used when the update was successful.
*
* @param status The current title of the stream
* @param game The current game
* @param viewers The current viewercount
* @param startedAt The timestamp when the stream was started, -1 if not set
* @param saveToHistory Whether to save the data to history
*/
private void set(String status, String game, int viewers, long startedAt, boolean saveToHistory) {
this.status = Helper.trim(Helper.removeLinebreaks(status));
this.game = Helper.trim(game);
this.viewers = viewers;
// Always set to -1 (do nothing) when stream is set as online, but also
// output a message if necessary
if (recheckOffline != -1) {
if (this.startedAt < startedAt) {
LOGGER.info("StreamInfo " + stream + ": Stream not offline anymore");
} else {
LOGGER.info("StreamInfo " + stream + ": Stream not offline");
}
}
recheckOffline = -1;
if (lastOnlineAgo() > MAX_PICNIC_LENGTH) {
// Only update online time with PICNICs when offline time was long
// enough (of course also depends on what stream data Chatty has)
this.startedAtWithPicnic = startedAt;
}
this.startedAt = startedAt;
this.lastOnline = System.currentTimeMillis();
this.online = true;
if (saveToHistory) {
addHistoryItem(System.currentTimeMillis(),new StreamInfoHistoryItem(viewers, status, game));
}
setUpdateSucceeded(true);
}
public void setExpiresAfter(int expiresAfter) {
this.expiresAfter = expiresAfter;
}
public void setUpdateFailed() {
setUpdateSucceeded(false);
}
private void setUpdateSucceeded(boolean succeeded) {
updateSucceeded = succeeded;
setUpdated();
if (succeeded) {
updateFailedCounter = 0;
}
else {
updateFailedCounter++;
if (recheckOffline != -1) {
// If an offline check is pending and the update failed, then
// just set as offline now (may of course not be accurate at all
// anymore).
LOGGER.warning("StreamInfo "+stream+": Update failed, delayed setting offline");
setOffline();
}
}
currentFullStatus = makeFullStatus();
if (succeeded && !currentFullStatus.equals(prevFullStatus) ||
lastUpdateLongAgo()) {
prevFullStatus = currentFullStatus;
streamInfoStatusChanged();
}
// Call at the end, so stuff is already updated
streamInfoUpdated();
}
public void setOffline() {
// If switching from online to offline
if (online && recheckOffline == -1) {
LOGGER.info("Waiting to recheck offline status for " + stream);
recheckOffline = System.currentTimeMillis();
} else {
if (recheckOffline != -1) {
//addHistoryItem(recheckOffline, new StreamInfoHistoryItem());
LOGGER.info("Offline after check: "+stream);
}
recheckOffline = -1;
this.online = false;
addHistoryItem(System.currentTimeMillis(), new StreamInfoHistoryItem());
}
setUpdateSucceeded(true);
}
/**
* Whether to recheck the offline status by requesting the stream status
* again earlier than usual.
*
* @return true if it should be checked, false otherwise
*/
public boolean recheckOffline() {
return recheckOffline != -1
&& System.currentTimeMillis() - recheckOffline > RECHECK_OFFLINE_DELAY;
}
public boolean getFollowed() {
return followed;
}
public boolean getOnline() {
return this.online;
}
/**
* The time the stream was started. As always, this may contain stale data
* if the stream info is not valid or the stream offline.
*
* @return The timestamp or -1 if no time was received
*/
public long getTimeStarted() {
return startedAt;
}
/**
* The time the stream was started, including short disconnects (max 10
* minutes). If there was no disconnect, then the time is equal to
* getTimeStarted(). As always, this may contain stale data if the stream
* info is not valid or the stream offline.
*
* @return The timestamp or -1 if not time was received or the time is
* invalid
*/
public long getTimeStartedWithPicnic() {
return startedAtWithPicnic;
}
/**
* How long ago the stream was last online. If the stream was never seen as
* online this session, then a huge number will be returned.
*
* @return The number of seconds that have passed since the stream was last
* seen as online
*/
public long lastOnlineAgo() {
return (System.currentTimeMillis() - lastOnline) / 1000;
}
public long getLastOnlineTime() {
return lastOnline;
}
private void setUpdated() {
lastUpdated = System.currentTimeMillis() / 1000;
requested = false;
}
// Getters
/**
* Gets the status stored for this stream. May not be correct, check
* isValid() before using any data.
*
* @return
*/
public String getStatus() {
return status;
}
/**
* Gets the title stored for this stream, which is the same as the status,
* unless the status is null. As opposed to getStatus() this never returns
* null.
*
* @return
*/
public String getTitle() {
if (status == null) {
return "No stream title set";
}
return status;
}
/**
* Gets the game stored for this stream. May not be correct, check
* isValid() before using any data.
*
* @return
*/
public String getGame() {
return game;
}
/**
* Gets the viewers stored for this stream. May not be correct, check
* isValid() before using any data.
*
* @return
*/
public int getViewers() {
return viewers;
}
/**
* Calculates the number of seconds that passed after the last update
*
* @return Number of seconds that have passed after the last update
*/
public long getUpdatedDelay() {
return (System.currentTimeMillis() / 1000) - lastUpdated;
}
/**
* Checks if the info should be updated. The stream info takes longer
* to expire when there were failed attempts at downloading the info from
* the API. This only affects hasExpired(), not isValid().
*
* @return true if the info should be updated, false otherwise
*/
public boolean hasExpired() {
return getUpdatedDelay() > expiresAfter * (1+ updateFailedCounter / 2);
}
/**
* Checks if the info is valid, taking into account if the last request
* succeeded and how old the data is.
*
* @return true if the info can be used, false otherwise
*/
public boolean isValid() {
if (!updateSucceeded || getUpdatedDelay() > expiresAfter*2) {
return false;
}
return true;
}
public boolean lastUpdateLongAgo() {
if (updateSucceeded && getUpdatedDelay() > expiresAfter*4) {
return true;
}
return false;
}
/**
* Returns the number of seconds the last status change is ago.
*
* @return
*/
public long getStatusChangeTimeAgo() {
return (System.currentTimeMillis() - lastStatusChange) / 1000;
}
public long getStatusChangeTime() {
return lastStatusChange;
}
private void addHistoryItem(Long time, StreamInfoHistoryItem item) {
synchronized(history) {
history.put(time, item);
}
}
public LinkedHashMap<Long,StreamInfoHistoryItem> getHistory() {
synchronized(history) {
return new LinkedHashMap<>(history);
}
}
/**
* Create a summary of the viewercount in the interval that hasn't been
* calculated yet (delay set as a constant).
*
* @param force Get stats even if the delay hasn't passed yet.
* @return
*/
public ViewerStats getViewerStats(boolean force) {
synchronized(history) {
if (lastViewerStats == 0 && !force) {
// No stats output yet, so assume current time as start, so
// it's output after the set delay
lastViewerStats = System.currentTimeMillis() - 5000;
}
long timePassed = System.currentTimeMillis() - lastViewerStats;
if (!force && timePassed < VIEWERSTATS_DELAY) {
return null;
}
long startAt = lastViewerStats+1;
// Only calculate the max length
if (timePassed > VIEWERSTATS_MAX_LENGTH) {
startAt = System.currentTimeMillis() - VIEWERSTATS_MAX_LENGTH;
}
int min = -1;
int max = -1;
int total = 0;
int count = 0;
long firstTime = -1;
long lastTime = -1;
StringBuilder b = new StringBuilder();
// Initiate with -2, because -1 already means offline
int prevViewers = -2;
for (long time : history.keySet()) {
if (time < startAt) {
continue;
}
// Start doing anything for values >= startAt
// Update so that it contains the last value that was looked at
// at the end of this method
lastViewerStats = time;
int viewers = history.get(time).getViewers();
// Append to viewercount development String
if (prevViewers > -1 && viewers != -1) {
// If there is a prevViewers set and if online
int diff = viewers - prevViewers;
if (diff >= 0) {
b.append("+");
}
b.append(Helper.formatViewerCount(diff));
} else if (viewers != -1) {
if (prevViewers == -1) {
// Previous was offline, so show that
b.append("_");
}
b.append(Helper.formatViewerCount(viewers));
}
prevViewers = viewers;
if (viewers == -1) {
continue;
}
// Calculate min/max/sum/count only when online
if (firstTime == -1) {
firstTime = time;
}
lastTime = time;
if (viewers > max) {
max = viewers;
}
if (min == -1 || viewers < min) {
min = viewers;
}
total += viewers;
count++;
}
// After going through all values, do some finishing work
if (prevViewers == -1) {
// Last value was offline, so show that
b.append("_");
}
if (count == 0) {
return null;
}
int avg = total / count;
return new ViewerStats(min, max, avg, firstTime, lastTime, count, b.toString());
}
}
/**
* Holds a set of immutable values that make up viewerstats.
*/
public static class ViewerStats {
public final int max;
public final int min;
public final int avg;
public final long startTime;
public final long endTime;
public final int count;
public final String history;
public ViewerStats(int min, int max, int avg, long startTime,
long endTime, int count, String history) {
this.max = max;
this.min = min;
this.avg = avg;
this.startTime = startTime;
this.endTime = endTime;
this.count = count;
this.history = history;
}
/**
* Which duration the data in this stats covers. This is not necessarily
* the whole duration that was worked with (e.g. if the stream went
* offline at the end, that data may not be included). This is the range
* between the first and last valid data point.
*
* @return The number of seconds this data covers.
*/
public long duration() {
return (endTime - startTime) / 1000;
}
/**
* Checks if these viewerstats contain any viewer data.
*
* @return
*/
public boolean isValid() {
// If min was set to another value than the initial one, then this
// means at least one data point with a viewercount was there.
return min != -1;
}
@Override
public String toString() {
return "Viewerstats ("+DateTime.format2(startTime)
+"-"+DateTime.format2(endTime)+"):"
+ " avg:"+Helper.formatViewerCount(avg)
+ " min:"+Helper.formatViewerCount(min)
+ " max:"+Helper.formatViewerCount(max)
+ " ["+count+"/"+history+"]";
}
}
}
| Java |
# Authorized Buyers Marketplace API Client Library for Java
The Authorized Buyers Marketplace API allows buyers programmatically discover inventory; propose, retrieve and negotiate deals with publishers.
This page contains information about getting started with the Authorized Buyers Marketplace API
using the Google API Client Library for Java. In addition, you may be interested
in the following documentation:
* Browse the [Javadoc reference for the Authorized Buyers Marketplace API][javadoc]
* Read the [Developer's Guide for the Google API Client Library for Java][google-api-client].
* Interact with this API in your browser using the [APIs Explorer for the Authorized Buyers Marketplace API][api-explorer]
## Installation
### Maven
Add the following lines to your `pom.xml` file:
```xml
<project>
<dependencies>
<dependency>
<groupId>com.google.apis</groupId>
<artifactId>google-api-services-authorizedbuyersmarketplace</artifactId>
<version>v1-rev20220212-1.32.1</version>
</dependency>
</dependencies>
</project>
```
### Gradle
```gradle
repositories {
mavenCentral()
}
dependencies {
implementation 'com.google.apis:google-api-services-authorizedbuyersmarketplace:v1-rev20220212-1.32.1'
}
```
[javadoc]: https://googleapis.dev/java/google-api-services-authorizedbuyersmarketplace/latest/index.html
[google-api-client]: https://github.com/googleapis/google-api-java-client/
[api-explorer]: https://developers.google.com/apis-explorer/#p/authorizedbuyersmarketplace/v1/
| Java |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0"
/>
<title>Bootstrap3响应式后台管理系统模版MeAdmin 表单布局</title>
<link href="bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css"
/>
<!--[if lt IE 9]>
<link rel="stylesheet" type="text/css" href="plugins/jquery-ui/jquery.ui.1.10.2.ie.css"
/>
<![endif]-->
<link href="assets/css/main.css" rel="stylesheet" type="text/css" />
<link href="assets/css/plugins.css" rel="stylesheet" type="text/css" />
<link href="assets/css/responsive.css" rel="stylesheet" type="text/css"
/>
<link href="assets/css/icons.css" rel="stylesheet" type="text/css" />
<link rel="stylesheet" href="assets/css/fontawesome/font-awesome.min.css">
<!--[if IE 7]>
<link rel="stylesheet" href="assets/css/fontawesome/font-awesome-ie7.min.css">
<![endif]-->
<!--[if IE 8]>
<link href="assets/css/ie8.css" rel="stylesheet" type="text/css" />
<![endif]-->
<link href='http://fonts.useso.com/css?family=Open+Sans:400,600,700'
rel='stylesheet' type='text/css'>
<script type="text/javascript" src="assets/js/libs/jquery-1.10.2.min.js">
</script>
<script type="text/javascript" src="plugins/jquery-ui/jquery-ui-1.10.2.custom.min.js">
</script>
<script type="text/javascript" src="bootstrap/js/bootstrap.min.js">
</script>
<script type="text/javascript" src="assets/js/libs/lodash.compat.min.js">
</script>
<!--[if lt IE 9]>
<script src="assets/js/libs/html5shiv.js">
</script>
<![endif]-->
<script type="text/javascript" src="plugins/touchpunch/jquery.ui.touch-punch.min.js">
</script>
<script type="text/javascript" src="plugins/event.swipe/jquery.event.move.js">
</script>
<script type="text/javascript" src="plugins/event.swipe/jquery.event.swipe.js">
</script>
<script type="text/javascript" src="assets/js/libs/breakpoints.js">
</script>
<script type="text/javascript" src="plugins/respond/respond.min.js">
</script>
<script type="text/javascript" src="plugins/cookie/jquery.cookie.min.js">
</script>
<script type="text/javascript" src="plugins/slimscroll/jquery.slimscroll.min.js">
</script>
<script type="text/javascript" src="plugins/slimscroll/jquery.slimscroll.horizontal.min.js">
</script>
<script type="text/javascript" src="plugins/sparkline/jquery.sparkline.min.js">
</script>
<script type="text/javascript" src="plugins/daterangepicker/moment.min.js">
</script>
<script type="text/javascript" src="plugins/daterangepicker/daterangepicker.js">
</script>
<script type="text/javascript" src="plugins/blockui/jquery.blockUI.min.js">
</script>
<script type="text/javascript" src="assets/js/app.js">
</script>
<script type="text/javascript" src="assets/js/plugins.js">
</script>
<script type="text/javascript" src="assets/js/plugins.form-components.js">
</script>
<script>
$(document).ready(function() {
App.init();
Plugins.init();
FormComponents.init()
});
</script>
<script type="text/javascript" src="assets/js/custom.js">
</script>
</head>
<body>
<header class="header navbar navbar-fixed-top" role="banner">
<div class="container">
<ul class="nav navbar-nav">
<li class="nav-toggle">
<a href="javascript:void(0);" title="">
<i class="icon-reorder">
</i>
</a>
</li>
</ul>
<a class="navbar-brand" href="index.html">
<img src="assets/img/logo.png" alt="logo" />
<strong>
Me
</strong>
Admin
</a>
<a href="#" class="toggle-sidebar bs-tooltip" data-placement="bottom"
data-original-title="Toggle navigation">
<i class="icon-reorder">
</i>
</a>
<ul class="nav navbar-nav navbar-left hidden-xs hidden-sm">
<li>
<a href="#">
Dashboard
</a>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
Dropdown
<i class="icon-caret-down small">
</i>
</a>
<ul class="dropdown-menu">
<li>
<a href="#">
<i class="icon-user">
</i>
Example #1
</a>
</li>
<li>
<a href="#">
<i class="icon-calendar">
</i>
Example #2
</a>
</li>
<li class="divider">
</li>
<li>
<a href="#">
<i class="icon-tasks">
</i>
Example #3
</a>
</li>
</ul>
</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
<i class="icon-warning-sign">
</i>
<span class="badge">
5
</span>
</a>
<ul class="dropdown-menu extended notification">
<li class="title">
<p>
You have 5 new notifications
</p>
</li>
<li>
<a href="javascript:void(0);">
<span class="label label-success">
<i class="icon-plus">
</i>
</span>
<span class="message">
New user registration.
</span>
<span class="time">
1 mins
</span>
</a>
</li>
<li>
<a href="javascript:void(0);">
<span class="label label-danger">
<i class="icon-warning-sign">
</i>
</span>
<span class="message">
High CPU load on cluster #2.
</span>
<span class="time">
5 mins
</span>
</a>
</li>
<li>
<a href="javascript:void(0);">
<span class="label label-success">
<i class="icon-plus">
</i>
</span>
<span class="message">
New user registration.
</span>
<span class="time">
10 mins
</span>
</a>
</li>
<li>
<a href="javascript:void(0);">
<span class="label label-info">
<i class="icon-bullhorn">
</i>
</span>
<span class="message">
New items are in queue.
</span>
<span class="time">
25 mins
</span>
</a>
</li>
<li>
<a href="javascript:void(0);">
<span class="label label-warning">
<i class="icon-bolt">
</i>
</span>
<span class="message">
Disk space to 85% full.
</span>
<span class="time">
55 mins
</span>
</a>
</li>
<li class="footer">
<a href="javascript:void(0);">
View all notifications
</a>
</li>
</ul>
</li>
<li class="dropdown hidden-xs hidden-sm">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
<i class="icon-tasks">
</i>
<span class="badge">
7
</span>
</a>
<ul class="dropdown-menu extended notification">
<li class="title">
<p>
You have 7 pending tasks
</p>
</li>
<li>
<a href="javascript:void(0);">
<span class="task">
<span class="desc">
Preparing new release
</span>
<span class="percent">
30%
</span>
</span>
<div class="progress progress-small">
<div style="width: 30%;" class="progress-bar progress-bar-info">
</div>
</div>
</a>
</li>
<li>
<a href="javascript:void(0);">
<span class="task">
<span class="desc">
Change management
</span>
<span class="percent">
80%
</span>
</span>
<div class="progress progress-small progress-striped active">
<div style="width: 80%;" class="progress-bar progress-bar-danger">
</div>
</div>
</a>
</li>
<li>
<a href="javascript:void(0);">
<span class="task">
<span class="desc">
Mobile development
</span>
<span class="percent">
60%
</span>
</span>
<div class="progress progress-small">
<div style="width: 60%;" class="progress-bar progress-bar-success">
</div>
</div>
</a>
</li>
<li>
<a href="javascript:void(0);">
<span class="task">
<span class="desc">
Database migration
</span>
<span class="percent">
20%
</span>
</span>
<div class="progress progress-small">
<div style="width: 20%;" class="progress-bar progress-bar-warning">
</div>
</div>
</a>
</li>
<li class="footer">
<a href="javascript:void(0);">
View all tasks
</a>
</li>
</ul>
</li>
<li class="dropdown hidden-xs hidden-sm">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
<i class="icon-envelope">
</i>
<span class="badge">
1
</span>
</a>
<ul class="dropdown-menu extended notification">
<li class="title">
<p>
You have 3 new messages
</p>
</li>
<li>
<a href="javascript:void(0);">
<span class="photo">
<img src="assets/img/demo/avatar-1.jpg" alt="" />
</span>
<span class="subject">
<span class="from">
Bob Carter
</span>
<span class="time">
Just Now
</span>
</span>
<span class="text">
Consetetur sadipscing elitr...
</span>
</a>
</li>
<li>
<a href="javascript:void(0);">
<span class="photo">
<img src="assets/img/demo/avatar-2.jpg" alt="" />
</span>
<span class="subject">
<span class="from">
Jane Doe
</span>
<span class="time">
45 mins
</span>
</span>
<span class="text">
Sed diam nonumy...
</span>
</a>
</li>
<li>
<a href="javascript:void(0);">
<span class="photo">
<img src="assets/img/demo/avatar-3.jpg" alt="" />
</span>
<span class="subject">
<span class="from">
Patrick Nilson
</span>
<span class="time">
6 hours
</span>
</span>
<span class="text">
No sea takimata sanctus...
</span>
</a>
</li>
<li class="footer">
<a href="javascript:void(0);">
View all messages
</a>
</li>
</ul>
</li>
<li>
<a href="#" class="dropdown-toggle row-bg-toggle">
<i class="icon-resize-vertical">
</i>
</a>
</li>
<li class="dropdown">
<a href="#" class="project-switcher-btn dropdown-toggle">
<i class="icon-folder-open">
</i>
<span>
Projects
</span>
</a>
</li>
<li class="dropdown user">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
<i class="icon-male">
</i>
<span class="username">
John Doe
</span>
<i class="icon-caret-down small">
</i>
</a>
<ul class="dropdown-menu">
<li>
<a href="pages_user_profile.html">
<i class="icon-user">
</i>
My Profile
</a>
</li>
<li>
<a href="pages_calendar.html">
<i class="icon-calendar">
</i>
My Calendar
</a>
</li>
<li>
<a href="#">
<i class="icon-tasks">
</i>
My Tasks
</a>
</li>
<li class="divider">
</li>
<li>
<a href="login.html">
<i class="icon-key">
</i>
Log Out
</a>
</li>
</ul>
</li>
</ul>
</div>
<div id="project-switcher" class="container project-switcher">
<div id="scrollbar">
<div class="handle">
</div>
</div>
<div id="frame">
<ul class="project-list">
<li>
<a href="javascript:void(0);">
<span class="image">
<i class="icon-desktop">
</i>
</span>
<span class="title">
Lorem ipsum dolor
</span>
</a>
</li>
<li>
<a href="javascript:void(0);">
<span class="image">
<i class="icon-compass">
</i>
</span>
<span class="title">
Dolor sit invidunt
</span>
</a>
</li>
<li class="current">
<a href="javascript:void(0);">
<span class="image">
<i class="icon-male">
</i>
</span>
<span class="title">
Consetetur sadipscing elitr
</span>
</a>
</li>
<li>
<a href="javascript:void(0);">
<span class="image">
<i class="icon-thumbs-up">
</i>
</span>
<span class="title">
Sed diam nonumy
</span>
</a>
</li>
<li>
<a href="javascript:void(0);">
<span class="image">
<i class="icon-female">
</i>
</span>
<span class="title">
At vero eos et
</span>
</a>
</li>
<li>
<a href="javascript:void(0);">
<span class="image">
<i class="icon-beaker">
</i>
</span>
<span class="title">
Sed diam voluptua
</span>
</a>
</li>
<li>
<a href="javascript:void(0);">
<span class="image">
<i class="icon-desktop">
</i>
</span>
<span class="title">
Lorem ipsum dolor
</span>
</a>
</li>
<li>
<a href="javascript:void(0);">
<span class="image">
<i class="icon-compass">
</i>
</span>
<span class="title">
Dolor sit invidunt
</span>
</a>
</li>
<li>
<a href="javascript:void(0);">
<span class="image">
<i class="icon-male">
</i>
</span>
<span class="title">
Consetetur sadipscing elitr
</span>
</a>
</li>
<li>
<a href="javascript:void(0);">
<span class="image">
<i class="icon-thumbs-up">
</i>
</span>
<span class="title">
Sed diam nonumy
</span>
</a>
</li>
<li>
<a href="javascript:void(0);">
<span class="image">
<i class="icon-female">
</i>
</span>
<span class="title">
At vero eos et
</span>
</a>
</li>
<li>
<a href="javascript:void(0);">
<span class="image">
<i class="icon-beaker">
</i>
</span>
<span class="title">
Sed diam voluptua
</span>
</a>
</li>
</ul>
</div>
</div>
</header>
<div id="container">
<div id="sidebar" class="sidebar-fixed">
<div id="sidebar-content">
<form class="sidebar-search">
<div class="input-box">
<button type="submit" class="submit">
<i class="icon-search">
</i>
</button>
<span>
<input type="text" placeholder="Search...">
</span>
</div>
</form>
<div class="sidebar-search-results">
<i class="icon-remove close">
</i>
<div class="title">
Documents
</div>
<ul class="notifications">
<li>
<a href="javascript:void(0);">
<div class="col-left">
<span class="label label-info">
<i class="icon-file-text">
</i>
</span>
</div>
<div class="col-right with-margin">
<span class="message">
<strong>
John Doe
</strong>
received $1.527,32
</span>
<span class="time">
finances.xls
</span>
</div>
</a>
</li>
<li>
<a href="javascript:void(0);">
<div class="col-left">
<span class="label label-success">
<i class="icon-file-text">
</i>
</span>
</div>
<div class="col-right with-margin">
<span class="message">
My name is
<strong>
John Doe
</strong>
...
</span>
<span class="time">
briefing.docx
</span>
</div>
</a>
</li>
</ul>
<div class="title">
Persons
</div>
<ul class="notifications">
<li>
<a href="javascript:void(0);">
<div class="col-left">
<span class="label label-danger">
<i class="icon-female">
</i>
</span>
</div>
<div class="col-right with-margin">
<span class="message">
Jane
<strong>
Doe
</strong>
</span>
<span class="time">
21 years old
</span>
</div>
</a>
</li>
</ul>
</div>
<ul id="nav">
<li>
<a href="index.html">
<i class="icon-dashboard">
</i>
Dashboard
</a>
</li>
<li>
<a href="javascript:void(0);">
<i class="icon-desktop">
</i>
UI Features
<span class="label label-info pull-right">
6
</span>
</a>
<ul class="sub-menu">
<li>
<a href="ui_general.html">
<i class="icon-angle-right">
</i>
General
</a>
</li>
<li>
<a href="ui_buttons.html">
<i class="icon-angle-right">
</i>
Buttons
</a>
</li>
<li>
<a href="ui_tabs_accordions.html">
<i class="icon-angle-right">
</i>
Tabs & Accordions
</a>
</li>
<li>
<a href="ui_sliders.html">
<i class="icon-angle-right">
</i>
Sliders
</a>
</li>
<li>
<a href="ui_nestable_list.html">
<i class="icon-angle-right">
</i>
Nestable List
</a>
</li>
<li>
<a href="ui_typography.html">
<i class="icon-angle-right">
</i>
Typography / Icons
</a>
</li>
<li>
<a href="ui_google_maps.html">
<i class="icon-angle-right">
</i>
Google Maps
</a>
</li>
<li>
<a href="ui_grid.html">
<i class="icon-angle-right">
</i>
Grid
</a>
</li>
</ul>
</li>
<li class="current open">
<a href="javascript:void(0);">
<i class="icon-edit">
</i>
Form Elements
</a>
<ul class="sub-menu">
<li>
<a href="form_components.html">
<i class="icon-angle-right">
</i>
Form Components
</a>
</li>
<li class="current">
<a href="form_layouts.html">
<i class="icon-angle-right">
</i>
Form Layouts
</a>
</li>
<li>
<a href="form_validation.html">
<i class="icon-angle-right">
</i>
Form Validation
</a>
</li>
<li>
<a href="form_wizard.html">
<i class="icon-angle-right">
</i>
Form Wizard
</a>
</li>
</ul>
</li>
<li>
<a href="javascript:void(0);">
<i class="icon-table">
</i>
Tables
</a>
<ul class="sub-menu">
<li>
<a href="tables_static.html">
<i class="icon-angle-right">
</i>
Static Tables
</a>
</li>
<li>
<a href="http://envato.stammtec.de/themeforest/melon/tables_dynamic.html">
<i class="icon-angle-right">
</i>
Dynamic Tables (DataTables)
</a>
</li>
<li>
<a href="tables_responsive.html">
<i class="icon-angle-right">
</i>
Responsive Tables
</a>
</li>
</ul>
</li>
<li>
<a href="charts.html">
<i class="icon-bar-chart">
</i>
Charts & Statistics
</a>
</li>
<li>
<a href="javascript:void(0);">
<i class="icon-folder-open-alt">
</i>
Pages
</a>
<ul class="sub-menu">
<li>
<a href="login.html">
<i class="icon-angle-right">
</i>
Login
</a>
</li>
<li>
<a href="pages_user_profile.html">
<i class="icon-angle-right">
</i>
User Profile
</a>
</li>
<li>
<a href="pages_calendar.html">
<i class="icon-angle-right">
</i>
Calendar
</a>
</li>
<li>
<a href="pages_invoice.html">
<i class="icon-angle-right">
</i>
Invoice
</a>
</li>
<li>
<a href="404.html">
<i class="icon-angle-right">
</i>
404 Page
</a>
</li>
</ul>
</li>
<li>
<a href="javascript:void(0);">
<i class="icon-list-ol">
</i>
4 Level Menu
</a>
<ul class="sub-menu">
<li class="open-default">
<a href="javascript:void(0);">
<i class="icon-cogs">
</i>
Item 1
<span class="arrow">
</span>
</a>
<ul class="sub-menu">
<li class="open-default">
<a href="javascript:void(0);">
<i class="icon-user">
</i>
Sample Link 1
<span class="arrow">
</span>
</a>
<ul class="sub-menu">
<li class="current">
<a href="javascript:void(0);">
<i class="icon-remove">
</i>
Sample Link 1
</a>
</li>
<li>
<a href="javascript:void(0);">
<i class="icon-pencil">
</i>
Sample Link 1
</a>
</li>
<li>
<a href="javascript:void(0);">
<i class="icon-edit">
</i>
Sample Link 1
</a>
</li>
</ul>
</li>
<li>
<a href="javascript:void(0);">
<i class="icon-user">
</i>
Sample Link 1
</a>
</li>
<li>
<a href="javascript:void(0);">
<i class="icon-external-link">
</i>
Sample Link 2
</a>
</li>
<li>
<a href="javascript:void(0);">
<i class="icon-bell">
</i>
Sample Link 3
</a>
</li>
</ul>
</li>
<li>
<a href="javascript:void(0);">
<i class="icon-globe">
</i>
Item 2
<span class="arrow">
</span>
</a>
<ul class="sub-menu">
<li>
<a href="javascript:void(0);">
<i class="icon-user">
</i>
Sample Link 1
</a>
</li>
<li>
<a href="javascript:void(0);">
<i class="icon-external-link">
</i>
Sample Link 1
</a>
</li>
<li>
<a href="javascript:void(0);">
<i class="icon-bell">
</i>
Sample Link 1
</a>
</li>
</ul>
</li>
<li>
<a href="javascript:void(0);">
<i class="icon-folder-open">
</i>
Item 3
</a>
</li>
</ul>
</li>
</ul>
<div class="sidebar-title">
<span>
Notifications
</span>
</div>
<ul class="notifications demo-slide-in">
<li style="display: none;">
<div class="col-left">
<span class="label label-danger">
<i class="icon-warning-sign">
</i>
</span>
</div>
<div class="col-right with-margin">
<span class="message">
Server
<strong>
#512
</strong>
crashed.
</span>
<span class="time">
few seconds ago
</span>
</div>
</li>
<li style="display: none;">
<div class="col-left">
<span class="label label-info">
<i class="icon-envelope">
</i>
</span>
</div>
<div class="col-right with-margin">
<span class="message">
<strong>
John
</strong>
sent you a message
</span>
<span class="time">
few second ago
</span>
</div>
</li>
<li>
<div class="col-left">
<span class="label label-success">
<i class="icon-plus">
</i>
</span>
</div>
<div class="col-right with-margin">
<span class="message">
<strong>
Emma
</strong>
's account was created
</span>
<span class="time">
4 hours ago
</span>
</div>
</li>
</ul>
<div class="sidebar-widget align-center">
<div class="btn-group" data-toggle="buttons" id="theme-switcher">
<label class="btn active">
<input type="radio" name="theme-switcher" data-theme="bright">
<i class="icon-sun">
</i>
Bright
</label>
<label class="btn">
<input type="radio" name="theme-switcher" data-theme="dark">
<i class="icon-moon">
</i>
Dark
</label>
</div>
</div>
</div>
<div id="divider" class="resizeable">
</div>
</div>
<div id="content">
<div class="container">
<div class="crumbs">
<ul id="breadcrumbs" class="breadcrumb">
<li>
<i class="icon-home">
</i>
<a href="index.html">
Dashboard
</a>
</li>
<li class="current">
<a href="pages_calendar.html" title="">
Calendar
</a>
</li>
</ul>
<ul class="crumb-buttons">
<li>
<a href="charts.html" title="">
<i class="icon-signal">
</i>
<span>
Statistics
</span>
</a>
</li>
<li class="dropdown">
<a href="#" title="" data-toggle="dropdown">
<i class="icon-tasks">
</i>
<span>
Users
<strong>
(+3)
</strong>
</span>
<i class="icon-angle-down left-padding">
</i>
</a>
<ul class="dropdown-menu pull-right">
<li>
<a href="form_components.html" title="">
<i class="icon-plus">
</i>
Add new User
</a>
</li>
<li>
<a href="http://envato.stammtec.de/themeforest/melon/tables_dynamic.html"
title="">
<i class="icon-reorder">
</i>
Overview
</a>
</li>
</ul>
</li>
<li class="range">
<a href="#">
<i class="icon-calendar">
</i>
<span>
</span>
<i class="icon-angle-down">
</i>
</a>
</li>
</ul>
</div>
<div class="page-header">
<div class="page-title">
<h3>
Form Layouts
</h3>
<span>
Good morning, John!
</span>
</div>
<ul class="page-stats">
<li>
<div class="summary">
<span>
New orders
</span>
<h3>
17,561
</h3>
</div>
<div id="sparkline-bar" class="graph sparkline hidden-xs">
20,15,8,50,20,40,20,30,20,15,30,20,25,20
</div>
</li>
<li>
<div class="summary">
<span>
My balance
</span>
<h3>
$21,561.21
</h3>
</div>
<div id="sparkline-bar2" class="graph sparkline hidden-xs">
20,15,8,50,20,40,20,30,20,15,30,20,25,20
</div>
</li>
</ul>
</div>
<div class="row">
<div class="col-md-12">
<div class="widget box">
<div class="widget-header">
<h4>
<i class="icon-reorder">
</i>
Horizontal Forms
</h4>
</div>
<div class="widget-content">
<form class="form-horizontal row-border" action="#">
<div class="form-group">
<label class="col-md-2 control-label">
Full width input:
</label>
<div class="col-md-10">
<input type="text" name="regular" class="form-control">
</div>
</div>
<div class="form-group">
<label class="col-md-2 control-label">
Multiple inputs:
</label>
<div class="col-md-10">
<div class="row">
<div class="col-md-4">
<input type="text" name="regular" class="form-control">
<span class="help-block">
Left aligned helper
</span>
</div>
<div class="col-md-4">
<input type="text" name="regular" class="form-control">
<span class="help-block align-center">
Centered helper
</span>
</div>
<div class="col-md-4">
<input type="text" name="regular" class="form-control">
<span class="help-block align-right">
Right aligned helper
</span>
</div>
</div>
</div>
</div>
<div class="form-group">
<label class="col-md-2 control-label">
Predefined width:
</label>
<div class="col-md-10">
<input class="form-control input-width-mini" type="text" placeholder=".input-width-mini"
style="display: block;">
<input class="form-control input-width-small" type="text" placeholder=".input-width-small"
style="display: block; margin-top: 6px;">
<input class="form-control input-width-medium" type="text" placeholder=".input-width-medium"
style="display: block; margin-top: 6px;">
<input class="form-control input-width-large" type="text" placeholder=".input-width-large"
style="display: block; margin-top: 6px;">
<input class="form-control input-width-xlarge" type="text" placeholder=".input-width-xlarge"
style="display: block; margin-top: 6px;">
<input class="form-control input-width-xxlarge" type="text" placeholder=".input-width-xxlarge"
style="display: block; margin-top: 6px;">
<input class="form-control input-block-level" type="text" placeholder=".input-block-level"
style="display: block; margin-top: 6px;">
</div>
</div>
<div class="form-group">
<label class="col-md-2 control-label">
Select:
</label>
<div class="col-md-10">
<div class="row">
<div class="col-md-4">
<select class="form-control" name="select">
<option value="opt1">
col-md-4
</option>
<option value="opt2">
Option 2
</option>
<option value="opt3">
Option 3
</option>
</select>
</div>
</div>
<div class="row next-row">
<div class="col-md-6">
<select class="form-control" name="select">
<option value="opt1">
col-md-6
</option>
<option value="opt2">
Option 2
</option>
<option value="opt3">
Option 3
</option>
</select>
</div>
</div>
<div class="row next-row">
<div class="col-md-8">
<select class="form-control" name="select">
<option value="opt1">
col-md-8
</option>
<option value="opt2">
Option 2
</option>
<option value="opt3">
Option 3
</option>
</select>
</div>
</div>
<div class="row next-row">
<div class="col-md-12">
<select class="form-control" name="select">
<option value="opt1">
col-md-12
</option>
<option value="opt2">
Option 2
</option>
<option value="opt3">
Option 3
</option>
</select>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="widget box">
<div class="widget-header">
<h4>
<i class="icon-reorder">
</i>
Vertical Forms
</h4>
</div>
<div class="widget-content">
<form class="form-vertical row-border" action="#">
<div class="form-group">
<label class="control-label">
Full width input:
</label>
<input type="text" name="regular" class="form-control">
</div>
<div class="form-group">
<label class="control-label">
Multiple inputs:
</label>
<div class="row">
<div class="col-md-4">
<input type="text" name="regular" class="form-control">
<span class="help-block">
Left aligned helper
</span>
</div>
<div class="col-md-4">
<input type="text" name="regular" class="form-control">
<span class="help-block align-center">
Centered helper
</span>
</div>
<div class="col-md-4">
<input type="text" name="regular" class="form-control">
<span class="help-block align-right">
Right aligned helper
</span>
</div>
</div>
</div>
<div class="form-group">
<label class="control-label">
Predefined width:
</label>
<input class="form-control input-width-mini" type="text" placeholder=".input-width-mini"
style="display: block;">
<input class="form-control input-width-small" type="text" placeholder=".input-width-small"
style="display: block; margin-top: 6px;">
<input class="form-control input-width-medium" type="text" placeholder=".input-width-medium"
style="display: block; margin-top: 6px;">
<input class="form-control input-width-large" type="text" placeholder=".input-width-large"
style="display: block; margin-top: 6px;">
<input class="form-control input-width-xlarge" type="text" placeholder=".input-width-xlarge"
style="display: block; margin-top: 6px;">
<input class="form-control input-width-xxlarge" type="text" placeholder=".input-width-xxlarge"
style="display: block; margin-top: 6px;">
<input class="form-control input-block-level" type="text" placeholder=".input-block-level"
style="display: block; margin-top: 6px;">
</div>
<div class="form-group">
<label class="control-label">
Select:
</label>
<div class="row">
<div class="col-md-4">
<select class="form-control" name="select">
<option value="opt1">
col-md-4
</option>
<option value="opt2">
Option 2
</option>
<option value="opt3">
Option 3
</option>
</select>
</div>
</div>
<div class="row next-row">
<div class="col-md-6">
<select class="form-control" name="select">
<option value="opt1">
col-md-6
</option>
<option value="opt2">
Option 2
</option>
<option value="opt3">
Option 3
</option>
</select>
</div>
</div>
<div class="row next-row">
<div class="col-md-8">
<select class="form-control" name="select">
<option value="opt1">
col-md-8
</option>
<option value="opt2">
Option 2
</option>
<option value="opt3">
Option 3
</option>
</select>
</div>
</div>
<div class="row next-row">
<div class="col-md-12">
<select class="form-control" name="select">
<option value="opt1">
col-md-12
</option>
<option value="opt2">
Option 2
</option>
<option value="opt3">
Option 3
</option>
</select>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="widget box">
<div class="widget-header">
<h4>
<i class="icon-reorder">
</i>
Form Grid
</h4>
</div>
<div class="widget-content">
<form class="form-vertical" action="#">
<div class="form-group">
<div class="row">
<div class="col-md-12">
<input type="text" name="regular" class="form-control" placeholder=".col-md-12">
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-11">
<input type="text" name="regular" class="form-control" placeholder=".col-md-11">
</div>
<div class="col-md-1">
<input type="text" name="regular" class="form-control" placeholder=".col-md-1">
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-10">
<input type="text" name="regular" class="form-control" placeholder=".col-md-10">
</div>
<div class="col-md-2">
<input type="text" name="regular" class="form-control" placeholder=".col-md-2">
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-9">
<input type="text" name="regular" class="form-control" placeholder=".col-md-9">
</div>
<div class="col-md-3">
<input type="text" name="regular" class="form-control" placeholder=".col-md-3">
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-8">
<input type="text" name="regular" class="form-control" placeholder=".col-md-8">
</div>
<div class="col-md-4">
<input type="text" name="regular" class="form-control" placeholder=".col-md-4">
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-7">
<input type="text" name="regular" class="form-control" placeholder=".col-md-7">
</div>
<div class="col-md-5">
<input type="text" name="regular" class="form-control" placeholder=".col-md-5">
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-6">
<input type="text" name="regular" class="form-control" placeholder=".col-md-6">
</div>
<div class="col-md-6">
<input type="text" name="regular" class="form-control" placeholder=".col-md-6">
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-5">
<input type="text" name="regular" class="form-control" placeholder=".col-md-5">
</div>
<div class="col-md-7">
<input type="text" name="regular" class="form-control" placeholder=".col-md-7">
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-4">
<input type="text" name="regular" class="form-control" placeholder=".col-md-4">
</div>
<div class="col-md-8">
<input type="text" name="regular" class="form-control" placeholder=".col-md-8">
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-3">
<input type="text" name="regular" class="form-control" placeholder=".col-md-3">
</div>
<div class="col-md-9">
<input type="text" name="regular" class="form-control" placeholder=".col-md-9">
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-2">
<input type="text" name="regular" class="form-control" placeholder=".col-md-2">
</div>
<div class="col-md-10">
<input type="text" name="regular" class="form-control" placeholder=".col-md-10">
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-1">
<input type="text" name="regular" class="form-control" placeholder=".col-md-1">
</div>
<div class="col-md-11">
<input type="text" name="regular" class="form-control" placeholder=".col-md-11">
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html> | Java |
To access the approval page, click on "Approval" in the main menu. It provides Interest Adjustments,
Pending Payments and Payment Moves Approval for supervisors.
| Java |
/***********************************************************************************************
*
* Copyright (C) 2016, IBL Software Engineering spol. s r. o.
*
* 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.iblsoft.iwxxm.webservice.ws.internal;
import com.googlecode.jsonrpc4j.JsonRpcParam;
import com.iblsoft.iwxxm.webservice.util.Log;
import com.iblsoft.iwxxm.webservice.validator.IwxxmValidator;
import com.iblsoft.iwxxm.webservice.validator.ValidationError;
import com.iblsoft.iwxxm.webservice.validator.ValidationResult;
import com.iblsoft.iwxxm.webservice.ws.IwxxmWebService;
import com.iblsoft.iwxxm.webservice.ws.messages.ValidationRequest;
import com.iblsoft.iwxxm.webservice.ws.messages.ValidationResponse;
import java.io.File;
import static com.google.common.base.Preconditions.checkArgument;
/**
* Implementation class of IwxxmWebService interface.
*/
public class IwxxmWebServiceImpl implements IwxxmWebService {
private final IwxxmValidator iwxxmValidator;
public IwxxmWebServiceImpl(File validationCatalogFile, File validationRulesDir, String defaultIwxxmVersion) {
this.iwxxmValidator = new IwxxmValidator(validationCatalogFile, validationRulesDir, defaultIwxxmVersion);
}
@Override
public ValidationResponse validate(@JsonRpcParam("request") ValidationRequest request) {
Log.INSTANCE.debug("IwxxmWebService.validate request started");
checkRequestVersion(request.getRequestVersion());
ValidationResult validationResult = iwxxmValidator.validate(request.getIwxxmData(), request.getIwxxmVersion());
ValidationResponse.Builder responseBuilder = ValidationResponse.builder();
for (ValidationError ve : validationResult.getValidationErrors()) {
responseBuilder.addValidationError(ve.getError(), ve.getLineNumber(), ve.getColumnNumber());
}
Log.INSTANCE.debug("IwxxmWebService.validate request finished");
return responseBuilder.build();
}
private void checkRequestVersion(String requestVersion) {
checkArgument(requestVersion != null && requestVersion.equals("1.0"), "Unsupported request version.");
}
}
| Java |
# Copyright 2011 WebDriver committers
# Copyright 2011 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.
"""The ActionChains implementation."""
from selenium.webdriver.remote.command import Command
class ActionChains(object):
"""Generate user actions.
All actions are stored in the ActionChains object. Call perform() to fire
stored actions."""
def __init__(self, driver):
"""Creates a new ActionChains.
Args:
driver: The WebDriver instance which performs user actions.
"""
self._driver = driver
self._actions = []
def perform(self):
"""Performs all stored actions."""
for action in self._actions:
action()
def click(self, on_element=None):
"""Clicks an element.
Args:
on_element: The element to click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.CLICK, {'button': 0}))
return self
def click_and_hold(self, on_element):
"""Holds down the left mouse button on an element.
Args:
on_element: The element to mouse down.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.MOUSE_DOWN, {}))
return self
def context_click(self, on_element):
"""Performs a context-click (right click) on an element.
Args:
on_element: The element to context-click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.CLICK, {'button': 2}))
return self
def double_click(self, on_element):
"""Double-clicks an element.
Args:
on_element: The element to double-click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.DOUBLE_CLICK, {}))
return self
def drag_and_drop(self, source, target):
"""Holds down the left mouse button on the source element,
then moves to the target element and releases the mouse button.
Args:
source: The element to mouse down.
target: The element to mouse up.
"""
self.click_and_hold(source)
self.release(target)
return self
def drag_and_drop_by_offset(self, source, xoffset, yoffset):
"""Holds down the left mouse button on the source element,
then moves to the target element and releases the mouse button.
Args:
source: The element to mouse down.
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self.click_and_hold(source)
self.move_by_offset(xoffset, yoffset)
self.release(source)
return self
def key_down(self, key, element=None):
"""Sends a key press only, without releasing it.
Should only be used with modifier keys (Control, Alt and Shift).
Args:
key: The modifier key to send. Values are defined in Keys class.
target: The element to send keys.
If None, sends a key to current focused element.
"""
if element: self.click(element)
self._actions.append(lambda:
self._driver.execute(Command.SEND_MODIFIER_KEY_TO_ACTIVE_ELEMENT, {
"value": key,
"isdown": True}))
return self
def key_up(self, key, element=None):
"""Releases a modifier key.
Args:
key: The modifier key to send. Values are defined in Keys class.
target: The element to send keys.
If None, sends a key to current focused element.
"""
if element: self.click(element)
self._actions.append(lambda:
self._driver.execute(Command.SEND_MODIFIER_KEY_TO_ACTIVE_ELEMENT, {
"value": key,
"isdown": False}))
return self
def move_by_offset(self, xoffset, yoffset):
"""Moving the mouse to an offset from current mouse position.
Args:
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {
'xoffset': xoffset,
'yoffset': yoffset}))
return self
def move_to_element(self, to_element):
"""Moving the mouse to the middle of an element.
Args:
to_element: The element to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {'element': to_element.id}))
return self
def move_to_element_with_offset(self, to_element, xoffset, yoffset):
"""Move the mouse by an offset of the specificed element.
Offsets are relative to the top-left corner of the element.
Args:
to_element: The element to move to.
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {
'element': to_element.id,
'xoffset': xoffset,
'yoffset': yoffset}))
return self
def release(self, on_element):
"""Releasing a held mouse button.
Args:
on_element: The element to mouse up.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.MOUSE_UP, {}))
return self
def send_keys(self, *keys_to_send):
"""Sends keys to current focused element.
Args:
keys_to_send: The keys to send.
"""
self._actions.append(lambda:
self._driver.switch_to_active_element().send_keys(*keys_to_send))
return self
def send_keys_to_element(self, element, *keys_to_send):
"""Sends keys to an element.
Args:
element: The element to send keys.
keys_to_send: The keys to send.
"""
self._actions.append(lambda:
element.send_keys(*keys_to_send))
return self
| Java |
package org.jboss.resteasy.reactive.client.processor.beanparam;
import static org.jboss.resteasy.reactive.common.processor.ResteasyReactiveDotNames.BEAN_PARAM;
import static org.jboss.resteasy.reactive.common.processor.ResteasyReactiveDotNames.COOKIE_PARAM;
import static org.jboss.resteasy.reactive.common.processor.ResteasyReactiveDotNames.FORM_PARAM;
import static org.jboss.resteasy.reactive.common.processor.ResteasyReactiveDotNames.HEADER_PARAM;
import static org.jboss.resteasy.reactive.common.processor.ResteasyReactiveDotNames.PATH_PARAM;
import static org.jboss.resteasy.reactive.common.processor.ResteasyReactiveDotNames.QUERY_PARAM;
import java.util.ArrayList;
import java.util.Collections;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Set;
import java.util.function.BiFunction;
import java.util.stream.Collectors;
import org.jboss.jandex.AnnotationInstance;
import org.jboss.jandex.AnnotationTarget;
import org.jboss.jandex.ClassInfo;
import org.jboss.jandex.DotName;
import org.jboss.jandex.FieldInfo;
import org.jboss.jandex.IndexView;
import org.jboss.jandex.MethodInfo;
import org.jboss.jandex.Type;
import org.jboss.resteasy.reactive.common.processor.JandexUtil;
public class BeanParamParser {
public static List<Item> parse(ClassInfo beanParamClass, IndexView index) {
Set<ClassInfo> processedBeanParamClasses = Collections.newSetFromMap(new IdentityHashMap<>());
return parseInternal(beanParamClass, index, processedBeanParamClasses);
}
private static List<Item> parseInternal(ClassInfo beanParamClass, IndexView index,
Set<ClassInfo> processedBeanParamClasses) {
if (!processedBeanParamClasses.add(beanParamClass)) {
throw new IllegalArgumentException("Cycle detected in BeanParam annotations; already processed class "
+ beanParamClass.name());
}
try {
List<Item> resultList = new ArrayList<>();
// Parse class tree recursively
if (!JandexUtil.DOTNAME_OBJECT.equals(beanParamClass.superName())) {
resultList
.addAll(parseInternal(index.getClassByName(beanParamClass.superName()), index,
processedBeanParamClasses));
}
resultList.addAll(paramItemsForFieldsAndMethods(beanParamClass, QUERY_PARAM,
(annotationValue, fieldInfo) -> new QueryParamItem(annotationValue,
new FieldExtractor(null, fieldInfo.name(), fieldInfo.declaringClass().name().toString()),
fieldInfo.type()),
(annotationValue, getterMethod) -> new QueryParamItem(annotationValue, new GetterExtractor(getterMethod),
getterMethod.returnType())));
resultList.addAll(paramItemsForFieldsAndMethods(beanParamClass, BEAN_PARAM,
(annotationValue, fieldInfo) -> {
Type type = fieldInfo.type();
if (type.kind() == Type.Kind.CLASS) {
List<Item> subBeanParamItems = parseInternal(index.getClassByName(type.asClassType().name()), index,
processedBeanParamClasses);
return new BeanParamItem(subBeanParamItems,
new FieldExtractor(null, fieldInfo.name(), fieldInfo.declaringClass().name().toString()));
} else {
throw new IllegalArgumentException("BeanParam annotation used on a field that is not an object: "
+ beanParamClass.name() + "." + fieldInfo.name());
}
},
(annotationValue, getterMethod) -> {
Type returnType = getterMethod.returnType();
List<Item> items = parseInternal(index.getClassByName(returnType.name()), index,
processedBeanParamClasses);
return new BeanParamItem(items, new GetterExtractor(getterMethod));
}));
resultList.addAll(paramItemsForFieldsAndMethods(beanParamClass, COOKIE_PARAM,
(annotationValue, fieldInfo) -> new CookieParamItem(annotationValue,
new FieldExtractor(null, fieldInfo.name(),
fieldInfo.declaringClass().name().toString()),
fieldInfo.type().name().toString()),
(annotationValue, getterMethod) -> new CookieParamItem(annotationValue,
new GetterExtractor(getterMethod), getterMethod.returnType().name().toString())));
resultList.addAll(paramItemsForFieldsAndMethods(beanParamClass, HEADER_PARAM,
(annotationValue, fieldInfo) -> new HeaderParamItem(annotationValue,
new FieldExtractor(null, fieldInfo.name(), fieldInfo.declaringClass().name().toString()),
fieldInfo.type().name().toString()),
(annotationValue, getterMethod) -> new HeaderParamItem(annotationValue,
new GetterExtractor(getterMethod), getterMethod.returnType().name().toString())));
resultList.addAll(paramItemsForFieldsAndMethods(beanParamClass, PATH_PARAM,
(annotationValue, fieldInfo) -> new PathParamItem(annotationValue, fieldInfo.type().name().toString(),
new FieldExtractor(null, fieldInfo.name(), fieldInfo.declaringClass().name().toString())),
(annotationValue, getterMethod) -> new PathParamItem(annotationValue,
getterMethod.returnType().name().toString(),
new GetterExtractor(getterMethod))));
resultList.addAll(paramItemsForFieldsAndMethods(beanParamClass, FORM_PARAM,
(annotationValue, fieldInfo) -> new FormParamItem(annotationValue,
fieldInfo.type().name().toString(),
new FieldExtractor(null, fieldInfo.name(), fieldInfo.declaringClass().name().toString())),
(annotationValue, getterMethod) -> new FormParamItem(annotationValue,
getterMethod.returnType().name().toString(),
new GetterExtractor(getterMethod))));
return resultList;
} finally {
processedBeanParamClasses.remove(beanParamClass);
}
}
private static MethodInfo getGetterMethod(ClassInfo beanParamClass, MethodInfo methodInfo) {
MethodInfo getter = null;
if (methodInfo.parameters().size() > 0) { // should be setter
// find the corresponding getter:
String setterName = methodInfo.name();
if (setterName.startsWith("set")) {
getter = beanParamClass.method(setterName.replace("^set", "^get"));
}
} else if (methodInfo.name().startsWith("get")) {
getter = methodInfo;
}
if (getter == null) {
throw new IllegalArgumentException(
"No getter corresponding to " + methodInfo.declaringClass().name() + "#" + methodInfo.name() + " found");
}
return getter;
}
private static <T extends Item> List<T> paramItemsForFieldsAndMethods(ClassInfo beanParamClass, DotName parameterType,
BiFunction<String, FieldInfo, T> fieldExtractor, BiFunction<String, MethodInfo, T> methodExtractor) {
return ParamTypeAnnotations.of(beanParamClass, parameterType).itemsForFieldsAndMethods(fieldExtractor, methodExtractor);
}
private BeanParamParser() {
}
private static class ParamTypeAnnotations {
private final ClassInfo beanParamClass;
private final List<AnnotationInstance> annotations;
private ParamTypeAnnotations(ClassInfo beanParamClass, DotName parameterType) {
this.beanParamClass = beanParamClass;
List<AnnotationInstance> relevantAnnotations = beanParamClass.annotations().get(parameterType);
this.annotations = relevantAnnotations == null
? Collections.emptyList()
: relevantAnnotations.stream().filter(this::isFieldOrMethodAnnotation).collect(Collectors.toList());
}
private static ParamTypeAnnotations of(ClassInfo beanParamClass, DotName parameterType) {
return new ParamTypeAnnotations(beanParamClass, parameterType);
}
private <T extends Item> List<T> itemsForFieldsAndMethods(BiFunction<String, FieldInfo, T> itemFromFieldExtractor,
BiFunction<String, MethodInfo, T> itemFromMethodExtractor) {
return annotations.stream()
.map(annotation -> toItem(annotation, itemFromFieldExtractor, itemFromMethodExtractor))
.collect(Collectors.toList());
}
private <T extends Item> T toItem(AnnotationInstance annotation,
BiFunction<String, FieldInfo, T> itemFromFieldExtractor,
BiFunction<String, MethodInfo, T> itemFromMethodExtractor) {
String annotationValue = annotation.value() == null ? null : annotation.value().asString();
return annotation.target().kind() == AnnotationTarget.Kind.FIELD
? itemFromFieldExtractor.apply(annotationValue, annotation.target().asField())
: itemFromMethodExtractor.apply(annotationValue,
getGetterMethod(beanParamClass, annotation.target().asMethod()));
}
private boolean isFieldOrMethodAnnotation(AnnotationInstance annotation) {
return annotation.target().kind() == AnnotationTarget.Kind.FIELD
|| annotation.target().kind() == AnnotationTarget.Kind.METHOD;
}
}
}
| Java |
import * as React from 'react'
import styled from 'styled-components'
import { colors } from 'styles/variables'
interface InputFeedbackProps {
className?: string
valid?: boolean
}
const InputFeedback: React.SFC<InputFeedbackProps> = ({ className, children }) => (
<div className={className}>{children}</div>
)
export default styled(InputFeedback)`
width: 100%;
margin-top: 0.25rem;
font-size: 80%;
color: ${props => (props.valid ? colors.green : colors.red)};
`
| Java |
Potree.TranslationTool = function(camera) {
THREE.Object3D.call( this );
var scope = this;
this.camera = camera;
this.geometry = new THREE.Geometry();
this.material = new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff } );
this.STATE = {
DEFAULT: 0,
TRANSLATE_X: 1,
TRANSLATE_Y: 2,
TRANSLATE_Z: 3
};
this.parts = {
ARROW_X : {name: "arrow_x", object: undefined, color: new THREE.Color( 0xff0000 ), state: this.STATE.TRANSLATE_X},
ARROW_Y : {name: "arrow_y", object: undefined, color: new THREE.Color( 0x00ff00 ), state: this.STATE.TRANSLATE_Y},
ARROW_Z : {name: "arrow_z", object: undefined, color: new THREE.Color( 0x0000ff ), state: this.STATE.TRANSLATE_Z}
}
this.translateStart;
this.state = this.STATE.DEFAULT;
this.highlighted;
this.targets;
this.build = function(){
var arrowX = scope.createArrow(scope.parts.ARROW_X, scope.parts.ARROW_X.color);
arrowX.rotation.z = -Math.PI/2;
var arrowY = scope.createArrow(scope.parts.ARROW_Y, scope.parts.ARROW_Y.color);
var arrowZ = scope.createArrow(scope.parts.ARROW_Z, scope.parts.ARROW_Z.color);
arrowZ.rotation.x = -Math.PI/2;
scope.add(arrowX);
scope.add(arrowY);
scope.add(arrowZ);
var boxXY = scope.createBox(new THREE.Color( 0xffff00 ));
boxXY.scale.z = 0.02;
boxXY.position.set(0.5, 0.5, 0);
var boxXZ = scope.createBox(new THREE.Color( 0xff00ff ));
boxXZ.scale.y = 0.02;
boxXZ.position.set(0.5, 0, -0.5);
var boxYZ = scope.createBox(new THREE.Color( 0x00ffff ));
boxYZ.scale.x = 0.02;
boxYZ.position.set(0, 0.5, -0.5);
scope.add(boxXY);
scope.add(boxXZ);
scope.add(boxYZ);
scope.parts.ARROW_X.object = arrowX;
scope.parts.ARROW_Y.object = arrowY;
scope.parts.ARROW_Z.object = arrowZ;
scope.scale.multiplyScalar(5);
};
this.createBox = function(color){
var boxGeometry = new THREE.BoxGeometry(1, 1, 1);
var boxMaterial = new THREE.MeshBasicMaterial({color: color, transparent: true, opacity: 0.5});
var box = new THREE.Mesh(boxGeometry, boxMaterial);
return box;
};
this.createArrow = function(partID, color){
var material = new THREE.MeshBasicMaterial({color: color});
var shaftGeometry = new THREE.CylinderGeometry(0.1, 0.1, 3, 10, 1, false);
var shaftMatterial = material;
var shaft = new THREE.Mesh(shaftGeometry, shaftMatterial);
shaft.position.y = 1.5;
var headGeometry = new THREE.CylinderGeometry(0, 0.3, 1, 10, 1, false);
var headMaterial = material;
var head = new THREE.Mesh(headGeometry, headMaterial);
head.position.y = 3;
var arrow = new THREE.Object3D();
arrow.add(shaft);
arrow.add(head);
arrow.partID = partID;
arrow.material = material;
return arrow;
};
this.setHighlighted = function(partID){
if(partID === undefined){
if(scope.highlighted){
scope.highlighted.object.material.color = scope.highlighted.color;
scope.highlighted = undefined;
}
return;
}else if(scope.highlighted !== undefined && scope.highlighted !== partID){
scope.highlighted.object.material.color = scope.highlighted.color;
}
scope.highlighted = partID;
partID.object.material.color = new THREE.Color(0xffff00);
}
this.getHoveredObject = function(mouse){
var vector = new THREE.Vector3( mouse.x, mouse.y, 0.5 );
vector.unproject(scope.camera);
var raycaster = new THREE.Raycaster();
raycaster.ray.set( scope.camera.position, vector.sub( scope.camera.position ).normalize() );
var intersections = raycaster.intersectObject(scope, true);
if(intersections.length === 0){
scope.setHighlighted(undefined);
return undefined;
}
var I = intersections[0];
var partID = I.object.parent.partID;
return partID;
}
this.onMouseMove = function(event){
var mouse = event.normalizedPosition;
if(scope.state === scope.STATE.DEFAULT){
scope.setHighlighted(scope.getHoveredObject(mouse));
}else if(scope.state === scope.STATE.TRANSLATE_X || scope.state === scope.STATE.TRANSLATE_Y || scope.state === scope.STATE.TRANSLATE_Z){
var origin = scope.start.lineStart.clone();
var direction = scope.start.lineEnd.clone().sub(scope.start.lineStart);
direction.normalize();
var mousePoint = new THREE.Vector3(mouse.x, mouse.y);
var directionDistance = new THREE.Vector3().subVectors(mousePoint, origin).dot(direction);
var pointOnLine = direction.clone().multiplyScalar(directionDistance).add(origin);
pointOnLine.unproject(scope.camera);
var diff = pointOnLine.clone().sub(scope.position);
scope.position.copy(pointOnLine);
for(var i = 0; i < scope.targets.length; i++){
var target = scope.targets[0];
target.position.add(diff);
}
event.signal.halt();
}
};
this.onMouseDown = function(event){
if(scope.state === scope.STATE.DEFAULT){
var hoveredObject = scope.getHoveredObject(event.normalizedPosition, scope.camera);
if(hoveredObject){
scope.state = hoveredObject.state;
var lineStart = scope.position.clone();
var lineEnd;
if(scope.state === scope.STATE.TRANSLATE_X){
lineEnd = scope.position.clone();
lineEnd.x += 2;
}else if(scope.state === scope.STATE.TRANSLATE_Y){
lineEnd = scope.position.clone();
lineEnd.y += 2;
}else if(scope.state === scope.STATE.TRANSLATE_Z){
lineEnd = scope.position.clone();
lineEnd.z -= 2;
}
lineStart.project(scope.camera);
lineEnd.project(scope.camera);
scope.start = {
mouse: event.normalizedPosition,
lineStart: lineStart,
lineEnd: lineEnd
};
event.signal.halt();
}
}
};
this.onMouseUp = function(event){
scope.setHighlighted();
scope.state = scope.STATE.DEFAULT;
};
this.setTargets = function(targets){
scope.targets = targets;
if(scope.targets.length === 0){
return;
}
//TODO calculate centroid of all targets
var centroid = targets[0].position.clone();
//for(var i = 0; i < targets.length; i++){
// var target = targets[i];
//}
scope.position.copy(centroid);
}
this.build();
};
Potree.TranslationTool.prototype = Object.create( THREE.Object3D.prototype );
| Java |
/*
* DBeaver - Universal Database Manager
* Copyright (C) 2010-2019 Serge Rider (serge@jkiss.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jkiss.dbeaver.ui.actions;
import org.eclipse.core.expressions.PropertyTester;
import org.eclipse.core.resources.*;
import org.jkiss.dbeaver.runtime.DBWorkbench;
import org.jkiss.dbeaver.runtime.IPluginService;
import org.jkiss.dbeaver.ui.ActionUtils;
/**
* GlobalPropertyTester
*/
public class GlobalPropertyTester extends PropertyTester {
//static final Log log = LogFactory.get vLog(ObjectPropertyTester.class);
public static final String NAMESPACE = "org.jkiss.dbeaver.core.global";
public static final String PROP_STANDALONE = "standalone";
public static final String PROP_HAS_ACTIVE_PROJECT = "hasActiveProject";
public static final String PROP_HAS_MULTI_PROJECTS = "hasMultipleProjects";
@Override
public boolean test(Object receiver, String property, Object[] args, Object expectedValue) {
switch (property) {
case PROP_HAS_MULTI_PROJECTS:
return DBWorkbench.getPlatform().getWorkspace().getProjects().size() > 1;
case PROP_HAS_ACTIVE_PROJECT:
return DBWorkbench.getPlatform().getWorkspace().getActiveProject() != null;
case PROP_STANDALONE:
return DBWorkbench.getPlatform().getApplication().isStandalone();
}
return false;
}
public static void firePropertyChange(String propName)
{
ActionUtils.evaluatePropertyState(NAMESPACE + "." + propName);
}
public static class ResourceListener implements IPluginService, IResourceChangeListener {
@Override
public void activateService() {
ResourcesPlugin.getWorkspace().addResourceChangeListener(this);
}
@Override
public void deactivateService() {
ResourcesPlugin.getWorkspace().removeResourceChangeListener(this);
}
@Override
public void resourceChanged(IResourceChangeEvent event) {
if (event.getType() == IResourceChangeEvent.POST_CHANGE) {
for (IResourceDelta childDelta : event.getDelta().getAffectedChildren()) {
if (childDelta.getResource() instanceof IProject) {
if (childDelta.getKind() == IResourceDelta.ADDED || childDelta.getKind() == IResourceDelta.REMOVED) {
firePropertyChange(GlobalPropertyTester.PROP_HAS_MULTI_PROJECTS);
}
}
}
}
}
}
}
| Java |
<?php
/**
* Razorphyn
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade the extension
* to newer versions in the future.
*
* @copyright Copyright (c) 2013 Razorphyn
*
* Extended Coming Soon Countdown
*
* @author Razorphyn
* @Site http://razorphyn.com/
*/
umask(002);
//REMEBER THE FIRST 0
$folderperm=0755; //Folders Permissions
$fileperm=0644; //Files Permissions
if(!is_dir("session")) {mkdir("session",$folderperm);file_put_contents("session/.htaccess","Deny from All \n IndexIgnore * \n Header set X-Frame-Options SAMEORIGIN \n Header set X-XSS-Protection '1; mode=block' \n Header set X-Content-Type-Options 'nosniff'");}
ini_set("session.auto_start", "0");
ini_set("session.hash_function", "sha512");
ini_set("session.entropy_file", "/dev/urandom");
ini_set("session.entropy_length", "512");
ini_set("session.save_path", "session");
ini_set("session.gc_probability", "1");
ini_set("session.cookie_httponly", "1");
ini_set("session.use_only_cookies", "1");
ini_set("session.use_trans_sid", "0");
session_name("RazorphynExtendedComingsoon");
if (isset($_SERVER['HTTPS']) && !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') {
ini_set('session.cookie_secure', '1');
}
session_start();
if(isset($_SESSION["created"]) && $_SESSION["created"]==true) {unset($_SESSION["created"]);header("Location: index.php");}
else{
$dir="../config";
$fileconfig=$dir."/config.txt";
$passfile=$dir."/pass.php";
$socialfile=$dir."/social.txt";
$dirmail= $dir."/mails/";
$filefnmail= $dir."/fnmail.txt";
$filefnmessage= $dir."/fnmessage.txt";
$filefnfooter= $dir."/footermail.txt";
$filelogo= $dir."/logo.txt";
$filefrontmess= $dir."/frontmess.txt";
$filenews= $dir."/news.txt";
$fileindexfoot= $dir."/indexfooter.txt";
$access= $dir."/.htaccess";
if(!is_dir($dir)){
if(mkdir($dir,0700)){
mkdir("../config/scheduled",$folderperm);
file_put_contents("../config/scheduled/.htaccess","Deny from All"."\n"."IndexIgnore * \n Header set X-Frame-Options SAMEORIGIN \n Header set X-XSS-Protection '1; mode=block' \n Header set X-Content-Type-Options 'nosniff'");
if(!is_file($fileconfig))file_put_contents($fileconfig,"");
if(!is_file($socialfile))file_put_contents($socialfile,"");
if(!is_dir($dirmail)){ mkdir($dirmail,$folderperm);file_put_contents($dirmail.".htaccess","Deny from All"."\n"."IndexIgnore * \n Header set X-Frame-Options SAMEORIGIN \n Header set X-XSS-Protection '1; mode=block' \n Header set X-Content-Type-Options 'nosniff'"); };
if(!is_file($filefnmail))file_put_contents($filefnmail,"");
if(!is_file($filefnmessage))file_put_contents($filefnmessage,"");
if(!is_file($filefnfooter))file_put_contents($filefnfooter,"");
if(!is_file($filelogo))file_put_contents($filelogo,"");
if(!is_file($filefrontmess))file_put_contents($filefrontmess,"");
if(!is_file($filenews))file_put_contents($filenews,"");
if(!is_file($fileindexfoot))file_put_contents($fileindexfoot,"");
if(!is_file($passfile))file_put_contents($passfile,'<?php $adminpassword=\''.(hash("whirlpool","admin")).'\'; ?>');
if(!is_file($access))file_put_contents($access,"Deny from All"."\n"."IndexIgnore * \n Header set X-Frame-Options SAMEORIGIN \n Header set X-XSS-Protection '1; mode=block' \n Header set X-Content-Type-Options 'nosniff'");
if(!is_file(".htaccess"))file_put_contents(".htaccess","IndexIgnore * \n Header set X-Frame-Options SAMEORIGIN \n Header set X-XSS-Protection '1; mode=block' \n Header set X-Content-Type-Options 'nosniff'");
chmod($fileconfig, $fileperm);
chmod($socialfile, $fileperm);
chmod($dirmail, $folderperm);
chmod($filefnmail, $fileperm);
chmod($filefnmessage, $fileperm);
chmod($filefnfooter, $fileperm);
chmod($filelogo, $fileperm);
chmod($filefrontmess, $fileperm);
chmod($filenews, $fileperm);
chmod($passfile, $fileperm);
$_SESSION["created"]=true;
}
}
else{
if(!is_dir("../config/scheduled")){
if(mkdir("../config/scheduled",$folderperm))
file_put_contents("../config/scheduled/.htaccess","Deny from All"."\n"."IndexIgnore * \n Header set X-Frame-Options SAMEORIGIN \n Header set X-XSS-Protection '1; mode=block' \n Header set X-Content-Type-Options 'nosniff'");
}
if(!is_file($fileconfig))file_put_contents($fileconfig,"");
if(!is_file($fileindexfoot))file_put_contents($fileindexfoot,"");
if(!is_file($socialfile))file_put_contents($socialfile,"");
if(!is_dir($dirmail)){mkdir($dirmail,folderperm);file_put_contents($dirmail.".htaccess","Deny from All"."\n"."IndexIgnore * \n Header set X-Frame-Options SAMEORIGIN \n Header set X-XSS-Protection '1; mode=block' \n Header set X-Content-Type-Options 'nosniff'"); };
if(!is_file($filefnmail))file_put_contents($filefnmail,"");
if(!is_file($filefnmessage))file_put_contents($filefnmessage,"");
if(!is_file($filefnfooter))file_put_contents($filefnfooter,"");
if(!is_file($filelogo))file_put_contents($filelogo,"");
if(!is_file($filefrontmess))file_put_contents($filefrontmess,"");
if(!is_file($filenews))file_put_contents($filenews,"");
if(!is_file($passfile))file_put_contents($passfile,'<?php $adminpassword=\''.(hash("whirlpool","admin")).'\'; ?>');
if(!is_file($access))file_put_contents($access,"Deny from All"."\n"."IndexIgnore *");
if(!is_file(".htaccess"))file_put_contents(".htaccess","IndexIgnore * \n Header set X-Frame-Options SAMEORIGIN \n Header set X-XSS-Protection '1; mode=block' \n Header set X-Content-Type-Options 'nosniff'");
chmod($fileconfig, $fileperm);
chmod($socialfile, $fileperm);
chmod($dirmail, $folderperm);
chmod($filefnmail, $fileperm);
chmod($filefnmessage, $fileperm);
chmod($filefnfooter, $fileperm);
chmod($filelogo, $fileperm);
chmod($filefrontmess, $fileperm);
chmod($filenews, $fileperm);
chmod($passfile, $fileperm);
$_SESSION["created"]=true;
}
echo "<html><head></head><body><button onclick='javascript:ref();' style='position:relative;display:block;margin:0 auto;top:45%'>Return Back</button><script>function ref(){location.reload(true);}</script></body></html>";
}
?>
| Java |
this is my new learning GitHub class
hello how are you doing
#This class is running in La Ciotat france
#this is github class
# this is test file
Pulling changes
Deepika Padukone talks about Katrina Kaif
Prabhas turned down Rs 10cr ad for Baahubali
Hrithik, Sussanne and Twinkle party together
Week 1: Baahubali 2 (Hindi) collects Rs 245 cr
Deepika wishes to take ‘Padmavati’ to Cannes
Soha on comparisons with Kareena
Milind wants to make a film on Lord Shiva
Pic: Sunny Leone sizzles in a special song
Then and now: Yesteryear actress Mumtaz
Movie review: Guardians of the Galaxy Vol. 2
| Java |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="Create a life that you love.">
<title>Are you trying to squeeze more into an already full life? - Quercus Coaching</title>
<link rel="canonical" href="/2016/03/30/blog-march/">
<!-- Bootstrap Core CSS -->
<link rel="stylesheet" href="/css/bootstrap.min.css">
<!-- Custom CSS -->
<link rel="stylesheet" href="/css/clean-blog.css">
<!-- Pygments Github CSS -->
<link rel="stylesheet" href="/css/syntax.css">
<!-- Custom Fonts -->
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">
<link href='//fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<!-- Navigation -->
<nav class="navbar navbar-default navbar-custom navbar-fixed-top">
<div class="container-fluid">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header page-scroll">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="/">Quercus Coaching</a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav navbar-right">
<li><a href="/" >Home</a></li>
<li><a href="/about/" >About</a></li>
<li><a href="/contact/" >Contact</a></li>
</ul>
<!-- <li>
<a href="/">Home</a>
</li>
<li>
<a href="/404.html">Page Not Found</a>
</li>
<li>
<a href="/about/">About</a>
</li>
<li>
<a href="/contact/">Contact</a>
</li>
</ul>
--> </div>
<!-- /.navbar-collapse -->
</div>
<!-- /.container -->
</nav>
<!-- Post Header -->
<header class="intro-header" style="background-image: url('/img/banner_photo.png')">
<div class="container">
<div class="row">
<div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
<div class="post-heading">
<h1>Are you trying to squeeze more into an already full life?</h1>
<h2 class="subheading">Have you ever noticed that so many things that could improve your life involve adding ... more?</h2>
<span class="meta">Posted by Alison Macduff on March 30, 2016</span>
</div>
</div>
</div>
</div>
</header>
<!-- Post Content -->
<article>
<div class="container">
<div class="row">
<div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
<p><em>Are you trying to squeeze more into an already full life?</em></p>
<p>Have you ever noticed that so many things that could improve your life involve adding … <strong>more?</strong></p>
<p><strong>For example:</strong></p>
<ul>
<li><strong>more</strong> time in the gym/with the kids/meditating/jogging</li>
<li><strong>more</strong> information about getting fit/healthy eating/how to succeed</li>
<li><strong>more</strong> attention to your loved ones/the present moment</li>
<li><strong>more</strong> action around career goals/marketing yourself/searching for The One.</li>
</ul>
<p>However, in my experience, trying to put more into a cup which is already full just results in overflow. In our lives that can feel like overwhelm - resulting in less sleep, poor health, low self esteem, guilt and even shame.</p>
<p>We are led to believe that if we only knew/did/had/were … (fill in the gap yourself) our lives would be perfect, and when we fail and end up feeling worse about ourselves – and less likely to try again.</p>
<p>Part of the job of a coach is to help you empty the cup – review your life to look at what’s working and, in areas of your life which aren’t working, examine what you have been doing and what you have learnt about yourself.</p>
<p>Part of emptying the cup also involves discarding the ‘shoulds’ in your life so that you are left with <u>your</u> core values – the ones that get you up in the morning. These values will be reflected in what you are committed to in life and the strengths that get you through the day.</p>
<p>Coaching can act like a knife to cut away everything that isn’t <u>you</u> or aligned with <u>your</u> values. Clients experience a clarity of vision that can be exhilarating, liberating the energy trapped in previous failed attempts, to be redirected into the strengths that have already got you this far.</p>
<p><u>For example</u>, who wants to lose weight? How many times have you tried and how much energy have you expended on this? However, to ‘lose weight’ covers many different areas- e.g. how healthy you feel, your size, what you eat, your shape.
What would it be like to give up the idea of losing weight? How would it feel to be ok about the weight you are now? Notice how your body responds to that thought.</p>
<p>Instead, what is it <u>specifically</u> that you want?</p>
<ul>
<li>To feel toned/fit into a size smaller?</li>
<li>To feel less out of breath?</li>
<li>To sleep better?</li>
<li>To give up coffee/sugar/alcohol/chocolate/smoking?</li>
<li>To have more energy?</li>
</ul>
<p><u>Choose one area</u> and look at:</p>
<ul>
<li>when you have tried and failed - and what you said about yourself.</li>
<li>what you think you ‘should’ do/be/have in this area.</li>
</ul>
<p>If you gave up all the regrets/blame/sense of failure, what one step could you do today to give you a positive result in this area?</p>
<p>Make it something that you enjoy, something that you are already good at or something that is aligned to a commitment you already have.</p>
<p>We are filled to the brim with knowledge, but knowledge isn’t enough until it works in the service of <u>your</u> values, <u>your</u> strengths and <u>your</u> commitments.
Enjoy!</p>
<hr>
<ul class="pager">
<li class="previous">
<a href="/2016/01/17/coaching-for-carers/" data-toggle="tooltip" data-placement="top" title="Coaching for carers">← Previous Post</a>
</li>
<li class="next">
<a href="/2016/04/28/are_you_sabotaging_yourself/" data-toggle="tooltip" data-placement="top" title="Are you sabotaging yourself?">Next Post →</a>
</li>
</ul>
</div>
</div>
</div>
</article>
<hr>
<!-- Footer -->
<footer>
<div class="container">
<div class="row">
<div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
<ul class="list-inline text-center">
<li>
<a href="/feed.xml">
<span class="fa-stack fa-lg">
<i class="fa fa-square fa-stack-2x"></i>
<i class="fa fa-rss fa-stack-1x fa-inverse"></i>
</span>
</a>
</li>
<li>
<a href="https://github.com/akmacduff">
<span class="fa-stack fa-lg">
<i class="fa fa-square fa-stack-2x"></i>
<i class="fa fa-github fa-stack-1x fa-inverse"></i>
</span>
</a>
</li>
</ul>
<p class="copyright text-muted">Copyright © Quercus Coaching 2016. Made using <a href="https://jekyllrb.com/">Jekyll</a> with the <a href="https://github.com/IronSummitMedia/startbootstrap-clean-blog-jekyll">startbootstrap clean blog jekyll theme</a>.</p>
</div>
</div>
</div>
</footer>
<!-- jQuery -->
<script src="/js/jquery.min.js "></script>
<!-- Bootstrap Core JavaScript -->
<script src="/js/bootstrap.min.js "></script>
<!-- Custom Theme JavaScript -->
<script src="/js/clean-blog.min.js "></script>
</body>
</html>
| Java |
package bwhatsapp
import (
"encoding/gob"
"encoding/json"
"errors"
"fmt"
"os"
"strings"
qrcodeTerminal "github.com/Baozisoftware/qrcode-terminal-go"
"github.com/Rhymen/go-whatsapp"
)
type ProfilePicInfo struct {
URL string `json:"eurl"`
Tag string `json:"tag"`
Status int16 `json:"status"`
}
func qrFromTerminal(invert bool) chan string {
qr := make(chan string)
go func() {
terminal := qrcodeTerminal.New()
if invert {
terminal = qrcodeTerminal.New2(qrcodeTerminal.ConsoleColors.BrightWhite, qrcodeTerminal.ConsoleColors.BrightBlack, qrcodeTerminal.QRCodeRecoveryLevels.Medium)
}
terminal.Get(<-qr).Print()
}()
return qr
}
func (b *Bwhatsapp) readSession() (whatsapp.Session, error) {
session := whatsapp.Session{}
sessionFile := b.Config.GetString(sessionFile)
if sessionFile == "" {
return session, errors.New("if you won't set SessionFile then you will need to scan QR code on every restart")
}
file, err := os.Open(sessionFile)
if err != nil {
return session, err
}
defer file.Close()
decoder := gob.NewDecoder(file)
return session, decoder.Decode(&session)
}
func (b *Bwhatsapp) writeSession(session whatsapp.Session) error {
sessionFile := b.Config.GetString(sessionFile)
if sessionFile == "" {
// we already sent a warning while starting the bridge, so let's be quiet here
return nil
}
file, err := os.Create(sessionFile)
if err != nil {
return err
}
defer file.Close()
encoder := gob.NewEncoder(file)
return encoder.Encode(session)
}
func (b *Bwhatsapp) restoreSession() (*whatsapp.Session, error) {
session, err := b.readSession()
if err != nil {
b.Log.Warn(err.Error())
}
b.Log.Debugln("Restoring WhatsApp session..")
session, err = b.conn.RestoreWithSession(session)
if err != nil {
// restore session connection timed out (I couldn't get over it without logging in again)
return nil, errors.New("failed to restore session: " + err.Error())
}
b.Log.Debugln("Session restored successfully!")
return &session, nil
}
func (b *Bwhatsapp) getSenderName(senderJid string) string {
if sender, exists := b.users[senderJid]; exists {
if sender.Name != "" {
return sender.Name
}
// if user is not in phone contacts
// it is the most obvious scenario unless you sync your phone contacts with some remote updated source
// users can change it in their WhatsApp settings -> profile -> click on Avatar
if sender.Notify != "" {
return sender.Notify
}
if sender.Short != "" {
return sender.Short
}
}
// try to reload this contact
_, err := b.conn.Contacts()
if err != nil {
b.Log.Errorf("error on update of contacts: %v", err)
}
if contact, exists := b.conn.Store.Contacts[senderJid]; exists {
// Add it to the user map
b.users[senderJid] = contact
if contact.Name != "" {
return contact.Name
}
// if user is not in phone contacts
// same as above
return contact.Notify
}
return ""
}
func (b *Bwhatsapp) getSenderNotify(senderJid string) string {
if sender, exists := b.users[senderJid]; exists {
return sender.Notify
}
return ""
}
func (b *Bwhatsapp) GetProfilePicThumb(jid string) (*ProfilePicInfo, error) {
data, err := b.conn.GetProfilePicThumb(jid)
if err != nil {
return nil, fmt.Errorf("failed to get avatar: %v", err)
}
content := <-data
info := &ProfilePicInfo{}
err = json.Unmarshal([]byte(content), info)
if err != nil {
return info, fmt.Errorf("failed to unmarshal avatar info: %v", err)
}
return info, nil
}
func isGroupJid(identifier string) bool {
return strings.HasSuffix(identifier, "@g.us") ||
strings.HasSuffix(identifier, "@temp") ||
strings.HasSuffix(identifier, "@broadcast")
}
| Java |
'use strict';
var consoleBaseUrl = window.location.href;
consoleBaseUrl = consoleBaseUrl.substring(0, consoleBaseUrl.indexOf("/console"));
consoleBaseUrl = consoleBaseUrl + "/console";
var configUrl = consoleBaseUrl + "/config";
var auth = {};
var resourceBundle;
var locale = 'en';
var module = angular.module('keycloak', [ 'keycloak.services', 'keycloak.loaders', 'ui.bootstrap', 'ui.select2', 'angularFileUpload', 'angularTreeview', 'pascalprecht.translate', 'ngCookies', 'ngSanitize', 'ui.ace']);
var resourceRequests = 0;
var loadingTimer = -1;
angular.element(document).ready(function () {
var keycloakAuth = new Keycloak(configUrl);
function whoAmI(success, error) {
var req = new XMLHttpRequest();
req.open('GET', consoleBaseUrl + "/whoami", true);
req.setRequestHeader('Accept', 'application/json');
req.setRequestHeader('Authorization', 'bearer ' + keycloakAuth.token);
req.onreadystatechange = function () {
if (req.readyState == 4) {
if (req.status == 200) {
var data = JSON.parse(req.responseText);
success(data);
} else {
error();
}
}
}
req.send();
}
function loadResourceBundle(success, error) {
var req = new XMLHttpRequest();
req.open('GET', consoleBaseUrl + '/messages.json?lang=' + locale, true);
req.setRequestHeader('Accept', 'application/json');
req.onreadystatechange = function () {
if (req.readyState == 4) {
if (req.status == 200) {
var data = JSON.parse(req.responseText);
success && success(data);
} else {
error && error();
}
}
}
req.send();
}
function hasAnyAccess(user) {
return user && user['realm_access'];
}
keycloakAuth.onAuthLogout = function() {
location.reload();
}
keycloakAuth.init({ onLoad: 'login-required' }).success(function () {
auth.authz = keycloakAuth;
if (auth.authz.idTokenParsed.locale) {
locale = auth.authz.idTokenParsed.locale;
}
auth.refreshPermissions = function(success, error) {
whoAmI(function(data) {
auth.user = data;
auth.loggedIn = true;
auth.hasAnyAccess = hasAnyAccess(data);
success();
}, function() {
error();
});
};
loadResourceBundle(function(data) {
resourceBundle = data;
auth.refreshPermissions(function () {
module.factory('Auth', function () {
return auth;
});
var injector = angular.bootstrap(document, ["keycloak"]);
injector.get('$translate')('consoleTitle').then(function (consoleTitle) {
document.title = consoleTitle;
});
});
});
}).error(function () {
window.location.reload();
});
});
module.factory('authInterceptor', function($q, Auth) {
return {
request: function (config) {
if (!config.url.match(/.html$/)) {
var deferred = $q.defer();
if (Auth.authz.token) {
Auth.authz.updateToken(5).success(function () {
config.headers = config.headers || {};
config.headers.Authorization = 'Bearer ' + Auth.authz.token;
deferred.resolve(config);
}).error(function () {
location.reload();
});
}
return deferred.promise;
} else {
return config;
}
}
};
});
module.config(['$translateProvider', function($translateProvider) {
$translateProvider.useSanitizeValueStrategy('sanitizeParameters');
$translateProvider.preferredLanguage(locale);
$translateProvider.translations(locale, resourceBundle);
}]);
module.config([ '$routeProvider', function($routeProvider) {
$routeProvider
.when('/create/realm', {
templateUrl : resourceUrl + '/partials/realm-create.html',
resolve : {
},
controller : 'RealmCreateCtrl'
})
.when('/realms/:realm', {
templateUrl : resourceUrl + '/partials/realm-detail.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'RealmDetailCtrl'
})
.when('/realms/:realm/login-settings', {
templateUrl : resourceUrl + '/partials/realm-login-settings.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
serverInfo : function(ServerInfo) {
return ServerInfo.delay;
}
},
controller : 'RealmLoginSettingsCtrl'
})
.when('/realms/:realm/theme-settings', {
templateUrl : resourceUrl + '/partials/realm-theme-settings.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'RealmThemeCtrl'
})
.when('/realms/:realm/cache-settings', {
templateUrl : resourceUrl + '/partials/realm-cache-settings.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'RealmCacheCtrl'
})
.when('/realms', {
templateUrl : resourceUrl + '/partials/realm-list.html',
controller : 'RealmListCtrl'
})
.when('/realms/:realm/token-settings', {
templateUrl : resourceUrl + '/partials/realm-tokens.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
}
},
controller : 'RealmTokenDetailCtrl'
})
.when('/realms/:realm/client-initial-access', {
templateUrl : resourceUrl + '/partials/client-initial-access.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
clientInitialAccess : function(ClientInitialAccessLoader) {
return ClientInitialAccessLoader();
},
clientRegTrustedHosts : function(ClientRegistrationTrustedHostListLoader) {
return ClientRegistrationTrustedHostListLoader();
}
},
controller : 'ClientInitialAccessCtrl'
})
.when('/realms/:realm/client-initial-access/create', {
templateUrl : resourceUrl + '/partials/client-initial-access-create.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
}
},
controller : 'ClientInitialAccessCreateCtrl'
})
.when('/realms/:realm/client-reg-trusted-hosts/create', {
templateUrl : resourceUrl + '/partials/client-reg-trusted-host-create.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
clientRegTrustedHost : function() {
return {};
}
},
controller : 'ClientRegistrationTrustedHostDetailCtrl'
})
.when('/realms/:realm/client-reg-trusted-hosts/:hostname', {
templateUrl : resourceUrl + '/partials/client-reg-trusted-host-detail.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
clientRegTrustedHost : function(ClientRegistrationTrustedHostLoader) {
return ClientRegistrationTrustedHostLoader();
}
},
controller : 'ClientRegistrationTrustedHostDetailCtrl'
})
.when('/realms/:realm/keys-settings', {
templateUrl : resourceUrl + '/partials/realm-keys.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
}
},
controller : 'RealmKeysDetailCtrl'
})
.when('/realms/:realm/identity-provider-settings', {
templateUrl : resourceUrl + '/partials/realm-identity-provider.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
},
instance : function(IdentityProviderLoader) {
return {};
},
providerFactory : function(IdentityProviderFactoryLoader) {
return {};
},
authFlows : function(AuthenticationFlowsLoader) {
return {};
}
},
controller : 'RealmIdentityProviderCtrl'
})
.when('/create/identity-provider/:realm/:provider_id', {
templateUrl : function(params){ return resourceUrl + '/partials/realm-identity-provider-' + params.provider_id + '.html'; },
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
},
instance : function(IdentityProviderLoader) {
return {};
},
providerFactory : function(IdentityProviderFactoryLoader) {
return new IdentityProviderFactoryLoader();
},
authFlows : function(AuthenticationFlowsLoader) {
return AuthenticationFlowsLoader();
}
},
controller : 'RealmIdentityProviderCtrl'
})
.when('/realms/:realm/identity-provider-settings/provider/:provider_id/:alias', {
templateUrl : function(params){ return resourceUrl + '/partials/realm-identity-provider-' + params.provider_id + '.html'; },
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
},
instance : function(IdentityProviderLoader) {
return IdentityProviderLoader();
},
providerFactory : function(IdentityProviderFactoryLoader) {
return IdentityProviderFactoryLoader();
},
authFlows : function(AuthenticationFlowsLoader) {
return AuthenticationFlowsLoader();
}
},
controller : 'RealmIdentityProviderCtrl'
})
.when('/realms/:realm/identity-provider-settings/provider/:provider_id/:alias/export', {
templateUrl : resourceUrl + '/partials/realm-identity-provider-export.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
},
identityProvider : function(IdentityProviderLoader) {
return IdentityProviderLoader();
},
providerFactory : function(IdentityProviderFactoryLoader) {
return IdentityProviderFactoryLoader();
}
},
controller : 'RealmIdentityProviderExportCtrl'
})
.when('/realms/:realm/identity-provider-mappers/:alias/mappers', {
templateUrl : function(params){ return resourceUrl + '/partials/identity-provider-mappers.html'; },
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
identityProvider : function(IdentityProviderLoader) {
return IdentityProviderLoader();
},
mapperTypes : function(IdentityProviderMapperTypesLoader) {
return IdentityProviderMapperTypesLoader();
},
mappers : function(IdentityProviderMappersLoader) {
return IdentityProviderMappersLoader();
}
},
controller : 'IdentityProviderMapperListCtrl'
})
.when('/realms/:realm/identity-provider-mappers/:alias/mappers/:mapperId', {
templateUrl : function(params){ return resourceUrl + '/partials/identity-provider-mapper-detail.html'; },
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
identityProvider : function(IdentityProviderLoader) {
return IdentityProviderLoader();
},
mapperTypes : function(IdentityProviderMapperTypesLoader) {
return IdentityProviderMapperTypesLoader();
},
mapper : function(IdentityProviderMapperLoader) {
return IdentityProviderMapperLoader();
}
},
controller : 'IdentityProviderMapperCtrl'
})
.when('/create/identity-provider-mappers/:realm/:alias', {
templateUrl : function(params){ return resourceUrl + '/partials/identity-provider-mapper-detail.html'; },
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
identityProvider : function(IdentityProviderLoader) {
return IdentityProviderLoader();
},
mapperTypes : function(IdentityProviderMapperTypesLoader) {
return IdentityProviderMapperTypesLoader();
}
},
controller : 'IdentityProviderMapperCreateCtrl'
})
.when('/realms/:realm/default-roles', {
templateUrl : resourceUrl + '/partials/realm-default-roles.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
clients : function(ClientListLoader) {
return ClientListLoader();
},
roles : function(RoleListLoader) {
return RoleListLoader();
}
},
controller : 'RealmDefaultRolesCtrl'
})
.when('/realms/:realm/smtp-settings', {
templateUrl : resourceUrl + '/partials/realm-smtp.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
}
},
controller : 'RealmSMTPSettingsCtrl'
})
.when('/realms/:realm/events', {
templateUrl : resourceUrl + '/partials/realm-events.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'RealmEventsCtrl'
})
.when('/realms/:realm/admin-events', {
templateUrl : resourceUrl + '/partials/realm-events-admin.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'RealmAdminEventsCtrl'
})
.when('/realms/:realm/events-settings', {
templateUrl : resourceUrl + '/partials/realm-events-config.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
},
eventsConfig : function(RealmEventsConfigLoader) {
return RealmEventsConfigLoader();
}
},
controller : 'RealmEventsConfigCtrl'
})
.when('/realms/:realm/partial-import', {
templateUrl : resourceUrl + '/partials/partial-import.html',
resolve : {
resourceName : function() { return 'users'},
realm : function(RealmLoader) {
return RealmLoader();
}
},
controller : 'RealmImportCtrl'
})
.when('/create/user/:realm', {
templateUrl : resourceUrl + '/partials/user-detail.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
user : function() {
return {};
}
},
controller : 'UserDetailCtrl'
})
.when('/realms/:realm/users/:user', {
templateUrl : resourceUrl + '/partials/user-detail.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
user : function(UserLoader) {
return UserLoader();
}
},
controller : 'UserDetailCtrl'
})
.when('/realms/:realm/users/:user/user-attributes', {
templateUrl : resourceUrl + '/partials/user-attributes.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
user : function(UserLoader) {
return UserLoader();
}
},
controller : 'UserDetailCtrl'
})
.when('/realms/:realm/users/:user/user-credentials', {
templateUrl : resourceUrl + '/partials/user-credentials.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
user : function(UserLoader) {
return UserLoader();
}
},
controller : 'UserCredentialsCtrl'
})
.when('/realms/:realm/users/:user/role-mappings', {
templateUrl : resourceUrl + '/partials/role-mappings.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
user : function(UserLoader) {
return UserLoader();
},
clients : function(ClientListLoader) {
return ClientListLoader();
},
client : function() {
return {};
}
},
controller : 'UserRoleMappingCtrl'
})
.when('/realms/:realm/users/:user/groups', {
templateUrl : resourceUrl + '/partials/user-group-membership.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
user : function(UserLoader) {
return UserLoader();
},
groups : function(GroupListLoader) {
return GroupListLoader();
}
},
controller : 'UserGroupMembershipCtrl'
})
.when('/realms/:realm/users/:user/sessions', {
templateUrl : resourceUrl + '/partials/user-sessions.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
user : function(UserLoader) {
return UserLoader();
},
sessions : function(UserSessionsLoader) {
return UserSessionsLoader();
}
},
controller : 'UserSessionsCtrl'
})
.when('/realms/:realm/users/:user/federated-identity', {
templateUrl : resourceUrl + '/partials/user-federated-identity-list.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
user : function(UserLoader) {
return UserLoader();
},
federatedIdentities : function(UserFederatedIdentityLoader) {
return UserFederatedIdentityLoader();
}
},
controller : 'UserFederatedIdentityCtrl'
})
.when('/create/federated-identity/:realm/:user', {
templateUrl : resourceUrl + '/partials/user-federated-identity-detail.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
user : function(UserLoader) {
return UserLoader();
},
federatedIdentities : function(UserFederatedIdentityLoader) {
return UserFederatedIdentityLoader();
}
},
controller : 'UserFederatedIdentityAddCtrl'
})
.when('/realms/:realm/users/:user/consents', {
templateUrl : resourceUrl + '/partials/user-consents.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
user : function(UserLoader) {
return UserLoader();
},
userConsents : function(UserConsentsLoader) {
return UserConsentsLoader();
}
},
controller : 'UserConsentsCtrl'
})
.when('/realms/:realm/users/:user/offline-sessions/:client', {
templateUrl : resourceUrl + '/partials/user-offline-sessions.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
user : function(UserLoader) {
return UserLoader();
},
client : function(ClientLoader) {
return ClientLoader();
},
offlineSessions : function(UserOfflineSessionsLoader) {
return UserOfflineSessionsLoader();
}
},
controller : 'UserOfflineSessionsCtrl'
})
.when('/realms/:realm/users', {
templateUrl : resourceUrl + '/partials/user-list.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
}
},
controller : 'UserListCtrl'
})
.when('/create/role/:realm', {
templateUrl : resourceUrl + '/partials/role-detail.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
role : function() {
return {};
},
roles : function(RoleListLoader) {
return RoleListLoader();
},
clients : function(ClientListLoader) {
return ClientListLoader();
}
},
controller : 'RoleDetailCtrl'
})
.when('/realms/:realm/roles/:role', {
templateUrl : resourceUrl + '/partials/role-detail.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
role : function(RoleLoader) {
return RoleLoader();
},
roles : function(RoleListLoader) {
return RoleListLoader();
},
clients : function(ClientListLoader) {
return ClientListLoader();
}
},
controller : 'RoleDetailCtrl'
})
.when('/realms/:realm/roles', {
templateUrl : resourceUrl + '/partials/role-list.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
roles : function(RoleListLoader) {
return RoleListLoader();
}
},
controller : 'RoleListCtrl'
})
.when('/realms/:realm/groups', {
templateUrl : resourceUrl + '/partials/group-list.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
groups : function(GroupListLoader) {
return GroupListLoader();
}
},
controller : 'GroupListCtrl'
})
.when('/create/group/:realm/parent/:parentId', {
templateUrl : resourceUrl + '/partials/create-group.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
parentId : function($route) {
return $route.current.params.parentId;
}
},
controller : 'GroupCreateCtrl'
})
.when('/realms/:realm/groups/:group', {
templateUrl : resourceUrl + '/partials/group-detail.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
group : function(GroupLoader) {
return GroupLoader();
}
},
controller : 'GroupDetailCtrl'
})
.when('/realms/:realm/groups/:group/attributes', {
templateUrl : resourceUrl + '/partials/group-attributes.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
group : function(GroupLoader) {
return GroupLoader();
}
},
controller : 'GroupDetailCtrl'
})
.when('/realms/:realm/groups/:group/members', {
templateUrl : resourceUrl + '/partials/group-members.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
group : function(GroupLoader) {
return GroupLoader();
}
},
controller : 'GroupMembersCtrl'
})
.when('/realms/:realm/groups/:group/role-mappings', {
templateUrl : resourceUrl + '/partials/group-role-mappings.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
group : function(GroupLoader) {
return GroupLoader();
},
clients : function(ClientListLoader) {
return ClientListLoader();
},
client : function() {
return {};
}
},
controller : 'GroupRoleMappingCtrl'
})
.when('/realms/:realm/default-groups', {
templateUrl : resourceUrl + '/partials/default-groups.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
groups : function(GroupListLoader) {
return GroupListLoader();
}
},
controller : 'DefaultGroupsCtrl'
})
.when('/create/role/:realm/clients/:client', {
templateUrl : resourceUrl + '/partials/client-role-detail.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
client : function(ClientLoader) {
return ClientLoader();
},
role : function() {
return {};
},
roles : function(RoleListLoader) {
return RoleListLoader();
},
clients : function(ClientListLoader) {
return ClientListLoader();
}
},
controller : 'ClientRoleDetailCtrl'
})
.when('/realms/:realm/clients/:client/roles/:role', {
templateUrl : resourceUrl + '/partials/client-role-detail.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
client : function(ClientLoader) {
return ClientLoader();
},
role : function(ClientRoleLoader) {
return ClientRoleLoader();
},
roles : function(RoleListLoader) {
return RoleListLoader();
},
clients : function(ClientListLoader) {
return ClientListLoader();
}
},
controller : 'ClientRoleDetailCtrl'
})
.when('/realms/:realm/clients/:client/mappers', {
templateUrl : resourceUrl + '/partials/client-mappers.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
client : function(ClientLoader) {
return ClientLoader();
},
templates : function(ClientTemplateListLoader) {
return ClientTemplateListLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'ClientProtocolMapperListCtrl'
})
.when('/realms/:realm/clients/:client/add-mappers', {
templateUrl : resourceUrl + '/partials/client-mappers-add.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
client : function(ClientLoader) {
return ClientLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'AddBuiltinProtocolMapperCtrl'
})
.when('/realms/:realm/clients/:client/mappers/:id', {
templateUrl : resourceUrl + '/partials/client-protocol-mapper-detail.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
client : function(ClientLoader) {
return ClientLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
},
mapper : function(ClientProtocolMapperLoader) {
return ClientProtocolMapperLoader();
}
},
controller : 'ClientProtocolMapperCtrl'
})
.when('/create/client/:realm/:client/mappers', {
templateUrl : resourceUrl + '/partials/client-protocol-mapper-detail.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
},
client : function(ClientLoader) {
return ClientLoader();
}
},
controller : 'ClientProtocolMapperCreateCtrl'
})
.when('/realms/:realm/client-templates/:template/mappers', {
templateUrl : resourceUrl + '/partials/client-template-mappers.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
template : function(ClientTemplateLoader) {
return ClientTemplateLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'ClientTemplateProtocolMapperListCtrl'
})
.when('/realms/:realm/client-templates/:template/add-mappers', {
templateUrl : resourceUrl + '/partials/client-template-mappers-add.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
template : function(ClientTemplateLoader) {
return ClientTemplateLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'ClientTemplateAddBuiltinProtocolMapperCtrl'
})
.when('/realms/:realm/client-templates/:template/mappers/:id', {
templateUrl : resourceUrl + '/partials/client-template-protocol-mapper-detail.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
template : function(ClientTemplateLoader) {
return ClientTemplateLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
},
mapper : function(ClientTemplateProtocolMapperLoader) {
return ClientTemplateProtocolMapperLoader();
}
},
controller : 'ClientTemplateProtocolMapperCtrl'
})
.when('/create/client-template/:realm/:template/mappers', {
templateUrl : resourceUrl + '/partials/client-template-protocol-mapper-detail.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
},
template : function(ClientTemplateLoader) {
return ClientTemplateLoader();
}
},
controller : 'ClientTemplateProtocolMapperCreateCtrl'
})
.when('/realms/:realm/clients/:client/sessions', {
templateUrl : resourceUrl + '/partials/client-sessions.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
client : function(ClientLoader) {
return ClientLoader();
},
sessionCount : function(ClientSessionCountLoader) {
return ClientSessionCountLoader();
}
},
controller : 'ClientSessionsCtrl'
})
.when('/realms/:realm/clients/:client/offline-access', {
templateUrl : resourceUrl + '/partials/client-offline-sessions.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
client : function(ClientLoader) {
return ClientLoader();
},
offlineSessionCount : function(ClientOfflineSessionCountLoader) {
return ClientOfflineSessionCountLoader();
}
},
controller : 'ClientOfflineSessionsCtrl'
})
.when('/realms/:realm/clients/:client/credentials', {
templateUrl : resourceUrl + '/partials/client-credentials.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
client : function(ClientLoader) {
return ClientLoader();
},
clientAuthenticatorProviders : function(ClientAuthenticatorProvidersLoader) {
return ClientAuthenticatorProvidersLoader();
},
clientConfigProperties: function(PerClientAuthenticationConfigDescriptionLoader) {
return PerClientAuthenticationConfigDescriptionLoader();
}
},
controller : 'ClientCredentialsCtrl'
})
.when('/realms/:realm/clients/:client/credentials/client-jwt/:keyType/import/:attribute', {
templateUrl : resourceUrl + '/partials/client-credentials-jwt-key-import.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
client : function(ClientLoader) {
return ClientLoader();
},
callingContext : function() {
return "jwt-credentials";
}
},
controller : 'ClientCertificateImportCtrl'
})
.when('/realms/:realm/clients/:client/credentials/client-jwt/:keyType/export/:attribute', {
templateUrl : resourceUrl + '/partials/client-credentials-jwt-key-export.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
client : function(ClientLoader) {
return ClientLoader();
},
callingContext : function() {
return "jwt-credentials";
}
},
controller : 'ClientCertificateExportCtrl'
})
.when('/realms/:realm/clients/:client/identity-provider', {
templateUrl : resourceUrl + '/partials/client-identity-provider.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
client : function(ClientLoader) {
return ClientLoader();
}
},
controller : 'ClientIdentityProviderCtrl'
})
.when('/realms/:realm/clients/:client/clustering', {
templateUrl : resourceUrl + '/partials/client-clustering.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
client : function(ClientLoader) {
return ClientLoader();
}
},
controller : 'ClientClusteringCtrl'
})
.when('/register-node/realms/:realm/clients/:client/clustering', {
templateUrl : resourceUrl + '/partials/client-clustering-node.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
client : function(ClientLoader) {
return ClientLoader();
}
},
controller : 'ClientClusteringNodeCtrl'
})
.when('/realms/:realm/clients/:client/clustering/:node', {
templateUrl : resourceUrl + '/partials/client-clustering-node.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
client : function(ClientLoader) {
return ClientLoader();
}
},
controller : 'ClientClusteringNodeCtrl'
})
.when('/realms/:realm/clients/:client/saml/keys', {
templateUrl : resourceUrl + '/partials/client-saml-keys.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
client : function(ClientLoader) {
return ClientLoader();
}
},
controller : 'ClientSamlKeyCtrl'
})
.when('/realms/:realm/clients/:client/saml/:keyType/import/:attribute', {
templateUrl : resourceUrl + '/partials/client-saml-key-import.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
client : function(ClientLoader) {
return ClientLoader();
},
callingContext : function() {
return "saml";
}
},
controller : 'ClientCertificateImportCtrl'
})
.when('/realms/:realm/clients/:client/saml/:keyType/export/:attribute', {
templateUrl : resourceUrl + '/partials/client-saml-key-export.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
client : function(ClientLoader) {
return ClientLoader();
},
callingContext : function() {
return "saml";
}
},
controller : 'ClientCertificateExportCtrl'
})
.when('/realms/:realm/clients/:client/roles', {
templateUrl : resourceUrl + '/partials/client-role-list.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
client : function(ClientLoader) {
return ClientLoader();
},
roles : function(ClientRoleListLoader) {
return ClientRoleListLoader();
}
},
controller : 'ClientRoleListCtrl'
})
.when('/realms/:realm/clients/:client/revocation', {
templateUrl : resourceUrl + '/partials/client-revocation.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
client : function(ClientLoader) {
return ClientLoader();
}
},
controller : 'ClientRevocationCtrl'
})
.when('/realms/:realm/clients/:client/scope-mappings', {
templateUrl : resourceUrl + '/partials/client-scope-mappings.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
client : function(ClientLoader) {
return ClientLoader();
},
templates : function(ClientTemplateListLoader) {
return ClientTemplateListLoader();
},
clients : function(ClientListLoader) {
return ClientListLoader();
}
},
controller : 'ClientScopeMappingCtrl'
})
.when('/realms/:realm/clients/:client/installation', {
templateUrl : resourceUrl + '/partials/client-installation.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
client : function(ClientLoader) {
return ClientLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'ClientInstallationCtrl'
})
.when('/realms/:realm/clients/:client/service-account-roles', {
templateUrl : resourceUrl + '/partials/client-service-account-roles.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
user : function(ClientServiceAccountUserLoader) {
return ClientServiceAccountUserLoader();
},
clients : function(ClientListLoader) {
return ClientListLoader();
},
client : function(ClientLoader) {
return ClientLoader();
}
},
controller : 'UserRoleMappingCtrl'
})
.when('/create/client/:realm', {
templateUrl : resourceUrl + '/partials/create-client.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
templates : function(ClientTemplateListLoader) {
return ClientTemplateListLoader();
},
clients : function(ClientListLoader) {
return ClientListLoader();
},
client : function() {
return {};
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'CreateClientCtrl'
})
.when('/realms/:realm/clients/:client', {
templateUrl : resourceUrl + '/partials/client-detail.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
templates : function(ClientTemplateListLoader) {
return ClientTemplateListLoader();
},
clients : function(ClientListLoader) {
return ClientListLoader();
},
client : function(ClientLoader) {
return ClientLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'ClientDetailCtrl'
})
.when('/create/client-template/:realm', {
templateUrl : resourceUrl + '/partials/client-template-detail.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
templates : function(ClientTemplateListLoader) {
return ClientTemplateListLoader();
},
template : function() {
return {};
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'ClientTemplateDetailCtrl'
})
.when('/realms/:realm/client-templates/:template', {
templateUrl : resourceUrl + '/partials/client-template-detail.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
templates : function(ClientTemplateListLoader) {
return ClientTemplateListLoader();
},
template : function(ClientTemplateLoader) {
return ClientTemplateLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'ClientTemplateDetailCtrl'
})
.when('/realms/:realm/client-templates/:template/scope-mappings', {
templateUrl : resourceUrl + '/partials/client-template-scope-mappings.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
template : function(ClientTemplateLoader) {
return ClientTemplateLoader();
},
clients : function(ClientListLoader) {
return ClientListLoader();
}
},
controller : 'ClientTemplateScopeMappingCtrl'
})
.when('/realms/:realm/clients', {
templateUrl : resourceUrl + '/partials/client-list.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
clients : function(ClientListLoader) {
return ClientListLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'ClientListCtrl'
})
.when('/realms/:realm/client-templates', {
templateUrl : resourceUrl + '/partials/client-template-list.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
templates : function(ClientTemplateListLoader) {
return ClientTemplateListLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'ClientTemplateListCtrl'
})
.when('/import/client/:realm', {
templateUrl : resourceUrl + '/partials/client-import.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'ClientImportCtrl'
})
.when('/', {
templateUrl : resourceUrl + '/partials/home.html',
controller : 'HomeCtrl'
})
.when('/mocks/:realm', {
templateUrl : resourceUrl + '/partials/realm-detail_mock.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'RealmDetailCtrl'
})
.when('/realms/:realm/sessions/revocation', {
templateUrl : resourceUrl + '/partials/session-revocation.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
}
},
controller : 'RealmRevocationCtrl'
})
.when('/realms/:realm/sessions/realm', {
templateUrl : resourceUrl + '/partials/session-realm.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
stats : function(RealmClientSessionStatsLoader) {
return RealmClientSessionStatsLoader();
}
},
controller : 'RealmSessionStatsCtrl'
})
.when('/create/user-storage/:realm/providers/:provider', {
templateUrl : resourceUrl + '/partials/user-storage-generic.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
instance : function() {
return {
};
},
providerId : function($route) {
return $route.current.params.provider;
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'GenericUserStorageCtrl'
})
.when('/realms/:realm/user-storage/providers/:provider/:componentId', {
templateUrl : resourceUrl + '/partials/user-storage-generic.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
instance : function(ComponentLoader) {
return ComponentLoader();
},
providerId : function($route) {
return $route.current.params.provider;
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'GenericUserStorageCtrl'
})
.when('/realms/:realm/user-federation', {
templateUrl : resourceUrl + '/partials/user-federation.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'UserFederationCtrl'
})
.when('/realms/:realm/user-federation/providers/ldap/:instance', {
templateUrl : resourceUrl + '/partials/federated-ldap.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
instance : function(UserFederationInstanceLoader) {
return UserFederationInstanceLoader();
}
},
controller : 'LDAPCtrl'
})
.when('/create/user-federation/:realm/providers/ldap', {
templateUrl : resourceUrl + '/partials/federated-ldap.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
instance : function() {
return {};
}
},
controller : 'LDAPCtrl'
})
.when('/realms/:realm/user-federation/providers/kerberos/:instance', {
templateUrl : resourceUrl + '/partials/federated-kerberos.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
instance : function(UserFederationInstanceLoader) {
return UserFederationInstanceLoader();
},
providerFactory : function() {
return { id: "kerberos" };
}
},
controller : 'GenericUserFederationCtrl'
})
.when('/create/user-federation/:realm/providers/kerberos', {
templateUrl : resourceUrl + '/partials/federated-kerberos.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
instance : function() {
return {};
},
providerFactory : function() {
return { id: "kerberos" };
}
},
controller : 'GenericUserFederationCtrl'
})
.when('/create/user-federation/:realm/providers/:provider', {
templateUrl : resourceUrl + '/partials/federated-generic.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
instance : function() {
return {
};
},
providerFactory : function(UserFederationFactoryLoader) {
return UserFederationFactoryLoader();
}
},
controller : 'GenericUserFederationCtrl'
})
.when('/realms/:realm/user-federation/providers/:provider/:instance', {
templateUrl : resourceUrl + '/partials/federated-generic.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
instance : function(UserFederationInstanceLoader) {
return UserFederationInstanceLoader();
},
providerFactory : function(UserFederationFactoryLoader) {
return UserFederationFactoryLoader();
}
},
controller : 'GenericUserFederationCtrl'
})
.when('/realms/:realm/user-federation/providers/:provider/:instance/mappers', {
templateUrl : function(params){ return resourceUrl + '/partials/federated-mappers.html'; },
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
provider : function(UserFederationInstanceLoader) {
return UserFederationInstanceLoader();
},
mapperTypes : function(UserFederationMapperTypesLoader) {
return UserFederationMapperTypesLoader();
},
mappers : function(UserFederationMappersLoader) {
return UserFederationMappersLoader();
}
},
controller : 'UserFederationMapperListCtrl'
})
.when('/realms/:realm/user-federation/providers/:provider/:instance/mappers/:mapperId', {
templateUrl : function(params){ return resourceUrl + '/partials/federated-mapper-detail.html'; },
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
provider : function(UserFederationInstanceLoader) {
return UserFederationInstanceLoader();
},
mapperTypes : function(UserFederationMapperTypesLoader) {
return UserFederationMapperTypesLoader();
},
mapper : function(UserFederationMapperLoader) {
return UserFederationMapperLoader();
},
clients : function(ClientListLoader) {
return ClientListLoader();
}
},
controller : 'UserFederationMapperCtrl'
})
.when('/create/user-federation-mappers/:realm/:provider/:instance', {
templateUrl : function(params){ return resourceUrl + '/partials/federated-mapper-detail.html'; },
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
provider : function(UserFederationInstanceLoader) {
return UserFederationInstanceLoader();
},
mapperTypes : function(UserFederationMapperTypesLoader) {
return UserFederationMapperTypesLoader();
},
clients : function(ClientListLoader) {
return ClientListLoader();
}
},
controller : 'UserFederationMapperCreateCtrl'
})
.when('/realms/:realm/defense/headers', {
templateUrl : resourceUrl + '/partials/defense-headers.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'DefenseHeadersCtrl'
})
.when('/realms/:realm/defense/brute-force', {
templateUrl : resourceUrl + '/partials/brute-force.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
}
},
controller : 'RealmBruteForceCtrl'
})
.when('/realms/:realm/protocols', {
templateUrl : resourceUrl + '/partials/protocol-list.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'ProtocolListCtrl'
})
.when('/realms/:realm/authentication/flows', {
templateUrl : resourceUrl + '/partials/authentication-flows.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
flows : function(AuthenticationFlowsLoader) {
return AuthenticationFlowsLoader();
},
selectedFlow : function() {
return null;
}
},
controller : 'AuthenticationFlowsCtrl'
})
.when('/realms/:realm/authentication/flow-bindings', {
templateUrl : resourceUrl + '/partials/authentication-flow-bindings.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
flows : function(AuthenticationFlowsLoader) {
return AuthenticationFlowsLoader();
},
serverInfo : function(ServerInfo) {
return ServerInfo.delay;
}
},
controller : 'RealmFlowBindingCtrl'
})
.when('/realms/:realm/authentication/flows/:flow', {
templateUrl : resourceUrl + '/partials/authentication-flows.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
flows : function(AuthenticationFlowsLoader) {
return AuthenticationFlowsLoader();
},
selectedFlow : function($route) {
return $route.current.params.flow;
}
},
controller : 'AuthenticationFlowsCtrl'
})
.when('/realms/:realm/authentication/flows/:flow/create/execution/:topFlow', {
templateUrl : resourceUrl + '/partials/create-execution.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
topFlow: function($route) {
return $route.current.params.topFlow;
},
parentFlow : function(AuthenticationFlowLoader) {
return AuthenticationFlowLoader();
},
formActionProviders : function(AuthenticationFormActionProvidersLoader) {
return AuthenticationFormActionProvidersLoader();
},
authenticatorProviders : function(AuthenticatorProvidersLoader) {
return AuthenticatorProvidersLoader();
},
clientAuthenticatorProviders : function(ClientAuthenticatorProvidersLoader) {
return ClientAuthenticatorProvidersLoader();
}
},
controller : 'CreateExecutionCtrl'
})
.when('/realms/:realm/authentication/flows/:flow/create/flow/execution/:topFlow', {
templateUrl : resourceUrl + '/partials/create-flow-execution.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
topFlow: function($route) {
return $route.current.params.topFlow;
},
parentFlow : function(AuthenticationFlowLoader) {
return AuthenticationFlowLoader();
},
formProviders : function(AuthenticationFormProvidersLoader) {
return AuthenticationFormProvidersLoader();
}
},
controller : 'CreateExecutionFlowCtrl'
})
.when('/realms/:realm/authentication/create/flow', {
templateUrl : resourceUrl + '/partials/create-flow.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
}
},
controller : 'CreateFlowCtrl'
})
.when('/realms/:realm/authentication/required-actions', {
templateUrl : resourceUrl + '/partials/required-actions.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
unregisteredRequiredActions : function(UnregisteredRequiredActionsListLoader) {
return UnregisteredRequiredActionsListLoader();
}
},
controller : 'RequiredActionsCtrl'
})
.when('/realms/:realm/authentication/password-policy', {
templateUrl : resourceUrl + '/partials/password-policy.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'RealmPasswordPolicyCtrl'
})
.when('/realms/:realm/authentication/otp-policy', {
templateUrl : resourceUrl + '/partials/otp-policy.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
serverInfo : function(ServerInfo) {
return ServerInfo.delay;
}
},
controller : 'RealmOtpPolicyCtrl'
})
.when('/realms/:realm/authentication/flows/:flow/config/:provider/:config', {
templateUrl : resourceUrl + '/partials/authenticator-config.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
flow : function(AuthenticationFlowLoader) {
return AuthenticationFlowLoader();
},
configType : function(AuthenticationConfigDescriptionLoader) {
return AuthenticationConfigDescriptionLoader();
},
config : function(AuthenticationConfigLoader) {
return AuthenticationConfigLoader();
}
},
controller : 'AuthenticationConfigCtrl'
})
.when('/create/authentication/:realm/flows/:flow/execution/:executionId/provider/:provider', {
templateUrl : resourceUrl + '/partials/authenticator-config.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
flow : function(AuthenticationFlowLoader) {
return AuthenticationFlowLoader();
},
configType : function(AuthenticationConfigDescriptionLoader) {
return AuthenticationConfigDescriptionLoader();
},
execution : function(ExecutionIdLoader) {
return ExecutionIdLoader();
}
},
controller : 'AuthenticationConfigCreateCtrl'
})
.when('/server-info', {
templateUrl : resourceUrl + '/partials/server-info.html',
resolve : {
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'ServerInfoCtrl'
})
.when('/server-info/providers', {
templateUrl : resourceUrl + '/partials/server-info-providers.html',
resolve : {
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'ServerInfoCtrl'
})
.when('/logout', {
templateUrl : resourceUrl + '/partials/home.html',
controller : 'LogoutCtrl'
})
.when('/notfound', {
templateUrl : resourceUrl + '/partials/notfound.html'
})
.when('/forbidden', {
templateUrl : resourceUrl + '/partials/forbidden.html'
})
.otherwise({
templateUrl : resourceUrl + '/partials/pagenotfound.html'
});
} ]);
module.config(function($httpProvider) {
$httpProvider.interceptors.push('errorInterceptor');
var spinnerFunction = function(data, headersGetter) {
if (resourceRequests == 0) {
loadingTimer = window.setTimeout(function() {
$('#loading').show();
loadingTimer = -1;
}, 500);
}
resourceRequests++;
return data;
};
$httpProvider.defaults.transformRequest.push(spinnerFunction);
$httpProvider.interceptors.push('spinnerInterceptor');
$httpProvider.interceptors.push('authInterceptor');
});
module.factory('spinnerInterceptor', function($q, $window, $rootScope, $location) {
return {
response: function(response) {
resourceRequests--;
if (resourceRequests == 0) {
if(loadingTimer != -1) {
window.clearTimeout(loadingTimer);
loadingTimer = -1;
}
$('#loading').hide();
}
return response;
},
responseError: function(response) {
resourceRequests--;
if (resourceRequests == 0) {
if(loadingTimer != -1) {
window.clearTimeout(loadingTimer);
loadingTimer = -1;
}
$('#loading').hide();
}
return $q.reject(response);
}
};
});
module.factory('errorInterceptor', function($q, $window, $rootScope, $location, Notifications, Auth) {
return {
response: function(response) {
return response;
},
responseError: function(response) {
if (response.status == 401) {
Auth.authz.logout();
} else if (response.status == 403) {
$location.path('/forbidden');
} else if (response.status == 404) {
$location.path('/notfound');
} else if (response.status) {
if (response.data && response.data.errorMessage) {
Notifications.error(response.data.errorMessage);
} else {
Notifications.error("An unexpected server error has occurred");
}
}
return $q.reject(response);
}
};
});
// collapsable form fieldsets
module.directive('collapsable', function() {
return function(scope, element, attrs) {
element.click(function() {
$(this).toggleClass('collapsed');
$(this).find('.toggle-icons').toggleClass('kc-icon-collapse').toggleClass('kc-icon-expand');
$(this).find('.toggle-icons').text($(this).text() == "Icon: expand" ? "Icon: collapse" : "Icon: expand");
$(this).parent().find('.form-group').toggleClass('hidden');
});
}
});
// collapsable form fieldsets
module.directive('uncollapsed', function() {
return function(scope, element, attrs) {
element.prepend('<i class="toggle-class fa fa-angle-down"></i> ');
element.click(function() {
$(this).find('.toggle-class').toggleClass('fa-angle-down').toggleClass('fa-angle-right');
$(this).parent().find('.form-group').toggleClass('hidden');
});
}
});
// collapsable form fieldsets
module.directive('collapsed', function() {
return function(scope, element, attrs) {
element.prepend('<i class="toggle-class fa fa-angle-right"></i> ');
element.parent().find('.form-group').toggleClass('hidden');
element.click(function() {
$(this).find('.toggle-class').toggleClass('fa-angle-down').toggleClass('fa-angle-right');
$(this).parent().find('.form-group').toggleClass('hidden');
});
}
});
/**
* Directive for presenting an ON-OFF switch for checkbox.
* Usage: <input ng-model="mmm" name="nnn" id="iii" onoffswitch [on-text="ooo" off-text="fff"] />
*/
module.directive('onoffswitch', function() {
return {
restrict: "EA",
replace: true,
scope: {
name: '@',
id: '@',
ngModel: '=',
ngDisabled: '=',
kcOnText: '@onText',
kcOffText: '@offText'
},
// TODO - The same code acts differently when put into the templateURL. Find why and move the code there.
//templateUrl: "templates/kc-switch.html",
template: "<span><div class='onoffswitch' tabindex='0'><input type='checkbox' ng-model='ngModel' ng-disabled='ngDisabled' class='onoffswitch-checkbox' name='{{name}}' id='{{id}}'><label for='{{id}}' class='onoffswitch-label'><span class='onoffswitch-inner'><span class='onoffswitch-active'>{{kcOnText}}</span><span class='onoffswitch-inactive'>{{kcOffText}}</span></span><span class='onoffswitch-switch'></span></label></div></span>",
compile: function(element, attrs) {
/*
We don't want to propagate basic attributes to the root element of directive. Id should be passed to the
input element only to achieve proper label binding (and validity).
*/
element.removeAttr('name');
element.removeAttr('id');
if (!attrs.onText) { attrs.onText = "ON"; }
if (!attrs.offText) { attrs.offText = "OFF"; }
element.bind('keydown', function(e){
var code = e.keyCode || e.which;
if (code === 32 || code === 13) {
e.stopImmediatePropagation();
e.preventDefault();
$(e.target).find('input').click();
}
});
}
}
});
/**
* Directive for presenting an ON-OFF switch for checkbox. The directive expects the value to be string 'true' or 'false', not boolean true/false
* This directive provides some additional capabilities to the default onoffswitch such as:
*
* - Dynamic values for id and name attributes. Useful if you need to use this directive inside a ng-repeat
* - Specific scope to specify the value. Instead of just true or false.
*
* Usage: <input ng-model="mmm" name="nnn" id="iii" kc-onoffswitch-model [on-text="ooo" off-text="fff"] />
*/
module.directive('onoffswitchstring', function() {
return {
restrict: "EA",
replace: true,
scope: {
name: '=',
id: '=',
value: '=',
ngModel: '=',
ngDisabled: '=',
kcOnText: '@onText',
kcOffText: '@offText'
},
// TODO - The same code acts differently when put into the templateURL. Find why and move the code there.
//templateUrl: "templates/kc-switch.html",
template: '<span><div class="onoffswitch" tabindex="0"><input type="checkbox" ng-true-value="\'true\'" ng-false-value="\'false\'" ng-model="ngModel" ng-disabled="ngDisabled" class="onoffswitch-checkbox" name="kc{{name}}" id="kc{{id}}"><label for="kc{{id}}" class="onoffswitch-label"><span class="onoffswitch-inner"><span class="onoffswitch-active">{{kcOnText}}</span><span class="onoffswitch-inactive">{{kcOffText}}</span></span><span class="onoffswitch-switch"></span></label></div></span>',
compile: function(element, attrs) {
if (!attrs.onText) { attrs.onText = "ON"; }
if (!attrs.offText) { attrs.offText = "OFF"; }
element.bind('keydown click', function(e){
var code = e.keyCode || e.which;
if (code === 32 || code === 13) {
e.stopImmediatePropagation();
e.preventDefault();
$(e.target).find('input').click();
}
});
}
}
});
/**
* Directive for presenting an ON-OFF switch for checkbox. The directive expects the true-value or false-value to be string like 'true' or 'false', not boolean true/false.
* This directive provides some additional capabilities to the default onoffswitch such as:
*
* - Specific scope to specify the value. Instead of just 'true' or 'false' you can use any other values. For example: true-value="'foo'" false-value="'bar'" .
* But 'true'/'false' are defaults if true-value and false-value are not specified
*
* Usage: <input ng-model="mmm" name="nnn" id="iii" onoffswitchvalue [ true-value="'true'" false-value="'false'" on-text="ooo" off-text="fff"] />
*/
module.directive('onoffswitchvalue', function() {
return {
restrict: "EA",
replace: true,
scope: {
name: '@',
id: '@',
trueValue: '@',
falseValue: '@',
ngModel: '=',
ngDisabled: '=',
kcOnText: '@onText',
kcOffText: '@offText'
},
// TODO - The same code acts differently when put into the templateURL. Find why and move the code there.
//templateUrl: "templates/kc-switch.html",
template: "<span><div class='onoffswitch' tabindex='0'><input type='checkbox' ng-true-value='{{trueValue}}' ng-false-value='{{falseValue}}' ng-model='ngModel' ng-disabled='ngDisabled' class='onoffswitch-checkbox' name='{{name}}' id='{{id}}'><label for='{{id}}' class='onoffswitch-label'><span class='onoffswitch-inner'><span class='onoffswitch-active'>{{kcOnText}}</span><span class='onoffswitch-inactive'>{{kcOffText}}</span></span><span class='onoffswitch-switch'></span></label></div></span>",
compile: function(element, attrs) {
/*
We don't want to propagate basic attributes to the root element of directive. Id should be passed to the
input element only to achieve proper label binding (and validity).
*/
element.removeAttr('name');
element.removeAttr('id');
if (!attrs.trueValue) { attrs.trueValue = "'true'"; }
if (!attrs.falseValue) { attrs.falseValue = "'false'"; }
if (!attrs.onText) { attrs.onText = "ON"; }
if (!attrs.offText) { attrs.offText = "OFF"; }
element.bind('keydown', function(e){
var code = e.keyCode || e.which;
if (code === 32 || code === 13) {
e.stopImmediatePropagation();
e.preventDefault();
$(e.target).find('input').click();
}
});
}
}
});
module.directive('kcInput', function() {
var d = {
scope : true,
replace : false,
link : function(scope, element, attrs) {
var form = element.children('form');
var label = element.children('label');
var input = element.children('input');
var id = form.attr('name') + '.' + input.attr('name');
element.attr('class', 'control-group');
label.attr('class', 'control-label');
label.attr('for', id);
input.wrap('<div class="controls"/>');
input.attr('id', id);
if (!input.attr('placeHolder')) {
input.attr('placeHolder', label.text());
}
if (input.attr('required')) {
label.append(' <span class="required">*</span>');
}
}
};
return d;
});
module.directive('kcEnter', function() {
return function(scope, element, attrs) {
element.bind("keydown keypress", function(event) {
if (event.which === 13) {
scope.$apply(function() {
scope.$eval(attrs.kcEnter);
});
event.preventDefault();
}
});
};
});
module.directive('kcSave', function ($compile, Notifications) {
return {
restrict: 'A',
link: function ($scope, elem, attr, ctrl) {
elem.addClass("btn btn-primary");
elem.attr("type","submit");
elem.bind('click', function() {
$scope.$apply(function() {
var form = elem.closest('form');
if (form && form.attr('name')) {
var ngValid = form.find('.ng-valid');
if ($scope[form.attr('name')].$valid) {
//ngValid.removeClass('error');
ngValid.parent().removeClass('has-error');
$scope['save']();
} else {
Notifications.error("Missing or invalid field(s). Please verify the fields in red.")
//ngValid.removeClass('error');
ngValid.parent().removeClass('has-error');
var ngInvalid = form.find('.ng-invalid');
//ngInvalid.addClass('error');
ngInvalid.parent().addClass('has-error');
}
}
});
})
}
}
});
module.directive('kcReset', function ($compile, Notifications) {
return {
restrict: 'A',
link: function ($scope, elem, attr, ctrl) {
elem.addClass("btn btn-default");
elem.attr("type","submit");
elem.bind('click', function() {
$scope.$apply(function() {
var form = elem.closest('form');
if (form && form.attr('name')) {
form.find('.ng-valid').removeClass('error');
form.find('.ng-invalid').removeClass('error');
$scope['reset']();
}
})
})
}
}
});
module.directive('kcCancel', function ($compile, Notifications) {
return {
restrict: 'A',
link: function ($scope, elem, attr, ctrl) {
elem.addClass("btn btn-default");
elem.attr("type","submit");
}
}
});
module.directive('kcDelete', function ($compile, Notifications) {
return {
restrict: 'A',
link: function ($scope, elem, attr, ctrl) {
elem.addClass("btn btn-danger");
elem.attr("type","submit");
}
}
});
module.directive('kcDropdown', function ($compile, Notifications) {
return {
scope: {
kcOptions: '=',
kcModel: '=',
id: "=",
kcPlaceholder: '@'
},
restrict: 'EA',
replace: true,
templateUrl: resourceUrl + '/templates/kc-select.html',
link: function(scope, element, attr) {
scope.updateModel = function(item) {
scope.kcModel = item;
};
}
}
});
module.directive('kcReadOnly', function() {
var disabled = {};
var d = {
replace : false,
link : function(scope, element, attrs) {
var disable = function(i, e) {
if (!e.disabled) {
disabled[e.tagName + i] = true;
e.disabled = true;
}
}
var enable = function(i, e) {
if (disabled[e.tagName + i]) {
e.disabled = false;
delete disabled[i];
}
}
var filterIgnored = function(i, e){
return !e.attributes['kc-read-only-ignore'];
}
scope.$watch(attrs.kcReadOnly, function(readOnly) {
if (readOnly) {
element.find('input').filter(filterIgnored).each(disable);
element.find('button').filter(filterIgnored).each(disable);
element.find('select').filter(filterIgnored).each(disable);
element.find('textarea').filter(filterIgnored).each(disable);
} else {
element.find('input').filter(filterIgnored).each(enable);
element.find('input').filter(filterIgnored).each(enable);
element.find('button').filter(filterIgnored).each(enable);
element.find('select').filter(filterIgnored).each(enable);
element.find('textarea').filter(filterIgnored).each(enable);
}
});
}
};
return d;
});
module.directive('kcMenu', function () {
return {
scope: true,
restrict: 'E',
replace: true,
templateUrl: resourceUrl + '/templates/kc-menu.html'
}
});
module.directive('kcTabsRealm', function () {
return {
scope: true,
restrict: 'E',
replace: true,
templateUrl: resourceUrl + '/templates/kc-tabs-realm.html'
}
});
module.directive('kcTabsAuthentication', function () {
return {
scope: true,
restrict: 'E',
replace: true,
templateUrl: resourceUrl + '/templates/kc-tabs-authentication.html'
}
});
module.directive('kcTabsUser', function () {
return {
scope: true,
restrict: 'E',
replace: true,
templateUrl: resourceUrl + '/templates/kc-tabs-user.html'
}
});
module.directive('kcTabsGroup', function () {
return {
scope: true,
restrict: 'E',
replace: true,
templateUrl: resourceUrl + '/templates/kc-tabs-group.html'
}
});
module.directive('kcTabsGroupList', function () {
return {
scope: true,
restrict: 'E',
replace: true,
templateUrl: resourceUrl + '/templates/kc-tabs-group-list.html'
}
});
module.directive('kcTabsClient', function () {
return {
scope: true,
restrict: 'E',
replace: true,
templateUrl: resourceUrl + '/templates/kc-tabs-client.html'
}
});
module.directive('kcTabsClientTemplate', function () {
return {
scope: true,
restrict: 'E',
replace: true,
templateUrl: resourceUrl + '/templates/kc-tabs-client-template.html'
}
});
module.directive('kcNavigationUser', function () {
return {
scope: true,
restrict: 'E',
replace: true,
templateUrl: resourceUrl + '/templates/kc-navigation-user.html'
}
});
module.directive('kcTabsIdentityProvider', function () {
return {
scope: true,
restrict: 'E',
replace: true,
templateUrl: resourceUrl + '/templates/kc-tabs-identity-provider.html'
}
});
module.directive('kcTabsUserFederation', function () {
return {
scope: true,
restrict: 'E',
replace: true,
templateUrl: resourceUrl + '/templates/kc-tabs-user-federation.html'
}
});
module.controller('RoleSelectorModalCtrl', function($scope, realm, config, configName, RealmRoles, Client, ClientRole, $modalInstance) {
$scope.selectedRealmRole = {
role: undefined
};
$scope.selectedClientRole = {
role: undefined
};
$scope.client = {
selected: undefined
};
$scope.selectRealmRole = function() {
config[configName] = $scope.selectedRealmRole.role.name;
$modalInstance.close();
}
$scope.selectClientRole = function() {
config[configName] = $scope.client.selected.clientId + "." + $scope.selectedClientRole.role.name;
$modalInstance.close();
}
$scope.cancel = function() {
$modalInstance.dismiss();
}
$scope.changeClient = function() {
if ($scope.client.selected) {
ClientRole.query({realm: realm.realm, client: $scope.client.selected.id}, function (data) {
$scope.clientRoles = data;
});
} else {
console.log('selected client was null');
$scope.clientRoles = null;
}
}
RealmRoles.query({realm: realm.realm}, function(data) {
$scope.realmRoles = data;
})
Client.query({realm: realm.realm}, function(data) {
$scope.clients = data;
if (data.length > 0) {
$scope.client.selected = data[0];
$scope.changeClient();
}
})
});
module.controller('ProviderConfigCtrl', function ($modal, $scope) {
$scope.openRoleSelector = function (configName, config) {
$modal.open({
templateUrl: resourceUrl + '/partials/modal/role-selector.html',
controller: 'RoleSelectorModalCtrl',
resolve: {
realm: function () {
return $scope.realm;
},
config: function () {
return config;
},
configName: function () {
return configName;
}
}
})
}
});
module.directive('kcProviderConfig', function ($modal) {
return {
scope: {
config: '=',
properties: '=',
realm: '=',
clients: '=',
configName: '='
},
restrict: 'E',
replace: true,
controller: 'ProviderConfigCtrl',
templateUrl: resourceUrl + '/templates/kc-provider-config.html'
}
});
module.controller('ComponentRoleSelectorModalCtrl', function($scope, realm, config, configName, RealmRoles, Client, ClientRole, $modalInstance) {
$scope.selectedRealmRole = {
role: undefined
};
$scope.selectedClientRole = {
role: undefined
};
$scope.client = {
selected: undefined
};
$scope.selectRealmRole = function() {
config[configName][0] = $scope.selectedRealmRole.role.name;
$modalInstance.close();
}
$scope.selectClientRole = function() {
config[configName][0] = $scope.client.selected.clientId + "." + $scope.selectedClientRole.role.name;
$modalInstance.close();
}
$scope.cancel = function() {
$modalInstance.dismiss();
}
$scope.changeClient = function() {
if ($scope.client.selected) {
ClientRole.query({realm: realm.realm, client: $scope.client.selected.id}, function (data) {
$scope.clientRoles = data;
});
} else {
console.log('selected client was null');
$scope.clientRoles = null;
}
}
RealmRoles.query({realm: realm.realm}, function(data) {
$scope.realmRoles = data;
})
Client.query({realm: realm.realm}, function(data) {
$scope.clients = data;
if (data.length > 0) {
$scope.client.selected = data[0];
$scope.changeClient();
}
})
});
module.controller('ComponentConfigCtrl', function ($modal, $scope) {
$scope.openRoleSelector = function (configName, config) {
$modal.open({
templateUrl: resourceUrl + '/partials/modal/component-role-selector.html',
controller: 'ComponentRoleSelectorModalCtrl',
resolve: {
realm: function () {
return $scope.realm;
},
config: function () {
return config;
},
configName: function () {
return configName;
}
}
})
}
});
module.directive('kcComponentConfig', function ($modal) {
return {
scope: {
config: '=',
properties: '=',
realm: '=',
clients: '=',
configName: '='
},
restrict: 'E',
replace: true,
controller: 'ComponentConfigCtrl',
templateUrl: resourceUrl + '/templates/kc-component-config.html'
}
});
/*
* Used to select the element (invoke $(elem).select()) on specified action list.
* Usages kc-select-action="click mouseover"
* When used in the textarea element, this will select/highlight the textarea content on specified action (i.e. click).
*/
module.directive('kcSelectAction', function ($compile, Notifications) {
return {
restrict: 'A',
compile: function (elem, attrs) {
var events = attrs.kcSelectAction.split(" ");
for(var i=0; i < events.length; i++){
elem.bind(events[i], function(){
elem.select();
});
}
}
}
});
module.filter('remove', function() {
return function(input, remove, attribute) {
if (!input || !remove) {
return input;
}
var out = [];
for ( var i = 0; i < input.length; i++) {
var e = input[i];
if (Array.isArray(remove)) {
for (var j = 0; j < remove.length; j++) {
if (attribute) {
if (remove[j][attribute] == e[attribute]) {
e = null;
break;
}
} else {
if (remove[j] == e) {
e = null;
break;
}
}
}
} else {
if (attribute) {
if (remove[attribute] == e[attribute]) {
e = null;
}
} else {
if (remove == e) {
e = null;
}
}
}
if (e != null) {
out.push(e);
}
}
return out;
};
});
module.filter('capitalize', function() {
return function(input) {
if (!input) {
return;
}
var splittedWords = input.split(/\s+/);
for (var i=0; i<splittedWords.length ; i++) {
splittedWords[i] = splittedWords[i].charAt(0).toUpperCase() + splittedWords[i].slice(1);
};
return splittedWords.join(" ");
};
});
/*
* Guarantees a deterministic property iteration order.
* See: http://www.2ality.com/2015/10/property-traversal-order-es6.html
*/
module.filter('toOrderedMapSortedByKey', function(){
return function(input){
if(!input){
return input;
}
var keys = Object.keys(input);
if(keys.length <= 1){
return input;
}
keys.sort();
var result = {};
for (var i = 0; i < keys.length; i++) {
result[keys[i]] = input[keys[i]];
}
return result;
};
});
module.directive('kcSidebarResize', function ($window) {
return function (scope, element) {
function resize() {
var navBar = angular.element(document.getElementsByClassName('navbar-pf')).height();
var container = angular.element(document.getElementById("view").getElementsByTagName("div")[0]).height();
var height = Math.max(container, window.innerHeight - navBar - 3);
element[0].style['min-height'] = height + 'px';
}
resize();
var w = angular.element($window);
scope.$watch(function () {
return {
'h': window.innerHeight,
'w': window.innerWidth
};
}, function () {
resize();
}, true);
w.bind('resize', function () {
scope.$apply();
});
}
});
module.directive('kcTooltip', function($compile) {
return {
restrict: 'E',
replace: false,
terminal: true,
priority: 1000,
link: function link(scope,element, attrs) {
var angularElement = angular.element(element[0]);
var tooltip = angularElement.text();
angularElement.text('');
element.addClass('hidden');
var label = angular.element(element.parent().children()[0]);
label.append(' <i class="fa fa-question-circle text-muted" tooltip="' + tooltip + '" tooltip-placement="right" tooltip-trigger="mouseover mouseout"></i>');
$compile(label)(scope);
}
};
});
module.directive( 'kcOpen', function ( $location ) {
return function ( scope, element, attrs ) {
var path;
attrs.$observe( 'kcOpen', function (val) {
path = val;
});
element.bind( 'click', function () {
scope.$apply( function () {
$location.path(path);
});
});
};
});
module.directive('kcOnReadFile', function ($parse) {
console.debug('kcOnReadFile');
return {
restrict: 'A',
scope: false,
link: function(scope, element, attrs) {
var fn = $parse(attrs.kcOnReadFile);
element.on('change', function(onChangeEvent) {
var reader = new FileReader();
reader.onload = function(onLoadEvent) {
scope.$apply(function() {
fn(scope, {$fileContent:onLoadEvent.target.result});
});
};
reader.readAsText((onChangeEvent.srcElement || onChangeEvent.target).files[0]);
});
}
};
});
| Java |
<html>
<head>
<title>RSEM-EVAL: A novel reference-free transcriptome assembly evaluation measure</title>
<!--This file is autogenerated. Edit the template instead.-->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$','$']]}
});
</script>
<script src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_SVG" type="text/javascript"></script>
<style type="text/css">
body { max-width: 50em; }
body, td { font-family: sans-serif; }
dt { font-family: monospace; }
h1, h2 { color: #990000; }
</style>
</head>
<body>
<h1>RSEM-EVAL: A novel reference-free transcriptome assembly evaluation measure</h1>
<h2><a name="introduction"></a> Introduction</h2>
<p>RSEM-EVAL is built off of RSEM. It is a reference-free de novo transcriptome assembly evaluator.</p>
<h2><a name="compilation"></a> Compilation & Installation</h2>
<p>To compile RSEM-EVAL, simply run</p>
<pre><code>make
</code></pre>
<p>To install, simply put the rsem directory in your environment's PATH
variable.</p>
<h3>Prerequisites</h3>
<p>C++, Perl and R are required to be installed. </p>
<p>To take advantage of RSEM-EVAL's built-in support for the Bowtie alignment
program, you must have <a href="http://bowtie-bio.sourceforge.net">Bowtie</a> installed.</p>
<h2><a name="usage"></a> Usage</h2>
<h3>I. Build an assembly from the RNA-Seq data using an assembler</h3>
<p>Please note that the RNA-Seq data set used to build the assembly
should be exactly the same as the RNA-Seq data set for evaluating this
assembly. RSEM-EVAL supports both single-end and paired-end reads.</p>
<h3>II. Estimate Transcript Length Distribution Parameters</h3>
<p>RSEM-EVAL provides a script
'rsem-eval-estimate-transcript-length-distribution' to estimate
transcript length distribution from a set of transcript
sequences. Transcripts can be from a closely related species to the
orgaism whose transcriptome is sequenced. Its usage is:</p>
<pre><code>rsem-eval-estimate-transcript-length-distribution input.fasta parameter_file
</code></pre>
<p>__input.fasta__ is a multi-FASTA file contains all transcript sequences used to learn the true transcript length distribution's parameters. <br>
__parameter_file__ records the learned parameters--the estimated mean and standard deviation (separated by a tab character).</p>
<p>We have some learned paramter files stored at folder
'true_transcript_length_distribution'. Please refer to
'true_length_dist_mean_sd.txt' in the folder for more details.</p>
<h3>III. Calculate the RSEM-EVAL score</h3>
<p>To calculate the RSEM-EVAL score, you should use 'rsem-eval-calculate-score'. Run</p>
<pre><code>rsem-eval-calculate-score --help
</code></pre>
<p>to get usage information.</p>
<h3>IV. Outputs related to the evaluation score</h3>
<p>RSEM-EVAL produces the following three score related files:
'sample_name.score', 'sample_name.score.isoforms.results' and
'sample_name.score.genes.results'.</p>
<p>'sample_name.score' stores the evaluation score for the evaluated
assembly. It contains 13 lines and each line contains a name and a
value separated by a tab.</p>
<p>The first 6 lines provide: 'Score', the RSEM-EVAL score;
'BIC_penalty', the BIC penalty term; 'Prior_score_on_contig_lengths (f
function canceled)', the log score of priors of contig lengths, with f
function values excluded (f function is defined in equation (4) at
page 5 of Additional file 1, which is the supplementary methods,
tables and figures of our DETONATE paper);
'Prior_score_on_contig_sequences', the log score of priors of contig
sequence bases; 'Data_likelihood_in_log_space_without_correction', the
RSEM log data likelihood calculated with contig-level read generating
probabilities mentioned in section 4 of Additional file 1;
'Correction_term_(f_function_canceled)', the correction term, with f
function values excluded. Score = BIC_penalty +
Prior_score_on_contig_lengths + Prior_score_on_contig_sequences +
Data_likelihood_in_log_space_without_correction -
Correction_term. Because both 'Prior_score_on_contig_lengths' and
'Correction_term' share the same f function values for each contig,
the f function values can be canceled out. Then
'Prior_score_on_contig_lengths_(f_function_canceled)' is the sum of
log $c_{\lambda}(\ell)$ terms in equation (9) at page 5 of Additional
file 1. 'Correction_term_(f_function_canceled)' is the sum of log $(1
- p_{\lambda_i})$ terms in equation (23) at page 9 of Additional file
1. For the correction term, we use $\lambda_i$ instead of $\lambda'_i$
to make f function canceled out.</p>
<p>NOTE: Higher RSEM-EVAL scores are better than lower scores. This is
true despite the fact that the scores are always negative. For
example, a score of -80000 is better than a score of -200000, since
-80000 > -200000.</p>
<p>The next 7 lines provide statistics that may help users to understand
the RSEM-EVAL score better. They are: 'Number_of_contigs', the number
of contigs contained in the assembly;
'Expected_number_of_aligned_reads_given_the_data', the expected number
of reads assigned to each contig estimated using the contig-level read
generating probabilities mentioned in section 4 of Additional file 1;
'Number_of_contigs_smaller_than_expected_read/fragment_length', the
number of contigs whose length is smaller than the expected
read/fragment length; 'Number_of_contigs_with_no_read_aligned_to', the
number of contigs whose expected number of aligned reads is smaller
than 0.005; 'Maximum_data_likelihood_in_log_space', the maximum data
likelihood in log space calculated from RSEM by treating the assembly
as "true" transcripts; 'Number_of_alignable_reads', the number of
reads that have at least one alignment found by the aligner (Because
'rsem-calculate-expression' tries to use a very loose criteria to find
alignments, reads with only low quality alignments may also be counted
as alignable reads here); 'Number_of_alignments_in_total', the number
of total alignments found by the aligner.</p>
<p>'sample_name.score.isoforms.results' and
'sample_name.score.genes.results' output "corrected" expression levels
based on contig-level read generating probabilities mentioned in
section 4 of Additional file 1. Unlike 'sample_name.isoforms.results'
and 'sample_name.genes.results', which are calculated by treating the
contigs as true transcripts, calculating
'sample_name.score.isoforms.results' and
'sample_name.score.genes.results' involves first estimating expected
read coverage for each contig and then convert the expected read
coverage into contig-level read generating probabilities. This
procedure is aware of that provided sequences are contigs and gives
better expression estimates for very short contigs. In addtion, the
'TPM' field is changed to 'CPM' field, which stands for contig per
million.</p>
<p>For 'sample_name.score.isoforms.results', one additional
column is added. The additional column is named as
'contig_impact_score' and gives the contig impact score for each
contig as described in section 5 of Additional file 1.</p>
<h2><a name="example"></a> Example</h2>
<p>We have a toy example in the 'examples' folder of the detonate distribution. A
single true transcript is stored at file 'toy_ref.fa'. The single-end, 76bp
reads generated from this transcript are stored in file 'toy_SE.fq'. In
addition, we have three different assemblies based on the data:
'toy_assembly_1.fa', 'toy_assembly_2.fa' and 'toy_assembly_3.fa'. We also know
the true transcript is from mouse and thus use 'mouse.txt' under
'true_transcript_length_distribution' as our transcript length parameter file.</p>
<p>We run (assuming that we are in the rsem-eval directory)</p>
<pre><code>./rsem-eval-calculate-score -p 8 \
--transcript-length-parameters true_transcript_length_distribution/mouse.txt \
../examples/toy_SE.fq \
../examples/toy_assembly_1.fa \
toy_assembly_1
76
</code></pre>
<p>to obtain the RSEM-EVAL score. </p>
<p>The RSEM-EVAL score can be found in 'toy_assembly_1.score'. The
contig impact scores can be found in
'toy_assembly_1.score.isoforms.results'.</p>
<h2><a name="authors"></a> Authors</h2>
<p>RSEM-EVAL is developed by Bo Li, with substaintial technical input from Colin Dewey and Nate Fillmore.</p>
<h2><a name="acknowledgements"></a> Acknowledgements</h2>
<p>Please refer to the acknowledgements section in 'README_RSEM.md'.</p>
<h2><a name="license"></a> License</h2>
<p>RSEM-EVAL is licensed under the <a href="http://www.gnu.org/licenses/gpl-3.0.html">GNU General Public License
v3</a>.</p>
</body>
</html> | Java |
/*
* AnyOf_test.cpp
*
* Created on: Jan 30, 2016
* Author: ljeff
*/
#include "AnyOf.h"
namespace algorithm {
} /* namespace algorithm */
| Java |
/*
* 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.
*
* See also http://www.apache.org/licenses/LICENSE-2.0.html for an
* explanation of the license and how it is applied.
*/
package org.mifos.customers.persistence;
import static org.mifos.application.meeting.util.helpers.MeetingType.CUSTOMER_MEETING;
import static org.mifos.application.meeting.util.helpers.RecurrenceType.WEEKLY;
import static org.mifos.framework.util.helpers.TestObjectFactory.EVERY_WEEK;
import java.sql.Date;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import junit.framework.Assert;
import org.mifos.accounts.business.AccountActionDateEntity;
import org.mifos.accounts.business.AccountBO;
import org.mifos.accounts.business.AccountFeesEntity;
import org.mifos.accounts.business.AccountStateEntity;
import org.mifos.accounts.business.AccountTestUtils;
import org.mifos.accounts.exceptions.AccountException;
import org.mifos.accounts.fees.business.AmountFeeBO;
import org.mifos.accounts.fees.business.FeeBO;
import org.mifos.accounts.fees.util.helpers.FeeCategory;
import org.mifos.accounts.loan.business.LoanBO;
import org.mifos.accounts.productdefinition.business.LoanOfferingBO;
import org.mifos.accounts.productdefinition.business.SavingsOfferingBO;
import org.mifos.accounts.productdefinition.util.helpers.RecommendedAmountUnit;
import org.mifos.accounts.savings.business.SavingsBO;
import org.mifos.accounts.util.helpers.AccountState;
import org.mifos.accounts.util.helpers.AccountStateFlag;
import org.mifos.accounts.util.helpers.AccountTypes;
import org.mifos.application.master.business.MifosCurrency;
import org.mifos.application.meeting.business.MeetingBO;
import org.mifos.application.meeting.exceptions.MeetingException;
import org.mifos.application.meeting.persistence.MeetingPersistence;
import org.mifos.application.meeting.util.helpers.RecurrenceType;
import org.mifos.application.servicefacade.CollectionSheetCustomerDto;
import org.mifos.application.util.helpers.YesNoFlag;
import org.mifos.config.AccountingRulesConstants;
import org.mifos.config.ConfigurationManager;
import org.mifos.core.CurrencyMismatchException;
import org.mifos.customers.business.CustomerAccountBO;
import org.mifos.customers.business.CustomerBO;
import org.mifos.customers.business.CustomerBOTestUtils;
import org.mifos.customers.business.CustomerNoteEntity;
import org.mifos.customers.business.CustomerPerformanceHistoryView;
import org.mifos.customers.business.CustomerSearch;
import org.mifos.customers.business.CustomerStatusEntity;
import org.mifos.customers.business.CustomerView;
import org.mifos.customers.center.business.CenterBO;
import org.mifos.customers.checklist.business.CheckListBO;
import org.mifos.customers.checklist.business.CustomerCheckListBO;
import org.mifos.customers.checklist.util.helpers.CheckListConstants;
import org.mifos.customers.client.business.AttendanceType;
import org.mifos.customers.client.business.ClientBO;
import org.mifos.customers.client.util.helpers.ClientConstants;
import org.mifos.customers.group.BasicGroupInfo;
import org.mifos.customers.group.business.GroupBO;
import org.mifos.customers.personnel.business.PersonnelBO;
import org.mifos.customers.personnel.util.helpers.PersonnelConstants;
import org.mifos.customers.util.helpers.ChildrenStateType;
import org.mifos.customers.util.helpers.CustomerLevel;
import org.mifos.customers.util.helpers.CustomerStatus;
import org.mifos.customers.util.helpers.CustomerStatusFlag;
import org.mifos.framework.MifosIntegrationTestCase;
import org.mifos.framework.TestUtils;
import org.mifos.framework.exceptions.ApplicationException;
import org.mifos.framework.exceptions.PersistenceException;
import org.mifos.framework.exceptions.SystemException;
import org.mifos.framework.hibernate.helper.QueryResult;
import org.mifos.framework.hibernate.helper.StaticHibernateUtil;
import org.mifos.framework.util.helpers.Money;
import org.mifos.framework.util.helpers.TestObjectFactory;
import org.mifos.security.util.UserContext;
public class CustomerPersistenceIntegrationTest extends MifosIntegrationTestCase {
public CustomerPersistenceIntegrationTest() throws Exception {
super();
}
private MeetingBO meeting;
private CustomerBO center;
private ClientBO client;
private CustomerBO group2;
private CustomerBO group;
private AccountBO account;
private LoanBO groupAccount;
private LoanBO clientAccount;
private SavingsBO centerSavingsAccount;
private SavingsBO groupSavingsAccount;
private SavingsBO clientSavingsAccount;
private SavingsOfferingBO savingsOffering;
private final CustomerPersistence customerPersistence = new CustomerPersistence();
@Override
protected void setUp() throws Exception {
super.setUp();
}
@Override
public void tearDown() throws Exception {
try {
TestObjectFactory.cleanUp(centerSavingsAccount);
TestObjectFactory.cleanUp(groupSavingsAccount);
TestObjectFactory.cleanUp(clientSavingsAccount);
TestObjectFactory.cleanUp(groupAccount);
TestObjectFactory.cleanUp(clientAccount);
TestObjectFactory.cleanUp(account);
TestObjectFactory.cleanUp(client);
TestObjectFactory.cleanUp(group2);
TestObjectFactory.cleanUp(group);
TestObjectFactory.cleanUp(center);
StaticHibernateUtil.closeSession();
} catch (Exception e) {
// Throwing from tearDown will tend to mask the real failure.
e.printStackTrace();
}
super.tearDown();
}
public void testGetTotalAmountForAllClientsOfGroupForSingleCurrency() throws Exception {
MeetingBO meeting = TestObjectFactory.createMeeting(TestObjectFactory.getTypicalMeeting());
center = createCenter("new_center");
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group", CustomerStatus.GROUP_ACTIVE, center);
client = TestObjectFactory.createClient("client1", CustomerStatus.CLIENT_ACTIVE, group);
AccountBO clientAccount1 = getLoanAccount(client, meeting, "fdbdhgsgh", "54hg", TestUtils.RUPEE);
AccountBO clientAccount2 = getLoanAccount(client, meeting, "fasdfdsfasdf", "1qwe", TestUtils.RUPEE);
Money amount = customerPersistence.getTotalAmountForAllClientsOfGroup(group.getOffice().getOfficeId(),
AccountState.LOAN_ACTIVE_IN_GOOD_STANDING, group.getSearchId() + ".%");
Assert.assertEquals(new Money(TestUtils.RUPEE, "600"), amount);
TestObjectFactory.cleanUp(clientAccount1);
TestObjectFactory.cleanUp(clientAccount2);
}
/*
* When trying to sum amounts across loans with different currencies, we should get an exception
*/
public void testGetTotalAmountForAllClientsOfGroupForMultipleCurrencies() throws Exception {
ConfigurationManager configMgr = ConfigurationManager.getInstance();
configMgr.setProperty(AccountingRulesConstants.ADDITIONAL_CURRENCY_CODES, TestUtils.EURO.getCurrencyCode());
AccountBO clientAccount1;
AccountBO clientAccount2;
try {
MeetingBO meeting = TestObjectFactory.createMeeting(TestObjectFactory.getTypicalMeeting());
center = createCenter("new_center");
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group", CustomerStatus.GROUP_ACTIVE, center);
client = TestObjectFactory.createClient("client1", CustomerStatus.CLIENT_ACTIVE, group);
clientAccount1 = getLoanAccount(client, meeting, "fdbdhgsgh", "54hg", TestUtils.RUPEE);
clientAccount2 = getLoanAccount(client, meeting, "fasdfdsfasdf", "1qwe", TestUtils.EURO);
try {
customerPersistence.getTotalAmountForAllClientsOfGroup(group.getOffice().getOfficeId(),
AccountState.LOAN_ACTIVE_IN_GOOD_STANDING, group.getSearchId() + ".%");
fail("didn't get the expected CurrencyMismatchException");
} catch (CurrencyMismatchException e) {
// if we got here then we got the exception we were expecting
assertNotNull(e);
} catch (Exception e) {
fail("didn't get the expected CurrencyMismatchException");
}
} finally {
configMgr.clearProperty(AccountingRulesConstants.ADDITIONAL_CURRENCY_CODES);
}
TestObjectFactory.cleanUp(clientAccount1);
TestObjectFactory.cleanUp(clientAccount2);
}
/*
* When trying to sum amounts across loans with different currencies, we should get an exception
*/
public void testGetTotalAmountForGroupForMultipleCurrencies() throws Exception {
ConfigurationManager configMgr = ConfigurationManager.getInstance();
configMgr.setProperty(AccountingRulesConstants.ADDITIONAL_CURRENCY_CODES, TestUtils.EURO.getCurrencyCode());
GroupBO group1;
AccountBO account1;
AccountBO account2;
try {
CustomerPersistence customerPersistence = new CustomerPersistence();
meeting = TestObjectFactory.createMeeting(TestObjectFactory.getNewMeetingForToday(WEEKLY, EVERY_WEEK,
CUSTOMER_MEETING));
center = TestObjectFactory.createWeeklyFeeCenter("Center", meeting);
group1 = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group1", CustomerStatus.GROUP_ACTIVE, center);
account1 = getLoanAccount(group1, meeting, "adsfdsfsd", "3saf", TestUtils.RUPEE);
account2 = getLoanAccount(group1, meeting, "adspp", "kkaf", TestUtils.EURO);
try {
customerPersistence.getTotalAmountForGroup(group1.getCustomerId(),
AccountState.LOAN_ACTIVE_IN_GOOD_STANDING);
fail("didn't get the expected CurrencyMismatchException");
} catch (CurrencyMismatchException e) {
// if we got here then we got the exception we were expecting
assertNotNull(e);
} catch (Exception e) {
fail("didn't get the expected CurrencyMismatchException");
}
} finally {
configMgr.clearProperty(AccountingRulesConstants.ADDITIONAL_CURRENCY_CODES);
}
TestObjectFactory.cleanUp(account1);
TestObjectFactory.cleanUp(account2);
TestObjectFactory.cleanUp(group1);
}
public void testGetTotalAmountForGroup() throws Exception {
CustomerPersistence customerPersistence = new CustomerPersistence();
meeting = TestObjectFactory.createMeeting(TestObjectFactory.getNewMeetingForToday(WEEKLY, EVERY_WEEK,
CUSTOMER_MEETING));
center = TestObjectFactory.createWeeklyFeeCenter("Center", meeting);
GroupBO group1 = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group1", CustomerStatus.GROUP_ACTIVE, center);
AccountBO account1 = getLoanAccount(group1, meeting, "adsfdsfsd", "3saf");
AccountBO account2 = getLoanAccount(group1, meeting, "adspp", "kkaf");
Money amount = customerPersistence.getTotalAmountForGroup(group1.getCustomerId(),
AccountState.LOAN_ACTIVE_IN_GOOD_STANDING);
Assert.assertEquals(new Money(getCurrency(), "600"), amount);
AccountBO account3 = getLoanAccountInActiveBadStanding(group1, meeting, "adsfdsfsd1", "4sa");
AccountBO account4 = getLoanAccountInActiveBadStanding(group1, meeting, "adspp2", "kaf5");
Money amount2 = customerPersistence.getTotalAmountForGroup(group1.getCustomerId(),
AccountState.LOAN_ACTIVE_IN_BAD_STANDING);
Assert.assertEquals(new Money(getCurrency(), "600"), amount2);
TestObjectFactory.cleanUp(account1);
TestObjectFactory.cleanUp(account2);
TestObjectFactory.cleanUp(account3);
TestObjectFactory.cleanUp(account4);
TestObjectFactory.cleanUp(group1);
}
public void testGetTotalAmountForAllClientsOfGroup() throws Exception {
MeetingBO meeting = TestObjectFactory.createMeeting(TestObjectFactory.getTypicalMeeting());
center = createCenter("new_center");
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group", CustomerStatus.GROUP_ACTIVE, center);
client = TestObjectFactory.createClient("client1", CustomerStatus.CLIENT_ACTIVE, group);
AccountBO clientAccount1 = getLoanAccount(client, meeting, "fdbdhgsgh", "54hg");
AccountBO clientAccount2 = getLoanAccount(client, meeting, "fasdfdsfasdf", "1qwe");
Money amount = customerPersistence.getTotalAmountForAllClientsOfGroup(group.getOffice().getOfficeId(),
AccountState.LOAN_ACTIVE_IN_GOOD_STANDING, group.getSearchId() + ".%");
Assert.assertEquals(new Money(getCurrency(), "600"), amount);
clientAccount1.changeStatus(AccountState.LOAN_ACTIVE_IN_BAD_STANDING.getValue(), null, "none");
clientAccount2.changeStatus(AccountState.LOAN_ACTIVE_IN_BAD_STANDING.getValue(), null, "none");
TestObjectFactory.updateObject(clientAccount1);
TestObjectFactory.updateObject(clientAccount2);
StaticHibernateUtil.commitTransaction();
Money amount2 = customerPersistence.getTotalAmountForAllClientsOfGroup(group.getOffice().getOfficeId(),
AccountState.LOAN_ACTIVE_IN_BAD_STANDING, group.getSearchId() + ".%");
Assert.assertEquals(new Money(getCurrency(), "600"), amount2);
TestObjectFactory.cleanUp(clientAccount1);
TestObjectFactory.cleanUp(clientAccount2);
}
public void testGetAllBasicGroupInfo() throws Exception {
CustomerPersistence customerPersistence = new CustomerPersistence();
center = createCenter("new_center");
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group", CustomerStatus.GROUP_ACTIVE, center);
GroupBO newGroup = TestObjectFactory.createWeeklyFeeGroupUnderCenter("newGroup", CustomerStatus.GROUP_HOLD, center);
GroupBO newGroup2 = TestObjectFactory.createWeeklyFeeGroupUnderCenter("newGroup2", CustomerStatus.GROUP_CANCELLED,
center);
GroupBO newGroup3 = TestObjectFactory.createWeeklyFeeGroupUnderCenter("newGroup3", CustomerStatus.GROUP_CLOSED, center);
GroupBO newGroup4 = TestObjectFactory.createWeeklyFeeGroupUnderCenter("newGroup4", CustomerStatus.GROUP_PARTIAL, center);
GroupBO newGroup5 = TestObjectFactory.createWeeklyFeeGroupUnderCenter("newGroup5", CustomerStatus.GROUP_PENDING, center);
List<BasicGroupInfo> groupInfos = customerPersistence.getAllBasicGroupInfo();
Assert.assertEquals(2, groupInfos.size());
Assert.assertEquals(group.getDisplayName(), groupInfos.get(0).getGroupName());
Assert.assertEquals(group.getSearchId(), groupInfos.get(0).getSearchId());
Assert.assertEquals(group.getOffice().getOfficeId(), groupInfos.get(0).getBranchId());
Assert.assertEquals(group.getCustomerId(), groupInfos.get(0).getGroupId());
Assert.assertEquals(newGroup.getDisplayName(), groupInfos.get(1).getGroupName());
Assert.assertEquals(newGroup.getSearchId(), groupInfos.get(1).getSearchId());
Assert.assertEquals(newGroup.getOffice().getOfficeId(), groupInfos.get(1).getBranchId());
Assert.assertEquals(newGroup.getCustomerId(), groupInfos.get(1).getGroupId());
TestObjectFactory.cleanUp(newGroup);
TestObjectFactory.cleanUp(newGroup2);
TestObjectFactory.cleanUp(newGroup3);
TestObjectFactory.cleanUp(newGroup4);
TestObjectFactory.cleanUp(newGroup5);
}
public void testCustomersUnderLO() throws Exception {
CustomerPersistence customerPersistence = new CustomerPersistence();
meeting = TestObjectFactory.createMeeting(TestObjectFactory.getTypicalMeeting());
center = TestObjectFactory.createWeeklyFeeCenter("Center_Active", meeting);
List<CustomerView> customers = customerPersistence.getActiveParentList(Short.valueOf("1"), CustomerLevel.CENTER
.getValue(), Short.valueOf("3"));
Assert.assertEquals(1, customers.size());
}
public void testActiveCustomersUnderParent() throws Exception {
CustomerPersistence customerPersistence = new CustomerPersistence();
createCustomers(CustomerStatus.GROUP_ACTIVE, CustomerStatus.CLIENT_ACTIVE);
List<CustomerView> customers = customerPersistence.getChildrenForParent(center.getCustomerId(), center
.getSearchId(), center.getOffice().getOfficeId());
Assert.assertEquals(2, customers.size());
}
public void testOnHoldCustomersUnderParent() throws Exception {
CustomerPersistence customerPersistence = new CustomerPersistence();
createCustomers(CustomerStatus.GROUP_HOLD, CustomerStatus.CLIENT_HOLD);
List<CustomerView> customers = customerPersistence.getChildrenForParent(center.getCustomerId(), center
.getSearchId(), center.getOffice().getOfficeId());
Assert.assertEquals(2, customers.size());
}
public void testGetLastMeetingDateForCustomer() throws Exception {
CustomerPersistence customerPersistence = new CustomerPersistence();
meeting = TestObjectFactory.createMeeting(TestObjectFactory.getNewMeetingForToday(WEEKLY, EVERY_WEEK,
CUSTOMER_MEETING));
center = TestObjectFactory.createWeeklyFeeCenter("Center", meeting);
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group", CustomerStatus.GROUP_ACTIVE, center);
account = getLoanAccount(group, meeting, "adsfdsfsd", "3saf");
// Date actionDate = new Date(2006,03,13);
Date meetingDate = customerPersistence.getLastMeetingDateForCustomer(center.getCustomerId());
Assert.assertEquals(new Date(getMeetingDates(meeting).getTime()).toString(), meetingDate.toString());
}
public void testGetChildernOtherThanClosed() throws Exception {
CustomerPersistence customerPersistence = new CustomerPersistence();
center = createCenter();
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group1", CustomerStatus.GROUP_ACTIVE, center);
client = TestObjectFactory.createClient("client1", CustomerStatus.CLIENT_ACTIVE, group);
ClientBO client2 = TestObjectFactory.createClient("client2", CustomerStatus.CLIENT_CLOSED, group);
ClientBO client3 = TestObjectFactory.createClient("client3", CustomerStatus.CLIENT_CANCELLED, group);
ClientBO client4 = TestObjectFactory.createClient("client4", CustomerStatus.CLIENT_PENDING, group);
List<CustomerBO> customerList = customerPersistence.getChildren(center.getSearchId(), center.getOffice()
.getOfficeId(), CustomerLevel.CLIENT, ChildrenStateType.OTHER_THAN_CLOSED);
Assert.assertEquals(new Integer("3").intValue(), customerList.size());
for (CustomerBO customer : customerList) {
if (customer.getCustomerId().intValue() == client3.getCustomerId().intValue()) {
Assert.assertTrue(true);
}
}
TestObjectFactory.cleanUp(client2);
TestObjectFactory.cleanUp(client3);
TestObjectFactory.cleanUp(client4);
}
public void testGetChildernActiveAndHold() throws Exception {
CustomerPersistence customerPersistence = new CustomerPersistence();
center = createCenter();
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group1", CustomerStatus.GROUP_ACTIVE, center);
client = TestObjectFactory.createClient("client1", CustomerStatus.CLIENT_ACTIVE, group);
ClientBO client2 = TestObjectFactory.createClient("client2", CustomerStatus.CLIENT_PARTIAL, group);
ClientBO client3 = TestObjectFactory.createClient("client3", CustomerStatus.CLIENT_PENDING, group);
ClientBO client4 = TestObjectFactory.createClient("client4", CustomerStatus.CLIENT_HOLD, group);
List<CustomerBO> customerList = customerPersistence.getChildren(center.getSearchId(), center.getOffice()
.getOfficeId(), CustomerLevel.CLIENT, ChildrenStateType.ACTIVE_AND_ONHOLD);
Assert.assertEquals(new Integer("2").intValue(), customerList.size());
for (CustomerBO customer : customerList) {
if (customer.getCustomerId().intValue() == client.getCustomerId().intValue()) {
Assert.assertTrue(true);
}
if (customer.getCustomerId().intValue() == client4.getCustomerId().intValue()) {
Assert.assertTrue(true);
}
}
TestObjectFactory.cleanUp(client2);
TestObjectFactory.cleanUp(client3);
TestObjectFactory.cleanUp(client4);
}
public void testGetChildernOtherThanClosedAndCancelled() throws Exception {
CustomerPersistence customerPersistence = new CustomerPersistence();
center = createCenter();
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group1", CustomerStatus.GROUP_ACTIVE, center);
client = TestObjectFactory.createClient("client1", CustomerStatus.CLIENT_ACTIVE, group);
ClientBO client2 = TestObjectFactory.createClient("client2", CustomerStatus.CLIENT_CLOSED, group);
ClientBO client3 = TestObjectFactory.createClient("client3", CustomerStatus.CLIENT_CANCELLED, group);
ClientBO client4 = TestObjectFactory.createClient("client4", CustomerStatus.CLIENT_PENDING, group);
List<CustomerBO> customerList = customerPersistence.getChildren(center.getSearchId(), center.getOffice()
.getOfficeId(), CustomerLevel.CLIENT, ChildrenStateType.OTHER_THAN_CANCELLED_AND_CLOSED);
Assert.assertEquals(new Integer("2").intValue(), customerList.size());
for (CustomerBO customer : customerList) {
if (customer.getCustomerId().equals(client4.getCustomerId())) {
Assert.assertTrue(true);
}
}
TestObjectFactory.cleanUp(client2);
TestObjectFactory.cleanUp(client3);
TestObjectFactory.cleanUp(client4);
}
public void testGetAllChildern() throws Exception {
CustomerPersistence customerPersistence = new CustomerPersistence();
center = createCenter();
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group1", CustomerStatus.GROUP_ACTIVE, center);
client = TestObjectFactory.createClient("client1", CustomerStatus.CLIENT_ACTIVE, group);
ClientBO client2 = TestObjectFactory.createClient("client2", CustomerStatus.CLIENT_CLOSED, group);
ClientBO client3 = TestObjectFactory.createClient("client3", CustomerStatus.CLIENT_CANCELLED, group);
ClientBO client4 = TestObjectFactory.createClient("client4", CustomerStatus.CLIENT_PENDING, group);
List<CustomerBO> customerList = customerPersistence.getChildren(center.getSearchId(), center.getOffice()
.getOfficeId(), CustomerLevel.CLIENT, ChildrenStateType.ALL);
Assert.assertEquals(new Integer("4").intValue(), customerList.size());
for (CustomerBO customer : customerList) {
if (customer.getCustomerId().equals(client2.getCustomerId())) {
Assert.assertTrue(true);
}
}
TestObjectFactory.cleanUp(client2);
TestObjectFactory.cleanUp(client3);
TestObjectFactory.cleanUp(client4);
}
public void testRetrieveSavingsAccountForCustomer() throws Exception {
java.util.Date currentDate = new java.util.Date();
CustomerPersistence customerPersistence = new CustomerPersistence();
center = createCenter();
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group1", CustomerStatus.GROUP_ACTIVE, center);
savingsOffering = TestObjectFactory.createSavingsProduct("SavingPrd1", "S", currentDate, RecommendedAmountUnit.COMPLETE_GROUP);
UserContext user = new UserContext();
user.setId(PersonnelConstants.SYSTEM_USER);
account = TestObjectFactory.createSavingsAccount("000100000000020", group, AccountState.SAVINGS_ACTIVE,
currentDate, savingsOffering, user);
StaticHibernateUtil.closeSession();
List<SavingsBO> savingsList = customerPersistence.retrieveSavingsAccountForCustomer(group.getCustomerId());
Assert.assertEquals(1, savingsList.size());
account = savingsList.get(0);
group = account.getCustomer();
center = group.getParentCustomer();
}
public void testNumberOfMeetingsAttended() throws Exception {
center = createCenter();
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group", CustomerStatus.GROUP_ACTIVE, center);
client = TestObjectFactory.createClient("Client", CustomerStatus.CLIENT_ACTIVE, group);
client.handleAttendance(new Date(System.currentTimeMillis()), AttendanceType.ABSENT);
client.handleAttendance(new Date(System.currentTimeMillis()), AttendanceType.PRESENT);
Calendar currentDate = new GregorianCalendar();
currentDate.roll(Calendar.DATE, 1);
client.handleAttendance(new Date(currentDate.getTimeInMillis()), AttendanceType.LATE);
StaticHibernateUtil.commitTransaction();
CustomerPerformanceHistoryView customerPerformanceHistoryView = customerPersistence.numberOfMeetings(true,
client.getCustomerId());
Assert.assertEquals(2, customerPerformanceHistoryView.getMeetingsAttended().intValue());
StaticHibernateUtil.closeSession();
}
public void testNumberOfMeetingsMissed() throws Exception {
center = createCenter();
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group", CustomerStatus.GROUP_ACTIVE, center);
client = TestObjectFactory.createClient("Client", CustomerStatus.CLIENT_ACTIVE, group);
client.handleAttendance(new Date(System.currentTimeMillis()), AttendanceType.PRESENT);
client.handleAttendance(new Date(System.currentTimeMillis()), AttendanceType.ABSENT);
Calendar currentDate = new GregorianCalendar();
currentDate.roll(Calendar.DATE, 1);
client.handleAttendance(new Date(currentDate.getTimeInMillis()), AttendanceType.APPROVED_LEAVE);
StaticHibernateUtil.commitTransaction();
CustomerPerformanceHistoryView customerPerformanceHistoryView = customerPersistence.numberOfMeetings(false,
client.getCustomerId());
Assert.assertEquals(2, customerPerformanceHistoryView.getMeetingsMissed().intValue());
StaticHibernateUtil.closeSession();
}
public void testLastLoanAmount() throws PersistenceException, AccountException {
Date startDate = new Date(System.currentTimeMillis());
center = createCenter();
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group", CustomerStatus.GROUP_ACTIVE, center);
client = TestObjectFactory.createClient("Client", CustomerStatus.CLIENT_ACTIVE, group);
LoanOfferingBO loanOffering = TestObjectFactory.createLoanOffering(startDate, center.getCustomerMeeting()
.getMeeting());
LoanBO loanBO = TestObjectFactory.createLoanAccount("42423142341", client,
AccountState.LOAN_ACTIVE_IN_GOOD_STANDING, startDate, loanOffering);
StaticHibernateUtil.commitTransaction();
StaticHibernateUtil.closeSession();
account = (AccountBO) StaticHibernateUtil.getSessionTL().get(LoanBO.class, loanBO.getAccountId());
AccountStateEntity accountStateEntity = new AccountStateEntity(AccountState.LOAN_CLOSED_OBLIGATIONS_MET);
account.setUserContext(TestObjectFactory.getContext());
account.changeStatus(accountStateEntity.getId(), null, "");
TestObjectFactory.updateObject(account);
CustomerPersistence customerPersistence = new CustomerPersistence();
CustomerPerformanceHistoryView customerPerformanceHistoryView = customerPersistence.getLastLoanAmount(client
.getCustomerId());
Assert.assertEquals("300.0", customerPerformanceHistoryView.getLastLoanAmount());
}
public void testFindBySystemId() throws Exception {
center = createCenter();
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group_Active_test", CustomerStatus.GROUP_ACTIVE, center);
GroupBO groupBO = (GroupBO) customerPersistence.findBySystemId(group.getGlobalCustNum());
Assert.assertEquals(groupBO.getDisplayName(), group.getDisplayName());
}
public void testGetBySystemId() throws Exception {
center = createCenter();
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group_Active_test", CustomerStatus.GROUP_ACTIVE, center);
GroupBO groupBO = (GroupBO) customerPersistence.findBySystemId(group.getGlobalCustNum(), group
.getCustomerLevel().getId());
Assert.assertEquals(groupBO.getDisplayName(), group.getDisplayName());
}
public void testOptionalCustomerStates() throws Exception {
Assert.assertEquals(Integer.valueOf(0).intValue(), customerPersistence.getCustomerStates(Short.valueOf("0"))
.size());
}
public void testCustomerStatesInUse() throws Exception {
Assert.assertEquals(Integer.valueOf(14).intValue(), customerPersistence.getCustomerStates(Short.valueOf("1"))
.size());
}
public void testGetCustomersWithUpdatedMeetings() throws Exception {
center = createCenter();
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group1", CustomerStatus.GROUP_ACTIVE, center);
CustomerBOTestUtils.setUpdatedFlag(group.getCustomerMeeting(), YesNoFlag.YES.getValue());
TestObjectFactory.updateObject(group);
List<Integer> customerIds = customerPersistence.getCustomersWithUpdatedMeetings();
Assert.assertEquals(1, customerIds.size());
}
public void testRetrieveAllLoanAccountUnderCustomer() throws PersistenceException {
MeetingBO meeting = TestObjectFactory.createMeeting(TestObjectFactory.getTypicalMeeting());
center = createCenter("center");
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group", CustomerStatus.GROUP_ACTIVE, center);
CenterBO center1 = createCenter("center1");
GroupBO group1 = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group1", CustomerStatus.GROUP_ACTIVE, center1);
client = TestObjectFactory.createClient("client1", CustomerStatus.CLIENT_ACTIVE, group);
ClientBO client2 = TestObjectFactory.createClient("client2", CustomerStatus.CLIENT_ACTIVE, group);
ClientBO client3 = TestObjectFactory.createClient("client3", CustomerStatus.CLIENT_ACTIVE, group1);
account = getLoanAccount(group, meeting, "cdfggdfs", "1qdd");
AccountBO account1 = getLoanAccount(client, meeting, "fdbdhgsgh", "54hg");
AccountBO account2 = getLoanAccount(client2, meeting, "fasdfdsfasdf", "1qwe");
AccountBO account3 = getLoanAccount(client3, meeting, "fdsgdfgfd", "543g");
AccountBO account4 = getLoanAccount(group1, meeting, "fasdf23", "3fds");
CustomerBOTestUtils.setCustomerStatus(client2, new CustomerStatusEntity(CustomerStatus.CLIENT_CLOSED));
TestObjectFactory.updateObject(client2);
client2 = TestObjectFactory.getClient(client2.getCustomerId());
CustomerBOTestUtils.setCustomerStatus(client3, new CustomerStatusEntity(CustomerStatus.CLIENT_CANCELLED));
TestObjectFactory.updateObject(client3);
client3 = TestObjectFactory.getClient(client3.getCustomerId());
List<AccountBO> loansForCenter = customerPersistence.retrieveAccountsUnderCustomer(center.getSearchId(), Short
.valueOf("3"), Short.valueOf("1"));
Assert.assertEquals(3, loansForCenter.size());
List<AccountBO> loansForGroup = customerPersistence.retrieveAccountsUnderCustomer(group.getSearchId(), Short
.valueOf("3"), Short.valueOf("1"));
Assert.assertEquals(3, loansForGroup.size());
List<AccountBO> loansForClient = customerPersistence.retrieveAccountsUnderCustomer(client.getSearchId(), Short
.valueOf("3"), Short.valueOf("1"));
Assert.assertEquals(1, loansForClient.size());
TestObjectFactory.cleanUp(account4);
TestObjectFactory.cleanUp(account3);
TestObjectFactory.cleanUp(account2);
TestObjectFactory.cleanUp(account1);
TestObjectFactory.cleanUp(client3);
TestObjectFactory.cleanUp(client2);
TestObjectFactory.cleanUp(group1);
TestObjectFactory.cleanUp(center1);
}
public void testRetrieveAllSavingsAccountUnderCustomer() throws Exception {
center = createCenter("new_center");
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group", CustomerStatus.GROUP_ACTIVE, center);
CenterBO center1 = createCenter("new_center1");
GroupBO group1 = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group1", CustomerStatus.GROUP_ACTIVE, center1);
client = TestObjectFactory.createClient("client1", CustomerStatus.CLIENT_ACTIVE, group);
ClientBO client2 = TestObjectFactory.createClient("client2", CustomerStatus.CLIENT_CLOSED, group);
ClientBO client3 = TestObjectFactory.createClient("client3", CustomerStatus.CLIENT_CANCELLED, group1);
account = getSavingsAccount(center, "Savings Prd1", "Abc1");
AccountBO account1 = getSavingsAccount(client, "Savings Prd2", "Abc2");
AccountBO account2 = getSavingsAccount(client2, "Savings Prd3", "Abc3");
AccountBO account3 = getSavingsAccount(client3, "Savings Prd4", "Abc4");
AccountBO account4 = getSavingsAccount(group1, "Savings Prd5", "Abc5");
AccountBO account5 = getSavingsAccount(group, "Savings Prd6", "Abc6");
AccountBO account6 = getSavingsAccount(center1, "Savings Prd7", "Abc7");
List<AccountBO> savingsForCenter = customerPersistence.retrieveAccountsUnderCustomer(center.getSearchId(),
Short.valueOf("3"), Short.valueOf("2"));
Assert.assertEquals(4, savingsForCenter.size());
List<AccountBO> savingsForGroup = customerPersistence.retrieveAccountsUnderCustomer(group.getSearchId(), Short
.valueOf("3"), Short.valueOf("2"));
Assert.assertEquals(3, savingsForGroup.size());
List<AccountBO> savingsForClient = customerPersistence.retrieveAccountsUnderCustomer(client.getSearchId(),
Short.valueOf("3"), Short.valueOf("2"));
Assert.assertEquals(1, savingsForClient.size());
TestObjectFactory.cleanUp(account3);
TestObjectFactory.cleanUp(account2);
TestObjectFactory.cleanUp(account1);
TestObjectFactory.cleanUp(client3);
TestObjectFactory.cleanUp(client2);
TestObjectFactory.cleanUp(account4);
TestObjectFactory.cleanUp(account5);
TestObjectFactory.cleanUp(group1);
TestObjectFactory.cleanUp(account6);
TestObjectFactory.cleanUp(center1);
}
public void testGetAllChildrenForParent() throws NumberFormatException, PersistenceException {
center = createCenter("Center");
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group", CustomerStatus.GROUP_ACTIVE, center);
CenterBO center1 = createCenter("center11");
GroupBO group1 = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group1", CustomerStatus.GROUP_ACTIVE, center1);
client = TestObjectFactory.createClient("client1", CustomerStatus.CLIENT_ACTIVE, group);
ClientBO client2 = TestObjectFactory.createClient("client2", CustomerStatus.CLIENT_CLOSED, group);
ClientBO client3 = TestObjectFactory.createClient("client3", CustomerStatus.CLIENT_CANCELLED, group1);
List<CustomerBO> customerList1 = customerPersistence.getAllChildrenForParent(center.getSearchId(), Short
.valueOf("3"), CustomerLevel.CENTER.getValue());
Assert.assertEquals(2, customerList1.size());
List<CustomerBO> customerList2 = customerPersistence.getAllChildrenForParent(center.getSearchId(), Short
.valueOf("3"), CustomerLevel.GROUP.getValue());
Assert.assertEquals(1, customerList2.size());
TestObjectFactory.cleanUp(client3);
TestObjectFactory.cleanUp(client2);
TestObjectFactory.cleanUp(group1);
TestObjectFactory.cleanUp(center1);
}
public void testGetChildrenForParent() throws NumberFormatException, SystemException, ApplicationException {
center = createCenter("center");
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group", CustomerStatus.GROUP_ACTIVE, center);
CenterBO center1 = createCenter("center1");
GroupBO group1 = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group1", CustomerStatus.GROUP_ACTIVE, center1);
client = TestObjectFactory.createClient("client1", CustomerStatus.CLIENT_ACTIVE, group);
ClientBO client2 = TestObjectFactory.createClient("client2", CustomerStatus.CLIENT_CLOSED, group);
ClientBO client3 = TestObjectFactory.createClient("client3", CustomerStatus.CLIENT_CANCELLED, group1);
List<Integer> customerIds = customerPersistence.getChildrenForParent(center.getSearchId(), Short.valueOf("3"));
Assert.assertEquals(3, customerIds.size());
CustomerBO customer = TestObjectFactory.getCustomer(customerIds.get(0));
Assert.assertEquals("Group", customer.getDisplayName());
customer = TestObjectFactory.getCustomer(customerIds.get(1));
Assert.assertEquals("client1", customer.getDisplayName());
customer = TestObjectFactory.getCustomer(customerIds.get(2));
Assert.assertEquals("client2", customer.getDisplayName());
TestObjectFactory.cleanUp(client3);
TestObjectFactory.cleanUp(client2);
TestObjectFactory.cleanUp(group1);
TestObjectFactory.cleanUp(center1);
}
public void testGetCustomers() throws NumberFormatException, SystemException, ApplicationException {
center = createCenter("center");
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group", CustomerStatus.GROUP_ACTIVE, center);
CenterBO center1 = createCenter("center11");
GroupBO group1 = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group1", CustomerStatus.GROUP_ACTIVE, center1);
client = TestObjectFactory.createClient("client1", CustomerStatus.CLIENT_ACTIVE, group);
ClientBO client2 = TestObjectFactory.createClient("client2", CustomerStatus.CLIENT_CLOSED, group);
ClientBO client3 = TestObjectFactory.createClient("client3", CustomerStatus.CLIENT_CANCELLED, group1);
List<Integer> customerIds = customerPersistence.getCustomers(CustomerLevel.CENTER.getValue());
Assert.assertEquals(2, customerIds.size());
TestObjectFactory.cleanUp(client3);
TestObjectFactory.cleanUp(client2);
TestObjectFactory.cleanUp(group1);
TestObjectFactory.cleanUp(center1);
}
public void testGetCustomerChecklist() throws NumberFormatException, SystemException, ApplicationException,
Exception {
center = createCenter("center");
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group", CustomerStatus.GROUP_ACTIVE, center);
client = TestObjectFactory.createClient("client1", CustomerStatus.CLIENT_ACTIVE, group);
CustomerCheckListBO checklistCenter = TestObjectFactory.createCustomerChecklist(center.getCustomerLevel()
.getId(), center.getCustomerStatus().getId(), CheckListConstants.STATUS_ACTIVE);
CustomerCheckListBO checklistClient = TestObjectFactory.createCustomerChecklist(client.getCustomerLevel()
.getId(), client.getCustomerStatus().getId(), CheckListConstants.STATUS_INACTIVE);
CustomerCheckListBO checklistGroup = TestObjectFactory.createCustomerChecklist(
group.getCustomerLevel().getId(), group.getCustomerStatus().getId(), CheckListConstants.STATUS_ACTIVE);
StaticHibernateUtil.closeSession();
Assert.assertEquals(1, customerPersistence.getStatusChecklist(center.getCustomerStatus().getId(),
center.getCustomerLevel().getId()).size());
client = (ClientBO) StaticHibernateUtil.getSessionTL().get(ClientBO.class,
Integer.valueOf(client.getCustomerId()));
group = (GroupBO) StaticHibernateUtil.getSessionTL().get(GroupBO.class, Integer.valueOf(group.getCustomerId()));
center = (CenterBO) StaticHibernateUtil.getSessionTL().get(CenterBO.class,
Integer.valueOf(center.getCustomerId()));
checklistCenter = (CustomerCheckListBO) StaticHibernateUtil.getSessionTL().get(CheckListBO.class,
new Short(checklistCenter.getChecklistId()));
checklistClient = (CustomerCheckListBO) StaticHibernateUtil.getSessionTL().get(CheckListBO.class,
new Short(checklistClient.getChecklistId()));
checklistGroup = (CustomerCheckListBO) StaticHibernateUtil.getSessionTL().get(CheckListBO.class,
new Short(checklistGroup.getChecklistId()));
TestObjectFactory.cleanUp(checklistCenter);
TestObjectFactory.cleanUp(checklistClient);
TestObjectFactory.cleanUp(checklistGroup);
}
public void testRetrieveAllCustomerStatusList() throws NumberFormatException, SystemException, ApplicationException {
center = createCenter();
Assert.assertEquals(2, customerPersistence.retrieveAllCustomerStatusList(center.getCustomerLevel().getId())
.size());
}
public void testCustomerCountByOffice() throws Exception {
int count = customerPersistence.getCustomerCountForOffice(CustomerLevel.CENTER, Short.valueOf("3"));
Assert.assertEquals(0, count);
center = createCenter();
count = customerPersistence.getCustomerCountForOffice(CustomerLevel.CENTER, Short.valueOf("3"));
Assert.assertEquals(1, count);
}
public void testGetAllCustomerNotes() throws Exception {
center = createCenter();
center.addCustomerNotes(TestObjectFactory.getCustomerNote("Test Note", center));
TestObjectFactory.updateObject(center);
Assert.assertEquals(1, customerPersistence.getAllCustomerNotes(center.getCustomerId()).getSize());
for (CustomerNoteEntity note : center.getCustomerNotes()) {
Assert.assertEquals("Test Note", note.getComment());
Assert.assertEquals(center.getPersonnel().getPersonnelId(), note.getPersonnel().getPersonnelId());
}
center = (CenterBO) StaticHibernateUtil.getSessionTL().get(CenterBO.class,
Integer.valueOf(center.getCustomerId()));
}
public void testGetAllCustomerNotesWithZeroNotes() throws Exception {
center = createCenter();
Assert.assertEquals(0, customerPersistence.getAllCustomerNotes(center.getCustomerId()).getSize());
Assert.assertEquals(0, center.getCustomerNotes().size());
}
public void testGetFormedByPersonnel() throws NumberFormatException, SystemException, ApplicationException {
center = createCenter();
Assert.assertEquals(1, customerPersistence.getFormedByPersonnel(ClientConstants.LOAN_OFFICER_LEVEL,
center.getOffice().getOfficeId()).size());
}
public void testGetAllClosedAccounts() throws Exception {
getCustomer();
groupAccount.changeStatus(AccountState.LOAN_CANCELLED.getValue(), AccountStateFlag.LOAN_WITHDRAW.getValue(),
"WITHDRAW LOAN ACCOUNT");
clientAccount.changeStatus(AccountState.LOAN_CLOSED_WRITTEN_OFF.getValue(), null, "WITHDRAW LOAN ACCOUNT");
clientSavingsAccount.changeStatus(AccountState.SAVINGS_CANCELLED.getValue(), AccountStateFlag.SAVINGS_REJECTED
.getValue(), "WITHDRAW LOAN ACCOUNT");
TestObjectFactory.updateObject(groupAccount);
TestObjectFactory.updateObject(clientAccount);
TestObjectFactory.updateObject(clientSavingsAccount);
StaticHibernateUtil.commitTransaction();
Assert.assertEquals(1, customerPersistence.getAllClosedAccount(client.getCustomerId(),
AccountTypes.LOAN_ACCOUNT.getValue()).size());
Assert.assertEquals(1, customerPersistence.getAllClosedAccount(group.getCustomerId(),
AccountTypes.LOAN_ACCOUNT.getValue()).size());
Assert.assertEquals(1, customerPersistence.getAllClosedAccount(client.getCustomerId(),
AccountTypes.SAVINGS_ACCOUNT.getValue()).size());
}
public void testGetAllClosedAccountsWhenNoAccountsClosed() throws Exception {
getCustomer();
Assert.assertEquals(0, customerPersistence.getAllClosedAccount(client.getCustomerId(),
AccountTypes.LOAN_ACCOUNT.getValue()).size());
Assert.assertEquals(0, customerPersistence.getAllClosedAccount(group.getCustomerId(),
AccountTypes.LOAN_ACCOUNT.getValue()).size());
Assert.assertEquals(0, customerPersistence.getAllClosedAccount(client.getCustomerId(),
AccountTypes.SAVINGS_ACCOUNT.getValue()).size());
}
public void testGetLOForCustomer() throws PersistenceException {
createCustomers(CustomerStatus.GROUP_ACTIVE, CustomerStatus.CLIENT_ACTIVE);
Short LO = customerPersistence.getLoanOfficerForCustomer(center.getCustomerId());
Assert.assertEquals(center.getPersonnel().getPersonnelId(), LO);
}
public void testUpdateLOsForAllChildren() {
createCustomers(CustomerStatus.GROUP_ACTIVE, CustomerStatus.CLIENT_ACTIVE);
Assert.assertEquals(center.getPersonnel().getPersonnelId(), group.getPersonnel().getPersonnelId());
Assert.assertEquals(center.getPersonnel().getPersonnelId(), client.getPersonnel().getPersonnelId());
StaticHibernateUtil.startTransaction();
PersonnelBO newLO = TestObjectFactory.getPersonnel(Short.valueOf("2"));
new CustomerPersistence().updateLOsForAllChildren(newLO.getPersonnelId(), center.getSearchId(), center
.getOffice().getOfficeId());
StaticHibernateUtil.commitTransaction();
StaticHibernateUtil.closeSession();
center = TestObjectFactory.getCenter(center.getCustomerId());
group = TestObjectFactory.getGroup(group.getCustomerId());
client = TestObjectFactory.getClient(client.getCustomerId());
Assert.assertEquals(newLO.getPersonnelId(), group.getPersonnel().getPersonnelId());
Assert.assertEquals(newLO.getPersonnelId(), client.getPersonnel().getPersonnelId());
}
public void testUpdateLOsForAllChildrenAccounts() throws Exception {
createCustomers(CustomerStatus.GROUP_ACTIVE, CustomerStatus.CLIENT_ACTIVE);
Assert.assertEquals(center.getPersonnel().getPersonnelId(), group.getPersonnel().getPersonnelId());
Assert.assertEquals(center.getPersonnel().getPersonnelId(), client.getPersonnel().getPersonnelId());
StaticHibernateUtil.startTransaction();
PersonnelBO newLO = TestObjectFactory.getPersonnel(Short.valueOf("2"));
new CustomerPersistence().updateLOsForAllChildrenAccounts(newLO.getPersonnelId(), center.getSearchId(), center
.getOffice().getOfficeId());
StaticHibernateUtil.commitTransaction();
StaticHibernateUtil.closeSession();
client = TestObjectFactory.getClient(client.getCustomerId());
for (AccountBO account : client.getAccounts()) {
Assert.assertEquals(newLO.getPersonnelId(), account.getPersonnel().getPersonnelId());
}
}
public void testCustomerDeleteMeeting() throws Exception {
MeetingBO meeting = TestObjectFactory.createMeeting(TestObjectFactory.getTypicalMeeting());
client = TestObjectFactory.createClient("myClient", meeting, CustomerStatus.CLIENT_PENDING);
StaticHibernateUtil.closeSession();
client = TestObjectFactory.getClient(client.getCustomerId());
customerPersistence.deleteCustomerMeeting(client);
CustomerBOTestUtils.setCustomerMeeting(client, null);
StaticHibernateUtil.commitTransaction();
StaticHibernateUtil.closeSession();
client = TestObjectFactory.getClient(client.getCustomerId());
Assert.assertNull(client.getCustomerMeeting());
}
public void testDeleteMeeting() throws Exception {
MeetingBO meeting = TestObjectFactory.createMeeting(TestObjectFactory.getTypicalMeeting());
StaticHibernateUtil.closeSession();
meeting = new MeetingPersistence().getMeeting(meeting.getMeetingId());
customerPersistence.deleteMeeting(meeting);
StaticHibernateUtil.commitTransaction();
StaticHibernateUtil.closeSession();
meeting = new MeetingPersistence().getMeeting(meeting.getMeetingId());
Assert.assertNull(meeting);
}
public void testSearchWithOfficeId() throws Exception {
createCustomers(CustomerStatus.GROUP_ACTIVE, CustomerStatus.CLIENT_ACTIVE);
StaticHibernateUtil.commitTransaction();
QueryResult queryResult = new CustomerPersistence().search("C", Short.valueOf("3"), Short.valueOf("1"), Short
.valueOf("1"));
Assert.assertNotNull(queryResult);
Assert.assertEquals(2, queryResult.getSize());
Assert.assertEquals(2, queryResult.get(0, 10).size());
}
public void testSearchWithoutOfficeId() throws Exception {
createCustomers(CustomerStatus.GROUP_ACTIVE, CustomerStatus.CLIENT_ACTIVE);
StaticHibernateUtil.commitTransaction();
QueryResult queryResult = new CustomerPersistence().search("C", Short.valueOf("0"), Short.valueOf("1"), Short
.valueOf("1"));
Assert.assertNotNull(queryResult);
Assert.assertEquals(2, queryResult.getSize());
Assert.assertEquals(2, queryResult.get(0, 10).size());
}
public void testSearchWithGlobalNo() throws Exception {
createCustomers(CustomerStatus.GROUP_ACTIVE, CustomerStatus.CLIENT_ACTIVE);
StaticHibernateUtil.commitTransaction();
QueryResult queryResult = new CustomerPersistence().search(group.getGlobalCustNum(), Short.valueOf("3"), Short
.valueOf("1"), Short.valueOf("1"));
Assert.assertNotNull(queryResult);
Assert.assertEquals(1, queryResult.getSize());
Assert.assertEquals(1, queryResult.get(0, 10).size());
}
public void testSearchWithGovernmentId() throws Exception {
createCustomersWithGovernmentId(CustomerStatus.GROUP_ACTIVE, CustomerStatus.CLIENT_ACTIVE);
StaticHibernateUtil.commitTransaction();
QueryResult queryResult = new CustomerPersistence().search("76346793216", Short.valueOf("3"), Short
.valueOf("1"), Short.valueOf("1"));
Assert.assertNotNull(queryResult);
Assert.assertEquals(1, queryResult.getSize());
Assert.assertEquals(1, queryResult.get(0, 10).size());
}
@SuppressWarnings("unchecked")
public void testSearchWithCancelLoanAccounts() throws Exception {
groupAccount = getLoanAccount();
groupAccount.changeStatus(AccountState.LOAN_CANCELLED.getValue(), AccountStateFlag.LOAN_WITHDRAW.getValue(),
"WITHDRAW LOAN ACCOUNT");
TestObjectFactory.updateObject(groupAccount);
StaticHibernateUtil.commitTransaction();
StaticHibernateUtil.closeSession();
groupAccount = TestObjectFactory.getObject(LoanBO.class, groupAccount.getAccountId());
center = TestObjectFactory.getCustomer(center.getCustomerId());
group = TestObjectFactory.getCustomer(group.getCustomerId());
QueryResult queryResult = new CustomerPersistence().search(group.getGlobalCustNum(), Short.valueOf("3"), Short
.valueOf("1"), Short.valueOf("1"));
Assert.assertNotNull(queryResult);
Assert.assertEquals(1, queryResult.getSize());
List results = queryResult.get(0, 10);
Assert.assertEquals(1, results.size());
CustomerSearch customerSearch = (CustomerSearch) results.get(0);
Assert.assertEquals(0, customerSearch.getLoanGlobalAccountNum().size());
}
public void testSearchWithAccountGlobalNo() throws Exception {
getCustomer();
StaticHibernateUtil.commitTransaction();
QueryResult queryResult = new CustomerPersistence().search(groupAccount.getGlobalAccountNum(), Short
.valueOf("3"), Short.valueOf("1"), Short.valueOf("1"));
Assert.assertNotNull(queryResult);
Assert.assertEquals(1, queryResult.getSize());
Assert.assertEquals(1, queryResult.get(0, 10).size());
}
public void testSearchGropAndClient() throws Exception {
createCustomers(CustomerStatus.GROUP_ACTIVE, CustomerStatus.CLIENT_ACTIVE);
StaticHibernateUtil.commitTransaction();
QueryResult queryResult = new CustomerPersistence().searchGroupClient("C", Short.valueOf("1"));
Assert.assertNotNull(queryResult);
Assert.assertEquals(1, queryResult.getSize());
Assert.assertEquals(1, queryResult.get(0, 10).size());
}
public void testSearchGropAndClientForLoNoResults() throws Exception {
meeting = TestObjectFactory.createMeeting(TestObjectFactory.getTypicalMeeting());
center = TestObjectFactory.createWeeklyFeeCenter("Center", meeting, Short.valueOf("3"), Short.valueOf("3"));
group = TestObjectFactory.createGroupUnderCenter("Group", CustomerStatus.GROUP_ACTIVE, "1234", true,
new java.util.Date(), null, null, null, Short.valueOf("3"), center);
StaticHibernateUtil.commitTransaction();
QueryResult queryResult = new CustomerPersistence().searchGroupClient("C", Short.valueOf("3"));
Assert.assertNotNull(queryResult);
Assert.assertEquals(0, queryResult.getSize());
Assert.assertEquals(0, queryResult.get(0, 10).size());
}
public void testSearchGropAndClientForLo() throws Exception {
meeting = TestObjectFactory.createMeeting(TestObjectFactory.getTypicalMeeting());
center = TestObjectFactory.createWeeklyFeeCenter("Center", meeting, Short.valueOf("3"), Short.valueOf("3"));
group = TestObjectFactory.createGroupUnderCenter("Group", CustomerStatus.GROUP_ACTIVE, "1234", true,
new java.util.Date(), null, null, null, Short.valueOf("3"), center);
StaticHibernateUtil.commitTransaction();
QueryResult queryResult = new CustomerPersistence().searchGroupClient("G", Short.valueOf("3"));
Assert.assertNotNull(queryResult);
Assert.assertEquals(1, queryResult.getSize());
Assert.assertEquals(1, queryResult.get(0, 10).size());
}
public void testSearchCustForSavings() throws Exception {
createCustomers(CustomerStatus.GROUP_ACTIVE, CustomerStatus.CLIENT_ACTIVE);
StaticHibernateUtil.commitTransaction();
QueryResult queryResult = new CustomerPersistence().searchCustForSavings("C", Short.valueOf("1"));
Assert.assertNotNull(queryResult);
Assert.assertEquals(2, queryResult.getSize());
Assert.assertEquals(2, queryResult.get(0, 10).size());
}
public void testGetCustomerAccountsForFee() throws Exception {
groupAccount = getLoanAccount();
FeeBO periodicFee = TestObjectFactory.createPeriodicAmountFee("ClientPeridoicFee", FeeCategory.CENTER, "5",
RecurrenceType.WEEKLY, Short.valueOf("1"));
AccountFeesEntity accountFee = new AccountFeesEntity(center.getCustomerAccount(), periodicFee,
((AmountFeeBO) periodicFee).getFeeAmount().getAmountDoubleValue());
CustomerAccountBO customerAccount = center.getCustomerAccount();
AccountTestUtils.addAccountFees(accountFee, customerAccount);
TestObjectFactory.updateObject(customerAccount);
StaticHibernateUtil.commitTransaction();
StaticHibernateUtil.closeSession();
// check for the account fee
List<AccountBO> accountList = new CustomerPersistence().getCustomerAccountsForFee(periodicFee.getFeeId());
Assert.assertNotNull(accountList);
Assert.assertEquals(1, accountList.size());
Assert.assertTrue(accountList.get(0) instanceof CustomerAccountBO);
// get all objects again
groupAccount = TestObjectFactory.getObject(LoanBO.class, groupAccount.getAccountId());
group = TestObjectFactory.getCustomer(group.getCustomerId());
center = TestObjectFactory.getCustomer(center.getCustomerId());
}
public void testRetrieveCustomerAccountActionDetails() throws Exception {
center = createCenter();
Assert.assertNotNull(center.getCustomerAccount());
List<AccountActionDateEntity> actionDates = new CustomerPersistence().retrieveCustomerAccountActionDetails(
center.getCustomerAccount().getAccountId(), new java.sql.Date(System.currentTimeMillis()));
Assert.assertEquals("The size of the due insallments is ", actionDates.size(), 1);
}
public void testGetActiveCentersUnderUser() throws Exception {
MeetingBO meeting = TestObjectFactory.createMeeting(TestObjectFactory.getTypicalMeeting());
center = TestObjectFactory.createWeeklyFeeCenter("center", meeting, Short.valueOf("1"), Short.valueOf("1"));
PersonnelBO personnel = TestObjectFactory.getPersonnel(Short.valueOf("1"));
List<CustomerBO> customers = new CustomerPersistence().getActiveCentersUnderUser(personnel);
Assert.assertNotNull(customers);
Assert.assertEquals(1, customers.size());
}
public void testgetGroupsUnderUser() throws Exception {
MeetingBO meeting = TestObjectFactory.createMeeting(TestObjectFactory.getTypicalMeeting());
center = TestObjectFactory.createWeeklyFeeCenter("center", meeting, Short.valueOf("1"), Short.valueOf("1"));
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group", CustomerStatus.GROUP_ACTIVE, center);
group2 = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group33", CustomerStatus.GROUP_CANCELLED, center);
PersonnelBO personnel = TestObjectFactory.getPersonnel(Short.valueOf("1"));
List<CustomerBO> customers = new CustomerPersistence().getGroupsUnderUser(personnel);
Assert.assertNotNull(customers);
Assert.assertEquals(1, customers.size());
}
@SuppressWarnings("unchecked")
public void testSearchForActiveInBadStandingLoanAccount() throws Exception {
groupAccount = getLoanAccount();
groupAccount.changeStatus(AccountState.LOAN_ACTIVE_IN_BAD_STANDING.getValue(), null, "Changing to badStanding");
TestObjectFactory.updateObject(groupAccount);
StaticHibernateUtil.closeSession();
groupAccount = TestObjectFactory.getObject(LoanBO.class, groupAccount.getAccountId());
center = TestObjectFactory.getCustomer(center.getCustomerId());
group = TestObjectFactory.getCustomer(group.getCustomerId());
QueryResult queryResult = new CustomerPersistence().search(group.getGlobalCustNum(), Short.valueOf("3"), Short
.valueOf("1"), Short.valueOf("1"));
Assert.assertNotNull(queryResult);
Assert.assertEquals(1, queryResult.getSize());
List results = queryResult.get(0, 10);
Assert.assertEquals(1, results.size());
CustomerSearch customerSearch = (CustomerSearch) results.get(0);
Assert.assertEquals(1, customerSearch.getLoanGlobalAccountNum().size());
}
public void testGetCustomersByLevelId() throws Exception {
createCustomers(CustomerStatus.GROUP_ACTIVE, CustomerStatus.CLIENT_ACTIVE);
StaticHibernateUtil.commitTransaction();
List<CustomerBO> client = new CustomerPersistence().getCustomersByLevelId(Short.parseShort("1"));
Assert.assertNotNull(client);
Assert.assertEquals(1, client.size());
List<CustomerBO> group = new CustomerPersistence().getCustomersByLevelId(Short.parseShort("2"));
Assert.assertNotNull(group);
Assert.assertEquals(1, group.size());
List<CustomerBO> center = new CustomerPersistence().getCustomersByLevelId(Short.parseShort("3"));
Assert.assertNotNull(center);
Assert.assertEquals(1, center.size());
}
public void testFindCustomerWithNoAssocationsLoadedReturnsActiveCenter() throws Exception {
meeting = TestObjectFactory.createMeeting(TestObjectFactory.getNewMeetingForToday(WEEKLY,
EVERY_WEEK, CUSTOMER_MEETING));
center = TestObjectFactory.createWeeklyFeeCenter("Active Center", meeting);
verifyCustomerLoaded(center.getCustomerId(), center.getDisplayName());
}
public void testFindCustomerWithNoAssocationsLoadedDoesntReturnInactiveCenter() throws Exception {
meeting = TestObjectFactory.createMeeting(TestObjectFactory.getNewMeetingForToday(WEEKLY,
EVERY_WEEK, CUSTOMER_MEETING));
center = TestObjectFactory.createWeeklyFeeCenter("Inactive Center", meeting);
center.changeStatus(CustomerStatus.CENTER_INACTIVE, CustomerStatusFlag.GROUP_CANCEL_BLACKLISTED, "Made Inactive");
StaticHibernateUtil.commitTransaction();
StaticHibernateUtil.closeSession();
center = (CenterBO) StaticHibernateUtil.getSessionTL().get(CenterBO.class, center.getCustomerId());
verifyCustomerNotLoaded(center.getCustomerId(), center.getDisplayName());
}
public void testFindCustomerWithNoAssocationsLoadedReturnsActiveGroup() throws Exception {
meeting = TestObjectFactory.createMeeting(TestObjectFactory.getNewMeetingForToday(WEEKLY,
EVERY_WEEK, CUSTOMER_MEETING));
center = TestObjectFactory.createWeeklyFeeCenter("Active Center", meeting);
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Active Group", CustomerStatus.GROUP_ACTIVE,
center);
verifyCustomerLoaded(group.getCustomerId(), group.getDisplayName());
}
public void testFindCustomerWithNoAssocationsLoadedReturnsHoldGroup() throws Exception {
meeting = TestObjectFactory.createMeeting(TestObjectFactory.getNewMeetingForToday(WEEKLY,
EVERY_WEEK, CUSTOMER_MEETING));
center = TestObjectFactory.createWeeklyFeeCenter("Active Center", meeting);
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Hold Group", CustomerStatus.GROUP_HOLD,
center);
verifyCustomerLoaded(group.getCustomerId(), group.getDisplayName());
}
public void testFindCustomerWithNoAssocationsLoadedDoesntReturnClosedGroup() throws Exception {
meeting = TestObjectFactory.createMeeting(TestObjectFactory.getNewMeetingForToday(WEEKLY,
EVERY_WEEK, CUSTOMER_MEETING));
center = TestObjectFactory.createWeeklyFeeCenter("Active Center", meeting);
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Closed Group", CustomerStatus.GROUP_CLOSED,
center);
verifyCustomerNotLoaded(group.getCustomerId(), group.getDisplayName());
}
public void testFindCustomerWithNoAssocationsLoadedReturnsActiveClient() throws Exception {
meeting = TestObjectFactory.createMeeting(TestObjectFactory.getNewMeetingForToday(WEEKLY,
EVERY_WEEK, CUSTOMER_MEETING));
center = TestObjectFactory.createWeeklyFeeCenter("Active Center", meeting);
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Active Group", CustomerStatus.GROUP_ACTIVE,
center);
client = TestObjectFactory.createClient("Active Client", CustomerStatus.CLIENT_ACTIVE, group);
verifyCustomerLoaded(client.getCustomerId(), client.getDisplayName());
}
public void testFindCustomerWithNoAssocationsLoadedReturnsHoldClient() throws Exception {
meeting = TestObjectFactory.createMeeting(TestObjectFactory.getNewMeetingForToday(WEEKLY,
EVERY_WEEK, CUSTOMER_MEETING));
center = TestObjectFactory.createWeeklyFeeCenter("Active Center", meeting);
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Active Group", CustomerStatus.GROUP_ACTIVE,
center);
client = TestObjectFactory.createClient("Hold Client", CustomerStatus.CLIENT_HOLD, group);
verifyCustomerLoaded(client.getCustomerId(), client.getDisplayName());
}
public void testFindCustomerWithNoAssocationsLoadedDoesntReturnClosedClient() throws Exception {
meeting = TestObjectFactory.createMeeting(TestObjectFactory.getNewMeetingForToday(WEEKLY,
EVERY_WEEK, CUSTOMER_MEETING));
center = TestObjectFactory.createWeeklyFeeCenter("Active Center", meeting);
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Active Group", CustomerStatus.GROUP_ACTIVE,
center);
client = TestObjectFactory.createClient("Closed Client", CustomerStatus.CLIENT_CLOSED, group);
verifyCustomerNotLoaded(client.getCustomerId(), client.getDisplayName());
}
private void verifyCustomerLoaded(Integer customerId, String customerName) {
CollectionSheetCustomerDto collectionSheetCustomerDto = customerPersistence
.findCustomerWithNoAssocationsLoaded(customerId);
Assert.assertNotNull(customerName + " was not returned", collectionSheetCustomerDto);
Assert.assertEquals(collectionSheetCustomerDto.getCustomerId(), customerId);
}
private void verifyCustomerNotLoaded(Integer customerId, String customerName) {
CollectionSheetCustomerDto collectionSheetCustomerDto = customerPersistence
.findCustomerWithNoAssocationsLoaded(customerId);
Assert.assertNull(customerName + " was returned", collectionSheetCustomerDto);
}
private AccountBO getSavingsAccount(final CustomerBO customer, final String prdOfferingname, final String shortName)
throws Exception {
Date startDate = new Date(System.currentTimeMillis());
SavingsOfferingBO savingsOffering = TestObjectFactory.createSavingsProduct(prdOfferingname, shortName,
startDate, RecommendedAmountUnit.COMPLETE_GROUP);
return TestObjectFactory.createSavingsAccount("432434", customer, Short.valueOf("16"), startDate,
savingsOffering);
}
private void getCustomer() throws Exception {
Date startDate = new Date(System.currentTimeMillis());
MeetingBO meeting = TestObjectFactory.createMeeting(TestObjectFactory.getTypicalMeeting());
center = TestObjectFactory.createWeeklyFeeCenter("Center", meeting);
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group", CustomerStatus.GROUP_ACTIVE, center);
client = TestObjectFactory.createClient("Client", CustomerStatus.CLIENT_ACTIVE, group);
LoanOfferingBO loanOffering1 = TestObjectFactory.createLoanOffering("Loanwer", "43fs", startDate, meeting);
LoanOfferingBO loanOffering2 = TestObjectFactory.createLoanOffering("Loancd123", "vfr", startDate, meeting);
groupAccount = TestObjectFactory.createLoanAccount("42423142341", group,
AccountState.LOAN_ACTIVE_IN_GOOD_STANDING, startDate, loanOffering1);
clientAccount = TestObjectFactory.createLoanAccount("3243", client, AccountState.LOAN_ACTIVE_IN_GOOD_STANDING,
startDate, loanOffering2);
MeetingBO meetingIntCalc = TestObjectFactory.createMeeting(TestObjectFactory.getTypicalMeeting());
MeetingBO meetingIntPost = TestObjectFactory.createMeeting(TestObjectFactory.getTypicalMeeting());
SavingsOfferingBO savingsOffering = TestObjectFactory.createSavingsProduct("SavingPrd12", "abc1", startDate,
RecommendedAmountUnit.COMPLETE_GROUP, meetingIntCalc, meetingIntPost);
SavingsOfferingBO savingsOffering1 = TestObjectFactory.createSavingsProduct("SavingPrd11", "abc2", startDate,
RecommendedAmountUnit.COMPLETE_GROUP, meetingIntCalc, meetingIntPost);
centerSavingsAccount = TestObjectFactory.createSavingsAccount("432434", center, Short.valueOf("16"), startDate,
savingsOffering);
clientSavingsAccount = TestObjectFactory.createSavingsAccount("432434", client, Short.valueOf("16"), startDate,
savingsOffering1);
}
private void createCustomers(final CustomerStatus groupStatus, final CustomerStatus clientStatus) {
meeting = TestObjectFactory.createMeeting(TestObjectFactory.getTypicalMeeting());
center = TestObjectFactory.createWeeklyFeeCenter("Center", meeting);
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group", groupStatus, center);
client = TestObjectFactory.createClient("Client", clientStatus, group);
}
private void createCustomersWithGovernmentId(final CustomerStatus groupStatus, final CustomerStatus clientStatus) {
meeting = TestObjectFactory.createMeeting(TestObjectFactory.getTypicalMeeting());
center = TestObjectFactory.createWeeklyFeeCenter("Center", meeting);
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group", groupStatus, center);
client = TestObjectFactory.createClient("Client", clientStatus, group, TestObjectFactory.getFees(), "76346793216", new java.util.Date(1222333444000L));
}
private static java.util.Date getMeetingDates(final MeetingBO meeting) {
List<java.util.Date> dates = new ArrayList<java.util.Date>();
try {
dates = meeting.getAllDates(new java.util.Date(System.currentTimeMillis()));
} catch (MeetingException e) {
e.printStackTrace();
}
return dates.get(dates.size() - 1);
}
private CenterBO createCenter() {
return createCenter("Center_Active_test");
}
private CenterBO createCenter(final String name) {
MeetingBO meeting = TestObjectFactory.createMeeting(TestObjectFactory.getNewMeetingForToday(WEEKLY, EVERY_WEEK,
CUSTOMER_MEETING));
return TestObjectFactory.createWeeklyFeeCenter(name, meeting);
}
private LoanBO getLoanAccount() {
Date startDate = new Date(System.currentTimeMillis());
MeetingBO meeting = TestObjectFactory.createMeeting(TestObjectFactory.getNewMeetingForToday(WEEKLY, EVERY_WEEK,
CUSTOMER_MEETING));
center = TestObjectFactory.createWeeklyFeeCenter("Center", meeting);
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group", CustomerStatus.GROUP_ACTIVE, center);
LoanOfferingBO loanOffering = TestObjectFactory.createLoanOffering(startDate, meeting);
return TestObjectFactory.createLoanAccount("42423142341", group, AccountState.LOAN_ACTIVE_IN_GOOD_STANDING,
startDate, loanOffering);
}
private AccountBO getLoanAccount(final CustomerBO group, final MeetingBO meeting, final String offeringName,
final String shortName) {
Date startDate = new Date(System.currentTimeMillis());
LoanOfferingBO loanOffering = TestObjectFactory.createLoanOffering(offeringName, shortName, startDate, meeting);
return TestObjectFactory.createLoanAccount("42423142341", group, AccountState.LOAN_ACTIVE_IN_GOOD_STANDING,
startDate, loanOffering);
}
private AccountBO getLoanAccount(final CustomerBO group, final MeetingBO meeting, final String offeringName,
final String shortName, MifosCurrency currency) {
Date startDate = new Date(System.currentTimeMillis());
LoanOfferingBO loanOffering = TestObjectFactory.createLoanOffering(offeringName, shortName, startDate, meeting, currency);
return TestObjectFactory.createLoanAccount("42423142341", group, AccountState.LOAN_ACTIVE_IN_GOOD_STANDING,
startDate, loanOffering);
}
private AccountBO getLoanAccountInActiveBadStanding(final CustomerBO group, final MeetingBO meeting,
final String offeringName, final String shortName) {
Date startDate = new Date(System.currentTimeMillis());
LoanOfferingBO loanOffering = TestObjectFactory.createLoanOffering(offeringName, shortName, startDate, meeting);
return TestObjectFactory.createLoanAccount("42423141111", group, AccountState.LOAN_ACTIVE_IN_BAD_STANDING,
startDate, loanOffering);
}
}
| Java |
/**
*
* @author Alex Karpov (mailto:karpov_aleksey@mail.ru)
* @version $Id$
* @since 0.1
*/
package ru.job4j.max; | Java |
package com.capgemini.resilience.employer.service;
public interface ErrorSimulationService {
void generateErrorDependingOnErrorPossibility();
}
| Java |
using UnityEngine;
using System.Collections;
public class blockGenerator : MonoBehaviour {
public int spawnRate = 1;
private float timeSinceLastSpawn = 0;
public GameObject oneCube;
public int count;
// Use this for initialization
void Start () {
//Debug.Log("ran cube creator");
count = 0;
}
// Update is called once per frame
void Update () {
//timeSinceLastSpawn += Time.realtimeSinceStartup;
//Debug.Log("running cube creator" + timeSinceLastSpawn );
// if ( timeSinceLastSpawn > spawnRate )
// {
//Clone the cubes and randomly place them
count = count + 1;
if (count.Equals(50)) {
GameObject newCube = (GameObject)GameObject.Instantiate (oneCube);
newCube.transform.position = new Vector3 (0, 0, 20.0f);
newCube.transform.Translate (Random.Range (-8, 8), Random.Range (0, 8), 1.0f);
timeSinceLastSpawn = 0;
//Debug.Log("cube created");
// }
count = 0;
}
}
} | Java |
// -----------------------------------------------------------------------
// <copyright file="Health.cs" company="PlayFab Inc">
// Copyright 2015 PlayFab 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.
// </copyright>
// -----------------------------------------------------------------------
using System.Threading;
using System.Threading.Tasks;
namespace Consul
{
public interface IHealthEndpoint
{
Task<QueryResult<HealthCheck[]>> Checks(string service, CancellationToken ct = default(CancellationToken));
Task<QueryResult<HealthCheck[]>> Checks(string service, QueryOptions q, CancellationToken ct = default(CancellationToken));
Task<QueryResult<HealthCheck[]>> Node(string node, CancellationToken ct = default(CancellationToken));
Task<QueryResult<HealthCheck[]>> Node(string node, QueryOptions q, CancellationToken ct = default(CancellationToken));
Task<QueryResult<ServiceEntry[]>> Service(string service, CancellationToken ct = default(CancellationToken));
Task<QueryResult<ServiceEntry[]>> Service(string service, string tag, CancellationToken ct = default(CancellationToken));
Task<QueryResult<ServiceEntry[]>> Service(string service, string tag, bool passingOnly, CancellationToken ct = default(CancellationToken));
Task<QueryResult<ServiceEntry[]>> Service(string service, string tag, bool passingOnly, QueryOptions q, CancellationToken ct = default(CancellationToken));
Task<QueryResult<HealthCheck[]>> State(HealthStatus status, CancellationToken ct = default(CancellationToken));
Task<QueryResult<HealthCheck[]>> State(HealthStatus status, QueryOptions q, CancellationToken ct = default(CancellationToken));
}
} | Java |
////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// 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 holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
////////////////////////////////////////////////////////////////////////////////
#include "RestHandler.h"
#include "Basics/StringUtils.h"
#include "Dispatcher/Dispatcher.h"
#include "Logger/Logger.h"
#include "Rest/GeneralRequest.h"
using namespace arangodb;
using namespace arangodb::basics;
using namespace arangodb::rest;
namespace {
std::atomic_uint_fast64_t NEXT_HANDLER_ID(
static_cast<uint64_t>(TRI_microtime() * 100000.0));
}
RestHandler::RestHandler(GeneralRequest* request, GeneralResponse* response)
: _handlerId(NEXT_HANDLER_ID.fetch_add(1, std::memory_order_seq_cst)),
_taskId(0),
_request(request),
_response(response) {}
RestHandler::~RestHandler() {
delete _request;
delete _response;
}
void RestHandler::setTaskId(uint64_t id, EventLoop loop) {
_taskId = id;
_loop = loop;
}
RestHandler::status RestHandler::executeFull() {
RestHandler::status result = status::FAILED;
requestStatisticsAgentSetRequestStart();
#ifdef USE_DEV_TIMERS
TRI_request_statistics_t::STATS = _statistics;
#endif
try {
prepareExecute();
try {
result = execute();
} catch (Exception const& ex) {
requestStatisticsAgentSetExecuteError();
handleError(ex);
} catch (std::bad_alloc const& ex) {
requestStatisticsAgentSetExecuteError();
Exception err(TRI_ERROR_OUT_OF_MEMORY, ex.what(), __FILE__, __LINE__);
handleError(err);
} catch (std::exception const& ex) {
requestStatisticsAgentSetExecuteError();
Exception err(TRI_ERROR_INTERNAL, ex.what(), __FILE__, __LINE__);
handleError(err);
} catch (...) {
requestStatisticsAgentSetExecuteError();
Exception err(TRI_ERROR_INTERNAL, __FILE__, __LINE__);
handleError(err);
}
finalizeExecute();
if (result != status::ASYNC && _response == nullptr) {
Exception err(TRI_ERROR_INTERNAL, "no response received from handler",
__FILE__, __LINE__);
handleError(err);
}
} catch (Exception const& ex) {
result = status::FAILED;
requestStatisticsAgentSetExecuteError();
LOG(ERR) << "caught exception: " << DIAGNOSTIC_INFORMATION(ex);
} catch (std::exception const& ex) {
result = status::FAILED;
requestStatisticsAgentSetExecuteError();
LOG(ERR) << "caught exception: " << ex.what();
} catch (...) {
result = status::FAILED;
requestStatisticsAgentSetExecuteError();
LOG(ERR) << "caught exception";
}
requestStatisticsAgentSetRequestEnd();
#ifdef USE_DEV_TIMERS
TRI_request_statistics_t::STATS = nullptr;
#endif
return result;
}
GeneralRequest* RestHandler::stealRequest() {
GeneralRequest* tmp = _request;
_request = nullptr;
return tmp;
}
GeneralResponse* RestHandler::stealResponse() {
GeneralResponse* tmp = _response;
_response = nullptr;
return tmp;
}
void RestHandler::setResponseCode(GeneralResponse::ResponseCode code) {
TRI_ASSERT(_response != nullptr);
_response->reset(code);
}
| Java |
package com.box.boxjavalibv2.responseparsers;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import junit.framework.Assert;
import org.apache.commons.io.IOUtils;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicHttpResponse;
import org.easymock.EasyMock;
import org.junit.Before;
import org.junit.Test;
import com.box.boxjavalibv2.dao.BoxPreview;
import com.box.restclientv2.exceptions.BoxRestException;
import com.box.restclientv2.responses.DefaultBoxResponse;
public class PreviewResponseParserTest {
private final static String PREVIEW_MOCK_CONTENT = "arbitrary string";
private final static String LINK_VALUE = "<https://api.box.com/2.0/files/5000369410/preview.png?page=%d>; rel=\"first\", <https://api.box.com/2.0/files/5000369410/preview.png?page=%d>; rel=\"last\"";
private final static String LINK_NAME = "Link";
private final static int firstPage = 1;
private final static int lastPage = 2;
private final static double length = 213;
private BoxPreview preview;
private DefaultBoxResponse boxResponse;
private HttpResponse response;
private HttpEntity entity;
private InputStream inputStream;
private Header header;
@Before
public void setUp() {
preview = new BoxPreview();
preview.setFirstPage(firstPage);
preview.setLastPage(lastPage);
boxResponse = EasyMock.createMock(DefaultBoxResponse.class);
response = EasyMock.createMock(BasicHttpResponse.class);
entity = EasyMock.createMock(StringEntity.class);
header = new BasicHeader("Link", String.format(LINK_VALUE, firstPage, lastPage));
}
@Test
public void testCanParsePreview() throws IllegalStateException, IOException, BoxRestException {
EasyMock.reset(boxResponse, response, entity);
inputStream = new ByteArrayInputStream(PREVIEW_MOCK_CONTENT.getBytes());
EasyMock.expect(boxResponse.getHttpResponse()).andReturn(response);
EasyMock.expect(boxResponse.getContentLength()).andReturn(length);
EasyMock.expect(response.getEntity()).andReturn(entity);
EasyMock.expect(entity.getContent()).andReturn(inputStream);
EasyMock.expect(boxResponse.getHttpResponse()).andReturn(response);
EasyMock.expect(response.getFirstHeader("Link")).andReturn(header);
EasyMock.replay(boxResponse, response, entity);
PreviewResponseParser parser = new PreviewResponseParser();
Object object = parser.parse(boxResponse);
Assert.assertEquals(BoxPreview.class, object.getClass());
BoxPreview parsed = (BoxPreview) object;
Assert.assertEquals(length, parsed.getContentLength());
Assert.assertEquals(firstPage, parsed.getFirstPage().intValue());
Assert.assertEquals(lastPage, parsed.getLastPage().intValue());
Assert.assertEquals(PREVIEW_MOCK_CONTENT, IOUtils.toString(parsed.getContent()));
EasyMock.verify(boxResponse, response, entity);
}
}
| Java |
// Copyright (C) 2018 The Android Open Source Project
//
// 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.google.gerrit.server.git.receive;
import com.google.common.collect.ImmutableList;
import com.google.gerrit.reviewdb.client.Change;
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
/**
* Keeps track of the change IDs thus far updated by ReceiveCommit.
*
* <p>This class is thread-safe.
*/
public class ResultChangeIds {
public enum Key {
CREATED,
REPLACED,
AUTOCLOSED,
}
private boolean isMagicPush;
private final Map<Key, List<Change.Id>> ids;
ResultChangeIds() {
ids = new EnumMap<>(Key.class);
for (Key k : Key.values()) {
ids.put(k, new ArrayList<>());
}
}
/** Record a change ID update as having completed. Thread-safe. */
public synchronized void add(Key key, Change.Id id) {
ids.get(key).add(id);
}
/** Indicate that the ReceiveCommits call involved a magic branch. */
public synchronized void setMagicPush(boolean magic) {
isMagicPush = magic;
}
public synchronized boolean isMagicPush() {
return isMagicPush;
}
/**
* Returns change IDs of the given type for which the BatchUpdate succeeded, or empty list if
* there are none. Thread-safe.
*/
public synchronized List<Change.Id> get(Key key) {
return ImmutableList.copyOf(ids.get(key));
}
}
| Java |
# Copyright 2016 The Meson development 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.
import os
import subprocess
import shutil
import argparse
from .. import mlog
from ..mesonlib import has_path_sep
from . import destdir_join
from .gettext import read_linguas
parser = argparse.ArgumentParser()
parser.add_argument('command')
parser.add_argument('--id', dest='project_id')
parser.add_argument('--subdir', dest='subdir')
parser.add_argument('--installdir', dest='install_dir')
parser.add_argument('--sources', dest='sources')
parser.add_argument('--media', dest='media', default='')
parser.add_argument('--langs', dest='langs', default='')
parser.add_argument('--symlinks', type=bool, dest='symlinks', default=False)
def build_pot(srcdir, project_id, sources):
# Must be relative paths
sources = [os.path.join('C', source) for source in sources]
outfile = os.path.join(srcdir, project_id + '.pot')
subprocess.call(['itstool', '-o', outfile] + sources)
def update_po(srcdir, project_id, langs):
potfile = os.path.join(srcdir, project_id + '.pot')
for lang in langs:
pofile = os.path.join(srcdir, lang, lang + '.po')
subprocess.call(['msgmerge', '-q', '-o', pofile, pofile, potfile])
def build_translations(srcdir, blddir, langs):
for lang in langs:
outdir = os.path.join(blddir, lang)
os.makedirs(outdir, exist_ok=True)
subprocess.call([
'msgfmt', os.path.join(srcdir, lang, lang + '.po'),
'-o', os.path.join(outdir, lang + '.gmo')
])
def merge_translations(blddir, sources, langs):
for lang in langs:
subprocess.call([
'itstool', '-m', os.path.join(blddir, lang, lang + '.gmo'),
'-o', os.path.join(blddir, lang)
] + sources)
def install_help(srcdir, blddir, sources, media, langs, install_dir, destdir, project_id, symlinks):
c_install_dir = os.path.join(install_dir, 'C', project_id)
for lang in langs + ['C']:
indir = destdir_join(destdir, os.path.join(install_dir, lang, project_id))
os.makedirs(indir, exist_ok=True)
for source in sources:
infile = os.path.join(srcdir if lang == 'C' else blddir, lang, source)
outfile = os.path.join(indir, source)
mlog.log('Installing %s to %s' % (infile, outfile))
shutil.copyfile(infile, outfile)
shutil.copystat(infile, outfile)
for m in media:
infile = os.path.join(srcdir, lang, m)
outfile = os.path.join(indir, m)
c_infile = os.path.join(srcdir, 'C', m)
if not os.path.exists(infile):
if not os.path.exists(c_infile):
mlog.warning('Media file "%s" did not exist in C directory' % m)
continue
elif symlinks:
srcfile = os.path.join(c_install_dir, m)
mlog.log('Symlinking %s to %s.' % (outfile, srcfile))
if has_path_sep(m):
os.makedirs(os.path.dirname(outfile), exist_ok=True)
try:
try:
os.symlink(srcfile, outfile)
except FileExistsError:
os.remove(outfile)
os.symlink(srcfile, outfile)
continue
except (NotImplementedError, OSError):
mlog.warning('Symlinking not supported, falling back to copying')
infile = c_infile
else:
# Lang doesn't have media file so copy it over 'C' one
infile = c_infile
mlog.log('Installing %s to %s' % (infile, outfile))
if has_path_sep(m):
os.makedirs(os.path.dirname(outfile), exist_ok=True)
shutil.copyfile(infile, outfile)
shutil.copystat(infile, outfile)
def run(args):
options = parser.parse_args(args)
langs = options.langs.split('@@') if options.langs else []
media = options.media.split('@@') if options.media else []
sources = options.sources.split('@@')
destdir = os.environ.get('DESTDIR', '')
src_subdir = os.path.join(os.environ['MESON_SOURCE_ROOT'], options.subdir)
build_subdir = os.path.join(os.environ['MESON_BUILD_ROOT'], options.subdir)
abs_sources = [os.path.join(src_subdir, 'C', source) for source in sources]
if not langs:
langs = read_linguas(src_subdir)
if options.command == 'pot':
build_pot(src_subdir, options.project_id, sources)
elif options.command == 'update-po':
build_pot(src_subdir, options.project_id, sources)
update_po(src_subdir, options.project_id, langs)
elif options.command == 'build':
if langs:
build_translations(src_subdir, build_subdir, langs)
elif options.command == 'install':
install_dir = os.path.join(os.environ['MESON_INSTALL_PREFIX'], options.install_dir)
if langs:
build_translations(src_subdir, build_subdir, langs)
merge_translations(build_subdir, abs_sources, langs)
install_help(src_subdir, build_subdir, sources, media, langs, install_dir,
destdir, options.project_id, options.symlinks)
| Java |
package com.veneweather.android;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.veneweather.android.db.City;
import com.veneweather.android.db.County;
import com.veneweather.android.db.Province;
import com.veneweather.android.util.HttpUtil;
import com.veneweather.android.util.Utility;
import org.litepal.crud.DataSupport;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
/**
* Created by lenovo on 2017/4/10.
*/
public class ChooseAreaFragment extends Fragment {
public static final int LEVEL_PROVINCE = 0;
public static final int LEVEL_CITY = 1;
public static final int LEVEL_COUNTY = 2;
private ProgressDialog progressDialog;
private TextView titleText;
private Button btn_back;
private ListView listView;
private ArrayAdapter<String> adapter;
private List<String> dataList = new ArrayList<>();
/**
* 省列表
*/
private List<Province> provinceList;
/**
* 市列表
*/
private List<City> cityList;
/**
* 县列表
*/
private List<County> countyList;
/**
* 选中的省份
*/
private Province selectedProvince;
/**
* 选中的城市
*/
private City selectedCity;
/**
* 当前选中的级别
*/
private int currentLevel;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.choose_area, container, false);
titleText = (TextView) view.findViewById(R.id.title_text);
btn_back = (Button) view.findViewById(R.id.back_button);
listView = (ListView) view.findViewById(R.id.list_view);
adapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_list_item_1, dataList);
listView.setAdapter(adapter);
return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
if (currentLevel == LEVEL_PROVINCE) {
selectedProvince = provinceList.get(position);
queryCities();
} else if (currentLevel == LEVEL_CITY) {
selectedCity = cityList.get(position);
queryCounties();
} else if (currentLevel == LEVEL_COUNTY) {
String weatherId = countyList.get(position).getWeatherId();
if (getActivity() instanceof MainActivity) {
Intent intent = new Intent(getActivity(), WeatherActivity.class);
intent.putExtra("weather_id", weatherId);
startActivity(intent);
getActivity().finish();
} else if (getActivity() instanceof WeatherActivity) {
WeatherActivity activity = (WeatherActivity) getActivity();
activity.drawerLayout.closeDrawers();
activity.swipeRefresh.setRefreshing(true);
activity.requestWeather(weatherId);
}
}
}
});
btn_back.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (currentLevel == LEVEL_CITY) {
queryProvinces();
} else if (currentLevel == LEVEL_COUNTY) {
queryCities();
}
}
});
queryProvinces();
}
/**
* 查询全国所有的省,优先从数据库查询,如果没有查询到再去服务器上查询
*/
private void queryProvinces() {
titleText.setText("中国");
btn_back.setVisibility(View.GONE);
provinceList = DataSupport.findAll(Province.class);
if (provinceList.size() > 0) {
dataList.clear();
for (Province province : provinceList) {
dataList.add(province.getProvinceName());
}
adapter.notifyDataSetChanged();
listView.setSelection(0);
currentLevel = LEVEL_PROVINCE;
} else {
String address = "http://guolin.tech/api/china";
queryFromServer(address, "province");
}
}
/**
* 查询选中省内所有市,优先从数据库查询,如果没有查询到再去服务器上查询
*/
private void queryCities() {
titleText.setText(selectedProvince.getProvinceName());
btn_back.setVisibility(View.VISIBLE);
cityList = DataSupport.where("provinceid = ?", String.valueOf(selectedProvince.getId())).find(City.class);
if (cityList.size() > 0) {
dataList.clear();
for (City city : cityList) {
dataList.add(city.getCityName());
}
adapter.notifyDataSetChanged();
listView.setSelection(0);
currentLevel = LEVEL_CITY;
} else {
int provinceCode = selectedProvince.getProvinceCode();
String address = "http://guolin.tech/api/china/" + provinceCode;
queryFromServer(address, "city");
}
}
/**
* 查询选中市内所有县,优先从数据库查询,如果没有查询到再去服务器上查询
*/
private void queryCounties() {
titleText.setText(selectedCity.getCityName());
btn_back.setVisibility(View.VISIBLE);
countyList = DataSupport.where("cityid = ?", String.valueOf(selectedCity.getId())).find(County.class);
if (countyList.size() > 0) {
dataList.clear();
for (County county : countyList) {
dataList.add(county.getCountyName());
}
adapter.notifyDataSetChanged();
listView.setSelection(0);
currentLevel = LEVEL_COUNTY;
} else {
int provinceCode = selectedProvince.getProvinceCode();
int cityCode = selectedCity.getCitycode();
String address = "http://guolin.tech/api/china/" + provinceCode + "/" + cityCode;
queryFromServer(address, "county");
}
}
/**
* 根据传入的地址和类型从服务器上查询省市县数据
*/
private void queryFromServer(String address, final String type) {
showProgressDialog();
HttpUtil.sendOkHttpRequest(address, new Callback() {
@Override
public void onResponse(Call call, Response response) throws IOException {
String responseText = response.body().string();
boolean result = false;
if ("province".equals(type)) {
result = Utility.handleProvinceResponse(responseText);
} else if ("city".equals(type)) {
result = Utility.handleCityResponse(responseText, selectedProvince.getId());
} else if ("county".equals(type)) {
result = Utility.handleCountyResponse(responseText, selectedCity.getId());
}
if (result) {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
closeProgressDialog();
if ("province".equals(type)) {
queryProvinces();
} else if ("city".equals(type)) {
queryCities();
} else if ("county".equals(type)) {
queryCounties();
}
}
});
}
}
@Override
public void onFailure(Call call, IOException e) {
// 通过runOnUiThread()方法回到主线程处理逻辑
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
closeProgressDialog();
Toast.makeText(getContext(), "加载失败", Toast.LENGTH_SHORT).show();
}
});
}
});
}
/**
* 显示进度对话框
*/
private void showProgressDialog() {
if (progressDialog == null) {
progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("正在加载...");
progressDialog.setCanceledOnTouchOutside(false);
}
progressDialog.show();
}
/**
* 关闭进度对话框
*/
private void closeProgressDialog() {
if (progressDialog != null) {
progressDialog.dismiss();
}
}
}
| Java |
<!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_152-ea) on Sat Jul 29 21:49:13 PDT 2017 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Class com.fasterxml.jackson.datatype.jsr310.ser.YearMonthSerializer (Jackson datatype: JSR310 2.9.0 API)</title>
<meta name="date" content="2017-07-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="Uses of Class com.fasterxml.jackson.datatype.jsr310.ser.YearMonthSerializer (Jackson datatype: JSR310 2.9.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="../../../../../../../com/fasterxml/jackson/datatype/jsr310/ser/YearMonthSerializer.html" title="class in com.fasterxml.jackson.datatype.jsr310.ser">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-all.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?com/fasterxml/jackson/datatype/jsr310/ser/class-use/YearMonthSerializer.html" target="_top">Frames</a></li>
<li><a href="YearMonthSerializer.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 com.fasterxml.jackson.datatype.jsr310.ser.YearMonthSerializer" class="title">Uses of Class<br>com.fasterxml.jackson.datatype.jsr310.ser.YearMonthSerializer</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="../../../../../../../com/fasterxml/jackson/datatype/jsr310/ser/YearMonthSerializer.html" title="class in com.fasterxml.jackson.datatype.jsr310.ser">YearMonthSerializer</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="#com.fasterxml.jackson.datatype.jsr310.ser">com.fasterxml.jackson.datatype.jsr310.ser</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="com.fasterxml.jackson.datatype.jsr310.ser">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../../../com/fasterxml/jackson/datatype/jsr310/ser/YearMonthSerializer.html" title="class in com.fasterxml.jackson.datatype.jsr310.ser">YearMonthSerializer</a> in <a href="../../../../../../../com/fasterxml/jackson/datatype/jsr310/ser/package-summary.html">com.fasterxml.jackson.datatype.jsr310.ser</a></h3>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing fields, and an explanation">
<caption><span>Fields in <a href="../../../../../../../com/fasterxml/jackson/datatype/jsr310/ser/package-summary.html">com.fasterxml.jackson.datatype.jsr310.ser</a> declared as <a href="../../../../../../../com/fasterxml/jackson/datatype/jsr310/ser/YearMonthSerializer.html" title="class in com.fasterxml.jackson.datatype.jsr310.ser">YearMonthSerializer</a></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>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>static <a href="../../../../../../../com/fasterxml/jackson/datatype/jsr310/ser/YearMonthSerializer.html" title="class in com.fasterxml.jackson.datatype.jsr310.ser">YearMonthSerializer</a></code></td>
<td class="colLast"><span class="typeNameLabel">YearMonthSerializer.</span><code><span class="memberNameLink"><a href="../../../../../../../com/fasterxml/jackson/datatype/jsr310/ser/YearMonthSerializer.html#INSTANCE">INSTANCE</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="../../../../../../../com/fasterxml/jackson/datatype/jsr310/ser/package-summary.html">com.fasterxml.jackson.datatype.jsr310.ser</a> that return <a href="../../../../../../../com/fasterxml/jackson/datatype/jsr310/ser/YearMonthSerializer.html" title="class in com.fasterxml.jackson.datatype.jsr310.ser">YearMonthSerializer</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>protected <a href="../../../../../../../com/fasterxml/jackson/datatype/jsr310/ser/YearMonthSerializer.html" title="class in com.fasterxml.jackson.datatype.jsr310.ser">YearMonthSerializer</a></code></td>
<td class="colLast"><span class="typeNameLabel">YearMonthSerializer.</span><code><span class="memberNameLink"><a href="../../../../../../../com/fasterxml/jackson/datatype/jsr310/ser/YearMonthSerializer.html#withFormat-java.lang.Boolean-java.time.format.DateTimeFormatter-com.fasterxml.jackson.annotation.JsonFormat.Shape-">withFormat</a></span>(<a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Boolean.html?is-external=true" title="class or interface in java.lang">Boolean</a> useTimestamp,
java.time.format.DateTimeFormatter formatter,
com.fasterxml.jackson.annotation.JsonFormat.Shape shape)</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="../../../../../../../com/fasterxml/jackson/datatype/jsr310/ser/YearMonthSerializer.html" title="class in com.fasterxml.jackson.datatype.jsr310.ser">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-all.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?com/fasterxml/jackson/datatype/jsr310/ser/class-use/YearMonthSerializer.html" target="_top">Frames</a></li>
<li><a href="YearMonthSerializer.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://fasterxml.com/">FasterXML</a>. All rights reserved.</small></p>
</body>
</html>
| Java |
#
#Programa Lista 4, questão 1;
#Felipe Henrique Bastos Costa - 1615310032;
#
#
#
#
lista = []#lista vazia;
cont1 = 0#contador do indice;
cont2 = 1#contador da posição do numero, se é o primeiro, segundo etc;
v = 5#representaria o len da lista;
while(cont1 < v):
x = int(input("Informe o %dº numero inteiro para colocar em sua lista:\n"%cont2))#x e a variavel que recebe
#o numero do usuario
lista.append(x)#o numero informado para x e colocado dentro da lista;
cont1+=1#Os contadores estao
cont2+=1#sendo incrementados;
print("A lista de informada foi:\n%s"%lista)
| Java |
/*
* proto/v1beta1/grafeas.proto
*
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* API version: version not set
* Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git)
*/
package grafeas
import (
"time"
)
// An instance of an analysis type that has been found on a resource.
type V1beta1Occurrence struct {
// Output only. The name of the occurrence in the form of `projects/[PROJECT_ID]/occurrences/[OCCURRENCE_ID]`.
Name string `json:"name,omitempty"`
// Required. Immutable. The resource for which the occurrence applies.
Resource *V1beta1Resource `json:"resource,omitempty"`
// Required. Immutable. The analysis note associated with this occurrence, in the form of `projects/[PROVIDER_ID]/notes/[NOTE_ID]`. This field can be used as a filter in list requests.
NoteName string `json:"note_name,omitempty"`
// Output only. This explicitly denotes which of the occurrence details are specified. This field can be used as a filter in list requests.
Kind *V1beta1NoteKind `json:"kind,omitempty"`
// A description of actions that can be taken to remedy the note.
Remediation string `json:"remediation,omitempty"`
// Output only. The time this occurrence was created.
CreateTime time.Time `json:"create_time,omitempty"`
// Output only. The time this occurrence was last updated.
UpdateTime time.Time `json:"update_time,omitempty"`
// Describes a security vulnerability.
Vulnerability *V1beta1vulnerabilityDetails `json:"vulnerability,omitempty"`
// Describes a verifiable build.
Build *V1beta1buildDetails `json:"build,omitempty"`
// Describes how this resource derives from the basis in the associated note.
DerivedImage *V1beta1imageDetails `json:"derived_image,omitempty"`
// Describes the installation of a package on the linked resource.
Installation *V1beta1packageDetails `json:"installation,omitempty"`
// Describes the deployment of an artifact on a runtime.
Deployment *V1beta1deploymentDetails `json:"deployment,omitempty"`
// Describes when a resource was discovered.
Discovered *V1beta1discoveryDetails `json:"discovered,omitempty"`
// Describes an attestation of an artifact.
Attestation *V1beta1attestationDetails `json:"attestation,omitempty"`
}
| Java |
---
date: 2016-09-13T09:00:00+00:00
title: Community support
type: page
layout: overview
aliases:
- /community/
---
Vamp Community Edition is open source and Apache 2.0 licensed. For details of the **Vamp Enterprise Edition** please check the [Vamp feature matrix](/product/enterprise-edition/), [start a free trial] (/ee-trial-signup/), or [contact us](mailto:info@vamp.io) to discuss your requirements, pricing and features.
## Community support
If you have a question about Vamp, please check the [Vamp documentation](/documentation/using-vamp/artifacts) first - we're always adding new resources, tutorials and examples.
* **Bug reports:** If you found a bug, please report it! [Create an issue on GitHub](https://github.com/magneticio/vamp/issues) and provide as much info as you can, specifically the version of Vamp you are running and the container driver you are using.
* **Gitter:** You can post questions directly to us on our [public Gitter channel](https://gitter.im/magneticio/vamp)
* **Twitter:** You can also follow us on Twitter: [@vamp_io](https://twitter.com/vamp_io)
| Java |
#include "stdafx.h"
#include "InputReader.h"
#include "graph.h"
#include <iostream>
#include <string>
using namespace std;
InputReader::InputReader(const char* fileName, const char* stFileName)
{
in.open(fileName);
if(!in.is_open())
{
cout<<"Input file "<<fileName<<" doesn't exist!"<<endl;
exit(1);
}
stIn.open(stFileName);
if(!stIn.is_open())
{
cout<<"Input file "<<stFileName<<" doesn't exist!"<<endl;
in.close();
exit(1);
}
}
InputReader::~InputReader()
{
in.close();
stIn.close();
}
void InputReader::ReadFirstLine()
{
in>>strLine;
assert(strLine[0] == 'g');
in>>strLine;
assert(strLine[0] == '#');
in>> gId;
}
bool InputReader::ReadGraph(Graph &g)
{
ReadFirstLine();
if(gId == 0)
{
return false; /*ÒѾûÓÐͼ*/
}
g.nId = gId;
in>>strLine;
assert(strLine[0] == 's'); /*¶ÁÈ¡¶¥µãÊýºÍ±ßÊý*/
in>>g.nV>>g.nE;
assert(g.nV < MAX); /*·ÀÖ¹ÁÚ½Ó¾ØÕó´óС²»¹»ÓÃ*/
/*ÏÂÃæ¶ÁÈ¡±ßµÄÐÅÏ¢*/
int u,v; /*u,vÊÇÒ»Ìõ±ßµÄÁ½¸ö¶¥µã*/
for(int i = 1; i <= g.nE; i++)
{
in>>strLine;
assert(strLine[0] == 'e');
in>>u>>v; /*×¢ÒâÕâ¸ö²»ÄÜÓëÏÂÃæµÄдµ½Ò»Æð*/
in>>g.matrix[u][v].iC>>g.matrix[u][v].dP>>g.matrix[u][v].iLabel;
}
return true;
}
void InputReader::ReadSourceSink(int &s, int &t)
{
stIn>>s>>t;
} | Java |
<?php
namespace Illuminate\Database\Eloquent;
use Closure;
use BadMethodCallException;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use Illuminate\Pagination\Paginator;
use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Database\Concerns\BuildsQueries;
use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Database\Query\Builder as QueryBuilder;
/**
* @mixin \Illuminate\Database\Query\Builder
*/
class Builder
{
use BuildsQueries, Concerns\QueriesRelationships;
/**
* The base query builder instance.
*
* @var \Illuminate\Database\Query\Builder
*/
protected $query;
/**
* The model being queried.
*
* @var \Illuminate\Database\Eloquent\Model
*/
protected $model;
/**
* The relationships that should be eager loaded.
*
* @var array
*/
protected $eagerLoad = [];
/**
* All of the globally registered builder macros.
*
* @var array
*/
protected static $macros = [];
/**
* All of the locally registered builder macros.
*
* @var array
*/
protected $localMacros = [];
/**
* A replacement for the typical delete function.
*
* @var \Closure
*/
protected $onDelete;
/**
* The methods that should be returned from query builder.
*
* @var array
*/
protected $passthru = [
'insert', 'insertGetId', 'getBindings', 'toSql',
'exists', 'doesntExist', 'count', 'min', 'max', 'avg', 'sum', 'getConnection',
];
/**
* Applied global scopes.
*
* @var array
*/
protected $scopes = [];
/**
* Removed global scopes.
*
* @var array
*/
protected $removedScopes = [];
/**
* Create a new Eloquent query builder instance.
*
* @param \Illuminate\Database\Query\Builder $query
* @return void
*/
public function __construct(QueryBuilder $query)
{
$this->query = $query;
}
/**
* Create and return an un-saved model instance.
*
* @param array $attributes
* @return \Illuminate\Database\Eloquent\Model
*/
public function make(array $attributes = [])
{
return $this->newModelInstance($attributes);
}
/**
* Register a new global scope.
*
* @param string $identifier
* @param \Illuminate\Database\Eloquent\Scope|\Closure $scope
* @return $this
*/
public function withGlobalScope($identifier, $scope)
{
$this->scopes[$identifier] = $scope;
if (method_exists($scope, 'extend')) {
$scope->extend($this);
}
return $this;
}
/**
* Remove a registered global scope.
*
* @param \Illuminate\Database\Eloquent\Scope|string $scope
* @return $this
*/
public function withoutGlobalScope($scope)
{
if (! is_string($scope)) {
$scope = get_class($scope);
}
unset($this->scopes[$scope]);
$this->removedScopes[] = $scope;
return $this;
}
/**
* Remove all or passed registered global scopes.
*
* @param array|null $scopes
* @return $this
*/
public function withoutGlobalScopes(array $scopes = null)
{
if (is_array($scopes)) {
foreach ($scopes as $scope) {
$this->withoutGlobalScope($scope);
}
} else {
$this->scopes = [];
}
return $this;
}
/**
* Get an array of global scopes that were removed from the query.
*
* @return array
*/
public function removedScopes()
{
return $this->removedScopes;
}
/**
* Add a where clause on the primary key to the query.
*
* @param mixed $id
* @return $this
*/
public function whereKey($id)
{
if (is_array($id) || $id instanceof Arrayable) {
$this->query->whereIn($this->model->getQualifiedKeyName(), $id);
return $this;
}
return $this->where($this->model->getQualifiedKeyName(), '=', $id);
}
/**
* Add a where clause on the primary key to the query.
*
* @param mixed $id
* @return $this
*/
public function whereKeyNot($id)
{
if (is_array($id) || $id instanceof Arrayable) {
$this->query->whereNotIn($this->model->getQualifiedKeyName(), $id);
return $this;
}
return $this->where($this->model->getQualifiedKeyName(), '!=', $id);
}
/**
* Add a basic where clause to the query.
*
* @param string|array|\Closure $column
* @param string $operator
* @param mixed $value
* @param string $boolean
* @return $this
*/
public function where($column, $operator = null, $value = null, $boolean = 'and')
{
if ($column instanceof Closure) {
$column($query = $this->model->newModelQuery());
$this->query->addNestedWhereQuery($query->getQuery(), $boolean);
} else {
$this->query->where(...func_get_args());
}
return $this;
}
/**
* Add an "or where" clause to the query.
*
* @param \Closure|array|string $column
* @param string $operator
* @param mixed $value
* @return \Illuminate\Database\Eloquent\Builder|static
*/
public function orWhere($column, $operator = null, $value = null)
{
list($value, $operator) = $this->query->prepareValueAndOperator(
$value, $operator, func_num_args() == 2
);
return $this->where($column, $operator, $value, 'or');
}
/**
* Create a collection of models from plain arrays.
*
* @param array $items
* @return \Illuminate\Database\Eloquent\Collection
*/
public function hydrate(array $items)
{
$instance = $this->newModelInstance();
return $instance->newCollection(array_map(function ($item) use ($instance) {
return $instance->newFromBuilder($item);
}, $items));
}
/**
* Create a collection of models from a raw query.
*
* @param string $query
* @param array $bindings
* @return \Illuminate\Database\Eloquent\Collection
*/
public function fromQuery($query, $bindings = [])
{
return $this->hydrate(
$this->query->getConnection()->select($query, $bindings)
);
}
/**
* Find a model by its primary key.
*
* @param mixed $id
* @param array $columns
* @return \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Collection|static[]|static|null
*/
public function find($id, $columns = ['*'])
{
if (is_array($id) || $id instanceof Arrayable) {
return $this->findMany($id, $columns);
}
return $this->whereKey($id)->first($columns);
}
/**
* Find multiple models by their primary keys.
*
* @param \Illuminate\Contracts\Support\Arrayable|array $ids
* @param array $columns
* @return \Illuminate\Database\Eloquent\Collection
*/
public function findMany($ids, $columns = ['*'])
{
if (empty($ids)) {
return $this->model->newCollection();
}
return $this->whereKey($ids)->get($columns);
}
/**
* Find a model by its primary key or throw an exception.
*
* @param mixed $id
* @param array $columns
* @return \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Collection
*
* @throws \Illuminate\Database\Eloquent\ModelNotFoundException
*/
public function findOrFail($id, $columns = ['*'])
{
$result = $this->find($id, $columns);
if (is_array($id)) {
if (count($result) == count(array_unique($id))) {
return $result;
}
} elseif (! is_null($result)) {
return $result;
}
throw (new ModelNotFoundException)->setModel(
get_class($this->model), $id
);
}
/**
* Find a model by its primary key or return fresh model instance.
*
* @param mixed $id
* @param array $columns
* @return \Illuminate\Database\Eloquent\Model
*/
public function findOrNew($id, $columns = ['*'])
{
if (! is_null($model = $this->find($id, $columns))) {
return $model;
}
return $this->newModelInstance();
}
/**
* Get the first record matching the attributes or instantiate it.
*
* @param array $attributes
* @param array $values
* @return \Illuminate\Database\Eloquent\Model
*/
public function firstOrNew(array $attributes, array $values = [])
{
if (! is_null($instance = $this->where($attributes)->first())) {
return $instance;
}
return $this->newModelInstance($attributes + $values);
}
/**
* Get the first record matching the attributes or create it.
*
* @param array $attributes
* @param array $values
* @return \Illuminate\Database\Eloquent\Model
*/
public function firstOrCreate(array $attributes, array $values = [])
{
if (! is_null($instance = $this->where($attributes)->first())) {
return $instance;
}
return tap($this->newModelInstance($attributes + $values), function ($instance) {
$instance->save();
});
}
/**
* Create or update a record matching the attributes, and fill it with values.
*
* @param array $attributes
* @param array $values
* @return \Illuminate\Database\Eloquent\Model
*/
public function updateOrCreate(array $attributes, array $values = [])
{
return tap($this->firstOrNew($attributes), function ($instance) use ($values) {
$instance->fill($values)->save();
});
}
/**
* Execute the query and get the first result or throw an exception.
*
* @param array $columns
* @return \Illuminate\Database\Eloquent\Model|static
*
* @throws \Illuminate\Database\Eloquent\ModelNotFoundException
*/
public function firstOrFail($columns = ['*'])
{
if (! is_null($model = $this->first($columns))) {
return $model;
}
throw (new ModelNotFoundException)->setModel(get_class($this->model));
}
/**
* Execute the query and get the first result or call a callback.
*
* @param \Closure|array $columns
* @param \Closure|null $callback
* @return \Illuminate\Database\Eloquent\Model|static|mixed
*/
public function firstOr($columns = ['*'], Closure $callback = null)
{
if ($columns instanceof Closure) {
$callback = $columns;
$columns = ['*'];
}
if (! is_null($model = $this->first($columns))) {
return $model;
}
return call_user_func($callback);
}
/**
* Get a single column's value from the first result of a query.
*
* @param string $column
* @return mixed
*/
public function value($column)
{
if ($result = $this->first([$column])) {
return $result->{$column};
}
}
/**
* Execute the query as a "select" statement.
*
* @param array $columns
* @return \Illuminate\Database\Eloquent\Collection|static[]
*/
public function get($columns = ['*'])
{
$builder = $this->applyScopes();
// If we actually found models we will also eager load any relationships that
// have been specified as needing to be eager loaded, which will solve the
// n+1 query issue for the developers to avoid running a lot of queries.
if (count($models = $builder->getModels($columns)) > 0) {
$models = $builder->eagerLoadRelations($models);
}
return $builder->getModel()->newCollection($models);
}
/**
* Get the hydrated models without eager loading.
*
* @param array $columns
* @return \Illuminate\Database\Eloquent\Model[]
*/
public function getModels($columns = ['*'])
{
return $this->model->hydrate(
$this->query->get($columns)->all()
)->all();
}
/**
* Eager load the relationships for the models.
*
* @param array $models
* @return array
*/
public function eagerLoadRelations(array $models)
{
foreach ($this->eagerLoad as $name => $constraints) {
// For nested eager loads we'll skip loading them here and they will be set as an
// eager load on the query to retrieve the relation so that they will be eager
// loaded on that query, because that is where they get hydrated as models.
if (strpos($name, '.') === false) {
$models = $this->eagerLoadRelation($models, $name, $constraints);
}
}
return $models;
}
/**
* Eagerly load the relationship on a set of models.
*
* @param array $models
* @param string $name
* @param \Closure $constraints
* @return array
*/
protected function eagerLoadRelation(array $models, $name, Closure $constraints)
{
// First we will "back up" the existing where conditions on the query so we can
// add our eager constraints. Then we will merge the wheres that were on the
// query back to it in order that any where conditions might be specified.
$relation = $this->getRelation($name);
$relation->addEagerConstraints($models);
$constraints($relation);
// Once we have the results, we just match those back up to their parent models
// using the relationship instance. Then we just return the finished arrays
// of models which have been eagerly hydrated and are readied for return.
return $relation->match(
$relation->initRelation($models, $name),
$relation->getEager(), $name
);
}
/**
* Get the relation instance for the given relation name.
*
* @param string $name
* @return \Illuminate\Database\Eloquent\Relations\Relation
*/
public function getRelation($name)
{
// We want to run a relationship query without any constrains so that we will
// not have to remove these where clauses manually which gets really hacky
// and error prone. We don't want constraints because we add eager ones.
$relation = Relation::noConstraints(function () use ($name) {
try {
return $this->getModel()->newInstance()->$name();
} catch (BadMethodCallException $e) {
throw RelationNotFoundException::make($this->getModel(), $name);
}
});
$nested = $this->relationsNestedUnder($name);
// If there are nested relationships set on the query, we will put those onto
// the query instances so that they can be handled after this relationship
// is loaded. In this way they will all trickle down as they are loaded.
if (count($nested) > 0) {
$relation->getQuery()->with($nested);
}
return $relation;
}
/**
* Get the deeply nested relations for a given top-level relation.
*
* @param string $relation
* @return array
*/
protected function relationsNestedUnder($relation)
{
$nested = [];
// We are basically looking for any relationships that are nested deeper than
// the given top-level relationship. We will just check for any relations
// that start with the given top relations and adds them to our arrays.
foreach ($this->eagerLoad as $name => $constraints) {
if ($this->isNestedUnder($relation, $name)) {
$nested[substr($name, strlen($relation.'.'))] = $constraints;
}
}
return $nested;
}
/**
* Determine if the relationship is nested.
*
* @param string $relation
* @param string $name
* @return bool
*/
protected function isNestedUnder($relation, $name)
{
return Str::contains($name, '.') && Str::startsWith($name, $relation.'.');
}
/**
* Get a generator for the given query.
*
* @return \Generator
*/
public function cursor()
{
foreach ($this->applyScopes()->query->cursor() as $record) {
yield $this->model->newFromBuilder($record);
}
}
/**
* Chunk the results of a query by comparing numeric IDs.
*
* @param int $count
* @param callable $callback
* @param string $column
* @param string|null $alias
* @return bool
*/
public function chunkById($count, callable $callback, $column = null, $alias = null)
{
$column = is_null($column) ? $this->getModel()->getKeyName() : $column;
$alias = is_null($alias) ? $column : $alias;
$lastId = 0;
do {
$clone = clone $this;
// We'll execute the query for the given page and get the results. If there are
// no results we can just break and return from here. When there are results
// we will call the callback with the current chunk of these results here.
$results = $clone->forPageAfterId($count, $lastId, $column)->get();
$countResults = $results->count();
if ($countResults == 0) {
break;
}
// On each chunk result set, we will pass them to the callback and then let the
// developer take care of everything within the callback, which allows us to
// keep the memory low for spinning through large result sets for working.
if ($callback($results) === false) {
return false;
}
$lastId = $results->last()->{$alias};
unset($results);
} while ($countResults == $count);
return true;
}
/**
* Add a generic "order by" clause if the query doesn't already have one.
*
* @return void
*/
protected function enforceOrderBy()
{
if (empty($this->query->orders) && empty($this->query->unionOrders)) {
$this->orderBy($this->model->getQualifiedKeyName(), 'asc');
}
}
/**
* Get an array with the values of a given column.
*
* @param string $column
* @param string|null $key
* @return \Illuminate\Support\Collection
*/
public function pluck($column, $key = null)
{
$results = $this->toBase()->pluck($column, $key);
// If the model has a mutator for the requested column, we will spin through
// the results and mutate the values so that the mutated version of these
// columns are returned as you would expect from these Eloquent models.
if (! $this->model->hasGetMutator($column) &&
! $this->model->hasCast($column) &&
! in_array($column, $this->model->getDates())) {
return $results;
}
return $results->map(function ($value) use ($column) {
return $this->model->newFromBuilder([$column => $value])->{$column};
});
}
/**
* Paginate the given query.
*
* @param int $perPage
* @param array $columns
* @param string $pageName
* @param int|null $page
* @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
*
* @throws \InvalidArgumentException
*/
public function paginate($perPage = null, $columns = ['*'], $pageName = 'page', $page = null)
{
$page = $page ?: Paginator::resolveCurrentPage($pageName);
$perPage = $perPage ?: $this->model->getPerPage();
$results = ($total = $this->toBase()->getCountForPagination())
? $this->forPage($page, $perPage)->get($columns)
: $this->model->newCollection();
return $this->paginator($results, $total, $perPage, $page, [
'path' => Paginator::resolveCurrentPath(),
'pageName' => $pageName,
]);
}
/**
* Paginate the given query into a simple paginator.
*
* @param int $perPage
* @param array $columns
* @param string $pageName
* @param int|null $page
* @return \Illuminate\Contracts\Pagination\Paginator
*/
public function simplePaginate($perPage = null, $columns = ['*'], $pageName = 'page', $page = null)
{
$page = $page ?: Paginator::resolveCurrentPage($pageName);
$perPage = $perPage ?: $this->model->getPerPage();
// Next we will set the limit and offset for this query so that when we get the
// results we get the proper section of results. Then, we'll create the full
// paginator instances for these results with the given page and per page.
$this->skip(($page - 1) * $perPage)->take($perPage + 1);
return $this->simplePaginator($this->get($columns), $perPage, $page, [
'path' => Paginator::resolveCurrentPath(),
'pageName' => $pageName,
]);
}
/**
* Save a new model and return the instance.
*
* @param array $attributes
* @return \Illuminate\Database\Eloquent\Model|$this
*/
public function create(array $attributes = [])
{
return tap($this->newModelInstance($attributes), function ($instance) {
$instance->save();
});
}
/**
* Save a new model and return the instance. Allow mass-assignment.
*
* @param array $attributes
* @return \Illuminate\Database\Eloquent\Model|$this
*/
public function forceCreate(array $attributes)
{
return $this->model->unguarded(function () use ($attributes) {
return $this->newModelInstance()->create($attributes);
});
}
/**
* Update a record in the database.
*
* @param array $values
* @return int
*/
public function update(array $values)
{
return $this->toBase()->update($this->addUpdatedAtColumn($values));
}
/**
* Increment a column's value by a given amount.
*
* @param string $column
* @param int $amount
* @param array $extra
* @return int
*/
public function increment($column, $amount = 1, array $extra = [])
{
return $this->toBase()->increment(
$column, $amount, $this->addUpdatedAtColumn($extra)
);
}
/**
* Decrement a column's value by a given amount.
*
* @param string $column
* @param int $amount
* @param array $extra
* @return int
*/
public function decrement($column, $amount = 1, array $extra = [])
{
return $this->toBase()->decrement(
$column, $amount, $this->addUpdatedAtColumn($extra)
);
}
/**
* Add the "updated at" column to an array of values.
*
* @param array $values
* @return array
*/
protected function addUpdatedAtColumn(array $values)
{
if (! $this->model->usesTimestamps()) {
return $values;
}
return Arr::add(
$values, $this->model->getUpdatedAtColumn(),
$this->model->freshTimestampString()
);
}
/**
* Delete a record from the database.
*
* @return mixed
*/
public function delete()
{
if (isset($this->onDelete)) {
return call_user_func($this->onDelete, $this);
}
return $this->toBase()->delete();
}
/**
* Run the default delete function on the builder.
*
* Since we do not apply scopes here, the row will actually be deleted.
*
* @return mixed
*/
public function forceDelete()
{
return $this->query->delete();
}
/**
* Register a replacement for the default delete function.
*
* @param \Closure $callback
* @return void
*/
public function onDelete(Closure $callback)
{
$this->onDelete = $callback;
}
/**
* Call the given local model scopes.
*
* @param array $scopes
* @return mixed
*/
public function scopes(array $scopes)
{
$builder = $this;
foreach ($scopes as $scope => $parameters) {
// If the scope key is an integer, then the scope was passed as the value and
// the parameter list is empty, so we will format the scope name and these
// parameters here. Then, we'll be ready to call the scope on the model.
if (is_int($scope)) {
list($scope, $parameters) = [$parameters, []];
}
// Next we'll pass the scope callback to the callScope method which will take
// care of grouping the "wheres" properly so the logical order doesn't get
// messed up when adding scopes. Then we'll return back out the builder.
$builder = $builder->callScope(
[$this->model, 'scope'.ucfirst($scope)],
(array) $parameters
);
}
return $builder;
}
/**
* Apply the scopes to the Eloquent builder instance and return it.
*
* @return \Illuminate\Database\Eloquent\Builder|static
*/
public function applyScopes()
{
if (! $this->scopes) {
return $this;
}
$builder = clone $this;
foreach ($this->scopes as $identifier => $scope) {
if (! isset($builder->scopes[$identifier])) {
continue;
}
$builder->callScope(function (Builder $builder) use ($scope) {
// If the scope is a Closure we will just go ahead and call the scope with the
// builder instance. The "callScope" method will properly group the clauses
// that are added to this query so "where" clauses maintain proper logic.
if ($scope instanceof Closure) {
$scope($builder);
}
// If the scope is a scope object, we will call the apply method on this scope
// passing in the builder and the model instance. After we run all of these
// scopes we will return back the builder instance to the outside caller.
if ($scope instanceof Scope) {
$scope->apply($builder, $this->getModel());
}
});
}
return $builder;
}
/**
* Apply the given scope on the current builder instance.
*
* @param callable $scope
* @param array $parameters
* @return mixed
*/
protected function callScope(callable $scope, $parameters = [])
{
array_unshift($parameters, $this);
$query = $this->getQuery();
// We will keep track of how many wheres are on the query before running the
// scope so that we can properly group the added scope constraints in the
// query as their own isolated nested where statement and avoid issues.
$originalWhereCount = is_null($query->wheres)
? 0 : count($query->wheres);
$result = $scope(...array_values($parameters)) ?? $this;
if (count((array) $query->wheres) > $originalWhereCount) {
$this->addNewWheresWithinGroup($query, $originalWhereCount);
}
return $result;
}
/**
* Nest where conditions by slicing them at the given where count.
*
* @param \Illuminate\Database\Query\Builder $query
* @param int $originalWhereCount
* @return void
*/
protected function addNewWheresWithinGroup(QueryBuilder $query, $originalWhereCount)
{
// Here, we totally remove all of the where clauses since we are going to
// rebuild them as nested queries by slicing the groups of wheres into
// their own sections. This is to prevent any confusing logic order.
$allWheres = $query->wheres;
$query->wheres = [];
$this->groupWhereSliceForScope(
$query, array_slice($allWheres, 0, $originalWhereCount)
);
$this->groupWhereSliceForScope(
$query, array_slice($allWheres, $originalWhereCount)
);
}
/**
* Slice where conditions at the given offset and add them to the query as a nested condition.
*
* @param \Illuminate\Database\Query\Builder $query
* @param array $whereSlice
* @return void
*/
protected function groupWhereSliceForScope(QueryBuilder $query, $whereSlice)
{
$whereBooleans = collect($whereSlice)->pluck('boolean');
// Here we'll check if the given subset of where clauses contains any "or"
// booleans and in this case create a nested where expression. That way
// we don't add any unnecessary nesting thus keeping the query clean.
if ($whereBooleans->contains('or')) {
$query->wheres[] = $this->createNestedWhere(
$whereSlice, $whereBooleans->first()
);
} else {
$query->wheres = array_merge($query->wheres, $whereSlice);
}
}
/**
* Create a where array with nested where conditions.
*
* @param array $whereSlice
* @param string $boolean
* @return array
*/
protected function createNestedWhere($whereSlice, $boolean = 'and')
{
$whereGroup = $this->getQuery()->forNestedWhere();
$whereGroup->wheres = $whereSlice;
return ['type' => 'Nested', 'query' => $whereGroup, 'boolean' => $boolean];
}
/**
* Set the relationships that should be eager loaded.
*
* @param mixed $relations
* @return $this
*/
public function with($relations)
{
$eagerLoad = $this->parseWithRelations(is_string($relations) ? func_get_args() : $relations);
$this->eagerLoad = array_merge($this->eagerLoad, $eagerLoad);
return $this;
}
/**
* Prevent the specified relations from being eager loaded.
*
* @param mixed $relations
* @return $this
*/
public function without($relations)
{
$this->eagerLoad = array_diff_key($this->eagerLoad, array_flip(
is_string($relations) ? func_get_args() : $relations
));
return $this;
}
/**
* Create a new instance of the model being queried.
*
* @param array $attributes
* @return \Illuminate\Database\Eloquent\Model
*/
public function newModelInstance($attributes = [])
{
return $this->model->newInstance($attributes)->setConnection(
$this->query->getConnection()->getName()
);
}
/**
* Parse a list of relations into individuals.
*
* @param array $relations
* @return array
*/
protected function parseWithRelations(array $relations)
{
$results = [];
foreach ($relations as $name => $constraints) {
// If the "relation" value is actually a numeric key, we can assume that no
// constraints have been specified for the eager load and we'll just put
// an empty Closure with the loader so that we can treat all the same.
if (is_numeric($name)) {
$name = $constraints;
list($name, $constraints) = Str::contains($name, ':')
? $this->createSelectWithConstraint($name)
: [$name, function () {
//
}];
}
// We need to separate out any nested includes. Which allows the developers
// to load deep relationships using "dots" without stating each level of
// the relationship with its own key in the array of eager load names.
$results = $this->addNestedWiths($name, $results);
$results[$name] = $constraints;
}
return $results;
}
/**
* Create a constraint to select the given columns for the relation.
*
* @param string $name
* @return array
*/
protected function createSelectWithConstraint($name)
{
return [explode(':', $name)[0], function ($query) use ($name) {
$query->select(explode(',', explode(':', $name)[1]));
}];
}
/**
* Parse the nested relationships in a relation.
*
* @param string $name
* @param array $results
* @return array
*/
protected function addNestedWiths($name, $results)
{
$progress = [];
// If the relation has already been set on the result array, we will not set it
// again, since that would override any constraints that were already placed
// on the relationships. We will only set the ones that are not specified.
foreach (explode('.', $name) as $segment) {
$progress[] = $segment;
if (! isset($results[$last = implode('.', $progress)])) {
$results[$last] = function () {
//
};
}
}
return $results;
}
/**
* Get the underlying query builder instance.
*
* @return \Illuminate\Database\Query\Builder
*/
public function getQuery()
{
return $this->query;
}
/**
* Set the underlying query builder instance.
*
* @param \Illuminate\Database\Query\Builder $query
* @return $this
*/
public function setQuery($query)
{
$this->query = $query;
return $this;
}
/**
* Get a base query builder instance.
*
* @return \Illuminate\Database\Query\Builder
*/
public function toBase()
{
return $this->applyScopes()->getQuery();
}
/**
* Get the relationships being eagerly loaded.
*
* @return array
*/
public function getEagerLoads()
{
return $this->eagerLoad;
}
/**
* Set the relationships being eagerly loaded.
*
* @param array $eagerLoad
* @return $this
*/
public function setEagerLoads(array $eagerLoad)
{
$this->eagerLoad = $eagerLoad;
return $this;
}
/**
* Get the model instance being queried.
*
* @return \Illuminate\Database\Eloquent\Model
*/
public function getModel()
{
return $this->model;
}
/**
* Set a model instance for the model being queried.
*
* @param \Illuminate\Database\Eloquent\Model $model
* @return $this
*/
public function setModel(Model $model)
{
$this->model = $model;
$this->query->from($model->getTable());
return $this;
}
/**
* Qualify the given column name by the model's table.
*
* @param string $column
* @return string
*/
public function qualifyColumn($column)
{
return $this->model->qualifyColumn($column);
}
/**
* Get the given macro by name.
*
* @param string $name
* @return \Closure
*/
public function getMacro($name)
{
return Arr::get($this->localMacros, $name);
}
/**
* Dynamically handle calls into the query instance.
*
* @param string $method
* @param array $parameters
* @return mixed
*/
public function __call($method, $parameters)
{
if ($method === 'macro') {
$this->localMacros[$parameters[0]] = $parameters[1];
return;
}
if (isset($this->localMacros[$method])) {
array_unshift($parameters, $this);
return $this->localMacros[$method](...$parameters);
}
if (isset(static::$macros[$method])) {
if (static::$macros[$method] instanceof Closure) {
return call_user_func_array(static::$macros[$method]->bindTo($this, static::class), $parameters);
}
return call_user_func_array(static::$macros[$method], $parameters);
}
if (method_exists($this->model, $scope = 'scope'.ucfirst($method))) {
return $this->callScope([$this->model, $scope], $parameters);
}
if (in_array($method, $this->passthru)) {
return $this->toBase()->{$method}(...$parameters);
}
$this->query->{$method}(...$parameters);
return $this;
}
/**
* Dynamically handle calls into the query instance.
*
* @param string $method
* @param array $parameters
* @return mixed
*
* @throws \BadMethodCallException
*/
public static function __callStatic($method, $parameters)
{
if ($method === 'macro') {
static::$macros[$parameters[0]] = $parameters[1];
return;
}
if (! isset(static::$macros[$method])) {
throw new BadMethodCallException("Method {$method} does not exist.");
}
if (static::$macros[$method] instanceof Closure) {
return call_user_func_array(Closure::bind(static::$macros[$method], null, static::class), $parameters);
}
return call_user_func_array(static::$macros[$method], $parameters);
}
/**
* Force a clone of the underlying query builder when cloning.
*
* @return void
*/
public function __clone()
{
$this->query = clone $this->query;
}
}
| Java |
package operationExtensibility.tests;
import static org.junit.Assert.assertEquals;
import org.junit.BeforeClass;
import org.junit.Test;
import operationExtensibility.*;
public class TestEvaluator {
private static Visitor<Integer> v;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
v = new Evaluator();
}
@Test
public void testLit() {
Lit x = new Lit();
x.setInfo(42);
assertEquals("evaluate a literal", 42, x.accept(v));
}
@Test
public void testAdd() {
Add x = new Add();
Lit y = new Lit();
y.setInfo(1);
x.setLeft(y);
y = new Lit();
y.setInfo(2);
x.setRight(y);
assertEquals("evaluate addition", 3, x.accept(v));
}
}
| Java |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using AspNetCoreTodo.Models;
namespace AspNetCoreTodo.Services
{
public interface ITodoItemService
{
Task<IEnumerable<TodoItem>> GetIncompleteItemsAsync(ApplicationUser user);
Task<bool> AddItemAsync(NewTodoItem newItem, ApplicationUser user);
Task<bool> MarkDoneAsync(Guid id, ApplicationUser user);
}
} | Java |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Frameset//EN""http://www.w3.org/TR/REC-html40/frameset.dtd">
<HTML>
<HEAD>
<meta name="generator" content="JDiff v1.0.9">
<!-- Generated by the JDiff Javadoc doclet -->
<!-- (http://www.jdiff.org) -->
<meta name="description" content="JDiff is a Javadoc doclet which generates an HTML report of all the packages, classes, constructors, methods, and fields which have been removed, added or changed in any way, including their documentation, when two APIs are compared.">
<meta name="keywords" content="diff, jdiff, javadiff, java diff, java difference, API difference, difference between two APIs, API diff, Javadoc, doclet">
<TITLE>
org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.PigSecondaryKeyComparator
</TITLE>
<LINK REL="stylesheet" TYPE="text/css" HREF="../stylesheet-jdiff.css" TITLE="Style">
</HEAD>
<BODY>
<!-- Start of nav bar -->
<TABLE summary="Navigation bar" BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<TABLE summary="Navigation bar" BORDER="0" CELLPADDING="0" CELLSPACING="3">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../api/org/apache/pig/backend/hadoop/executionengine/mapReduceLayer/PigSecondaryKeyComparator.html" target="_top"><FONT CLASS="NavBarFont1"><B><tt>pig 0.8.0-CDH3B4-SNAPSHOT</tt></B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="changes-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="pkg_org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="jdiff_statistics.html"><FONT CLASS="NavBarFont1"><B>Statistics</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="jdiff_help.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM><b>Generated by<br><a href="http://www.jdiff.org" class="staysblack" target="_top">JDiff</a></b></EM></TD>
</TR>
<TR>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.PigRecordReader.html"><B>PREV CLASS</B></A>
<A HREF="org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.PigSplit.html"><B>NEXT CLASS</B></A>
<A HREF="../changes.html" TARGET="_top"><B>FRAMES</B></A>
<A HREF="org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.PigSecondaryKeyComparator.html" TARGET="_top"><B>NO FRAMES</B></A></FONT></TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:
<a href="#constructors">CONSTRUCTORS</a> |
<a href="#methods">METHODS</a> |
FIELDS
</FONT></TD>
</TR>
</TABLE>
<HR>
<!-- End of nav bar -->
<H2>
Class org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.<A HREF="../../api/org/apache/pig/backend/hadoop/executionengine/mapReduceLayer/PigSecondaryKeyComparator.html" target="_top"><tt>PigSecondaryKeyComparator</tt></A>
</H2>
<a NAME="constructors"></a>
<p>
<a NAME="Changed"></a>
<TABLE summary="Changed Constructors" BORDER="1" CELLPADDING="3" CELLSPACING="0" WIDTH="100%">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TD VALIGN="TOP" COLSPAN=3><FONT SIZE="+1"><B>Changed Constructors</B></FONT></TD>
</TR>
<TR BGCOLOR="#FFFFFF" CLASS="TableRowColor">
<TD VALIGN="TOP" WIDTH="25%">
<A NAME="org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.PigSecondaryKeyComparator.ctor_changed()"></A>
<nobr><A HREF="../../api/org/apache/pig/backend/hadoop/executionengine/mapReduceLayer/PigSecondaryKeyComparator.html#PigSecondaryKeyComparator()" target="_top"><tt>PigSecondaryKeyComparator</tt></A>(<code>void</code>) </nobr>
</TD>
<TD VALIGN="TOP" WIDTH="30%">
Change of visibility from public to protected.<br>
</TD>
<TD> </TD>
</TR>
</TABLE>
<a NAME="methods"></a>
<p>
<a NAME="Removed"></a>
<TABLE summary="Removed Methods" BORDER="1" CELLPADDING="3" CELLSPACING="0" WIDTH="100%">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TD VALIGN="TOP" COLSPAN=2><FONT SIZE="+1"><B>Removed Methods</B></FONT></TD>
</TR>
<TR BGCOLOR="#FFFFFF" CLASS="TableRowColor">
<TD VALIGN="TOP" WIDTH="25%">
<A NAME="org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.PigSecondaryKeyComparator.compare_removed(java.lang.Object, java.lang.Object, int, int, boolean[], boolean)"></A>
<nobr><code>int</code> <A HREF="http://hadoop.apache.org/pig/docs/r0.7.0/api/org/apache/pig/backend/hadoop/executionengine/mapReduceLayer/PigSecondaryKeyComparator.html#compare(java.lang.Object, java.lang.Object, int, int, boolean[], boolean)" target="_top"><tt>compare</tt></A>(<code>Object,</nobr> Object<nobr>,</nobr> int<nobr>,</nobr> int<nobr>,</nobr> boolean[]<nobr>,</nobr> boolean<nobr><nobr></code>)</nobr>
</TD>
<TD> </TD>
</TR>
</TABLE>
<a NAME="fields"></a>
<HR>
<!-- Start of nav bar -->
<TABLE summary="Navigation bar" BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<TABLE summary="Navigation bar" BORDER="0" CELLPADDING="0" CELLSPACING="3">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../api/org/apache/pig/backend/hadoop/executionengine/mapReduceLayer/PigSecondaryKeyComparator.html" target="_top"><FONT CLASS="NavBarFont1"><B><tt>pig 0.8.0-CDH3B4-SNAPSHOT</tt></B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="changes-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="pkg_org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="jdiff_statistics.html"><FONT CLASS="NavBarFont1"><B>Statistics</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="jdiff_help.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3></TD>
</TR>
<TR>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.PigRecordReader.html"><B>PREV CLASS</B></A>
<A HREF="org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.PigSplit.html"><B>NEXT CLASS</B></A>
<A HREF="../changes.html" TARGET="_top"><B>FRAMES</B></A>
<A HREF="org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.PigSecondaryKeyComparator.html" TARGET="_top"><B>NO FRAMES</B></A></FONT></TD>
<TD BGCOLOR="0xFFFFFF" CLASS="NavBarCell3"></TD>
</TR>
</TABLE>
<HR>
<!-- End of nav bar -->
</BODY>
</HTML>
| Java |
/*
* 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.ivy.core.pack;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import org.apache.ivy.util.FileUtil;
/**
* Packaging which handle OSGi bundles with inner packed jar
*/
public class OsgiBundlePacking extends ZipPacking {
private static final String[] NAMES = {"bundle"};
@Override
public String[] getNames() {
return NAMES;
}
@Override
protected void writeFile(InputStream zip, File f) throws IOException {
// XXX maybe we should only unpack file listed by the 'Bundle-ClassPath' MANIFEST header ?
if (f.getName().endsWith(".jar.pack.gz")) {
zip = FileUtil.unwrapPack200(zip);
f = new File(f.getParentFile(), f.getName().substring(0, f.getName().length() - 8));
}
super.writeFile(zip, f);
}
}
| Java |
package fr.openwide.core.wicket.more.markup.html.feedback;
import java.util.ArrayList;
import java.util.List;
import org.apache.wicket.MarkupContainer;
import org.apache.wicket.feedback.FeedbackMessage;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.markup.html.panel.Panel;
public abstract class AbstractFeedbackPanel extends Panel {
private static final long serialVersionUID = 8440891357292721078L;
private static final int[] ERROR_MESSAGE_LEVELS = {
FeedbackMessage.FATAL,
FeedbackMessage.ERROR,
FeedbackMessage.WARNING,
FeedbackMessage.SUCCESS,
FeedbackMessage.INFO,
FeedbackMessage.DEBUG,
FeedbackMessage.UNDEFINED
};
private static final String[] ERROR_MESSAGE_LEVEL_NAMES = {
"FATAL",
"ERROR",
"WARNING",
"SUCCESS",
"INFO",
"DEBUG",
"UNDEFINED"
};
private List<FeedbackPanel> feedbackPanels = new ArrayList<FeedbackPanel>();
public AbstractFeedbackPanel(String id, MarkupContainer container) {
super(id);
int i = 0;
for(int level: ERROR_MESSAGE_LEVELS) {
FeedbackPanel f = getFeedbackPanel(ERROR_MESSAGE_LEVEL_NAMES[i] + "feedbackPanel", level, container);
feedbackPanels.add(f);
add(f);
i++;
}
}
public abstract FeedbackPanel getFeedbackPanel(String id, int level, MarkupContainer container);
}
| Java |
<h3 class="page-header">Розв'язок</h3>
<div class="task-solution-top"></div>
<div class="task-solution-bg">
<p>
В першу чергу, обчислимо ОДЗ:
</p>
<div class="formula-block">
\begin{equation*}
\begin{aligned}
\mbox{ОДЗ}:\;&x-3\geq 0;\\
&x\geq 3;
\end{aligned}
\end{equation*}
</div>
<p>
Перший доданок є завжди додатним, бо це квадратний корінь. Другий доданок,
також завжди додатний, бо це модуль. Очевидно, що сума двох додатних чисел
рівна нулю лише тоді, коли ці числа рівні нулю. Тобто, ми маємо таку систему:
</p>
<div class="formula-block">
\begin{equation*}
\begin{aligned}
&\left\{
\begin{aligned}
&x-3=0,\\
&x^2-9=0;
\end{aligned}
\right.\\
&\left\{
\begin{aligned}
&x=3,\\
&x=\pm 3;
\end{aligned}
\right.
\end{aligned}
\end{equation*}
</div>
<p>
Значення $x=-3$ не задовольняє ОДЗ, тому відповідь буде:
</p>
<div class="formula-block">
$$x=3.$$
</div>
</div>
| Java |
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*
| -------------------------------------------------------------------------
| URI ROUTING
| -------------------------------------------------------------------------
| This file lets you re-map URI requests to specific controller functions.
|
| Typically there is a one-to-one relationship between a URL string
| and its corresponding controller class/method. The segments in a
| URL normally follow this pattern:
|
| example.com/class/method/id/
|
| In some instances, however, you may want to remap this relationship
| so that a different class/function is called than the one
| corresponding to the URL.
|
| Please see the user guide for complete details:
|
| http://codeigniter.com/user_guide/general/routing.html
|
| -------------------------------------------------------------------------
| RESERVED ROUTES
| -------------------------------------------------------------------------
|
| There area two reserved routes:
|
| $route['default_controller'] = 'welcome';
|
| This route indicates which controller class should be loaded if the
| URI contains no data. In the above example, the "welcome" class
| would be loaded.
|
| $route['404_override'] = 'errors/page_missing';
|
| This route will tell the Router what URI segments to use if those provided
| in the URL cannot be matched to a valid route.
|
*/
$route['default_controller'] = "reader";
$route['sitemap.xml'] = "reader/sitemap";
$route['rss.xml'] = "reader/feeds";
$route['atom.xml'] = "reader/feeds/atom";
$route['admin'] = "admin/series";
$route['admin/series/series/(:any)'] = "admin/series/serie/$1";
$route['account'] = "account/index/profile";
$route['account/profile'] = "account/index/profile";
$route['account/teams'] = "account/index/teams";
$route['account/leave_team/(:any)'] = "account/index/leave_team/$1";
$route['account/request/(:any)'] = "account/index/request/$1";
$route['account/leave_leadership/(:any)'] = "account/index/leave_leadership/$1";
$route['reader/list'] = 'reader/lista';
$route['reader/list/(:num)'] = 'reader/lista/$1';
$route['admin/members/members'] = 'admin/members/membersa';
// added for compatibility on upgrade 0.8.1 -> 0.8.2 on 30/09/2011
$route['admin/upgrade'] = 'admin/system/upgrade';
$route['404_override'] = '';
/* End of file routes.php */
/* Location: ./application/config/routes.php */ | Java |
/*
* EditorMouseMenu.java
*
* Created on March 21, 2007, 10:34 AM; Updated May 29, 2007
*
* Copyright 2007 Grotto Networking
*/
package Samples.MouseMenu;
import edu.uci.ics.jung.algorithms.layout.Layout;
import edu.uci.ics.jung.algorithms.layout.StaticLayout;
import edu.uci.ics.jung.graph.SparseMultigraph;
import edu.uci.ics.jung.visualization.VisualizationViewer;
import edu.uci.ics.jung.visualization.control.EditingModalGraphMouse;
import edu.uci.ics.jung.visualization.control.ModalGraphMouse;
import edu.uci.ics.jung.visualization.decorators.ToStringLabeller;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JPopupMenu;
/**
* Illustrates the use of custom edge and vertex classes in a graph editing application.
* Demonstrates a new graph mouse plugin for bringing up popup menus for vertices and
* edges.
* @author Dr. Greg M. Bernstein
*/
public class EditorMouseMenu {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
JFrame frame = new JFrame("Editing and Mouse Menu Demo");
SparseMultigraph<GraphElements.MyVertex, GraphElements.MyEdge> g =
new SparseMultigraph<GraphElements.MyVertex, GraphElements.MyEdge>();
// Layout<V, E>, VisualizationViewer<V,E>
// Map<GraphElements.MyVertex,Point2D> vertexLocations = new HashMap<GraphElements.MyVertex, Point2D>();
Layout<GraphElements.MyVertex, GraphElements.MyEdge> layout = new StaticLayout(g);
layout.setSize(new Dimension(300,300));
VisualizationViewer<GraphElements.MyVertex,GraphElements.MyEdge> vv =
new VisualizationViewer<GraphElements.MyVertex,GraphElements.MyEdge>(layout);
vv.setPreferredSize(new Dimension(350,350));
// Show vertex and edge labels
vv.getRenderContext().setVertexLabelTransformer(new ToStringLabeller());
vv.getRenderContext().setEdgeLabelTransformer(new ToStringLabeller());
// Create a graph mouse and add it to the visualization viewer
EditingModalGraphMouse gm = new EditingModalGraphMouse(vv.getRenderContext(),
GraphElements.MyVertexFactory.getInstance(),
GraphElements.MyEdgeFactory.getInstance());
// Set some defaults for the Edges...
GraphElements.MyEdgeFactory.setDefaultCapacity(192.0);
GraphElements.MyEdgeFactory.setDefaultWeight(5.0);
// Trying out our new popup menu mouse plugin...
PopupVertexEdgeMenuMousePlugin myPlugin = new PopupVertexEdgeMenuMousePlugin();
// Add some popup menus for the edges and vertices to our mouse plugin.
JPopupMenu edgeMenu = new MyMouseMenus.EdgeMenu(frame);
JPopupMenu vertexMenu = new MyMouseMenus.VertexMenu();
myPlugin.setEdgePopup(edgeMenu);
myPlugin.setVertexPopup(vertexMenu);
gm.remove(gm.getPopupEditingPlugin()); // Removes the existing popup editing plugin
gm.add(myPlugin); // Add our new plugin to the mouse
vv.setGraphMouse(gm);
//JFrame frame = new JFrame("Editing and Mouse Menu Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(vv);
// Let's add a menu for changing mouse modes
JMenuBar menuBar = new JMenuBar();
JMenu modeMenu = gm.getModeMenu();
modeMenu.setText("Mouse Mode");
modeMenu.setIcon(null); // I'm using this in a main menu
modeMenu.setPreferredSize(new Dimension(80,20)); // Change the size so I can see the text
menuBar.add(modeMenu);
frame.setJMenuBar(menuBar);
gm.setMode(ModalGraphMouse.Mode.EDITING); // Start off in editing mode
frame.pack();
frame.setVisible(true);
}
}
| Java |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright 2016 Eugene Frolov <eugene@frolov.net.ru>
#
# 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.
import random
import uuid as pyuuid
import mock
import requests
from six.moves.urllib import parse
from restalchemy.common import utils
from restalchemy.storage import exceptions
from restalchemy.storage.sql import engines
from restalchemy.tests.functional.restapi.ra_based.microservice import (
storable_models as models)
from restalchemy.tests.functional.restapi.ra_based.microservice import consts
from restalchemy.tests.functional.restapi.ra_based.microservice import service
from restalchemy.tests.unit import base
TEMPL_SERVICE_ENDPOINT = utils.lastslash("http://127.0.0.1:%s/")
TEMPL_ROOT_COLLECTION_ENDPOINT = TEMPL_SERVICE_ENDPOINT
TEMPL_V1_COLLECTION_ENDPOINT = utils.lastslash(parse.urljoin(
TEMPL_SERVICE_ENDPOINT, 'v1'))
TEMPL_VMS_COLLECTION_ENDPOINT = utils.lastslash(parse.urljoin(
TEMPL_V1_COLLECTION_ENDPOINT, 'vms'))
TEMPL_VM_RESOURCE_ENDPOINT = parse.urljoin(TEMPL_VMS_COLLECTION_ENDPOINT, '%s')
TEMPL_POWERON_ACTION_ENDPOINT = parse.urljoin(
utils.lastslash(TEMPL_VM_RESOURCE_ENDPOINT),
'actions/poweron/invoke')
TEMPL_PORTS_COLLECTION_ENDPOINT = utils.lastslash(parse.urljoin(
utils.lastslash(TEMPL_VM_RESOURCE_ENDPOINT), 'ports'))
TEMPL_PORT_RESOURCE_ENDPOINT = parse.urljoin(TEMPL_PORTS_COLLECTION_ENDPOINT,
'%s')
class BaseResourceTestCase(base.BaseTestCase):
def get_endpoint(self, template, *args):
return template % ((self.service_port,) + tuple(args))
def setUp(self):
super(BaseResourceTestCase, self).setUp()
engines.engine_factory.configure_factory(consts.DATABASE_URI)
engine = engines.engine_factory.get_engine()
self.session = engine.get_session()
self.session.execute("""CREATE TABLE IF NOT EXISTS vms (
uuid CHAR(36) NOT NULL,
state VARCHAR(10) NOT NULL,
name VARCHAR(255) NOT NULL,
PRIMARY KEY (uuid)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;""", None)
self.service_port = random.choice(range(2100, 2200))
url = parse.urlparse(self.get_endpoint(TEMPL_SERVICE_ENDPOINT))
self._service = service.RESTService(bind_host=url.hostname,
bind_port=url.port)
self._service.start()
def tearDown(self):
super(BaseResourceTestCase, self).tearDown()
self._service.stop()
self.session.execute("DROP TABLE IF EXISTS vms;", None)
class TestRootResourceTestCase(BaseResourceTestCase):
def test_get_versions_list(self):
response = requests.get(self.get_endpoint(
TEMPL_ROOT_COLLECTION_ENDPOINT))
self.assertEqual(response.status_code, 200)
self.assertEqual(response.json(), ["v1"])
class TestVersionsResourceTestCase(BaseResourceTestCase):
def test_get_resources_list(self):
response = requests.get(
self.get_endpoint(TEMPL_V1_COLLECTION_ENDPOINT))
self.assertEqual(response.status_code, 200)
self.assertEqual(response.json(), ["vms"])
class TestVMResourceTestCase(BaseResourceTestCase):
def _insert_vm_to_db(self, uuid, name, state):
vm = models.VM(uuid=uuid, name=name, state=state)
vm.save()
def _vm_exists_in_db(self, uuid):
try:
models.VM.objects.get_one(filters={'uuid': uuid})
return True
except exceptions.RecordNotFound:
return False
@mock.patch('uuid.uuid4')
def test_create_vm_resource_successful(self, uuid4_mock):
RESOURCE_ID = pyuuid.UUID("00000000-0000-0000-0000-000000000001")
uuid4_mock.return_value = RESOURCE_ID
vm_request_body = {
"name": "test"
}
vm_response_body = {
"uuid": str(RESOURCE_ID),
"name": "test",
"state": "off"
}
LOCATION = self.get_endpoint(TEMPL_VM_RESOURCE_ENDPOINT, RESOURCE_ID)
response = requests.post(self.get_endpoint(
TEMPL_VMS_COLLECTION_ENDPOINT), json=vm_request_body)
self.assertEqual(response.status_code, 201)
self.assertEqual(response.headers['location'], LOCATION)
self.assertEqual(response.json(), vm_response_body)
def test_get_vm_resource_by_uuid_successful(self):
RESOURCE_ID = pyuuid.UUID("00000000-0000-0000-0000-000000000001")
self._insert_vm_to_db(uuid=RESOURCE_ID, name="test", state="off")
vm_response_body = {
"uuid": str(RESOURCE_ID),
"name": "test",
"state": "off"
}
VM_RES_ENDPOINT = self.get_endpoint(TEMPL_VM_RESOURCE_ENDPOINT,
RESOURCE_ID)
response = requests.get(VM_RES_ENDPOINT)
self.assertEqual(response.status_code, 200)
self.assertEqual(response.json(), vm_response_body)
def test_update_vm_resource_successful(self):
RESOURCE_ID = pyuuid.UUID("00000000-0000-0000-0000-000000000001")
self._insert_vm_to_db(uuid=RESOURCE_ID, name="old", state="off")
vm_request_body = {
"name": "new"
}
vm_response_body = {
"uuid": str(RESOURCE_ID),
"name": "new",
"state": "off"
}
VM_RES_ENDPOINT = self.get_endpoint(TEMPL_VM_RESOURCE_ENDPOINT,
RESOURCE_ID)
response = requests.put(VM_RES_ENDPOINT, json=vm_request_body)
self.assertEqual(response.status_code, 200)
self.assertEqual(response.json(), vm_response_body)
def test_delete_vm_resource_successful(self):
RESOURCE_ID = pyuuid.UUID("00000000-0000-0000-0000-000000000001")
self._insert_vm_to_db(uuid=RESOURCE_ID, name="test", state="off")
VM_RES_ENDPOINT = self.get_endpoint(TEMPL_VM_RESOURCE_ENDPOINT,
RESOURCE_ID)
response = requests.delete(VM_RES_ENDPOINT)
self.assertEqual(response.status_code, 204)
self.assertFalse(self._vm_exists_in_db(RESOURCE_ID))
def test_process_vm_action_successful(self):
RESOURCE_ID = pyuuid.UUID("00000000-0000-0000-0000-000000000001")
self._insert_vm_to_db(uuid=RESOURCE_ID, name="test", state="off")
vm_response_body = {
"uuid": str(RESOURCE_ID),
"name": "test",
"state": "on"
}
POWERON_ACT_ENDPOINT = self.get_endpoint(TEMPL_POWERON_ACTION_ENDPOINT,
RESOURCE_ID)
response = requests.post(POWERON_ACT_ENDPOINT)
self.assertEqual(response.status_code, 200)
self.assertEqual(response.json(), vm_response_body)
def test_get_collection_vms_successful(self):
RESOURCE_ID1 = pyuuid.UUID("00000000-0000-0000-0000-000000000001")
RESOURCE_ID2 = pyuuid.UUID("00000000-0000-0000-0000-000000000002")
self._insert_vm_to_db(uuid=RESOURCE_ID1, name="test1", state="off")
self._insert_vm_to_db(uuid=RESOURCE_ID2, name="test2", state="on")
vm_response_body = [{
"uuid": str(RESOURCE_ID1),
"name": "test1",
"state": "off"
}, {
"uuid": str(RESOURCE_ID2),
"name": "test2",
"state": "on"
}]
response = requests.get(self.get_endpoint(
TEMPL_VMS_COLLECTION_ENDPOINT))
self.assertEqual(response.status_code, 200)
self.assertEqual(response.json(), vm_response_body)
class TestNestedResourceTestCase(BaseResourceTestCase):
def setUp(self):
super(TestNestedResourceTestCase, self).setUp()
self.session.execute("""CREATE TABLE IF NOT EXISTS ports (
uuid CHAR(36) NOT NULL,
mac CHAR(17) NOT NULL,
vm CHAR(36) NOT NULL,
PRIMARY KEY (uuid),
CONSTRAINT FOREIGN KEY ix_vms_uuid (vm) REFERENCES vms (uuid)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;""", None)
self.vm1 = models.VM(
uuid=pyuuid.UUID("00000000-0000-0000-0000-000000000001"),
name="vm1",
state="on")
self.vm1.save(session=self.session)
self.vm2 = models.VM(
uuid=pyuuid.UUID("00000000-0000-0000-0000-000000000002"),
name="vm2",
state="off")
self.vm2.save(session=self.session)
self.session.commit()
def tearDown(self):
self.session.execute("DROP TABLE IF EXISTS ports;", None)
super(TestNestedResourceTestCase, self).tearDown()
@mock.patch('uuid.uuid4')
def test_create_nested_resource_successful(self, uuid4_mock):
VM_RESOURCE_ID = pyuuid.UUID("00000000-0000-0000-0000-000000000001")
PORT_RESOURCE_ID = pyuuid.UUID("00000000-0000-0000-0000-000000000003")
uuid4_mock.return_value = PORT_RESOURCE_ID
port_request_body = {
"mac": "00:00:00:00:00:03"
}
port_response_body = {
"uuid": str(PORT_RESOURCE_ID),
"mac": "00:00:00:00:00:03",
"vm": parse.urlparse(
self.get_endpoint(TEMPL_VM_RESOURCE_ENDPOINT,
VM_RESOURCE_ID)).path
}
LOCATION = self.get_endpoint(TEMPL_PORT_RESOURCE_ENDPOINT,
VM_RESOURCE_ID,
PORT_RESOURCE_ID)
response = requests.post(
self.get_endpoint(TEMPL_PORTS_COLLECTION_ENDPOINT, VM_RESOURCE_ID),
json=port_request_body)
self.assertEqual(response.status_code, 201)
self.assertEqual(response.headers['location'], LOCATION)
self.assertEqual(response.json(), port_response_body)
def test_get_nested_resource_successful(self):
VM_RESOURCE_ID = pyuuid.UUID("00000000-0000-0000-0000-000000000001")
PORT_RESOURCE_ID = pyuuid.UUID("00000000-0000-0000-0000-000000000003")
port = models.Port(uuid=PORT_RESOURCE_ID,
mac="00:00:00:00:00:03",
vm=self.vm1)
port.save(session=self.session)
self.session.commit()
port_response_body = {
"uuid": str(PORT_RESOURCE_ID),
"mac": "00:00:00:00:00:03",
"vm": parse.urlparse(
self.get_endpoint(TEMPL_VM_RESOURCE_ENDPOINT,
VM_RESOURCE_ID)).path
}
response = requests.get(
self.get_endpoint(TEMPL_PORT_RESOURCE_ENDPOINT,
VM_RESOURCE_ID,
PORT_RESOURCE_ID))
self.assertEqual(response.status_code, 200)
self.assertEqual(response.json(), port_response_body)
def test_get_ports_collection_successful(self):
VM_RESOURCE_ID = pyuuid.UUID("00000000-0000-0000-0000-000000000001")
PORT1_RESOURCE_ID = pyuuid.UUID("00000000-0000-0000-0000-000000000003")
PORT2_RESOURCE_ID = pyuuid.UUID("00000000-0000-0000-0000-000000000004")
PORT3_RESOURCE_ID = pyuuid.UUID("00000000-0000-0000-0000-000000000005")
port1 = models.Port(uuid=PORT1_RESOURCE_ID,
mac="00:00:00:00:00:03",
vm=self.vm1)
port1.save(session=self.session)
port2 = models.Port(uuid=PORT2_RESOURCE_ID,
mac="00:00:00:00:00:04",
vm=self.vm1)
port2.save(session=self.session)
port3 = models.Port(uuid=PORT3_RESOURCE_ID,
mac="00:00:00:00:00:05",
vm=self.vm2)
port3.save(session=self.session)
ports_response_body = [{
"uuid": str(PORT1_RESOURCE_ID),
"mac": "00:00:00:00:00:03",
"vm": parse.urlparse(
self.get_endpoint(TEMPL_VM_RESOURCE_ENDPOINT,
VM_RESOURCE_ID)).path
}, {
"uuid": str(PORT2_RESOURCE_ID),
"mac": "00:00:00:00:00:04",
"vm": parse.urlparse(
self.get_endpoint(TEMPL_VM_RESOURCE_ENDPOINT,
VM_RESOURCE_ID)).path
}]
self.session.commit()
response = requests.get(
self.get_endpoint(TEMPL_PORTS_COLLECTION_ENDPOINT, VM_RESOURCE_ID))
self.assertEqual(response.status_code, 200)
self.assertEqual(response.json(), ports_response_body)
def test_delete_nested_resource_successful(self):
VM_RESOURCE_ID = pyuuid.UUID("00000000-0000-0000-0000-000000000001")
PORT_RESOURCE_ID = pyuuid.UUID("00000000-0000-0000-0000-000000000003")
port = models.Port(uuid=PORT_RESOURCE_ID,
mac="00:00:00:00:00:03",
vm=self.vm1)
port.save(session=self.session)
self.session.commit()
response = requests.delete(
self.get_endpoint(TEMPL_PORT_RESOURCE_ENDPOINT,
VM_RESOURCE_ID,
PORT_RESOURCE_ID))
self.assertEqual(response.status_code, 204)
self.assertRaises(exceptions.RecordNotFound,
models.Port.objects.get_one,
filters={'uuid': PORT_RESOURCE_ID})
| Java |
package ru.job4j.max;
/**
*Класс помогает узнать, какое из двух чисел больше.
*@author ifedorenko
*@since 14.08.2017
*@version 1
*/
public class Max {
/**
*Возвращает большее число из двух.
*@param first содержит первое число
*@param second содержит второе число
*@return Большее из двух
*/
public int max(int first, int second) {
return first > second ? first : second;
}
/**
*Возвращает большее число из трех.
*@param first содержит первое число
*@param second содержит второе число
*@param third содержит третье число
*@return Большее из трех
*/
public int max(int first, int second, int third) {
return max(first, max(second, third));
}
} | Java |
/**
* Autogenerated by Thrift
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
*/
package com.cloudera.flume.reporter.server;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.EnumMap;
import java.util.Set;
import java.util.HashSet;
import java.util.EnumSet;
import java.util.Collections;
import java.util.BitSet;
import java.util.Arrays;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.thrift.*;
import org.apache.thrift.meta_data.*;
import org.apache.thrift.protocol.*;
public class FlumeReport implements TBase<FlumeReport._Fields>, java.io.Serializable, Cloneable {
private static final TStruct STRUCT_DESC = new TStruct("FlumeReport");
private static final TField STRING_METRICS_FIELD_DESC = new TField("stringMetrics", TType.MAP, (short)3);
private static final TField LONG_METRICS_FIELD_DESC = new TField("longMetrics", TType.MAP, (short)4);
private static final TField DOUBLE_METRICS_FIELD_DESC = new TField("doubleMetrics", TType.MAP, (short)5);
public Map<String,String> stringMetrics;
public Map<String,Long> longMetrics;
public Map<String,Double> doubleMetrics;
/** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
public enum _Fields implements TFieldIdEnum {
STRING_METRICS((short)3, "stringMetrics"),
LONG_METRICS((short)4, "longMetrics"),
DOUBLE_METRICS((short)5, "doubleMetrics");
private static final Map<Integer, _Fields> byId = new HashMap<Integer, _Fields>();
private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();
static {
for (_Fields field : EnumSet.allOf(_Fields.class)) {
byId.put((int)field._thriftId, field);
byName.put(field.getFieldName(), field);
}
}
/**
* Find the _Fields constant that matches fieldId, or null if its not found.
*/
public static _Fields findByThriftId(int fieldId) {
return byId.get(fieldId);
}
/**
* Find the _Fields constant that matches fieldId, throwing an exception
* if it is not found.
*/
public static _Fields findByThriftIdOrThrow(int fieldId) {
_Fields fields = findByThriftId(fieldId);
if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!");
return fields;
}
/**
* Find the _Fields constant that matches name, or null if its not found.
*/
public static _Fields findByName(String name) {
return byName.get(name);
}
private final short _thriftId;
private final String _fieldName;
_Fields(short thriftId, String fieldName) {
_thriftId = thriftId;
_fieldName = fieldName;
}
public short getThriftFieldId() {
return _thriftId;
}
public String getFieldName() {
return _fieldName;
}
}
// isset id assignments
public static final Map<_Fields, FieldMetaData> metaDataMap = Collections.unmodifiableMap(new EnumMap<_Fields, FieldMetaData>(_Fields.class) {{
put(_Fields.STRING_METRICS, new FieldMetaData("stringMetrics", TFieldRequirementType.DEFAULT,
new MapMetaData(TType.MAP,
new FieldValueMetaData(TType.STRING),
new FieldValueMetaData(TType.STRING))));
put(_Fields.LONG_METRICS, new FieldMetaData("longMetrics", TFieldRequirementType.DEFAULT,
new MapMetaData(TType.MAP,
new FieldValueMetaData(TType.STRING),
new FieldValueMetaData(TType.I64))));
put(_Fields.DOUBLE_METRICS, new FieldMetaData("doubleMetrics", TFieldRequirementType.DEFAULT,
new MapMetaData(TType.MAP,
new FieldValueMetaData(TType.STRING),
new FieldValueMetaData(TType.DOUBLE))));
}});
static {
FieldMetaData.addStructMetaDataMap(FlumeReport.class, metaDataMap);
}
public FlumeReport() {
}
public FlumeReport(
Map<String,String> stringMetrics,
Map<String,Long> longMetrics,
Map<String,Double> doubleMetrics)
{
this();
this.stringMetrics = stringMetrics;
this.longMetrics = longMetrics;
this.doubleMetrics = doubleMetrics;
}
/**
* Performs a deep copy on <i>other</i>.
*/
public FlumeReport(FlumeReport other) {
if (other.isSetStringMetrics()) {
Map<String,String> __this__stringMetrics = new HashMap<String,String>();
for (Map.Entry<String, String> other_element : other.stringMetrics.entrySet()) {
String other_element_key = other_element.getKey();
String other_element_value = other_element.getValue();
String __this__stringMetrics_copy_key = other_element_key;
String __this__stringMetrics_copy_value = other_element_value;
__this__stringMetrics.put(__this__stringMetrics_copy_key, __this__stringMetrics_copy_value);
}
this.stringMetrics = __this__stringMetrics;
}
if (other.isSetLongMetrics()) {
Map<String,Long> __this__longMetrics = new HashMap<String,Long>();
for (Map.Entry<String, Long> other_element : other.longMetrics.entrySet()) {
String other_element_key = other_element.getKey();
Long other_element_value = other_element.getValue();
String __this__longMetrics_copy_key = other_element_key;
Long __this__longMetrics_copy_value = other_element_value;
__this__longMetrics.put(__this__longMetrics_copy_key, __this__longMetrics_copy_value);
}
this.longMetrics = __this__longMetrics;
}
if (other.isSetDoubleMetrics()) {
Map<String,Double> __this__doubleMetrics = new HashMap<String,Double>();
for (Map.Entry<String, Double> other_element : other.doubleMetrics.entrySet()) {
String other_element_key = other_element.getKey();
Double other_element_value = other_element.getValue();
String __this__doubleMetrics_copy_key = other_element_key;
Double __this__doubleMetrics_copy_value = other_element_value;
__this__doubleMetrics.put(__this__doubleMetrics_copy_key, __this__doubleMetrics_copy_value);
}
this.doubleMetrics = __this__doubleMetrics;
}
}
public FlumeReport deepCopy() {
return new FlumeReport(this);
}
@Deprecated
public FlumeReport clone() {
return new FlumeReport(this);
}
public int getStringMetricsSize() {
return (this.stringMetrics == null) ? 0 : this.stringMetrics.size();
}
public void putToStringMetrics(String key, String val) {
if (this.stringMetrics == null) {
this.stringMetrics = new HashMap<String,String>();
}
this.stringMetrics.put(key, val);
}
public Map<String,String> getStringMetrics() {
return this.stringMetrics;
}
public FlumeReport setStringMetrics(Map<String,String> stringMetrics) {
this.stringMetrics = stringMetrics;
return this;
}
public void unsetStringMetrics() {
this.stringMetrics = null;
}
/** Returns true if field stringMetrics is set (has been asigned a value) and false otherwise */
public boolean isSetStringMetrics() {
return this.stringMetrics != null;
}
public void setStringMetricsIsSet(boolean value) {
if (!value) {
this.stringMetrics = null;
}
}
public int getLongMetricsSize() {
return (this.longMetrics == null) ? 0 : this.longMetrics.size();
}
public void putToLongMetrics(String key, long val) {
if (this.longMetrics == null) {
this.longMetrics = new HashMap<String,Long>();
}
this.longMetrics.put(key, val);
}
public Map<String,Long> getLongMetrics() {
return this.longMetrics;
}
public FlumeReport setLongMetrics(Map<String,Long> longMetrics) {
this.longMetrics = longMetrics;
return this;
}
public void unsetLongMetrics() {
this.longMetrics = null;
}
/** Returns true if field longMetrics is set (has been asigned a value) and false otherwise */
public boolean isSetLongMetrics() {
return this.longMetrics != null;
}
public void setLongMetricsIsSet(boolean value) {
if (!value) {
this.longMetrics = null;
}
}
public int getDoubleMetricsSize() {
return (this.doubleMetrics == null) ? 0 : this.doubleMetrics.size();
}
public void putToDoubleMetrics(String key, double val) {
if (this.doubleMetrics == null) {
this.doubleMetrics = new HashMap<String,Double>();
}
this.doubleMetrics.put(key, val);
}
public Map<String,Double> getDoubleMetrics() {
return this.doubleMetrics;
}
public FlumeReport setDoubleMetrics(Map<String,Double> doubleMetrics) {
this.doubleMetrics = doubleMetrics;
return this;
}
public void unsetDoubleMetrics() {
this.doubleMetrics = null;
}
/** Returns true if field doubleMetrics is set (has been asigned a value) and false otherwise */
public boolean isSetDoubleMetrics() {
return this.doubleMetrics != null;
}
public void setDoubleMetricsIsSet(boolean value) {
if (!value) {
this.doubleMetrics = null;
}
}
public void setFieldValue(_Fields field, Object value) {
switch (field) {
case STRING_METRICS:
if (value == null) {
unsetStringMetrics();
} else {
setStringMetrics((Map<String,String>)value);
}
break;
case LONG_METRICS:
if (value == null) {
unsetLongMetrics();
} else {
setLongMetrics((Map<String,Long>)value);
}
break;
case DOUBLE_METRICS:
if (value == null) {
unsetDoubleMetrics();
} else {
setDoubleMetrics((Map<String,Double>)value);
}
break;
}
}
public void setFieldValue(int fieldID, Object value) {
setFieldValue(_Fields.findByThriftIdOrThrow(fieldID), value);
}
public Object getFieldValue(_Fields field) {
switch (field) {
case STRING_METRICS:
return getStringMetrics();
case LONG_METRICS:
return getLongMetrics();
case DOUBLE_METRICS:
return getDoubleMetrics();
}
throw new IllegalStateException();
}
public Object getFieldValue(int fieldId) {
return getFieldValue(_Fields.findByThriftIdOrThrow(fieldId));
}
/** Returns true if field corresponding to fieldID is set (has been asigned a value) and false otherwise */
public boolean isSet(_Fields field) {
switch (field) {
case STRING_METRICS:
return isSetStringMetrics();
case LONG_METRICS:
return isSetLongMetrics();
case DOUBLE_METRICS:
return isSetDoubleMetrics();
}
throw new IllegalStateException();
}
public boolean isSet(int fieldID) {
return isSet(_Fields.findByThriftIdOrThrow(fieldID));
}
@Override
public boolean equals(Object that) {
if (that == null)
return false;
if (that instanceof FlumeReport)
return this.equals((FlumeReport)that);
return false;
}
public boolean equals(FlumeReport that) {
if (that == null)
return false;
boolean this_present_stringMetrics = true && this.isSetStringMetrics();
boolean that_present_stringMetrics = true && that.isSetStringMetrics();
if (this_present_stringMetrics || that_present_stringMetrics) {
if (!(this_present_stringMetrics && that_present_stringMetrics))
return false;
if (!this.stringMetrics.equals(that.stringMetrics))
return false;
}
boolean this_present_longMetrics = true && this.isSetLongMetrics();
boolean that_present_longMetrics = true && that.isSetLongMetrics();
if (this_present_longMetrics || that_present_longMetrics) {
if (!(this_present_longMetrics && that_present_longMetrics))
return false;
if (!this.longMetrics.equals(that.longMetrics))
return false;
}
boolean this_present_doubleMetrics = true && this.isSetDoubleMetrics();
boolean that_present_doubleMetrics = true && that.isSetDoubleMetrics();
if (this_present_doubleMetrics || that_present_doubleMetrics) {
if (!(this_present_doubleMetrics && that_present_doubleMetrics))
return false;
if (!this.doubleMetrics.equals(that.doubleMetrics))
return false;
}
return true;
}
@Override
public int hashCode() {
return 0;
}
public void read(TProtocol iprot) throws TException {
TField field;
iprot.readStructBegin();
while (true)
{
field = iprot.readFieldBegin();
if (field.type == TType.STOP) {
break;
}
_Fields fieldId = _Fields.findByThriftId(field.id);
if (fieldId == null) {
TProtocolUtil.skip(iprot, field.type);
} else {
switch (fieldId) {
case STRING_METRICS:
if (field.type == TType.MAP) {
{
TMap _map0 = iprot.readMapBegin();
this.stringMetrics = new HashMap<String,String>(2*_map0.size);
for (int _i1 = 0; _i1 < _map0.size; ++_i1)
{
String _key2;
String _val3;
_key2 = iprot.readString();
_val3 = iprot.readString();
this.stringMetrics.put(_key2, _val3);
}
iprot.readMapEnd();
}
} else {
TProtocolUtil.skip(iprot, field.type);
}
break;
case LONG_METRICS:
if (field.type == TType.MAP) {
{
TMap _map4 = iprot.readMapBegin();
this.longMetrics = new HashMap<String,Long>(2*_map4.size);
for (int _i5 = 0; _i5 < _map4.size; ++_i5)
{
String _key6;
long _val7;
_key6 = iprot.readString();
_val7 = iprot.readI64();
this.longMetrics.put(_key6, _val7);
}
iprot.readMapEnd();
}
} else {
TProtocolUtil.skip(iprot, field.type);
}
break;
case DOUBLE_METRICS:
if (field.type == TType.MAP) {
{
TMap _map8 = iprot.readMapBegin();
this.doubleMetrics = new HashMap<String,Double>(2*_map8.size);
for (int _i9 = 0; _i9 < _map8.size; ++_i9)
{
String _key10;
double _val11;
_key10 = iprot.readString();
_val11 = iprot.readDouble();
this.doubleMetrics.put(_key10, _val11);
}
iprot.readMapEnd();
}
} else {
TProtocolUtil.skip(iprot, field.type);
}
break;
}
iprot.readFieldEnd();
}
}
iprot.readStructEnd();
// check for required fields of primitive type, which can't be checked in the validate method
validate();
}
public void write(TProtocol oprot) throws TException {
validate();
oprot.writeStructBegin(STRUCT_DESC);
if (this.stringMetrics != null) {
oprot.writeFieldBegin(STRING_METRICS_FIELD_DESC);
{
oprot.writeMapBegin(new TMap(TType.STRING, TType.STRING, this.stringMetrics.size()));
for (Map.Entry<String, String> _iter12 : this.stringMetrics.entrySet())
{
oprot.writeString(_iter12.getKey());
oprot.writeString(_iter12.getValue());
}
oprot.writeMapEnd();
}
oprot.writeFieldEnd();
}
if (this.longMetrics != null) {
oprot.writeFieldBegin(LONG_METRICS_FIELD_DESC);
{
oprot.writeMapBegin(new TMap(TType.STRING, TType.I64, this.longMetrics.size()));
for (Map.Entry<String, Long> _iter13 : this.longMetrics.entrySet())
{
oprot.writeString(_iter13.getKey());
oprot.writeI64(_iter13.getValue());
}
oprot.writeMapEnd();
}
oprot.writeFieldEnd();
}
if (this.doubleMetrics != null) {
oprot.writeFieldBegin(DOUBLE_METRICS_FIELD_DESC);
{
oprot.writeMapBegin(new TMap(TType.STRING, TType.DOUBLE, this.doubleMetrics.size()));
for (Map.Entry<String, Double> _iter14 : this.doubleMetrics.entrySet())
{
oprot.writeString(_iter14.getKey());
oprot.writeDouble(_iter14.getValue());
}
oprot.writeMapEnd();
}
oprot.writeFieldEnd();
}
oprot.writeFieldStop();
oprot.writeStructEnd();
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("FlumeReport(");
boolean first = true;
sb.append("stringMetrics:");
if (this.stringMetrics == null) {
sb.append("null");
} else {
sb.append(this.stringMetrics);
}
first = false;
if (!first) sb.append(", ");
sb.append("longMetrics:");
if (this.longMetrics == null) {
sb.append("null");
} else {
sb.append(this.longMetrics);
}
first = false;
if (!first) sb.append(", ");
sb.append("doubleMetrics:");
if (this.doubleMetrics == null) {
sb.append("null");
} else {
sb.append(this.doubleMetrics);
}
first = false;
sb.append(")");
return sb.toString();
}
public void validate() throws TException {
// check for required fields
}
}
| Java |
/**
* Copyright 2005-2014 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.docsearch.dao.impl;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import javax.sql.DataSource;
import org.apache.commons.lang.StringUtils;
import org.kuali.rice.core.api.uif.RemotableAttributeField;
import org.kuali.rice.coreservice.framework.CoreFrameworkServiceLocator;
import org.kuali.rice.kew.api.KewApiConstants;
import org.kuali.rice.kew.api.document.search.DocumentSearchCriteria;
import org.kuali.rice.kew.api.document.search.DocumentSearchResults;
import org.kuali.rice.kew.docsearch.dao.DocumentSearchDAO;
import org.kuali.rice.kew.impl.document.search.DocumentSearchGenerator;
import org.kuali.rice.kew.util.PerformanceLogger;
import org.kuali.rice.krad.util.KRADConstants;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.ConnectionCallback;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy;
/**
* Spring JdbcTemplate implementation of DocumentSearchDAO
*
* @author Kuali Rice Team (rice.collab@kuali.org)
*
*/
public class DocumentSearchDAOJdbcImpl implements DocumentSearchDAO {
public static final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(DocumentSearchDAOJdbcImpl.class);
private static final int DEFAULT_FETCH_MORE_ITERATION_LIMIT = 10;
private DataSource dataSource;
public void setDataSource(DataSource dataSource) {
this.dataSource = new TransactionAwareDataSourceProxy(dataSource);
}
@Override
public DocumentSearchResults.Builder findDocuments(final DocumentSearchGenerator documentSearchGenerator, final DocumentSearchCriteria criteria, final boolean criteriaModified, final List<RemotableAttributeField> searchFields) {
final int maxResultCap = getMaxResultCap(criteria);
try {
final JdbcTemplate template = new JdbcTemplate(dataSource);
return template.execute(new ConnectionCallback<DocumentSearchResults.Builder>() {
@Override
public DocumentSearchResults.Builder doInConnection(final Connection con) throws SQLException {
final Statement statement = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
try {
final int fetchIterationLimit = getFetchMoreIterationLimit();
final int fetchLimit = fetchIterationLimit * maxResultCap;
statement.setFetchSize(maxResultCap + 1);
statement.setMaxRows(fetchLimit + 1);
PerformanceLogger perfLog = new PerformanceLogger();
String sql = documentSearchGenerator.generateSearchSql(criteria, searchFields);
perfLog.log("Time to generate search sql from documentSearchGenerator class: " + documentSearchGenerator
.getClass().getName(), true);
LOG.info("Executing document search with statement max rows: " + statement.getMaxRows());
LOG.info("Executing document search with statement fetch size: " + statement.getFetchSize());
perfLog = new PerformanceLogger();
final ResultSet rs = statement.executeQuery(sql);
try {
perfLog.log("Time to execute doc search database query.", true);
final Statement searchAttributeStatement = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
try {
return documentSearchGenerator.processResultSet(criteria, criteriaModified, searchAttributeStatement, rs, maxResultCap, fetchLimit);
} finally {
try {
searchAttributeStatement.close();
} catch (SQLException e) {
LOG.warn("Could not close search attribute statement.");
}
}
} finally {
try {
rs.close();
} catch (SQLException e) {
LOG.warn("Could not close result set.");
}
}
} finally {
try {
statement.close();
} catch (SQLException e) {
LOG.warn("Could not close statement.");
}
}
}
});
} catch (DataAccessException dae) {
String errorMsg = "DataAccessException: " + dae.getMessage();
LOG.error("getList() " + errorMsg, dae);
throw new RuntimeException(errorMsg, dae);
} catch (Exception e) {
String errorMsg = "LookupException: " + e.getMessage();
LOG.error("getList() " + errorMsg, e);
throw new RuntimeException(errorMsg, e);
}
}
/**
* Returns the maximum number of results that should be returned from the document search.
*
* @param criteria the criteria in which to check for a max results value
* @return the maximum number of results that should be returned from a document search
*/
public int getMaxResultCap(DocumentSearchCriteria criteria) {
int systemLimit = KewApiConstants.DOCUMENT_LOOKUP_DEFAULT_RESULT_CAP;
String resultCapValue = CoreFrameworkServiceLocator.getParameterService().getParameterValueAsString(KewApiConstants.KEW_NAMESPACE, KRADConstants.DetailTypes.DOCUMENT_SEARCH_DETAIL_TYPE, KewApiConstants.DOC_SEARCH_RESULT_CAP);
if (StringUtils.isNotBlank(resultCapValue)) {
try {
int configuredLimit = Integer.parseInt(resultCapValue);
if (configuredLimit <= 0) {
LOG.warn(KewApiConstants.DOC_SEARCH_RESULT_CAP + " was less than or equal to zero. Please use a positive integer.");
} else {
systemLimit = configuredLimit;
}
} catch (NumberFormatException e) {
LOG.warn(KewApiConstants.DOC_SEARCH_RESULT_CAP + " is not a valid number. Value was " + resultCapValue + ". Using default: " + KewApiConstants.DOCUMENT_LOOKUP_DEFAULT_RESULT_CAP);
}
}
int maxResults = systemLimit;
if (criteria.getMaxResults() != null) {
int criteriaLimit = criteria.getMaxResults().intValue();
if (criteriaLimit > systemLimit) {
LOG.warn("Result set cap of " + criteriaLimit + " is greater than system value of " + systemLimit);
} else {
if (criteriaLimit < 0) {
LOG.warn("Criteria results limit was less than zero.");
criteriaLimit = 0;
}
maxResults = criteriaLimit;
}
}
return maxResults;
}
public int getFetchMoreIterationLimit() {
int fetchMoreLimit = DEFAULT_FETCH_MORE_ITERATION_LIMIT;
String fetchMoreLimitValue = CoreFrameworkServiceLocator.getParameterService().getParameterValueAsString(KewApiConstants.KEW_NAMESPACE, KRADConstants.DetailTypes.DOCUMENT_SEARCH_DETAIL_TYPE, KewApiConstants.DOC_SEARCH_FETCH_MORE_ITERATION_LIMIT);
if (!StringUtils.isBlank(fetchMoreLimitValue)) {
try {
fetchMoreLimit = Integer.parseInt(fetchMoreLimitValue);
if (fetchMoreLimit < 0) {
LOG.warn(KewApiConstants.DOC_SEARCH_FETCH_MORE_ITERATION_LIMIT + " was less than zero. Please use a value greater than or equal to zero.");
fetchMoreLimit = DEFAULT_FETCH_MORE_ITERATION_LIMIT;
}
} catch (NumberFormatException e) {
LOG.warn(KewApiConstants.DOC_SEARCH_FETCH_MORE_ITERATION_LIMIT + " is not a valid number. Value was " + fetchMoreLimitValue);
}
}
return fetchMoreLimit;
}
}
| Java |
/*
* Copyright 2016 Alexander Severgin
*
* 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 eu.alpinweiss.filegen.util.generator.impl;
import eu.alpinweiss.filegen.model.FieldDefinition;
import eu.alpinweiss.filegen.model.FieldType;
import eu.alpinweiss.filegen.util.wrapper.AbstractDataWrapper;
import eu.alpinweiss.filegen.util.generator.FieldGenerator;
import eu.alpinweiss.filegen.util.vault.ParameterVault;
import eu.alpinweiss.filegen.util.vault.ValueVault;
import org.apache.commons.lang.StringUtils;
import java.util.concurrent.ThreadLocalRandom;
/**
* {@link AutoNumberGenerator}.
*
* @author Aleksandrs.Severgins | <a href="http://alpinweiss.eu">SIA Alpinweiss</a>
*/
public class AutoNumberGenerator implements FieldGenerator {
private final FieldDefinition fieldDefinition;
private int startNum;
public AutoNumberGenerator(FieldDefinition fieldDefinition) {
this.fieldDefinition = fieldDefinition;
final String pattern = this.fieldDefinition.getPattern();
if (!pattern.isEmpty()) {
startNum = Integer.parseInt(pattern);
}
}
@Override
public void generate(final ParameterVault parameterVault, ThreadLocalRandom randomGenerator, ValueVault valueVault) {
valueVault.storeValue(new IntegerDataWrapper() {
@Override
public Double getNumberValue() {
int value = startNum + (parameterVault.rowCount() * parameterVault.dataPartNumber()) + parameterVault.iterationNumber();
return new Double(value);
}
});
}
private class IntegerDataWrapper extends AbstractDataWrapper {
@Override
public FieldType getFieldType() {
return FieldType.INTEGER;
}
}
}
| Java |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
package org.elasticsearch.xpack.analytics.mapper;
import org.elasticsearch.index.mapper.FieldTypeTestCase;
import org.elasticsearch.index.mapper.MappedFieldType;
public class HistogramFieldTypeTests extends FieldTypeTestCase<MappedFieldType> {
@Override
protected MappedFieldType createDefaultFieldType() {
return new HistogramFieldMapper.HistogramFieldType();
}
}
| Java |
/**
* <copyright>
* </copyright>
*
* $Id$
*/
package net.opengis.gml.provider;
import java.util.Collection;
import java.util.List;
import net.opengis.gml.FeatureStyleType;
import net.opengis.gml.GmlFactory;
import net.opengis.gml.GmlPackage;
import org.eclipse.emf.common.notify.AdapterFactory;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.ecore.EStructuralFeature;
import org.eclipse.emf.ecore.util.FeatureMap;
import org.eclipse.emf.ecore.util.FeatureMapUtil;
import org.eclipse.emf.edit.provider.ComposeableAdapterFactory;
import org.eclipse.emf.edit.provider.IEditingDomainItemProvider;
import org.eclipse.emf.edit.provider.IItemLabelProvider;
import org.eclipse.emf.edit.provider.IItemPropertyDescriptor;
import org.eclipse.emf.edit.provider.IItemPropertySource;
import org.eclipse.emf.edit.provider.IStructuredItemContentProvider;
import org.eclipse.emf.edit.provider.ITreeItemContentProvider;
import org.eclipse.emf.edit.provider.ItemPropertyDescriptor;
import org.eclipse.emf.edit.provider.ViewerNotification;
/**
* This is the item provider adapter for a {@link net.opengis.gml.FeatureStyleType} object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public class FeatureStyleTypeItemProvider
extends AbstractGMLTypeItemProvider
implements
IEditingDomainItemProvider,
IStructuredItemContentProvider,
ITreeItemContentProvider,
IItemLabelProvider,
IItemPropertySource {
/**
* This constructs an instance from a factory and a notifier.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public FeatureStyleTypeItemProvider(AdapterFactory adapterFactory) {
super(adapterFactory);
}
/**
* This returns the property descriptors for the adapted class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public List<IItemPropertyDescriptor> getPropertyDescriptors(Object object) {
if (itemPropertyDescriptors == null) {
super.getPropertyDescriptors(object);
addFeatureConstraintPropertyDescriptor(object);
addBaseTypePropertyDescriptor(object);
addFeatureTypePropertyDescriptor(object);
addQueryGrammarPropertyDescriptor(object);
}
return itemPropertyDescriptors;
}
/**
* This adds a property descriptor for the Feature Constraint feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addFeatureConstraintPropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_FeatureStyleType_featureConstraint_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_FeatureStyleType_featureConstraint_feature", "_UI_FeatureStyleType_type"),
GmlPackage.eINSTANCE.getFeatureStyleType_FeatureConstraint(),
true,
false,
false,
ItemPropertyDescriptor.GENERIC_VALUE_IMAGE,
null,
null));
}
/**
* This adds a property descriptor for the Base Type feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addBaseTypePropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_FeatureStyleType_baseType_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_FeatureStyleType_baseType_feature", "_UI_FeatureStyleType_type"),
GmlPackage.eINSTANCE.getFeatureStyleType_BaseType(),
true,
false,
false,
ItemPropertyDescriptor.GENERIC_VALUE_IMAGE,
null,
null));
}
/**
* This adds a property descriptor for the Feature Type feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addFeatureTypePropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_FeatureStyleType_featureType_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_FeatureStyleType_featureType_feature", "_UI_FeatureStyleType_type"),
GmlPackage.eINSTANCE.getFeatureStyleType_FeatureType(),
true,
false,
false,
ItemPropertyDescriptor.GENERIC_VALUE_IMAGE,
null,
null));
}
/**
* This adds a property descriptor for the Query Grammar feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addQueryGrammarPropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_FeatureStyleType_queryGrammar_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_FeatureStyleType_queryGrammar_feature", "_UI_FeatureStyleType_type"),
GmlPackage.eINSTANCE.getFeatureStyleType_QueryGrammar(),
true,
false,
false,
ItemPropertyDescriptor.GENERIC_VALUE_IMAGE,
null,
null));
}
/**
* This specifies how to implement {@link #getChildren} and is used to deduce an appropriate feature for an
* {@link org.eclipse.emf.edit.command.AddCommand}, {@link org.eclipse.emf.edit.command.RemoveCommand} or
* {@link org.eclipse.emf.edit.command.MoveCommand} in {@link #createCommand}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Collection<? extends EStructuralFeature> getChildrenFeatures(Object object) {
if (childrenFeatures == null) {
super.getChildrenFeatures(object);
childrenFeatures.add(GmlPackage.eINSTANCE.getFeatureStyleType_GeometryStyle());
childrenFeatures.add(GmlPackage.eINSTANCE.getFeatureStyleType_TopologyStyle());
childrenFeatures.add(GmlPackage.eINSTANCE.getFeatureStyleType_LabelStyle());
}
return childrenFeatures;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EStructuralFeature getChildFeature(Object object, Object child) {
// Check the type of the specified child object and return the proper feature to use for
// adding (see {@link AddCommand}) it as a child.
return super.getChildFeature(object, child);
}
/**
* This returns FeatureStyleType.gif.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object getImage(Object object) {
return overlayImage(object, getResourceLocator().getImage("full/obj16/FeatureStyleType"));
}
/**
* This returns the label text for the adapted class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String getText(Object object) {
String label = ((FeatureStyleType)object).getId();
return label == null || label.length() == 0 ?
getString("_UI_FeatureStyleType_type") :
getString("_UI_FeatureStyleType_type") + " " + label;
}
/**
* This handles model notifications by calling {@link #updateChildren} to update any cached
* children and by creating a viewer notification, which it passes to {@link #fireNotifyChanged}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void notifyChanged(Notification notification) {
updateChildren(notification);
switch (notification.getFeatureID(FeatureStyleType.class)) {
case GmlPackage.FEATURE_STYLE_TYPE__FEATURE_CONSTRAINT:
case GmlPackage.FEATURE_STYLE_TYPE__BASE_TYPE:
case GmlPackage.FEATURE_STYLE_TYPE__FEATURE_TYPE:
case GmlPackage.FEATURE_STYLE_TYPE__QUERY_GRAMMAR:
fireNotifyChanged(new ViewerNotification(notification, notification.getNotifier(), false, true));
return;
case GmlPackage.FEATURE_STYLE_TYPE__GEOMETRY_STYLE:
case GmlPackage.FEATURE_STYLE_TYPE__TOPOLOGY_STYLE:
case GmlPackage.FEATURE_STYLE_TYPE__LABEL_STYLE:
fireNotifyChanged(new ViewerNotification(notification, notification.getNotifier(), true, false));
return;
}
super.notifyChanged(notification);
}
/**
* This adds {@link org.eclipse.emf.edit.command.CommandParameter}s describing the children
* that can be created under this object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected void collectNewChildDescriptors(Collection<Object> newChildDescriptors, Object object) {
super.collectNewChildDescriptors(newChildDescriptors, object);
newChildDescriptors.add
(createChildParameter
(GmlPackage.eINSTANCE.getFeatureStyleType_GeometryStyle(),
GmlFactory.eINSTANCE.createGeometryStylePropertyType()));
newChildDescriptors.add
(createChildParameter
(GmlPackage.eINSTANCE.getFeatureStyleType_TopologyStyle(),
GmlFactory.eINSTANCE.createTopologyStylePropertyType()));
newChildDescriptors.add
(createChildParameter
(GmlPackage.eINSTANCE.getFeatureStyleType_LabelStyle(),
GmlFactory.eINSTANCE.createLabelStylePropertyType()));
}
/**
* This returns the label text for {@link org.eclipse.emf.edit.command.CreateChildCommand}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String getCreateChildText(Object owner, Object feature, Object child, Collection<?> selection) {
Object childFeature = feature;
Object childObject = child;
if (childFeature instanceof EStructuralFeature && FeatureMapUtil.isFeatureMap((EStructuralFeature)childFeature)) {
FeatureMap.Entry entry = (FeatureMap.Entry)childObject;
childFeature = entry.getEStructuralFeature();
childObject = entry.getValue();
}
boolean qualify =
childFeature == GmlPackage.eINSTANCE.getAbstractGMLType_Name() ||
childFeature == GmlPackage.eINSTANCE.getDocumentRoot_CoordinateOperationName() ||
childFeature == GmlPackage.eINSTANCE.getDocumentRoot_CsName() ||
childFeature == GmlPackage.eINSTANCE.getDocumentRoot_DatumName() ||
childFeature == GmlPackage.eINSTANCE.getDocumentRoot_EllipsoidName() ||
childFeature == GmlPackage.eINSTANCE.getDocumentRoot_GroupName() ||
childFeature == GmlPackage.eINSTANCE.getDocumentRoot_MeridianName() ||
childFeature == GmlPackage.eINSTANCE.getDocumentRoot_MethodName() ||
childFeature == GmlPackage.eINSTANCE.getDocumentRoot_ParameterName() ||
childFeature == GmlPackage.eINSTANCE.getDocumentRoot_SrsName();
if (qualify) {
return getString
("_UI_CreateChild_text2",
new Object[] { getTypeText(childObject), getFeatureText(childFeature), getTypeText(owner) });
}
return super.getCreateChildText(owner, feature, child, selection);
}
}
| Java |
\section{ESRI}
\index{ESRI}
\index{Environmental Systems Research Institute}
Environmental Systems Research Institute (ESRI) offers geospatial related data
services and process online through its proprietary API. Features of the ESRI
platform include access to basemaps, geocoding, demographic data, a dynamic
world atlas, and multiple data sets in a open-data resource~\cite{hid-sp18-505-ESRI2018}.
| Java |
# Copyright 2021 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.
"""GKE nodes service account permissions for logging.
The service account used by GKE nodes should have the logging.logWriter
role, otherwise ingestion of logs won't work.
"""
from gcpdiag import lint, models
from gcpdiag.queries import gke, iam
ROLE = 'roles/logging.logWriter'
def prefetch_rule(context: models.Context):
# Make sure that we have the IAM policy in cache.
project_ids = {c.project_id for c in gke.get_clusters(context).values()}
for pid in project_ids:
iam.get_project_policy(pid)
def run_rule(context: models.Context, report: lint.LintReportRuleInterface):
# Find all clusters with logging enabled.
clusters = gke.get_clusters(context)
iam_policy = iam.get_project_policy(context.project_id)
if not clusters:
report.add_skipped(None, 'no clusters found')
for _, c in sorted(clusters.items()):
if not c.has_logging_enabled():
report.add_skipped(c, 'logging disabled')
else:
# Verify service-account permissions for every nodepool.
for np in c.nodepools:
sa = np.service_account
if not iam.is_service_account_enabled(sa, context.project_id):
report.add_failed(np, f'service account disabled or deleted: {sa}')
elif not iam_policy.has_role_permissions(f'serviceAccount:{sa}', ROLE):
report.add_failed(np, f'service account: {sa}\nmissing role: {ROLE}')
else:
report.add_ok(np)
| Java |
package sarama
// ApiVersionsRequest ...
type ApiVersionsRequest struct{}
func (a *ApiVersionsRequest) encode(pe packetEncoder) error {
return nil
}
func (a *ApiVersionsRequest) decode(pd packetDecoder, version int16) (err error) {
return nil
}
func (a *ApiVersionsRequest) key() int16 {
return 18
}
func (a *ApiVersionsRequest) version() int16 {
return 0
}
func (a *ApiVersionsRequest) headerVersion() int16 {
return 1
}
func (a *ApiVersionsRequest) requiredVersion() KafkaVersion {
return V0_10_0_0
}
| Java |
/*
* 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.neptune.model;
import java.io.Serializable;
import javax.annotation.Generated;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/neptune-2014-10-31/RemoveRoleFromDBCluster" target="_top">AWS
* API Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class RemoveRoleFromDBClusterResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof RemoveRoleFromDBClusterResult == false)
return false;
RemoveRoleFromDBClusterResult other = (RemoveRoleFromDBClusterResult) obj;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
return hashCode;
}
@Override
public RemoveRoleFromDBClusterResult clone() {
try {
return (RemoveRoleFromDBClusterResult) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
}
| Java |
<!DOCTYPE html>
<html>
<head>
<title>Startup Cookie Manager</title>
</head>
<body>
<h3 title="example.com will preserve example.com, and *.example.com cookies.">Cookie whitelist (include subdomains)</h3>
<p title="example.com will preserve example.com, and *.example.com cookies.">
<textarea id="subdomain-whitelist" rows="4" cols="50"></textarea>
</p>
<h3 title="example.com will preserve example.com, .example.com, and www.example.com cookies.">Cookie whitelist (root domains only)</h3>
<p title="example.com will preserve example.com, .example.com, and www.example.com cookies.">
<textarea id="domain-only-whitelist" rows="4" cols="50"></textarea>
</p>
<h3 title="Additional tasks to perform whenever cookies and site data are cleared.">Additional settings</h3>
<p>
<input type="checkbox" id="cache_option">
<label for="cache_option">Clear cache.</label>
</p>
<p>
<input type="checkbox" id="history_option">
<label for="history_option">Clear history.</label>
</p>
<p align="center" style="color:grey;">
Developed by <a href="https://aaronhorler.com">Aaron Horler</a> (aghorler) | <a href="https://github.com/aghorler/Startup-Cookie-Destroyer">GitHub source</a>
</p>
<script src="/js/options.js"></script>
</body>
</html>
| Java |
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" charset="UTF-8">
<title>minus</title>
<link href="../../../images/logo-icon.svg" rel="icon" type="image/svg">
<script>var pathToRoot = "../../../";</script>
<script type="text/javascript" src="../../../scripts/sourceset_dependencies.js" async="async"></script>
<link href="../../../styles/style.css" rel="Stylesheet">
<link href="../../../styles/logo-styles.css" rel="Stylesheet">
<link href="../../../styles/jetbrains-mono.css" rel="Stylesheet">
<link href="../../../styles/main.css" rel="Stylesheet">
<script type="text/javascript" src="../../../scripts/clipboard.js" async="async"></script>
<script type="text/javascript" src="../../../scripts/navigation-loader.js" async="async"></script>
<script type="text/javascript" src="../../../scripts/platform-content-handler.js" async="async"></script>
<script type="text/javascript" src="../../../scripts/main.js" async="async"></script>
</head>
<body>
<div id="container">
<div id="leftColumn">
<div id="logo"></div>
<div id="paneSearch"></div>
<div id="sideMenu"></div>
</div>
<div id="main">
<div id="leftToggler"><span class="icon-toggler"></span></div>
<script type="text/javascript" src="../../../scripts/pages.js"></script>
<script type="text/javascript" src="../../../scripts/main.js"></script>
<div class="main-content" id="content" pageIds="org.hexworks.zircon.api.data/Rect/minus/#org.hexworks.zircon.api.data.Rect/PointingToDeclaration//-828656838">
<div class="navigation-wrapper" id="navigation-wrapper">
<div class="breadcrumbs"><a href="../../index.html">zircon.core</a>/<a href="../index.html">org.hexworks.zircon.api.data</a>/<a href="index.html">Rect</a>/<a href="minus.html">minus</a></div>
<div class="pull-right d-flex">
<div class="filter-section" id="filter-section"><button class="platform-tag platform-selector common-like" data-active="" data-filter=":zircon.core:dokkaHtml/commonMain">common</button></div>
<div id="searchBar"></div>
</div>
</div>
<div class="cover ">
<h1 class="cover"><span>minus</span></h1>
</div>
<div class="divergent-group" data-filterable-current=":zircon.core:dokkaHtml/commonMain" data-filterable-set=":zircon.core:dokkaHtml/commonMain"><div class="with-platform-tags"><span class="pull-right"></span></div>
<div>
<div class="platform-hinted " data-platform-hinted="data-platform-hinted"><div class="content sourceset-depenent-content" data-active="" data-togglable=":zircon.core:dokkaHtml/commonMain"><div class="symbol monospace">abstract operator fun <a href="minus.html">minus</a>(rect: <a href="index.html">Rect</a>): <a href="index.html">Rect</a><span class="top-right-position"><span class="copy-icon"></span><div class="copy-popup-wrapper popup-to-left"><span class="copy-popup-icon"></span><span>Content copied to clipboard</span></div></span></div></div></div>
</div>
</div>
<h2 class="">Sources</h2>
<div class="table" data-togglable="Sources"><a data-name="%5Borg.hexworks.zircon.api.data%2FRect%2Fminus%2F%23org.hexworks.zircon.api.data.Rect%2FPointingToDeclaration%2F%5D%2FSource%2F-828656838" anchor-label="https://github.com/Hexworks/zircon/tree/master/zircon.core/src/commonMain/kotlin/org/hexworks/zircon/api/data/Rect.kt#L50" id="%5Borg.hexworks.zircon.api.data%2FRect%2Fminus%2F%23org.hexworks.zircon.api.data.Rect%2FPointingToDeclaration%2F%5D%2FSource%2F-828656838" data-filterable-set=":zircon.core:dokkaHtml/commonMain"></a>
<div class="table-row" data-filterable-current=":zircon.core:dokkaHtml/commonMain" data-filterable-set=":zircon.core:dokkaHtml/commonMain">
<div class="main-subrow keyValue ">
<div class=""><span class="inline-flex"><a href="https://github.com/Hexworks/zircon/tree/master/zircon.core/src/commonMain/kotlin/org/hexworks/zircon/api/data/Rect.kt#L50">(source)</a><span class="anchor-wrapper"><span class="anchor-icon" pointing-to="%5Borg.hexworks.zircon.api.data%2FRect%2Fminus%2F%23org.hexworks.zircon.api.data.Rect%2FPointingToDeclaration%2F%5D%2FSource%2F-828656838"></span>
<div class="copy-popup-wrapper "><span class="copy-popup-icon"></span><span>Link copied to clipboard</span></div>
</span></span></div>
<div></div>
</div>
</div>
</div>
</div>
<div class="footer"><span class="go-to-top-icon"><a href="#content"></a></span><span>© 2020 Copyright</span><span class="pull-right"><span>Sponsored and developed by dokka</span><a href="https://github.com/Kotlin/dokka"><span class="padded-icon"></span></a></span></div>
</div>
</div>
</body>
</html>
| Java |
using System.Collections.Generic;
namespace Microsoft.Xna.Framework.Graphics
{
internal partial class DXConstantBufferData
{
public string Name { get; private set; }
public int Size { get; private set; }
public List<int> ParameterIndex { get; private set; }
public List<int> ParameterOffset { get; private set; }
public List<DXEffectObject.d3dx_parameter> Parameters { get; private set; }
public bool SameAs(DXConstantBufferData other)
{
// If the names of the constant buffers don't
// match then consider them different right off
// the bat... even if their parameters are the same.
if (Name != other.Name)
return false;
// Do we have the same count of parameters and size?
if ( Size != other.Size ||
Parameters.Count != other.Parameters.Count)
return false;
// Compare the parameters themselves.
for (var i = 0; i < Parameters.Count; i++)
{
var p1 = Parameters[i];
var p2 = other.Parameters[i];
// Check the importaint bits.
if ( p1.name != p2.name ||
p1.rows != p2.rows ||
p1.columns != p2.columns ||
p1.class_ != p2.class_ ||
p1.type != p2.type ||
p1.bufferOffset != p2.bufferOffset)
return false;
}
// These are equal.
return true;
}
}
}
| Java |
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="{{ site.description }}">
<title>{% if page.title %}{{ page.title }} - {{ site.title }}{% else %}{{ site.title }}{% endif %}</title>
<link rel="canonical" href="{{ page.url | replace:'index.html','' | prepend: site.baseurl | prepend: site.url }}">
<!-- Bootstrap Core CSS -->
<link rel="stylesheet" href="{{ "/css/bootstrap.min.css" | prepend: site.baseurl }}">
<!-- Custom CSS -->
<link rel="stylesheet" href="{{ "/css/clean-blog.css" | prepend: site.baseurl }}">
<link rel="stylesheet" href="{{ "/css/style.css" | prepend: site.baseurl }}">
<!-- Pygments Github CSS -->
<link rel="stylesheet" href="{{ "/css/syntax.css" | prepend: site.baseurl }}">
<!-- Custom Fonts -->
<link href="http://maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">
<link href='http://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
| Java |
PUSH
====
An open framework that allows data to be pushed from a server to a client
| Java |
<!--
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.
-->
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- **************************************************************** -->
<!-- * PLEASE KEEP COMPLICATED EXPRESSIONS OUT OF THESE TEMPLATES, * -->
<!-- * i.e. only iterate & print data where possible. Thanks, Jez. * -->
<!-- **************************************************************** -->
<html>
<head>
<!-- Generated by groovydoc -->
<title>VersionStrategies (Gradle Wooga Release plugin API)</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link href="../../../../../groovy.ico" type="image/x-icon" rel="shortcut icon">
<link href="../../../../../groovy.ico" type="image/x-icon" rel="icon">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
<body class="center">
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="VersionStrategies (Gradle Wooga Release plugin API)";
}
//-->
</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="../../../../../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">
<div>
<ul class="navList">
<li><a href="../../../../../index.html?wooga/gradle/release/version/semver/VersionStrategies" target="_top">Frames</a></li>
<li><a href="VersionStrategies.html" target="_top">No Frames</a></li>
</ul>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
Nested Field <li><a href="#property_summary">Property</a></li> Constructor Method
</ul>
<ul class="subNavList">
<li> | Detail: </li>
Field <li><a href="#prop_detail">Property</a></li> Constructor Method
</ul>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">Package: <strong>wooga.gradle.release.version.semver</strong></div>
<h2 title="[Groovy] Class VersionStrategies" class="title">[Groovy] Class VersionStrategies</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li><ul class="inheritance"></ul></li><li>wooga.gradle.release.version.semver.VersionStrategies
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- =========== NESTED CLASS SUMMARY =========== -->
<!-- =========== ENUM CONSTANT SUMMARY =========== -->
<!-- =========== FIELD SUMMARY =========== -->
<!-- =========== PROPERTY SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="property_summary"><!-- --></a>
<h3>Properties Summary</h3>
<ul class="blockList">
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Properties Summary table, listing nested classes, and an explanation">
<caption><span>Properties</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Type</th>
<th class="colLast" scope="col">Name and description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code><strong>static org.ajoberstar.gradle.git.release.semver.PartialSemVerStrategy</strong></code> </td>
<td class="colLast"><code><a href="#COUNT_INCREMENTED">COUNT_INCREMENTED</a></code><br></td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code><strong>static org.ajoberstar.gradle.git.release.semver.SemVerStrategy</strong></code> </td>
<td class="colLast"><code><a href="#DEVELOPMENT">DEVELOPMENT</a></code><br>Returns a version strategy to be used for <CODE>development</CODE> builds.</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code><strong>static org.ajoberstar.gradle.git.release.semver.SemVerStrategy</strong></code> </td>
<td class="colLast"><code><a href="#FINAL">FINAL</a></code><br>Returns a version strategy to be used for <CODE>final</CODE> builds.</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code><strong>static org.ajoberstar.gradle.git.release.semver.SemVerStrategy</strong></code> </td>
<td class="colLast"><code><a href="#PRE_RELEASE">PRE_RELEASE</a></code><br>Returns a version strategy to be used for <CODE>pre-release</CODE>/<CODE>candidate</CODE> builds.</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code><strong>static org.ajoberstar.gradle.git.release.semver.SemVerStrategy</strong></code> </td>
<td class="colLast"><code><a href="#SNAPSHOT">SNAPSHOT</a></code><br>Returns a version strategy to be used for <CODE>snapshot</CODE> builds.</td>
</tr>
</table>
</ul>
</li>
</ul>
<!-- =========== ELEMENT SUMMARY =========== -->
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method_summary"><!-- --></a>
<h3>Inherited Methods Summary</h3>
<ul class="blockList">
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Inherited Methods Summary table">
<caption><span>Inherited Methods</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Methods inherited from class</th>
<th class="colLast" scope="col">Name</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>class java.lang.Object</code></td>
<td class="colLast"><code>java.lang.Object#wait(long, int), java.lang.Object#wait(long), java.lang.Object#wait(), java.lang.Object#equals(java.lang.Object), java.lang.Object#toString(), java.lang.Object#hashCode(), java.lang.Object#getClass(), java.lang.Object#notify(), java.lang.Object#notifyAll()</code></td>
</tr>
</table>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- =========== PROPERTY DETAIL =========== -->
<ul class="blockList">
<li class="blockList"><a name="prop_detail">
<!-- -->
</a>
<h3>Property Detail</h3>
<a name="COUNT_INCREMENTED"><!-- --></a>
<ul class="blockListLast">
<li class="blockList">
<h4>static final org.ajoberstar.gradle.git.release.semver.PartialSemVerStrategy <strong>COUNT_INCREMENTED</strong></h4>
<p></p>
</li>
</ul>
<a name="DEVELOPMENT"><!-- --></a>
<ul class="blockListLast">
<li class="blockList">
<h4>static final org.ajoberstar.gradle.git.release.semver.SemVerStrategy <strong>DEVELOPMENT</strong></h4>
<p> Returns a version strategy to be used for <CODE>development</CODE> builds.
<p>
This strategy creates a unique version string based on last commit hash and the
distance of commits to nearest normal version.
This version string is not compatible with <a href="https://fsprojects.github.io/Paket/">Paket</a> or
<a href="https://www.nuget.org/">Nuget</a>
<p>
Example:
<pre>
<CODE>releaseScope = "minor"
nearestVersion = "1.3.0"
commitHash = "90c90b9"
distance = 22
inferred = "1.3.0-dev.22+90c90b9"
</CODE>
</pre>
</p>
</li>
</ul>
<a name="FINAL"><!-- --></a>
<ul class="blockListLast">
<li class="blockList">
<h4>static final org.ajoberstar.gradle.git.release.semver.SemVerStrategy <strong>FINAL</strong></h4>
<p> Returns a version strategy to be used for <CODE>final</CODE> builds.
<p>
This strategy infers the release version by checking the nearest release.
<p>
Example:
<pre>
<CODE>releaseScope = "minor"
nearestVersion = "1.3.0"
inferred = "1.4.0"
</CODE>
</pre>
</p>
</li>
</ul>
<a name="PRE_RELEASE"><!-- --></a>
<ul class="blockListLast">
<li class="blockList">
<h4>static final org.ajoberstar.gradle.git.release.semver.SemVerStrategy <strong>PRE_RELEASE</strong></h4>
<p> Returns a version strategy to be used for <CODE>pre-release</CODE>/<CODE>candidate</CODE> builds.
<p>
This strategy infers the release version by checking the nearest any release.
If a <CODE>pre-release</CODE> with the same <CODE>major</CODE>.<CODE>minor</CODE>.<CODE>patch</CODE> version exists, bumps the count part.
<p>
Example <i>new pre release</i>:
<pre>
<CODE>releaseScope = "minor"
nearestVersion = "1.2.0"
nearestAnyVersion = ""
inferred = "1.3.0-rc00001"
</CODE>
</pre>
<p>
Example <i>pre release version exists</i>:
<pre>
<CODE>releaseScope = "minor"
nearestVersion = "1.2.0"
nearestAnyVersion = "1.3.0-rc00001"
inferred = "1.3.0-rc00002"
</CODE>
</pre>
<p>
Example <i>last final release higher than pre-release</i>:
<pre>
<CODE>releaseScope = "minor"
nearestVersion = "1.3.0"
nearestAnyVersion = "1.3.0-rc00001"
inferred = "1.4.0-rc00001"
</CODE>
</pre>
</p>
</li>
</ul>
<a name="SNAPSHOT"><!-- --></a>
<ul class="blockListLast">
<li class="blockList">
<h4>static final org.ajoberstar.gradle.git.release.semver.SemVerStrategy <strong>SNAPSHOT</strong></h4>
<p> Returns a version strategy to be used for <CODE>snapshot</CODE> builds.
<p>
This strategy creates a snapshot version suitable for <a href="https://fsprojects.github.io/Paket/">Paket</a> and
<a href="https://www.nuget.org/">Nuget</a>. <CODE>Nuget</CODE> and <CODE>Paket</CODE> don't support
<CODE>SNAPSHOT</CODE> versions or any numerical values after the <CODE>patch</CODE> component. We trick these package managers
by creating a unique version based on <CODE>branch</CODE> and the distance of commits to nearest normal version.
If the branch name contains numerical values, they will be converted into alphanumerical counterparts.
The <CODE>master</CODE> branch is a special case so it will end up being higher than any other branch build (m>b)
<p>
Example <i>from master branch</i>:
<pre>
<CODE>releaseScope = "minor"
nearestVersion = "1.3.0"
branch = "master"
distance = 22
inferred = "1.4.0-master00022"
</CODE>
</pre>
<p>
Example <i>from topic branch</i>:
<pre>
<CODE>releaseScope = "minor"
nearestVersion = "1.3.0"
branch = "feature/fix_22"
distance = 34
inferred = "1.4.0-branchFeatureFixTwoTow00034"
</CODE>
</pre>
</p>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</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="../../../../../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">
<div>
<ul class="navList">
<li><a href="../../../../../index.html?wooga/gradle/release/version/semver/VersionStrategies" target="_top">Frames</a></li>
<li><a href="VersionStrategies.html" target="_top">No Frames</a></li>
</ul>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
Nested Field <li><a href="#property_summary">Property</a></li> Constructor Method
</ul>
<ul class="subNavList">
<li> | Detail: </li>
Field <li><a href="#prop_detail">Property</a></li> Constructor Method
</ul>
</div>
<p>Gradle Wooga Release plugin API</p>
<a name="skip-navbar_bottom">
<!-- -->
</a>
</div>
</div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| Java |
/**
* @file XMLConstructorException.h
* @brief XMLConstructorException an exception thrown by XML classes
* @author Ben Bornstein
*
* <!--------------------------------------------------------------------------
* This file is part of libSBML. Please visit http://sbml.org for more
* information about SBML, and the latest version of libSBML.
*
* Copyright (C) 2013-2015 jointly by the following organizations:
* 1. California Institute of Technology, Pasadena, CA, USA
* 2. EMBL European Bioinformatics Institute (EMBL-EBI), Hinxton, UK
* 3. University of Heidelberg, Heidelberg, Germany
*
* Copyright (C) 2009-2013 jointly by the following organizations:
* 1. California Institute of Technology, Pasadena, CA, USA
* 2. EMBL European Bioinformatics Institute (EMBL-EBI), Hinxton, UK
*
* Copyright (C) 2006-2008 by the California Institute of Technology,
* Pasadena, CA, USA
*
* Copyright (C) 2002-2005 jointly by the following organizations:
* 1. California Institute of Technology, Pasadena, CA, USA
* 2. Japan Science and Technology Agency, Japan
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation. A copy of the license agreement is provided
* in the file named "LICENSE.txt" included with this software distribution
* and also available online as http://sbml.org/software/libsbml/license.html
* ------------------------------------------------------------------------ -->
*
* @class XMLConstructorException
* @sbmlbrief{core} Exceptions thrown by some libSBML constructors.
*
* @htmlinclude not-sbml-warning.html
*
* In some situations, constructors for SBML objects may need to indicate
* to callers that the creation of the object failed. The failure may be
* for different reasons, such as an attempt to use invalid parameters or a
* system condition such as a memory error. To communicate this to
* callers, those classes will throw an XMLConstructorException. @if cpp
* Callers can use the standard C++ <code>std::exception</code> method
* <code>what()</code> to extract the diagnostic message stored with the
* exception.@endif@~
* <p>
* In languages that don't have an exception mechanism (e.g., C), the
* constructors generally try to return an error code instead of throwing
* an exception.
*
* @see SBMLConstructorException
*/
#ifndef XMLConstructorException_h
#define XMLConstructorException_h
#include <sbml/common/sbmlfwd.h>
#ifdef __cplusplus
#include <string>
#include <stdexcept>
LIBSBML_CPP_NAMESPACE_BEGIN
class LIBSBML_EXTERN XMLConstructorException : public std::invalid_argument
{
public:
/** @cond doxygenLibsbmlInternal */
/* constructor */
XMLConstructorException (std::string
message="NULL reference in XML constructor");
/** @endcond */
};
LIBSBML_CPP_NAMESPACE_END
#endif /* __cplusplus */
#ifndef SWIG
LIBSBML_CPP_NAMESPACE_BEGIN
BEGIN_C_DECLS
END_C_DECLS
LIBSBML_CPP_NAMESPACE_END
#endif /* !SWIG */
#endif /* XMLConstructorException_h */
| Java |
package ru.istolbov;
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
/**
* Test.
* @author istolbov
* @version $Id$
*/
public class TurnTest {
/**
* Test turn back array.
*/
@Test
public void whenWeTurnBackArray() {
final int[] targetArray = new int[] {5, 4, 3, 2, 1};
final int[] testArray = new int[] {1, 2, 3, 4, 5};
final Turn turn = new Turn();
final int[] resultArray = turn.back(testArray);
assertThat(resultArray, is(targetArray));
}
/**
* Test sort.
*/
@Test
public void whenWeSortArray() {
final int[] targetArray = new int[] {1, 2, 3, 4, 5};
final int[] testArray = new int[] {5, 3, 4, 1, 2};
final Turn turn = new Turn();
final int[] resultArray = turn.sort(testArray);
assertThat(resultArray, is(targetArray));
}
/**
* Test rotate.
*/
@Test
public void whenWeRotateArray() {
final int[][] targetArray = new int[][] {{13, 9, 5, 1}, {14, 10, 6, 2}, {15, 11, 7, 3}, {16, 12, 8, 4}};
final int[][] testArray = new int[][] {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}};
final Turn turn = new Turn();
final int[][] resultArray = turn.rotate(testArray);
assertThat(resultArray, is(targetArray));
}
/**
* Test duplicateDelete.
*/
@Test
public void whenWeDuplicateDeleteInArray() {
final String[] targetArray = new String[] {"Привет", "Мир", "Май"};
final String[] testArray = new String[] {"Привет", "Привет", "Мир", "Привет", "Май", "Май", "Мир"};
final Turn turn = new Turn();
final String[] resultArray = turn.duplicateDelete(testArray);
assertThat(resultArray, is(targetArray));
}
/**
* Test join.
*/
@Test
public void whenWeJoinArrays() {
final int[] firstTestArray = new int[] {1, 3, 5, 7, 9};
final int[] secondTestArray = new int[] {2, 4, 6, 8, 10};
final int[] targetArray = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
final Turn turn = new Turn();
final int[] resultArray = turn.join(firstTestArray, secondTestArray);
assertThat(resultArray, is(targetArray));
}
} | Java |
""" Launcher functionality for the Google Compute Engine (GCE)
"""
import json
import logging
import os
from dcos_launch import onprem, util
from dcos_launch.platforms import gcp
from dcos_test_utils.helpers import Host
from googleapiclient.errors import HttpError
log = logging.getLogger(__name__)
def get_credentials(env=None) -> tuple:
path = None
if env is None:
env = os.environ.copy()
if 'GCE_CREDENTIALS' in env:
json_credentials = env['GCE_CREDENTIALS']
elif 'GOOGLE_APPLICATION_CREDENTIALS' in env:
path = env['GOOGLE_APPLICATION_CREDENTIALS']
json_credentials = util.read_file(path)
else:
raise util.LauncherError(
'MissingParameter', 'Either GCE_CREDENTIALS or GOOGLE_APPLICATION_CREDENTIALS must be set in env')
return json_credentials, path
class OnPremLauncher(onprem.AbstractOnpremLauncher):
# Launches a homogeneous cluster of plain GMIs intended for onprem DC/OS
def __init__(self, config: dict, env=None):
creds_string, _ = get_credentials(env)
self.gcp_wrapper = gcp.GcpWrapper(json.loads(creds_string))
self.config = config
@property
def deployment(self):
""" Builds a BareClusterDeployment instance with self.config, but only returns it successfully if the
corresponding real deployment (active machines) exists and doesn't contain any errors.
"""
try:
deployment = gcp.BareClusterDeployment(self.gcp_wrapper, self.config['deployment_name'],
self.config['gce_zone'])
info = deployment.get_info()
errors = info['operation'].get('error')
if errors:
raise util.LauncherError('DeploymentContainsErrors', str(errors))
return deployment
except HttpError as e:
if e.resp.status == 404:
raise util.LauncherError('DeploymentNotFound',
"The deployment you are trying to access doesn't exist") from e
raise e
def create(self) -> dict:
self.key_helper()
node_count = 1 + (self.config['num_masters'] + self.config['num_public_agents']
+ self.config['num_private_agents'])
gcp.BareClusterDeployment.create(
self.gcp_wrapper,
self.config['deployment_name'],
self.config['gce_zone'],
node_count,
self.config['disk_size'],
self.config['disk_type'],
self.config['source_image'],
self.config['machine_type'],
self.config['image_project'],
self.config['ssh_user'],
self.config['ssh_public_key'],
self.config['disable_updates'],
self.config['use_preemptible_vms'],
tags=self.config.get('tags'))
return self.config
def key_helper(self):
""" Generates a public key and a private key and stores them in the config. The public key will be applied to
all the instances in the deployment later on when wait() is called.
"""
if self.config['key_helper']:
private_key, public_key = util.generate_rsa_keypair()
self.config['ssh_private_key'] = private_key.decode()
self.config['ssh_public_key'] = public_key.decode()
def get_cluster_hosts(self) -> [Host]:
return list(self.deployment.hosts)[1:]
def get_bootstrap_host(self) -> Host:
return list(self.deployment.hosts)[0]
def wait(self):
""" Waits for the deployment to complete: first, the network that will contain the cluster is deployed. Once
the network is deployed, a firewall for the network and an instance template are deployed. Finally,
once the instance template is deployed, an instance group manager and all its instances are deployed.
"""
self.deployment.wait_for_completion()
def delete(self):
""" Deletes all the resources associated with the deployment (instance template, network, firewall, instance
group manager and all its instances.
"""
self.deployment.delete()
| Java |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("ConsoleApplication2")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("jd")]
[assembly: AssemblyProduct("ConsoleApplication2")]
[assembly: AssemblyCopyright("Copyright © jd 2011")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("54da768a-cc04-48a7-892b-57549b90159e")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| Java |
package javay.test.security;
import java.security.Key;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
/**
* DES安全编码组件
*
* <pre>
* 支持 DES、DESede(TripleDES,就是3DES)、AES、Blowfish、RC2、RC4(ARCFOUR)
* DES key size must be equal to 56
* DESede(TripleDES) key size must be equal to 112 or 168
* AES key size must be equal to 128, 192 or 256,but 192 and 256 bits may not be available
* Blowfish key size must be multiple of 8, and can only range from 32 to 448 (inclusive)
* RC2 key size must be between 40 and 1024 bits
* RC4(ARCFOUR) key size must be between 40 and 1024 bits
* 具体内容 需要关注 JDK Document http://.../docs/technotes/guides/security/SunProviders.html
* </pre>
*
*/
public abstract class DESCoder extends Coder {
/**
* ALGORITHM 算法 <br>
* 可替换为以下任意一种算法,同时key值的size相应改变。
*
* <pre>
* DES key size must be equal to 56
* DESede(TripleDES) key size must be equal to 112 or 168
* AES key size must be equal to 128, 192 or 256,but 192 and 256 bits may not be available
* Blowfish key size must be multiple of 8, and can only range from 32 to 448 (inclusive)
* RC2 key size must be between 40 and 1024 bits
* RC4(ARCFOUR) key size must be between 40 and 1024 bits
* </pre>
*
* 在Key toKey(byte[] key)方法中使用下述代码
* <code>SecretKey secretKey = new SecretKeySpec(key, ALGORITHM);</code> 替换
* <code>
* DESKeySpec dks = new DESKeySpec(key);
* SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
* SecretKey secretKey = keyFactory.generateSecret(dks);
* </code>
*/
public static final String ALGORITHM = "DES";
/**
* 转换密钥<br>
*
* @param key
* @return
* @throws Exception
*/
private static Key toKey(byte[] key) throws Exception {
DESKeySpec dks = new DESKeySpec(key);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
SecretKey secretKey = keyFactory.generateSecret(dks);
// 当使用其他对称加密算法时,如AES、Blowfish等算法时,用下述代码替换上述三行代码
// SecretKey secretKey = new SecretKeySpec(key, ALGORITHM);
return secretKey;
}
/**
* 解密
*
* @param data
* @param key
* @return
* @throws Exception
*/
public static byte[] decrypt(byte[] data, String key) throws Exception {
Key k = toKey(decryptBASE64(key));
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, k);
return cipher.doFinal(data);
}
/**
* 加密
*
* @param data
* @param key
* @return
* @throws Exception
*/
public static byte[] encrypt(byte[] data, String key) throws Exception {
Key k = toKey(decryptBASE64(key));
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, k);
return cipher.doFinal(data);
}
/**
* 生成密钥
*
* @return
* @throws Exception
*/
public static String initKey() throws Exception {
return initKey(null);
}
/**
* 生成密钥
*
* @param seed
* @return
* @throws Exception
*/
public static String initKey(String seed) throws Exception {
SecureRandom secureRandom = null;
if (seed != null) {
secureRandom = new SecureRandom(decryptBASE64(seed));
} else {
secureRandom = new SecureRandom();
}
KeyGenerator kg = KeyGenerator.getInstance(ALGORITHM);
kg.init(secureRandom);
SecretKey secretKey = kg.generateKey();
return encryptBASE64(secretKey.getEncoded());
}
}
| Java |
---
title: TiDB 简介
aliases: ['/docs-cn/dev/overview/','/docs-cn/dev/key-features/']
---
# TiDB 简介
[TiDB](https://github.com/pingcap/tidb) 是 [PingCAP](https://pingcap.com/about-cn/) 公司自主设计、研发的开源分布式关系型数据库,是一款同时支持在线事务处理与在线分析处理 (Hybrid Transactional and Analytical Processing, HTAP) 的融合型分布式数据库产品,具备水平扩容或者缩容、金融级高可用、实时 HTAP、云原生的分布式数据库、兼容 MySQL 5.7 协议和 MySQL 生态等重要特性。目标是为用户提供一站式 OLTP (Online Transactional Processing)、OLAP (Online Analytical Processing)、HTAP 解决方案。TiDB 适合高可用、强一致要求较高、数据规模较大等各种应用场景。
关于 TiDB 的关键技术创新,请观看以下视频。
<video src="https://tidb-docs.s3.us-east-2.amazonaws.com/compressed+-+Lesson+01.mp4" width="600px" height="450px" controls="controls" poster="https://tidb-docs.s3.us-east-2.amazonaws.com/thumbnail+-+lesson+1.png"></video>
## 五大核心特性
- 一键水平扩容或者缩容
得益于 TiDB 存储计算分离的架构的设计,可按需对计算、存储分别进行在线扩容或者缩容,扩容或者缩容过程中对应用运维人员透明。
- 金融级高可用
数据采用多副本存储,数据副本通过 Multi-Raft 协议同步事务日志,多数派写入成功事务才能提交,确保数据强一致性且少数副本发生故障时不影响数据的可用性。可按需配置副本地理位置、副本数量等策略满足不同容灾级别的要求。
- 实时 HTAP
提供行存储引擎 [TiKV](/tikv-overview.md)、列存储引擎 [TiFlash](/tiflash/tiflash-overview.md) 两款存储引擎,TiFlash 通过 Multi-Raft Learner 协议实时从 TiKV 复制数据,确保行存储引擎 TiKV 和列存储引擎 TiFlash 之间的数据强一致。TiKV、TiFlash 可按需部署在不同的机器,解决 HTAP 资源隔离的问题。
- 云原生的分布式数据库
专为云而设计的分布式数据库,通过 [TiDB Operator](https://docs.pingcap.com/zh/tidb-in-kubernetes/stable/tidb-operator-overview) 可在公有云、私有云、混合云中实现部署工具化、自动化。
- 兼容 MySQL 5.7 协议和 MySQL 生态
兼容 MySQL 5.7 协议、MySQL 常用的功能、MySQL 生态,应用无需或者修改少量代码即可从 MySQL 迁移到 TiDB。提供丰富的[数据迁移工具](/ecosystem-tool-user-guide.md)帮助应用便捷完成数据迁移。
## 四大核心应用场景
- 对数据一致性及高可靠、系统高可用、可扩展性、容灾要求较高的金融行业属性的场景
众所周知,金融行业对数据一致性及高可靠、系统高可用、可扩展性、容灾要求较高。传统的解决方案是同城两个机房提供服务、异地一个机房提供数据容灾能力但不提供服务,此解决方案存在以下缺点:资源利用率低、维护成本高、RTO (Recovery Time Objective) 及 RPO (Recovery Point Objective) 无法真实达到企业所期望的值。TiDB 采用多副本 + Multi-Raft 协议的方式将数据调度到不同的机房、机架、机器,当部分机器出现故障时系统可自动进行切换,确保系统的 RTO <= 30s 及 RPO = 0。
- 对存储容量、可扩展性、并发要求较高的海量数据及高并发的 OLTP 场景
随着业务的高速发展,数据呈现爆炸性的增长,传统的单机数据库无法满足因数据爆炸性的增长对数据库的容量要求,可行方案是采用分库分表的中间件产品或者 NewSQL 数据库替代、采用高端的存储设备等,其中性价比最大的是 NewSQL 数据库,例如:TiDB。TiDB 采用计算、存储分离的架构,可对计算、存储分别进行扩容和缩容,计算最大支持 512 节点,每个节点最大支持 1000 并发,集群容量最大支持 PB 级别。
- Real-time HTAP 场景
随着 5G、物联网、人工智能的高速发展,企业所生产的数据会越来越多,其规模可能达到数百 TB 甚至 PB 级别,传统的解决方案是通过 OLTP 型数据库处理在线联机交易业务,通过 ETL 工具将数据同步到 OLAP 型数据库进行数据分析,这种处理方案存在存储成本高、实时性差等多方面的问题。TiDB 在 4.0 版本中引入列存储引擎 TiFlash 结合行存储引擎 TiKV 构建真正的 HTAP 数据库,在增加少量存储成本的情况下,可以同一个系统中做联机交易处理、实时数据分析,极大地节省企业的成本。
- 数据汇聚、二次加工处理的场景
当前绝大部分企业的业务数据都分散在不同的系统中,没有一个统一的汇总,随着业务的发展,企业的决策层需要了解整个公司的业务状况以便及时做出决策,故需要将分散在各个系统的数据汇聚在同一个系统并进行二次加工处理生成 T+0 或 T+1 的报表。传统常见的解决方案是采用 ETL + Hadoop 来完成,但 Hadoop 体系太复杂,运维、存储成本太高无法满足用户的需求。与 Hadoop 相比,TiDB 就简单得多,业务通过 ETL 工具或者 TiDB 的同步工具将数据同步到 TiDB,在 TiDB 中可通过 SQL 直接生成报表。
关于 TiDB 典型应用场景和用户案例的介绍,请观看以下视频。
<video src="https://tidb-docs.s3.us-east-2.amazonaws.com/compressed+-+Lesson+06.mp4" width="600px" height="450px" controls="controls" poster="https://tidb-docs.s3.us-east-2.amazonaws.com/thumbnail+-+lesson+6.png"></video>
## 另请参阅
- [TiDB 整体架构](/tidb-architecture.md)
- [TiDB 数据库的存储](/tidb-storage.md)
- [TiDB 数据库的计算](/tidb-computing.md)
- [TiDB 数据库的调度](/tidb-scheduling.md)
| Java |
/*
* Copyright 2016 Yu Sheng. 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.
*/
package com.ysheng.auth.model.api;
/**
* Defines the grant types.
*/
public enum GrantType {
AUTHORIZATION_CODE,
IMPLICIT,
PASSWORD,
CLIENT_CREDENTIALS
}
| Java |
# Stachybotrys renispora P.C. Misra SPECIES
#### Status
ACCEPTED
#### According to
Index Fungorum
#### Published in
Mycotaxon 4(1): 161 (1976)
#### Original name
Stachybotrys renispora P.C. Misra
### Remarks
null | Java |
# Asteroma senecionis Ellis & Everh. SPECIES
#### Status
ACCEPTED
#### According to
Index Fungorum
#### Published in
null
#### Original name
Asteroma senecionis Ellis & Everh.
### Remarks
null | Java |
# Bulbophyllum ambongense Schltr. SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | Java |
# Statice formosa Hort. ex Vilm. SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | Java |
# Pyrethrum seticuspe Maxim. SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | Java |
# Cortinarius turmalis (Fr.) Fr., 1838 SPECIES
#### Status
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
Epicr. syst. mycol. (Upsaliae) 257 (1838)
#### Original name
Cortinarius turmalis (Fr.) Fr., 1838
### Remarks
null | Java |
# Ramularia knautiae (C. Massal.) Bubák, 1903 SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
Öst. bot. Z. 53: 50 (1903)
#### Original name
Ramularia succisae var. knautiae C. Massal., 1889
### Remarks
null | Java |
/* jshint sub: true */
/* global exports: true */
'use strict';
// //////////////////////////////////////////////////////////////////////////////
// / @brief node-request-style HTTP requests
// /
// / @file
// /
// / DISCLAIMER
// /
// / Copyright 2015 triAGENS GmbH, Cologne, Germany
// /
// / 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 holder is triAGENS GmbH, Cologne, Germany
// /
// / @author Alan Plum
// / @author Copyright 2015, triAGENS GmbH, Cologne, Germany
// //////////////////////////////////////////////////////////////////////////////
const internal = require('internal');
const Buffer = require('buffer').Buffer;
const extend = require('lodash').extend;
const httperr = require('http-errors');
const is = require('@arangodb/is');
const querystring = require('querystring');
const qs = require('qs');
const url = require('url');
class Response {
throw (msg) {
if (this.status >= 400) {
throw Object.assign(
httperr(this.status, msg || this.message),
{details: this}
);
}
}
constructor (res, encoding, json) {
this.status = this.statusCode = res.code;
this.message = res.message;
this.headers = res.headers ? res.headers : {};
this.body = this.rawBody = res.body;
if (this.body && encoding !== null) {
this.body = this.body.toString(encoding || 'utf-8');
if (json) {
try {
this.json = JSON.parse(this.body);
} catch (e) {
this.json = undefined;
}
}
}
}
}
function querystringify (query, useQuerystring) {
if (!query) {
return '';
}
if (typeof query === 'string') {
return query.charAt(0) === '?' ? query.slice(1) : query;
}
return (useQuerystring ? querystring : qs).stringify(query)
.replace(/[!'()*]/g, function (c) {
// Stricter RFC 3986 compliance
return '%' + c.charCodeAt(0).toString(16);
});
}
function request (req) {
if (typeof req === 'string') {
req = {url: req, method: 'GET'};
}
let path = req.url || req.uri;
if (!path) {
throw new Error('Request URL must not be empty.');
}
let pathObj = typeof path === 'string' ? url.parse(path) : path;
if (pathObj.auth) {
let auth = pathObj.auth.split(':');
req = extend({
auth: {
username: decodeURIComponent(auth[0]),
password: decodeURIComponent(auth[1])
}
}, req);
delete pathObj.auth;
}
let query = typeof req.qs === 'string' ? req.qs : querystringify(req.qs, req.useQuerystring);
if (query) {
pathObj.search = query;
}
path = url.format(pathObj);
let contentType;
let body = req.body;
if (req.json) {
body = JSON.stringify(body);
contentType = 'application/json';
} else if (typeof body === 'string') {
contentType = 'text/plain; charset=utf-8';
} else if (typeof body === 'object' && body instanceof Buffer) {
contentType = 'application/octet-stream';
} else if (!body) {
if (req.form) {
contentType = 'application/x-www-form-urlencoded';
body = typeof req.form === 'string' ? req.form : querystringify(req.form, req.useQuerystring);
} else if (req.formData) {
// contentType = 'multipart/form-data'
// body = formData(req.formData)
throw new Error('Multipart form encoding is currently not supported.');
} else if (req.multipart) {
// contentType = 'multipart/related'
// body = multipart(req.multipart)
throw new Error('Multipart encoding is currently not supported.');
}
}
const headers = {};
if (contentType) {
headers['content-type'] = contentType;
}
if (req.headers) {
Object.keys(req.headers).forEach(function (name) {
headers[name.toLowerCase()] = req.headers[name];
});
}
if (req.auth) {
headers['authorization'] = ( // eslint-disable-line dot-notation
req.auth.bearer ?
'Bearer ' + req.auth.bearer :
'Basic ' + new Buffer(
req.auth.username + ':' +
req.auth.password
).toString('base64')
);
}
let options = {
method: (req.method || 'get').toUpperCase(),
headers: headers,
returnBodyAsBuffer: true,
returnBodyOnError: req.returnBodyOnError !== false
};
if (is.existy(req.timeout)) {
options.timeout = req.timeout;
}
if (is.existy(req.followRedirect)) {
options.followRedirects = req.followRedirect; // [sic] node-request compatibility
}
if (is.existy(req.maxRedirects)) {
options.maxRedirects = req.maxRedirects;
} else {
options.maxRedirects = 10;
}
if (req.sslProtocol) {
options.sslProtocol = req.sslProtocol;
}
let result = internal.download(path, body, options);
return new Response(result, req.encoding, req.json);
}
exports = request;
exports.request = request;
exports.Response = Response;
['delete', 'get', 'head', 'patch', 'post', 'put']
.forEach(function (method) {
exports[method.toLowerCase()] = function (url, options) {
if (typeof url === 'object') {
options = url;
url = undefined;
} else if (typeof url === 'string') {
options = extend({}, options, {url: url});
}
return request(extend({method: method.toUpperCase()}, options));
};
});
module.exports = exports;
| Java |
Android Kod Yazım Kılavuzu
---------------------------
Bu dokümanın amacı Android uygulama geliştirirken bize yardımcı olacak kod yazım prensiplerini belirlemektir. Uygulama geliştirirken bu dokümana göre hareket etmek temiz ve istikrarlı kod yazımında bize yardımcı olacaktır.
Not: Bazı yerlerde İngilizce-Türkçe kullanımında karışıklık olmaktadır. Bunlar kullanılan kelimelerin tam karşılığının olmamasından kaynaklanmaktadır. Örneğin; handle etmek , class dosyaları..
##1. Uygulama Prensipleri
###1.1 Proje Yapısı
Uygulama geliştirirken, proje yapısı ağağıdaki gibi olmadır. :
src/AndroidTest
src/Test
src/CommonTest
src/main
**AndroidTest** - Fonksiyonel testleri içeren klasör.
**Test** - Unit testleri içeren klasör.
**CommonTest** - Paylaşılan AndroidTest & Test kodlarının bulunduğu klasör.
**main** - Uygulamanın kodlarını içeren klasör.
Uygulamanın genel yapısı herhangi bir değişiklikte ya da yeni bir özellik eklendiğinde yukarıda belirlenmiş şekilde kalmalıdır. Bu yapıyı kullanmanın avantajı test ile ilişkili olan kodların ayrı olmasıdır.
###1.2 Dosya İsimlendirme
####1.2.1 Class dosyaları
Her class dosyası BüyükKüçük şeklinde tanımlanmaldır. Örnek olarak;
AndroidActivity, NetworkHelper, UserFragment, PerActivity
Android kütüphanesinden kalıtılmış bileşen **her zaman** hangi sınıftan kalıtılıyorsa o bileşenin ismi ile bitmelidir. Örnek olarak;
UserFragment, SignUpActivity, RateAppDialog, PushNotificationServer, NumberView
BüyükKüçük harf şeklinde kullanılan class isimleri okunabilirlik açısından kolaylık sağlamaktadır. Ayrıca class'ları bileşenlerin isimlerine göre isimlendirme de hangi class'ın ne için kullanıldığı hakkında bize bilgi vermektedir. Örnek olarak RegistrationDialog bize kayıt ile ilgili işlemin bu dialog'da yapıldığını göstermektedir.
####1.2.2 Resource Dosyaları
Resource dosyalarını isimlendirirken küçük-harf kullanmalıyız ve boşluk yerine alt çizgi (_) kullanmalıyız. Örnek olarak;
activity_main, fragment_user, item_post
Bu şekilde kullanım, herhangi bir amaca yönelik oluşturulmuş layout dosyasını bulmamızda bize kolaylık sağlar. Android Studio'da layout kısmı alfabetik olarak sıralanmış durumdadır. Böylece activity_main şeklinde isim verildiğinde tüm aynı amaca hizmet eden layout'lar gruplanmış olacaktır.
####1.2.2.1 Drawable Dosyaları
Drawable resource dosyaları **ic_name_00dp** şeklinde adlandırılmalıdır..
ic_entrance_24dp , ic_accept_32dp
Bu şekilde bir isimlendirme, drawable klasörlerinde bulunan ikonların boyutlarının açılmadan öğrenilmesine yardımcı olacaktır.
Diğer drawable bileşenlerinin kullanımı aşağıdaki şekilde olmalıdır.
| Tipi | Ön Eki | Örnek |
|------------|-----------|------------------------|
| Selector | selector_ | selector_button_cancel |
| Background | bg_ | bg_rounded_button |
| Circle | circle_ | circle_white |
| Progress | progress_ | progress_circle_purple |
| Divider | divider_ | divider_grey |
Bu şekilde isimlendirme benzer bileşenlerin Android Studio ile gruplandırılmasına yardımcı olmaktadır. Aynı zamanda hangi bileşenin nerede kullanıldığına dair bilgi vermektedir. Doğru isimlendirme uygulama geliştirirken meydana gelecek ikilikleri engellemektedir.
Selector state resource dosyası oluşurken de duruma göre son ek vermemiz gerekmektedir.
| Durum | Son Ek | Örnek |
|----------|-----------|---------------------|
| Normal | _normal | btn_accept_normal |
| Pressed | _pressed | btn_accept_pressed |
| Focused | _focused | btn_accept_focused |
| Disabled | _disabled | btn_accept_disabled |
| Selected | _selected | btn_accept_selected |
####1.2.2.2 Layout Dosyaları
Layout dosyaları aşağıdaki şekilde Java class'ına göre oluşturulmalıdır.
**class_java_name**
| Bileşen | Class İsmi | Layout İsmi |
|------------------|-----------------|-------------------|
| Activity | MainActivity | activity_main |
| Fragment | MainFragment | fragment_main |
| Dialog | RateDialog | dialog_rate |
| Widget | UserProfileView | view_user_profile |
| AdapterView Item | N/A | item_follower |
####1.2.2.3 Menu Dosyaları
Menu dosyalarının menu_ ön eki ile isimlendirilmesine gerek yoktur. Zaten bu dosyalar menu klasörü içinde bulunmaktadır.
####1.2.2.4 Values Dosyaları
Values kısmında bulunan dosyalar çoğul olmalıdır.
attrs.xml, strings.xml, styles.xml, colors.xml, dimens.xml
##2. Kod Rehberi
###2.1 Java Dili Kuralları
####2.1.1 Exceptionları görmezden gelmeyin :)
Exceptionları handle etmeden bırakmayınız.
public void setUserId(String id) {
try {
mUserId = Integer.parseInt(id);
} catch (NumberFormatException e) { }
}
Yukarıdaki yazım tarzı hem kullanıcıya, hem de uygulama geliştiriciye meydana gelen hata ile ilgili bilgi vermemektedir. Bunun yerine ilgili hata ile ilgili bilgi verdiren log yazdırılmalıdır.
public void setCount(String count) {
try {
count = Integer.parseInt(id);
} catch (NumberFormatException e) {
count = 0;
Log.e(TAG, "There was an error parsing the count " + e);
DialogFactory.showErrorMessage(R.string.error_message_parsing_count);
}
}
Hataları şu şekilde handle etmeliyiz.
- Kullanıcıya hata meydana geldiğine dair uyarı vermeliyiz.
- Hata oluşması durumunda değişkene sabit bir değer vermeliyiz.
- Uygun olan exception'ı göstermeliyiz.
####2.1.2 Türü belli olmayan exception'lar
Exception yakalarken aşağıdaki şekilde en genel halini göstermemeliyiz.
public void openCustomTab(Context context, Uri uri) {
Intent intent = buildIntent(context, uri);
try {
context.startActivity(intent);
} catch (Exception e) {
Log.e(TAG, "There was an error opening the custom tab " + e);
}
}
Neden?
Bu şekilde genel haliyle yakalanan exception'lar bize aldığımız hatalar hakkında bilgi vermemektedir.
Bunun yerine duruma göre exceptionlar yakalanmaladır.
public void openCustomTab(Context context, Uri uri) {
Intent intent = buildIntent(context, uri);
try {
context.startActivity(intent);
} catch (ActivityNotFoundException e) {
Log.e(TAG, "There was an error opening the custom tab " + e);
}
}
####2.1.3 Exception'ların gruplanması.
Exceptionlar aynı koddan meydana geliyorsa gruplandırılması gerekmektedir.
public void openCustomTab(Context context, @Nullable Uri uri) {
Intent intent = buildIntent(context, uri);
try {
context.startActivity(intent);
} catch (ActivityNotFoundException e) {
Log.e(TAG, "There was an error opening the custom tab " + e);
} catch (NullPointerException e) {
Log.e(TAG, "There was an error opening the custom tab " + e);
} catch (SomeOtherException e) {
// Show some dialog
}
}
Gruplanmış exception' lar aşağıdaki gibidir:
public void openCustomTab(Context context, @Nullable Uri uri) {
Intent intent = buildIntent(context, uri);
try {
context.startActivity(intent);
} catch (ActivityNotFoundException e | NullPointerException e) {
Log.e(TAG, "There was an error opening the custom tab " + e);
} catch (SomeOtherException e) {
// Show some dialog
}
}
####2.1.4 Try-catch kulllanımı
Try-catch kullanımı kod okunabilirliğini arttırır. Meydana gelen hata da kolayca handle edilmiş olur. Aynı zamanda debug aşamasını da epey kolaylaştırmış olur.
####2.1.5 Never use Finalizers
*There are no guarantees as to when a finalizer will be called, or even that it will be called at all. In most cases, you can do what you need from a finalizer with good exception handling. If you absolutely need it, define a close() method (or the like) and document exactly when that method needs to be called. See InputStreamfor an example. In this case it is appropriate but not required to print a short log message from the finalizer, as long as it is not expected to flood the logs.* - taken from the Android code style guidelines
####2.1.6 Bileşenlerin import edilmesi.
Bileşenler import edilirken tüm ismi ile import edilmeli.
Bunun yerine:
import android.support.v7.widget.*;
Bunu yapın :) 😃
import android.support.v7.widget.RecyclerView;
####2.1.7 Kullanılmayan importları tutmayın.
###2.2 Java Kod Stili Kuralları
####2.2.1 Field tanımlama ve isimlendirme
Tüm field'lar sayfanın en üstünde ve aşağıdaki kurallara göre tanımlanmalıdır.
- Private, non-static olmayan fieldların isimleri *m* ile başlamamalıdır:
userSignedIn, userNameText, acceptButton
Aşağıdaki kullanım kod okunabilirliğini azaltmaktadır:
mUserSignedIn, mUserNameText, mAcceptButton
- Private, static field isimleri *s* ile başlamamalıdır.:
someStaticField, userNameText
Aşağıdaki kullanım da okunabilirliği azaltmaktadır:
sSomeStaticField, sUserNameText
- Diğer tüm fieldlar küçük harfle başlamalıdır.
int numOfChildren;
String username;
- Static final değişkenler BUYUK_HARFLE_VE_ALTYAZI ile yazılmalıdır. .
private static final int PAGE_COUNT = 0;
Değişken isimleri kullanıma göre isimlendirilmelidir.
int e; //listedeki eleman sayısı
Yukarıdaki kullanım yerine, değişkenin ismini kullanım amacına göre vermemiz gerekmekdir.
int elemanSayisi;
####2.2.1.2 View Alanlarının İsimlendirmesi
View bileşenleri isimlendirilirken, bileşenlerinin isimlerine göre adlandırılır.
| View | Name |
|----------------|--------------------|
| TextView | usernameText |
| Button | acceptLoginButton |
| ImageView | profileAvatarImage |
| RelativeLayout | profileLayout |
Yukarıdaki kullanım ile birlikte hangi değişkenimizin hangi bileşenden meydana geldiğini anlayabiliriz.
####2.2.2 Container tiplerini isimlendirmede kullanmamalıyız
Bunu yapın:
List<String> userIds = new ArrayList<>();
Bunu yapmayın:
List<String> userIdList = new ArrayList<>();
####2.2.3 Aynı isimlendirme yapmaktan kaçının
Bir değişkeni, metodu isimlendirirken aynı isimleri kullanmayınız.
hasUserSelectedSingleProfilePreviously
hasUserSelectedSignedProfilePreviously
####2.2.4 Number series naming
Method oluştururken kullandığımız parametreleri amaçlarına göre isimlendirmeliyiz.
public void doSomething(String s1, String s2, String s3)
Yukarıdaki kullanımda s1, s2 ve s3'ün ne olduğu belli değil. Bunun yerine:
public void doSomething(String userName, String userEmail, String userId)
Parametreleri değişkenlere göre isimlendirmeliyiz.
####2.2.5 Pronouncable names
Field' lar metotlar ve sınıflar adlandırılırken:
- Okunabilir olmalı: Etkin bir isim okunduğunda direk anlaşılabilmelidir.
- Kolay telaffuz edilebilmeli
- Kolay arama yapılabilmeli : Örneğin bir methot' u bir sınıf içerisinde ararken kolayca sonuca ulaştırabilecek isimler tercih edilmelidir.
- Maceristan notasyonu (Hungarian notation- mLocation vb.) yukarıda bahsedilen üç maddeye uymadığı için kullanmayınız.
####2.2.6 Kısaltmaları (Baş harflerden oluşan) kelime olarak kullanma
Sınıf isimlerinin,değişken isimlerinin kısaltmaları kelime olarak kullanıken sadece baş harfi büyük harfle yazılarak kullanılmalıdır.
Örneğin:
| Doğru | Yanlış |
|--------------------|------------------|
| setUserId | setUserID |
| String Uri | String URI |
| int id | int ID |
| parseHtml | parseHTML |
| generateXmlFile | generateXMLFile |
####2.2.7 Satırların uzunluğuna göre ayarlama
Değişken tanımlarker satıların dizilimi için herhangi bir özel form kullanmayınız, örneğin:
private int userId = 8;
private int count = 0;
private String username = "hitherejoe";
Bu şekilde yapmaktan kaçının:
private String username = "hitherejoe";
private int userId = 8;
private int count = 0;
####2.2.8 Girintiler için boşluk kullanma
Bloklar için 4 boşluk bırakılmalı:
if (userSignedIn) {
count = 1;
}
String tanımlamalar için baştan 8 satır boşluk bırakılmalı.
String userAboutText =
"This is some text about the user and it is pretty long, can you see!"
###2.2.9 If-Statements
####2.2.9.1 Standart süslü parantez stili
Süslü parantez ile koşul daima aynı satırda olmalıdır.
Aşağıdaki gibi yazmaktan kaçının.
class SomeClass {
private void someFunction()
{
if (isSomething)
{
}
else if (!isSomethingElse)
{
}
else
{
}
}
}
yerine bunu kullanın :
class SomeClass {
private void someFunction() {
if (isSomething) {
} else if (!isSomethingElse) {
} else {
}
}
}
####2.2.9.2 Satır-içi if-clauses
bazı durumlarlar if bloklar tek satırda yazmak daha mantıklıdır. Örneğin:
if (user == null) return false;
Fakat, bu sadece basit işlemler için geçerlidir. Aşağıdaki şekilde olan kod parçacıkları için süslü parantezlerle yazmak daha doğrudur.
if (user == null) throw new IllegalArgumentExeption("Oops, user object is required.");
####2.2.9.3 İç içe if koşulu
Mümkün oldukça iç içe if lokları yazmaktan kaçının. Örneğin:
Bunun yerine:
if (userSignedIn) {
if (userId != null) {
}
}
Bu şekilde yazmayı tercih ediniz:
if (userSignedIn && userId != null) {
}
Bu şekilde yazımlar kod okunabilirliğini artırttırır ve gereksiz satır kullanımını engellenmiş olur.
####2.2.9.4 üçlü operatör
Uygun olduğu durumlarda işlemleri kolaylaştımak için üçlü operatörler kullanılabilir.
Örneğin bu kod satırını okumak kolaydır:
userStatusImage = signedIn ? R.drawable.ic_tick : R.drawable.ic_cross;
ve aşağıdaki gibi fazla satır :
if (signedIn) {
userStatusImage = R.drawable.ic_tick;
} else {
userStatusImage = R.drawable.ic_cross;
}
**Note:** Üçlü operatörlerin kullanıldığı bazı zamnlar vardır. Eğer if-koşul mantığı karmaşık ya da karakter sayısı fazla ise standart süslü parantez stili kullanılmalıdır.
###2.2.10 Annotations
####2.2.10.1 Annotation practices
Android kod stil rehberinden alınmıştır:
**@Override:** The @Override annotation must be used whenever a method overrides the declaration or implementation from a super-class. For example, if you use the @inheritdocs Javadoc tag, and derive from a class (not an interface), you must also annotate that the method @Overrides the parent class's method.
@Override annotation bir metot üst bir sınıftan kalıtıldığında kullanılmalıdır.
**@SuppressWarnings:** The @SuppressWarnings annotation should only be used under circumstances where it is impossible to eliminate a warning. If a warning passes this "impossible to eliminate" test, the @SuppressWarnings annotation must be used, so as to ensure that all warnings reflect actual problems in the code.
--Daha fazla bilgi almak için rehbere bakabilirsiniz.
----------
Annotations mümkün oldukça her zaman kullanılmalıdır. Örneğin bir field'ın null olması umulduğu durumlarda @Nullable annotation'ı kullanılmalıdır.
@Nullable TextView userNameText;
private void getName(@Nullable String name) { }
####2.2.10.2 Annotation stili
Metotlar yada class lar için kullanılan annotation'lar satır başına sadece biri için yazılmalıdır:
@Annotation
@AnotherAnnotation
public class SomeClass {
@SomeAnotation
public String getMeAString() {
}
}
####2.2.11 Kullanılmayan elementler
Bütün kullanılmayan elementler **fields**, **imports**, **methods** and **classes** kaldırılmalıdır.(Eğer özel bir sebebi yoksa).
####2.2.12 Arguments in fragments and activities
intent ve bundle ile veri gönderirken, key - value aşağıdaki tanımlamalar kullanılmalıdır.
**Activity**
Bir activity' e veri gönderirken bir KEY aracılığı ile gönderilir.
private static final String KEY_NAME = "com.your.package.name.to.activity.KEY_NAME";
**Fragment**
Bir fragment' e veri gönderirken bir EXTRA aracılığı ile gönderilir.
private static final String EXTRA_NAME = "EXTRA_NAME";
**Activity**
public static Intent getStartIntent(Context context, Post post) {
Intent intent = new Intent(context, CurrentActivity.class);
intent.putParcelableExtra(EXTRA_POST, post);
return intent;
}
**Fragment**
public static PostFragment newInstance(Post post) {
PostFragment fragment = new PostFragment();
Bundle args = new Bundle();
args.putParcelable(ARGUMENT_POST, post);
fragment.setArguments(args)
return fragment;
}
###2.2.13 Yorum satırları
####2.2.13.1 Satır içi yorumlar
Kodların kompleks olduğu durumlarda okuyucunun anlaması için kolay anlaşılabilir cümlelerle açıklamalar yazılmalıdır. Fakat aslolan kodların yorum satırı olmadan anlaşılabilecek şekilde yazılmasıdır.
**Not:** Yorum satırı olmak zorunda değildir max 100 karakteri de geçmemesine özen gösterilmeli.
### 2.3 Resource dosyalarının isimlendirilmesi
Tüm resource dosyaları isimlendirilirken küçük harf ve alt çizgi kullanılmalıdır.
text_username, activity_main, fragment_user, error_message_network_connection
Bu şekilde kullanımın bize kazandırdığı en büyük avantaj, proje dosyalarında bir tutarlılığın oluşmasıdır.
#### 2.3.1 ID İsimlendirmesi
Tüm ID'ler isimlendirilirken ait olduğu element'e göre isimlendirilir.
Örneğin;
| Element | Ön Ek |
|----------------|-----------|
| ImageView | image_ |
| Fragment | fragment_ |
| RelativeLayout | layout_ |
| Button | button_ |
| TextView | text_ |
| View | view_ |
Kullanım:
<TextView
android:id="@+id/text_username"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
#### 2.3.2 Strings
String isimlendirmeleri kullanıldığı ekrana ve kullanım amacına göre isimlendirilmelidir.
| Ekran | String ifade | Strings.xml karşılığı |
|-----------------------|----------------|---------------------------|
| Registration Fragment | “Register now” | registration_register_now |
| Sign Up Activity | “Cancel” | sign_up_cancel |
| Rate App Dialog | “No thanks” | rate_app_no_thanks |
Eğer yukarıdaki gibi isimlendirme mümkün değilse aşağıdaki gibi kullanım tipine göre isimlendirme opsiyonu kullanılabilir.
| Ön Ek | Açıklama |
|---------|----------------------------------------------|
| error_ | Error mesajalrı için kullanılır. |
| title_ | Dialog başlıklarında kullanılır. |
| action_ | Menü ile ilgili string ifadelerde kullanılır.|
| msg_ | Used for generic message such as in a dialog |
| label_ | Used for activity labels |
Two important things to note for String resources:
- String resources should never be reused across screens. This can cause issues when it comes to changing a string for a specific screen. It saves future complications by having a single string for each screens usage.
- String resources should **always** be defined in the strings file and never hardcoded in layout or class files.
#### 2.3.3 Stiller ve temalar
Stil ve tema isimlendirmeleri BuyukKucuk isimlendirme şeklinde yapılmalıdır.
AppTheme.DarkBackground.NoActionBar
AppTheme.LightBackground.TransparentStatusBar
ProfileButtonStyle
TitleTextStyle
### 2.3.4 XML Attribute sıralanması
Attribute sıralaması için Android Studio içerisinde bir fonksiyon bulunmalıdır. XML ile ilgili yaptığımız değişikliklikler sonrası bu fonksiyonu çalıştırmalıyız.
Windows bilgisayarlar için çalıştırma yöntemi;
`Ctrl + shift + L`
Mac için çalıştırma yöntemi;
`cmd + shift + L`
# 3. Gradle Stili
## 3.1 Kütüphaneler
### 3.1.1 Versiyonlama
Uygulanabilirse, aynı versiyonu paylaşan kütüphanelerin versiyon numarası tek bir değişkenle tutulup, diğer kütüphanelerle paylaşılabilir.
Örneğin;
final SUPPORT_LIBRARY_VERSION = '23.4.0'
compile "com.android.support:support-v4:$SUPPORT_LIBRARY_VERSION"
compile "com.android.support:recyclerview-v7:$SUPPORT_LIBRARY_VERSION"
compile "com.android.support:support-annotations:$SUPPORT_LIBRARY_VERSION"
compile "com.android.support:design:$SUPPORT_LIBRARY_VERSION"
compile "com.android.support:percent:$SUPPORT_LIBRARY_VERSION"
compile "com.android.support:customtabs:$SUPPORT_LIBRARY_VERSION"
Bu şekilde kullandığımızda ileride kütüphanelerde güncelleme yapacağımız zaman tek seferde versiyon numarasını değiştirerek tüm kütüphaneleri tek seferde güncellemiş oluruz.
### 3.1.2 Gruplama
Aynı package adını kullanan kütüphaneler gruplanabilir.
compile "com.android.support:percent:$SUPPORT_LIBRARY_VERSION"
compile "com.android.support:customtabs:$SUPPORT_LIBRARY_VERSION"
compile 'io.reactivex:rxandroid:1.2.0'
compile 'io.reactivex:rxjava:1.1.5'
compile 'com.jakewharton:butterknife:7.0.1'
compile 'com.jakewharton.timber:timber:4.1.2'
compile 'com.github.bumptech.glide:glide:3.7.0'
`compile` , `testCompile` and `androidTestCompile` kütüphaneleri de kendi içerisinde gruplanabilir.
// Uygulama Kütüphaneleri
compile "com.android.support:support-v4:$SUPPORT_LIBRARY_VERSION"
compile "com.android.support:recyclerview-v7:$SUPPORT_LIBRARY_VERSION"
// Cihaz testi kütüphanesi
androidTestCompile "com.android.support:support-annotations:$SUPPORT_LIBRARY_VERSION"
// Unit test kütüphanesi
testCompile 'org.robolectric:robolectric:3.0'
Bu şekilde kullanım,geliştiriciye kütüphanelerin kullanımında bir düzen ve kolaylık sağlamaktadır.
### 3.1.3 Amaca uygun kütüphaneler
Uygulamaya eklenen kütüphaneler belirli amaca uygun olarak kullanılacaksa `compile` , `testCompile` veya `androidTestCompile` yazım tarzı kullanılan amacına uygun olmalı. Örneğin; roboelectric kütüphanesi sadece unit test amacı ile gereklidir. Bu yüzden de `testCompile` şeklinde eklenmektedir.
testCompile 'org.robolectric:robolectric:3.0'
| Java |
/// <reference path="../apimanPlugin.ts"/>
/// <reference path="../services.ts"/>
module Apiman {
export var UserRedirectController = _module.controller("Apiman.UserRedirectController",
['$q', '$scope', '$location', 'PageLifecycle', '$routeParams',
($q, $scope, $location, PageLifecycle, $routeParams) => {
PageLifecycle.loadPage('UserRedirect', undefined, undefined, $scope, function() {
PageLifecycle.forwardTo('/users/{0}/orgs', $routeParams.user);
});
}])
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.