code
stringlengths 3
1.05M
| repo_name
stringlengths 4
116
| path
stringlengths 4
991
| language
stringclasses 9
values | license
stringclasses 15
values | size
int32 3
1.05M
|
---|---|---|---|---|---|
/*
* TestTracker.cs
* SnowplowTrackerTests
*
* Copyright (c) 2015 Snowplow Analytics Ltd. All rights reserved.
*
* This program is licensed to you under the Apache License Version 2.0,
* and you may not use this file except in compliance with the Apache License Version 2.0.
* You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Apache License Version 2.0 is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
*
* Authors: Joshua Beemster
* Copyright: Copyright (c) 2015 Snowplow Analytics Ltd
* License: Apache License Version 2.0
*/
using System;
using System.Collections.Generic;
using NUnit.Framework;
using SnowplowTrackerTests.TestHelpers;
using SnowplowTracker;
using SnowplowTracker.Emitters;
using SnowplowTracker.Enums;
using SnowplowTracker.Events;
using SnowplowTracker.Payloads;
namespace SnowplowTrackerTests
{
[TestFixture()]
public class TestTracker
{
[Test()]
public void TestTrackerInitMinimal()
{
Tracker t = new Tracker(new AsyncEmitter("acme.com", HttpProtocol.HTTP, HttpMethod.POST, 500, 52000L, 52000L), "aNamespace", "aAppId");
Assert.NotNull(t);
Assert.NotNull(t.GetEmitter());
Assert.Null(t.GetSubject());
Assert.Null(t.GetSession());
Assert.AreEqual("aNamespace", t.GetTrackerNamespace());
Assert.AreEqual("aAppId", t.GetAppId());
Assert.AreEqual(true, t.GetBase64Encoded());
Assert.AreEqual(DevicePlatforms.Mobile.Value, t.GetPlatform().Value);
}
[Test()]
public void TestTrackerInitException()
{
Tracker t = null;
try
{
t = new Tracker(null, "aNamespace", "aAppId");
}
catch (Exception e)
{
Assert.AreEqual("Emitter cannot be null.", e.Message);
}
Assert.Null(t);
}
[Test()]
public void TestTrackerSetterFunctions()
{
Subject s1 = new Subject();
Session sess1 = new Session(null);
IEmitter e1 = new AsyncEmitter("acme.com", HttpProtocol.HTTP, HttpMethod.POST, 500, 52000L, 52000L);
Tracker t = new Tracker(e1, "aNamespace", "aAppId", s1, sess1);
Assert.NotNull(t.GetEmitter());
Assert.AreEqual("http://acme.com/com.snowplowanalytics.snowplow/tp2", t.GetEmitter().GetCollectorUri().ToString());
Assert.NotNull(t.GetSubject());
Assert.NotNull(t.GetSession());
Assert.AreEqual("aNamespace", t.GetTrackerNamespace());
Assert.AreEqual("aAppId", t.GetAppId());
Assert.AreEqual(true, t.GetBase64Encoded());
Assert.AreEqual(DevicePlatforms.Mobile.Value, t.GetPlatform().Value);
IEmitter e2 = new AsyncEmitter("acme.com.au", HttpProtocol.HTTP, HttpMethod.POST, 500, 52000L, 52000L);
t.SetEmitter(e2);
Assert.AreEqual("http://acme.com.au/com.snowplowanalytics.snowplow/tp2", t.GetEmitter().GetCollectorUri().ToString());
t.SetSession(null);
Assert.Null(t.GetSession());
t.SetSubject(null);
Assert.Null(t.GetSubject());
t.SetTrackerNamespace("newNamespace");
Assert.AreEqual("newNamespace", t.GetTrackerNamespace());
t.SetAppId("newAppId");
Assert.AreEqual("newAppId", t.GetAppId());
t.SetBase64Encoded(false);
Assert.AreEqual(false, t.GetBase64Encoded());
t.SetPlatform(DevicePlatforms.Desktop);
Assert.AreEqual(DevicePlatforms.Desktop.Value, t.GetPlatform().Value);
}
[Test()]
public void TestTrackerSendEvent()
{
IEmitter e1 = new BaseEmitter();
Tracker t = new Tracker(e1, "aNamespace", "aAppId");
t.StartEventTracking();
t.Track(new PageView().SetPageTitle("title").SetPageUrl("url").SetReferrer("ref").SetTimestamp(1234567890).SetEventId("event-id-custom").Build());
t.Track(new PageView().SetPageTitle("title").SetPageUrl("url").SetReferrer("ref").SetTimestamp(1234567890).SetEventId("event-id-custom").Build());
BaseEmitter te1 = (BaseEmitter)t.GetEmitter();
Assert.AreEqual(2, te1.payloads.Count);
foreach (TrackerPayload payload in te1.payloads)
{
Dictionary<string, object> dict = payload.GetDictionary();
Assert.AreEqual(SnowplowTracker.Version.VERSION, dict[Constants.TRACKER_VERSION]);
Assert.AreEqual("1234567890", dict[Constants.TIMESTAMP]);
Assert.AreEqual("event-id-custom", dict[Constants.EID]);
Assert.AreEqual("aNamespace", dict[Constants.NAMESPACE]);
Assert.AreEqual("aAppId", dict[Constants.APP_ID]);
Assert.AreEqual("mob", dict[Constants.PLATFORM]);
Assert.AreEqual(Constants.EVENT_PAGE_VIEW, dict[Constants.EVENT]);
Assert.AreEqual("title", dict[Constants.PAGE_TITLE]);
Assert.AreEqual("url", dict[Constants.PAGE_URL]);
Assert.AreEqual("ref", dict[Constants.PAGE_REFR]);
}
}
}
}
|
snowplow/snowplow-unity-tracker
|
SnowplowTracker.Tests/Assets/Tests/TestTracker.cs
|
C#
|
apache-2.0
| 5,574 |
package com.skyrocketgwt.core.client.layouts.layoutpanel.appearance;
import com.google.gwt.dom.client.Element;
/**
* Created by v on 2/22/2015.
*/
public interface SkySplitterAppearance {
Element render(double splitterSize);
}
|
SkyRocketGWT/skyrocketgwt
|
skyrocket-core/src/main/java/com/skyrocketgwt/core/client/layouts/layoutpanel/appearance/SkySplitterAppearance.java
|
Java
|
apache-2.0
| 237 |
package com.example.chengqi.mycoderepo.layouts;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.example.chengqi.mycoderepo.R;
public class RelativeLayoutActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_relative_layout);
}
}
|
firstbytegithub/MyCodeRepo
|
app/src/main/java/com/example/chengqi/mycoderepo/layouts/RelativeLayoutActivity.java
|
Java
|
apache-2.0
| 415 |
##
# Copyright (c) 2009-2014 Apple Inc. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
##
"""
Test memcacheprops.
"""
import os
from txweb2.http import HTTPError
from txdav.xml.base import encodeXMLName
from twistedcaldav.memcacheprops import MemcachePropertyCollection
from twistedcaldav.test.util import InMemoryPropertyStore
from twistedcaldav.test.util import TestCase
class StubCollection(object):
def __init__(self, path, childNames):
self.path = path
self.fp = StubFP(path)
self.children = {}
for childName in childNames:
self.children[childName] = StubResource(self, path, childName)
def listChildren(self):
return self.children.iterkeys()
def getChild(self, childName):
return self.children[childName]
def propertyCollection(self):
if not hasattr(self, "_propertyCollection"):
self._propertyCollection = MemcachePropertyCollection(self)
return self._propertyCollection
class StubResource(object):
def __init__(self, parent, path, name):
self.parent = parent
self.fp = StubFP(os.path.join(path, name))
def deadProperties(self):
if not hasattr(self, "_dead_properties"):
self._dead_properties = self.parent.propertyCollection().propertyStoreForChild(self, InMemoryPropertyStore())
return self._dead_properties
class StubFP(object):
def __init__(self, path):
self.path = path
def child(self, childName):
class _Child(object):
def __init__(self, path):
self.path = path
return _Child(os.path.join(self.path, childName))
def basename(self):
return os.path.basename(self.path)
class StubProperty(object):
def __init__(self, ns, name, value=None):
self.ns = ns
self.name = name
self.value = value
def qname(self):
return self.ns, self.name
def __repr__(self):
return "%s = %s" % (encodeXMLName(self.ns, self.name), self.value)
class MemcachePropertyCollectionTestCase(TestCase):
"""
Test MemcacheProprtyCollection
"""
def getColl(self):
return StubCollection("calendars", ["a", "b", "c"])
def test_setget(self):
child1 = self.getColl().getChild("a")
child1.deadProperties().set(StubProperty("ns1:", "prop1", value="val1"))
child2 = self.getColl().getChild("a")
self.assertEquals(child2.deadProperties().get(("ns1:", "prop1")).value,
"val1")
child2.deadProperties().set(StubProperty("ns1:", "prop1", value="val2"))
# force memcache to be consulted (once per collection per request)
child1 = self.getColl().getChild("a")
self.assertEquals(child1.deadProperties().get(("ns1:", "prop1")).value,
"val2")
def test_merge(self):
child1 = self.getColl().getChild("a")
child2 = self.getColl().getChild("a")
child1.deadProperties().set(StubProperty("ns1:", "prop1", value="val0"))
child1.deadProperties().set(StubProperty("ns1:", "prop2", value="val0"))
child1.deadProperties().set(StubProperty("ns1:", "prop3", value="val0"))
self.assertEquals(child2.deadProperties().get(("ns1:", "prop1")).value,
"val0")
self.assertEquals(child1.deadProperties().get(("ns1:", "prop2")).value,
"val0")
self.assertEquals(child1.deadProperties().get(("ns1:", "prop3")).value,
"val0")
child2.deadProperties().set(StubProperty("ns1:", "prop1", value="val1"))
child1.deadProperties().set(StubProperty("ns1:", "prop3", value="val3"))
# force memcache to be consulted (once per collection per request)
child2 = self.getColl().getChild("a")
# verify properties
self.assertEquals(child2.deadProperties().get(("ns1:", "prop1")).value,
"val1")
self.assertEquals(child2.deadProperties().get(("ns1:", "prop2")).value,
"val0")
self.assertEquals(child2.deadProperties().get(("ns1:", "prop3")).value,
"val3")
self.assertEquals(child1.deadProperties().get(("ns1:", "prop1")).value,
"val1")
self.assertEquals(child1.deadProperties().get(("ns1:", "prop2")).value,
"val0")
self.assertEquals(child1.deadProperties().get(("ns1:", "prop3")).value,
"val3")
def test_delete(self):
child1 = self.getColl().getChild("a")
child2 = self.getColl().getChild("a")
child1.deadProperties().set(StubProperty("ns1:", "prop1", value="val0"))
child1.deadProperties().set(StubProperty("ns1:", "prop2", value="val0"))
child1.deadProperties().set(StubProperty("ns1:", "prop3", value="val0"))
self.assertEquals(child2.deadProperties().get(("ns1:", "prop1")).value,
"val0")
self.assertEquals(child1.deadProperties().get(("ns1:", "prop2")).value,
"val0")
self.assertEquals(child1.deadProperties().get(("ns1:", "prop3")).value,
"val0")
child2.deadProperties().set(StubProperty("ns1:", "prop1", value="val1"))
child1.deadProperties().delete(("ns1:", "prop1"))
self.assertRaises(HTTPError, child1.deadProperties().get, ("ns1:", "prop1"))
self.assertFalse(child1.deadProperties().contains(("ns1:", "prop1")))
self.assertEquals(child1.deadProperties().get(("ns1:", "prop2")).value,
"val0")
self.assertEquals(child1.deadProperties().get(("ns1:", "prop3")).value,
"val0")
# force memcache to be consulted (once per collection per request)
child2 = self.getColl().getChild("a")
# verify properties
self.assertFalse(child2.deadProperties().contains(("ns1:", "prop1")))
self.assertEquals(child2.deadProperties().get(("ns1:", "prop2")).value,
"val0")
self.assertEquals(child2.deadProperties().get(("ns1:", "prop3")).value,
"val0")
def test_setget_uids(self):
for uid in (None, "123", "456"):
child1 = self.getColl().getChild("a")
child1.deadProperties().set(StubProperty("ns1:", "prop1", value="val1%s" % (uid if uid else "",)), uid=uid)
child2 = self.getColl().getChild("a")
self.assertEquals(child2.deadProperties().get(("ns1:", "prop1"), uid=uid).value,
"val1%s" % (uid if uid else "",))
child2.deadProperties().set(StubProperty("ns1:", "prop1", value="val2%s" % (uid if uid else "",)), uid=uid)
# force memcache to be consulted (once per collection per request)
child1 = self.getColl().getChild("a")
self.assertEquals(child1.deadProperties().get(("ns1:", "prop1"), uid=uid).value,
"val2%s" % (uid if uid else "",))
def test_merge_uids(self):
for uid in (None, "123", "456"):
child1 = self.getColl().getChild("a")
child2 = self.getColl().getChild("a")
child1.deadProperties().set(StubProperty("ns1:", "prop1", value="val0%s" % (uid if uid else "",)), uid=uid)
child1.deadProperties().set(StubProperty("ns1:", "prop2", value="val0%s" % (uid if uid else "",)), uid=uid)
child1.deadProperties().set(StubProperty("ns1:", "prop3", value="val0%s" % (uid if uid else "",)), uid=uid)
self.assertEquals(child2.deadProperties().get(("ns1:", "prop1"), uid=uid).value,
"val0%s" % (uid if uid else "",))
self.assertEquals(child1.deadProperties().get(("ns1:", "prop2"), uid=uid).value,
"val0%s" % (uid if uid else "",))
self.assertEquals(child1.deadProperties().get(("ns1:", "prop3"), uid=uid).value,
"val0%s" % (uid if uid else "",))
child2.deadProperties().set(StubProperty("ns1:", "prop1", value="val1%s" % (uid if uid else "",)), uid=uid)
child1.deadProperties().set(StubProperty("ns1:", "prop3", value="val3%s" % (uid if uid else "",)), uid=uid)
# force memcache to be consulted (once per collection per request)
child2 = self.getColl().getChild("a")
# verify properties
self.assertEquals(child2.deadProperties().get(("ns1:", "prop1"), uid=uid).value,
"val1%s" % (uid if uid else "",))
self.assertEquals(child2.deadProperties().get(("ns1:", "prop2"), uid=uid).value,
"val0%s" % (uid if uid else "",))
self.assertEquals(child2.deadProperties().get(("ns1:", "prop3"), uid=uid).value,
"val3%s" % (uid if uid else "",))
self.assertEquals(child1.deadProperties().get(("ns1:", "prop1"), uid=uid).value,
"val1%s" % (uid if uid else "",))
self.assertEquals(child1.deadProperties().get(("ns1:", "prop2"), uid=uid).value,
"val0%s" % (uid if uid else "",))
self.assertEquals(child1.deadProperties().get(("ns1:", "prop3"), uid=uid).value,
"val3%s" % (uid if uid else "",))
def test_delete_uids(self):
for uid in (None, "123", "456"):
child1 = self.getColl().getChild("a")
child2 = self.getColl().getChild("a")
child1.deadProperties().set(StubProperty("ns1:", "prop1", value="val0%s" % (uid if uid else "",)), uid=uid)
child1.deadProperties().set(StubProperty("ns1:", "prop2", value="val0%s" % (uid if uid else "",)), uid=uid)
child1.deadProperties().set(StubProperty("ns1:", "prop3", value="val0%s" % (uid if uid else "",)), uid=uid)
self.assertEquals(child2.deadProperties().get(("ns1:", "prop1"), uid=uid).value,
"val0%s" % (uid if uid else "",))
self.assertEquals(child1.deadProperties().get(("ns1:", "prop2"), uid=uid).value,
"val0%s" % (uid if uid else "",))
self.assertEquals(child1.deadProperties().get(("ns1:", "prop3"), uid=uid).value,
"val0%s" % (uid if uid else "",))
child2.deadProperties().set(StubProperty("ns1:", "prop1", value="val1%s" % (uid if uid else "",)), uid=uid)
child1.deadProperties().delete(("ns1:", "prop1"), uid=uid)
self.assertRaises(HTTPError, child1.deadProperties().get, ("ns1:", "prop1"), uid=uid)
self.assertFalse(child1.deadProperties().contains(("ns1:", "prop1"), uid=uid))
self.assertEquals(child1.deadProperties().get(("ns1:", "prop2"), uid=uid).value,
"val0%s" % (uid if uid else "",))
self.assertEquals(child1.deadProperties().get(("ns1:", "prop3"), uid=uid).value,
"val0%s" % (uid if uid else "",))
# force memcache to be consulted (once per collection per request)
child2 = self.getColl().getChild("a")
# verify properties
self.assertFalse(child2.deadProperties().contains(("ns1:", "prop1"), uid=uid))
self.assertEquals(child2.deadProperties().get(("ns1:", "prop2"), uid=uid).value,
"val0%s" % (uid if uid else "",))
self.assertEquals(child2.deadProperties().get(("ns1:", "prop3"), uid=uid).value,
"val0%s" % (uid if uid else "",))
def _stub_set_multi(self, values, time=None):
self.callCount += 1
for key, value in values.iteritems():
self.results[key] = value
def test_splitSetMulti(self):
self.callCount = 0
self.results = {}
mpc = MemcachePropertyCollection(None)
values = {}
for i in xrange(600):
values["key%d" % (i,)] = "value%d" % (i,)
mpc._split_set_multi(values, self._stub_set_multi)
self.assertEquals(self.callCount, 3)
self.assertEquals(self.results, values)
def test_splitSetMultiWithChunksize(self):
self.callCount = 0
self.results = {}
mpc = MemcachePropertyCollection(None)
values = {}
for i in xrange(13):
values["key%d" % (i,)] = "value%d" % (i,)
mpc._split_set_multi(values, self._stub_set_multi, chunksize=3)
self.assertEquals(self.callCount, 5)
self.assertEquals(self.results, values)
def _stub_gets_multi(self, keys):
self.callCount += 1
result = {}
for key in keys:
result[key] = self.expected[key]
return result
def test_splitGetsMulti(self):
self.callCount = 0
self.expected = {}
keys = []
for i in xrange(600):
keys.append("key%d" % (i,))
self.expected["key%d" % (i,)] = "value%d" % (i,)
mpc = MemcachePropertyCollection(None)
result = mpc._split_gets_multi(keys, self._stub_gets_multi)
self.assertEquals(self.callCount, 3)
self.assertEquals(self.expected, result)
def test_splitGetsMultiWithChunksize(self):
self.callCount = 0
self.expected = {}
keys = []
for i in xrange(600):
keys.append("key%d" % (i,))
self.expected["key%d" % (i,)] = "value%d" % (i,)
mpc = MemcachePropertyCollection(None)
result = mpc._split_gets_multi(keys, self._stub_gets_multi, chunksize=12)
self.assertEquals(self.callCount, 50)
self.assertEquals(self.expected, result)
|
trevor/calendarserver
|
twistedcaldav/test/test_memcacheprops.py
|
Python
|
apache-2.0
| 14,385 |
package ru.stqa.pft.sandbox;
/**
* Created by Yulia on 3/1/2017.
*/
public class Equality {
public static void main(String [] args){
String s1 = "firefox";
String s2 = new String(s1);
System.out.println(s1 == s2);
System.out.println(s1.equals(s2));
}
}
|
yvasilevskaya/java_pft
|
sandbox/src/main/java/ru/stqa/pft/sandbox/Equality.java
|
Java
|
apache-2.0
| 279 |
# -*- coding: utf-8 -*-
from selenium import webdriver
from fixture.session import SessionHelper
from fixture.group import GroupHelper
from fixture.address import AddressHelper
class Application(object):
def __init__(self, browser, base_url):
if browser == "firefox":
self.wd = webdriver.Firefox()
elif browser == 'chrome':
self.wd = webdriver.Chrome()
elif browser == "ie":
self.wd = webdriver.Ie()
else:
raise ValueError(f"Unrecognized browser {browser}")
self.wd.implicitly_wait(3)
self.session = SessionHelper(self)
self.group = GroupHelper(self)
self.address = AddressHelper(self)
self.base_url = base_url
self.open_home_page()
def open_home_page(self):
# open homepage
wd = self.wd
if not (wd.current_url.endswith("/addressbook/") and wd.find_element_by_name("searchstring")):
wd.get(self.base_url)
def is_valid(self):
try:
self.wd.current_url
return True
except:
return False
def destroy(self):
self.wd.quit()
|
vpalex999/python_training
|
fixture/application.py
|
Python
|
apache-2.0
| 1,165 |
jQuery(document).ready(function($){
$("a[data-upvote-id]").click(function(){
var id = $(this).attr('data-upvote-id');
$.ajax( {
url: WP_API_Settings.root + 'goodmorning-news/1.0/upvote/' + id,
method: 'GET',
beforeSend: function ( xhr ) {
xhr.setRequestHeader( 'X-WP-Nonce', WP_API_Settings.nonce );
}
} ).done( function ( response ) {
console.log( response );
} );
});
$("a[data-downvote-id]").click(function(){
var id = $(this).attr('data-downvote-id');
$.ajax( {
url: WP_API_Settings.root + 'goodmorning-news/1.0/downvote/' + id,
method: 'GET',
beforeSend: function ( xhr ) {
xhr.setRequestHeader( 'X-WP-Nonce', WP_API_Settings.nonce );
}
} ).done( function ( response ) {
console.log( response );
} );
});
});
|
Luehrsen/good_morning_news
|
www/wp-content/plugins/goodmorning_plugin/js/admin.js
|
JavaScript
|
apache-2.0
| 787 |
<?php include 'db.php';?>
<?php
if(isset($_POST["login-submit"]))
{
$sql="SELECT
`email`,
`passwd`
FROM
`register`
WHERE
email ='".$_POST['email']."';";
if($res = $mysqli->query($sql))
{
if ($res->num_rows > 0) {
// output data of each row
while($row = $res->fetch_assoc()) {
if($row['email'] == $_POST['email'] && $row['passwd'] == $_POST['passwd'])
{
echo '<script> window.location.href = "type.html";';
echo '</script>';
}
else
{
echo "<script> alert('invalid username or password');";
echo 'window.location.href = "login.html";';
echo '</script>';
}
}
}
}
}
?>
|
hkbhkb7/online_complaitbox
|
login.php
|
PHP
|
apache-2.0
| 672 |
/**
*
*/
package edu.mycourses.adt.st;
/**
* @author Ibrahima Diarra
*
*/
public class BasicST<Key, Value> extends AbstractST<Key, Value> {
@Override
public void put(Key key, Value value) {
}
@Override
public Value get(Key key) {
return null;
}
@Override
public int size() {
return 0;
}
@Override
public Iterable<Key> keys() {
return null;
}
}
|
githubdiarra/playground-repo
|
playground/src/main/java/edu/mycourses/adt/st/BasicST.java
|
Java
|
apache-2.0
| 407 |
#!/usr/bin/python
from __future__ import absolute_import, print_function
import argparse
import csv
import os
import re
import sys
try:
from plistlib import load as load_plist # Python 3
from plistlib import dump as dump_plist
except ImportError:
from plistlib import readPlist as load_plist # Python 2
from plistlib import writePlist as dump_plist
def getOptionsString(optionList):
# optionList should be a list item
optionsString = ''
for option in optionList:
if option == optionList[-1]:
optionsString += "\"%s\":\"%s\"" % (str(option.split('=')[0]), str(option.split('=')[1]))
else:
optionsString += "\"%s\":\"%s\"" % (str(option.split('=')[0]), str(option.split('=')[1])) + ', '
return optionsString
parser = argparse.ArgumentParser(description='Generate a Munki nopkg-style pkginfo for printer installation.')
parser.add_argument('--printername', help='Name of printer queue. May not contain spaces, tabs, # or /. Required.')
parser.add_argument('--driver', help='Name of driver file in /Library/Printers/PPDs/Contents/Resources/. Can be relative or full path. Required.')
parser.add_argument('--address', help='IP or DNS address of printer. If no protocol is specified, defaults to lpd://. Required.')
parser.add_argument('--location', help='Location name for printer. Optional. Defaults to printername.')
parser.add_argument('--displayname', help='Display name for printer (and Munki pkginfo). Optional. Defaults to printername.')
parser.add_argument('--desc', help='Description for Munki pkginfo only. Optional.')
parser.add_argument('--requires', help='Required packages in form of space-delimited \'CanonDriver1 CanonDriver2\'. Optional.')
parser.add_argument('--options', nargs='*', dest='options', help='Printer options in form of space-delimited \'Option1=Key Option2=Key Option3=Key\', etc. Optional.')
parser.add_argument('--version', help='Version number of Munki pkginfo. Optional. Defaults to 1.0.', default='1.0')
parser.add_argument('--icon', help='Specifies an existing icon in the Munki repo to display for the printer in Managed Software Center. Optional.')
parser.add_argument('--csv', help='Path to CSV file containing printer info. If CSV is provided, all other options are ignored.')
args = parser.parse_args()
pwd = os.path.dirname(os.path.realpath(__file__))
f = open(os.path.join(pwd, 'AddPrinter-Template.plist'), 'rb')
templatePlist = load_plist(f)
f.close()
if args.csv:
# A CSV was found, use that for all data.
with open(args.csv, mode='r') as infile:
reader = csv.reader(infile)
next(reader, None) # skip the header row
for row in reader:
newPlist = dict(templatePlist)
# each row contains 10 elements:
# Printer name, location, display name, address, driver, description, options, version, requires, icon
# options in the form of "Option=Value Option2=Value Option3=Value"
# requires in the form of "package1 package2" Note: the space seperator
theOptionString = ''
if row[6] != "":
theOptionString = getOptionsString(row[6].split(" "))
# First, change the plist keys in the pkginfo itself
newPlist['display_name'] = row[2]
newPlist['description'] = row[5]
newPlist['name'] = "AddPrinter_" + str(row[0]) # set to printer name
# Check for an icon
if row[9] != "":
newPlist['icon_name'] = row[9]
# Check for a version number
if row[7] != "":
# Assume the user specified a version number
version = row[7]
else:
# Use the default version of 1.0
version = "1.0"
newPlist['version'] = version
# Check for a protocol listed in the address
if '://' in row[3]:
# Assume the user passed in a full address and protocol
address = row[3]
else:
# Assume the user wants to use the default, lpd://
address = 'lpd://' + row[3]
# Append the driver path to the driver file specified in the csv
driver = '/Library/Printers/PPDs/Contents/Resources/%s' % row[4]
base_driver = row[4]
if row[4].endswith('.gz'):
base_driver = row[4].replace('.gz', '')
if base_driver.endswith('.ppd'):
base_driver = base_driver.replace('.ppd', '')
# Now change the variables in the installcheck_script
newPlist['installcheck_script'] = newPlist['installcheck_script'].replace("PRINTERNAME", row[0])
newPlist['installcheck_script'] = newPlist['installcheck_script'].replace("OPTIONS", theOptionString)
newPlist['installcheck_script'] = newPlist['installcheck_script'].replace("LOCATION", row[1].replace('"', ''))
newPlist['installcheck_script'] = newPlist['installcheck_script'].replace("DISPLAY_NAME", row[2].replace('"', ''))
newPlist['installcheck_script'] = newPlist['installcheck_script'].replace("ADDRESS", address)
newPlist['installcheck_script'] = newPlist['installcheck_script'].replace("DRIVER", base_driver)
# Now change the variables in the postinstall_script
newPlist['postinstall_script'] = newPlist['postinstall_script'].replace("PRINTERNAME", row[0])
newPlist['postinstall_script'] = newPlist['postinstall_script'].replace("LOCATION", row[1].replace('"', ''))
newPlist['postinstall_script'] = newPlist['postinstall_script'].replace("DISPLAY_NAME", row[2].replace('"', ''))
newPlist['postinstall_script'] = newPlist['postinstall_script'].replace("ADDRESS", address)
newPlist['postinstall_script'] = newPlist['postinstall_script'].replace("DRIVER", driver)
newPlist['postinstall_script'] = newPlist['postinstall_script'].replace("OPTIONS", theOptionString)
# Now change the one variable in the uninstall_script
newPlist['uninstall_script'] = newPlist['uninstall_script'].replace("PRINTERNAME", row[0])
# Add required packages if passed in the csv
if row[8] != "":
newPlist['requires'] = row[8].split(' ')
# Write out the file
newFileName = "AddPrinter-" + row[0] + "-" + version + ".pkginfo"
f = open(newFileName, 'wb')
dump_plist(newPlist, f)
f.close()
else:
if not args.printername:
print(os.path.basename(sys.argv[0]) + ': error: argument --printername is required', file=sys.stderr)
parser.print_usage()
sys.exit(1)
if not args.driver:
print(os.path.basename(sys.argv[0]) + ': error: argument --driver is required', file=sys.stderr)
parser.print_usage()
sys.exit(1)
if not args.address:
print(os.path.basename(sys.argv[0]) + ': error: argument --address is required', file=sys.stderr)
parser.print_usage()
sys.exit(1)
if re.search(r"[\s#/]", args.printername):
# printernames can't contain spaces, tabs, # or /. See lpadmin manpage for details.
print("ERROR: Printernames can't contain spaces, tabs, # or /.", file=sys.stderr)
sys.exit(1)
if args.desc:
description = args.desc
else:
description = ""
if args.displayname:
displayName = args.displayname
else:
displayName = str(args.printername)
if args.location:
location = args.location
else:
location = args.printername
if args.version:
version = str(args.version)
else:
version = "1.0"
if args.requires:
requires = args.requires
else:
requires = ""
if args.icon:
icon = args.icon
else:
icon = ""
if args.options:
optionsString = str(args.options[0]).split(' ')
optionsString = getOptionsString(optionsString)
else:
optionsString = ''
if args.driver.startswith('/Library'):
# Assume the user passed in a full path rather than a relative filename
driver = args.driver
else:
# Assume only a relative filename
driver = os.path.join('/Library/Printers/PPDs/Contents/Resources', args.driver)
if '://' in args.address:
# Assume the user passed in a full address and protocol
address = args.address
else:
# Assume the user wants to use the default, lpd://
address = 'lpd://' + args.address
newPlist = dict(templatePlist)
# root pkginfo variable replacement
newPlist['description'] = description
newPlist['display_name'] = displayName
newPlist['name'] = "AddPrinter_" + displayName.replace(" ", "")
newPlist['version'] = version
newPlist['icon_name'] = icon
# installcheck_script variable replacement
newPlist['installcheck_script'] = templatePlist['installcheck_script'].replace("PRINTERNAME", args.printername)
newPlist['installcheck_script'] = newPlist['installcheck_script'].replace("ADDRESS", address)
newPlist['installcheck_script'] = newPlist['installcheck_script'].replace("DISPLAY_NAME", displayName)
newPlist['installcheck_script'] = newPlist['installcheck_script'].replace("LOCATION", location.replace('"', ''))
newPlist['installcheck_script'] = newPlist['installcheck_script'].replace("DRIVER", os.path.splitext(os.path.basename(driver))[0].replace('"', ''))
newPlist['installcheck_script'] = newPlist['installcheck_script'].replace("OPTIONS", optionsString)
# postinstall_script variable replacement
newPlist['postinstall_script'] = templatePlist['postinstall_script'].replace("PRINTERNAME", args.printername)
newPlist['postinstall_script'] = newPlist['postinstall_script'].replace("ADDRESS", address)
newPlist['postinstall_script'] = newPlist['postinstall_script'].replace("DISPLAY_NAME", displayName)
newPlist['postinstall_script'] = newPlist['postinstall_script'].replace("LOCATION", location.replace('"', ''))
newPlist['postinstall_script'] = newPlist['postinstall_script'].replace("DRIVER", driver.replace('"', ''))
newPlist['postinstall_script'] = newPlist['postinstall_script'].replace("OPTIONS", optionsString)
# uninstall_script variable replacement
newPlist['uninstall_script'] = templatePlist['uninstall_script'].replace("PRINTERNAME", args.printername)
# required packages
if requires != "":
newPlist['requires'] = [r.replace('\\', '') for r in re.split(r"(?<!\\)\s", requires)]
newFileName = "AddPrinter-" + str(args.printername) + "-%s.pkginfo" % str(version)
f = open(newFileName, 'wb')
dump_plist(newPlist, f)
f.close()
|
nmcspadden/PrinterGenerator
|
print_generator.py
|
Python
|
apache-2.0
| 10,809 |
package jp.co.altxt2db.dto;
/**
* 環境情報保持DTO
*
*/
public class EnvironmentDto {
/** 実行用アクションクラスパス */
public String actionClass;
/** 実行時引数 */
public String[] args;
}
|
hisataka/altxt2db
|
src/main/java/jp/co/altxt2db/dto/EnvironmentDto.java
|
Java
|
apache-2.0
| 236 |
#include <iostream>
#include <ctime>
class Stos
{
private:
int dane[100];
int n;
int id;
public:
Stos(int id){
this->id = id;
n=0;
std::cout << "["<< id <<"] Pojawiam sie!" << std::endl;
}
~Stos(){
std::cout << "["<< id <<"] Znikam!" << std::endl;
}
void push(int e) { dane[n++] = e; }
int pop() { return dane[--n]; }
int empty() { return n==0; }
int size(){return n;}
int getId() { return id;}
};
class Data{
private:
int day;
int month;
int year;
public:
Data(){
time_t t = time(0);
struct tm * now = localtime( & t );
this->year = now->tm_year + 1900;
this->month = now->tm_mon + 1;
this->day = now->tm_mday;
}
Data(int day, int month, int year){
this->day = day;
this->month = month;
this->year = year;
}
void set(int d, int m, int r){
this->day = d;
this->month = m;
this->year = r;
}
void print(){
std::cout << day <<"-" << month << "-" << year;
}
};
void ex7(){
std::cout <<"Startuje program" <<std::endl;
for (int i = 0; i < 12; i++){
Stos* stos = new Stos(i);
std::cout << "Stworzylem stos!" << std::endl;
stos->push(2); stos->push(5); stos->push(3);
while(!stos->empty()){
std::cout << stos->pop() << std::endl;
}
delete stos;
std::cout << "Usunalem obiekt!" << std::endl;
}
}
void ex10(){
for (int i = 1; i <= 3; i++){
Stos* stos = new Stos(i);
delete stos;
}
std::cout <<std::endl;
Stos* stacks[3];
for (int i = 1; i <= 3; i++){
stacks[i-1] = new Stos(i);
}
for (int i = 3; i >= 1; i--){
delete stacks[(i-1)] ;
}
std::cout <<std::endl;
for (int i = 1; i <= 3; i++){
stacks[i-1] = new Stos(i);
}
for (int i = 1; i <= 3; i++){
delete stacks[(i-1)] ;
}
}
void dataEx2(){
int day,month, year;
std::cout <<"Podaj swoja date urodzenia! " << std::endl;
std::cout <<"Podaj dzien! " << std::endl;
std::cin >> day;
std::cout <<"Podaj miesiac! " << std::endl;
std::cin >> month;
std::cout <<"Podaj rok! " << std::endl;
std::cin >> year;
Data* date = new Date(day, month, year);
delete date;
}
main()
{
Data date;
}
|
grzegorz2047/UAMRepo
|
POB/po-c1/po-c1.cpp
|
C++
|
apache-2.0
| 2,750 |
package org.onvif.ver10.schema;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAnyElement;
import javax.xml.bind.annotation.XmlType;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.cxf.xjc.runtime.JAXBToStringStyle;
import org.w3c.dom.Element;
/**
* <p>Java class for IOCapabilitiesExtension2 complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="IOCapabilitiesExtension2">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <any processContents='lax' namespace='http://www.onvif.org/ver10/schema' maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "IOCapabilitiesExtension2", propOrder = {
"any"
})
public class IOCapabilitiesExtension2 {
@XmlAnyElement(lax = true)
protected List<java.lang.Object> any;
/**
* Gets the value of the any property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the any property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getAny().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link Element }
* {@link java.lang.Object }
*
*
*/
public List<java.lang.Object> getAny() {
if (any == null) {
any = new ArrayList<java.lang.Object>();
}
return this.any;
}
/**
* Generates a String representation of the contents of this type.
* This is an extension method, produced by the 'ts' xjc plugin
*
*/
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this, JAXBToStringStyle.DEFAULT_STYLE);
}
}
|
fpompermaier/onvif
|
onvif-ws-client/src/main/java/org/onvif/ver10/schema/IOCapabilitiesExtension2.java
|
Java
|
apache-2.0
| 2,379 |
/*
* Copyright (C) 2011 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.android.inputmethod.compat;
import java.lang.reflect.Method;
import java.util.Arrays;
public class ArraysCompatUtils {
private static final Method METHOD_Arrays_binarySearch = CompatUtils
.getMethod(Arrays.class, "binarySearch", int[].class, int.class, int.class, int.class);
public static int binarySearch(int[] array, int startIndex, int endIndex, int value) {
if (METHOD_Arrays_binarySearch != null) {
final Object index = CompatUtils.invoke(null, 0, METHOD_Arrays_binarySearch,
array, startIndex, endIndex, value);
return (Integer)index;
} else {
return compatBinarySearch(array, startIndex, endIndex, value);
}
}
/* package */ static int compatBinarySearch(int[] array, int startIndex, int endIndex,
int value) {
if (startIndex > endIndex) throw new IllegalArgumentException();
if (startIndex < 0 || endIndex > array.length) throw new ArrayIndexOutOfBoundsException();
final int work[] = new int[endIndex - startIndex];
System.arraycopy(array, startIndex, work, 0, work.length);
final int index = Arrays.binarySearch(work, value);
if (index >= 0) {
return index + startIndex;
} else {
return ~(~index + startIndex);
}
}
}
|
soeminnminn/LatinIME_ICS_ported
|
src/com/android/inputmethod/compat/ArraysCompatUtils.java
|
Java
|
apache-2.0
| 2,027 |
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/inspector2/model/GetFindingsReportStatusResult.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/UnreferencedParam.h>
#include <utility>
using namespace Aws::Inspector2::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws;
GetFindingsReportStatusResult::GetFindingsReportStatusResult() :
m_errorCode(ReportingErrorCode::NOT_SET),
m_status(ExternalReportStatus::NOT_SET)
{
}
GetFindingsReportStatusResult::GetFindingsReportStatusResult(const Aws::AmazonWebServiceResult<JsonValue>& result) :
m_errorCode(ReportingErrorCode::NOT_SET),
m_status(ExternalReportStatus::NOT_SET)
{
*this = result;
}
GetFindingsReportStatusResult& GetFindingsReportStatusResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
JsonView jsonValue = result.GetPayload().View();
if(jsonValue.ValueExists("destination"))
{
m_destination = jsonValue.GetObject("destination");
}
if(jsonValue.ValueExists("errorCode"))
{
m_errorCode = ReportingErrorCodeMapper::GetReportingErrorCodeForName(jsonValue.GetString("errorCode"));
}
if(jsonValue.ValueExists("errorMessage"))
{
m_errorMessage = jsonValue.GetString("errorMessage");
}
if(jsonValue.ValueExists("filterCriteria"))
{
m_filterCriteria = jsonValue.GetObject("filterCriteria");
}
if(jsonValue.ValueExists("reportId"))
{
m_reportId = jsonValue.GetString("reportId");
}
if(jsonValue.ValueExists("status"))
{
m_status = ExternalReportStatusMapper::GetExternalReportStatusForName(jsonValue.GetString("status"));
}
return *this;
}
|
aws/aws-sdk-cpp
|
aws-cpp-sdk-inspector2/source/model/GetFindingsReportStatusResult.cpp
|
C++
|
apache-2.0
| 1,854 |
package com.joyue.tech.gankio.mvp.history;
import com.joyue.tech.core.mvp.listener.OnLoadDataListListener;
import com.joyue.tech.gankio.api.GankApi;
import rx.Observer;
public class HistoryModel implements HistoryContract.Model {
@Override
public void history(OnLoadDataListListener listener) {
GankApi.getInstance().history(new Observer<String[]>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
//设置页面为加载错误
listener.onFailure(e);
}
@Override
public void onNext(String[] data) {
listener.onSuccess(data);
}
});
}
}
|
skyofthinking/AndRapid
|
gankio/src/main/java/com/joyue/tech/gankio/mvp/history/HistoryModel.java
|
Java
|
apache-2.0
| 764 |
module Amigrind
class Repo
include Amigrind::Core::Logging::Mixin
attr_reader :path
def initialize(path)
@path = File.expand_path path
raise "'path' (#{path}) is not a directory." unless Dir.exist?(path)
raise "'path' is not an Amigrind root (lacks .amigrind_root file)." \
unless File.exist?(File.join(path, '.amigrind_root'))
info_log "using Amigrind path: #{path}"
end
def environments_path
File.join(path, 'environments')
end
def blueprints_path
File.join(path, 'blueprints')
end
# TODO: Ruby DSL environments
def environment_names
yaml_environments =
Dir[File.join(environments_path, '*.yaml')] \
.map { |f| File.basename(f, '.yaml').to_s.strip.downcase }
rb_environments =
[].map { |f| File.basename(f, '.rb').to_s.strip.downcase }
duplicate_environments = yaml_environments & rb_environments
duplicate_environments.each do |dup_env_name|
warn_log "environment '#{dup_env_name}' found in both YAML and Ruby; skipping."
end
(yaml_environments + rb_environments - duplicate_environments).sort
end
# TODO: cache environments (but make configurable)
def environment(name)
yaml_path = yaml_path_if_exists(name)
rb_path = rb_path_if_exists(name)
raise "found multiple env files for same env #{name}." if !yaml_path.nil? && !rb_path.nil?
raise "TODO: implement Ruby environments." unless rb_path.nil?
env = Environments::Environment.load_yaml_file(yaml_path) unless yaml_path.nil?
raise "no env found for '#{name}'." if env.nil?
IceNine.deep_freeze(env)
env
end
def with_environment(environment_name, &block)
block.call(environment(environment_name))
end
def blueprint_names
Dir[File.join(blueprints_path, "*.rb")].map { |f| File.basename(f, ".rb") }
end
# TODO: cache blueprint/environment tuples (but make configurable)
def evaluate_blueprint(blueprint_name, env)
raise "'env' must be a String or an Environment." \
unless env.is_a?(String) || env.is_a?(Environments::Environment)
if env.is_a?(String)
env = environment(env)
end
ev = Amigrind::Blueprints::Evaluator.new(File.join(blueprints_path,
"#{blueprint_name}.rb"),
env)
ev.blueprint
end
# TODO: refactor these client-y things.
def add_to_channel(env, blueprint_name, id, channel)
raise "'env' must be a String or an Environment." \
unless env.is_a?(String) || env.is_a?(Environments::Environment)
raise "'blueprint_name' must be a String." unless blueprint_name.is_a?(String)
raise "'id' must be a Fixnum." unless id.is_a?(Fixnum)
raise "'channel' must be a String or Symbol." \
unless channel.is_a?(String) || channel.is_a?(Symbol)
if env.is_a?(String)
env = environment(env)
end
raise "channel '#{channel}' does not exist in environment '#{env.name}'." \
unless env.channels.key?(channel.to_s) || channel.to_sym == :latest
credentials = Amigrind::Config.aws_credentials(env)
amigrind_client = Amigrind::Core::Client.new(env.aws.region, credentials)
ec2 = Aws::EC2::Client.new(region: env.aws.region, credentials: credentials)
image = amigrind_client.get_image_by_id(name: blueprint_name, id: id)
tag_key = Amigrind::Core::AMIGRIND_CHANNEL_TAG % { channel_name: channel }
info_log "setting '#{tag_key}' on image #{image.id}..."
ec2.create_tags(
resources: [ image.id ],
tags: [
{
key: tag_key,
value: '1'
}
]
)
end
def remove_from_channel(env, blueprint_name, id, channel)
raise "'env' must be a String or an Environment." \
unless env.is_a?(String) || env.is_a?(Environments::Environment)
raise "'blueprint_name' must be a String." unless blueprint_name.is_a?(String)
raise "'id' must be a Fixnum." unless id.is_a?(Fixnum)
raise "'channel' must be a String or Symbol." \
unless channel.is_a?(String) || channel.is_a?(Symbol)
if env.is_a?(String)
env = environment(env)
end
raise "channel '#{channel}' does not exist in environment '#{env.name}'." \
unless env.channels.key?(channel.to_s) || channel.to_sym == :latest
credentials = Amigrind::Config.aws_credentials(env)
amigrind_client = Amigrind::Core::Client.new(env.aws.region, credentials)
ec2 = Aws::EC2::Client.new(region: env.aws.region, credentials: credentials)
image = amigrind_client.get_image_by_id(name: blueprint_name, id: id)
tag_key = Amigrind::Core::AMIGRIND_CHANNEL_TAG % { channel_name: channel }
info_log "clearing '#{tag_key}' on image #{image.id}..."
ec2.delete_tags(
resources: [ image.id ],
tags: [
{
key: tag_key,
value: nil
}
]
)
end
def get_image_by_channel(env, blueprint_name, channel, steps_back = 0)
raise "'env' must be a String or an Environment." \
unless env.is_a?(String) || env.is_a?(Environments::Environment)
raise "'blueprint_name' must be a String." unless blueprint_name.is_a?(String)
raise "'channel' must be a String or Symbol." \
unless channel.is_a?(String) || channel.is_a?(Symbol)
if env.is_a?(String)
env = environment(env)
end
raise "channel '#{channel}' does not exist in environment '#{env.name}'." \
unless env.channels.key?(channel.to_s) || channel.to_sym == :latest
credentials = Amigrind::Config.aws_credentials(env)
amigrind_client = Amigrind::Core::Client.new(env.aws.region, credentials)
amigrind_client.get_image_by_channel(name: blueprint_name, channel: channel, steps_back: steps_back)
end
class << self
def init(path:)
raise "TODO: implement"
end
def with_repo(path: nil, &block)
path = path || ENV['AMIGRIND_PATH'] || Dir.pwd
repo = Repo.new(path)
Dir.chdir path do
block.call(repo)
end
end
end
private
def yaml_path_if_exists(name)
matches = [
"#{environments_path}/#{name}.yml",
"#{environments_path}/#{name}.yaml",
"#{environments_path}/#{name}.yml.erb",
"#{environments_path}/#{name}.yaml.erb"
].select { |f| File.exist?(f) }
case matches.size
when 0
nil
when 1
matches.first
else
raise "found multiple env files for same env #{name}."
end
end
def rb_path_if_exists(name)
path = "#{environments_path}/#{name}.rb"
File.exist?(path) ? path : nil
end
end
end
|
eropple/amigrind
|
lib/amigrind/repo.rb
|
Ruby
|
apache-2.0
| 6,902 |
require_relative '../../test_helper'
class TestVersion < Minitest::Test
def test_version
assert_equal( false, SendWithUs::VERSION.nil? )
end
end
|
sendwithus/sendwithus_ruby
|
test/lib/send_with_us/version_test.rb
|
Ruby
|
apache-2.0
| 156 |
package com.google.ratel.deps.jackson.databind.ser.std;
import java.io.IOException;
import java.lang.reflect.Type;
import com.google.ratel.deps.jackson.core.*;
import com.google.ratel.deps.jackson.databind.JavaType;
import com.google.ratel.deps.jackson.databind.JsonMappingException;
import com.google.ratel.deps.jackson.databind.JsonNode;
import com.google.ratel.deps.jackson.databind.SerializerProvider;
import com.google.ratel.deps.jackson.databind.annotation.JacksonStdImpl;
import com.google.ratel.deps.jackson.databind.jsonFormatVisitors.JsonFormatVisitorWrapper;
/**
* This is the special serializer for regular {@link java.lang.String}s.
*<p>
* Since this is one of "native" types, no type information is ever
* included on serialization (unlike for most scalar types as of 1.5)
*/
@JacksonStdImpl
public final class StringSerializer
extends NonTypedScalarSerializerBase<String>
{
public StringSerializer() { super(String.class); }
/**
* For Strings, both null and Empty String qualify for emptiness.
*/
@Override
public boolean isEmpty(String value) {
return (value == null) || (value.length() == 0);
}
@Override
public void serialize(String value, JsonGenerator jgen, SerializerProvider provider)
throws IOException, JsonGenerationException
{
jgen.writeString(value);
}
@Override
public JsonNode getSchema(SerializerProvider provider, Type typeHint)
{
return createSchemaNode("string", true);
}
@Override
public void acceptJsonFormatVisitor(JsonFormatVisitorWrapper visitor, JavaType typeHint)
throws JsonMappingException
{
if (visitor != null) visitor.expectStringFormat(typeHint);
}
}
|
sabob/ratel
|
ratel/src/com/google/ratel/deps/jackson/databind/ser/std/StringSerializer.java
|
Java
|
apache-2.0
| 1,752 |
/**
* Copyright 2016 Sebastien Pelletier
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.pellse.decorator.collection;
public abstract class InitializedBoundedList<E> extends BoundedList<E>{
public InitializedBoundedList() {
super(3);
}
}
|
pellse/decorator
|
src/test/java/io/github/pellse/decorator/collection/InitializedBoundedList.java
|
Java
|
apache-2.0
| 772 |
import Ember from 'ember';
import HasIdMixin from '../mixins/has-id';
const { computed, Mixin, assert, defineProperty } = Ember;
/*
A mixin that enriches a component that is attached to a model property.
The property name by default is taken from the formComponent, computed unless explictly
defined in the `property` variable.
This mixin also binds a property named `errors` to the model's `model.errors.@propertyName` array
*/
export default Mixin.create(HasIdMixin, {
property: undefined,
propertyName: computed('property', 'formComponent.property', {
get() {
if (this.get('property')) {
return this.get('property');
} else if (this.get('formComponent.property')) {
return this.get('formComponent.property');
} else {
return assert(false, 'Property could not be found.');
}
}
}),
init() {
this._super(...arguments);
defineProperty(this, 'errors', computed.alias((`model.errors.${this.get('propertyName')}`)));
}
});
|
slannigan/computed_input_errors
|
addon/mixins/has-property.js
|
JavaScript
|
apache-2.0
| 1,005 |
using DotvvmAcademy.Meta.Syntax;
using System;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
namespace DotvvmAcademy.Meta
{
internal class MetaMemberInfoVisitor : MemberInfoVisitor<NameNode>
{
public override NameNode DefaultVisit(MemberInfo info)
{
throw new NotSupportedException($"MemberInfo of type \"{info.GetType()}\" is not supported.");
}
public override NameNode VisitConstructor(ConstructorInfo info)
{
return VisitMember(info);
}
public override NameNode VisitEvent(EventInfo info)
{
return VisitMember(info);
}
public override NameNode VisitField(FieldInfo info)
{
return VisitMember(info);
}
public override NameNode VisitMethod(MethodInfo info)
{
return VisitMember(info);
}
public override NameNode VisitProperty(PropertyInfo info)
{
return VisitMember(info);
}
public override NameNode VisitType(Type info)
{
if (info.IsConstructedGenericType)
{
var arguments = info.GetGenericArguments()
.Select(a => Visit(a));
return NameFactory.ConstructedType(Visit(info.GetGenericTypeDefinition()), arguments);
}
else if (info.IsNested)
{
return NameFactory.NestedType(Visit(info.DeclaringType), info.Name, info.GetGenericArguments().Length);
}
else if (info.IsPointer)
{
return NameFactory.PointerType(Visit(info.GetElementType()));
}
else if (info.IsArray)
{
return NameFactory.ArrayType(Visit(info.GetElementType()), info.GetArrayRank());
}
else
{
if (info.Namespace == null)
{
return NameFactory.Simple(info.Name);
}
else
{
return NameFactory.Qualified(VisitNamespace(info.Namespace), NameFactory.Simple(info.Name));
}
}
}
private NameNode VisitNamespace(string @namespace)
{
var segments = @namespace.Split('.');
NameNode result = NameFactory.Identifier(segments[0]);
for (int i = 1; i < segments.Length; i++)
{
result = NameFactory.Qualified(result, segments[i]);
}
return result;
}
private NameNode VisitMember(MemberInfo info)
{
return NameFactory.Member(Visit(info.DeclaringType), info.Name);
}
}
}
|
riganti/dotvvm-samples-academy
|
src/DotvvmAcademy.Meta/MetaMemberInfoVisitor.cs
|
C#
|
apache-2.0
| 2,764 |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
using System.Management.Automation;
using System.Text;
using System.Threading;
namespace NetworkUtility
{
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member
public class UriPathSegmentList : IList<string>, IList, INotifyPropertyChanged, INotifyCollectionChanged, IEquatable<UriPathSegmentList>, IComparable<UriPathSegmentList>, IComparable
{
private static StringComparer _comparer = StringComparer.InvariantCultureIgnoreCase;
private object _syncRoot = new object();
private List<string> _segments = null;
private List<char> _separators = new List<char>();
private int _count = 0;
private string _fullPath = "";
private string _encodedFullPath = "";
public event PropertyChangedEventHandler PropertyChanged;
public event NotifyCollectionChangedEventHandler CollectionChanged;
public string FullPath
{
get
{
Monitor.Enter(_syncRoot);
try { return _fullPath; }
finally { Monitor.Exit(_syncRoot); }
}
}
public string EncodedFullPath
{
get
{
Monitor.Enter(_syncRoot);
try { return _encodedFullPath; }
finally { Monitor.Exit(_syncRoot); }
}
}
public bool IsEmpty
{
get
{
Monitor.Enter(_syncRoot);
try { return _segments == null; }
finally { Monitor.Exit(_syncRoot); }
}
}
public bool IsPathRooted
{
get
{
Monitor.Enter(_syncRoot);
try { return _segments != null && _separators.Count == _segments.Count; }
finally { Monitor.Exit(_syncRoot); }
}
set
{
Monitor.Enter(_syncRoot);
try
{
if (value)
{
if (_separators == null)
_separators = new List<char>();
else if (_separators.Count < _segments.Count)
_separators.Insert(0, _separators.DefaultIfEmpty('/').First());
}
else if (_separators != null)
{
if (_separators.Count == 0)
_separators = null;
else
_separators.RemoveAt(0);
}
}
finally { Monitor.Exit(_syncRoot); }
}
}
public string this[int index]
{
get
{
Monitor.Enter(_syncRoot);
try { return _segments[index]; }
finally { Monitor.Exit(_syncRoot); }
}
set
{
string oldValue;
Monitor.Enter(_syncRoot);
try
{
if (value == null)
throw new ArgumentNullException();
if (_segments[index] == value)
return;
oldValue = _segments[index];
_segments[index] = value;
}
finally { Monitor.Exit(_syncRoot); }
UpdateFullPath(() => RaiseCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace, value, oldValue, index)));
}
}
object IList.this[int index]
{
get { return this[index]; }
set
{
object obj = value;
if (obj != null && obj is PSObject)
obj = (obj as PSObject).BaseObject;
this[index] = (string)obj;
}
}
public int Count
{
get
{
Monitor.Enter(_syncRoot);
try { return _count; }
finally { Monitor.Exit(_syncRoot); }
}
}
bool ICollection<string>.IsReadOnly { get { return false; } }
bool IList.IsReadOnly { get { return false; } }
bool IList.IsFixedSize { get { return false; } }
object ICollection.SyncRoot { get { return _syncRoot; } }
bool ICollection.IsSynchronized { get { return true; } }
public static string EscapePathSegment(string value)
{
if (String.IsNullOrEmpty(value))
return "";
StringBuilder sb = new StringBuilder();
foreach (char c in value)
{
switch (c)
{
case '%':
sb.Append("%25");
break;
case '\\':
sb.Append("%5C");
break;
case '#':
sb.Append("%23");
break;
case '/':
sb.Append("%2F");
break;
case ':':
sb.Append("%3A");
break;
case '?':
sb.Append("%3F");
break;
default:
if (c < ' ' || c > 126)
sb.Append(Uri.HexEscape(c));
else
sb.Append(c);
break;
}
}
return sb.ToString();
}
public static string EncodePathSegment(string value)
{
if (String.IsNullOrEmpty(value))
return "";
StringBuilder sb = new StringBuilder();
foreach (char c in value)
{
switch (c)
{
case ' ':
sb.Append("%20");
break;
case '"':
sb.Append("%22");
break;
case '%':
sb.Append("%25");
break;
case '<':
sb.Append("%3C");
break;
case '>':
sb.Append("%3E");
break;
case '\\':
sb.Append("%5C");
break;
case '^':
sb.Append("%5E");
break;
case '`':
sb.Append("%60");
break;
case '{':
sb.Append("%7B");
break;
case '|':
sb.Append("%7C");
break;
case '}':
sb.Append("%7D");
break;
case '#':
sb.Append("%23");
break;
case '+':
sb.Append("%2B");
break;
case '/':
sb.Append("%2F");
break;
case ':':
sb.Append("%3A");
break;
case '?':
sb.Append("%3F");
break;
default:
if (c < ' ' || c > 126)
sb.Append(Uri.HexEscape(c));
else
sb.Append(c);
break;
}
}
return sb.ToString();
}
private void EnsureCount(Action action)
{
try { action(); }
finally { EnsureCount(); }
}
private void EnsureCount()
{
Monitor.Enter(_syncRoot);
try
{
if (_count == _segments.Count)
return;
_count = _segments.Count;
}
finally { Monitor.Exit(_syncRoot); }
RaisePropertyChanged("Count");
}
private void UpdateFullPath(Action action)
{
try { action(); }
finally { UpdateFullPath(); }
}
private void UpdateFullPath()
{
string encodedFullPath, escapedFullPath;
Monitor.Enter(_syncRoot);
try
{
if (_segments.Count == 0)
{
encodedFullPath = "";
escapedFullPath = "";
}
else
{
StringBuilder encoded = new StringBuilder();
StringBuilder escaped = new StringBuilder();
if (_segments.Count == _separators.Count)
{
for (int i = 0; i < _segments.Count; i++)
{
char c = _separators[i];
encoded.Append(c);
escaped.Append(c);
string s = _segments[i];
encoded.Append(EncodePathSegment(s));
escaped.Append(EscapePathSegment(s));
}
}
else
{
encoded.Append(EncodePathSegment(_segments[0]));
for (int i = 1; i < _segments.Count; i++)
{
char c = _separators[i - 1];
encoded.Append(c);
encoded.Append(c);
string s = _segments[i];
encoded.Append(EncodePathSegment(s));
escaped.Append(EscapePathSegment(s));
}
}
encodedFullPath = encoded.ToString();
escapedFullPath = escaped.ToString();
}
if (_encodedFullPath == encodedFullPath)
encodedFullPath = null;
else
_encodedFullPath = encodedFullPath;
if (_fullPath == escapedFullPath)
escapedFullPath = null;
else
_fullPath = escapedFullPath;
}
finally { Monitor.Exit(_syncRoot); }
if (escapedFullPath != null)
RaisePropertyChanged("FullPath");
if (encodedFullPath != null)
RaisePropertyChanged("EncodedFullPath");
}
protected virtual void OnPropertyChanged(PropertyChangedEventArgs args) { }
protected void RaisePropertyChanged(string propertyName)
{
PropertyChangedEventArgs args = new PropertyChangedEventArgs(propertyName);
try { OnPropertyChanged(args); }
finally
{
PropertyChangedEventHandler propertyChanged = PropertyChanged;
if (propertyChanged != null)
propertyChanged(this, args);
}
}
protected virtual void OnCollectionChanged(NotifyCollectionChangedEventArgs args) { }
private void RaiseCollectionChanged(NotifyCollectionChangedEventArgs args)
{
try { OnCollectionChanged(args); }
finally
{
NotifyCollectionChangedEventHandler collectionChanged = CollectionChanged;
if (collectionChanged != null)
collectionChanged(this, args);
}
}
public int Add(string item)
{
if (item == null)
throw new ArgumentNullException("item");
Monitor.Enter(_syncRoot);
int index;
try
{
index = _segments.Count;
if (_separators == null)
_separators = new List<char>();
else
_separators.Add(_separators.DefaultIfEmpty('/').Last());
_segments.Add(item);
}
finally { Monitor.Exit(_syncRoot); }
EnsureCount();
UpdateFullPath();
return index;
}
void ICollection<string>.Add(string item) { Add(item); }
int IList.Add(object value)
{
object obj = value;
if (obj != null && obj is PSObject)
obj = (obj as PSObject).BaseObject;
return Add((string)obj);
}
public void Clear()
{
Monitor.Enter(_syncRoot);
try
{
if (_segments.Count == 0)
return;
if (_separators.Count == _segments.Count)
_separators.Clear();
else
_separators = null;
_segments.Clear();
}
finally { Monitor.Exit(_syncRoot); }
EnsureCount();
UpdateFullPath();
}
public bool Contains(string item)
{
if (item == null)
return false;
Monitor.Enter(_syncRoot);
try
{
if (_segments.Count == 0)
return false;
for (int i = 0; i < _segments.Count; i++)
{
if (_comparer.Equals(_segments[i], item))
return true;
}
}
finally { Monitor.Exit(_syncRoot); }
return false;
}
bool IList.Contains(object value)
{
object obj = value;
if (obj != null && obj is PSObject)
obj = (obj as PSObject).BaseObject;
return Contains(obj as string);
}
public void CopyTo(string[] array, int arrayIndex)
{
Monitor.Enter(_syncRoot);
try { _segments.CopyTo(array, arrayIndex); }
finally { Monitor.Exit(_syncRoot); }
}
void ICollection.CopyTo(Array array, int index)
{
Monitor.Enter(_syncRoot);
try { _segments.ToArray().CopyTo(array, index); }
finally { Monitor.Exit(_syncRoot); }
}
public IEnumerator<string> GetEnumerator() { return _segments.GetEnumerator(); }
public char? GetSeparator(int index)
{
Monitor.Enter(_syncRoot);
try
{
if (index < 0 || index >= _segments.Count)
throw new ArgumentOutOfRangeException("index");
if (_separators != null && _separators.Count == _segments.Count)
return _separators[index];
if (index == 0)
return null;
return _separators[index - 1];
}
finally { Monitor.Exit(_syncRoot); }
}
public int IndexOf(string item)
{
if (item == null)
return -1;
Monitor.Enter(_syncRoot);
try
{
if (_segments.Count == 0)
return -1;
int index = _segments.IndexOf(item);
if (index < 0)
{
for (int i = 0; i < _segments.Count; i++)
{
if (_comparer.Equals(_segments[i], item))
return i;
}
}
return index;
}
finally { Monitor.Exit(_syncRoot); }
}
int IList.IndexOf(object value)
{
object obj = value;
if (obj != null && obj is PSObject)
obj = (obj as PSObject).BaseObject;
return IndexOf(obj as string);
}
public void Insert(int index, string item)
{
if (item == null)
throw new ArgumentNullException("item");
Monitor.Enter(_syncRoot);
try
{
if (index < 0 || index > _segments.Count)
throw new ArgumentOutOfRangeException("index");
if (index == _segments.Count)
{
_segments.Add(item);
if (_separators == null)
_separators = new List<char>();
else
_separators.Add(_separators.DefaultIfEmpty('/').Last());
}
else
{
if (_separators.Count == _segments.Count)
_separators.Insert(index, _separators[index]);
else if (index == _separators.Count)
_separators.Add(_separators.DefaultIfEmpty('/').Last());
else if (index == 0)
_separators.Insert(0, _separators.DefaultIfEmpty('/').First());
else
_separators.Insert(index - 1, _separators[index - 1]);
_segments.Insert(index, item);
}
}
finally { Monitor.Exit(_syncRoot); }
EnsureCount();
UpdateFullPath();
}
void IList.Insert(int index, object value)
{
object obj = value;
if (obj != null && obj is PSObject)
obj = (obj as PSObject).BaseObject;
Insert(index, (string)obj);
}
public bool Remove(string item)
{
if (item == null)
return false;
Monitor.Enter(_syncRoot);
try
{
int index = IndexOf(item);
if (index < 0)
return false;
if (_segments.Count == _separators.Count)
_separators.RemoveAt(index);
else
_separators.RemoveAt((index > 0) ? index - 1 : 0);
_segments.RemoveAt(index);
}
finally { Monitor.Exit(_syncRoot); }
EnsureCount();
UpdateFullPath();
return true;
}
void IList.Remove(object value)
{
object obj = value;
if (obj != null && obj is PSObject)
obj = (obj as PSObject).BaseObject;
Remove(obj as string);
}
public void RemoveAt(int index)
{
Monitor.Enter(_syncRoot);
try
{
if (index < 0 || index >= _segments.Count)
throw new ArgumentOutOfRangeException("index");
if (_segments.Count == _separators.Count)
_separators.RemoveAt(index);
else
_separators.RemoveAt((index > 0) ? index - 1 : 0);
_segments.RemoveAt(index);
}
finally { Monitor.Exit(_syncRoot); }
EnsureCount();
UpdateFullPath();
}
public void SetSeparator(int index, char separator)
{
if (!(separator == ':' || separator == '/' || separator == '\\'))
throw new ArgumentException("Invalid separator character", "separator");
Monitor.Enter(_syncRoot);
try
{
if (index < 0 || index >= _segments.Count)
throw new ArgumentOutOfRangeException("index");
if (_separators.Count == _segments.Count)
_separators[index] = separator;
else if (index == 0)
_separators.Insert(0, separator);
else
_separators[index - 1] = separator;
}
finally { Monitor.Exit(_syncRoot); }
UpdateFullPath();
}
IEnumerator IEnumerable.GetEnumerator() { return _segments.ToArray().GetEnumerator(); }
#warning Not implemented
public int CompareTo(UriPathSegmentList other)
{
throw new NotImplementedException();
}
public int CompareTo(object obj) { return CompareTo(obj as UriPathSegmentList); }
public bool Equals(UriPathSegmentList other)
{
throw new NotImplementedException();
}
public override bool Equals(object obj) { return Equals(obj as UriPathSegmentList); }
public override int GetHashCode() { return ToString().GetHashCode(); }
public override string ToString()
{
Monitor.Enter(_syncRoot);
try
{
throw new NotImplementedException();
}
finally { Monitor.Exit(_syncRoot); }
}
}
#pragma warning restore CS1591 // Missing XML comment for publicly visible type or member
}
|
lerwine/PowerShell-Modules
|
src/NetworkUtility/UriPathSegmentList.cs
|
C#
|
apache-2.0
| 21,377 |
package botservice.schedule;
import botservice.model.system.UserLogEntity;
import botservice.model.system.UserLogEntity_;
import botservice.properties.BotServiceProperty;
import botservice.properties.BotServicePropertyConst;
import botservice.service.SystemService;
import botservice.service.common.BaseParam;
import botservice.serviceException.ServiceException;
import botservice.serviceException.ServiceExceptionObject;
import botservice.util.BotMsgDirectionType;
import botservice.util.BotMsgTransportStatus;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.ejb.*;
import javax.enterprise.event.Event;
import javax.inject.Inject;
import java.io.Serializable;
import java.util.List;
/**
* Бин, вызываемый по расписанию и пытающийся доставить те сообщения в очередь ботам (конечным пользователям),
* которые по каким-либо причинам не удалось доставить сразу
*/
@Singleton
@Startup
public class MsgToUserResender implements Serializable {
@Resource
private TimerService timerService;
@Inject
SystemService systemService;
@Inject
@ServiceException
Event<ServiceExceptionObject> serviceExceptionEvent;
@Inject
@BotServiceProperty(name = BotServicePropertyConst.MSG_TO_USER_RESEND_TIMEAUT)
private int msgToUserResendTimeOut;
@PostConstruct
public void init(){
timerService.createIntervalTimer(0L, msgToUserResendTimeOut*1000,
new TimerConfig(this, false));
}
@Timeout
public void resendMsgToClntApp(Timer timer){
if (timer.getInfo() instanceof MsgToUserResender){
List<UserLogEntity> userLogEntityList = systemService.getEntityListByCriteria(UserLogEntity.class,
new BaseParam(UserLogEntity_.directionType, BotMsgDirectionType.TO_USER),
new BaseParam(UserLogEntity_.transportStatus, BotMsgTransportStatus.DEFERRED));
for(UserLogEntity userLogEntity: userLogEntityList){
try {
systemService.sendMessageToBotQueue(userLogEntity.getMsgBody(), userLogEntity.getUserKeyEntity());
userLogEntity.setTransportStatus(BotMsgTransportStatus.DELIVERED);
systemService.mergeEntity(userLogEntity);
} catch (Exception e){
serviceExceptionEvent.fire(new ServiceExceptionObject(
"Ошибка при попытке повторной отправки сообщения в очередь бота: " +
userLogEntity.getUserKeyEntity().getBotEntity().getName(), e));
}
}
}
}
}
|
dev-comp/botservice
|
botservice-ejb/src/main/java/botservice/schedule/MsgToUserResender.java
|
Java
|
apache-2.0
| 2,890 |
package com.unit16.z.indexed;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.function.Function;
import java.util.function.Predicate;
import com.google.common.collect.Iterators;
import com.google.common.collect.Lists;
import com.google.common.collect.UnmodifiableIterator;
public abstract class DSL<B>
implements Indexed<B>, Iterable<B>
{
private static final class ListBacked<C>
extends DSL<C>
{
private final List<C> _list;
ListBacked(List<C> i)
{
_list = i;
}
ListBacked(DSL<C> i)
{
_list = new ArrayList<>(i.size());
for (C c : i) { _list.add(c); }
}
@Override public C get(int i) { return _list.get(i); }
@Override public int size() { return _list.size(); }
@Override public Iterator<C> iterator() { return _list.iterator(); }
@Override public String toString() { return getClass().getSimpleName() + ": " + _list.toString(); }
}
private static final class IndexedBacked<C>
extends DSL<C>
{
private final Indexed<C> _i;
IndexedBacked(Indexed<C> i) {
_i = i;
}
@Override
public C get(int i) { return _i.get(i); }
@Override
public int size() { return _i.size(); }
@Override
public Iterator<C> iterator() {
return new UnmodifiableIterator<C>() {
private int _j = 0;
@Override
public boolean hasNext() { return _j < size(); }
@Override
public C next() { _j++; return get(_j - 1);}
};
}
}
public static <C> DSL<C> from(List<C> c)
{
return new ListBacked<>(c);
}
public static <C> DSL<C> from(Indexed<C> c)
{
return (c instanceof DSL) ? (DSL<C>) c : new IndexedBacked<>(c);
}
public final <C> DSL<C> map(Function<? super B, ? extends C> f)
{
return new OnResultOf<>(this, f);
}
public final DSL<B> head(final int max)
{
final Indexed<B> w = this;
return new IndexedBacked<>(new Indexed<B>(){
@Override
public B get(int i) { return w.get(i); }
@Override
public int size() { return max; }});
}
public final DSL<B> tail(final int min)
{
final Indexed<B> w = this;
return new IndexedBacked<>(new Indexed<B>(){
@Override
public B get(int i) { return w.get(i + min); }
@Override
public int size() { return w.size() - min; }});
}
public final DSL<B> filter(Predicate<? super B> p)
{
if (size() > 0)
{
final Iterator<B> i = Iterators.filter(this.iterator(), x -> p.test(x));
if (i.hasNext())
{
return new ListBacked<>(Lists.newArrayList(i));
}
}
return new Empty<>();
}
public final DSL<B> strict()
{
return new ListBacked<>(this);
}
public final DSL<B> append(Indexed<B> snd)
{
return new Concat<>(this, snd);
}
private static final class Concat<C>
extends DSL<C>
{
private final DSL<C> fst_;
private final DSL<C> snd_;
private final int sf;
private final int ss;
Concat(Indexed<C> fst, Indexed<C> snd) {
fst_ = from(fst);
snd_ = from(snd);
sf = fst_.size();
ss = snd_.size();
}
@Override
public C get(int i) {
return i < sf ? fst_.get(i) : snd_.get(i - sf);
}
@Override
public int size() { return sf + ss; }
@Override
public Iterator<C> iterator() {
return Iterators.concat(fst_.iterator(), snd_.iterator()); }
}
}
|
vincentk/unit16-z
|
src/main/java/com/unit16/z/indexed/DSL.java
|
Java
|
apache-2.0
| 3,250 |
<h1>This is an taxonomy</h1>
<ul>
<li>id: {{ $taxonomy->id }}</li>
<li>slug: {{ $taxonomy->slug }}</li>
<li>hierarchical: {{ $taxonomy->hierarchical }}</li>
{{ dump($taxonomy->terms) }}
</ul>
|
Datahjelpen/PEAK
|
resources/views/item/taxonomy/content-main.blade.php
|
PHP
|
apache-2.0
| 206 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using Elasticsearch.Net;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Nest
{
[JsonConverter(typeof(GetAliasResponseConverter))]
public interface IGetAliasResponse : IResponse
{
IReadOnlyDictionary<string, IReadOnlyList<AliasDefinition>> Indices { get; }
/// <summary>
/// An additional error message if an error occurs.
/// </summary>
/// <remarks>Applies to Elasticsearch 5.5.0+</remarks>
string Error { get; }
int? StatusCode { get; }
}
public class GetAliasResponse : ResponseBase, IGetAliasResponse
{
public IReadOnlyDictionary<string, IReadOnlyList<AliasDefinition>> Indices { get; internal set; } = EmptyReadOnly<string, IReadOnlyList<AliasDefinition>>.Dictionary;
public override bool IsValid => this.Indices.Count > 0;
public string Error { get; internal set; }
public int? StatusCode { get; internal set; }
}
internal class GetAliasResponseConverter : JsonConverter
{
public override bool CanWrite => false;
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotSupportedException();
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var j = JObject.Load(reader);
var errorProperty =j.Property("error");
string error = null;
if (errorProperty?.Value?.Type == JTokenType.String)
{
error = errorProperty.Value.Value<string>();
errorProperty.Remove();
}
var statusProperty =j.Property("status");
int? statusCode = null;
if (statusProperty?.Value?.Type == JTokenType.Integer)
{
statusCode = statusProperty.Value.Value<int>();
statusProperty.Remove();
}
//Read the remaining properties as aliases
var dict = serializer.Deserialize<Dictionary<string, Dictionary<string, Dictionary<string, AliasDefinition>>>>(j.CreateReader());
var indices = new Dictionary<string, IReadOnlyList<AliasDefinition>>();
foreach (var kv in dict)
{
var indexDict = kv.Key;
var aliases = new List<AliasDefinition>();
if (kv.Value != null && kv.Value.ContainsKey("aliases"))
{
var aliasDict = kv.Value["aliases"];
if (aliasDict != null)
aliases = aliasDict.Select(kva =>
{
var alias = kva.Value;
alias.Name = kva.Key;
return alias;
}).ToList();
}
indices.Add(indexDict, aliases);
}
return new GetAliasResponse { Indices = indices, Error = error, StatusCode = statusCode};
}
public override bool CanConvert(Type objectType) => true;
}
}
|
CSGOpenSource/elasticsearch-net
|
src/Nest/Indices/AliasManagement/GetAlias/GetAliasResponse.cs
|
C#
|
apache-2.0
| 2,661 |
/*
* #%L
* FlatPack Demonstration Client
* %%
* Copyright (C) 2012 Perka 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.
* #L%
*/
package com.getperka.flatpack.demo.client;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;
import javax.ws.rs.core.UriBuilder;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import com.getperka.flatpack.Configuration;
import com.getperka.flatpack.FlatPack;
import com.getperka.flatpack.FlatPackEntity;
import com.getperka.flatpack.client.StatusCodeException;
import com.getperka.flatpack.demo.server.DemoServer;
/**
* Contains a variety of smoke tests to demonstrate various facets of the FlatPack stack.
*/
public class ClientSmokeTest {
private static final int PORT = 8111;
/**
* Spin up an instance of the demo server.
*/
@BeforeClass
public static void beforeClass() {
assertTrue(new DemoServer().start(PORT));
}
private ClientApi api;
private Random random;
/**
* Creates an instance of the ClientApi.
*/
@Before
public void before() throws IOException {
random = new Random(0);
Configuration config = new Configuration()
.addTypeSource(ClientTypeSource.get());
api = new ClientApi(FlatPack.create(config));
api.setServerBase(UriBuilder.fromUri("http://localhost").port(PORT).build());
api.setVerbose(true);
assertEquals(204, api.resetPost().execute().getResponseCode());
}
/**
* Demonstrates ConstraintViolation handling. ConstraintViolations are returned as a simple
* {@code string:string} map in the FlatPackEntity's {@code error} block. The goal is to provide
* enough context for user interfaces to present the error message in a useful way, without
* assuming that the client is a Java app.
*/
@Test
public void testConstraintViolation() throws IOException {
Product p = makeProduct();
p.setPrice(BigDecimal.valueOf(-1));
FlatPackEntity<?> entity = null;
try {
api.productsPut(Collections.singletonList(p))
.queryParameter("isAdmin", "true")
.execute();
fail("Should have seen StatusCodeException");
} catch (StatusCodeException e) {
// The 400 status code is returned by the service method.
assertEquals(400, e.getStatusCode());
/*
* If the server returned a valid flatpack-encoded response, it can be retrieved from the
* StatusCodeException. Otherwise, this method will return null.
*/
entity = e.getEntity();
}
// Pull out the error messages
Map<String, String> errors = entity.getExtraErrors();
assertNotNull(errors);
assertEquals(1, errors.size());
Map.Entry<String, String> entry = errors.entrySet().iterator().next();
assertEquals("price", entry.getKey());
assertEquals("must be greater than or equal to 0", entry.getValue());
}
/**
* Demonstrates how generated client API will present a non-FlatPack resource (as an
* HttpUrlConnection).
*/
@Test
public void testNonFlatpackEndpoint() throws IOException {
// The query parameters are added as a builder-style pattern
HttpURLConnection conn = api.helloGet().withName("ClientSmokeTest").execute();
assertEquals(200, conn.getResponseCode());
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(),
Charset.forName("UTF8")));
assertEquals("Hello ClientSmokeTest!", reader.readLine());
}
/**
* Demonstrates the use of roles to restrict property setters.
*/
@Test
public void testRolePropertyAccess() throws IOException {
// Create a Product
Product p = new Product();
UUID uuid = p.getUuid();
p.setName("Product");
p.setNotes("Some notes");
p.setPrice(BigDecimal.valueOf(42));
api.productsPut(Collections.singletonList(p))
.queryParameter("isAdmin", "true")
.execute();
// Try to update it with a non-admin request
p = new Product();
p.setUuid(uuid);
p.setPrice(BigDecimal.valueOf(1));
api.productsPut(Collections.singletonList(p)).execute();
// Verify that nothing changed, as nobody
List<Product> products = api.productsGet().execute().getValue();
assertEquals(1, products.size());
p = products.get(0);
// Same UUID
assertEquals(uuid, p.getUuid());
// Unchanged price
assertEquals(BigDecimal.valueOf(42), p.getPrice());
// Can't see the notes
assertNull(p.getNotes());
// Now try the update again, as an admin
p = new Product();
p.setUuid(uuid);
p.setPrice(BigDecimal.valueOf(99));
api.productsPut(Collections.singletonList(p))
.queryParameter("isAdmin", "true")
.execute();
// Verify the changes, as nobody
products = api.productsGet().execute().getValue();
assertEquals(1, products.size());
p = products.get(0);
// Same UUID
assertEquals(uuid, p.getUuid());
// Unchanged price
assertEquals(BigDecimal.valueOf(99), p.getPrice());
}
/**
* Demonstrates a couple of round-trips to the server.
*/
@Test
public void testSimpleGetAndPut() throws IOException {
List<Product> products = api.productsGet().execute().getValue();
assertEquals(0, products.size());
// A server error would be reported as a StatusCodeException, a subclass of IOException
api.productsPut(Arrays.asList(makeProduct(), makeProduct()))
.queryParameter("isAdmin", "true")
.execute();
/*
* The object returned from productsGet() is an endpoint-specific interface that may contain
* additional fluid setters for declared query parameters. It also provides access to some
* request internals, including the FlatPackEntity that will be sent as part of the request.
* This allows callers to further customize outgoing requests, in the above case to add the
* isAdmin query parameter that interacts with the DummyAuthenticator. The call to execute()
* triggers payload serialization and execution of the HTTP request. This returns a
* FlatPackEntity describing the response, and getValue() returns the primary value object
* contained in the payload.
*/
FlatPackEntity<List<Product>> entity = api.productsGet().execute();
assertTrue(entity.getExtraErrors().toString(), entity.getExtraErrors().isEmpty());
assertTrue(entity.getExtraWarnings().toString(), entity.getExtraWarnings().isEmpty());
products = entity.getValue();
assertEquals(2, products.size());
assertEquals(BigDecimal.valueOf(360), products.get(0).getPrice());
assertEquals(BigDecimal.valueOf(948), products.get(1).getPrice());
assertTrue(products.get(0).wasPersistent());
assertTrue(products.get(1).wasPersistent());
// Try to update one of the objects
Product p = products.get(0);
p.setPrice(BigDecimal.valueOf(99));
assertEquals(Collections.singleton("price"), p.dirtyPropertyNames());
api.productsPut(Collections.singletonList(p)).queryParameter("isAdmin", "true").execute();
// Re-fetch and verify update
products = api.productsGet().execute().getValue();
assertEquals(99, products.get(0).getPrice().intValue());
assertTrue(products.get(0).dirtyPropertyNames().isEmpty());
}
private Product makeProduct() {
Product p = new Product();
p.setName("ClientSmokeTest");
p.setPrice(BigDecimal.valueOf(random.nextInt(1000)));
return p;
}
}
|
perka/flatpack-java
|
demo-client/src/test/java/com/getperka/flatpack/demo/client/ClientSmokeTest.java
|
Java
|
apache-2.0
| 8,420 |
package com.example.testconnectionappmart;
public class Service {
private int id;
private String discountEndDt;
private String discountPrice;
private String logoImagePath;
private String discountAmount;
private String saveType;
private String appmartPrice;
private String serviceName;
private String appName;
private String exp;
private String price;
private String serviceId;
private String cntCycle;
private String saleType;
private String discountStartDt;
private String policy;
private String developId;
private String discountRate;
private String dayCycle;
private String setlType;
private String monthCycle;
//constructor
//constructor
public Service(){}
public Service(String serviceId){
this.serviceId= serviceId;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getServiceId() {
return serviceId;
}
public void setServiceId(String serviceId) {
this.serviceId = serviceId;
}
public String getDiscountEndDt() {
return discountEndDt;
}
public void setDiscountEndDt(String discountEndDt) {
this.discountEndDt = discountEndDt;
}
public String getDiscountPrice() {
return discountPrice;
}
public void setDiscountPrice(String discountPrice) {
this.discountPrice = discountPrice;
}
public String getLogoImagePath() {
return logoImagePath;
}
public void setLogoImagePath(String logoImagePath) {
this.logoImagePath = logoImagePath;
}
public String getDiscountAmount() {
return discountAmount;
}
public void setDiscountAmount(String discountAmount) {
this.discountAmount = discountAmount;
}
public String getSaveType() {
return saveType;
}
public void setSaveType(String saveType) {
this.saveType = saveType;
}
public String getAppmartPrice() {
return appmartPrice;
}
public void setAppmartPrice(String appmartPrice) {
this.appmartPrice = appmartPrice;
}
public String getServiceName() {
return serviceName;
}
public void setServiceName(String serviceName) {
this.serviceName = serviceName;
}
public String getAppName() {
return appName;
}
public void setAppName(String appName) {
this.appName = appName;
}
public String getExp() {
return exp;
}
public void setExp(String exp) {
this.exp = exp;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getCntCycle() {
return cntCycle;
}
public void setCntCycle(String cntCycle) {
this.cntCycle = cntCycle;
}
public String getSaleType() {
return saleType;
}
public void setSaleType(String saleType) {
this.saleType = saleType;
}
public String getDiscountStartDt() {
return discountStartDt;
}
public void setDiscountStartDt(String discountStartDt) {
this.discountStartDt = discountStartDt;
}
public String getPolicy() {
return policy;
}
public void setPolicy(String policy) {
this.policy = policy;
}
public String getDevelopId() {
return developId;
}
public void setDevelopId(String developId) {
this.developId = developId;
}
public String getDiscountRate() {
return discountRate;
}
public void setDiscountRate(String discountRate) {
this.discountRate = discountRate;
}
public String getDayCycle() {
return dayCycle;
}
public void setDayCycle(String dayCycle) {
this.dayCycle = dayCycle;
}
public String getSetlType() {
return setlType;
}
public void setSetlType(String setlType) {
this.setlType = setlType;
}
public String getMonthCycle() {
return monthCycle;
}
public void setMonthCycle(String monthCycle) {
this.monthCycle = monthCycle;
}
}
|
info-appmart/OthersMethods
|
src/com/example/testconnectionappmart/Service.java
|
Java
|
apache-2.0
| 3,650 |
package com.animerom.filemanager.commands.shell;
import com.animerom.filemanager.commands.ChangePermissionsExecutable;
import com.animerom.filemanager.console.CommandNotFoundException;
import com.animerom.filemanager.console.ExecutionException;
import com.animerom.filemanager.console.InsufficientPermissionsException;
import com.animerom.filemanager.model.MountPoint;
import com.animerom.filemanager.model.Permissions;
import com.animerom.filemanager.util.MountPointHelper;
import java.text.ParseException;
/**
* A class for change the permissions of an object.
*
* {@link "http://unixhelp.ed.ac.uk/CGI/man-cgi?chmod"}
*/
public class ChangePermissionsCommand
extends SyncResultProgram implements ChangePermissionsExecutable {
private static final String ID = "chmod"; //$NON-NLS-1$
private Boolean mRet;
private final String mFileName;
/**
* Constructor of <code>ChangePermissionsCommand</code>.
*
* @param fileName The name of the file or directory to be moved
* @param newPermissions The new permissions to apply to the object
* @throws InvalidCommandDefinitionException If the command has an invalid definition
*/
public ChangePermissionsCommand(
String fileName, Permissions newPermissions) throws InvalidCommandDefinitionException {
super(ID, newPermissions.toOctalString(), fileName);
this.mFileName = fileName;
}
/**
* {@inheritDoc}
*/
@Override
public void parse(String in, String err) throws ParseException {
//Release the return object
this.mRet = Boolean.TRUE;
}
/**
* {@inheritDoc}
*/
@Override
public Boolean getResult() {
return this.mRet;
}
/**
* {@inheritDoc}
*/
@Override
public void checkExitCode(int exitCode)
throws InsufficientPermissionsException, CommandNotFoundException, ExecutionException {
if (exitCode != 0) {
throw new ExecutionException("exitcode != 0"); //$NON-NLS-1$
}
}
/**
* {@inheritDoc}
*/
@Override
public MountPoint getSrcWritableMountPoint() {
return null;
}
/**
* {@inheritDoc}
*/
@Override
public MountPoint getDstWritableMountPoint() {
return MountPointHelper.getMountPointFromDirectory(this.mFileName);
}
}
|
AnimeROM/android_package_AnimeManager
|
src/com/animerom/filemanager/commands/shell/ChangePermissionsCommand.java
|
Java
|
apache-2.0
| 2,364 |
<?php
/**
* This example updates a proposal's notes. To determine which proposals exist,
* run GetAllProposals.php.
*
* PHP version 5
*
* Copyright 2014, 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.
*
* @package GoogleApiAdsDfp
* @subpackage v201702
* @category WebServices
* @copyright 2014, Google Inc. All Rights Reserved.
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache License,
* Version 2.0
*/
error_reporting(E_STRICT | E_ALL);
// You can set the include path to src directory or reference
// DfpUser.php directly via require_once.
// $path = '/path/to/dfp_api_php_lib/src';
$path = dirname(__FILE__) . '/../../../../src';
set_include_path(get_include_path() . PATH_SEPARATOR . $path);
require_once 'Google/Api/Ads/Dfp/Lib/DfpUser.php';
require_once 'Google/Api/Ads/Dfp/Util/v201702/StatementBuilder.php';
require_once dirname(__FILE__) . '/../../../Common/ExampleUtils.php';
// Set the ID of the proposal to update.
$proposalId = 'INSERT_PROPOSAL_ID_HERE';
try {
// Get DfpUser from credentials in "../auth.ini"
// relative to the DfpUser.php file's directory.
$user = new DfpUser();
// Log SOAP XML request and response.
$user->LogDefaults();
// Get the ProposalService.
$proposalService = $user->GetService('ProposalService', 'v201702');
// Create a statement to select a single proposal by ID.
$statementBuilder = new StatementBuilder();
$statementBuilder->Where('id = :id')
->OrderBy('id ASC')
->Limit(1)
->WithBindVariableValue('id', $proposalId);
// Get the proposal.
$page = $proposalService->getProposalsByStatement(
$statementBuilder->ToStatement());
$proposal = $page->results[0];
// Update the proposal's notes.
$proposal->internalNotes = 'Proposal needs further review before approval.';
// Update the proposal on the server.
$proposals = $proposalService->updateProposals(array($proposal));
foreach ($proposals as $updatedProposal) {
printf("Proposal with ID %d and name '%s' was updated.\n",
$updatedProposal->id, $updatedProposal->name);
}
} catch (OAuth2Exception $e) {
ExampleUtils::CheckForOAuth2Errors($e);
} catch (ValidationException $e) {
ExampleUtils::CheckForOAuth2Errors($e);
} catch (Exception $e) {
printf("%s\n", $e->getMessage());
}
|
Getsidecar/googleads-php-lib
|
examples/Dfp/v201702/ProposalService/UpdateProposals.php
|
PHP
|
apache-2.0
| 2,856 |
/*
* Copyright © 2014 - 2019 Leipzig University (Database Research Group)
*
* 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.gradoop.flink.model.impl.operators.matching.single.cypher.common.functions;
import org.gradoop.common.model.impl.id.GradoopId;
import org.gradoop.flink.model.impl.operators.matching.single.cypher.functions.ReverseEdgeEmbedding;
import org.gradoop.flink.model.impl.operators.matching.single.cypher.pojos.Embedding;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class ReverseEdgeEmbeddingTest {
@Test
public void testReversingAnEdgeEmbedding() throws Exception {
GradoopId a = GradoopId.get();
GradoopId e = GradoopId.get();
GradoopId b = GradoopId.get();
Embedding edge = new Embedding();
edge.add(a);
edge.add(e);
edge.add(b);
ReverseEdgeEmbedding op = new ReverseEdgeEmbedding();
Embedding reversed = op.map(edge);
assertEquals(b, reversed.getId(0));
assertEquals(e, reversed.getId(1));
assertEquals(a, reversed.getId(2));
}
}
|
rostam/gradoop
|
gradoop-flink/src/test/java/org/gradoop/flink/model/impl/operators/matching/single/cypher/common/functions/ReverseEdgeEmbeddingTest.java
|
Java
|
apache-2.0
| 1,568 |
/*
* Copyright 2013 Gunnar Kappei.
*
* 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 net.opengis.gml;
/**
* An XML MultiSurfaceDomainType(@http://www.opengis.net/gml).
*
* This is a complex type.
*/
public interface MultiSurfaceDomainType extends net.opengis.gml.DomainSetType
{
public static final org.apache.xmlbeans.SchemaType type = (org.apache.xmlbeans.SchemaType)
org.apache.xmlbeans.XmlBeans.typeSystemForClassLoader(MultiSurfaceDomainType.class.getClassLoader(), "schemaorg_apache_xmlbeans.system.s6E28D279B6C224D74769DB8B98AF1665").resolveHandle("multisurfacedomaintype70a9type");
/**
* Gets the "MultiSurface" element
*/
net.opengis.gml.MultiSurfaceType getMultiSurface();
/**
* True if has "MultiSurface" element
*/
boolean isSetMultiSurface();
/**
* Sets the "MultiSurface" element
*/
void setMultiSurface(net.opengis.gml.MultiSurfaceType multiSurface);
/**
* Appends and returns a new empty "MultiSurface" element
*/
net.opengis.gml.MultiSurfaceType addNewMultiSurface();
/**
* Unsets the "MultiSurface" element
*/
void unsetMultiSurface();
/**
* A factory class with static methods for creating instances
* of this type.
*/
public static final class Factory
{
public static net.opengis.gml.MultiSurfaceDomainType newInstance() {
return (net.opengis.gml.MultiSurfaceDomainType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newInstance( type, null ); }
public static net.opengis.gml.MultiSurfaceDomainType newInstance(org.apache.xmlbeans.XmlOptions options) {
return (net.opengis.gml.MultiSurfaceDomainType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newInstance( type, options ); }
/** @param xmlAsString the string value to parse */
public static net.opengis.gml.MultiSurfaceDomainType parse(java.lang.String xmlAsString) throws org.apache.xmlbeans.XmlException {
return (net.opengis.gml.MultiSurfaceDomainType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( xmlAsString, type, null ); }
public static net.opengis.gml.MultiSurfaceDomainType parse(java.lang.String xmlAsString, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException {
return (net.opengis.gml.MultiSurfaceDomainType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( xmlAsString, type, options ); }
/** @param file the file from which to load an xml document */
public static net.opengis.gml.MultiSurfaceDomainType parse(java.io.File file) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (net.opengis.gml.MultiSurfaceDomainType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( file, type, null ); }
public static net.opengis.gml.MultiSurfaceDomainType parse(java.io.File file, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (net.opengis.gml.MultiSurfaceDomainType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( file, type, options ); }
public static net.opengis.gml.MultiSurfaceDomainType parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (net.opengis.gml.MultiSurfaceDomainType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( u, type, null ); }
public static net.opengis.gml.MultiSurfaceDomainType parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (net.opengis.gml.MultiSurfaceDomainType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( u, type, options ); }
public static net.opengis.gml.MultiSurfaceDomainType parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (net.opengis.gml.MultiSurfaceDomainType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( is, type, null ); }
public static net.opengis.gml.MultiSurfaceDomainType parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (net.opengis.gml.MultiSurfaceDomainType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( is, type, options ); }
public static net.opengis.gml.MultiSurfaceDomainType parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (net.opengis.gml.MultiSurfaceDomainType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( r, type, null ); }
public static net.opengis.gml.MultiSurfaceDomainType parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (net.opengis.gml.MultiSurfaceDomainType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( r, type, options ); }
public static net.opengis.gml.MultiSurfaceDomainType parse(javax.xml.stream.XMLStreamReader sr) throws org.apache.xmlbeans.XmlException {
return (net.opengis.gml.MultiSurfaceDomainType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( sr, type, null ); }
public static net.opengis.gml.MultiSurfaceDomainType parse(javax.xml.stream.XMLStreamReader sr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException {
return (net.opengis.gml.MultiSurfaceDomainType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( sr, type, options ); }
public static net.opengis.gml.MultiSurfaceDomainType parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException {
return (net.opengis.gml.MultiSurfaceDomainType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( node, type, null ); }
public static net.opengis.gml.MultiSurfaceDomainType parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException {
return (net.opengis.gml.MultiSurfaceDomainType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( node, type, options ); }
/** @deprecated {@link org.apache.xmlbeans.xml.stream.XMLInputStream} */
@Deprecated
public static net.opengis.gml.MultiSurfaceDomainType parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException {
return (net.opengis.gml.MultiSurfaceDomainType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( xis, type, null ); }
/** @deprecated {@link org.apache.xmlbeans.xml.stream.XMLInputStream} */
@Deprecated
public static net.opengis.gml.MultiSurfaceDomainType parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException {
return (net.opengis.gml.MultiSurfaceDomainType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( xis, type, options ); }
/** @deprecated {@link org.apache.xmlbeans.xml.stream.XMLInputStream} */
@Deprecated
public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException {
return org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, null ); }
/** @deprecated {@link org.apache.xmlbeans.xml.stream.XMLInputStream} */
@Deprecated
public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException {
return org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, options ); }
private Factory() { } // No instance of this class allowed
}
}
|
moosbusch/xbLIDO
|
src/net/opengis/gml/MultiSurfaceDomainType.java
|
Java
|
apache-2.0
| 8,916 |
package o;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import com.quizup.core.QuizApplication;
import com.quizup.core.activities.WallpaperActivity;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
public final class ฯ extends BaseAdapter
{
public ArrayList<Υ> ˊ;
private WallpaperActivity ˋ;
private Bitmap ˎ;
private int ˏ;
public ฯ(WallpaperActivity paramWallpaperActivity)
{
this.ˋ = paramWallpaperActivity;
this.ˊ = ϟ.ˊ(QuizApplication.ᐝ());
this.ˏ = ((int)TypedValue.applyDimension(1, 120.0F, Resources.getSystem().getDisplayMetrics()));
Υ localΥ = new Υ(paramWallpaperActivity);
localΥ.ˊ = "file://wallpaper:pattern_1:purple";
this.ˎ = ϟ.ˊ(paramWallpaperActivity, localΥ, this.ˏ);
}
public final int getCount()
{
return this.ˊ.size();
}
public final long getItemId(int paramInt)
{
return 0L;
}
public final View getView(int paramInt, View paramView, ViewGroup paramViewGroup)
{
ImageView localImageView2;
if (paramView == null)
{
ImageView localImageView1 = new ImageView(this.ˋ);
localImageView2 = localImageView1;
localImageView1.setLayoutParams(new AbsListView.LayoutParams(this.ˏ, this.ˏ));
}
else
{
localImageView2 = (ImageView)paramView;
}
int i;
if (((Υ)this.ˊ.get(paramInt)).ˋ == null)
i = 1;
else
i = 0;
if (i != 0)
{
Υ localΥ = (Υ)this.ˊ.get(paramInt);
ImageView localImageView3 = localImageView2;
if (localImageView3 != null)
{
Drawable localDrawable = localImageView3.getDrawable();
if ((localDrawable instanceof ฯ.if))
{
localʇ1 = (ʇ)((ฯ.if)localDrawable).ˊ.get();
break label140;
}
}
ʇ localʇ1 = null;
label140: ʇ localʇ2 = localʇ1;
if (localʇ1 != null)
if (localʇ2.ˊ.equals(localΥ))
{
localʇ2.cancel(true);
}
else
{
j = 0;
break label181;
}
int j = 1;
label181: if (j != 0)
{
ʇ localʇ3 = new ʇ(this.ˋ, localImageView3, localΥ, this.ˏ);
localImageView3.setImageDrawable(new ฯ.if(this.ˋ.getResources(), this.ˎ, localʇ3));
localʇ3.execute(new Void[0]);
}
return localImageView2;
}
localImageView2.setImageBitmap(((Υ)this.ˊ.get(paramInt)).ˋ);
return localImageView2;
}
}
/* Location: /Users/vikas/Documents/Mhacks_Real_app/classes-dex2jar.jar
* Qualified Name: o.ฯ
* JD-Core Version: 0.6.2
*/
|
mmmsplay10/QuizUpWinner
|
quizup/o/ฯ.java
|
Java
|
apache-2.0
| 2,925 |
<?php
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* This layout outputs events in a JSON-encoded GELF format.
*
* This class was originally contributed by Dmitry Ulyanov.
*
* ## Configurable parameters: ##
*
* - **host** - Server on which logs are collected.
* - **shortMessageLength** - Maximum length of short message.
* - **locationInfo** - If set to true, adds the file name and line number at
* which the log statement originated. Slightly slower, defaults to false.
*
* @package log4php
* @subpackage layouts
* @since 2.4.0
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0
* @link http://logging.apache.org/log4php/docs/layouts/html.html Layout documentation
* @link http://github.com/d-ulyanov/log4php-graylog2 Dmitry Ulyanov's original submission.
* @link http://graylog2.org/about/gelf GELF documentation.
*/
class LoggerLayoutGelf extends LoggerLayout {
/**
* GELF log levels according to syslog priority
*/
const LEVEL_EMERGENCY = 0;
const LEVEL_ALERT = 1;
const LEVEL_CRITICAL = 2;
const LEVEL_ERROR = 3;
const LEVEL_WARNING = 4;
const LEVEL_NOTICE = 5;
const LEVEL_INFO = 6;
const LEVEL_DEBUG = 7;
/**
* Version of Graylog2 GELF protocol (1.1 since 11/2013)
*/
const GELF_PROTOCOL_VERSION = '1.1';
/**
* Whether to log location information (file and line number).
* @var boolean
*/
protected $locationInfo = false;
/**
* Maximum length of short message
* @var int
*/
protected $shortMessageLength = 255;
/**
* Server on which logs are collected
* @var string
*/
protected $host;
/**
* Maps log4php levels to equivalent Gelf levels
* @var array
*/
protected $levelMap = array(
LoggerLevel::TRACE => self::LEVEL_DEBUG,
LoggerLevel::DEBUG => self::LEVEL_DEBUG,
LoggerLevel::INFO => self::LEVEL_INFO,
LoggerLevel::WARN => self::LEVEL_WARNING,
LoggerLevel::ERROR => self::LEVEL_ERROR,
LoggerLevel::FATAL => self::LEVEL_CRITICAL,
);
public function activateOptions() {
if (!$this->getHost()) {
$this->setHost(gethostname());
}
return parent::activateOptions();
}
/**
* @param LoggerLoggingEvent $event
* @return string
*/
public function format(LoggerLoggingEvent $event) {
$messageAsArray = array(
// Basic fields
'version' => self::GELF_PROTOCOL_VERSION,
'host' => $this->getHost(),
'short_message' => $this->getShortMessage($event),
'full_message' => $this->getFullMessage($event),
'timestamp' => $event->getTimeStamp(),
'level' => $this->getGelfLevel($event->getLevel()),
// Additional fields
'_facility' => $event->getLoggerName(),
'_thread' => $event->getThreadName(),
);
if ($this->getLocationInfo()) {
$messageAsArray += $this->getEventLocationFields($event);
}
$messageAsArray += $this->getEventMDCFields($event);
return json_encode($messageAsArray);
}
/**
* Returns event location information as array
* @param LoggerLoggingEvent $event
* @return array
*/
public function getEventLocationFields(LoggerLoggingEvent $event) {
$locInfo = $event->getLocationInformation();
return array(
'_file' => $locInfo->getFileName(),
'_line' => $locInfo->getLineNumber(),
'_class' => $locInfo->getClassName(),
'_method' => $locInfo->getMethodName()
);
}
/**
* Returns event MDC data as array
* @param LoggerLoggingEvent $event
* @return array
*/
public function getEventMDCFields(LoggerLoggingEvent $event) {
$fields = array();
foreach ($event->getMDCMap() as $key => $value) {
$fieldName = "_".$key;
if ($this->isAdditionalFieldNameValid($fieldName)) {
$fields[$fieldName] = $value;
}
}
return $fields;
}
/**
* Checks is field name valid according to Gelf specification
* @param string $fieldName
* @return bool
*/
public function isAdditionalFieldNameValid($fieldName) {
return (preg_match("@^_[\w\.\-]*$@", $fieldName) AND $fieldName != '_id');
}
/**
* Sets the 'locationInfo' parameter.
* @param boolean $locationInfo
*/
public function setLocationInfo($locationInfo) {
$this->setBoolean('locationInfo', $locationInfo);
}
/**
* Returns the value of the 'locationInfo' parameter.
* @return boolean
*/
public function getLocationInfo() {
return $this->locationInfo;
}
/**
* @param LoggerLoggingEvent $event
* @return string
*/
public function getShortMessage(LoggerLoggingEvent $event) {
$shortMessage = mb_substr($event->getRenderedMessage(), 0, $this->getShortMessageLength());
return $this->cleanNonUtfSymbols($shortMessage);
}
/**
* @param LoggerLoggingEvent $event
* @return string
*/
public function getFullMessage(LoggerLoggingEvent $event) {
return $this->cleanNonUtfSymbols(
$event->getRenderedMessage()
);
}
/**
* @param LoggerLevel $level
* @return int
*/
public function getGelfLevel(LoggerLevel $level) {
$int = $level->toInt();
if (isset($this->levelMap[$int])) {
return $this->levelMap[$int];
} else {
return self::LEVEL_ALERT;
}
}
/**
* @param int $shortMessageLength
*/
public function setShortMessageLength($shortMessageLength) {
$this->setPositiveInteger('shortMessageLength', $shortMessageLength);
}
/**
* @return int
*/
public function getShortMessageLength() {
return $this->shortMessageLength;
}
/**
* @param string $host
*/
public function setHost($host) {
$this->setString('host', $host);
}
/**
* @return string
*/
public function getHost() {
return $this->host;
}
/**
* @param string $message
* @return string
*/
protected function cleanNonUtfSymbols($message) {
/**
* Reject overly long 2 byte sequences, as well as characters
* above U+10000 and replace with ?
*/
$message = preg_replace(
'/[\x00-\x08\x10\x0B\x0C\x0E-\x19\x7F]'.
'|[\x00-\x7F][\x80-\xBF]+'.
'|([\xC0\xC1]|[\xF0-\xFF])[\x80-\xBF]*'.
'|[\xC2-\xDF]((?![\x80-\xBF])|[\x80-\xBF]{2,})'.
'|[\xE0-\xEF](([\x80-\xBF](?![\x80-\xBF]))|(?![\x80-\xBF]{2})|[\x80-\xBF]{3,})/S',
'?',
$message
);
/**
* Reject overly long 3 byte sequences and UTF-16 surrogates
* and replace with ?
*/
$message = preg_replace(
'/\xE0[\x80-\x9F][\x80-\xBF]'.
'|\xED[\xA0-\xBF][\x80-\xBF]/S',
'?',
$message
);
return $message;
}
}
|
d-ulyanov/log4php-graylog2
|
src/main/php/layouts/LoggerLayoutGelf.php
|
PHP
|
apache-2.0
| 8,053 |
<?php
namespace MonologCreator\Processor;
/**
* Class ExtraFieldProcessor
*
* Allows adding additional high-level or special fields to the log output.
*
* @package MonologCreator\Processor
* @author Sebastian Götze <s.goetze@bigpoint.net>
*/
class ExtraFieldProcessor implements \Monolog\Processor\ProcessorInterface
{
/**
* Array to hold additional fields
*
* @var array
*/
private $extraFields = array();
public function __construct(array $extraFields = array())
{
$this->extraFields = $extraFields;
}
/**
* Invoke processor
*
* Adds fields to record before returning it.
*
* @param array $record
* @return array
*/
public function __invoke(array $record)
{
if (false === \is_array($record['extra'])) {
$record['extra'] = array();
}
// Add fields to record
$record['extra'] = \array_merge($record['extra'], $this->extraFields);
return $record;
}
}
|
Bigpoint/monolog-creator
|
src/MonologCreator/Processor/ExtraFieldProcessor.php
|
PHP
|
apache-2.0
| 1,014 |
#include "common/router/upstream_request.h"
#include <chrono>
#include <cstdint>
#include <functional>
#include <memory>
#include <string>
#include "envoy/event/dispatcher.h"
#include "envoy/event/timer.h"
#include "envoy/grpc/status.h"
#include "envoy/http/conn_pool.h"
#include "envoy/runtime/runtime.h"
#include "envoy/upstream/cluster_manager.h"
#include "envoy/upstream/upstream.h"
#include "common/common/assert.h"
#include "common/common/empty_string.h"
#include "common/common/enum_to_int.h"
#include "common/common/scope_tracker.h"
#include "common/common/utility.h"
#include "common/grpc/common.h"
#include "common/http/codes.h"
#include "common/http/header_map_impl.h"
#include "common/http/headers.h"
#include "common/http/message_impl.h"
#include "common/http/utility.h"
#include "common/network/application_protocol.h"
#include "common/network/transport_socket_options_impl.h"
#include "common/network/upstream_server_name.h"
#include "common/network/upstream_subject_alt_names.h"
#include "common/router/config_impl.h"
#include "common/router/debug_config.h"
#include "common/router/router.h"
#include "common/stream_info/uint32_accessor_impl.h"
#include "common/tracing/http_tracer_impl.h"
#include "extensions/common/proxy_protocol/proxy_protocol_header.h"
#include "extensions/filters/http/well_known_names.h"
namespace Envoy {
namespace Router {
UpstreamRequest::UpstreamRequest(RouterFilterInterface& parent,
std::unique_ptr<GenericConnPool>&& conn_pool)
: parent_(parent), conn_pool_(std::move(conn_pool)), grpc_rq_success_deferred_(false),
stream_info_(parent_.callbacks()->dispatcher().timeSource()),
start_time_(parent_.callbacks()->dispatcher().timeSource().monotonicTime()),
calling_encode_headers_(false), upstream_canary_(false), decode_complete_(false),
encode_complete_(false), encode_trailers_(false), retried_(false), awaiting_headers_(true),
outlier_detection_timeout_recorded_(false),
create_per_try_timeout_on_request_complete_(false), paused_for_connect_(false),
record_timeout_budget_(parent_.cluster()->timeoutBudgetStats().has_value()) {
if (parent_.config().start_child_span_) {
span_ = parent_.callbacks()->activeSpan().spawnChild(
parent_.callbacks()->tracingConfig(), "router " + parent.cluster()->name() + " egress",
parent.timeSource().systemTime());
if (parent.attemptCount() != 1) {
// This is a retry request, add this metadata to span.
span_->setTag(Tracing::Tags::get().RetryCount, std::to_string(parent.attemptCount() - 1));
}
}
stream_info_.healthCheck(parent_.callbacks()->streamInfo().healthCheck());
if (conn_pool_->protocol().has_value()) {
stream_info_.protocol(conn_pool_->protocol().value());
}
}
UpstreamRequest::~UpstreamRequest() {
if (span_ != nullptr) {
Tracing::HttpTracerUtility::finalizeUpstreamSpan(*span_, upstream_headers_.get(),
upstream_trailers_.get(), stream_info_,
Tracing::EgressConfig::get());
}
if (per_try_timeout_ != nullptr) {
// Allows for testing.
per_try_timeout_->disableTimer();
}
if (max_stream_duration_timer_ != nullptr) {
max_stream_duration_timer_->disableTimer();
}
clearRequestEncoder();
// If desired, fire the per-try histogram when the UpstreamRequest
// completes.
if (record_timeout_budget_) {
Event::Dispatcher& dispatcher = parent_.callbacks()->dispatcher();
const MonotonicTime end_time = dispatcher.timeSource().monotonicTime();
const std::chrono::milliseconds response_time =
std::chrono::duration_cast<std::chrono::milliseconds>(end_time - start_time_);
Upstream::ClusterTimeoutBudgetStatsOptRef tb_stats = parent_.cluster()->timeoutBudgetStats();
tb_stats->get().upstream_rq_timeout_budget_per_try_percent_used_.recordValue(
FilterUtility::percentageOfTimeout(response_time, parent_.timeout().per_try_timeout_));
}
stream_info_.setUpstreamTiming(upstream_timing_);
stream_info_.onRequestComplete();
for (const auto& upstream_log : parent_.config().upstream_logs_) {
upstream_log->log(parent_.downstreamHeaders(), upstream_headers_.get(),
upstream_trailers_.get(), stream_info_);
}
while (downstream_data_disabled_ != 0) {
parent_.callbacks()->onDecoderFilterBelowWriteBufferLowWatermark();
parent_.cluster()->stats().upstream_flow_control_drained_total_.inc();
--downstream_data_disabled_;
}
}
void UpstreamRequest::decode100ContinueHeaders(Http::ResponseHeaderMapPtr&& headers) {
ScopeTrackerScopeState scope(&parent_.callbacks()->scope(), parent_.callbacks()->dispatcher());
ASSERT(100 == Http::Utility::getResponseStatus(*headers));
parent_.onUpstream100ContinueHeaders(std::move(headers), *this);
}
void UpstreamRequest::decodeHeaders(Http::ResponseHeaderMapPtr&& headers, bool end_stream) {
ScopeTrackerScopeState scope(&parent_.callbacks()->scope(), parent_.callbacks()->dispatcher());
// We drop 1xx other than 101 on the floor; 101 upgrade headers need to be passed to the client as
// part of the final response. 100-continue headers are handled in onUpstream100ContinueHeaders.
//
// We could in principle handle other headers here, but this might result in the double invocation
// of decodeHeaders() (once for informational, again for non-informational), which is likely an
// easy to miss corner case in the filter and HCM contract.
//
// This filtering is done early in upstream request, unlike 100 coalescing which is performed in
// the router filter, since the filtering only depends on the state of a single upstream, and we
// don't want to confuse accounting such as onFirstUpstreamRxByteReceived() with informational
// headers.
const uint64_t response_code = Http::Utility::getResponseStatus(*headers);
if (Http::CodeUtility::is1xx(response_code) &&
response_code != enumToInt(Http::Code::SwitchingProtocols)) {
return;
}
// TODO(rodaine): This is actually measuring after the headers are parsed and not the first
// byte.
upstream_timing_.onFirstUpstreamRxByteReceived(parent_.callbacks()->dispatcher().timeSource());
maybeEndDecode(end_stream);
awaiting_headers_ = false;
if (!parent_.config().upstream_logs_.empty()) {
upstream_headers_ = Http::createHeaderMap<Http::ResponseHeaderMapImpl>(*headers);
}
stream_info_.response_code_ = static_cast<uint32_t>(response_code);
if (paused_for_connect_ && response_code == 200) {
encodeBodyAndTrailers();
paused_for_connect_ = false;
}
parent_.onUpstreamHeaders(response_code, std::move(headers), *this, end_stream);
}
void UpstreamRequest::decodeData(Buffer::Instance& data, bool end_stream) {
ScopeTrackerScopeState scope(&parent_.callbacks()->scope(), parent_.callbacks()->dispatcher());
maybeEndDecode(end_stream);
stream_info_.addBytesReceived(data.length());
parent_.onUpstreamData(data, *this, end_stream);
}
void UpstreamRequest::decodeTrailers(Http::ResponseTrailerMapPtr&& trailers) {
ScopeTrackerScopeState scope(&parent_.callbacks()->scope(), parent_.callbacks()->dispatcher());
maybeEndDecode(true);
if (!parent_.config().upstream_logs_.empty()) {
upstream_trailers_ = Http::createHeaderMap<Http::ResponseTrailerMapImpl>(*trailers);
}
parent_.onUpstreamTrailers(std::move(trailers), *this);
}
const RouteEntry& UpstreamRequest::routeEntry() const { return *parent_.routeEntry(); }
const Network::Connection& UpstreamRequest::connection() const {
return *parent_.callbacks()->connection();
}
void UpstreamRequest::decodeMetadata(Http::MetadataMapPtr&& metadata_map) {
parent_.onUpstreamMetadata(std::move(metadata_map));
}
void UpstreamRequest::maybeEndDecode(bool end_stream) {
if (end_stream) {
upstream_timing_.onLastUpstreamRxByteReceived(parent_.callbacks()->dispatcher().timeSource());
decode_complete_ = true;
}
}
void UpstreamRequest::onUpstreamHostSelected(Upstream::HostDescriptionConstSharedPtr host) {
stream_info_.onUpstreamHostSelected(host);
upstream_host_ = host;
parent_.callbacks()->streamInfo().onUpstreamHostSelected(host);
parent_.onUpstreamHostSelected(host);
}
void UpstreamRequest::encodeHeaders(bool end_stream) {
ASSERT(!encode_complete_);
encode_complete_ = end_stream;
conn_pool_->newStream(this);
}
void UpstreamRequest::encodeData(Buffer::Instance& data, bool end_stream) {
ASSERT(!encode_complete_);
encode_complete_ = end_stream;
if (!upstream_ || paused_for_connect_) {
ENVOY_STREAM_LOG(trace, "buffering {} bytes", *parent_.callbacks(), data.length());
if (!buffered_request_body_) {
buffered_request_body_ = std::make_unique<Buffer::WatermarkBuffer>(
[this]() -> void { this->enableDataFromDownstreamForFlowControl(); },
[this]() -> void { this->disableDataFromDownstreamForFlowControl(); },
[]() -> void { /* TODO(adisuissa): Handle overflow watermark */ });
buffered_request_body_->setWatermarks(parent_.callbacks()->decoderBufferLimit());
}
buffered_request_body_->move(data);
} else {
ASSERT(downstream_metadata_map_vector_.empty());
ENVOY_STREAM_LOG(trace, "proxying {} bytes", *parent_.callbacks(), data.length());
stream_info_.addBytesSent(data.length());
upstream_->encodeData(data, end_stream);
if (end_stream) {
upstream_timing_.onLastUpstreamTxByteSent(parent_.callbacks()->dispatcher().timeSource());
}
}
}
void UpstreamRequest::encodeTrailers(const Http::RequestTrailerMap& trailers) {
ASSERT(!encode_complete_);
encode_complete_ = true;
encode_trailers_ = true;
if (!upstream_) {
ENVOY_STREAM_LOG(trace, "buffering trailers", *parent_.callbacks());
} else {
ASSERT(downstream_metadata_map_vector_.empty());
ENVOY_STREAM_LOG(trace, "proxying trailers", *parent_.callbacks());
upstream_->encodeTrailers(trailers);
upstream_timing_.onLastUpstreamTxByteSent(parent_.callbacks()->dispatcher().timeSource());
}
}
void UpstreamRequest::encodeMetadata(Http::MetadataMapPtr&& metadata_map_ptr) {
if (!upstream_) {
ENVOY_STREAM_LOG(trace, "upstream_ not ready. Store metadata_map to encode later: {}",
*parent_.callbacks(), *metadata_map_ptr);
downstream_metadata_map_vector_.emplace_back(std::move(metadata_map_ptr));
} else {
ENVOY_STREAM_LOG(trace, "Encode metadata: {}", *parent_.callbacks(), *metadata_map_ptr);
Http::MetadataMapVector metadata_map_vector;
metadata_map_vector.emplace_back(std::move(metadata_map_ptr));
upstream_->encodeMetadata(metadata_map_vector);
}
}
void UpstreamRequest::onResetStream(Http::StreamResetReason reason,
absl::string_view transport_failure_reason) {
ScopeTrackerScopeState scope(&parent_.callbacks()->scope(), parent_.callbacks()->dispatcher());
if (span_ != nullptr) {
// Add tags about reset.
span_->setTag(Tracing::Tags::get().Error, Tracing::Tags::get().True);
span_->setTag(Tracing::Tags::get().ErrorReason, Http::Utility::resetReasonToString(reason));
}
clearRequestEncoder();
awaiting_headers_ = false;
if (!calling_encode_headers_) {
stream_info_.setResponseFlag(Filter::streamResetReasonToResponseFlag(reason));
parent_.onUpstreamReset(reason, transport_failure_reason, *this);
} else {
deferred_reset_reason_ = reason;
}
}
void UpstreamRequest::resetStream() {
// Don't reset the stream if we're already done with it.
if (encode_complete_ && decode_complete_) {
return;
}
if (span_ != nullptr) {
// Add tags about the cancellation.
span_->setTag(Tracing::Tags::get().Canceled, Tracing::Tags::get().True);
}
if (conn_pool_->cancelAnyPendingStream()) {
ENVOY_STREAM_LOG(debug, "canceled pool request", *parent_.callbacks());
ASSERT(!upstream_);
}
if (upstream_) {
ENVOY_STREAM_LOG(debug, "resetting pool request", *parent_.callbacks());
upstream_->resetStream();
clearRequestEncoder();
}
}
void UpstreamRequest::setupPerTryTimeout() {
ASSERT(!per_try_timeout_);
if (parent_.timeout().per_try_timeout_.count() > 0) {
per_try_timeout_ =
parent_.callbacks()->dispatcher().createTimer([this]() -> void { onPerTryTimeout(); });
per_try_timeout_->enableTimer(parent_.timeout().per_try_timeout_);
}
}
void UpstreamRequest::onPerTryTimeout() {
// If we've sent anything downstream, ignore the per try timeout and let the response continue
// up to the global timeout
if (!parent_.downstreamResponseStarted()) {
ENVOY_STREAM_LOG(debug, "upstream per try timeout", *parent_.callbacks());
stream_info_.setResponseFlag(StreamInfo::ResponseFlag::UpstreamRequestTimeout);
parent_.onPerTryTimeout(*this);
} else {
ENVOY_STREAM_LOG(debug,
"ignored upstream per try timeout due to already started downstream response",
*parent_.callbacks());
}
}
void UpstreamRequest::onPoolFailure(ConnectionPool::PoolFailureReason reason,
absl::string_view transport_failure_reason,
Upstream::HostDescriptionConstSharedPtr host) {
Http::StreamResetReason reset_reason = Http::StreamResetReason::ConnectionFailure;
switch (reason) {
case ConnectionPool::PoolFailureReason::Overflow:
reset_reason = Http::StreamResetReason::Overflow;
break;
case ConnectionPool::PoolFailureReason::RemoteConnectionFailure:
FALLTHRU;
case ConnectionPool::PoolFailureReason::LocalConnectionFailure:
reset_reason = Http::StreamResetReason::ConnectionFailure;
break;
case ConnectionPool::PoolFailureReason::Timeout:
reset_reason = Http::StreamResetReason::LocalReset;
}
// Mimic an upstream reset.
onUpstreamHostSelected(host);
onResetStream(reset_reason, transport_failure_reason);
}
void UpstreamRequest::onPoolReady(
std::unique_ptr<GenericUpstream>&& upstream, Upstream::HostDescriptionConstSharedPtr host,
const Network::Address::InstanceConstSharedPtr& upstream_local_address,
const StreamInfo::StreamInfo& info) {
// This may be called under an existing ScopeTrackerScopeState but it will unwind correctly.
ScopeTrackerScopeState scope(&parent_.callbacks()->scope(), parent_.callbacks()->dispatcher());
ENVOY_STREAM_LOG(debug, "pool ready", *parent_.callbacks());
upstream_ = std::move(upstream);
if (parent_.requestVcluster()) {
// The cluster increases its upstream_rq_total_ counter right before firing this onPoolReady
// callback. Hence, the upstream request increases the virtual cluster's upstream_rq_total_ stat
// here.
parent_.requestVcluster()->stats().upstream_rq_total_.inc();
}
host->outlierDetector().putResult(Upstream::Outlier::Result::LocalOriginConnectSuccess);
onUpstreamHostSelected(host);
stream_info_.setUpstreamFilterState(std::make_shared<StreamInfo::FilterStateImpl>(
info.filterState().parent()->parent(), StreamInfo::FilterState::LifeSpan::Request));
stream_info_.setUpstreamLocalAddress(upstream_local_address);
parent_.callbacks()->streamInfo().setUpstreamLocalAddress(upstream_local_address);
stream_info_.setUpstreamSslConnection(info.downstreamSslConnection());
parent_.callbacks()->streamInfo().setUpstreamSslConnection(info.downstreamSslConnection());
if (parent_.downstreamEndStream()) {
setupPerTryTimeout();
} else {
create_per_try_timeout_on_request_complete_ = true;
}
// Make sure the connection manager will inform the downstream watermark manager when the
// downstream buffers are overrun. This may result in immediate watermark callbacks referencing
// the encoder.
parent_.callbacks()->addDownstreamWatermarkCallbacks(downstream_watermark_manager_);
calling_encode_headers_ = true;
auto* headers = parent_.downstreamHeaders();
if (parent_.routeEntry()->autoHostRewrite() && !host->hostname().empty()) {
parent_.downstreamHeaders()->setHost(host->hostname());
}
if (span_ != nullptr) {
span_->injectContext(*parent_.downstreamHeaders());
}
upstream_timing_.onFirstUpstreamTxByteSent(parent_.callbacks()->dispatcher().timeSource());
// Make sure that when we are forwarding CONNECT payload we do not do so until
// the upstream has accepted the CONNECT request.
if (conn_pool_->protocol().has_value() &&
headers->getMethodValue() == Http::Headers::get().MethodValues.Connect) {
paused_for_connect_ = true;
}
if (upstream_host_->cluster().commonHttpProtocolOptions().has_max_stream_duration()) {
const auto max_stream_duration = std::chrono::milliseconds(DurationUtil::durationToMilliseconds(
upstream_host_->cluster().commonHttpProtocolOptions().max_stream_duration()));
if (max_stream_duration.count()) {
max_stream_duration_timer_ = parent_.callbacks()->dispatcher().createTimer(
[this]() -> void { onStreamMaxDurationReached(); });
max_stream_duration_timer_->enableTimer(max_stream_duration);
}
}
upstream_->encodeHeaders(*parent_.downstreamHeaders(), shouldSendEndStream());
calling_encode_headers_ = false;
if (!paused_for_connect_) {
encodeBodyAndTrailers();
}
}
void UpstreamRequest::encodeBodyAndTrailers() {
// It is possible to get reset in the middle of an encodeHeaders() call. This happens for
// example in the HTTP/2 codec if the frame cannot be encoded for some reason. This should never
// happen but it's unclear if we have covered all cases so protect against it and test for it.
// One specific example of a case where this happens is if we try to encode a total header size
// that is too big in HTTP/2 (64K currently).
if (deferred_reset_reason_) {
onResetStream(deferred_reset_reason_.value(), absl::string_view());
} else {
// Encode metadata after headers and before any other frame type.
if (!downstream_metadata_map_vector_.empty()) {
ENVOY_STREAM_LOG(debug, "Send metadata onPoolReady. {}", *parent_.callbacks(),
downstream_metadata_map_vector_);
upstream_->encodeMetadata(downstream_metadata_map_vector_);
downstream_metadata_map_vector_.clear();
if (shouldSendEndStream()) {
Buffer::OwnedImpl empty_data("");
upstream_->encodeData(empty_data, true);
}
}
if (buffered_request_body_) {
stream_info_.addBytesSent(buffered_request_body_->length());
upstream_->encodeData(*buffered_request_body_, encode_complete_ && !encode_trailers_);
}
if (encode_trailers_) {
upstream_->encodeTrailers(*parent_.downstreamTrailers());
}
if (encode_complete_) {
upstream_timing_.onLastUpstreamTxByteSent(parent_.callbacks()->dispatcher().timeSource());
}
}
}
void UpstreamRequest::onStreamMaxDurationReached() {
upstream_host_->cluster().stats().upstream_rq_max_duration_reached_.inc();
// The upstream had closed then try to retry along with retry policy.
parent_.onStreamMaxDurationReached(*this);
}
void UpstreamRequest::clearRequestEncoder() {
// Before clearing the encoder, unsubscribe from callbacks.
if (upstream_) {
parent_.callbacks()->removeDownstreamWatermarkCallbacks(downstream_watermark_manager_);
}
upstream_.reset();
}
void UpstreamRequest::DownstreamWatermarkManager::onAboveWriteBufferHighWatermark() {
ASSERT(parent_.upstream_);
// There are two states we should get this callback in: 1) the watermark was
// hit due to writes from a different filter instance over a shared
// downstream connection, or 2) the watermark was hit due to THIS filter
// instance writing back the "winning" upstream request. In either case we
// can disable reads from upstream.
ASSERT(!parent_.parent_.finalUpstreamRequest() ||
&parent_ == parent_.parent_.finalUpstreamRequest());
// The downstream connection is overrun. Pause reads from upstream.
// If there are multiple calls to readDisable either the codec (H2) or the underlying
// Network::Connection (H1) will handle reference counting.
parent_.parent_.cluster()->stats().upstream_flow_control_paused_reading_total_.inc();
parent_.upstream_->readDisable(true);
}
void UpstreamRequest::DownstreamWatermarkManager::onBelowWriteBufferLowWatermark() {
ASSERT(parent_.upstream_);
// One source of connection blockage has buffer available. Pass this on to the stream, which
// will resume reads if this was the last remaining high watermark.
parent_.parent_.cluster()->stats().upstream_flow_control_resumed_reading_total_.inc();
parent_.upstream_->readDisable(false);
}
void UpstreamRequest::disableDataFromDownstreamForFlowControl() {
// If there is only one upstream request, we can be assured that
// disabling reads will not slow down other upstream requests. If we've
// already seen the full downstream request (downstream_end_stream_) then
// disabling reads is a noop.
// This assert condition must be true because
// parent_.upstreamRequests().size() can only be greater than 1 in the
// case of a per-try-timeout with hedge_on_per_try_timeout enabled, and
// the per try timeout timer is started only after downstream_end_stream_
// is true.
ASSERT(parent_.upstreamRequests().size() == 1 || parent_.downstreamEndStream());
parent_.cluster()->stats().upstream_flow_control_backed_up_total_.inc();
parent_.callbacks()->onDecoderFilterAboveWriteBufferHighWatermark();
++downstream_data_disabled_;
}
void UpstreamRequest::enableDataFromDownstreamForFlowControl() {
// If there is only one upstream request, we can be assured that
// disabling reads will not overflow any write buffers in other upstream
// requests. If we've already seen the full downstream request
// (downstream_end_stream_) then enabling reads is a noop.
// This assert condition must be true because
// parent_.upstreamRequests().size() can only be greater than 1 in the
// case of a per-try-timeout with hedge_on_per_try_timeout enabled, and
// the per try timeout timer is started only after downstream_end_stream_
// is true.
ASSERT(parent_.upstreamRequests().size() == 1 || parent_.downstreamEndStream());
parent_.cluster()->stats().upstream_flow_control_drained_total_.inc();
parent_.callbacks()->onDecoderFilterBelowWriteBufferLowWatermark();
ASSERT(downstream_data_disabled_ != 0);
if (downstream_data_disabled_ > 0) {
--downstream_data_disabled_;
}
}
} // namespace Router
} // namespace Envoy
|
envoyproxy/envoy-wasm
|
source/common/router/upstream_request.cc
|
C++
|
apache-2.0
| 22,548 |
package com.planet_ink.coffee_mud.Abilities.Spells;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;
import java.util.*;
/*
Copyright 2001-2022 Bo Zimmerman
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.
*/
public class Spell_Erase extends Spell
{
@Override
public String ID()
{
return "Spell_Erase";
}
private final static String localizedName = CMLib.lang().L("Erase Scroll");
@Override
public String name()
{
return localizedName;
}
@Override
protected int canTargetCode()
{
return CAN_ITEMS;
}
@Override
public int classificationCode()
{
return Ability.ACODE_SPELL|Ability.DOMAIN_ALTERATION;
}
@Override
public int abstractQuality()
{
return Ability.QUALITY_INDIFFERENT;
}
@Override
public boolean invoke(final MOB mob, final List<String> commands, final Physical givenTarget, final boolean auto, final int asLevel)
{
if((commands.size()<1)&&(givenTarget==null))
{
mob.tell(L("Erase what?."));
return false;
}
final Item target=getTarget(mob,mob.location(),givenTarget,commands,Wearable.FILTER_ANY);
if(target==null)
return false;
if(!(target instanceof Scroll)&&(!target.isReadable()))
{
mob.tell(L("You can't erase that."));
return false;
}
if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
return false;
final boolean success=proficiencyCheck(mob,0,auto);
if(success)
{
final CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto),auto?L("The words on <T-NAME> fade."):L("^S<S-NAME> whisper(s), and then rub(s) on <T-NAMESELF>, making the words fade.^?"));
if(mob.location().okMessage(mob,msg))
{
mob.location().send(mob,msg);
if(target instanceof Scroll)
((Scroll)target).setSpellList("");
else
target.setReadableText("");
}
}
else
beneficialWordsFizzle(mob,target,L("<S-NAME> whisper(s), and then rub(s) on <T-NAMESELF>, but nothing happens."));
// return whether it worked
return success;
}
}
|
bozimmerman/CoffeeMud
|
com/planet_ink/coffee_mud/Abilities/Spells/Spell_Erase.java
|
Java
|
apache-2.0
| 3,338 |
/*******************************************************************************
* Copyright 2020 Tremolo Security, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package com.tremolosecurity.unison.gitlab.provisioning.targets;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.http.Header;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import org.apache.logging.log4j.Logger;
import org.gitlab4j.api.GitLabApi;
import org.gitlab4j.api.GitLabApiException;
import org.gitlab4j.api.GroupApi;
import org.gitlab4j.api.UserApi;
import org.gitlab4j.api.models.AccessLevel;
import org.gitlab4j.api.models.Group;
import org.gitlab4j.api.models.Identity;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import com.tremolosecurity.config.util.ConfigManager;
import com.tremolosecurity.provisioning.core.ProvisioningException;
import com.tremolosecurity.provisioning.core.User;
import com.tremolosecurity.provisioning.core.UserStoreProviderWithAddGroup;
import com.tremolosecurity.provisioning.core.Workflow;
import com.tremolosecurity.provisioning.util.GenPasswd;
import com.tremolosecurity.provisioning.core.ProvisioningUtil.ActionType;
import com.tremolosecurity.saml.Attribute;
public class GitlabUserProvider implements UserStoreProviderWithAddGroup {
static Logger logger = org.apache.logging.log4j.LogManager.getLogger(GitlabUserProvider.class.getName());
ConfigManager cfgMgr;
String name;
String token;
String url;
GitLabApi gitLabApi;
UserApi userApi;
GroupApi groupApi;
BeanUtils beanUtils = new BeanUtils();
public static final String GITLAB_IDENTITIES = "com.tremolosecurity.unison.gitlab.itentities";
public static final String GITLAB_GROUP_ENTITLEMENTS = "com.tremolosecurity.unison.gitlab.group-entitlements";
@Override
public void createUser(User user, Set<String> attributes, Map<String, Object> request)
throws ProvisioningException {
int approvalID = 0;
if (request.containsKey("APPROVAL_ID")) {
approvalID = (Integer) request.get("APPROVAL_ID");
}
Workflow workflow = (Workflow) request.get("WORKFLOW");
org.gitlab4j.api.models.User newUser = new org.gitlab4j.api.models.User();
newUser.setUsername(user.getUserID());
for (String attrName : attributes) {
Attribute attr = user.getAttribs().get(attrName);
if (attr != null) {
try {
this.beanUtils.setProperty(newUser, attrName, attr.getValues().get(0));
} catch (IllegalAccessException | InvocationTargetException e) {
throw new ProvisioningException("Could not set " + attrName + " for " + user.getUserID(),e);
}
}
}
try {
this.userApi.createUser(newUser, new GenPasswd(50).getPassword(), false);
} catch (GitLabApiException e) {
throw new ProvisioningException("Could not create user",e);
}
newUser = this.findUserByName(user.getUserID());
int numTries = 0;
while (newUser == null) {
if (numTries > 10) {
throw new ProvisioningException("User " + user.getUserID() + " never created");
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
newUser = this.findUserByName(user.getUserID());
numTries++;
}
this.cfgMgr.getProvisioningEngine().logAction(this.name,true, ActionType.Add, approvalID, workflow, "id", newUser.getId().toString());
for (String attrName : attributes) {
Attribute attr = user.getAttribs().get(attrName);
if (attr != null) {
this.cfgMgr.getProvisioningEngine().logAction(this.name,false, ActionType.Add, approvalID, workflow, attrName, attr.getValues().get(0));
}
}
List<GitlabFedIdentity> ids = (List<GitlabFedIdentity>) request.get(GitlabUserProvider.GITLAB_IDENTITIES);
if (ids != null) {
ArrayList<Header> defheaders = new ArrayList<Header>();
defheaders.add(new BasicHeader("Private-Token", this.token));
BasicHttpClientConnectionManager bhcm = new BasicHttpClientConnectionManager(
cfgMgr.getHttpClientSocketRegistry());
RequestConfig rc = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).setRedirectsEnabled(false)
.build();
CloseableHttpClient http = HttpClients.custom()
.setConnectionManager(bhcm)
.setDefaultHeaders(defheaders)
.setDefaultRequestConfig(rc)
.build();
try {
for (GitlabFedIdentity id : ids) {
HttpPut getmembers = new HttpPut(new StringBuilder().append(this.url).append("/api/v4/users/").append(newUser.getId()).append("?provider=").append(id.getProvider()).append("&extern_uid=").append(URLEncoder.encode(user.getUserID(), "UTF-8")).toString());
CloseableHttpResponse resp = http.execute(getmembers);
if (resp.getStatusLine().getStatusCode() != 200) {
throw new IOException("Invalid response " + resp.getStatusLine().getStatusCode());
}
this.cfgMgr.getProvisioningEngine().logAction(this.name,false, ActionType.Add, approvalID, workflow, "identity-provider", id.getProvider());
this.cfgMgr.getProvisioningEngine().logAction(this.name,false, ActionType.Add, approvalID, workflow, "identity-externid", id.getExternalUid());
}
} catch (IOException e) {
throw new ProvisioningException("Could not set identity",e);
} finally {
try {
http.close();
} catch (IOException e) {
}
bhcm.close();
}
}
HashMap<String,Integer> groupmap = (HashMap<String, Integer>) request.get(GitlabUserProvider.GITLAB_GROUP_ENTITLEMENTS);
if (groupmap == null) {
groupmap = new HashMap<String, Integer>();
}
for (String group : user.getGroups()) {
try {
Group groupObj = this.findGroupByName(group);
if (groupObj == null) {
logger.warn("Group " + group + " does not exist");
} else {
int accessLevel = AccessLevel.DEVELOPER.ordinal();
if (groupmap.containsKey(group)) {
accessLevel = groupmap.get(group);
}
this.groupApi.addMember(groupObj.getId(), newUser.getId(), accessLevel);
this.cfgMgr.getProvisioningEngine().logAction(this.name,false, ActionType.Add, approvalID, workflow, "group", group);
}
} catch (GitLabApiException e) {
throw new ProvisioningException("Could not find group " + group,e);
}
}
}
@Override
public void setUserPassword(User user, Map<String, Object> request) throws ProvisioningException {
// TODO Auto-generated method stub
}
@Override
public void syncUser(User user, boolean addOnly, Set<String> attributes, Map<String, Object> request)
throws ProvisioningException {
List<GitlabFedIdentity> ids = (List<GitlabFedIdentity>) request.get(GitlabUserProvider.GITLAB_IDENTITIES);
int approvalID = 0;
if (request.containsKey("APPROVAL_ID")) {
approvalID = (Integer) request.get("APPROVAL_ID");
}
Workflow workflow = (Workflow) request.get("WORKFLOW");
User fromGitlab = this.findUser(user.getUserID(), attributes, request);
if (fromGitlab == null) {
this.createUser(user, attributes, request);
return;
}
List<GitlabFedIdentity> idsFromGitlab = (List<GitlabFedIdentity>) request.get(GitlabUserProvider.GITLAB_IDENTITIES);
HashMap<String,String> toSet = new HashMap<String,String>();
HashSet<String> toDelete = new HashSet<String>();
for (String attrName : attributes) {
Attribute attrFromGitlab = fromGitlab.getAttribs().get(attrName);
Attribute attrIn = user.getAttribs().get(attrName);
if ((attrIn != null && attrFromGitlab == null) || (attrIn != null && attrFromGitlab != null && ! attrIn.getValues().get(0).equals(attrFromGitlab.getValues().get(0)))) {
toSet.put(attrName,attrIn.getValues().get(0));
} else if (! addOnly) {
if (attrIn == null && attrFromGitlab != null) {
toDelete.add(attrName);
}
}
}
org.gitlab4j.api.models.User toSave = this.findUserByName(user.getUserID());
for (String attrName : toSet.keySet()) {
try {
this.beanUtils.setProperty(toSave, attrName, toSet.get(attrName));
} catch (IllegalAccessException | InvocationTargetException e) {
throw new ProvisioningException("Could not update user " + user.getUserID(),e);
}
}
for (String attrName : toDelete) {
try {
this.beanUtils.setProperty(toSave, attrName, "");
} catch (IllegalAccessException | InvocationTargetException e) {
throw new ProvisioningException("Could not update user " + user.getUserID(),e);
}
}
if (ids != null) {
ArrayList<Header> defheaders = new ArrayList<Header>();
defheaders.add(new BasicHeader("Private-Token", this.token));
BasicHttpClientConnectionManager bhcm = new BasicHttpClientConnectionManager(
cfgMgr.getHttpClientSocketRegistry());
RequestConfig rc = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).setRedirectsEnabled(false)
.build();
CloseableHttpClient http = HttpClients.custom()
.setConnectionManager(bhcm)
.setDefaultHeaders(defheaders)
.setDefaultRequestConfig(rc)
.build();
try {
for (GitlabFedIdentity id : ids) {
boolean found = false;
for (GitlabFedIdentity idfromgl : idsFromGitlab) {
if (id.getExternalUid().equals(idfromgl.getExternalUid()) && id.getProvider().equals(idfromgl.getProvider()) ) {
found = true;
break;
}
}
if (! found) {
HttpPut getmembers = new HttpPut(new StringBuilder().append(this.url).append("/api/v4/users/").append(toSave.getId()).append("?provider=").append(id.getProvider()).append("&extern_uid=").append(URLEncoder.encode(user.getUserID(), "UTF-8")).toString());
CloseableHttpResponse resp = http.execute(getmembers);
if (resp.getStatusLine().getStatusCode() != 200) {
throw new IOException("Invalid response " + resp.getStatusLine().getStatusCode());
}
this.cfgMgr.getProvisioningEngine().logAction(this.name,false, ActionType.Add, approvalID, workflow, "identity-provider", id.getProvider());
this.cfgMgr.getProvisioningEngine().logAction(this.name,false, ActionType.Add, approvalID, workflow, "identity-externid", id.getExternalUid());
}
}
} catch (IOException e) {
throw new ProvisioningException("Could not set identity",e);
} finally {
try {
http.close();
} catch (IOException e) {
}
bhcm.close();
}
}
try {
this.userApi.updateUser(toSave, null);
} catch (GitLabApiException e) {
throw new ProvisioningException("Could not save user " + user.getUserID(),e);
}
for (String attrName : toSet.keySet()) {
this.cfgMgr.getProvisioningEngine().logAction(this.name,false, ActionType.Replace, approvalID, workflow, attrName, toSet.get(attrName));
}
for (String attrName : toDelete) {
this.cfgMgr.getProvisioningEngine().logAction(this.name,false, ActionType.Replace, approvalID, workflow, attrName, "");
}
HashMap<String,Integer> groupmap = (HashMap<String, Integer>) request.get(GitlabUserProvider.GITLAB_GROUP_ENTITLEMENTS);
if (groupmap == null) {
groupmap = new HashMap<String, Integer>();
}
for (String inGroup : user.getGroups()) {
if (! fromGitlab.getGroups().contains(inGroup)) {
try {
Group groupObj = this.findGroupByName(inGroup);
if (groupObj == null) {
logger.warn("Group " + inGroup + " does not exist");
} else {
int accessLevel = AccessLevel.DEVELOPER.ordinal();
if (groupmap.containsKey(inGroup)) {
accessLevel = groupmap.get(inGroup);
}
this.groupApi.addMember(groupObj.getId(), toSave.getId(), accessLevel);
this.cfgMgr.getProvisioningEngine().logAction(this.name,false, ActionType.Add, approvalID, workflow, "group", inGroup);
}
} catch (GitLabApiException e) {
if (e.getMessage().equalsIgnoreCase("Member already exists")) {
continue;
} else {
throw new ProvisioningException("Could not find group " + inGroup,e);
}
}
}
}
if (! addOnly) {
for (String groupFromGitlab : fromGitlab.getGroups()) {
if (! user.getGroups().contains(groupFromGitlab)) {
try {
Group groupObj = this.findGroupByName(groupFromGitlab);
if (groupObj == null) {
logger.warn("Group " + groupFromGitlab + " does not exist");
} else {
this.groupApi.removeMember(groupObj.getId(), toSave.getId());
this.cfgMgr.getProvisioningEngine().logAction(this.name,false, ActionType.Delete, approvalID, workflow, "group", groupFromGitlab);
}
} catch (GitLabApiException e) {
throw new ProvisioningException("Could not find group " + groupFromGitlab);
}
}
}
}
}
@Override
public void deleteUser(User user, Map<String, Object> request) throws ProvisioningException {
int approvalID = 0;
if (request.containsKey("APPROVAL_ID")) {
approvalID = (Integer) request.get("APPROVAL_ID");
}
Workflow workflow = (Workflow) request.get("WORKFLOW");
org.gitlab4j.api.models.User fromGitlab = this.findUserByName(user.getUserID());
if (fromGitlab == null) {
return;
}
try {
this.userApi.deleteUser(fromGitlab.getId(),false);
} catch (GitLabApiException e) {
throw new ProvisioningException("Could not delete " + user.getUserID(),e);
}
this.cfgMgr.getProvisioningEngine().logAction(this.name,true, ActionType.Delete, approvalID, workflow, "id", fromGitlab.getId().toString());
}
@Override
public User findUser(String userID, Set<String> attributes, Map<String, Object> request)
throws ProvisioningException {
org.gitlab4j.api.models.User fromGitlab = findUserByName(userID);
if (fromGitlab == null) {
return null;
}
User forUnison = new User(userID);
for (String attrName : attributes) {
try {
String val = beanUtils.getProperty(fromGitlab, attrName);
if (val != null) {
Attribute attr = new Attribute(attrName,val);
forUnison.getAttribs().put(attrName, attr);
}
} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
throw new ProvisioningException("Couldn't load attribute " + attrName,e);
}
}
if (fromGitlab.getIdentities() != null) {
ArrayList<GitlabFedIdentity> ids = new ArrayList<GitlabFedIdentity>();
for (Identity fedid : fromGitlab.getIdentities()) {
GitlabFedIdentity id = new GitlabFedIdentity();
id.setExternalUid(fedid.getExternUid());
id.setProvider(fedid.getProvider());
ids.add(id);
}
request.put(GitlabUserProvider.GITLAB_IDENTITIES,ids);
}
ArrayList<Header> defheaders = new ArrayList<Header>();
defheaders.add(new BasicHeader("Private-Token", this.token));
BasicHttpClientConnectionManager bhcm = new BasicHttpClientConnectionManager(
cfgMgr.getHttpClientSocketRegistry());
RequestConfig rc = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).setRedirectsEnabled(false)
.build();
CloseableHttpClient http = HttpClients.custom()
.setConnectionManager(bhcm)
.setDefaultHeaders(defheaders)
.setDefaultRequestConfig(rc)
.build();
try {
HttpGet getmembers = new HttpGet(new StringBuilder().append(this.url).append("/api/v4/users/").append(fromGitlab.getId()).append("/memberships").toString());
CloseableHttpResponse resp = http.execute(getmembers);
if (resp.getStatusLine().getStatusCode() != 200) {
throw new IOException("Invalid response " + resp.getStatusLine().getStatusCode());
}
String json = EntityUtils.toString(resp.getEntity());
JSONArray members = (JSONArray) new JSONParser().parse(json);
for (Object o : members) {
JSONObject member = (JSONObject) o;
String sourceType = (String) member.get("source_type");
String sourceName = (String) member.get("source_name");
if (sourceType.equalsIgnoreCase("Namespace")) {
forUnison.getGroups().add(sourceName);
}
}
} catch (IOException | ParseException e) {
throw new ProvisioningException("Could not get group memebers",e);
} finally {
try {
http.close();
} catch (IOException e) {
}
bhcm.close();
}
return forUnison;
}
private org.gitlab4j.api.models.User findUserByName(String userID) throws ProvisioningException {
org.gitlab4j.api.models.User fromGitlab;
try {
List<org.gitlab4j.api.models.User> users = this.userApi.findUsers(userID);
if (users.size() == 0) {
return null;
} else if (users.size() > 1) {
int count = 0;
org.gitlab4j.api.models.User foundUser = null;
for (org.gitlab4j.api.models.User user : users) {
if (user.getUsername().equals(userID)) {
count++;
foundUser = user;
}
}
if (count > 1) {
throw new ProvisioningException(userID + " maps to multiple users");
} else if (count == 0) {
return null;
} else {
return foundUser;
}
} else {
fromGitlab = users.get(0);
}
} catch (GitLabApiException e) {
throw new ProvisioningException("Could not load user",e);
}
return fromGitlab;
}
@Override
public void init(Map<String, Attribute> cfg, ConfigManager cfgMgr, String name) throws ProvisioningException {
this.token = cfg.get("token").getValues().get(0);
this.url = cfg.get("url").getValues().get(0);
this.name = name;
this.gitLabApi = new GitLabApi(this.url, this.token);
this.userApi = new UserApi(this.gitLabApi);
this.groupApi = new GroupApi(this.gitLabApi);
this.cfgMgr = cfgMgr;
}
@Override
public void addGroup(String name, Map<String, String> additionalAttributes, User user, Map<String, Object> request)
throws ProvisioningException {
if (this.isGroupExists(name, null, request)) {
return;
}
int approvalID = 0;
if (request.containsKey("APPROVAL_ID")) {
approvalID = (Integer) request.get("APPROVAL_ID");
}
Workflow workflow = (Workflow) request.get("WORKFLOW");
Group groupToCreate = new Group();
groupToCreate.setName(name);
groupToCreate.setPath(name);
for (String prop : additionalAttributes.keySet()) {
try {
this.beanUtils.setProperty(groupToCreate, prop, additionalAttributes.get(prop));
} catch (IllegalAccessException | InvocationTargetException e) {
throw new ProvisioningException("Could not set properties",e);
}
}
try {
this.groupApi.addGroup(groupToCreate);
} catch (GitLabApiException e) {
throw new ProvisioningException("Could not create group " + name,e);
}
this.cfgMgr.getProvisioningEngine().logAction(this.name,true, ActionType.Add, approvalID, workflow, "group-object", name);
}
@Override
public void deleteGroup(String name, User user, Map<String, Object> request) throws ProvisioningException {
if (! this.isGroupExists(name, null, request)) {
return;
}
int approvalID = 0;
if (request.containsKey("APPROVAL_ID")) {
approvalID = (Integer) request.get("APPROVAL_ID");
}
Workflow workflow = (Workflow) request.get("WORKFLOW");
try {
this.groupApi.deleteGroup(name);
} catch (GitLabApiException e) {
throw new ProvisioningException("Could not delete group " + name,e);
}
this.cfgMgr.getProvisioningEngine().logAction(this.name,true, ActionType.Delete, approvalID, workflow, "group-object", name);
}
@Override
public boolean isGroupExists(String name, User user, Map<String, Object> request) throws ProvisioningException {
try {
Group group = this.findGroupByName(name);
return group != null;
} catch (GitLabApiException e) {
throw new ProvisioningException("Could not search for groups",e);
}
}
public Group findGroupByName(String name) throws GitLabApiException {
List<Group> groups = this.groupApi.getGroups(name);
for (Group group : groups) {
if (group.getName().equalsIgnoreCase(name)) {
return group;
}
}
return null;
}
public GitLabApi getApi() {
return this.gitLabApi;
}
public String getName() {
return this.name;
}
@Override
public void shutdown() throws ProvisioningException {
this.gitLabApi.close();
}
}
|
TremoloSecurity/OpenUnison
|
unison/unison-applications-gitlab/src/main/java/com/tremolosecurity/unison/gitlab/provisioning/targets/GitlabUserProvider.java
|
Java
|
apache-2.0
| 21,837 |
package com.github.gserv.serv.wx.message;
/**
* 消息解析异常
*
* @author shiying
*
*/
public class XmlMessageParseException extends RuntimeException {
/**
*
*/
private static final long serialVersionUID = 6648701329524322380L;
public XmlMessageParseException() {
super();
// TODO Auto-generated constructor stub
}
public XmlMessageParseException(String arg0, Throwable arg1) {
super(arg0, arg1);
// TODO Auto-generated constructor stub
}
public XmlMessageParseException(String arg0) {
super(arg0);
// TODO Auto-generated constructor stub
}
public XmlMessageParseException(Throwable arg0) {
super(arg0);
// TODO Auto-generated constructor stub
}
}
|
gserv/serv
|
serv-wx/src/main/java/com/github/gserv/serv/wx/message/XmlMessageParseException.java
|
Java
|
apache-2.0
| 700 |
/*
* Copyright (c) 2020 EmeraldPay Inc, All Rights Reserved.
* Copyright (c) 2016-2017 Infinitape 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.
*/
package io.emeraldpay.etherjar.abi;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class UFixedType extends DecimalType {
public final static UFixedType DEFAULT = new UFixedType();
final static Map<Integer, UFixedType> CACHED_INSTANCES =
Stream.of(8, 16, 32, 64, 128).collect(Collectors.collectingAndThen(
Collectors.toMap(Function.identity(), UFixedType::new), Collections::unmodifiableMap));
final static String NAME_PREFIX = "ufixed";
final static Pattern NAME_PATTERN = Pattern.compile("ufixed((\\d{1,3})x(\\d{1,3}))?");
/**
* Try to parse a {@link UFixedType} string representation (either canonical form or not).
*
* @param str a string
* @return a {@link UFixedType} instance is packed as {@link Optional} value,
* or {@link Optional#empty()} instead
* @throws NullPointerException if a {@code str} is {@code null}
* @throws IllegalArgumentException if a {@link IntType} has invalid input
* @see #getCanonicalName()
*/
public static Optional<UFixedType> from(String str) {
if (!str.startsWith(NAME_PREFIX))
return Optional.empty();
Matcher matcher = NAME_PATTERN.matcher(str);
if (!matcher.matches())
throw new IllegalArgumentException("Wrong 'ufixed' type format: " + str);
if (Objects.isNull(matcher.group(1)))
return Optional.of(DEFAULT);
int mBits = Integer.parseInt(matcher.group(2));
int nBits = Integer.parseInt(matcher.group(3));
return Optional.of(mBits == nBits && CACHED_INSTANCES.containsKey(mBits) ?
CACHED_INSTANCES.get(mBits) : new UFixedType(mBits, nBits));
}
private final BigDecimal minValue;
private final BigDecimal maxValue;
private final NumericType numericType;
public UFixedType() {
this(128, 128);
}
public UFixedType(int bits) {
this(bits, bits);
}
public UFixedType(int mBits, int nBits) {
super(mBits, nBits);
numericType = new UIntType(mBits + nBits);
minValue = new BigDecimal(
numericType.getMinValue().shiftRight(nBits));
maxValue = new BigDecimal(
numericType.getMaxValue().shiftRight(nBits));
}
@Override
public BigDecimal getMinValue() {
return minValue;
}
@Override
public BigDecimal getMaxValue() {
return maxValue;
}
@Override
public NumericType getNumericType() {
return numericType;
}
@Override
public String getCanonicalName() {
return String.format("ufixed%dx%d", getMBits(), getNBits());
}
}
|
ethereumproject/etherjar
|
etherjar-abi/src/main/java/io/emeraldpay/etherjar/abi/UFixedType.java
|
Java
|
apache-2.0
| 3,629 |
<?php
/**
* @var \Ecommerce\Item $item ;
*/
?>
<div class="ecommerce">
<div class="row">
<div class="col-md-3 item-sidebar">
<div class="sidebar-block">
<div class="items">
<?php $this->widget('Ecommerce\categorys'); ?>
</div>
</div>
</div>
<div class="col-md-9">
<div class="detail_item content">
<div class="row">
<div class="col-sm-5">
<img src="<?= Statics::file($item->image ? $item->image->path : false, '350x800'); ?>"
class="img-responsive"/>
</div>
<div class="col-sm-7">
<h1><?= $item->name(); ?></h1>
<ul class="item-options">
<?php
foreach ($item->options as $param) {
if (!$param->item_option_view || !$param->value) {
continue;
}
if ($param->item_option_type == 'select') {
if (empty($param->option->items[$param->value])) {
continue;
}
$value = $param->option->items[$param->value]->value;
} else {
$value = $param->value;
}
$paramName = $param->item_option_name;
echo "<li>{$paramName}: {$value} {$param->item_option_postfix}</li>";
}
?>
</ul>
<div class="item-actions">
<div class="item-price">
<span class="item-price-caption">Цена: </span>
<span class="item-price-amount"><?= number_format($item->getPrice()->price, 2, '.', ' '); ?></span>
<span class="item-price-currency">руб</span>
</div>
<div class="btn btn-primary item-addtocart"
onclick="inji.Ecommerce.Cart.addItem(<?= $item->getPrice()->id; ?>, 1);">
<i class="glyphicon glyphicon-shopping-cart"></i> Добавить в корзину
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-xs-12">
<div class="item-description">
<?= $item->description; ?>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
|
injitools/cms-Inji
|
system/modules/Ecommerce/appControllers/content/view.php
|
PHP
|
apache-2.0
| 3,001 |
// Copyright 2016 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.
using Google.Apis.Appengine.v1.Data;
using GoogleCloudExtension.Utils;
namespace GoogleCloudExtension.CloudExplorerSources.Gae
{
/// <summary>
/// This class represents a GAE service in the Properties Window.
/// </summary>
internal class VersionItem : PropertyWindowItemBase
{
private readonly Version _version;
public VersionItem(Version version) : base(className: Resources.CloudExplorerGaeVersionCategory, componentName: version.Id)
{
_version = version;
}
[LocalizedCategory(nameof(Resources.CloudExplorerGaeVersionCategory))]
public string Name => _version.Name;
[LocalizedCategory(nameof(Resources.CloudExplorerGaeVersionCategory))]
public string Id => _version.Id;
[LocalizedCategory(nameof(Resources.CloudExplorerGaeVersionCategory))]
public string Status => _version.ServingStatus;
[LocalizedCategory(nameof(Resources.CloudExplorerGaeVersionCategory))]
public string Deployer => _version.CreatedBy;
[LocalizedCategory(nameof(Resources.CloudExplorerGaeVersionCategory))]
public string Url => _version.VersionUrl;
[LocalizedCategory(nameof(Resources.CloudExplorerGaeVersionCategory))]
public string Runtime => _version.Runtime;
[LocalizedCategory(nameof(Resources.CloudExplorerGaeVersionCategory))]
public string Environment => _version.Env;
[LocalizedDisplayName(nameof(Resources.CloudExplorerGaeVersionInstanceClassDisplayName))]
[LocalizedCategory(nameof(Resources.CloudExplorerGaeVersionCategory))]
public string InstanceClass => _version.InstanceClass;
[LocalizedDisplayName(nameof(Resources.CloudExplorerGaeVersionCreationTimeDisplayName))]
[LocalizedCategory(nameof(Resources.CloudExplorerGaeVersionCategory))]
public string CreationTime => _version.CreateTime;
[LocalizedDisplayName(nameof(Resources.CloudExplorerGaeVersionVirtualMachineDisplayName))]
[LocalizedCategory(nameof(Resources.CloudExplorerGaeVersionCategory))]
public bool? VirtualMachine => _version.Vm;
[LocalizedCategory(nameof(Resources.CloudExplorerGaeVersionResourcesCategory))]
public double? CPU => _version.Resources?.Cpu;
[LocalizedDisplayName(nameof(Resources.CloudExplorerGaeVersionResoucesDiskDisplayName))]
[LocalizedCategory(nameof(Resources.CloudExplorerGaeVersionResourcesCategory))]
public double? Disk => _version.Resources?.DiskGb;
[LocalizedDisplayName(nameof(Resources.CloudExplorerGaeVersionResoucesMemoryDisplayName))]
[LocalizedCategory(nameof(Resources.CloudExplorerGaeVersionResourcesCategory))]
public double? Memory => _version.Resources?.MemoryGb;
public override string ToString() => _version.Id;
}
}
|
ivannaranjo/google-cloud-visualstudio
|
GoogleCloudExtension/GoogleCloudExtension/CloudExplorerSources/Gae/VersionItem.cs
|
C#
|
apache-2.0
| 3,463 |
/**
*
*/
package com.app.base.common.calculation;
/**
* 用来定义两个点之间的距离.
*
* @author tianyu912@yeah.net
*/
public class Space {
/**
* x,y轴需要增加或增小的距离.
*/
public float x_space = 0, y_space = 0;
/**
*
*/
public Space() {
super();
}
/**
* 构造Space对象.
* @param x_space x轴需要增加或增小的距离.
* @param y_space y轴需要增加或增小的距离.
*/
public Space(float x_space, float y_space) {
super();
this.x_space = x_space;
this.y_space = y_space;
}
}
|
treason258/TreLibrary
|
LovelyReaderAS/appbase/src/main/java/com/app/base/common/calculation/Space.java
|
Java
|
apache-2.0
| 560 |
angular.module('asics').controller('ReportCtrl', [
'$mdToast',
'$scope',
'$interval',
'admin',
'$stateParams',
function ($mdToast, $scope, $interval, admin, $stateParams) {
$scope.strings = {};
$scope.language = $stateParams.language;
$scope.country_count = [];
$scope.available_dates = [];
$scope.current_date = [];
angular.copy(adminReportStrings[$scope.language], $scope.strings);
function get_reports(day) {
admin.getReport(day)
.then(readReportInformation)
.catch(errorToast);
}
createDateList();
setCurrentDate();
function createDateList() {
for (var day = 3; day < 22; day++) {
$scope.available_dates.push({
date: day
});
}
}
function setCurrentDate() {
var d = new Date();
var day = d.getDate();
$scope.current_date = $.grep($scope.available_dates, function(e){ return e.date == day })[0];
}
function readReportInformation(result) {
angular.copy(result.country_count, $scope.country_count);
}
$scope.$watch('current_date', function () {
get_reports($scope.current_date.date)
});
function errorToast(error) {
var toast = $mdToast.simple()
.textContent(error)
.position('top right')
.hideDelay(3000)
.theme('error-toast');
$mdToast.show(toast);
}
}
]);
var adminReportStrings = {
EN: {
date: "Day",
title: "Visitors list",
description: "Select the date to look up the number of visitors per country on that day."
},
PT: {
date: "Dia",
title: "Lista de visitantes",
description: "Selecione a data para pesquisar o número de visitantes por país no dia."
}
};
|
d3estudio/asics-access
|
web/app/assets/javascripts/controllers/admin/reportCtrl.js
|
JavaScript
|
apache-2.0
| 1,736 |
package org.mimacom.commons.liferay.adapter6110;
/*
* Copyright (c) 2014 mimacom a.g.
*
* 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 java.io.File;
import org.mimacom.commons.liferay.adapter.LiferayTools;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactory;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.util.FileUtil;
import com.liferay.portal.kernel.util.HtmlUtil;
import com.liferay.portal.kernel.util.ServerDetector;
import com.liferay.portal.kernel.xml.SAXReaderUtil;
import com.liferay.portal.util.FileImpl;
import com.liferay.portal.util.HtmlImpl;
import com.liferay.portal.util.PortalImpl;
import com.liferay.portal.util.PortalUtil;
import com.liferay.portal.xml.SAXReaderImpl;
public class LiferayToolsImpl implements LiferayTools {
public LiferayToolsImpl() {
}
static void addExtraContent(String appServerType, StringBuilder content) {
if (ServerDetector.WEBSPHERE_ID.equals(appServerType)) {
content.append("<context-param>");
content
.append("<param-name>com.ibm.websphere.portletcontainer.PortletDeploymentEnabled</param-name>");
content.append("<param-value>false</param-value>");
content.append("</context-param>");
}
}
public String getVersion() {
return "6.1.10";
}
public void initLiferay() {
new FileUtil().setFile(new FileImpl());
new SAXReaderUtil().setSAXReader(new SAXReaderImpl());
new PortalUtil().setPortal(new PortalImpl());
new HtmlUtil().setHtml(new HtmlImpl());
}
public void mergeCss(File basedir) {
// TODO stni
// create the merged css uncompressed and compressed
// String cssPath = new File(basedir, "css").getAbsolutePath();
// String unpacked = cssPath + "/everything_unpacked.css";
// new CSSBuilder(cssPath, unpacked);
// YUICompressor.main(new String[] { "--type", "css", "-o", cssPath +
// "/everything_packed.css", unpacked });
}
public void initLog(final org.apache.maven.plugin.logging.Log log) {
LogFactoryUtil.setLogFactory(new LogFactory() {
public Log getLog(String name) {
return new MavenLiferayLog(name, log);
}
public Log getLog(Class<?> c) {
return new MavenLiferayLog(c.getSimpleName(), log);
}
});
}
public void deployLayout(String serverType, File sourceDir)
throws Exception {
new StandaloneLayoutDeployer(serverType).deployFile(sourceDir,null);
}
public void deployPortlet(String version, String serverType, File sourceDir)
throws Exception {
new StandalonePortletDeployer(version, serverType).deployFile(
sourceDir, null);
}
public void deployTheme(String serverType, File sourceDir) throws Exception {
new StandaloneThemeDeployer(serverType).deployFile(sourceDir,null);
}
public void deployHook(String serverType, File sourceDir) throws Exception {
new StandaloneHookDeployer(serverType).deployFile(sourceDir,null);
}
public void buildService(String arg0, String arg1, String arg2,
String arg3, String arg4, String arg5, String arg6, String arg7,
String arg8, String arg9, String arg10, String arg11, String arg12,
String arg13, String arg14, String arg15, String arg16,
String arg17, String arg18, String arg19, boolean arg20,
String arg21, String arg22, String arg23, String arg24) {
// TODO Auto-generated method stub
}
}
|
mimacom/maven-liferay-plugin
|
mimacom-liferay-adapter/mimacom-liferay-adapter-6.1.10/src/main/java/org/mimacom/commons/liferay/adapter6110/LiferayToolsImpl.java
|
Java
|
apache-2.0
| 3,832 |
/*
* Copyright 2007 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package cn.sherlock.com.sun.media.sound;
/**
* Connection blocks are used to connect source variable
* to a destination variable.
* For example Note On velocity can be connected to output gain.
* In DLS this is called articulator and in SoundFonts (SF2) a modulator.
*
* @author Karl Helgason
*/
public class ModelConnectionBlock {
//
// source1 * source2 * scale -> destination
//
private final static ModelSource[] no_sources = new ModelSource[0];
private ModelSource[] sources = no_sources;
private double scale = 1;
private ModelDestination destination;
public ModelConnectionBlock() {
}
public ModelConnectionBlock(double scale, ModelDestination destination) {
this.scale = scale;
this.destination = destination;
}
public ModelConnectionBlock(ModelSource source,
ModelDestination destination) {
if (source != null) {
this.sources = new ModelSource[1];
this.sources[0] = source;
}
this.destination = destination;
}
public ModelConnectionBlock(ModelSource source, double scale,
ModelDestination destination) {
if (source != null) {
this.sources = new ModelSource[1];
this.sources[0] = source;
}
this.scale = scale;
this.destination = destination;
}
public ModelConnectionBlock(ModelSource source, ModelSource control,
ModelDestination destination) {
if (source != null) {
if (control == null) {
this.sources = new ModelSource[1];
this.sources[0] = source;
} else {
this.sources = new ModelSource[2];
this.sources[0] = source;
this.sources[1] = control;
}
}
this.destination = destination;
}
public ModelConnectionBlock(ModelSource source, ModelSource control,
double scale, ModelDestination destination) {
if (source != null) {
if (control == null) {
this.sources = new ModelSource[1];
this.sources[0] = source;
} else {
this.sources = new ModelSource[2];
this.sources[0] = source;
this.sources[1] = control;
}
}
this.scale = scale;
this.destination = destination;
}
public ModelDestination getDestination() {
return destination;
}
public void setDestination(ModelDestination destination) {
this.destination = destination;
}
public double getScale() {
return scale;
}
public void setScale(double scale) {
this.scale = scale;
}
public ModelSource[] getSources() {
return sources;
}
public void setSources(ModelSource[] source) {
this.sources = source;
}
public void addSource(ModelSource source) {
ModelSource[] oldsources = sources;
sources = new ModelSource[oldsources.length + 1];
for (int i = 0; i < oldsources.length; i++) {
sources[i] = oldsources[i];
}
sources[sources.length - 1] = source;
}
}
|
KyoSherlock/SherlockMidi
|
sherlockmidi/src/main/java/cn/sherlock/com/sun/media/sound/ModelConnectionBlock.java
|
Java
|
apache-2.0
| 4,417 |
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.common.http.client.handler;
import com.alibaba.nacos.common.http.HttpRestResult;
import com.alibaba.nacos.common.http.client.response.HttpClientResponse;
import com.alibaba.nacos.common.http.param.Header;
import com.alibaba.nacos.common.utils.IoUtils;
import org.apache.http.HttpStatus;
import java.lang.reflect.Type;
/**
* Abstract response handler.
*
* @author mai.jh
*/
public abstract class AbstractResponseHandler<T> implements ResponseHandler<T> {
private Type responseType;
@Override
public final void setResponseType(Type responseType) {
this.responseType = responseType;
}
@Override
public final HttpRestResult<T> handle(HttpClientResponse response) throws Exception {
if (HttpStatus.SC_OK != response.getStatusCode()) {
return handleError(response);
}
return convertResult(response, this.responseType);
}
private HttpRestResult<T> handleError(HttpClientResponse response) throws Exception {
Header headers = response.getHeaders();
String message = IoUtils.toString(response.getBody(), headers.getCharset());
return new HttpRestResult<T>(headers, response.getStatusCode(), null, message);
}
/**
* Abstract convertResult method, Different types of converters for expansion.
*
* @param response http client response
* @param responseType responseType
* @return HttpRestResult
* @throws Exception ex
*/
public abstract HttpRestResult<T> convertResult(HttpClientResponse response, Type responseType) throws Exception;
}
|
alibaba/nacos
|
common/src/main/java/com/alibaba/nacos/common/http/client/handler/AbstractResponseHandler.java
|
Java
|
apache-2.0
| 2,256 |
/**
*
*/
package org.apache.hadoop.hdfs.server.namenodeFBT.rule;
import org.apache.hadoop.hdfs.server.namenodeFBT.FBTDirectory;
import org.apache.hadoop.hdfs.server.namenodeFBT.NameNodeFBTProcessor;
import org.apache.hadoop.hdfs.server.namenodeFBT.NodeVisitor;
import org.apache.hadoop.hdfs.server.namenodeFBT.NodeVisitorFactory;
import org.apache.hadoop.hdfs.server.namenodeFBT.utils.StringUtility;
/**
* @author hanhlh
*
*/
public class CompleteFileRule extends AbstractRule{
public CompleteFileRule(RuleManager manager) {
super(manager);
}
@Override
protected Class[] events() {
return new Class[] { CompleteFileRequest.class };
}
@Override
protected void action(RuleEvent event) {
StringUtility.debugSpace("CompleteFileRule action");
CompleteFileRequest request = (CompleteFileRequest) event;
FBTDirectory directory =
(FBTDirectory) NameNodeFBTProcessor.
lookup(request.getDirectoryName());
NodeVisitorFactory visitorFactory = directory.getNodeVisitorFactory();
NodeVisitor visitor = visitorFactory.createCompleteFileVisitor();
visitor.setRequest(request);
visitor.run();
_manager.dispatch(visitor.getResponse());
}
}
|
hanhlh/hadoop-0.20.2_FatBTree
|
src/hdfs/org/apache/hadoop/hdfs/server/namenodeFBT/rule/CompleteFileRule.java
|
Java
|
apache-2.0
| 1,272 |
/*
* Copyright (C) ExBin Project
*
* This application or 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, either version 3 of the License,
* or (at your option) any later version.
*
* This application or library is distributed in the hope that it will be
* useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along this application. If not, see <http://www.gnu.org/licenses/>.
*/
package org.exbin.framework.editor.text.panel;
import java.awt.Font;
import java.awt.event.ItemEvent;
import java.awt.font.TextAttribute;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.prefs.Preferences;
import org.exbin.framework.gui.options.api.OptionsPanel;
import org.exbin.framework.gui.options.api.OptionsPanel.ModifiedOptionListener;
import org.exbin.framework.gui.options.api.OptionsPanel.PathItem;
/**
* Text font options panel.
*
* @version 0.2.0 2017/01/04
* @author ExBin Project (http://exbin.org)
*/
public class TextFontOptionsPanel extends javax.swing.JPanel implements OptionsPanel {
public static final String PREFERENCES_TEXT_FONT_DEFAULT = "textFont.default";
public static final String PREFERENCES_TEXT_FONT_FAMILY = "textFont.family";
public static final String PREFERENCES_TEXT_FONT_SIZE = "textFont.size";
public static final String PREFERENCES_TEXT_FONT_UNDERLINE = "textFont.underline";
public static final String PREFERENCES_TEXT_FONT_STRIKETHROUGH = "textFont.strikethrough";
public static final String PREFERENCES_TEXT_FONT_STRONG = "textFont.strong";
public static final String PREFERENCES_TEXT_FONT_ITALIC = "textFont.italic";
public static final String PREFERENCES_TEXT_FONT_SUBSCRIPT = "textFont.subscript";
public static final String PREFERENCES_TEXT_FONT_SUPERSCRIPT = "textFont.superscript";
private ModifiedOptionListener modifiedOptionListener;
private FontChangeAction fontChangeAction;
private final ResourceBundle resourceBundle;
private final TextFontPanelApi frame;
private Font font;
public TextFontOptionsPanel(TextFontPanelApi frame) {
this.frame = frame;
resourceBundle = java.util.ResourceBundle.getBundle("org/exbin/framework/editor/text/panel/resources/TextFontOptionsPanel");
initComponents();
}
@Override
public void setEnabled(boolean enabled) {
super.setEnabled(enabled);
fontPreviewLabel.setEnabled(enabled);
fillDefaultFontButton.setEnabled(enabled);
fillCurrentFontButton.setEnabled(enabled);
changeFontButton.setEnabled(enabled);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jColorChooser1 = new javax.swing.JColorChooser();
defaultFontCheckBox = new javax.swing.JCheckBox();
fillDefaultFontButton = new javax.swing.JButton();
changeFontButton = new javax.swing.JButton();
fontPreviewLabel = new javax.swing.JLabel();
fillCurrentFontButton = new javax.swing.JButton();
jColorChooser1.setName("jColorChooser1"); // NOI18N
setName("Form"); // NOI18N
defaultFontCheckBox.setSelected(true);
defaultFontCheckBox.setText(resourceBundle.getString("TextFontOptionsPanel.defaultFontCheckBox.text")); // NOI18N
defaultFontCheckBox.setName("defaultFontCheckBox"); // NOI18N
defaultFontCheckBox.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
defaultFontCheckBoxItemStateChanged(evt);
}
});
fillDefaultFontButton.setText(resourceBundle.getString("TextFontOptionsPanel.fillDefaultFontButton.text")); // NOI18N
fillDefaultFontButton.setEnabled(false);
fillDefaultFontButton.setName("fillDefaultFontButton"); // NOI18N
fillDefaultFontButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
fillDefaultFontButtonActionPerformed(evt);
}
});
changeFontButton.setText(resourceBundle.getString("TextFontOptionsPanel.changeFontButton.text")); // NOI18N
changeFontButton.setEnabled(false);
changeFontButton.setName("changeFontButton"); // NOI18N
changeFontButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
changeFontButtonActionPerformed(evt);
}
});
fontPreviewLabel.setBackground(java.awt.Color.white);
fontPreviewLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
fontPreviewLabel.setText(resourceBundle.getString("TextFontOptionsPanel.fontPreviewLabel.text")); // NOI18N
fontPreviewLabel.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
fontPreviewLabel.setEnabled(false);
fontPreviewLabel.setName("fontPreviewLabel"); // NOI18N
fontPreviewLabel.setOpaque(true);
fillCurrentFontButton.setText(resourceBundle.getString("TextFontOptionsPanel.fillCurrentFontButton.text")); // NOI18N
fillCurrentFontButton.setEnabled(false);
fillCurrentFontButton.setName("fillCurrentFontButton"); // NOI18N
fillCurrentFontButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
fillCurrentFontButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(fontPreviewLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(defaultFontCheckBox, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addComponent(changeFontButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(fillDefaultFontButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(fillCurrentFontButton)
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(defaultFontCheckBox)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(fontPreviewLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(changeFontButton)
.addComponent(fillDefaultFontButton)
.addComponent(fillCurrentFontButton))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
}// </editor-fold>//GEN-END:initComponents
private void defaultFontCheckBoxItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_defaultFontCheckBoxItemStateChanged
boolean selected = evt.getStateChange() != ItemEvent.SELECTED;
fontPreviewLabel.setEnabled(selected);
fillDefaultFontButton.setEnabled(selected);
fillCurrentFontButton.setEnabled(selected);
changeFontButton.setEnabled(selected);
setModified(true);
}//GEN-LAST:event_defaultFontCheckBoxItemStateChanged
private void fillDefaultFontButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fillDefaultFontButtonActionPerformed
fontPreviewLabel.setFont(frame.getDefaultFont());
setModified(true);
}//GEN-LAST:event_fillDefaultFontButtonActionPerformed
private void changeFontButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_changeFontButtonActionPerformed
if (fontChangeAction != null) {
Font resultFont = fontChangeAction.changeFont(fontPreviewLabel.getFont());
if (resultFont != null) {
fontPreviewLabel.setFont(resultFont);
setModified(true);
}
}
}//GEN-LAST:event_changeFontButtonActionPerformed
private void fillCurrentFontButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fillCurrentFontButtonActionPerformed
fontPreviewLabel.setFont(frame.getCurrentFont());
setModified(true);
}//GEN-LAST:event_fillCurrentFontButtonActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton changeFontButton;
private javax.swing.JCheckBox defaultFontCheckBox;
private javax.swing.JButton fillCurrentFontButton;
private javax.swing.JButton fillDefaultFontButton;
private javax.swing.JLabel fontPreviewLabel;
private javax.swing.JColorChooser jColorChooser1;
// End of variables declaration//GEN-END:variables
@Override
public List<OptionsPanel.PathItem> getPath() {
ArrayList<OptionsPanel.PathItem> path = new ArrayList<>();
path.add(new PathItem("apperance", ""));
path.add(new PathItem("font", resourceBundle.getString("options.Path.0")));
return path;
}
@Override
public void loadFromPreferences(Preferences preferences) {
Boolean defaultColor = Boolean.valueOf(preferences.get(PREFERENCES_TEXT_FONT_DEFAULT, Boolean.toString(true)));
defaultFontCheckBox.setSelected(defaultColor);
setEnabled(!defaultColor);
String value;
Map<TextAttribute, Object> attribs = new HashMap<>();
value = preferences.get(PREFERENCES_TEXT_FONT_FAMILY, null);
if (value != null) {
attribs.put(TextAttribute.FAMILY, value);
}
value = preferences.get(PREFERENCES_TEXT_FONT_SIZE, null);
if (value != null) {
attribs.put(TextAttribute.SIZE, new Integer(value).floatValue());
}
if (Boolean.valueOf(preferences.get(PREFERENCES_TEXT_FONT_UNDERLINE, null))) {
attribs.put(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_LOW_ONE_PIXEL);
}
if (Boolean.valueOf(preferences.get(PREFERENCES_TEXT_FONT_STRIKETHROUGH, null))) {
attribs.put(TextAttribute.STRIKETHROUGH, TextAttribute.STRIKETHROUGH_ON);
}
if (Boolean.valueOf(preferences.get(PREFERENCES_TEXT_FONT_STRONG, null))) {
attribs.put(TextAttribute.WEIGHT, TextAttribute.WEIGHT_BOLD);
}
if (Boolean.valueOf(preferences.get(PREFERENCES_TEXT_FONT_ITALIC, null))) {
attribs.put(TextAttribute.POSTURE, TextAttribute.POSTURE_OBLIQUE);
}
if (Boolean.valueOf(preferences.get(PREFERENCES_TEXT_FONT_SUBSCRIPT, null))) {
attribs.put(TextAttribute.SUPERSCRIPT, TextAttribute.SUPERSCRIPT_SUB);
}
if (Boolean.valueOf(preferences.get(PREFERENCES_TEXT_FONT_SUPERSCRIPT, null))) {
attribs.put(TextAttribute.SUPERSCRIPT, TextAttribute.SUPERSCRIPT_SUPER);
}
font = frame.getDefaultFont().deriveFont(attribs);
fontPreviewLabel.setFont(font);
}
@Override
public void saveToPreferences(Preferences preferences) {
preferences.put(PREFERENCES_TEXT_FONT_DEFAULT, Boolean.toString(defaultFontCheckBox.isSelected()));
Map<TextAttribute, ?> attribs = font.getAttributes();
String value = (String) attribs.get(TextAttribute.FAMILY);
if (value != null) {
preferences.put(PREFERENCES_TEXT_FONT_FAMILY, value);
} else {
preferences.remove(PREFERENCES_TEXT_FONT_FAMILY);
}
Float fontSize = (Float) attribs.get(TextAttribute.SIZE);
if (fontSize != null) {
preferences.put(PREFERENCES_TEXT_FONT_SIZE, Integer.toString((int) (float) fontSize));
} else {
preferences.remove(PREFERENCES_TEXT_FONT_SIZE);
}
preferences.put(PREFERENCES_TEXT_FONT_UNDERLINE, Boolean.toString(TextAttribute.UNDERLINE_LOW_ONE_PIXEL.equals(attribs.get(TextAttribute.UNDERLINE))));
preferences.put(PREFERENCES_TEXT_FONT_STRIKETHROUGH, Boolean.toString(TextAttribute.STRIKETHROUGH_ON.equals(attribs.get(TextAttribute.STRIKETHROUGH))));
preferences.put(PREFERENCES_TEXT_FONT_STRONG, Boolean.toString(TextAttribute.WEIGHT_BOLD.equals(attribs.get(TextAttribute.WEIGHT))));
preferences.put(PREFERENCES_TEXT_FONT_ITALIC, Boolean.toString(TextAttribute.POSTURE_OBLIQUE.equals(attribs.get(TextAttribute.POSTURE))));
preferences.put(PREFERENCES_TEXT_FONT_SUBSCRIPT, Boolean.toString(TextAttribute.SUPERSCRIPT_SUB.equals(attribs.get(TextAttribute.SUPERSCRIPT))));
preferences.put(PREFERENCES_TEXT_FONT_SUPERSCRIPT, Boolean.toString(TextAttribute.SUPERSCRIPT_SUPER.equals(attribs.get(TextAttribute.SUPERSCRIPT))));
}
@Override
public void applyPreferencesChanges() {
if (defaultFontCheckBox.isSelected()) {
frame.setCurrentFont(frame.getDefaultFont());
} else {
frame.setCurrentFont(font);
}
}
private void setModified(boolean b) {
if (modifiedOptionListener != null) {
modifiedOptionListener.wasModified();
}
}
@Override
public void setModifiedOptionListener(ModifiedOptionListener listener) {
modifiedOptionListener = listener;
}
public void setFontChangeAction(FontChangeAction fontChangeAction) {
this.fontChangeAction = fontChangeAction;
}
public static interface FontChangeAction {
Font changeFont(Font currentFont);
}
}
|
hajdam/deltahex-netbeans
|
src/org/exbin/framework/editor/text/panel/TextFontOptionsPanel.java
|
Java
|
apache-2.0
| 15,094 |
<?
$error = false;
if (isset($_POST['action'])) {
switch ($_POST['action']) {
case 'crypt_set_key':
$_SESSION['core']['install']['crypt']['key'] = $_POST['key'];
break;
}
}
ob_start();
?>
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Install Crypt</title>
<meta charset="UTF-8">
<meta name="robots" content="none">
</head>
<body>
<h1>Install Crypt</h1>
<?
if (!$error) {
if (!isset($_SESSION['core']['install']['crypt']['key'])) {
$error = true;
?>
<form method="post">
<input type="hidden" name="action" value="crypt_set_key">
<label for="key">Key</label>
<br>
<input type="text" name="key" value="<?= str_pad(bin2hex(openssl_random_pseudo_bytes(16)), 32, "\0") ?>">
<br><br>
<input type="submit" value="Next">
</form>
<?
}
}
?>
</body>
</html>
<?
$content = ob_get_contents();
ob_end_clean();
if ($error) {
echo $content;
exit;
}
// Install module
$data->extractTo(ROOT);
if (!APP::Module('Registry')->Get('module_crypt_key')) {
APP::Module('Registry')->Add('module_crypt_key', $_SESSION['core']['install']['crypt']['key']);
}
|
Tendors/phpshell
|
protected/modules/Crypt/install.php
|
PHP
|
apache-2.0
| 1,294 |
/*
* Copyright 2012 GitHub Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.janela.mobile.ui.gist;
import static android.content.Intent.FLAG_ACTIVITY_CLEAR_TOP;
import static android.content.Intent.FLAG_ACTIVITY_SINGLE_TOP;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.text.Editable;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.CheckBox;
import android.widget.EditText;
import com.janela.mobile.R;
import com.janela.mobile.ui.BaseActivity;
import com.janela.mobile.ui.TextWatcherAdapter;
import com.janela.mobile.util.ShareUtils;
import org.eclipse.egit.github.core.Gist;
/**
* Activity to share a text selection as a public or private Gist
*/
public class CreateGistActivity extends BaseActivity {
private EditText descriptionText;
private EditText nameText;
private EditText contentText;
private CheckBox publicCheckBox;
private MenuItem createItem;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gist_create);
descriptionText = finder.find(R.id.et_gist_description);
nameText = finder.find(R.id.et_gist_name);
contentText = finder.find(R.id.et_gist_content);
publicCheckBox = finder.find(R.id.cb_public);
ActionBar actionBar = getSupportActionBar();
actionBar.setTitle(R.string.new_gist);
actionBar.setIcon(R.drawable.action_gist);
actionBar.setDisplayHomeAsUpEnabled(true);
String text = ShareUtils.getBody(getIntent());
if (!TextUtils.isEmpty(text))
contentText.setText(text);
String subject = ShareUtils.getSubject(getIntent());
if (!TextUtils.isEmpty(subject))
descriptionText.setText(subject);
contentText.addTextChangedListener(new TextWatcherAdapter() {
@Override
public void afterTextChanged(Editable s) {
updateCreateMenu(s);
}
});
updateCreateMenu();
}
private void updateCreateMenu() {
if (contentText != null)
updateCreateMenu(contentText.getText());
}
private void updateCreateMenu(CharSequence text) {
if (createItem != null)
createItem.setEnabled(!TextUtils.isEmpty(text));
}
@Override
public boolean onCreateOptionsMenu(Menu options) {
getMenuInflater().inflate(R.menu.gist_create, options);
createItem = options.findItem(R.id.m_apply);
updateCreateMenu();
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.m_apply:
createGist();
return true;
case android.R.id.home:
finish();
Intent intent = new Intent(this, GistsActivity.class);
intent.addFlags(FLAG_ACTIVITY_CLEAR_TOP | FLAG_ACTIVITY_SINGLE_TOP);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void createGist() {
final boolean isPublic = publicCheckBox.isChecked();
String enteredDescription = descriptionText.getText().toString().trim();
final String description = enteredDescription.length() > 0 ? enteredDescription
: getString(R.string.gist_description_hint);
String enteredName = nameText.getText().toString().trim();
final String name = enteredName.length() > 0 ? enteredName
: getString(R.string.gist_file_name_hint);
final String content = contentText.getText().toString();
new CreateGistTask(this, description, isPublic, name, content) {
@Override
protected void onSuccess(Gist gist) throws Exception {
super.onSuccess(gist);
startActivity(GistsViewActivity.createIntent(gist));
setResult(RESULT_OK);
finish();
}
}.create();
}
}
|
DeLaSalleUniversity-Manila/forkhub-Janelaaa
|
app/src/main/java/com/janela/mobile/ui/gist/CreateGistActivity.java
|
Java
|
apache-2.0
| 4,694 |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace Rawr.CustomControls
{
public partial class ExtendedToolTipLabel : Label
{
private ToolTip _ToolTip;
private string _ToolTipText;
public ExtendedToolTipLabel()
{
InitializeComponent();
_ToolTip = new ToolTip();
this.MouseLeave += new EventHandler(ExtendedToolTipLabel_MouseLeave);
this.MouseHover += new EventHandler(ExtendedToolTipLabel_MouseHover);
}
void ExtendedToolTipLabel_MouseHover(object sender, EventArgs e)
{
if (!String.IsNullOrEmpty(_ToolTipText))
{
int x = PointToClient(MousePosition).X + 10;
_ToolTip.Show(_ToolTipText, this, new Point(x, -10));
}
}
public string ToolTipText
{
get { return _ToolTipText; }
set { _ToolTipText = value; }
}
void ExtendedToolTipLabel_MouseLeave(object sender, EventArgs e)
{
if (!String.IsNullOrEmpty(_ToolTipText))
{
_ToolTip.Hide(this);
}
}
}
}
|
Alacant/Rawr-RG
|
Rawr.Base/CustomControls/ExtendedToolTipLabel.cs
|
C#
|
apache-2.0
| 1,292 |
package org.gradle.test.performance.mediummonolithicjavaproject.p388;
import org.junit.Test;
import static org.junit.Assert.*;
public class Test7764 {
Production7764 objectUnderTest = new Production7764();
@Test
public void testProperty0() {
String value = "value";
objectUnderTest.setProperty0(value);
assertEquals(value, objectUnderTest.getProperty0());
}
@Test
public void testProperty1() {
String value = "value";
objectUnderTest.setProperty1(value);
assertEquals(value, objectUnderTest.getProperty1());
}
@Test
public void testProperty2() {
String value = "value";
objectUnderTest.setProperty2(value);
assertEquals(value, objectUnderTest.getProperty2());
}
@Test
public void testProperty3() {
String value = "value";
objectUnderTest.setProperty3(value);
assertEquals(value, objectUnderTest.getProperty3());
}
@Test
public void testProperty4() {
String value = "value";
objectUnderTest.setProperty4(value);
assertEquals(value, objectUnderTest.getProperty4());
}
@Test
public void testProperty5() {
String value = "value";
objectUnderTest.setProperty5(value);
assertEquals(value, objectUnderTest.getProperty5());
}
@Test
public void testProperty6() {
String value = "value";
objectUnderTest.setProperty6(value);
assertEquals(value, objectUnderTest.getProperty6());
}
@Test
public void testProperty7() {
String value = "value";
objectUnderTest.setProperty7(value);
assertEquals(value, objectUnderTest.getProperty7());
}
@Test
public void testProperty8() {
String value = "value";
objectUnderTest.setProperty8(value);
assertEquals(value, objectUnderTest.getProperty8());
}
@Test
public void testProperty9() {
String value = "value";
objectUnderTest.setProperty9(value);
assertEquals(value, objectUnderTest.getProperty9());
}
}
|
oehme/analysing-gradle-performance
|
my-app/src/test/java/org/gradle/test/performance/mediummonolithicjavaproject/p388/Test7764.java
|
Java
|
apache-2.0
| 2,111 |
/**
* Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.engine.fudgemsg;
import java.util.ArrayList;
import java.util.List;
import org.fudgemsg.FudgeField;
import org.fudgemsg.FudgeMsg;
import org.fudgemsg.MutableFudgeMsg;
import org.fudgemsg.mapping.FudgeBuilder;
import org.fudgemsg.mapping.FudgeDeserializer;
import org.fudgemsg.mapping.FudgeSerializer;
import org.fudgemsg.mapping.GenericFudgeBuilderFor;
import org.fudgemsg.wire.types.FudgeWireType;
import com.opengamma.engine.value.ValueProperties;
/**
* Fudge message builder for {@link ValueProperties}. Messages can take the form:
* <ul>
* <li>The empty property set is an empty message.
* <li>A simple property set has a field named {@code with} that contains a sub-message. This in turn contains a field per property - the name of
* the field is the name of the property. This is either a:
* <ul>
* <li>Simple string value
* <li>An indicator indicating a wild-card property value
* <li>A sub-message containing un-named fields with each possible value of the property.
* </ul>
* If the property is optional, the sub-message form is used with a field named {@code optional}. If the field is an optional wild-card the sub-message
* form is used which contains only the {@code optional} field.
* <li>The infinite property set ({@link ValueProperties#all}) has a field named {@code without} that contains an empty sub-message.
* <li>The near-infinite property set has a field named {@code without} that contains a field for each of absent entries, the string value of each field
* is the property name.
* </ul>
*/
@GenericFudgeBuilderFor(ValueProperties.class)
public class ValuePropertiesFudgeBuilder implements FudgeBuilder<ValueProperties> {
// TODO: The message format described above is not particularly efficient or convenient, but kept for compatibility
/**
* Field name for the sub-message containing property values.
*/
public static final String WITH_FIELD = "with";
/**
* Field name for the sub-message representing the infinite or near-infinite property set.
*/
public static final String WITHOUT_FIELD = "without";
/**
* Field name for the 'optional' flag.
*/
public static final String OPTIONAL_FIELD = "optional";
@Override
public MutableFudgeMsg buildMessage(final FudgeSerializer serializer, final ValueProperties object) {
final MutableFudgeMsg message = serializer.newMessage();
object.toFudgeMsg(message);
return message;
}
@Override
public ValueProperties buildObject(final FudgeDeserializer deserializer, final FudgeMsg message) {
if (message.isEmpty()) {
return ValueProperties.none();
}
FudgeMsg subMsg = message.getMessage(WITHOUT_FIELD);
if (subMsg != null) {
if (subMsg.isEmpty()) {
// Infinite
return ValueProperties.all();
}
// Near-infinite
final ValueProperties.Builder builder = ValueProperties.all().copy();
for (final FudgeField field : subMsg) {
if (field.getType().getTypeId() == FudgeWireType.STRING_TYPE_ID) {
builder.withoutAny((String) field.getValue());
}
}
return builder.get();
}
subMsg = message.getMessage(WITH_FIELD);
if (subMsg == null) {
return ValueProperties.none();
}
final ValueProperties.Builder builder = ValueProperties.builder();
for (final FudgeField field : subMsg) {
final String propertyName = field.getName();
switch (field.getType().getTypeId()) {
case FudgeWireType.INDICATOR_TYPE_ID:
builder.withAny(propertyName);
break;
case FudgeWireType.STRING_TYPE_ID:
builder.with(propertyName, (String) field.getValue());
break;
case FudgeWireType.SUB_MESSAGE_TYPE_ID: {
final FudgeMsg subMsg2 = (FudgeMsg) field.getValue();
final List<String> values = new ArrayList<>(subMsg2.getNumFields());
for (final FudgeField field2 : subMsg2) {
switch (field2.getType().getTypeId()) {
case FudgeWireType.INDICATOR_TYPE_ID:
builder.withOptional(propertyName);
break;
case FudgeWireType.STRING_TYPE_ID:
values.add((String) field2.getValue());
break;
}
}
if (!values.isEmpty()) {
builder.with(propertyName, values);
}
break;
}
}
}
return builder.get();
}
}
|
McLeodMoores/starling
|
projects/engine/src/main/java/com/opengamma/engine/fudgemsg/ValuePropertiesFudgeBuilder.java
|
Java
|
apache-2.0
| 4,577 |
/// <reference path="BaseCallback.d.ts" />
/// <reference path="CommonUtil.d.ts" />
/// <reference path="IServiceResultCallback.d.ts" />
/// <reference path="IServiceResultCallbackError.d.ts" />
/// <reference path="IServiceResultCallbackWarning.d.ts" />
/// <reference path="ServiceResponse.d.ts" />
/**
--| ADAPTIVE RUNTIME PLATFORM |----------------------------------------------------------------------------------------
(C) Copyright 2013-2015 Carlos Lozano Diez t/a Adaptive.me <http://adaptive.me>.
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 appli-
-cable 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.
Original author:
* Carlos Lozano Diez
<http://github.com/carloslozano>
<http://twitter.com/adaptivecoder>
<mailto:carlos@adaptive.me>
Contributors:
* Ferran Vila Conesa
<http://github.com/fnva>
<http://twitter.com/ferran_vila>
<mailto:ferran.vila.conesa@gmail.com>
* See source code files for contributors.
Release:
* @version v2.2.15
-------------------------------------------| aut inveniam viam aut faciam |--------------------------------------------
*/
declare module Adaptive {
/**
Interface for Managing the Services operations
Auto-generated implementation of IServiceResultCallback specification.
*/
/**
@property {Adaptive.Dictionary} registeredServiceResultCallback
@member Adaptive
@private
ServiceResultCallback control dictionary.
*/
var registeredServiceResultCallback: Dictionary<IServiceResultCallback>;
/**
@method
@private
@member Adaptive
@param {number} id
@param {Adaptive.IServiceResultCallbackError} error
*/
function handleServiceResultCallbackError(id: number, error: IServiceResultCallbackError): void;
/**
@method
@private
@member Adaptive
@param {number} id
@param {Adaptive.ServiceResponse} response
*/
function handleServiceResultCallbackResult(id: number, response: ServiceResponse): void;
/**
@method
@private
@member Adaptive
@param {number} id
@param {Adaptive.ServiceResponse} response
@param {Adaptive.IServiceResultCallbackWarning} warning
*/
function handleServiceResultCallbackWarning(id: number, response: ServiceResponse, warning: IServiceResultCallbackWarning): void;
/**
@class Adaptive.ServiceResultCallback
@extends Adaptive.BaseCallback
*/
class ServiceResultCallback extends BaseCallback implements IServiceResultCallback {
/**
@private
@property
*/
onErrorFunction: (error: IServiceResultCallbackError) => void;
/**
@private
@property
*/
onResultFunction: (response: ServiceResponse) => void;
/**
@private
@property
*/
onWarningFunction: (response: ServiceResponse, warning: IServiceResultCallbackWarning) => void;
/**
@method constructor
Constructor with anonymous handler functions for callback.
@param {Function} onErrorFunction Function receiving parameters of type: Adaptive.IServiceResultCallbackError
@param {Function} onResultFunction Function receiving parameters of type: Adaptive.ServiceResponse
@param {Function} onWarningFunction Function receiving parameters of type: Adaptive.ServiceResponse, Adaptive.IServiceResultCallbackWarning
*/
constructor(onErrorFunction: (error: IServiceResultCallbackError) => void, onResultFunction: (response: ServiceResponse) => void, onWarningFunction: (response: ServiceResponse, warning: IServiceResultCallbackWarning) => void);
/**
@method
This method is called on Error
@param {Adaptive.IServiceResultCallbackError} error error returned by the platform
@since v2.0
*/
onError(error: IServiceResultCallbackError): void;
/**
@method
This method is called on Result
@param {Adaptive.ServiceResponse} response response data
@since v2.0
*/
onResult(response: ServiceResponse): void;
/**
@method
This method is called on Warning
@param {Adaptive.ServiceResponse} response response data
@param {Adaptive.IServiceResultCallbackWarning} warning warning returned by the platform
@since v2.0
*/
onWarning(response: ServiceResponse, warning: IServiceResultCallbackWarning): void;
}
}
|
AdaptiveMe/adaptive-arp-javascript
|
adaptive-arp-js/src_units/ServiceResultCallback.d.ts
|
TypeScript
|
apache-2.0
| 5,079 |
package voltric.io.data.arff;
/**
* Created by Fernando on 2/15/2017.
*/
public class ArffFolderReader {
}
|
fernandoj92/mvca-parkinson
|
voltric-ltm-analysis/src/main/java/voltric/io/data/arff/ArffFolderReader.java
|
Java
|
apache-2.0
| 110 |
/*
* Copyright (C) 2015 The Gravitee team (http://gravitee.io)
*
* 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 { StateParams, StateService } from '@uirouter/core';
import _ = require('lodash');
import { ApiService } from '../../../../../services/api.service';
import NotificationService from '../../../../../services/notification.service';
class ApiEndpointGroupController {
private api: any;
private group: any;
private initialGroups: any;
private discovery: any;
private creation = false;
private serviceDiscoveryJsonSchemaForm: string[];
private types: any[];
private serviceDiscoveryJsonSchema: any;
private serviceDiscoveryConfigurationForm: any;
constructor(
private ApiService: ApiService,
private NotificationService: NotificationService,
private ServiceDiscoveryService,
private $scope,
private $rootScope: ng.IRootScopeService,
private resolvedServicesDiscovery,
private $state: StateService,
private $stateParams: StateParams,
private $timeout,
) {
'ngInject';
}
$onInit() {
this.api = this.$scope.$parent.apiCtrl.api;
this.group = _.find(this.api.proxy.groups, { name: this.$stateParams.groupName });
this.$scope.duplicateEndpointNames = false;
// Creation mode
if (!this.group) {
this.group = {};
this.creation = true;
}
this.serviceDiscoveryJsonSchemaForm = ['*'];
this.types = this.resolvedServicesDiscovery.data;
this.discovery = this.group.services && this.group.services.discovery;
this.discovery = this.discovery || { enabled: false, configuration: {} };
this.initialGroups = _.cloneDeep(this.api.proxy.groups);
this.$scope.lbs = [
{
name: 'Round-Robin',
value: 'ROUND_ROBIN',
},
{
name: 'Random',
value: 'RANDOM',
},
{
name: 'Weighted Round-Robin',
value: 'WEIGHTED_ROUND_ROBIN',
},
{
name: 'Weighted Random',
value: 'WEIGHTED_RANDOM',
},
];
if (!this.group.load_balancing) {
this.group.load_balancing = {
type: this.$scope.lbs[0].value,
};
}
this.retrievePluginSchema();
}
onTypeChange() {
this.discovery.configuration = {};
this.retrievePluginSchema();
}
retrievePluginSchema() {
if (this.discovery.provider !== undefined) {
this.ServiceDiscoveryService.getSchema(this.discovery.provider).then(
({ data }) => {
this.serviceDiscoveryJsonSchema = data;
},
(response) => {
if (response.status === 404) {
this.serviceDiscoveryJsonSchema = {};
return {
schema: {},
};
} else {
// todo manage errors
this.NotificationService.showError('Unexpected error while loading service discovery schema for ' + this.discovery.provider);
}
},
);
}
}
update(api) {
// include discovery service
this.group.services = {
discovery: this.discovery,
};
if (!_.includes(api.proxy.groups, this.group)) {
if (!api.proxy.groups) {
api.proxy.groups = [this.group];
} else {
api.proxy.groups.push(this.group);
}
}
if (this.group.ssl.trustAll) {
delete this.group.ssl.trustStore;
}
if (this.group.ssl.trustStore && (!this.group.ssl.trustStore.type || this.group.ssl.trustStore.type === '')) {
delete this.group.ssl.trustStore;
}
if (this.group.ssl.keyStore && (!this.group.ssl.keyStore.type || this.group.ssl.keyStore.type === '')) {
delete this.group.ssl.keyStore;
}
if (this.group.headers.length > 0) {
this.group.headers = _.mapValues(_.keyBy(this.group.headers, 'name'), 'value');
} else {
delete this.group.headers;
}
this.ApiService.update(api).then((updatedApi) => {
this.api = updatedApi.data;
this.api.etag = updatedApi.headers('etag');
this.onApiUpdate();
this.initialGroups = _.cloneDeep(api.proxy.groups);
});
}
onApiUpdate() {
this.$rootScope.$broadcast('apiChangeSuccess', { api: this.api });
this.NotificationService.show('Group configuration saved');
this.$state.go('management.apis.detail.proxy.endpoints');
}
reset() {
this.$scope.duplicateEndpointNames = false;
this.$state.reload();
}
backToEndpointsConfiguration() {
this.reset();
this.api.proxy.groups = _.cloneDeep(this.initialGroups);
this.$state.go('management.apis.detail.proxy.endpoints');
}
checkEndpointNameUniqueness() {
this.$scope.duplicateEndpointNames = this.ApiService.isEndpointNameAlreadyUsed(this.api, this.group.name, this.creation);
}
}
export default ApiEndpointGroupController;
|
gravitee-io/gravitee-management-webui
|
src/management/api/proxy/backend/endpoint/group.controller.ts
|
TypeScript
|
apache-2.0
| 5,282 |
/*
* Copyright 2020 Red Hat, Inc. and/or its affiliates.
*
* 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.optaplanner.core.impl.solver.scope;
import java.util.List;
import java.util.Random;
import java.util.concurrent.Semaphore;
import org.optaplanner.core.api.domain.solution.PlanningSolution;
import org.optaplanner.core.api.score.Score;
import org.optaplanner.core.api.solver.Solver;
import org.optaplanner.core.impl.domain.solution.descriptor.SolutionDescriptor;
import org.optaplanner.core.impl.phase.scope.AbstractPhaseScope;
import org.optaplanner.core.impl.score.definition.ScoreDefinition;
import org.optaplanner.core.impl.score.director.InnerScoreDirector;
import org.optaplanner.core.impl.solver.termination.Termination;
import org.optaplanner.core.impl.solver.thread.ChildThreadType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
*/
public class SolverScope<Solution_> {
protected final transient Logger logger = LoggerFactory.getLogger(getClass());
protected int startingSolverCount;
protected Random workingRandom;
protected InnerScoreDirector<Solution_, ?> scoreDirector;
/**
* Used for capping CPU power usage in multithreaded scenarios.
*/
protected Semaphore runnableThreadSemaphore = null;
protected volatile Long startingSystemTimeMillis;
protected volatile Long endingSystemTimeMillis;
protected long childThreadsScoreCalculationCount = 0;
protected Score startingInitializedScore;
protected volatile Solution_ bestSolution;
protected volatile Score bestScore;
protected Long bestSolutionTimeMillis;
// ************************************************************************
// Constructors and simple getters/setters
// ************************************************************************
public int getStartingSolverCount() {
return startingSolverCount;
}
public void setStartingSolverCount(int startingSolverCount) {
this.startingSolverCount = startingSolverCount;
}
public Random getWorkingRandom() {
return workingRandom;
}
public void setWorkingRandom(Random workingRandom) {
this.workingRandom = workingRandom;
}
public InnerScoreDirector<Solution_, ?> getScoreDirector() {
return scoreDirector;
}
public void setScoreDirector(InnerScoreDirector<Solution_, ?> scoreDirector) {
this.scoreDirector = scoreDirector;
}
public void setRunnableThreadSemaphore(Semaphore runnableThreadSemaphore) {
this.runnableThreadSemaphore = runnableThreadSemaphore;
}
public Long getStartingSystemTimeMillis() {
return startingSystemTimeMillis;
}
public Long getEndingSystemTimeMillis() {
return endingSystemTimeMillis;
}
public SolutionDescriptor<Solution_> getSolutionDescriptor() {
return scoreDirector.getSolutionDescriptor();
}
public ScoreDefinition getScoreDefinition() {
return scoreDirector.getScoreDefinition();
}
public Solution_ getWorkingSolution() {
return scoreDirector.getWorkingSolution();
}
public int getWorkingEntityCount() {
return scoreDirector.getWorkingEntityCount();
}
public List<Object> getWorkingEntityList() {
return scoreDirector.getWorkingEntityList();
}
public int getWorkingValueCount() {
return scoreDirector.getWorkingValueCount();
}
public Score calculateScore() {
return scoreDirector.calculateScore();
}
public void assertScoreFromScratch(Solution_ solution) {
scoreDirector.getScoreDirectorFactory().assertScoreFromScratch(solution);
}
public Score getStartingInitializedScore() {
return startingInitializedScore;
}
public void setStartingInitializedScore(Score startingInitializedScore) {
this.startingInitializedScore = startingInitializedScore;
}
public void addChildThreadsScoreCalculationCount(long addition) {
childThreadsScoreCalculationCount += addition;
}
public long getScoreCalculationCount() {
return scoreDirector.getCalculationCount() + childThreadsScoreCalculationCount;
}
public Solution_ getBestSolution() {
return bestSolution;
}
/**
* The {@link PlanningSolution best solution} must never be the same instance
* as the {@link PlanningSolution working solution}, it should be a (un)changed clone.
*
* @param bestSolution never null
*/
public void setBestSolution(Solution_ bestSolution) {
this.bestSolution = bestSolution;
}
public Score getBestScore() {
return bestScore;
}
public void setBestScore(Score bestScore) {
this.bestScore = bestScore;
}
public Long getBestSolutionTimeMillis() {
return bestSolutionTimeMillis;
}
public void setBestSolutionTimeMillis(Long bestSolutionTimeMillis) {
this.bestSolutionTimeMillis = bestSolutionTimeMillis;
}
// ************************************************************************
// Calculated methods
// ************************************************************************
public void startingNow() {
startingSystemTimeMillis = System.currentTimeMillis();
endingSystemTimeMillis = null;
}
public Long getBestSolutionTimeMillisSpent() {
return bestSolutionTimeMillis - startingSystemTimeMillis;
}
public void endingNow() {
endingSystemTimeMillis = System.currentTimeMillis();
}
public boolean isBestSolutionInitialized() {
return bestScore.isSolutionInitialized();
}
public long calculateTimeMillisSpentUpToNow() {
long now = System.currentTimeMillis();
return now - startingSystemTimeMillis;
}
public long getTimeMillisSpent() {
return endingSystemTimeMillis - startingSystemTimeMillis;
}
/**
* @return at least 0, per second
*/
public long getScoreCalculationSpeed() {
long timeMillisSpent = getTimeMillisSpent();
// Avoid divide by zero exception on a fast CPU
return getScoreCalculationCount() * 1000L / (timeMillisSpent == 0L ? 1L : timeMillisSpent);
}
public void setWorkingSolutionFromBestSolution() {
// The workingSolution must never be the same instance as the bestSolution.
scoreDirector.setWorkingSolution(scoreDirector.cloneSolution(bestSolution));
}
public SolverScope<Solution_> createChildThreadSolverScope(ChildThreadType childThreadType) {
SolverScope<Solution_> childThreadSolverScope = new SolverScope<>();
childThreadSolverScope.startingSolverCount = startingSolverCount;
// TODO FIXME use RandomFactory
// Experiments show that this trick to attain reproducibility doesn't break uniform distribution
childThreadSolverScope.workingRandom = new Random(workingRandom.nextLong());
childThreadSolverScope.scoreDirector = scoreDirector.createChildThreadScoreDirector(childThreadType);
childThreadSolverScope.startingSystemTimeMillis = startingSystemTimeMillis;
childThreadSolverScope.endingSystemTimeMillis = null;
childThreadSolverScope.startingInitializedScore = null;
childThreadSolverScope.bestSolution = null;
childThreadSolverScope.bestScore = null;
childThreadSolverScope.bestSolutionTimeMillis = null;
return childThreadSolverScope;
}
public void initializeYielding() {
if (runnableThreadSemaphore != null) {
try {
runnableThreadSemaphore.acquire();
} catch (InterruptedException e) {
// TODO it will take a while before the BasicPlumbingTermination is called
// The BasicPlumbingTermination will terminate the solver.
Thread.currentThread().interrupt();
}
}
}
/**
* Similar to {@link Thread#yield()}, but allows capping the number of active solver threads
* at less than the CPU processor count, so other threads (for example servlet threads that handle REST calls)
* and other processes (such as SSH) have access to uncontested CPUs and don't suffer any latency.
* <p>
* Needs to be called <b>before</b> {@link Termination#isPhaseTerminated(AbstractPhaseScope)},
* so the decision to start a new iteration is after any yield waiting time has been consumed
* (so {@link Solver#terminateEarly()} reacts immediately).
*/
public void checkYielding() {
if (runnableThreadSemaphore != null) {
runnableThreadSemaphore.release();
try {
runnableThreadSemaphore.acquire();
} catch (InterruptedException e) {
// The BasicPlumbingTermination will terminate the solver.
Thread.currentThread().interrupt();
}
}
}
public void destroyYielding() {
if (runnableThreadSemaphore != null) {
runnableThreadSemaphore.release();
}
}
}
|
droolsjbpm/optaplanner
|
optaplanner-core/src/main/java/org/optaplanner/core/impl/solver/scope/SolverScope.java
|
Java
|
apache-2.0
| 9,712 |
package org.flowcolab.account.service.client.dto.account;
import org.flowcolab.account.service.client.dto.person.PersonCreateRequest;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;
import javax.validation.constraints.AssertTrue;
import javax.validation.constraints.NotNull;
public class AccountCreateRequest {
@NotNull
@NotEmpty
private String username;
@NotNull
@NotEmpty
private String password;
@NotNull
@NotEmpty
@Email
private String email;
@AssertTrue
private Boolean isTermsAccepted;
@NotNull
private PersonCreateRequest person;
public AccountCreateRequest() {
}
public AccountCreateRequest(String username,
String password,
String email,
Boolean isTermsAccepted,
PersonCreateRequest person) {
this.username = username;
this.password = password;
this.email = email;
this.isTermsAccepted = isTermsAccepted;
this.person = person;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Boolean getIsTermsAccepted() {
return isTermsAccepted;
}
public void setIsTermsAccepted(Boolean isTermsAccepted) {
this.isTermsAccepted = isTermsAccepted;
}
public PersonCreateRequest getPerson() {
return person;
}
public void setPerson(PersonCreateRequest person) {
this.person = person;
}
@Override
public String toString() {
return "AccountCreateRequest{" +
"username='" + username + '\'' +
", email='" + email + '\'' +
", isTermsAccepted=" + isTermsAccepted +
'}';
}
}
|
omacarena/novaburst.flowcolab
|
app/modules/account/account.service.client/src/main/org/flowcolab/account/service/client/dto/account/AccountCreateRequest.java
|
Java
|
apache-2.0
| 2,219 |
/**
* Copyright (C) 2012 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.analytics.financial.credit.creditdefaultswap.pricing;
import javax.time.calendar.ZonedDateTime;
import com.opengamma.analytics.financial.credit.BuySellProtection;
import com.opengamma.analytics.financial.credit.PriceType;
import com.opengamma.analytics.financial.credit.cds.ISDACurve;
import com.opengamma.analytics.financial.credit.creditdefaultswap.definition.LegacyCreditDefaultSwapDefinition;
import com.opengamma.analytics.financial.credit.hazardratemodel.HazardRateCurve;
import com.opengamma.analytics.financial.credit.schedulegeneration.GenerateCreditDefaultSwapIntegrationSchedule;
import com.opengamma.analytics.financial.credit.schedulegeneration.GenerateCreditDefaultSwapPremiumLegSchedule;
import com.opengamma.analytics.util.time.TimeCalculator;
import com.opengamma.financial.convention.daycount.DayCount;
import com.opengamma.financial.convention.daycount.DayCountFactory;
import com.opengamma.util.ArgumentChecker;
/**
* Class containing methods for the valuation of a vanilla Legacy CDS
*/
public class PresentValueLegacyCreditDefaultSwap {
// -------------------------------------------------------------------------------------------------
private static final DayCount ACT_365 = DayCountFactory.INSTANCE.getDayCount("ACT/365");
// Set the number of partitions to divide the timeline up into for the valuation of the contingent leg
private static final int DEFAULT_N_POINTS = 30;
private final int _numberOfIntegrationSteps;
public PresentValueLegacyCreditDefaultSwap() {
this(DEFAULT_N_POINTS);
}
public PresentValueLegacyCreditDefaultSwap(int numberOfIntegrationPoints) {
_numberOfIntegrationSteps = numberOfIntegrationPoints;
}
// -------------------------------------------------------------------------------------------------
// TODO : Lots of ongoing work to do in this class - Work In Progress
// TODO : Add a method to calc both the legs in one method (useful for performance reasons e.g. not computing survival probabilities and discount factors twice)
// TODO : If valuationDate = adjustedMatDate - 1day have to be more careful in how the contingent leg integral is calculated
// TODO : Fix the bug when val date is very close to mat date
// TODO : Need to add the code for when the settlement date > 0 business days (just a discount factor)
// TODO : Replace the while with a binary search function
// TODO : Should build the cashflow schedules outside of the leg valuation routines to avoid repitition of calculations
// TODO : Eventually replace the ISDACurve with a YieldCurve object (currently using ISDACurve built by RiskCare as this allows exact comparison with the ISDA model)
// TODO : Replace the accrued schedule double with a ZonedDateTime object to make it consistent with other calculations
// TODO : Tidy up the calculatePremiumLeg, valueFeeLegAccrualOnDefault and methods
// TODO : Add the calculation for the settlement and stepin discount factors
// -------------------------------------------------------------------------------------------------
// Public method for computing the PV of a CDS based on an input CDS contract (with a hazard rate curve calibrated to market observed data)
public double getPresentValueCreditDefaultSwap(LegacyCreditDefaultSwapDefinition cds, ISDACurve yieldCurve, HazardRateCurve hazardRateCurve) {
// -------------------------------------------------------------
// Check input CDS, YieldCurve and SurvivalCurve objects are not null
ArgumentChecker.notNull(cds, "LegacyCreditDefaultSwapDefinition");
ArgumentChecker.notNull(yieldCurve, "YieldCurve");
ArgumentChecker.notNull(hazardRateCurve, "HazardRateCurve");
// -------------------------------------------------------------
// Calculate the value of the premium leg (including accrued if required)
double presentValuePremiumLeg = calculatePremiumLeg(cds, yieldCurve, hazardRateCurve);
// Calculate the value of the contingent leg
double presentValueContingentLeg = calculateContingentLeg(cds, yieldCurve, hazardRateCurve);
// Calculate the PV of the CDS (assumes we are buying protection i.e. paying the premium leg, receiving the contingent leg)
double presentValue = -(cds.getParSpread() / 10000.0) * presentValuePremiumLeg + presentValueContingentLeg;
// -------------------------------------------------------------
// If we require the clean price, then calculate the accrued interest and add this to the PV
if (cds.getPriceType() == PriceType.CLEAN) {
presentValue += calculateAccruedInterest(cds, yieldCurve, hazardRateCurve);
}
// If we are selling protection, then reverse the direction of the premium and contingent leg cashflows
if (cds.getBuySellProtection() == BuySellProtection.SELL) {
presentValue = -1 * presentValue;
}
// -------------------------------------------------------------
return presentValue;
}
//-------------------------------------------------------------------------------------------------
// Public method to calculate the par spread of a CDS at contract inception (with a hazard rate curve calibrated to market observed data)
public double getParSpreadCreditDefaultSwap(LegacyCreditDefaultSwapDefinition cds, ISDACurve yieldCurve, HazardRateCurve hazardRateCurve) {
// -------------------------------------------------------------
// Check input CDS, YieldCurve and SurvivalCurve objects are not null
ArgumentChecker.notNull(cds, "CDS field");
ArgumentChecker.notNull(yieldCurve, "YieldCurve field");
ArgumentChecker.notNull(hazardRateCurve, "HazardRateCurve field");
// -------------------------------------------------------------
double parSpread = 0.0;
// -------------------------------------------------------------
// Construct a cashflow schedule object
final GenerateCreditDefaultSwapPremiumLegSchedule cashflowSchedule = new GenerateCreditDefaultSwapPremiumLegSchedule();
// Check if the valuationDate equals the adjusted effective date (have to do this after the schedule is constructed)
ArgumentChecker.isTrue(cds.getValuationDate().equals(cashflowSchedule.getAdjustedEffectiveDate(cds)), "Valuation Date should equal the adjusted effective date when computing par spreads");
// -------------------------------------------------------------
// Calculate the value of the premium leg
double presentValuePremiumLeg = calculatePremiumLeg(cds, yieldCurve, hazardRateCurve);
// Calculate the value of the contingent leg
double presentValueContingentLeg = calculateContingentLeg(cds, yieldCurve, hazardRateCurve);
// -------------------------------------------------------------
// Calculate the par spread (NOTE : Returned value is in bps)
if (Double.doubleToLongBits(presentValuePremiumLeg) == 0.0) {
throw new IllegalStateException("Warning : The premium leg has a PV of zero - par spread cannot be computed");
} else {
parSpread = 10000.0 * presentValueContingentLeg / presentValuePremiumLeg;
}
// -------------------------------------------------------------
return parSpread;
}
// -------------------------------------------------------------------------------------------------
// Method to calculate the value of the premium leg of a CDS (with a hazard rate curve calibrated to market observed data)
// The code for the accrued calc has just been lifted from RiskCare's implementation for now because it exactly reproduces the ISDA model - will replace with a better model in due course
private double calculatePremiumLeg(LegacyCreditDefaultSwapDefinition cds, ISDACurve yieldCurve, HazardRateCurve hazardRateCurve) {
// -------------------------------------------------------------
// Local variable definitions
int startIndex = 0;
int endIndex = 0;
double presentValuePremiumLeg = 0.0;
double presentValueAccruedInterest = 0.0;
// -------------------------------------------------------------
// Construct a cashflow schedule object for the premium leg
final GenerateCreditDefaultSwapPremiumLegSchedule cashflowSchedule = new GenerateCreditDefaultSwapPremiumLegSchedule();
// Build the premium leg cashflow schedule from the contract specification
ZonedDateTime[] premiumLegSchedule = cashflowSchedule.constructCreditDefaultSwapPremiumLegSchedule(cds);
// Construct a schedule object for the accrued leg (this is not a cashflow schedule per se, but a set of time nodes for evaluating the accrued payment integral)
GenerateCreditDefaultSwapIntegrationSchedule accruedSchedule = new GenerateCreditDefaultSwapIntegrationSchedule();
// Build the integration schedule for the calculation of the accrued leg
double[] accruedLegIntegrationSchedule = accruedSchedule.constructCreditDefaultSwapAccruedLegIntegrationSchedule(cds, yieldCurve, hazardRateCurve);
// Calculate the stepin time with the appropriate offset
double offsetStepinTime = accruedSchedule.calculateCreditDefaultSwapOffsetStepinTime(cds, ACT_365);
// -------------------------------------------------------------
// Get the date on which we want to calculate the MtM
ZonedDateTime valuationDate = cds.getValuationDate();
// Get the (adjusted) maturity date of the trade
ZonedDateTime adjustedMaturityDate = cashflowSchedule.getAdjustedMaturityDate(cds);
// -------------------------------------------------------------
// If the valuationDate is after the adjusted maturity date then throw an exception (differs from check in ctor because of the adjusted maturity date)
ArgumentChecker.isTrue(!valuationDate.isAfter(adjustedMaturityDate), "Valuation date {} must be on or before the adjusted maturity date {}", valuationDate, adjustedMaturityDate);
// If the valuation date is exactly the adjusted maturity date then simply return zero
if (valuationDate.equals(adjustedMaturityDate)) {
return 0.0;
}
// -------------------------------------------------------------
// Determine where in the cashflow schedule the valuationDate is
int startCashflowIndex = getCashflowIndex(cds, premiumLegSchedule, 1, 1);
// -------------------------------------------------------------
// Calculate the value of the remaining premium and accrual payments (due after valuationDate)
for (int i = startCashflowIndex; i < premiumLegSchedule.length; i++) {
// Get the beginning and end dates of the current coupon
ZonedDateTime accrualStart = premiumLegSchedule[i - 1];
ZonedDateTime accrualEnd = premiumLegSchedule[i];
// -------------------------------------------------------------
// Calculate the time between the valuation date (time at which survival probability is unity) and the current cashflow
double t = TimeCalculator.getTimeBetween(valuationDate, accrualEnd, ACT_365);
// Calculate the discount factor at time t
double discountFactor = yieldCurve.getDiscountFactor(t);
// -------------------------------------------------------------
// If protection starts at the beginning of the period ...
if (cds.getProtectionStart()) {
// ... Roll all but the last date back by 1/365 of a year
if (i < premiumLegSchedule.length - 1) {
t -= cds.getProtectionOffset();
}
// This is a bit of a hack - need a more elegant way of dealing with the timing nuances
if (i == 1) {
accrualStart = accrualStart.minusDays(1);
}
// ... Roll the final maturity date forward by one day
if (i == premiumLegSchedule.length - 1) {
accrualEnd = accrualEnd.plusDays(1);
}
}
// -------------------------------------------------------------
// Compute the daycount fraction for the current accrual period
double dcf = cds.getDayCountFractionConvention().getDayCountFraction(accrualStart, accrualEnd);
// Calculate the survival probability at the modified time t
double survivalProbability = hazardRateCurve.getSurvivalProbability(t);
// Add this discounted cashflow to the running total for the value of the premium leg
presentValuePremiumLeg += dcf * discountFactor * survivalProbability;
// -------------------------------------------------------------
// Now calculate the accrued leg component if required (need to re-write this code)
if (cds.getIncludeAccruedPremium()) {
double stepinDiscountFactor = 1.0;
startIndex = endIndex;
while (accruedLegIntegrationSchedule[endIndex] < t) {
++endIndex;
}
presentValueAccruedInterest += valueFeeLegAccrualOnDefault(dcf, accruedLegIntegrationSchedule, yieldCurve, hazardRateCurve, startIndex, endIndex,
offsetStepinTime, stepinDiscountFactor);
}
// -------------------------------------------------------------
}
// -------------------------------------------------------------
return cds.getNotional() * (presentValuePremiumLeg + presentValueAccruedInterest);
// -------------------------------------------------------------
}
//-------------------------------------------------------------------------------------------------
// Need to re-write this code completely!!
private double valueFeeLegAccrualOnDefault(final double amount, final double[] timeline, final ISDACurve yieldCurve, final HazardRateCurve hazardRateCurve, final int startIndex,
final int endIndex, final double stepinTime, final double stepinDiscountFactor) {
final double[] timePoints = timeline; //timeline.getTimePoints();
final double startTime = timePoints[startIndex];
final double endTime = timePoints[endIndex];
final double subStartTime = stepinTime > startTime ? stepinTime : startTime;
final double accrualRate = amount / (endTime - startTime);
double t0, t1, dt, survival0, survival1, discount0, discount1;
double lambda, fwdRate, lambdaFwdRate, valueForTimeStep, value;
t0 = subStartTime - startTime + 0.5 * (1.0 / 365.0); //HALF_DAY_ACT_365F;
survival0 = hazardRateCurve.getSurvivalProbability(subStartTime);
double PRICING_TIME = 0.0;
discount0 = startTime < stepinTime || startTime < PRICING_TIME ? stepinDiscountFactor : yieldCurve.getDiscountFactor(timePoints[startIndex]); //discountFactors[startIndex];
value = 0.0;
for (int i = startIndex + 1; i <= endIndex; ++i) {
if (timePoints[i] <= stepinTime) {
continue;
}
t1 = timePoints[i] - startTime + 0.5 * (1.0 / 365.0); //HALF_DAY_ACT_365F;
dt = t1 - t0;
survival1 = hazardRateCurve.getSurvivalProbability(timePoints[i]);
discount1 = yieldCurve.getDiscountFactor(timePoints[i]); //discountFactors[i];
lambda = Math.log(survival0 / survival1) / dt;
fwdRate = Math.log(discount0 / discount1) / dt;
lambdaFwdRate = lambda + fwdRate + 1.0e-50;
valueForTimeStep = lambda * accrualRate * survival0 * discount0
* (((t0 + 1.0 / lambdaFwdRate) / lambdaFwdRate) - ((t1 + 1.0 / lambdaFwdRate) / lambdaFwdRate) * survival1 / survival0 * discount1 / discount0);
value += valueForTimeStep;
t0 = t1;
survival0 = survival1;
discount0 = discount1;
}
return value;
}
// -------------------------------------------------------------------------------------------------
// If the cleanPrice flag is TRUE then this function is called to calculate the accrued interest between valuationDate and the previous coupon date
private double calculateAccruedInterest(LegacyCreditDefaultSwapDefinition cds, ISDACurve yieldCurve, HazardRateCurve hazardRateCurve) {
// Construct a cashflow schedule object
final GenerateCreditDefaultSwapPremiumLegSchedule cashflowSchedule = new GenerateCreditDefaultSwapPremiumLegSchedule();
// Build the premium leg cashflow schedule from the contract specification
ZonedDateTime[] premiumLegSchedule = cashflowSchedule.constructCreditDefaultSwapPremiumLegSchedule(cds);
// Assume the stepin date is the valuation date + 1 day (this is not business day adjusted)
ZonedDateTime stepinDate = cds.getValuationDate().plusDays(1);
// Determine where in the premium leg cashflow schedule the current valuation date is
int startCashflowIndex = getCashflowIndex(cds, premiumLegSchedule, 0, 1);
// Get the date of the last coupon before the current valuation date
ZonedDateTime previousPeriod = premiumLegSchedule[startCashflowIndex - 1];
// Compute the amount of time between previousPeriod and stepinDate
double dcf = cds.getDayCountFractionConvention().getDayCountFraction(previousPeriod, stepinDate);
// Calculate the accrued interest gained in this period of time
double accruedInterest = (cds.getParSpread() / 10000.0) * dcf * cds.getNotional();
return accruedInterest;
}
// -------------------------------------------------------------------------------------------------
// Method to determine where in the premium leg cashflow schedule the valuation date is
private int getCashflowIndex(LegacyCreditDefaultSwapDefinition cds, ZonedDateTime[] premiumLegSchedule, final int startIndex, final int deltaDays) {
int counter = startIndex;
// Determine where in the cashflow schedule the valuationDate is
while (!cds.getValuationDate().isBefore(premiumLegSchedule[counter].minusDays(deltaDays))) {
counter++;
}
return counter;
}
// -------------------------------------------------------------------------------------------------
// Method to calculate the contingent leg (replicates the calculation in the ISDA model)
private double calculateContingentLeg(LegacyCreditDefaultSwapDefinition cds, ISDACurve yieldCurve, HazardRateCurve hazardRateCurve) {
// -------------------------------------------------------------
// Local variable definitions
double presentValueContingentLeg = 0.0;
// -------------------------------------------------------------
// Construct an integration schedule object for the contingent leg
GenerateCreditDefaultSwapIntegrationSchedule contingentLegSchedule = new GenerateCreditDefaultSwapIntegrationSchedule();
// Build the integration schedule for the calculation of the contingent leg
double[] contingentLegIntegrationSchedule = contingentLegSchedule.constructCreditDefaultSwapContingentLegIntegrationSchedule(cds, yieldCurve, hazardRateCurve);
// -------------------------------------------------------------
// Get the survival probability at the first point in the integration schedule
double survivalProbability = hazardRateCurve.getSurvivalProbability(contingentLegIntegrationSchedule[0]);
// Get the discount factor at the first point in the integration schedule
double discountFactor = yieldCurve.getDiscountFactor(contingentLegIntegrationSchedule[0]);
// -------------------------------------------------------------
// Loop over each of the points in the integration schedule
for (int i = 1; i < contingentLegIntegrationSchedule.length; ++i) {
// Calculate the time between adjacent points in the integration schedule
double deltat = contingentLegIntegrationSchedule[i] - contingentLegIntegrationSchedule[i - 1];
// Set the probability of survival up to the previous point in the integration schedule
double survivalProbabilityPrevious = survivalProbability;
// Set the discount factor up to the previous point in the integration schedule
double discountFactorPrevious = discountFactor;
// Get the survival probability at this point in the integration schedule
survivalProbability = hazardRateCurve.getSurvivalProbability(contingentLegIntegrationSchedule[i]);
// Get the discount factor at this point in the integration schedule
discountFactor = yieldCurve.getDiscountFactor(contingentLegIntegrationSchedule[i]);
// Calculate the forward hazard rate over the interval deltat (assumes the hazard rate is constant over this period)
double hazardRate = Math.log(survivalProbabilityPrevious / survivalProbability) / deltat;
// Calculate the forward interest rate over the interval deltat (assumes the interest rate is constant over this period)
double interestRate = Math.log(discountFactorPrevious / discountFactor) / deltat;
// Calculate the contribution of the interval deltat to the overall contingent leg integral
presentValueContingentLeg += (hazardRate / (hazardRate + interestRate)) * (1.0 - Math.exp(-(hazardRate + interestRate) * deltat)) * survivalProbabilityPrevious * discountFactorPrevious;
}
// -------------------------------------------------------------
return cds.getNotional() * (1 - cds.getRecoveryRate()) * presentValueContingentLeg;
}
// -------------------------------------------------------------------------------------------------
// Method to calculate the value of the contingent leg of a CDS (with a hazard rate curve calibrated to market observed data) - Currently not used but this is a more elegant calc than ISDA
private double calculateContingentLegOld(LegacyCreditDefaultSwapDefinition cds, ISDACurve yieldCurve, HazardRateCurve hazardRateCurve) {
// -------------------------------------------------------------
// Construct a schedule generation object (to access the adjusted maturity date method)
GenerateCreditDefaultSwapPremiumLegSchedule cashflowSchedule = new GenerateCreditDefaultSwapPremiumLegSchedule();
// Get the date when protection begins
ZonedDateTime valuationDate = cds.getValuationDate();
// Get the date when protection ends
ZonedDateTime adjustedMaturityDate = cashflowSchedule.getAdjustedMaturityDate(cds);
// -------------------------------------------------------------
// If the valuationDate is after the adjusted maturity date then throw an exception (differs from check in ctor because of the adjusted maturity date)
ArgumentChecker.isTrue(!valuationDate.isAfter(adjustedMaturityDate), "Valuation date {} must be on or before the adjusted maturity date {}", valuationDate, adjustedMaturityDate);
// If the valuation date is exactly the adjusted maturity date then simply return zero
if (valuationDate.equals(adjustedMaturityDate)) {
return 0.0;
}
// -------------------------------------------------------------
double presentValueContingentLeg = 0.0;
// -------------------------------------------------------------
// Calculate the partition of the time axis for the calculation of the integral in the contingent leg
// The period of time for which protection is provided
double protectionPeriod = TimeCalculator.getTimeBetween(valuationDate, adjustedMaturityDate.plusDays(1), /*cds.getDayCountFractionConvention()*/ACT_365);
// Given the protection period, how many partitions should it be divided into
int numberOfPartitions = (int) (_numberOfIntegrationSteps * protectionPeriod + 0.5);
// The size of the time increments in the calculation of the integral
double epsilon = protectionPeriod / numberOfPartitions;
// -------------------------------------------------------------
// Calculate the integral for the contingent leg (note the limits of the loop)
for (int k = 1; k <= numberOfPartitions; k++) {
double t = k * epsilon;
double tPrevious = (k - 1) * epsilon;
double discountFactor = yieldCurve.getDiscountFactor(t);
double survivalProbability = hazardRateCurve.getSurvivalProbability(t);
double survivalProbabilityPrevious = hazardRateCurve.getSurvivalProbability(tPrevious);
presentValueContingentLeg += discountFactor * (survivalProbabilityPrevious - survivalProbability);
}
// -------------------------------------------------------------
return cds.getNotional() * (1.0 - cds.getRecoveryRate()) * presentValueContingentLeg;
}
// -------------------------------------------------------------------------------------------------
}
|
charles-cooper/idylfin
|
src/com/opengamma/analytics/financial/credit/creditdefaultswap/pricing/PresentValueLegacyCreditDefaultSwap.java
|
Java
|
apache-2.0
| 24,342 |
package com.twu.biblioteca;
public class MockMenuOption {
}
|
archana-khanal/twu-biblioteca-archanakhanal
|
test/com/twu/biblioteca/MockMenuOption.java
|
Java
|
apache-2.0
| 61 |
<?php
if (!defined('IN_IAEWEB')) exit();
/**
* 图片路径自动补全
*/
function image($url)
{
if (empty($url) || strlen($url) < 4) return SITE_PATH.'data/upload/nopic.gif';
if (substr($url, 0, 7) == 'http://') return $url;
if (strpos($url, SITE_PATH) !== false && SITE_PATH != '/') return $url;
if (substr($url, 0, 1) == '/') $url = substr($url, 1);
return SITE_PATH.$url;
}
/**
* 缩略图片
*/
function thumb($img, $width = 200, $height = 200)
{
if (empty($img) || strlen($img) < 4) return SITE_PATH.'data/upload/nopic.gif';
if (file_exists(IAEWEB_PATH.$img)) {
$ext = fileext($img);
$thumb = $img.'.thumb.'.$width.'x'.$height.'.'.$ext;
if (!file_exists(IAEWEB_PATH.$thumb)) {
$image = iaeweb::load_class('image');
$image->thumb(IAEWEB_PATH.$img, IAEWEB_PATH.$thumb, $width, $height); // 生成图像缩略图
}
return $thumb;
}
return $img;
}
/**
* 字符截取 支持UTF8/GBK
*/
function strcut($string, $length, $dot = '')
{
if (strlen($string) <= $length) return $string;
$string = str_replace(array('&', '"', '<', '>'), array('&', '"', '<', '>'), $string);
$strcut = '';
$n = $tn = $noc = 0;
while ($n < strlen($string)) {
$t = ord($string[$n]);
if ($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
$tn = 1;
$n++;
$noc++;
} elseif (194 <= $t && $t <= 223) {
$tn = 2;
$n += 2;
$noc += 2;
} elseif (224 <= $t && $t <= 239) {
$tn = 3;
$n += 3;
$noc += 2;
} elseif (240 <= $t && $t <= 247) {
$tn = 4;
$n += 4;
$noc += 2;
} elseif (248 <= $t && $t <= 251) {
$tn = 5;
$n += 5;
$noc += 2;
} elseif ($t == 252 || $t == 253) {
$tn = 6;
$n += 6;
$noc += 2;
} else {
$n++;
}
if ($noc >= $length) break;
}
if ($noc > $length) $n -= $tn;
$strcut = substr($string, 0, $n);
$strcut = str_replace(array('&', '"', '<', '>'), array('&', '"', '<', '>'), $strcut);
return $strcut.$dot;
}
/**
* 取得文件扩展
*/
function fileext($filename)
{
return pathinfo($filename, PATHINFO_EXTENSION);
}
/**
* 正则表达式验证email格式
*/
function is_email($email)
{
return strlen($email) > 6 && strlen($email) <= 32 && preg_match("/^([A-Za-z0-9\-_.+]+)@([A-Za-z0-9\-]+[.][A-Za-z0-9\-.]+)$/", $email);
}
/**
* 栏目面包屑导航 当前位置
*/
function position($catid, $symbol = ' > ')
{
if (empty($catid)) return false;
$cats = get_cache('category');
$catids = parentids($catid, $cats);
$catids = array_filter(explode(',', $catids));
krsort($catids);
$html = '';
foreach ($catids as $t) {
$html .= "<a href=\"".$cats[$t]['url']."\" title=\"".$cats[$t]['catname']."\">".$cats[$t]['catname']."</a>";
if ($catid != $t) $html .= $symbol;
}
return $html;
}
/**
* 递归获取上级栏目集合
*/
function parentids($catid, $cats)
{
if (empty($catid)) return false;
$catids = $catid.',';
if ($cats[$catid]['parentid']) $catids .= parentids($cats[$catid]['parentid'], $cats);
return $catids;
}
/**
* 获取当前栏目顶级栏目
*/
function get_top_cat($catid)
{
$cats = get_cache('category');
$cat = $cats[$catid];
if ($cat['parentid']) $cat = get_top_cat($cat['parentid']);
return $cat;
}
/**
* 程序执行时间
*/
function runtime()
{
$temptime = explode(' ', SYS_START_TIME);
$time = $temptime[1] + $temptime[0];
$temptime = explode(' ', microtime());
$now = $temptime[1] + $temptime[0];
return number_format($now - $time, 6);
}
/**
* 返回经stripslashes处理过的字符串或数组
*/
function new_stripslashes($string)
{
if (!is_array($string)) return stripslashes($string);
foreach ($string as $key => $val) $string[$key] = new_stripslashes($val);
return $string;
}
/**
* 将字符串转换为数组
*/
function string2array($data)
{
if ($data == '') return array();
return unserialize($data);
}
/**
* 将数组转换为字符串
*/
function array2string($data, $isformdata = 1)
{
if ($data == '') return '';
if ($isformdata) $data = new_stripslashes($data);
return serialize($data);
}
/**
* 字节格式化
*/
function file_size_count($size, $dec = 2)
{
$a = array("B", "KB", "MB", "GB", "TB", "PB");
$pos = 0;
while ($size >= 1024) {
$size /= 1024;
$pos++;
}
return round($size, $dec)." ".$a[$pos];
}
/**
* 汉字转为拼音
*/
function word2pinyin($word)
{
if (empty($word)) return '';
$pin = iaeweb::load_class('pinyin');
return str_replace('/', '', $pin->output($word));
}
/**
* 判断是否手机访问
*/
function is_mobile()
{
static $is_mobile;
if (isset($is_mobile)) return $is_mobile;
if (empty($_SERVER['HTTP_USER_AGENT'])) {
$is_mobile = false;
} elseif (strpos($_SERVER['HTTP_USER_AGENT'], 'Mobile') !== false // many mobile devices (all iPhone, iPad, etc.)
|| strpos($_SERVER['HTTP_USER_AGENT'], 'Android') !== false || strpos($_SERVER['HTTP_USER_AGENT'], 'Silk/') !== false || strpos($_SERVER['HTTP_USER_AGENT'], 'Kindle') !== false || strpos($_SERVER['HTTP_USER_AGENT'], 'BlackBerry') !== false || strpos($_SERVER['HTTP_USER_AGENT'], 'Opera Mini') !== false || strpos($_SERVER['HTTP_USER_AGENT'], 'Opera Mobi') !== false) {
$is_mobile = true;
} else {
$is_mobile = false;
}
return $is_mobile;
}
/**
* 判定微信端
*/
function is_wechat()
{
static $is_wechat;
if (isset($is_wechat)) return $is_wechat;
if (empty($_SERVER['HTTP_USER_AGENT'])) {
$is_wechat = false;
} elseif (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false) {
$is_wechat = true;
} else {
$is_wechat = false;
}
return $is_wechat;
}
/**
* 转化 \ 为 /
*/
function dir_path($path)
{
$path = str_replace('\\', '/', $path);
if (substr($path, -1) != '/') $path = $path.'/';
return $path;
}
/**
* 递归创建目录
*/
function mkdirs($dir)
{
if (empty($dir)) return false;
if (!is_dir($dir)) {
mkdirs(dirname($dir));
mkdir($dir);
}
}
/**
* 删除目录及目录下面的所有文件
*/
function delete_dir($dir)
{
$dir = dir_path($dir);
if (!is_dir($dir)) return FALSE;
$list = glob($dir.'*');
foreach ($list as $v) {
is_dir($v) ? delete_dir($v) : @unlink($v);
}
return @rmdir($dir);
}
/**
* 写入缓存
*/
function set_cache($cache_file, $value)
{
if (!$cache_file) return false;
$cache_file = DATA_DIR.'cache'.DIRECTORY_SEPARATOR.$cache_file.'.cache.php';
$value = (!is_array($value)) ? serialize(trim($value)) : serialize($value);
//增加安全
$value = "<?php if (!defined('IN_IAEWEB')) exit(); ?>".$value;
if (!is_dir(DATA_DIR.'cache'.DIRECTORY_SEPARATOR)) {
mkdirs(DATA_DIR.'cache'.DIRECTORY_SEPARATOR);
}
return file_put_contents($cache_file, $value, LOCK_EX) ? true : false;
}
/**
* 获取缓存
*/
function get_cache($cache_file)
{
if (!$cache_file) return false;
static $cacheid = array();
if (!isset($cacheid[$cache_file])) {
$file = DATA_DIR.'cache'.DIRECTORY_SEPARATOR.$cache_file.'.cache.php';
if (is_file($file)) {
$value=str_replace("<?php if (!defined('IN_IAEWEB')) exit(); ?>", "", file_get_contents($file));
//$value = preg_replace('!s:(\d+):"(.*?)";!se', "'s:'.strlen('$2').':\"$2\";'", $value);
$cacheid[$cache_file] = unserialize($value);
} else {
return false;
}
}
return $cacheid[$cache_file];
}
/**
* 删除缓存
*/
function delete_cache($cache_file)
{
if (!$cache_file) return true;
$cache_file = DATA_DIR.'cache'.DIRECTORY_SEPARATOR.$cache_file.'.cache.php';
return is_file($cache_file) ? unlink($cache_file) : true;
}
/**
* 组装url
*/
function url($route, $params = null)
{
if (!$route) return false;
$arr = explode('/', $route);
$arr = array_diff($arr, array(''));
$url = 'index.php';
if (isset($arr[0]) && $arr[0]) {
$url .= '?c='.strtolower($arr[0]);
if (isset($arr[1]) && $arr[1] && $arr[1] != 'index') $url .= '&a='.strtolower($arr[1]);
}
if (!is_null($params) && is_array($params)) {
$params_url = array();
foreach ($params as $key => $value) {
$params_url[] = trim($key).'='.trim($value);
}
$url .= '&'.implode('&', $params_url);
}
$url = str_replace('//', '/', $url);
return Base::get_base_url().$url;
}
/* hbsion PLUS*/
/**
* 递归获取上级栏目路径
*/
function get_parent_dir($catid, $symbol = '/')
{
if (empty($catid)) return false;
$cats = get_cache('category');
$catids = parentids($catid, $cats);
$catids = array_filter(explode(',', $catids));
krsort($catids);
$catdirs = '';
foreach ($catids as $t) {
$catdirs .= $cats[$t]['catdir'];
if ($catid != $t) $catdirs .= $symbol;
}
return $catdirs;
}
/**
* 字符串替换一次
*/
function str_replace_once($needkeywords, $replacekeywords, $content)
{
$pos = strpos($content, $needkeywords);
if ($pos === false) {
return $content;
}
return substr_replace($content, $replacekeywords, $pos, strlen($needkeywords));
}
//计算年龄
function birthday($birthday)
{
$age = strtotime($birthday);
if ($age == false) {
return false;
}
list($y1, $m1, $d1) = explode("-", date("Y-m-d", $age));
$now = strtotime("now");
list($y2, $m2, $d2) = explode("-", date("Y-m-d", $now));
$age = $y2 - $y1;
if ((int)($m2.$d2) < (int)($m1.$d1)) $age -= 1;
return $age;
}
/* 采集 PLUS*/
require("spider.function.php");
|
xiaohaoyong/www.jzfupin.cn
|
core/library/global.function.php
|
PHP
|
apache-2.0
| 10,008 |
/*
* Copyright (c) 2013-2015, Arjuna Technologies Limited, Newcastle-upon-Tyne, England. All rights reserved.
*/
package com.arjuna.databroker.metadata.client;
import java.util.List;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
public interface ContentProxy
{
@GET
@Path("contents")
@Produces(MediaType.APPLICATION_JSON)
public List<String> listMetadata(@QueryParam("requesterId") String requesterId, @QueryParam("userId") String userId);
@GET
@Path("/content/{id}")
@Produces(MediaType.TEXT_PLAIN)
public String getMetadata(@PathParam("id") String id, @QueryParam("requesterId") String requesterId, @QueryParam("userId") String userId);
@POST
@Path("/contents")
@Consumes(MediaType.APPLICATION_JSON)
public String postMetadata(@QueryParam("requesterId") String requesterId, @QueryParam("userId") String userId, String content);
@POST
@Path("/contents")
@Consumes(MediaType.APPLICATION_JSON)
public String postMetadata(@QueryParam("parentId") String parentId, @QueryParam("requesterId") String requesterId, @QueryParam("userId") String userId, String content);
@PUT
@Path("/content/{id}")
@Consumes(MediaType.TEXT_PLAIN)
public void putMetadata(@PathParam("id") String id, @QueryParam("requesterId") String requesterId, @QueryParam("userId") String userId, String content);
}
|
RISBIC/DataBroker
|
metadata-ws/src/main/java/com/arjuna/databroker/metadata/client/ContentProxy.java
|
Java
|
apache-2.0
| 1,572 |
/*
* 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.devopsguru.model;
import javax.annotation.Generated;
/**
* <p>
* The request was denied due to a request throttling.
* </p>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ThrottlingException extends com.amazonaws.services.devopsguru.model.AmazonDevOpsGuruException {
private static final long serialVersionUID = 1L;
/**
* <p>
* The code of the quota that was exceeded, causing the throttling exception.
* </p>
*/
private String quotaCode;
/**
* <p>
* The code of the service that caused the throttling exception.
* </p>
*/
private String serviceCode;
/**
* <p>
* The number of seconds after which the action that caused the throttling exception can be retried.
* </p>
*/
private Integer retryAfterSeconds;
/**
* Constructs a new ThrottlingException with the specified error message.
*
* @param message
* Describes the error encountered.
*/
public ThrottlingException(String message) {
super(message);
}
/**
* <p>
* The code of the quota that was exceeded, causing the throttling exception.
* </p>
*
* @param quotaCode
* The code of the quota that was exceeded, causing the throttling exception.
*/
@com.fasterxml.jackson.annotation.JsonProperty("QuotaCode")
public void setQuotaCode(String quotaCode) {
this.quotaCode = quotaCode;
}
/**
* <p>
* The code of the quota that was exceeded, causing the throttling exception.
* </p>
*
* @return The code of the quota that was exceeded, causing the throttling exception.
*/
@com.fasterxml.jackson.annotation.JsonProperty("QuotaCode")
public String getQuotaCode() {
return this.quotaCode;
}
/**
* <p>
* The code of the quota that was exceeded, causing the throttling exception.
* </p>
*
* @param quotaCode
* The code of the quota that was exceeded, causing the throttling exception.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ThrottlingException withQuotaCode(String quotaCode) {
setQuotaCode(quotaCode);
return this;
}
/**
* <p>
* The code of the service that caused the throttling exception.
* </p>
*
* @param serviceCode
* The code of the service that caused the throttling exception.
*/
@com.fasterxml.jackson.annotation.JsonProperty("ServiceCode")
public void setServiceCode(String serviceCode) {
this.serviceCode = serviceCode;
}
/**
* <p>
* The code of the service that caused the throttling exception.
* </p>
*
* @return The code of the service that caused the throttling exception.
*/
@com.fasterxml.jackson.annotation.JsonProperty("ServiceCode")
public String getServiceCode() {
return this.serviceCode;
}
/**
* <p>
* The code of the service that caused the throttling exception.
* </p>
*
* @param serviceCode
* The code of the service that caused the throttling exception.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ThrottlingException withServiceCode(String serviceCode) {
setServiceCode(serviceCode);
return this;
}
/**
* <p>
* The number of seconds after which the action that caused the throttling exception can be retried.
* </p>
*
* @param retryAfterSeconds
* The number of seconds after which the action that caused the throttling exception can be retried.
*/
@com.fasterxml.jackson.annotation.JsonProperty("Retry-After")
public void setRetryAfterSeconds(Integer retryAfterSeconds) {
this.retryAfterSeconds = retryAfterSeconds;
}
/**
* <p>
* The number of seconds after which the action that caused the throttling exception can be retried.
* </p>
*
* @return The number of seconds after which the action that caused the throttling exception can be retried.
*/
@com.fasterxml.jackson.annotation.JsonProperty("Retry-After")
public Integer getRetryAfterSeconds() {
return this.retryAfterSeconds;
}
/**
* <p>
* The number of seconds after which the action that caused the throttling exception can be retried.
* </p>
*
* @param retryAfterSeconds
* The number of seconds after which the action that caused the throttling exception can be retried.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ThrottlingException withRetryAfterSeconds(Integer retryAfterSeconds) {
setRetryAfterSeconds(retryAfterSeconds);
return this;
}
}
|
aws/aws-sdk-java
|
aws-java-sdk-devopsguru/src/main/java/com/amazonaws/services/devopsguru/model/ThrottlingException.java
|
Java
|
apache-2.0
| 5,545 |
# Copyright 2016 Red Hat, 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.
"""
Definition of block device actions to display in the CLI.
"""
from .._actions import PhysicalActions
PHYSICAL_SUBCMDS = [
(
"list",
dict(
help="List information about blockdevs in the pool",
args=[
(
"pool_name",
dict(action="store", default=None, nargs="?", help="Pool name"),
)
],
func=PhysicalActions.list_devices,
),
)
]
|
stratis-storage/stratis-cli
|
src/stratis_cli/_parser/_physical.py
|
Python
|
apache-2.0
| 1,060 |
package org.dongzhou.rescueTime;
import java.net.URI;
import java.net.URISyntaxException;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.log4j.Logger;
public class ApiUtil {
private static Logger logger = Logger.getLogger(ApiUtil.class.getName());
private static final String KEY = "B63vb_55nMqMqfDXcvoNJQqYcavyMlGnClMPRLeT";
public static RequestBuilder createRequestBuilder(String uri) {
return createRequestBuilder(createURI(uri));
}
private static RequestBuilder createRequestBuilder(URI uri) {
return RequestBuilder.get().setUri(uri).addParameter("key", KEY);
}
private static URI createURI(String uri) {
try {
return new URI(uri);
} catch (URISyntaxException e) {
logger.error(e);
return null;
}
}
}
|
zhou-dong/probabilistic-graphical-models
|
src/org/dongzhou/rescueTime/ApiUtil.java
|
Java
|
apache-2.0
| 767 |
/**
* Copyright (c) 2011-2013, Lukas Eder, lukas.eder@gmail.com
* All rights reserved.
*
* This software is licensed to you under the Apache License, Version 2.0
* (the "License"); You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* . Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* . Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* . Neither the name "jOOR" nor the names of its contributors may be
* used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package com.janeluo.jfinalplus.kit;
import java.lang.reflect.InvocationTargetException;
/**
* A unchecked wrapper for any of Java's checked reflection exceptions:
* <p>
* These exceptions are
* <ul>
* <li> {@link ClassNotFoundException}</li>
* <li> {@link IllegalAccessException}</li>
* <li> {@link IllegalArgumentException}</li>
* <li> {@link InstantiationException}</li>
* <li> {@link InvocationTargetException}</li>
* <li> {@link NoSuchMethodException}</li>
* <li> {@link NoSuchFieldException}</li>
* <li> {@link SecurityException}</li>
* </ul>
*
* @author Lukas Eder
*/
public class ReflectException extends RuntimeException {
/**
* Generated UID
*/
private static final long serialVersionUID = -6213149635297151442L;
public ReflectException(String message) {
super(message);
}
public ReflectException(String message, Throwable cause) {
super(message, cause);
}
public ReflectException() {
super();
}
public ReflectException(Throwable cause) {
super(cause);
}
}
|
yangyining/JFinal-plus
|
src/main/java/com/janeluo/jfinalplus/kit/ReflectException.java
|
Java
|
apache-2.0
| 2,843 |
package org.dbflute.erflute.db;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.Driver;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.List;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.StringTokenizer;
import org.dbflute.erflute.core.util.Check;
import org.dbflute.erflute.editor.model.settings.JDBCDriverSetting;
import org.dbflute.erflute.preference.PreferenceInitializer;
import org.dbflute.erflute.preference.jdbc.JDBCPathDialog;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.ui.PlatformUI;
/**
* @author modified by jflute (originated in ermaster)
*/
public abstract class DBManagerBase implements DBManager {
private final Set<String> reservedWords;
public DBManagerBase() {
DBManagerFactory.addDB(this);
this.reservedWords = getReservedWords();
}
@Override
public String getURL(String serverName, String dbName, int port) {
String temp = serverName.replaceAll("\\\\", "\\\\\\\\");
String url = getURL().replaceAll("<SERVER NAME>", temp);
url = url.replaceAll("<PORT>", String.valueOf(port));
temp = dbName.replaceAll("\\\\", "\\\\\\\\");
url = url.replaceAll("<DB NAME>", temp);
return url;
}
@Override
public Class<Driver> getDriverClass(String driverClassName) {
String path = null;
try {
try {
@SuppressWarnings("unchecked")
final Class<Driver> clazz = (Class<Driver>) Class.forName(driverClassName);
return clazz;
} catch (final ClassNotFoundException e) {
path = PreferenceInitializer.getJDBCDriverPath(getId(), driverClassName);
if (Check.isEmpty(path)) {
throw new IllegalStateException(
String.format("JDBC Driver Class \"%s\" is not found.\rIs \"Preferences> ERFlute> JDBC Driver\" set correctly?",
driverClassName));
}
final ClassLoader loader = getClassLoader(path);
@SuppressWarnings("unchecked")
final Class<Driver> clazz = (Class<Driver>) loader.loadClass(driverClassName);
return clazz;
}
} catch (final MalformedURLException | ClassNotFoundException e) {
final JDBCPathDialog dialog = new JDBCPathDialog(
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(),
getId(), driverClassName, path, new ArrayList<JDBCDriverSetting>(), false);
if (dialog.open() == IDialogConstants.OK_ID) {
final JDBCDriverSetting newDriverSetting =
new JDBCDriverSetting(getId(), dialog.getDriverClassName(), dialog.getPath());
final List<JDBCDriverSetting> driverSettingList = PreferenceInitializer.getJDBCDriverSettingList();
if (driverSettingList.contains(newDriverSetting)) {
driverSettingList.remove(newDriverSetting);
}
driverSettingList.add(newDriverSetting);
PreferenceInitializer.saveJDBCDriverSettingList(driverSettingList);
return getDriverClass(dialog.getDriverClassName());
}
}
return null;
}
private ClassLoader getClassLoader(String uri) throws MalformedURLException {
final StringTokenizer tokenizer = new StringTokenizer(uri, ";");
final int count = tokenizer.countTokens();
final URL[] urls = new URL[count];
for (int i = 0; i < urls.length; i++) {
urls[i] = new URL("file", "", tokenizer.nextToken());
}
return new URLClassLoader(urls, getClass().getClassLoader());
}
protected abstract String getURL();
@Override
public abstract String getDriverClassName();
protected Set<String> getReservedWords() {
final Set<String> reservedWords = new HashSet<>();
final ResourceBundle bundle = ResourceBundle.getBundle(getClass().getPackage().getName() + ".reserved_word");
final Enumeration<String> keys = bundle.getKeys();
while (keys.hasMoreElements()) {
reservedWords.add(keys.nextElement().toUpperCase());
}
return reservedWords;
}
@Override
public boolean isReservedWord(String str) {
return reservedWords.contains(str.toUpperCase());
}
@Override
public boolean isSupported(int supportItem) {
final int[] supportItems = getSupportItems();
for (int i = 0; i < supportItems.length; i++) {
if (supportItems[i] == supportItem) {
return true;
}
}
return false;
}
@Override
public boolean doesNeedURLDatabaseName() {
return true;
}
@Override
public boolean doesNeedURLServerName() {
return true;
}
abstract protected int[] getSupportItems();
@Override
public List<String> getImportSchemaList(Connection con) throws SQLException {
final List<String> schemaList = new ArrayList<>();
final DatabaseMetaData metaData = con.getMetaData();
try {
final ResultSet rs = metaData.getSchemas();
while (rs.next()) {
schemaList.add(rs.getString(1));
}
} catch (final SQLException ignored) {
// when schema is not supported
}
return schemaList;
}
@Override
public List<String> getSystemSchemaList() {
return new ArrayList<>();
}
}
|
dbflute-session/erflute
|
src/org/dbflute/erflute/db/DBManagerBase.java
|
Java
|
apache-2.0
| 5,834 |
package com.centurylink.mdw.model.request;
import com.centurylink.mdw.model.Jsonable;
import com.centurylink.mdw.xml.XmlPath;
import org.apache.xmlbeans.XmlException;
/**
* Request handler spec.
* TODO: JSONPath
*/
public class HandlerSpec implements Comparable<HandlerSpec>, Jsonable {
private String name;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
private final String handlerClass;
public String getHandlerClass() { return handlerClass; }
private String path;
public String getPath() { return path; }
public void setPath(String path) { this.path = path; }
private boolean contentRouting = true;
public boolean isContentRouting() { return contentRouting; }
public void setContentRouting(boolean contentRouting) { this.contentRouting = contentRouting; }
public HandlerSpec(String name, String handlerClass) {
this.name = name;
this.handlerClass = handlerClass;
}
private XmlPath xpath;
public XmlPath getXpath() throws XmlException {
if (xpath == null)
xpath = new XmlPath(path);
return xpath;
}
private String assetPath;
public String getAssetPath() { return assetPath; }
public void setAssetPath(String assetPath) { this.assetPath = assetPath; }
@Override
public int compareTo(HandlerSpec other) {
if (handlerClass.equals(other.handlerClass))
return path.compareToIgnoreCase(other.handlerClass);
else
return handlerClass.compareToIgnoreCase(other.handlerClass);
}
@Override
public String toString() {
return path + " -> " + handlerClass;
}
@Override
public boolean equals(Object other) {
return this.toString().equals(other.toString());
}
@Override
public int hashCode() {
return toString().hashCode();
}
}
|
CenturyLinkCloud/mdw
|
mdw-common/src/com/centurylink/mdw/model/request/HandlerSpec.java
|
Java
|
apache-2.0
| 1,912 |
package tk.zielony.carbonsamples.applibrary;
import android.app.Activity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import java.util.Arrays;
import java.util.List;
import carbon.widget.RecyclerView;
import tk.zielony.carbonsamples.R;
/**
* Created by Marcin on 2014-12-15.
*/
public class RecyclerCardsActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recycler_cards);
List<ViewModel> items = Arrays.asList(new ViewModel(), new ViewModel(), new ViewModel(), new ViewModel(), new ViewModel(), new ViewModel(), new ViewModel());
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
recyclerView.setAdapter(new RecyclerAdapter(items, R.layout.card));
recyclerView.setHeader(R.layout.header_scrollview);
}
}
|
sevoan/Carbon
|
samples/src/main/java/tk/zielony/carbonsamples/applibrary/RecyclerCardsActivity.java
|
Java
|
apache-2.0
| 1,051 |
package dk.lessismore.nojpa.net.link;
import dk.lessismore.nojpa.serialization.Serializer;
import java.net.Socket;
import java.io.IOException;
public class ClientLink extends AbstractLink {
public ClientLink(String serverName, int port) throws IOException {
this(serverName, port, null);
}
public ClientLink(String serverName, int port, Serializer serializer) throws IOException {
super(serializer);
socket = new Socket(serverName, port);
socket.setKeepAlive(true);
socket.setSoTimeout(0); // This implies that a read call will block forever.
in = socket.getInputStream();
out = socket.getOutputStream();
}
}
|
NoJPA-LESS-IS-MORE/NoJPA
|
nojpa_common/src/main/java/dk/lessismore/nojpa/net/link/ClientLink.java
|
Java
|
apache-2.0
| 687 |
/*
* Copyright (C) 2014 Divide.io
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.divide.client.auth;
import io.divide.shared.server.KeyManager;
import io.divide.shared.util.Crypto;
import java.security.KeyPair;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
public class MockKeyManager implements KeyManager {
private String encryptionKey;
private String pushKey;
private KeyPair keyPair;
public MockKeyManager(String encryptionKey) throws NoSuchAlgorithmException {
this.encryptionKey = encryptionKey;
this.keyPair = Crypto.getNew();
}
public PublicKey getPublicKey(){
return keyPair.getPublic();
}
public PrivateKey getPrivateKey(){
return keyPair.getPrivate();
}
public String getSymmetricKey(){
return encryptionKey;
}
public String getPushKey() {
return pushKey;
}
}
|
HiddenStage/divide
|
Client/mock-client/src/main/java/io/divide/client/auth/MockKeyManager.java
|
Java
|
apache-2.0
| 1,473 |
def write(es,body,index,doc_type):
try:
res = es.index(index=index, doc_type=doc_type, body=body)
return res
except Exception, e:
return e
def search(es,body,index,doc_type,size=None):
if size is None:
size=1000
try:
res = es.search(index=index, doc_type=doc_type, body=body, size=size)
return res
except Exception, e:
return None
def update(es,body,index,doc_type,id):
res = es.update(index=index, id=id, doc_type=doc_type, body=body)
return res
def delete(es,index,doc_type,id):
res = es.delete(index=index,doc_type=doc_type,id=id)
return res
def compare(d1,d2):
d1_keys = set(d1.keys())
d2_keys = set(d2.keys())
intersect_keys = d1_keys.intersection(d2_keys)
compared = {o : (d1[o], d2[o]) for o in intersect_keys if d1[o] != d2[o]}
return compared
def consolidate(mac,es,type):
device1={}
deviceQuery = {"query": {"match_phrase": {"mac": { "query": mac }}}}
deviceInfo=search(es, deviceQuery, 'sweet_security', type)
for device in deviceInfo['hits']['hits']:
if len(device1) > 0:
modifiedInfo = compare(device1['_source'],device['_source'])
#usually just two, but we'll keep the oldest one, since that one has probably been modified
if modifiedInfo['firstSeen'][0] < modifiedInfo['firstSeen'][1]:
deleteID=device['_id']
else:
deleteID=device1['_id']
delete(es,'sweet_security',type,deleteID)
device1=device
|
TravisFSmith/SweetSecurity
|
apache/flask/webapp/es.py
|
Python
|
apache-2.0
| 1,377 |
package com.bottlerocketstudios.continuitysample.core.application;
import android.app.Application;
import android.databinding.DataBindingUtil;
import com.bottlerocketstudios.continuitysample.core.databinding.PicassoDataBindingComponent;
import com.bottlerocketstudios.continuitysample.core.injection.ServiceInitializer;
import com.bottlerocketstudios.groundcontrol.convenience.GroundControl;
public class ContinuitySampleApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
//Avoid adding a whole DI framework and all of that just to keep a few objects around.
ServiceInitializer.initializeContext(this);
/**
* Set the default component for DataBinding to use Picasso. This could also be GlideDataBindingComponent();
* If there is an actual need to decide at launch which DataBindingComponent to use, it can be done here.
* Avoid repeatedly calling setDefaultComponent to switch on the fly. It will cause your application
* to behave unpredictably and is not thread safe. If a different DataBindingComponent is needed for a
* specific layout, you can specify that DataBindingComponent when you inflate the layout/setContentView.
*/
DataBindingUtil.setDefaultComponent(new PicassoDataBindingComponent());
/**
* GroundControl's default UI policy will use a built in cache. It isn't necessary and actually
* causes confusion as the Presenters serve this role.
*/
GroundControl.disableCache();
}
}
|
BottleRocketStudios/Android-Continuity
|
ContinuitySample/app/src/main/java/com/bottlerocketstudios/continuitysample/core/application/ContinuitySampleApplication.java
|
Java
|
apache-2.0
| 1,583 |
/*
* ------
* Adept
* -----
* Copyright (C) 2012-2017 Raytheon BBN Technologies Corp.
* -----
* 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 (C) 2016 Raytheon BBN Technologies Corp.
*
* 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 adept.example;
import org.junit.Test;
import java.util.List;
import adept.common.Document;
import adept.common.EntityMention;
import adept.common.Sentence;
import adept.common.TokenOffset;
import adept.common.HltContentContainer;
import adept.common.Passage;
import adept.utilities.DocumentMaker;
// TODO: Auto-generated Javadoc
/**
* Simple class to test the dummy NER module.
*/
public class ExampleNamedEntityTaggerTest {
/**
* The main method.
*
* @param args
* the arguments
*/
@Test
public void Test() {
HltContentContainer hltContainer = new HltContentContainer();
Document doc = DocumentMaker.getInstance().createDocument(
ClassLoader.getSystemResource("ExampleNamedEntityTaggerTest.txt").getFile(),hltContainer);
for(Passage p : hltContainer.getPassages())
System.out.println("PASSAGE::: " + p.getTokenOffset().getBegin() + " " + p.getTokenOffset().getEnd());
// create a sentence from the document. Note that the offsets are random
// here,
// and do not reflect an actual grammatical sentence.
Sentence s = new Sentence(0, new TokenOffset(0, 30), doc.getDefaultTokenStream());
ExampleNamedEntityTagger dummy = new ExampleNamedEntityTagger();
List<EntityMention> mentions = dummy.process(s);
System.out.println("After process method");
for (EntityMention mention : mentions) {
System.out.println(mention.getValue());
}
}
}
|
BBN-E/Adept
|
example/src/test/java/adept/example/ExampleNamedEntityTaggerTest.java
|
Java
|
apache-2.0
| 2,679 |
package debop4s.data.orm.hibernate.repository;
import debop4s.core.collections.PaginatedList;
import debop4s.data.orm.hibernate.HibernateParameter;
import org.hibernate.*;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Example;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.ProjectionList;
import org.springframework.transaction.annotation.Transactional;
import java.io.Serializable;
import java.util.Collection;
import java.util.List;
/**
* HibernateRepository
*
* @author 배성혁 sunghyouk.bae@gmail.com
* @since 2013. 11. 8. 오후 3:49
* @deprecated use {@link debop4s.data.orm.hibernate.repository.HibernateDao}
*/
@Deprecated
@Transactional(readOnly = true)
public interface HibernateRepository<T> {
Session getSession();
void flush();
T load(Serializable id);
T load(Serializable id, LockOptions lockOptions);
T get(Serializable id);
T get(Serializable id, LockOptions lockOptions);
List<T> getIn(Collection<? extends Serializable> ids);
List<T> getIn(Serializable[] ids);
ScrollableResults scroll(Class<?> clazz);
ScrollableResults scroll(DetachedCriteria dc);
ScrollableResults scroll(DetachedCriteria dc, ScrollMode scrollMode);
ScrollableResults scroll(Criteria criteria);
ScrollableResults scroll(Criteria criteria, ScrollMode scrollMode);
ScrollableResults scroll(Query query, HibernateParameter... parameters);
ScrollableResults scroll(Query query, ScrollMode scrollMode, HibernateParameter... parameters);
List<T> findAll();
List<T> findAll(Order... orders);
List<T> findAll(int firstResult, int maxResult, Order... orders);
List<T> find(Criteria criteria, Order... orders);
List<T> find(Criteria criteria, int firstResult, int maxResult, Order... orders);
List<T> find(DetachedCriteria dc, Order... orders);
List<T> find(DetachedCriteria dc, int firstResult, int maxResults, Order... orders);
List<T> find(Query query, HibernateParameter... parameters);
List<T> find(Query query, int firstResult, int maxResults, HibernateParameter... parameters);
List<T> findByHql(final String hql, HibernateParameter... parameters);
List<T> findByHql(final String hql, int firstResult, int maxResults, HibernateParameter... parameters);
List<T> findByNamedQuery(String queryName, HibernateParameter... parameters);
List<T> findByNamedQuery(final String queryName, int firstResult, int maxResults, HibernateParameter... parameters);
List<T> findBySQLString(final String sqlString, HibernateParameter... parameters);
List<T> findBySQLString(final String sqlString, int firstResult, int maxResults, HibernateParameter... parameters);
List<T> findByExample(Example example);
PaginatedList<T> getPage(Criteria criteria, int pageNo, int pageSize, Order... orders);
PaginatedList<T> getPage(DetachedCriteria dc, int pageNo, int pageSize, Order... orders);
PaginatedList<T> getPage(Query query, int pageNo, int pageSize, HibernateParameter... parameters);
PaginatedList<T> getPageByHql(String hql, int pageNo, int pageSize, HibernateParameter... parameters);
PaginatedList<T> getPageByNamedQuery(final String queryName, int pageNo, int pageSize, HibernateParameter... parameters);
PaginatedList<T> getPageBySQLString(final String sqlString, int pageNo, int pageSize, HibernateParameter... parameters);
/**
* 지정한 엔티티에 대한 유일한 결과를 조회합니다. (결과가 없거나, 복수이면 예외가 발생합니다.
*
* @param criteria 조회 조건
* @return 조회된 엔티티
*/
T findUnique(Criteria criteria);
/**
* 지정한 엔티티에 대한 유일한 결과를 조회합니다. (결과가 없거나, 복수이면 예외가 발생합니다.
*
* @param dc 조회 조건
* @return 조회된 엔티티
*/
T findUnique(DetachedCriteria dc);
/**
* 지정한 엔티티에 대한 유일한 결과를 조회합니다. (결과가 없거나, 복수이면 예외가 발생합니다.
*
* @param query 조회 조건
* @return 조회된 엔티티
*/
T findUnique(Query query, HibernateParameter... parameters);
/**
* 지정한 엔티티에 대한 유일한 결과를 조회합니다. (결과가 없거나, 복수이면 예외가 발생합니다.
*
* @param hql 조회 조건
* @return 조회된 엔티티
*/
T findUniqueByHql(String hql, HibernateParameter... parameters);
/**
* 지정한 엔티티에 대한 유일한 결과를 조회합니다. (결과가 없거나, 복수이면 예외가 발생합니다.
*
* @param queryName 쿼리 명
* @return 조회된 엔티티
*/
T findUniqueByNamedQuery(final String queryName, HibernateParameter... parameters);
/**
* 지정한 엔티티에 대한 유일한 결과를 조회합니다. (결과가 없거나, 복수이면 예외가 발생합니다.
*
* @param sqlString 쿼리 명
* @return 조회된 엔티티
*/
T findUniqueBySQLString(final String sqlString, HibernateParameter... parameters);
/**
* 질의 조건에 만족하는 첫번째 엔티티를 반환합니다.
*
* @param criteria 조회 조건
* @return 조회된 엔티티
*/
T findFirst(Criteria criteria, Order... orders);
/**
* 질의 조건에 만족하는 첫번째 엔티티를 반환합니다.
*
* @param dc 조회 조건
* @return 조회된 엔티티
*/
T findFirst(DetachedCriteria dc, Order... orders);
/**
* 질의 조건에 만족하는 첫번째 엔티티를 반환합니다.
*
* @param query 조회 조건
* @return 조회된 엔티티
*/
T findFirst(Query query, HibernateParameter... parameters);
/**
* 질의 조건에 만족하는 첫번째 엔티티를 반환합니다.
*
* @param hql 조회 조건
* @return 조회된 엔티티
*/
T findFirstByHql(String hql, HibernateParameter... parameters);
/**
* 질의 조건에 만족하는 첫번째 엔티티를 반환합니다.
*
* @param queryName 쿼리 명
* @return 조회된 엔티티
*/
T findFirstByNamedQuery(final String queryName, HibernateParameter... parameters);
/**
* 질의 조건에 만족하는 첫번째 엔티티를 반환합니다.
*
* @param sqlString 쿼리 명
* @return 조회된 엔티티
*/
T findFirstBySQLString(final String sqlString, HibernateParameter... parameters);
boolean exists(Class<?> clazz);
boolean exists(Criteria criteria);
boolean exists(DetachedCriteria dc);
boolean exists(Query query, HibernateParameter... parameters);
boolean existsByHql(String hql, HibernateParameter... parameters);
boolean existsByNamedQuery(final String queryName, HibernateParameter... parameters);
boolean existsBySQLString(final String sqlString, HibernateParameter... parameters);
long count();
long count(Criteria criteria);
long count(DetachedCriteria dc);
long count(Query query, HibernateParameter... parameters);
long countByHql(String hql, HibernateParameter... parameters);
long countByNamedQuery(final String queryName, HibernateParameter... parameters);
long countBySQLString(final String sqlString, HibernateParameter... parameters);
T merge(T entity);
@Transactional
void persist(T entity);
@Transactional
Serializable save(T entity);
@Transactional
void saveOrUpdate(T entity);
@Transactional
void update(T entity);
@Transactional
void delete(T entity);
@Transactional
void deleteById(Serializable id);
@Transactional
void deleteAll();
@Transactional
void deleteAll(Collection<? extends T> entities);
@Transactional
void deleteAll(Criteria criteria);
@Transactional
void deleteAll(DetachedCriteria dc);
/** Cascade 적용 없이 엔티티들을 모두 삭제합니다. */
@Transactional
int deleteAllWithoutCascade();
/**
* 쿼리를 실행합니다.
*
* @param query 실행할 Query
* @param parameters 인자 정보
* @return 실행에 영향 받은 행의 수
*/
@Transactional
int executeUpdate(Query query, HibernateParameter... parameters);
/**
* 지정한 HQL 구문 (insert, update, del) 을 수행합니다.
*
* @param hql 수행할 HQL 구문
* @param parameters 인자 정보
* @return 실행에 영향 받은 행의 수
*/
@Transactional
int executeUpdateByHql(String hql, HibernateParameter... parameters);
/**
* 지정한 쿼리 구문 (insert, update, del) 을 수행합니다.
*
* @param queryName 수행할 Query 명
* @param parameters 인자 정보
* @return 실행에 영향 받은 행의 수
*/
@Transactional
int executeUpdateByNamedQuery(final String queryName, HibernateParameter... parameters);
/**
* 지정한 쿼리 구문 (insert, update, del) 을 수행합니다.
*
* @param sqlString 수행할 Query
* @param parameters 인자 정보
* @return 실행에 영향 받은 행의 수
*/
@Transactional
int executeUpdateBySQLString(final String sqlString, HibernateParameter... parameters);
<P> P reportOne(Class<P> projectClass, ProjectionList projectionList, Criteria criteria);
<P> P reportOne(Class<P> projectClass, ProjectionList projectionList, DetachedCriteria dc);
<P> List<P> reportList(Class<P> projectClass, ProjectionList projectionList, Criteria criteria);
<P> List<P> reportList(Class<P> projectClass, ProjectionList projectionList, Criteria criteria, int firstResult, int maxResults);
<P> List<P> reportList(Class<P> projectClass, ProjectionList projectionList, DetachedCriteria dc);
<P> List<P> reportList(Class<P> projectClass, ProjectionList projectionList, DetachedCriteria dc, int firstResult, int maxResults);
<P> PaginatedList<P> reportPage(Class<P> projectClass, ProjectionList projectionList, Criteria criteria, int pageNo, int pageSize);
<P> PaginatedList<P> reportPage(Class<P> projectClass, ProjectionList projectionList, DetachedCriteria dc, int pageNo, int pageSize);
}
|
debop/debop4s
|
debop4s-data-orm/src/main/scala/debop4s/data/orm/hibernate/repository/HibernateRepository.java
|
Java
|
apache-2.0
| 10,406 |
/*
* Copyright © 2019 Cask Data, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package io.cdap.plugin.zuora.objects;
import com.google.gson.annotations.SerializedName;
import io.cdap.cdap.api.data.schema.Schema;
import io.cdap.plugin.zuora.restobjects.annotations.ObjectDefinition;
import io.cdap.plugin.zuora.restobjects.annotations.ObjectFieldDefinition;
import io.cdap.plugin.zuora.restobjects.objects.BaseObject;
import javax.annotation.Nullable;
/**
* Object name: ProxyModifyUnitOfMeasure (ProxyModifyUnitOfMeasure).
* Related objects:
**/
@SuppressWarnings("unused")
@ObjectDefinition(
Name = "ProxyModifyUnitOfMeasure",
ObjectType = ObjectDefinition.ObjectDefinitionType.NESTED
)
public class ProxyModifyUnitOfMeasure extends BaseObject {
/**
* Name: Active (Active), Type: boolean.
* Options (custom, update, select): false, false, false
**/
@Nullable
@SerializedName("active")
@ObjectFieldDefinition(FieldType = Schema.Type.BOOLEAN)
private Boolean active;
/**
* Name: DecimalPlaces (DecimalPlaces), Type: integer.
* Options (custom, update, select): false, false, false
**/
@Nullable
@SerializedName("decimalPlaces")
@ObjectFieldDefinition(FieldType = Schema.Type.INT)
private Integer decimalPlaces;
/**
* Name: DisplayedAs (DisplayedAs), Type: string.
* Options (custom, update, select): false, false, false
**/
@Nullable
@SerializedName("displayedAs")
@ObjectFieldDefinition(FieldType = Schema.Type.STRING)
private String displayedAs;
/**
* Name: RoundingMode (RoundingMode), Type: string.
* Options (custom, update, select): false, false, false
**/
@Nullable
@SerializedName("roundingMode")
@ObjectFieldDefinition(FieldType = Schema.Type.STRING)
private String roundingMode;
/**
* Name: UomName (UomName), Type: string.
* Options (custom, update, select): false, false, false
**/
@Nullable
@SerializedName("uomName")
@ObjectFieldDefinition(FieldType = Schema.Type.STRING)
private String uomName;
@Override
public void addFields() {
addCustomField("active", active, Boolean.class);
addCustomField("decimalPlaces", decimalPlaces, Integer.class);
addCustomField("displayedAs", displayedAs, String.class);
addCustomField("roundingMode", roundingMode, String.class);
addCustomField("uomName", uomName, String.class);
}
}
|
data-integrations/zuora
|
src/main/java/io/cdap/plugin/zuora/objects/ProxyModifyUnitOfMeasure.java
|
Java
|
apache-2.0
| 2,879 |
package se.ugli.habanero.j;
public class HabaneroException extends RuntimeException {
private static final long serialVersionUID = 8697180611643224014L;
public HabaneroException(final String msg) {
super(msg);
}
public HabaneroException(final Throwable t) {
super(t);
}
}
|
ugli/habanero-java
|
src/main/java/se/ugli/habanero/j/HabaneroException.java
|
Java
|
apache-2.0
| 285 |
/*
* Copyright 2010-2014 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.
*/
/*
* Do not modify this file. This file is generated from the ec2-2015-10-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Amazon.EC2.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
namespace Amazon.EC2.Model.Internal.MarshallTransformations
{
/// <summary>
/// AttachVpnGateway Request Marshaller
/// </summary>
public class AttachVpnGatewayRequestMarshaller : IMarshaller<IRequest, AttachVpnGatewayRequest> , IMarshaller<IRequest,AmazonWebServiceRequest>
{
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public IRequest Marshall(AmazonWebServiceRequest input)
{
return this.Marshall((AttachVpnGatewayRequest)input);
}
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="publicRequest"></param>
/// <returns></returns>
public IRequest Marshall(AttachVpnGatewayRequest publicRequest)
{
IRequest request = new DefaultRequest(publicRequest, "Amazon.EC2");
request.Parameters.Add("Action", "AttachVpnGateway");
request.Parameters.Add("Version", "2015-10-01");
if(publicRequest != null)
{
if(publicRequest.IsSetVpcId())
{
request.Parameters.Add("VpcId", StringUtils.FromString(publicRequest.VpcId));
}
if(publicRequest.IsSetVpnGatewayId())
{
request.Parameters.Add("VpnGatewayId", StringUtils.FromString(publicRequest.VpnGatewayId));
}
}
return request;
}
}
}
|
rafd123/aws-sdk-net
|
sdk/src/Services/EC2/Generated/Model/Internal/MarshallTransformations/AttachVpnGatewayRequestMarshaller.cs
|
C#
|
apache-2.0
| 2,614 |
package com.esm.employee.service.utils;
import java.io.IOException;
import java.time.LocalDate;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
public class LocalDateTimeSerializer extends JsonSerializer<LocalDate> {
@Override
public void serialize(LocalDate localDate, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
jsonGenerator.writeString(localDate.toString());
}
}
|
esm-services/esm-employee-service
|
src/main/java/com/esm/employee/service/utils/LocalDateTimeSerializer.java
|
Java
|
apache-2.0
| 633 |
/*
* Copyright 2010-2013 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.
*/
using System;
using System.Threading;
using Amazon.ElasticLoadBalancing.Model;
using Amazon.ElasticLoadBalancing.Model.Internal.MarshallTransformations;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Auth;
using Amazon.Runtime.Internal.Transform;
namespace Amazon.ElasticLoadBalancing
{
/// <summary>
/// Implementation for accessing AmazonElasticLoadBalancing.
///
/// Elastic Load Balancing <para> Elastic Load Balancing is a cost-effective and easy to use web service to help you improve the availability
/// and scalability of your application running on Amazon Elastic Cloud Compute (Amazon EC2). It makes it easy for you to distribute application
/// loads between two or more EC2 instances. Elastic Load Balancing supports the growth in traffic of your application by enabling availability
/// through redundancy. </para> <para>This guide provides detailed information about Elastic Load Balancing actions, data types, and parameters
/// that can be used for sending a query request. Query requests are HTTP or HTTPS requests that use the HTTP verb GET or POST and a query
/// parameter named Action or Operation. Action is used throughout this documentation, although Operation is supported for backward
/// compatibility with other AWS Query APIs.</para> <para>For detailed information on constructing a query request using the actions, data
/// types, and parameters mentioned in this guide, go to Using the Query API in the <i>Elastic Load Balancing Developer Guide</i> .</para>
/// <para>For detailed information about Elastic Load Balancing features and their associated actions, go to Using Elastic Load Balancing in the
/// <i>Elastic Load Balancing Developer Guide</i> .</para> <para>This reference guide is based on the current WSDL, which is available at:
/// </para>
/// </summary>
public class AmazonElasticLoadBalancingClient : AmazonWebServiceClient, AmazonElasticLoadBalancing
{
AbstractAWSSigner signer = new AWS4Signer();
#region Constructors
/// <summary>
/// Constructs AmazonElasticLoadBalancingClient with the credentials loaded from the application's
/// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance.
///
/// Example App.config with credentials set.
/// <code>
/// <?xml version="1.0" encoding="utf-8" ?>
/// <configuration>
/// <appSettings>
/// <add key="AWSAccessKey" value="********************"/>
/// <add key="AWSSecretKey" value="****************************************"/>
/// </appSettings>
/// </configuration>
/// </code>
///
/// </summary>
public AmazonElasticLoadBalancingClient()
: base(FallbackCredentialsFactory.GetCredentials(), new AmazonElasticLoadBalancingConfig(), true, AuthenticationTypes.User) { }
/// <summary>
/// Constructs AmazonElasticLoadBalancingClient with the credentials loaded from the application's
/// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance.
///
/// Example App.config with credentials set.
/// <code>
/// <?xml version="1.0" encoding="utf-8" ?>
/// <configuration>
/// <appSettings>
/// <add key="AWSAccessKey" value="********************"/>
/// <add key="AWSSecretKey" value="****************************************"/>
/// </appSettings>
/// </configuration>
/// </code>
///
/// </summary>
/// <param name="region">The region to connect.</param>
public AmazonElasticLoadBalancingClient(RegionEndpoint region)
: base(FallbackCredentialsFactory.GetCredentials(), new AmazonElasticLoadBalancingConfig(){RegionEndpoint = region}, true, AuthenticationTypes.User) { }
/// <summary>
/// Constructs AmazonElasticLoadBalancingClient with the credentials loaded from the application's
/// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance.
///
/// Example App.config with credentials set.
/// <code>
/// <?xml version="1.0" encoding="utf-8" ?>
/// <configuration>
/// <appSettings>
/// <add key="AWSAccessKey" value="********************"/>
/// <add key="AWSSecretKey" value="****************************************"/>
/// </appSettings>
/// </configuration>
/// </code>
///
/// </summary>
/// <param name="config">The AmazonElasticLoadBalancing Configuration Object</param>
public AmazonElasticLoadBalancingClient(AmazonElasticLoadBalancingConfig config)
: base(FallbackCredentialsFactory.GetCredentials(), config, true, AuthenticationTypes.User) { }
/// <summary>
/// Constructs AmazonElasticLoadBalancingClient with AWS Credentials
/// </summary>
/// <param name="credentials">AWS Credentials</param>
public AmazonElasticLoadBalancingClient(AWSCredentials credentials)
: this(credentials, new AmazonElasticLoadBalancingConfig())
{
}
/// <summary>
/// Constructs AmazonElasticLoadBalancingClient with AWS Credentials
/// </summary>
/// <param name="credentials">AWS Credentials</param>
/// <param name="region">The region to connect.</param>
public AmazonElasticLoadBalancingClient(AWSCredentials credentials, RegionEndpoint region)
: this(credentials, new AmazonElasticLoadBalancingConfig(){RegionEndpoint=region})
{
}
/// <summary>
/// Constructs AmazonElasticLoadBalancingClient with AWS Credentials and an
/// AmazonElasticLoadBalancingClient Configuration object.
/// </summary>
/// <param name="credentials">AWS Credentials</param>
/// <param name="clientConfig">The AmazonElasticLoadBalancingClient Configuration Object</param>
public AmazonElasticLoadBalancingClient(AWSCredentials credentials, AmazonElasticLoadBalancingConfig clientConfig)
: base(credentials, clientConfig, false, AuthenticationTypes.User)
{
}
/// <summary>
/// Constructs AmazonElasticLoadBalancingClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
public AmazonElasticLoadBalancingClient(string awsAccessKeyId, string awsSecretAccessKey)
: this(awsAccessKeyId, awsSecretAccessKey, new AmazonElasticLoadBalancingConfig())
{
}
/// <summary>
/// Constructs AmazonElasticLoadBalancingClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="region">The region to connect.</param>
public AmazonElasticLoadBalancingClient(string awsAccessKeyId, string awsSecretAccessKey, RegionEndpoint region)
: this(awsAccessKeyId, awsSecretAccessKey, new AmazonElasticLoadBalancingConfig() {RegionEndpoint=region})
{
}
/// <summary>
/// Constructs AmazonElasticLoadBalancingClient with AWS Access Key ID, AWS Secret Key and an
/// AmazonElasticLoadBalancingClient Configuration object. If the config object's
/// UseSecureStringForAwsSecretKey is false, the AWS Secret Key
/// is stored as a clear-text string. Please use this option only
/// if the application environment doesn't allow the use of SecureStrings.
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="clientConfig">The AmazonElasticLoadBalancingClient Configuration Object</param>
public AmazonElasticLoadBalancingClient(string awsAccessKeyId, string awsSecretAccessKey, AmazonElasticLoadBalancingConfig clientConfig)
: base(awsAccessKeyId, awsSecretAccessKey, clientConfig, AuthenticationTypes.User)
{
}
#endregion
#region DescribeLoadBalancerPolicyTypes
/// <summary>
/// <para> Returns meta-information on the specified LoadBalancer policies defined by the Elastic Load Balancing service. The policy types that
/// are returned from this action can be used in a CreateLoadBalancerPolicy action to instantiate specific policy configurations that will be
/// applied to an Elastic LoadBalancer. </para>
/// </summary>
///
/// <param name="describeLoadBalancerPolicyTypesRequest">Container for the necessary parameters to execute the DescribeLoadBalancerPolicyTypes
/// service method on AmazonElasticLoadBalancing.</param>
///
/// <returns>The response from the DescribeLoadBalancerPolicyTypes service method, as returned by AmazonElasticLoadBalancing.</returns>
///
/// <exception cref="PolicyTypeNotFoundException"/>
public DescribeLoadBalancerPolicyTypesResponse DescribeLoadBalancerPolicyTypes(DescribeLoadBalancerPolicyTypesRequest describeLoadBalancerPolicyTypesRequest)
{
IAsyncResult asyncResult = invokeDescribeLoadBalancerPolicyTypes(describeLoadBalancerPolicyTypesRequest, null, null, true);
return EndDescribeLoadBalancerPolicyTypes(asyncResult);
}
/// <summary>
/// Initiates the asynchronous execution of the DescribeLoadBalancerPolicyTypes operation.
/// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.DescribeLoadBalancerPolicyTypes"/>
/// </summary>
///
/// <param name="describeLoadBalancerPolicyTypesRequest">Container for the necessary parameters to execute the DescribeLoadBalancerPolicyTypes
/// operation on AmazonElasticLoadBalancing.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking
/// EndDescribeLoadBalancerPolicyTypes operation.</returns>
public IAsyncResult BeginDescribeLoadBalancerPolicyTypes(DescribeLoadBalancerPolicyTypesRequest describeLoadBalancerPolicyTypesRequest, AsyncCallback callback, object state)
{
return invokeDescribeLoadBalancerPolicyTypes(describeLoadBalancerPolicyTypesRequest, callback, state, false);
}
/// <summary>
/// Finishes the asynchronous execution of the DescribeLoadBalancerPolicyTypes operation.
/// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.DescribeLoadBalancerPolicyTypes"/>
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeLoadBalancerPolicyTypes.</param>
///
/// <returns>Returns a DescribeLoadBalancerPolicyTypesResult from AmazonElasticLoadBalancing.</returns>
public DescribeLoadBalancerPolicyTypesResponse EndDescribeLoadBalancerPolicyTypes(IAsyncResult asyncResult)
{
return endOperation<DescribeLoadBalancerPolicyTypesResponse>(asyncResult);
}
IAsyncResult invokeDescribeLoadBalancerPolicyTypes(DescribeLoadBalancerPolicyTypesRequest describeLoadBalancerPolicyTypesRequest, AsyncCallback callback, object state, bool synchronized)
{
IRequest irequest = new DescribeLoadBalancerPolicyTypesRequestMarshaller().Marshall(describeLoadBalancerPolicyTypesRequest);
var unmarshaller = DescribeLoadBalancerPolicyTypesResponseUnmarshaller.GetInstance();
AsyncResult result = new AsyncResult(irequest, callback, state, synchronized, signer, unmarshaller);
Invoke(result);
return result;
}
/// <summary>
/// <para> Returns meta-information on the specified LoadBalancer policies defined by the Elastic Load Balancing service. The policy types that
/// are returned from this action can be used in a CreateLoadBalancerPolicy action to instantiate specific policy configurations that will be
/// applied to an Elastic LoadBalancer. </para>
/// </summary>
///
/// <returns>The response from the DescribeLoadBalancerPolicyTypes service method, as returned by AmazonElasticLoadBalancing.</returns>
///
/// <exception cref="PolicyTypeNotFoundException"/>
public DescribeLoadBalancerPolicyTypesResponse DescribeLoadBalancerPolicyTypes()
{
return DescribeLoadBalancerPolicyTypes(new DescribeLoadBalancerPolicyTypesRequest());
}
#endregion
#region ConfigureHealthCheck
/// <summary>
/// <para> Enables the client to define an application healthcheck for the instances. </para>
/// </summary>
///
/// <param name="configureHealthCheckRequest">Container for the necessary parameters to execute the ConfigureHealthCheck service method on
/// AmazonElasticLoadBalancing.</param>
///
/// <returns>The response from the ConfigureHealthCheck service method, as returned by AmazonElasticLoadBalancing.</returns>
///
/// <exception cref="LoadBalancerNotFoundException"/>
public ConfigureHealthCheckResponse ConfigureHealthCheck(ConfigureHealthCheckRequest configureHealthCheckRequest)
{
IAsyncResult asyncResult = invokeConfigureHealthCheck(configureHealthCheckRequest, null, null, true);
return EndConfigureHealthCheck(asyncResult);
}
/// <summary>
/// Initiates the asynchronous execution of the ConfigureHealthCheck operation.
/// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.ConfigureHealthCheck"/>
/// </summary>
///
/// <param name="configureHealthCheckRequest">Container for the necessary parameters to execute the ConfigureHealthCheck operation on
/// AmazonElasticLoadBalancing.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking
/// EndConfigureHealthCheck operation.</returns>
public IAsyncResult BeginConfigureHealthCheck(ConfigureHealthCheckRequest configureHealthCheckRequest, AsyncCallback callback, object state)
{
return invokeConfigureHealthCheck(configureHealthCheckRequest, callback, state, false);
}
/// <summary>
/// Finishes the asynchronous execution of the ConfigureHealthCheck operation.
/// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.ConfigureHealthCheck"/>
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginConfigureHealthCheck.</param>
///
/// <returns>Returns a ConfigureHealthCheckResult from AmazonElasticLoadBalancing.</returns>
public ConfigureHealthCheckResponse EndConfigureHealthCheck(IAsyncResult asyncResult)
{
return endOperation<ConfigureHealthCheckResponse>(asyncResult);
}
IAsyncResult invokeConfigureHealthCheck(ConfigureHealthCheckRequest configureHealthCheckRequest, AsyncCallback callback, object state, bool synchronized)
{
IRequest irequest = new ConfigureHealthCheckRequestMarshaller().Marshall(configureHealthCheckRequest);
var unmarshaller = ConfigureHealthCheckResponseUnmarshaller.GetInstance();
AsyncResult result = new AsyncResult(irequest, callback, state, synchronized, signer, unmarshaller);
Invoke(result);
return result;
}
#endregion
#region DetachLoadBalancerFromSubnets
/// <summary>
/// <para> Removes subnets from the set of configured subnets in the VPC for the LoadBalancer. </para> <para> After a subnet is removed all of
/// the EndPoints registered with the LoadBalancer that are in the removed subnet will go into the <i>OutOfService</i> state. When a subnet is
/// removed, the LoadBalancer will balance the traffic among the remaining routable subnets for the LoadBalancer. </para>
/// </summary>
///
/// <param name="detachLoadBalancerFromSubnetsRequest">Container for the necessary parameters to execute the DetachLoadBalancerFromSubnets
/// service method on AmazonElasticLoadBalancing.</param>
///
/// <returns>The response from the DetachLoadBalancerFromSubnets service method, as returned by AmazonElasticLoadBalancing.</returns>
///
/// <exception cref="InvalidConfigurationRequestException"/>
/// <exception cref="LoadBalancerNotFoundException"/>
public DetachLoadBalancerFromSubnetsResponse DetachLoadBalancerFromSubnets(DetachLoadBalancerFromSubnetsRequest detachLoadBalancerFromSubnetsRequest)
{
IAsyncResult asyncResult = invokeDetachLoadBalancerFromSubnets(detachLoadBalancerFromSubnetsRequest, null, null, true);
return EndDetachLoadBalancerFromSubnets(asyncResult);
}
/// <summary>
/// Initiates the asynchronous execution of the DetachLoadBalancerFromSubnets operation.
/// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.DetachLoadBalancerFromSubnets"/>
/// </summary>
///
/// <param name="detachLoadBalancerFromSubnetsRequest">Container for the necessary parameters to execute the DetachLoadBalancerFromSubnets
/// operation on AmazonElasticLoadBalancing.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking
/// EndDetachLoadBalancerFromSubnets operation.</returns>
public IAsyncResult BeginDetachLoadBalancerFromSubnets(DetachLoadBalancerFromSubnetsRequest detachLoadBalancerFromSubnetsRequest, AsyncCallback callback, object state)
{
return invokeDetachLoadBalancerFromSubnets(detachLoadBalancerFromSubnetsRequest, callback, state, false);
}
/// <summary>
/// Finishes the asynchronous execution of the DetachLoadBalancerFromSubnets operation.
/// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.DetachLoadBalancerFromSubnets"/>
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginDetachLoadBalancerFromSubnets.</param>
///
/// <returns>Returns a DetachLoadBalancerFromSubnetsResult from AmazonElasticLoadBalancing.</returns>
public DetachLoadBalancerFromSubnetsResponse EndDetachLoadBalancerFromSubnets(IAsyncResult asyncResult)
{
return endOperation<DetachLoadBalancerFromSubnetsResponse>(asyncResult);
}
IAsyncResult invokeDetachLoadBalancerFromSubnets(DetachLoadBalancerFromSubnetsRequest detachLoadBalancerFromSubnetsRequest, AsyncCallback callback, object state, bool synchronized)
{
IRequest irequest = new DetachLoadBalancerFromSubnetsRequestMarshaller().Marshall(detachLoadBalancerFromSubnetsRequest);
var unmarshaller = DetachLoadBalancerFromSubnetsResponseUnmarshaller.GetInstance();
AsyncResult result = new AsyncResult(irequest, callback, state, synchronized, signer, unmarshaller);
Invoke(result);
return result;
}
#endregion
#region DescribeLoadBalancerPolicies
/// <summary>
/// <para>Returns detailed descriptions of the policies. If you specify a LoadBalancer name, the operation returns either the descriptions of
/// the specified policies, or descriptions of all the policies created for the LoadBalancer. If you don't specify a LoadBalancer name, the
/// operation returns descriptions of the specified sample policies, or descriptions of all the sample policies. The names of the sample
/// policies have the <c>ELBSample-</c> prefix. </para>
/// </summary>
///
/// <param name="describeLoadBalancerPoliciesRequest">Container for the necessary parameters to execute the DescribeLoadBalancerPolicies service
/// method on AmazonElasticLoadBalancing.</param>
///
/// <returns>The response from the DescribeLoadBalancerPolicies service method, as returned by AmazonElasticLoadBalancing.</returns>
///
/// <exception cref="PolicyNotFoundException"/>
/// <exception cref="LoadBalancerNotFoundException"/>
public DescribeLoadBalancerPoliciesResponse DescribeLoadBalancerPolicies(DescribeLoadBalancerPoliciesRequest describeLoadBalancerPoliciesRequest)
{
IAsyncResult asyncResult = invokeDescribeLoadBalancerPolicies(describeLoadBalancerPoliciesRequest, null, null, true);
return EndDescribeLoadBalancerPolicies(asyncResult);
}
/// <summary>
/// Initiates the asynchronous execution of the DescribeLoadBalancerPolicies operation.
/// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.DescribeLoadBalancerPolicies"/>
/// </summary>
///
/// <param name="describeLoadBalancerPoliciesRequest">Container for the necessary parameters to execute the DescribeLoadBalancerPolicies
/// operation on AmazonElasticLoadBalancing.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking
/// EndDescribeLoadBalancerPolicies operation.</returns>
public IAsyncResult BeginDescribeLoadBalancerPolicies(DescribeLoadBalancerPoliciesRequest describeLoadBalancerPoliciesRequest, AsyncCallback callback, object state)
{
return invokeDescribeLoadBalancerPolicies(describeLoadBalancerPoliciesRequest, callback, state, false);
}
/// <summary>
/// Finishes the asynchronous execution of the DescribeLoadBalancerPolicies operation.
/// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.DescribeLoadBalancerPolicies"/>
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeLoadBalancerPolicies.</param>
///
/// <returns>Returns a DescribeLoadBalancerPoliciesResult from AmazonElasticLoadBalancing.</returns>
public DescribeLoadBalancerPoliciesResponse EndDescribeLoadBalancerPolicies(IAsyncResult asyncResult)
{
return endOperation<DescribeLoadBalancerPoliciesResponse>(asyncResult);
}
IAsyncResult invokeDescribeLoadBalancerPolicies(DescribeLoadBalancerPoliciesRequest describeLoadBalancerPoliciesRequest, AsyncCallback callback, object state, bool synchronized)
{
IRequest irequest = new DescribeLoadBalancerPoliciesRequestMarshaller().Marshall(describeLoadBalancerPoliciesRequest);
var unmarshaller = DescribeLoadBalancerPoliciesResponseUnmarshaller.GetInstance();
AsyncResult result = new AsyncResult(irequest, callback, state, synchronized, signer, unmarshaller);
Invoke(result);
return result;
}
/// <summary>
/// <para>Returns detailed descriptions of the policies. If you specify a LoadBalancer name, the operation returns either the descriptions of
/// the specified policies, or descriptions of all the policies created for the LoadBalancer. If you don't specify a LoadBalancer name, the
/// operation returns descriptions of the specified sample policies, or descriptions of all the sample policies. The names of the sample
/// policies have the <c>ELBSample-</c> prefix. </para>
/// </summary>
///
/// <returns>The response from the DescribeLoadBalancerPolicies service method, as returned by AmazonElasticLoadBalancing.</returns>
///
/// <exception cref="PolicyNotFoundException"/>
/// <exception cref="LoadBalancerNotFoundException"/>
public DescribeLoadBalancerPoliciesResponse DescribeLoadBalancerPolicies()
{
return DescribeLoadBalancerPolicies(new DescribeLoadBalancerPoliciesRequest());
}
#endregion
#region SetLoadBalancerPoliciesOfListener
/// <summary>
/// <para> Associates, updates, or disables a policy with a listener on the LoadBalancer. You can associate multiple policies with a listener.
/// </para>
/// </summary>
///
/// <param name="setLoadBalancerPoliciesOfListenerRequest">Container for the necessary parameters to execute the
/// SetLoadBalancerPoliciesOfListener service method on AmazonElasticLoadBalancing.</param>
///
/// <returns>The response from the SetLoadBalancerPoliciesOfListener service method, as returned by AmazonElasticLoadBalancing.</returns>
///
/// <exception cref="PolicyNotFoundException"/>
/// <exception cref="InvalidConfigurationRequestException"/>
/// <exception cref="LoadBalancerNotFoundException"/>
/// <exception cref="ListenerNotFoundException"/>
public SetLoadBalancerPoliciesOfListenerResponse SetLoadBalancerPoliciesOfListener(SetLoadBalancerPoliciesOfListenerRequest setLoadBalancerPoliciesOfListenerRequest)
{
IAsyncResult asyncResult = invokeSetLoadBalancerPoliciesOfListener(setLoadBalancerPoliciesOfListenerRequest, null, null, true);
return EndSetLoadBalancerPoliciesOfListener(asyncResult);
}
/// <summary>
/// Initiates the asynchronous execution of the SetLoadBalancerPoliciesOfListener operation.
/// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.SetLoadBalancerPoliciesOfListener"/>
/// </summary>
///
/// <param name="setLoadBalancerPoliciesOfListenerRequest">Container for the necessary parameters to execute the
/// SetLoadBalancerPoliciesOfListener operation on AmazonElasticLoadBalancing.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking
/// EndSetLoadBalancerPoliciesOfListener operation.</returns>
public IAsyncResult BeginSetLoadBalancerPoliciesOfListener(SetLoadBalancerPoliciesOfListenerRequest setLoadBalancerPoliciesOfListenerRequest, AsyncCallback callback, object state)
{
return invokeSetLoadBalancerPoliciesOfListener(setLoadBalancerPoliciesOfListenerRequest, callback, state, false);
}
/// <summary>
/// Finishes the asynchronous execution of the SetLoadBalancerPoliciesOfListener operation.
/// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.SetLoadBalancerPoliciesOfListener"/>
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginSetLoadBalancerPoliciesOfListener.</param>
///
/// <returns>Returns a SetLoadBalancerPoliciesOfListenerResult from AmazonElasticLoadBalancing.</returns>
public SetLoadBalancerPoliciesOfListenerResponse EndSetLoadBalancerPoliciesOfListener(IAsyncResult asyncResult)
{
return endOperation<SetLoadBalancerPoliciesOfListenerResponse>(asyncResult);
}
IAsyncResult invokeSetLoadBalancerPoliciesOfListener(SetLoadBalancerPoliciesOfListenerRequest setLoadBalancerPoliciesOfListenerRequest, AsyncCallback callback, object state, bool synchronized)
{
IRequest irequest = new SetLoadBalancerPoliciesOfListenerRequestMarshaller().Marshall(setLoadBalancerPoliciesOfListenerRequest);
var unmarshaller = SetLoadBalancerPoliciesOfListenerResponseUnmarshaller.GetInstance();
AsyncResult result = new AsyncResult(irequest, callback, state, synchronized, signer, unmarshaller);
Invoke(result);
return result;
}
#endregion
#region DisableAvailabilityZonesForLoadBalancer
/// <summary>
/// <para> Removes the specified EC2 Availability Zones from the set of configured Availability Zones for the LoadBalancer. </para> <para> There
/// must be at least one Availability Zone registered with a LoadBalancer at all times. A client cannot remove all the Availability Zones from a
/// LoadBalancer. Once an Availability Zone is removed, all the instances registered with the LoadBalancer that are in the removed Availability
/// Zone go into the OutOfService state. Upon Availability Zone removal, the LoadBalancer attempts to equally balance the traffic among its
/// remaining usable Availability Zones. Trying to remove an Availability Zone that was not associated with the LoadBalancer does nothing.
/// </para> <para><b>NOTE:</b> In order for this call to be successful, the client must have created the LoadBalancer. The client must provide
/// the same account credentials as those that were used to create the LoadBalancer. </para>
/// </summary>
///
/// <param name="disableAvailabilityZonesForLoadBalancerRequest">Container for the necessary parameters to execute the
/// DisableAvailabilityZonesForLoadBalancer service method on AmazonElasticLoadBalancing.</param>
///
/// <returns>The response from the DisableAvailabilityZonesForLoadBalancer service method, as returned by AmazonElasticLoadBalancing.</returns>
///
/// <exception cref="InvalidConfigurationRequestException"/>
/// <exception cref="LoadBalancerNotFoundException"/>
public DisableAvailabilityZonesForLoadBalancerResponse DisableAvailabilityZonesForLoadBalancer(DisableAvailabilityZonesForLoadBalancerRequest disableAvailabilityZonesForLoadBalancerRequest)
{
IAsyncResult asyncResult = invokeDisableAvailabilityZonesForLoadBalancer(disableAvailabilityZonesForLoadBalancerRequest, null, null, true);
return EndDisableAvailabilityZonesForLoadBalancer(asyncResult);
}
/// <summary>
/// Initiates the asynchronous execution of the DisableAvailabilityZonesForLoadBalancer operation.
/// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.DisableAvailabilityZonesForLoadBalancer"/>
/// </summary>
///
/// <param name="disableAvailabilityZonesForLoadBalancerRequest">Container for the necessary parameters to execute the
/// DisableAvailabilityZonesForLoadBalancer operation on AmazonElasticLoadBalancing.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking
/// EndDisableAvailabilityZonesForLoadBalancer operation.</returns>
public IAsyncResult BeginDisableAvailabilityZonesForLoadBalancer(DisableAvailabilityZonesForLoadBalancerRequest disableAvailabilityZonesForLoadBalancerRequest, AsyncCallback callback, object state)
{
return invokeDisableAvailabilityZonesForLoadBalancer(disableAvailabilityZonesForLoadBalancerRequest, callback, state, false);
}
/// <summary>
/// Finishes the asynchronous execution of the DisableAvailabilityZonesForLoadBalancer operation.
/// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.DisableAvailabilityZonesForLoadBalancer"/>
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginDisableAvailabilityZonesForLoadBalancer.</param>
///
/// <returns>Returns a DisableAvailabilityZonesForLoadBalancerResult from AmazonElasticLoadBalancing.</returns>
public DisableAvailabilityZonesForLoadBalancerResponse EndDisableAvailabilityZonesForLoadBalancer(IAsyncResult asyncResult)
{
return endOperation<DisableAvailabilityZonesForLoadBalancerResponse>(asyncResult);
}
IAsyncResult invokeDisableAvailabilityZonesForLoadBalancer(DisableAvailabilityZonesForLoadBalancerRequest disableAvailabilityZonesForLoadBalancerRequest, AsyncCallback callback, object state, bool synchronized)
{
IRequest irequest = new DisableAvailabilityZonesForLoadBalancerRequestMarshaller().Marshall(disableAvailabilityZonesForLoadBalancerRequest);
var unmarshaller = DisableAvailabilityZonesForLoadBalancerResponseUnmarshaller.GetInstance();
AsyncResult result = new AsyncResult(irequest, callback, state, synchronized, signer, unmarshaller);
Invoke(result);
return result;
}
#endregion
#region DescribeInstanceHealth
/// <summary>
/// <para> Returns the current state of the instances of the specified LoadBalancer. If no instances are specified, the state of all the
/// instances for the LoadBalancer is returned. </para> <para><b>NOTE:</b> The client must have created the specified input LoadBalancer in
/// order to retrieve this information; the client must provide the same account credentials as those that were used to create the LoadBalancer.
/// </para>
/// </summary>
///
/// <param name="describeInstanceHealthRequest">Container for the necessary parameters to execute the DescribeInstanceHealth service method on
/// AmazonElasticLoadBalancing.</param>
///
/// <returns>The response from the DescribeInstanceHealth service method, as returned by AmazonElasticLoadBalancing.</returns>
///
/// <exception cref="LoadBalancerNotFoundException"/>
/// <exception cref="InvalidInstanceException"/>
public DescribeInstanceHealthResponse DescribeInstanceHealth(DescribeInstanceHealthRequest describeInstanceHealthRequest)
{
IAsyncResult asyncResult = invokeDescribeInstanceHealth(describeInstanceHealthRequest, null, null, true);
return EndDescribeInstanceHealth(asyncResult);
}
/// <summary>
/// Initiates the asynchronous execution of the DescribeInstanceHealth operation.
/// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.DescribeInstanceHealth"/>
/// </summary>
///
/// <param name="describeInstanceHealthRequest">Container for the necessary parameters to execute the DescribeInstanceHealth operation on
/// AmazonElasticLoadBalancing.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking
/// EndDescribeInstanceHealth operation.</returns>
public IAsyncResult BeginDescribeInstanceHealth(DescribeInstanceHealthRequest describeInstanceHealthRequest, AsyncCallback callback, object state)
{
return invokeDescribeInstanceHealth(describeInstanceHealthRequest, callback, state, false);
}
/// <summary>
/// Finishes the asynchronous execution of the DescribeInstanceHealth operation.
/// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.DescribeInstanceHealth"/>
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeInstanceHealth.</param>
///
/// <returns>Returns a DescribeInstanceHealthResult from AmazonElasticLoadBalancing.</returns>
public DescribeInstanceHealthResponse EndDescribeInstanceHealth(IAsyncResult asyncResult)
{
return endOperation<DescribeInstanceHealthResponse>(asyncResult);
}
IAsyncResult invokeDescribeInstanceHealth(DescribeInstanceHealthRequest describeInstanceHealthRequest, AsyncCallback callback, object state, bool synchronized)
{
IRequest irequest = new DescribeInstanceHealthRequestMarshaller().Marshall(describeInstanceHealthRequest);
var unmarshaller = DescribeInstanceHealthResponseUnmarshaller.GetInstance();
AsyncResult result = new AsyncResult(irequest, callback, state, synchronized, signer, unmarshaller);
Invoke(result);
return result;
}
#endregion
#region DeleteLoadBalancerPolicy
/// <summary>
/// <para> Deletes a policy from the LoadBalancer. The specified policy must not be enabled for any listeners. </para>
/// </summary>
///
/// <param name="deleteLoadBalancerPolicyRequest">Container for the necessary parameters to execute the DeleteLoadBalancerPolicy service method
/// on AmazonElasticLoadBalancing.</param>
///
/// <returns>The response from the DeleteLoadBalancerPolicy service method, as returned by AmazonElasticLoadBalancing.</returns>
///
/// <exception cref="InvalidConfigurationRequestException"/>
/// <exception cref="LoadBalancerNotFoundException"/>
public DeleteLoadBalancerPolicyResponse DeleteLoadBalancerPolicy(DeleteLoadBalancerPolicyRequest deleteLoadBalancerPolicyRequest)
{
IAsyncResult asyncResult = invokeDeleteLoadBalancerPolicy(deleteLoadBalancerPolicyRequest, null, null, true);
return EndDeleteLoadBalancerPolicy(asyncResult);
}
/// <summary>
/// Initiates the asynchronous execution of the DeleteLoadBalancerPolicy operation.
/// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.DeleteLoadBalancerPolicy"/>
/// </summary>
///
/// <param name="deleteLoadBalancerPolicyRequest">Container for the necessary parameters to execute the DeleteLoadBalancerPolicy operation on
/// AmazonElasticLoadBalancing.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking
/// EndDeleteLoadBalancerPolicy operation.</returns>
public IAsyncResult BeginDeleteLoadBalancerPolicy(DeleteLoadBalancerPolicyRequest deleteLoadBalancerPolicyRequest, AsyncCallback callback, object state)
{
return invokeDeleteLoadBalancerPolicy(deleteLoadBalancerPolicyRequest, callback, state, false);
}
/// <summary>
/// Finishes the asynchronous execution of the DeleteLoadBalancerPolicy operation.
/// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.DeleteLoadBalancerPolicy"/>
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginDeleteLoadBalancerPolicy.</param>
///
/// <returns>Returns a DeleteLoadBalancerPolicyResult from AmazonElasticLoadBalancing.</returns>
public DeleteLoadBalancerPolicyResponse EndDeleteLoadBalancerPolicy(IAsyncResult asyncResult)
{
return endOperation<DeleteLoadBalancerPolicyResponse>(asyncResult);
}
IAsyncResult invokeDeleteLoadBalancerPolicy(DeleteLoadBalancerPolicyRequest deleteLoadBalancerPolicyRequest, AsyncCallback callback, object state, bool synchronized)
{
IRequest irequest = new DeleteLoadBalancerPolicyRequestMarshaller().Marshall(deleteLoadBalancerPolicyRequest);
var unmarshaller = DeleteLoadBalancerPolicyResponseUnmarshaller.GetInstance();
AsyncResult result = new AsyncResult(irequest, callback, state, synchronized, signer, unmarshaller);
Invoke(result);
return result;
}
#endregion
#region CreateLoadBalancerPolicy
/// <summary>
/// <para> Creates a new policy that contains the necessary attributes depending on the policy type. Policies are settings that are saved for
/// your Elastic LoadBalancer and that can be applied to the front-end listener, or the back-end application server, depending on your policy
/// type. </para>
/// </summary>
///
/// <param name="createLoadBalancerPolicyRequest">Container for the necessary parameters to execute the CreateLoadBalancerPolicy service method
/// on AmazonElasticLoadBalancing.</param>
///
/// <returns>The response from the CreateLoadBalancerPolicy service method, as returned by AmazonElasticLoadBalancing.</returns>
///
/// <exception cref="PolicyTypeNotFoundException"/>
/// <exception cref="InvalidConfigurationRequestException"/>
/// <exception cref="DuplicatePolicyNameException"/>
/// <exception cref="TooManyPoliciesException"/>
/// <exception cref="LoadBalancerNotFoundException"/>
public CreateLoadBalancerPolicyResponse CreateLoadBalancerPolicy(CreateLoadBalancerPolicyRequest createLoadBalancerPolicyRequest)
{
IAsyncResult asyncResult = invokeCreateLoadBalancerPolicy(createLoadBalancerPolicyRequest, null, null, true);
return EndCreateLoadBalancerPolicy(asyncResult);
}
/// <summary>
/// Initiates the asynchronous execution of the CreateLoadBalancerPolicy operation.
/// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.CreateLoadBalancerPolicy"/>
/// </summary>
///
/// <param name="createLoadBalancerPolicyRequest">Container for the necessary parameters to execute the CreateLoadBalancerPolicy operation on
/// AmazonElasticLoadBalancing.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking
/// EndCreateLoadBalancerPolicy operation.</returns>
public IAsyncResult BeginCreateLoadBalancerPolicy(CreateLoadBalancerPolicyRequest createLoadBalancerPolicyRequest, AsyncCallback callback, object state)
{
return invokeCreateLoadBalancerPolicy(createLoadBalancerPolicyRequest, callback, state, false);
}
/// <summary>
/// Finishes the asynchronous execution of the CreateLoadBalancerPolicy operation.
/// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.CreateLoadBalancerPolicy"/>
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginCreateLoadBalancerPolicy.</param>
///
/// <returns>Returns a CreateLoadBalancerPolicyResult from AmazonElasticLoadBalancing.</returns>
public CreateLoadBalancerPolicyResponse EndCreateLoadBalancerPolicy(IAsyncResult asyncResult)
{
return endOperation<CreateLoadBalancerPolicyResponse>(asyncResult);
}
IAsyncResult invokeCreateLoadBalancerPolicy(CreateLoadBalancerPolicyRequest createLoadBalancerPolicyRequest, AsyncCallback callback, object state, bool synchronized)
{
IRequest irequest = new CreateLoadBalancerPolicyRequestMarshaller().Marshall(createLoadBalancerPolicyRequest);
var unmarshaller = CreateLoadBalancerPolicyResponseUnmarshaller.GetInstance();
AsyncResult result = new AsyncResult(irequest, callback, state, synchronized, signer, unmarshaller);
Invoke(result);
return result;
}
#endregion
#region EnableAvailabilityZonesForLoadBalancer
/// <summary>
/// <para> Adds one or more EC2 Availability Zones to the LoadBalancer. </para> <para> The LoadBalancer evenly distributes requests across all
/// its registered Availability Zones that contain instances. As a result, the client must ensure that its LoadBalancer is appropriately scaled
/// for each registered Availability Zone. </para> <para><b>NOTE:</b> The new EC2 Availability Zones to be added must be in the same EC2 Region
/// as the Availability Zones for which the LoadBalancer was created. </para>
/// </summary>
///
/// <param name="enableAvailabilityZonesForLoadBalancerRequest">Container for the necessary parameters to execute the
/// EnableAvailabilityZonesForLoadBalancer service method on AmazonElasticLoadBalancing.</param>
///
/// <returns>The response from the EnableAvailabilityZonesForLoadBalancer service method, as returned by AmazonElasticLoadBalancing.</returns>
///
/// <exception cref="LoadBalancerNotFoundException"/>
public EnableAvailabilityZonesForLoadBalancerResponse EnableAvailabilityZonesForLoadBalancer(EnableAvailabilityZonesForLoadBalancerRequest enableAvailabilityZonesForLoadBalancerRequest)
{
IAsyncResult asyncResult = invokeEnableAvailabilityZonesForLoadBalancer(enableAvailabilityZonesForLoadBalancerRequest, null, null, true);
return EndEnableAvailabilityZonesForLoadBalancer(asyncResult);
}
/// <summary>
/// Initiates the asynchronous execution of the EnableAvailabilityZonesForLoadBalancer operation.
/// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.EnableAvailabilityZonesForLoadBalancer"/>
/// </summary>
///
/// <param name="enableAvailabilityZonesForLoadBalancerRequest">Container for the necessary parameters to execute the
/// EnableAvailabilityZonesForLoadBalancer operation on AmazonElasticLoadBalancing.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking
/// EndEnableAvailabilityZonesForLoadBalancer operation.</returns>
public IAsyncResult BeginEnableAvailabilityZonesForLoadBalancer(EnableAvailabilityZonesForLoadBalancerRequest enableAvailabilityZonesForLoadBalancerRequest, AsyncCallback callback, object state)
{
return invokeEnableAvailabilityZonesForLoadBalancer(enableAvailabilityZonesForLoadBalancerRequest, callback, state, false);
}
/// <summary>
/// Finishes the asynchronous execution of the EnableAvailabilityZonesForLoadBalancer operation.
/// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.EnableAvailabilityZonesForLoadBalancer"/>
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginEnableAvailabilityZonesForLoadBalancer.</param>
///
/// <returns>Returns a EnableAvailabilityZonesForLoadBalancerResult from AmazonElasticLoadBalancing.</returns>
public EnableAvailabilityZonesForLoadBalancerResponse EndEnableAvailabilityZonesForLoadBalancer(IAsyncResult asyncResult)
{
return endOperation<EnableAvailabilityZonesForLoadBalancerResponse>(asyncResult);
}
IAsyncResult invokeEnableAvailabilityZonesForLoadBalancer(EnableAvailabilityZonesForLoadBalancerRequest enableAvailabilityZonesForLoadBalancerRequest, AsyncCallback callback, object state, bool synchronized)
{
IRequest irequest = new EnableAvailabilityZonesForLoadBalancerRequestMarshaller().Marshall(enableAvailabilityZonesForLoadBalancerRequest);
var unmarshaller = EnableAvailabilityZonesForLoadBalancerResponseUnmarshaller.GetInstance();
AsyncResult result = new AsyncResult(irequest, callback, state, synchronized, signer, unmarshaller);
Invoke(result);
return result;
}
#endregion
#region CreateLoadBalancerListeners
/// <summary>
/// <para> Creates one or more listeners on a LoadBalancer for the specified port. If a listener with the given port does not already exist, it
/// will be created; otherwise, the properties of the new listener must match the properties of the existing listener. </para>
/// </summary>
///
/// <param name="createLoadBalancerListenersRequest">Container for the necessary parameters to execute the CreateLoadBalancerListeners service
/// method on AmazonElasticLoadBalancing.</param>
///
/// <returns>The response from the CreateLoadBalancerListeners service method, as returned by AmazonElasticLoadBalancing.</returns>
///
/// <exception cref="InvalidConfigurationRequestException"/>
/// <exception cref="DuplicateListenerException"/>
/// <exception cref="CertificateNotFoundException"/>
/// <exception cref="LoadBalancerNotFoundException"/>
public CreateLoadBalancerListenersResponse CreateLoadBalancerListeners(CreateLoadBalancerListenersRequest createLoadBalancerListenersRequest)
{
IAsyncResult asyncResult = invokeCreateLoadBalancerListeners(createLoadBalancerListenersRequest, null, null, true);
return EndCreateLoadBalancerListeners(asyncResult);
}
/// <summary>
/// Initiates the asynchronous execution of the CreateLoadBalancerListeners operation.
/// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.CreateLoadBalancerListeners"/>
/// </summary>
///
/// <param name="createLoadBalancerListenersRequest">Container for the necessary parameters to execute the CreateLoadBalancerListeners operation
/// on AmazonElasticLoadBalancing.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking
/// EndCreateLoadBalancerListeners operation.</returns>
public IAsyncResult BeginCreateLoadBalancerListeners(CreateLoadBalancerListenersRequest createLoadBalancerListenersRequest, AsyncCallback callback, object state)
{
return invokeCreateLoadBalancerListeners(createLoadBalancerListenersRequest, callback, state, false);
}
/// <summary>
/// Finishes the asynchronous execution of the CreateLoadBalancerListeners operation.
/// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.CreateLoadBalancerListeners"/>
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginCreateLoadBalancerListeners.</param>
///
/// <returns>Returns a CreateLoadBalancerListenersResult from AmazonElasticLoadBalancing.</returns>
public CreateLoadBalancerListenersResponse EndCreateLoadBalancerListeners(IAsyncResult asyncResult)
{
return endOperation<CreateLoadBalancerListenersResponse>(asyncResult);
}
IAsyncResult invokeCreateLoadBalancerListeners(CreateLoadBalancerListenersRequest createLoadBalancerListenersRequest, AsyncCallback callback, object state, bool synchronized)
{
IRequest irequest = new CreateLoadBalancerListenersRequestMarshaller().Marshall(createLoadBalancerListenersRequest);
var unmarshaller = CreateLoadBalancerListenersResponseUnmarshaller.GetInstance();
AsyncResult result = new AsyncResult(irequest, callback, state, synchronized, signer, unmarshaller);
Invoke(result);
return result;
}
#endregion
#region CreateLoadBalancer
/// <summary>
/// <para> Creates a new LoadBalancer. </para> <para> After the call has completed successfully, a new LoadBalancer is created; however, it will
/// not be usable until at least one instance has been registered. When the LoadBalancer creation is completed, the client can check whether or
/// not it is usable by using the DescribeInstanceHealth action. The LoadBalancer is usable as soon as any registered instance is
/// <i>InService</i> .
/// </para> <para><b>NOTE:</b> Currently, the client's quota of LoadBalancers is limited to ten per Region. </para> <para><b>NOTE:</b>
/// LoadBalancer DNS names vary depending on the Region they're created in. For LoadBalancers created in the United States, the DNS name ends
/// with: us-east-1.elb.amazonaws.com (for the US Standard Region) us-west-1.elb.amazonaws.com (for the Northern California Region) For
/// LoadBalancers created in the EU (Ireland) Region, the DNS name ends with: eu-west-1.elb.amazonaws.com </para> <para>For information on using
/// CreateLoadBalancer to create a new LoadBalancer in Amazon EC2, go to Using Query API section in the <i>Creating a Load Balancer With SSL
/// Cipher Settings and Back-end Authentication</i> topic of the <i>Elastic Load Balancing Developer Guide</i> .</para> <para>For information on
/// using CreateLoadBalancer to create a new LoadBalancer in Amazon VPC, go to Using Query API section in the <i>Creating a Basic Load Balancer
/// in Amazon VPC</i> topic of the <i>Elastic Load Balancing Developer Guide</i> .</para>
/// </summary>
///
/// <param name="createLoadBalancerRequest">Container for the necessary parameters to execute the CreateLoadBalancer service method on
/// AmazonElasticLoadBalancing.</param>
///
/// <returns>The response from the CreateLoadBalancer service method, as returned by AmazonElasticLoadBalancing.</returns>
///
/// <exception cref="InvalidSubnetException"/>
/// <exception cref="InvalidConfigurationRequestException"/>
/// <exception cref="InvalidSecurityGroupException"/>
/// <exception cref="CertificateNotFoundException"/>
/// <exception cref="InvalidSchemeException"/>
/// <exception cref="DuplicateLoadBalancerNameException"/>
/// <exception cref="TooManyLoadBalancersException"/>
/// <exception cref="SubnetNotFoundException"/>
public CreateLoadBalancerResponse CreateLoadBalancer(CreateLoadBalancerRequest createLoadBalancerRequest)
{
IAsyncResult asyncResult = invokeCreateLoadBalancer(createLoadBalancerRequest, null, null, true);
return EndCreateLoadBalancer(asyncResult);
}
/// <summary>
/// Initiates the asynchronous execution of the CreateLoadBalancer operation.
/// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.CreateLoadBalancer"/>
/// </summary>
///
/// <param name="createLoadBalancerRequest">Container for the necessary parameters to execute the CreateLoadBalancer operation on
/// AmazonElasticLoadBalancing.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking
/// EndCreateLoadBalancer operation.</returns>
public IAsyncResult BeginCreateLoadBalancer(CreateLoadBalancerRequest createLoadBalancerRequest, AsyncCallback callback, object state)
{
return invokeCreateLoadBalancer(createLoadBalancerRequest, callback, state, false);
}
/// <summary>
/// Finishes the asynchronous execution of the CreateLoadBalancer operation.
/// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.CreateLoadBalancer"/>
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginCreateLoadBalancer.</param>
///
/// <returns>Returns a CreateLoadBalancerResult from AmazonElasticLoadBalancing.</returns>
public CreateLoadBalancerResponse EndCreateLoadBalancer(IAsyncResult asyncResult)
{
return endOperation<CreateLoadBalancerResponse>(asyncResult);
}
IAsyncResult invokeCreateLoadBalancer(CreateLoadBalancerRequest createLoadBalancerRequest, AsyncCallback callback, object state, bool synchronized)
{
IRequest irequest = new CreateLoadBalancerRequestMarshaller().Marshall(createLoadBalancerRequest);
var unmarshaller = CreateLoadBalancerResponseUnmarshaller.GetInstance();
AsyncResult result = new AsyncResult(irequest, callback, state, synchronized, signer, unmarshaller);
Invoke(result);
return result;
}
#endregion
#region DeleteLoadBalancer
/// <summary>
/// <para> Deletes the specified LoadBalancer. </para> <para> If attempting to recreate the LoadBalancer, the client must reconfigure all the
/// settings. The DNS name associated with a deleted LoadBalancer will no longer be usable. Once deleted, the name and associated DNS record of
/// the LoadBalancer no longer exist and traffic sent to any of its IP addresses will no longer be delivered to client instances. The client
/// will not receive the same DNS name even if a new LoadBalancer with same LoadBalancerName is created. </para> <para> To successfully call
/// this API, the client must provide the same account credentials as were used to create the LoadBalancer. </para> <para><b>NOTE:</b> By
/// design, if the LoadBalancer does not exist or has already been deleted, DeleteLoadBalancer still succeeds. </para>
/// </summary>
///
/// <param name="deleteLoadBalancerRequest">Container for the necessary parameters to execute the DeleteLoadBalancer service method on
/// AmazonElasticLoadBalancing.</param>
///
/// <returns>The response from the DeleteLoadBalancer service method, as returned by AmazonElasticLoadBalancing.</returns>
///
public DeleteLoadBalancerResponse DeleteLoadBalancer(DeleteLoadBalancerRequest deleteLoadBalancerRequest)
{
IAsyncResult asyncResult = invokeDeleteLoadBalancer(deleteLoadBalancerRequest, null, null, true);
return EndDeleteLoadBalancer(asyncResult);
}
/// <summary>
/// Initiates the asynchronous execution of the DeleteLoadBalancer operation.
/// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.DeleteLoadBalancer"/>
/// </summary>
///
/// <param name="deleteLoadBalancerRequest">Container for the necessary parameters to execute the DeleteLoadBalancer operation on
/// AmazonElasticLoadBalancing.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking
/// EndDeleteLoadBalancer operation.</returns>
public IAsyncResult BeginDeleteLoadBalancer(DeleteLoadBalancerRequest deleteLoadBalancerRequest, AsyncCallback callback, object state)
{
return invokeDeleteLoadBalancer(deleteLoadBalancerRequest, callback, state, false);
}
/// <summary>
/// Finishes the asynchronous execution of the DeleteLoadBalancer operation.
/// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.DeleteLoadBalancer"/>
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginDeleteLoadBalancer.</param>
///
/// <returns>Returns a DeleteLoadBalancerResult from AmazonElasticLoadBalancing.</returns>
public DeleteLoadBalancerResponse EndDeleteLoadBalancer(IAsyncResult asyncResult)
{
return endOperation<DeleteLoadBalancerResponse>(asyncResult);
}
IAsyncResult invokeDeleteLoadBalancer(DeleteLoadBalancerRequest deleteLoadBalancerRequest, AsyncCallback callback, object state, bool synchronized)
{
IRequest irequest = new DeleteLoadBalancerRequestMarshaller().Marshall(deleteLoadBalancerRequest);
var unmarshaller = DeleteLoadBalancerResponseUnmarshaller.GetInstance();
AsyncResult result = new AsyncResult(irequest, callback, state, synchronized, signer, unmarshaller);
Invoke(result);
return result;
}
#endregion
#region SetLoadBalancerPoliciesForBackendServer
/// <summary>
/// <para> Replaces the current set of policies associated with a port on which the back-end server is listening with a new set of policies.
/// After the policies have been created using CreateLoadBalancerPolicy, they can be applied here as a list. At this time, only the back-end
/// server authentication policy type can be applied to the back-end ports; this policy type is composed of multiple public key policies.
/// </para>
/// </summary>
///
/// <param name="setLoadBalancerPoliciesForBackendServerRequest">Container for the necessary parameters to execute the
/// SetLoadBalancerPoliciesForBackendServer service method on AmazonElasticLoadBalancing.</param>
///
/// <returns>The response from the SetLoadBalancerPoliciesForBackendServer service method, as returned by AmazonElasticLoadBalancing.</returns>
///
/// <exception cref="PolicyNotFoundException"/>
/// <exception cref="InvalidConfigurationRequestException"/>
/// <exception cref="LoadBalancerNotFoundException"/>
public SetLoadBalancerPoliciesForBackendServerResponse SetLoadBalancerPoliciesForBackendServer(SetLoadBalancerPoliciesForBackendServerRequest setLoadBalancerPoliciesForBackendServerRequest)
{
IAsyncResult asyncResult = invokeSetLoadBalancerPoliciesForBackendServer(setLoadBalancerPoliciesForBackendServerRequest, null, null, true);
return EndSetLoadBalancerPoliciesForBackendServer(asyncResult);
}
/// <summary>
/// Initiates the asynchronous execution of the SetLoadBalancerPoliciesForBackendServer operation.
/// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.SetLoadBalancerPoliciesForBackendServer"/>
/// </summary>
///
/// <param name="setLoadBalancerPoliciesForBackendServerRequest">Container for the necessary parameters to execute the
/// SetLoadBalancerPoliciesForBackendServer operation on AmazonElasticLoadBalancing.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking
/// EndSetLoadBalancerPoliciesForBackendServer operation.</returns>
public IAsyncResult BeginSetLoadBalancerPoliciesForBackendServer(SetLoadBalancerPoliciesForBackendServerRequest setLoadBalancerPoliciesForBackendServerRequest, AsyncCallback callback, object state)
{
return invokeSetLoadBalancerPoliciesForBackendServer(setLoadBalancerPoliciesForBackendServerRequest, callback, state, false);
}
/// <summary>
/// Finishes the asynchronous execution of the SetLoadBalancerPoliciesForBackendServer operation.
/// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.SetLoadBalancerPoliciesForBackendServer"/>
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginSetLoadBalancerPoliciesForBackendServer.</param>
///
/// <returns>Returns a SetLoadBalancerPoliciesForBackendServerResult from AmazonElasticLoadBalancing.</returns>
public SetLoadBalancerPoliciesForBackendServerResponse EndSetLoadBalancerPoliciesForBackendServer(IAsyncResult asyncResult)
{
return endOperation<SetLoadBalancerPoliciesForBackendServerResponse>(asyncResult);
}
IAsyncResult invokeSetLoadBalancerPoliciesForBackendServer(SetLoadBalancerPoliciesForBackendServerRequest setLoadBalancerPoliciesForBackendServerRequest, AsyncCallback callback, object state, bool synchronized)
{
IRequest irequest = new SetLoadBalancerPoliciesForBackendServerRequestMarshaller().Marshall(setLoadBalancerPoliciesForBackendServerRequest);
var unmarshaller = SetLoadBalancerPoliciesForBackendServerResponseUnmarshaller.GetInstance();
AsyncResult result = new AsyncResult(irequest, callback, state, synchronized, signer, unmarshaller);
Invoke(result);
return result;
}
#endregion
#region DeleteLoadBalancerListeners
/// <summary>
/// <para> Deletes listeners from the LoadBalancer for the specified port. </para>
/// </summary>
///
/// <param name="deleteLoadBalancerListenersRequest">Container for the necessary parameters to execute the DeleteLoadBalancerListeners service
/// method on AmazonElasticLoadBalancing.</param>
///
/// <returns>The response from the DeleteLoadBalancerListeners service method, as returned by AmazonElasticLoadBalancing.</returns>
///
/// <exception cref="LoadBalancerNotFoundException"/>
public DeleteLoadBalancerListenersResponse DeleteLoadBalancerListeners(DeleteLoadBalancerListenersRequest deleteLoadBalancerListenersRequest)
{
IAsyncResult asyncResult = invokeDeleteLoadBalancerListeners(deleteLoadBalancerListenersRequest, null, null, true);
return EndDeleteLoadBalancerListeners(asyncResult);
}
/// <summary>
/// Initiates the asynchronous execution of the DeleteLoadBalancerListeners operation.
/// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.DeleteLoadBalancerListeners"/>
/// </summary>
///
/// <param name="deleteLoadBalancerListenersRequest">Container for the necessary parameters to execute the DeleteLoadBalancerListeners operation
/// on AmazonElasticLoadBalancing.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking
/// EndDeleteLoadBalancerListeners operation.</returns>
public IAsyncResult BeginDeleteLoadBalancerListeners(DeleteLoadBalancerListenersRequest deleteLoadBalancerListenersRequest, AsyncCallback callback, object state)
{
return invokeDeleteLoadBalancerListeners(deleteLoadBalancerListenersRequest, callback, state, false);
}
/// <summary>
/// Finishes the asynchronous execution of the DeleteLoadBalancerListeners operation.
/// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.DeleteLoadBalancerListeners"/>
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginDeleteLoadBalancerListeners.</param>
///
/// <returns>Returns a DeleteLoadBalancerListenersResult from AmazonElasticLoadBalancing.</returns>
public DeleteLoadBalancerListenersResponse EndDeleteLoadBalancerListeners(IAsyncResult asyncResult)
{
return endOperation<DeleteLoadBalancerListenersResponse>(asyncResult);
}
IAsyncResult invokeDeleteLoadBalancerListeners(DeleteLoadBalancerListenersRequest deleteLoadBalancerListenersRequest, AsyncCallback callback, object state, bool synchronized)
{
IRequest irequest = new DeleteLoadBalancerListenersRequestMarshaller().Marshall(deleteLoadBalancerListenersRequest);
var unmarshaller = DeleteLoadBalancerListenersResponseUnmarshaller.GetInstance();
AsyncResult result = new AsyncResult(irequest, callback, state, synchronized, signer, unmarshaller);
Invoke(result);
return result;
}
#endregion
#region DeregisterInstancesFromLoadBalancer
/// <summary>
/// <para> Deregisters instances from the LoadBalancer. Once the instance is deregistered, it will stop receiving traffic from the LoadBalancer.
/// </para> <para> In order to successfully call this API, the same account credentials as those used to create the LoadBalancer must be
/// provided. </para>
/// </summary>
///
/// <param name="deregisterInstancesFromLoadBalancerRequest">Container for the necessary parameters to execute the
/// DeregisterInstancesFromLoadBalancer service method on AmazonElasticLoadBalancing.</param>
///
/// <returns>The response from the DeregisterInstancesFromLoadBalancer service method, as returned by AmazonElasticLoadBalancing.</returns>
///
/// <exception cref="LoadBalancerNotFoundException"/>
/// <exception cref="InvalidInstanceException"/>
public DeregisterInstancesFromLoadBalancerResponse DeregisterInstancesFromLoadBalancer(DeregisterInstancesFromLoadBalancerRequest deregisterInstancesFromLoadBalancerRequest)
{
IAsyncResult asyncResult = invokeDeregisterInstancesFromLoadBalancer(deregisterInstancesFromLoadBalancerRequest, null, null, true);
return EndDeregisterInstancesFromLoadBalancer(asyncResult);
}
/// <summary>
/// Initiates the asynchronous execution of the DeregisterInstancesFromLoadBalancer operation.
/// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.DeregisterInstancesFromLoadBalancer"/>
/// </summary>
///
/// <param name="deregisterInstancesFromLoadBalancerRequest">Container for the necessary parameters to execute the
/// DeregisterInstancesFromLoadBalancer operation on AmazonElasticLoadBalancing.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking
/// EndDeregisterInstancesFromLoadBalancer operation.</returns>
public IAsyncResult BeginDeregisterInstancesFromLoadBalancer(DeregisterInstancesFromLoadBalancerRequest deregisterInstancesFromLoadBalancerRequest, AsyncCallback callback, object state)
{
return invokeDeregisterInstancesFromLoadBalancer(deregisterInstancesFromLoadBalancerRequest, callback, state, false);
}
/// <summary>
/// Finishes the asynchronous execution of the DeregisterInstancesFromLoadBalancer operation.
/// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.DeregisterInstancesFromLoadBalancer"/>
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginDeregisterInstancesFromLoadBalancer.</param>
///
/// <returns>Returns a DeregisterInstancesFromLoadBalancerResult from AmazonElasticLoadBalancing.</returns>
public DeregisterInstancesFromLoadBalancerResponse EndDeregisterInstancesFromLoadBalancer(IAsyncResult asyncResult)
{
return endOperation<DeregisterInstancesFromLoadBalancerResponse>(asyncResult);
}
IAsyncResult invokeDeregisterInstancesFromLoadBalancer(DeregisterInstancesFromLoadBalancerRequest deregisterInstancesFromLoadBalancerRequest, AsyncCallback callback, object state, bool synchronized)
{
IRequest irequest = new DeregisterInstancesFromLoadBalancerRequestMarshaller().Marshall(deregisterInstancesFromLoadBalancerRequest);
var unmarshaller = DeregisterInstancesFromLoadBalancerResponseUnmarshaller.GetInstance();
AsyncResult result = new AsyncResult(irequest, callback, state, synchronized, signer, unmarshaller);
Invoke(result);
return result;
}
#endregion
#region SetLoadBalancerListenerSSLCertificate
/// <summary>
/// <para> Sets the certificate that terminates the specified listener's SSL connections. The specified certificate replaces any prior
/// certificate that was used on the same LoadBalancer and port. </para> <para>For information on using SetLoadBalancerListenerSSLCertificate,
/// go to Using the Query API in <i>Updating an SSL Certificate for a Load Balancer</i> section of the <i>Elastic Load Balancing Developer
/// Guide</i> .</para>
/// </summary>
///
/// <param name="setLoadBalancerListenerSSLCertificateRequest">Container for the necessary parameters to execute the
/// SetLoadBalancerListenerSSLCertificate service method on AmazonElasticLoadBalancing.</param>
///
/// <returns>The response from the SetLoadBalancerListenerSSLCertificate service method, as returned by AmazonElasticLoadBalancing.</returns>
///
/// <exception cref="InvalidConfigurationRequestException"/>
/// <exception cref="CertificateNotFoundException"/>
/// <exception cref="LoadBalancerNotFoundException"/>
/// <exception cref="ListenerNotFoundException"/>
public SetLoadBalancerListenerSSLCertificateResponse SetLoadBalancerListenerSSLCertificate(SetLoadBalancerListenerSSLCertificateRequest setLoadBalancerListenerSSLCertificateRequest)
{
IAsyncResult asyncResult = invokeSetLoadBalancerListenerSSLCertificate(setLoadBalancerListenerSSLCertificateRequest, null, null, true);
return EndSetLoadBalancerListenerSSLCertificate(asyncResult);
}
/// <summary>
/// Initiates the asynchronous execution of the SetLoadBalancerListenerSSLCertificate operation.
/// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.SetLoadBalancerListenerSSLCertificate"/>
/// </summary>
///
/// <param name="setLoadBalancerListenerSSLCertificateRequest">Container for the necessary parameters to execute the
/// SetLoadBalancerListenerSSLCertificate operation on AmazonElasticLoadBalancing.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking
/// EndSetLoadBalancerListenerSSLCertificate operation.</returns>
public IAsyncResult BeginSetLoadBalancerListenerSSLCertificate(SetLoadBalancerListenerSSLCertificateRequest setLoadBalancerListenerSSLCertificateRequest, AsyncCallback callback, object state)
{
return invokeSetLoadBalancerListenerSSLCertificate(setLoadBalancerListenerSSLCertificateRequest, callback, state, false);
}
/// <summary>
/// Finishes the asynchronous execution of the SetLoadBalancerListenerSSLCertificate operation.
/// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.SetLoadBalancerListenerSSLCertificate"/>
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginSetLoadBalancerListenerSSLCertificate.</param>
///
/// <returns>Returns a SetLoadBalancerListenerSSLCertificateResult from AmazonElasticLoadBalancing.</returns>
public SetLoadBalancerListenerSSLCertificateResponse EndSetLoadBalancerListenerSSLCertificate(IAsyncResult asyncResult)
{
return endOperation<SetLoadBalancerListenerSSLCertificateResponse>(asyncResult);
}
IAsyncResult invokeSetLoadBalancerListenerSSLCertificate(SetLoadBalancerListenerSSLCertificateRequest setLoadBalancerListenerSSLCertificateRequest, AsyncCallback callback, object state, bool synchronized)
{
IRequest irequest = new SetLoadBalancerListenerSSLCertificateRequestMarshaller().Marshall(setLoadBalancerListenerSSLCertificateRequest);
var unmarshaller = SetLoadBalancerListenerSSLCertificateResponseUnmarshaller.GetInstance();
AsyncResult result = new AsyncResult(irequest, callback, state, synchronized, signer, unmarshaller);
Invoke(result);
return result;
}
#endregion
#region CreateLBCookieStickinessPolicy
/// <summary>
/// <para> Generates a stickiness policy with sticky session lifetimes controlled by the lifetime of the browser (user-agent) or a specified
/// expiration period. This policy can be associated only with HTTP/HTTPS listeners. </para> <para> When a LoadBalancer implements this policy,
/// the LoadBalancer uses a special cookie to track the backend server instance for each request. When the LoadBalancer receives a request, it
/// first checks to see if this cookie is present in the request. If so, the LoadBalancer sends the request to the application server specified
/// in the cookie. If not, the LoadBalancer sends the request to a server that is chosen based on the existing load balancing algorithm. </para>
/// <para> A cookie is inserted into the response for binding subsequent requests from the same user to that server. The validity of the cookie
/// is based on the cookie expiration time, which is specified in the policy configuration. </para>
/// </summary>
///
/// <param name="createLBCookieStickinessPolicyRequest">Container for the necessary parameters to execute the CreateLBCookieStickinessPolicy
/// service method on AmazonElasticLoadBalancing.</param>
///
/// <returns>The response from the CreateLBCookieStickinessPolicy service method, as returned by AmazonElasticLoadBalancing.</returns>
///
/// <exception cref="InvalidConfigurationRequestException"/>
/// <exception cref="DuplicatePolicyNameException"/>
/// <exception cref="TooManyPoliciesException"/>
/// <exception cref="LoadBalancerNotFoundException"/>
public CreateLBCookieStickinessPolicyResponse CreateLBCookieStickinessPolicy(CreateLBCookieStickinessPolicyRequest createLBCookieStickinessPolicyRequest)
{
IAsyncResult asyncResult = invokeCreateLBCookieStickinessPolicy(createLBCookieStickinessPolicyRequest, null, null, true);
return EndCreateLBCookieStickinessPolicy(asyncResult);
}
/// <summary>
/// Initiates the asynchronous execution of the CreateLBCookieStickinessPolicy operation.
/// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.CreateLBCookieStickinessPolicy"/>
/// </summary>
///
/// <param name="createLBCookieStickinessPolicyRequest">Container for the necessary parameters to execute the CreateLBCookieStickinessPolicy
/// operation on AmazonElasticLoadBalancing.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking
/// EndCreateLBCookieStickinessPolicy operation.</returns>
public IAsyncResult BeginCreateLBCookieStickinessPolicy(CreateLBCookieStickinessPolicyRequest createLBCookieStickinessPolicyRequest, AsyncCallback callback, object state)
{
return invokeCreateLBCookieStickinessPolicy(createLBCookieStickinessPolicyRequest, callback, state, false);
}
/// <summary>
/// Finishes the asynchronous execution of the CreateLBCookieStickinessPolicy operation.
/// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.CreateLBCookieStickinessPolicy"/>
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginCreateLBCookieStickinessPolicy.</param>
///
/// <returns>Returns a CreateLBCookieStickinessPolicyResult from AmazonElasticLoadBalancing.</returns>
public CreateLBCookieStickinessPolicyResponse EndCreateLBCookieStickinessPolicy(IAsyncResult asyncResult)
{
return endOperation<CreateLBCookieStickinessPolicyResponse>(asyncResult);
}
IAsyncResult invokeCreateLBCookieStickinessPolicy(CreateLBCookieStickinessPolicyRequest createLBCookieStickinessPolicyRequest, AsyncCallback callback, object state, bool synchronized)
{
IRequest irequest = new CreateLBCookieStickinessPolicyRequestMarshaller().Marshall(createLBCookieStickinessPolicyRequest);
var unmarshaller = CreateLBCookieStickinessPolicyResponseUnmarshaller.GetInstance();
AsyncResult result = new AsyncResult(irequest, callback, state, synchronized, signer, unmarshaller);
Invoke(result);
return result;
}
#endregion
#region AttachLoadBalancerToSubnets
/// <summary>
/// <para> Adds one or more subnets to the set of configured subnets in the VPC for the LoadBalancer. </para> <para> The Loadbalancers evenly
/// distribute requests across all of the registered subnets. </para>
/// </summary>
///
/// <param name="attachLoadBalancerToSubnetsRequest">Container for the necessary parameters to execute the AttachLoadBalancerToSubnets service
/// method on AmazonElasticLoadBalancing.</param>
///
/// <returns>The response from the AttachLoadBalancerToSubnets service method, as returned by AmazonElasticLoadBalancing.</returns>
///
/// <exception cref="InvalidSubnetException"/>
/// <exception cref="InvalidConfigurationRequestException"/>
/// <exception cref="LoadBalancerNotFoundException"/>
/// <exception cref="SubnetNotFoundException"/>
public AttachLoadBalancerToSubnetsResponse AttachLoadBalancerToSubnets(AttachLoadBalancerToSubnetsRequest attachLoadBalancerToSubnetsRequest)
{
IAsyncResult asyncResult = invokeAttachLoadBalancerToSubnets(attachLoadBalancerToSubnetsRequest, null, null, true);
return EndAttachLoadBalancerToSubnets(asyncResult);
}
/// <summary>
/// Initiates the asynchronous execution of the AttachLoadBalancerToSubnets operation.
/// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.AttachLoadBalancerToSubnets"/>
/// </summary>
///
/// <param name="attachLoadBalancerToSubnetsRequest">Container for the necessary parameters to execute the AttachLoadBalancerToSubnets operation
/// on AmazonElasticLoadBalancing.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking
/// EndAttachLoadBalancerToSubnets operation.</returns>
public IAsyncResult BeginAttachLoadBalancerToSubnets(AttachLoadBalancerToSubnetsRequest attachLoadBalancerToSubnetsRequest, AsyncCallback callback, object state)
{
return invokeAttachLoadBalancerToSubnets(attachLoadBalancerToSubnetsRequest, callback, state, false);
}
/// <summary>
/// Finishes the asynchronous execution of the AttachLoadBalancerToSubnets operation.
/// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.AttachLoadBalancerToSubnets"/>
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginAttachLoadBalancerToSubnets.</param>
///
/// <returns>Returns a AttachLoadBalancerToSubnetsResult from AmazonElasticLoadBalancing.</returns>
public AttachLoadBalancerToSubnetsResponse EndAttachLoadBalancerToSubnets(IAsyncResult asyncResult)
{
return endOperation<AttachLoadBalancerToSubnetsResponse>(asyncResult);
}
IAsyncResult invokeAttachLoadBalancerToSubnets(AttachLoadBalancerToSubnetsRequest attachLoadBalancerToSubnetsRequest, AsyncCallback callback, object state, bool synchronized)
{
IRequest irequest = new AttachLoadBalancerToSubnetsRequestMarshaller().Marshall(attachLoadBalancerToSubnetsRequest);
var unmarshaller = AttachLoadBalancerToSubnetsResponseUnmarshaller.GetInstance();
AsyncResult result = new AsyncResult(irequest, callback, state, synchronized, signer, unmarshaller);
Invoke(result);
return result;
}
#endregion
#region CreateAppCookieStickinessPolicy
/// <summary>
/// <para> Generates a stickiness policy with sticky session lifetimes that follow that of an application-generated cookie. This policy can be
/// associated only with HTTP/HTTPS listeners. </para> <para> This policy is similar to the policy created by CreateLBCookieStickinessPolicy,
/// except that the lifetime of the special Elastic Load Balancing cookie follows the lifetime of the application-generated cookie specified in
/// the policy configuration. The LoadBalancer only inserts a new stickiness cookie when the application response includes a new application
/// cookie. </para> <para> If the application cookie is explicitly removed or expires, the session stops being sticky until a new application
/// cookie is issued. </para> <para><b>NOTE:</b> An application client must receive and send two cookies: the application-generated cookie and
/// the special Elastic Load Balancing cookie named AWSELB. This is the default behavior for many common web browsers. </para>
/// </summary>
///
/// <param name="createAppCookieStickinessPolicyRequest">Container for the necessary parameters to execute the CreateAppCookieStickinessPolicy
/// service method on AmazonElasticLoadBalancing.</param>
///
/// <returns>The response from the CreateAppCookieStickinessPolicy service method, as returned by AmazonElasticLoadBalancing.</returns>
///
/// <exception cref="InvalidConfigurationRequestException"/>
/// <exception cref="DuplicatePolicyNameException"/>
/// <exception cref="TooManyPoliciesException"/>
/// <exception cref="LoadBalancerNotFoundException"/>
public CreateAppCookieStickinessPolicyResponse CreateAppCookieStickinessPolicy(CreateAppCookieStickinessPolicyRequest createAppCookieStickinessPolicyRequest)
{
IAsyncResult asyncResult = invokeCreateAppCookieStickinessPolicy(createAppCookieStickinessPolicyRequest, null, null, true);
return EndCreateAppCookieStickinessPolicy(asyncResult);
}
/// <summary>
/// Initiates the asynchronous execution of the CreateAppCookieStickinessPolicy operation.
/// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.CreateAppCookieStickinessPolicy"/>
/// </summary>
///
/// <param name="createAppCookieStickinessPolicyRequest">Container for the necessary parameters to execute the CreateAppCookieStickinessPolicy
/// operation on AmazonElasticLoadBalancing.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking
/// EndCreateAppCookieStickinessPolicy operation.</returns>
public IAsyncResult BeginCreateAppCookieStickinessPolicy(CreateAppCookieStickinessPolicyRequest createAppCookieStickinessPolicyRequest, AsyncCallback callback, object state)
{
return invokeCreateAppCookieStickinessPolicy(createAppCookieStickinessPolicyRequest, callback, state, false);
}
/// <summary>
/// Finishes the asynchronous execution of the CreateAppCookieStickinessPolicy operation.
/// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.CreateAppCookieStickinessPolicy"/>
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginCreateAppCookieStickinessPolicy.</param>
///
/// <returns>Returns a CreateAppCookieStickinessPolicyResult from AmazonElasticLoadBalancing.</returns>
public CreateAppCookieStickinessPolicyResponse EndCreateAppCookieStickinessPolicy(IAsyncResult asyncResult)
{
return endOperation<CreateAppCookieStickinessPolicyResponse>(asyncResult);
}
IAsyncResult invokeCreateAppCookieStickinessPolicy(CreateAppCookieStickinessPolicyRequest createAppCookieStickinessPolicyRequest, AsyncCallback callback, object state, bool synchronized)
{
IRequest irequest = new CreateAppCookieStickinessPolicyRequestMarshaller().Marshall(createAppCookieStickinessPolicyRequest);
var unmarshaller = CreateAppCookieStickinessPolicyResponseUnmarshaller.GetInstance();
AsyncResult result = new AsyncResult(irequest, callback, state, synchronized, signer, unmarshaller);
Invoke(result);
return result;
}
#endregion
#region RegisterInstancesWithLoadBalancer
/// <summary>
/// <para> Adds new instances to the LoadBalancer. </para> <para> Once the instance is registered, it starts receiving traffic and requests from
/// the LoadBalancer. Any instance that is not in any of the Availability Zones registered for the LoadBalancer will be moved to the
/// <i>OutOfService</i> state. It will move to the <i>InService</i> state when the Availability Zone is added to the LoadBalancer. </para>
/// <para><b>NOTE:</b> In order for this call to be successful, the client must have created the LoadBalancer. The client must provide the same
/// account credentials as those that were used to create the LoadBalancer. </para> <para><b>NOTE:</b> Completion of this API does not guarantee
/// that operation has completed. Rather, it means that the request has been registered and the changes will happen shortly. </para>
/// </summary>
///
/// <param name="registerInstancesWithLoadBalancerRequest">Container for the necessary parameters to execute the
/// RegisterInstancesWithLoadBalancer service method on AmazonElasticLoadBalancing.</param>
///
/// <returns>The response from the RegisterInstancesWithLoadBalancer service method, as returned by AmazonElasticLoadBalancing.</returns>
///
/// <exception cref="LoadBalancerNotFoundException"/>
/// <exception cref="InvalidInstanceException"/>
public RegisterInstancesWithLoadBalancerResponse RegisterInstancesWithLoadBalancer(RegisterInstancesWithLoadBalancerRequest registerInstancesWithLoadBalancerRequest)
{
IAsyncResult asyncResult = invokeRegisterInstancesWithLoadBalancer(registerInstancesWithLoadBalancerRequest, null, null, true);
return EndRegisterInstancesWithLoadBalancer(asyncResult);
}
/// <summary>
/// Initiates the asynchronous execution of the RegisterInstancesWithLoadBalancer operation.
/// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.RegisterInstancesWithLoadBalancer"/>
/// </summary>
///
/// <param name="registerInstancesWithLoadBalancerRequest">Container for the necessary parameters to execute the
/// RegisterInstancesWithLoadBalancer operation on AmazonElasticLoadBalancing.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking
/// EndRegisterInstancesWithLoadBalancer operation.</returns>
public IAsyncResult BeginRegisterInstancesWithLoadBalancer(RegisterInstancesWithLoadBalancerRequest registerInstancesWithLoadBalancerRequest, AsyncCallback callback, object state)
{
return invokeRegisterInstancesWithLoadBalancer(registerInstancesWithLoadBalancerRequest, callback, state, false);
}
/// <summary>
/// Finishes the asynchronous execution of the RegisterInstancesWithLoadBalancer operation.
/// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.RegisterInstancesWithLoadBalancer"/>
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginRegisterInstancesWithLoadBalancer.</param>
///
/// <returns>Returns a RegisterInstancesWithLoadBalancerResult from AmazonElasticLoadBalancing.</returns>
public RegisterInstancesWithLoadBalancerResponse EndRegisterInstancesWithLoadBalancer(IAsyncResult asyncResult)
{
return endOperation<RegisterInstancesWithLoadBalancerResponse>(asyncResult);
}
IAsyncResult invokeRegisterInstancesWithLoadBalancer(RegisterInstancesWithLoadBalancerRequest registerInstancesWithLoadBalancerRequest, AsyncCallback callback, object state, bool synchronized)
{
IRequest irequest = new RegisterInstancesWithLoadBalancerRequestMarshaller().Marshall(registerInstancesWithLoadBalancerRequest);
var unmarshaller = RegisterInstancesWithLoadBalancerResponseUnmarshaller.GetInstance();
AsyncResult result = new AsyncResult(irequest, callback, state, synchronized, signer, unmarshaller);
Invoke(result);
return result;
}
#endregion
#region ApplySecurityGroupsToLoadBalancer
/// <summary>
/// <para> Associates one or more security groups with your LoadBalancer in VPC. The provided security group IDs will override any currently
/// applied security groups. </para>
/// </summary>
///
/// <param name="applySecurityGroupsToLoadBalancerRequest">Container for the necessary parameters to execute the
/// ApplySecurityGroupsToLoadBalancer service method on AmazonElasticLoadBalancing.</param>
///
/// <returns>The response from the ApplySecurityGroupsToLoadBalancer service method, as returned by AmazonElasticLoadBalancing.</returns>
///
/// <exception cref="InvalidConfigurationRequestException"/>
/// <exception cref="InvalidSecurityGroupException"/>
/// <exception cref="LoadBalancerNotFoundException"/>
public ApplySecurityGroupsToLoadBalancerResponse ApplySecurityGroupsToLoadBalancer(ApplySecurityGroupsToLoadBalancerRequest applySecurityGroupsToLoadBalancerRequest)
{
IAsyncResult asyncResult = invokeApplySecurityGroupsToLoadBalancer(applySecurityGroupsToLoadBalancerRequest, null, null, true);
return EndApplySecurityGroupsToLoadBalancer(asyncResult);
}
/// <summary>
/// Initiates the asynchronous execution of the ApplySecurityGroupsToLoadBalancer operation.
/// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.ApplySecurityGroupsToLoadBalancer"/>
/// </summary>
///
/// <param name="applySecurityGroupsToLoadBalancerRequest">Container for the necessary parameters to execute the
/// ApplySecurityGroupsToLoadBalancer operation on AmazonElasticLoadBalancing.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking
/// EndApplySecurityGroupsToLoadBalancer operation.</returns>
public IAsyncResult BeginApplySecurityGroupsToLoadBalancer(ApplySecurityGroupsToLoadBalancerRequest applySecurityGroupsToLoadBalancerRequest, AsyncCallback callback, object state)
{
return invokeApplySecurityGroupsToLoadBalancer(applySecurityGroupsToLoadBalancerRequest, callback, state, false);
}
/// <summary>
/// Finishes the asynchronous execution of the ApplySecurityGroupsToLoadBalancer operation.
/// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.ApplySecurityGroupsToLoadBalancer"/>
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginApplySecurityGroupsToLoadBalancer.</param>
///
/// <returns>Returns a ApplySecurityGroupsToLoadBalancerResult from AmazonElasticLoadBalancing.</returns>
public ApplySecurityGroupsToLoadBalancerResponse EndApplySecurityGroupsToLoadBalancer(IAsyncResult asyncResult)
{
return endOperation<ApplySecurityGroupsToLoadBalancerResponse>(asyncResult);
}
IAsyncResult invokeApplySecurityGroupsToLoadBalancer(ApplySecurityGroupsToLoadBalancerRequest applySecurityGroupsToLoadBalancerRequest, AsyncCallback callback, object state, bool synchronized)
{
IRequest irequest = new ApplySecurityGroupsToLoadBalancerRequestMarshaller().Marshall(applySecurityGroupsToLoadBalancerRequest);
var unmarshaller = ApplySecurityGroupsToLoadBalancerResponseUnmarshaller.GetInstance();
AsyncResult result = new AsyncResult(irequest, callback, state, synchronized, signer, unmarshaller);
Invoke(result);
return result;
}
#endregion
#region DescribeLoadBalancers
/// <summary>
/// <para> Returns detailed configuration information for the specified LoadBalancers. If no LoadBalancers are specified, the operation returns
/// configuration information for all LoadBalancers created by the caller. </para> <para><b>NOTE:</b> The client must have created the specified
/// input LoadBalancers in order to retrieve this information; the client must provide the same account credentials as those that were used to
/// create the LoadBalancer. </para>
/// </summary>
///
/// <param name="describeLoadBalancersRequest">Container for the necessary parameters to execute the DescribeLoadBalancers service method on
/// AmazonElasticLoadBalancing.</param>
///
/// <returns>The response from the DescribeLoadBalancers service method, as returned by AmazonElasticLoadBalancing.</returns>
///
/// <exception cref="LoadBalancerNotFoundException"/>
public DescribeLoadBalancersResponse DescribeLoadBalancers(DescribeLoadBalancersRequest describeLoadBalancersRequest)
{
IAsyncResult asyncResult = invokeDescribeLoadBalancers(describeLoadBalancersRequest, null, null, true);
return EndDescribeLoadBalancers(asyncResult);
}
/// <summary>
/// Initiates the asynchronous execution of the DescribeLoadBalancers operation.
/// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.DescribeLoadBalancers"/>
/// </summary>
///
/// <param name="describeLoadBalancersRequest">Container for the necessary parameters to execute the DescribeLoadBalancers operation on
/// AmazonElasticLoadBalancing.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking
/// EndDescribeLoadBalancers operation.</returns>
public IAsyncResult BeginDescribeLoadBalancers(DescribeLoadBalancersRequest describeLoadBalancersRequest, AsyncCallback callback, object state)
{
return invokeDescribeLoadBalancers(describeLoadBalancersRequest, callback, state, false);
}
/// <summary>
/// Finishes the asynchronous execution of the DescribeLoadBalancers operation.
/// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.DescribeLoadBalancers"/>
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeLoadBalancers.</param>
///
/// <returns>Returns a DescribeLoadBalancersResult from AmazonElasticLoadBalancing.</returns>
public DescribeLoadBalancersResponse EndDescribeLoadBalancers(IAsyncResult asyncResult)
{
return endOperation<DescribeLoadBalancersResponse>(asyncResult);
}
IAsyncResult invokeDescribeLoadBalancers(DescribeLoadBalancersRequest describeLoadBalancersRequest, AsyncCallback callback, object state, bool synchronized)
{
IRequest irequest = new DescribeLoadBalancersRequestMarshaller().Marshall(describeLoadBalancersRequest);
var unmarshaller = DescribeLoadBalancersResponseUnmarshaller.GetInstance();
AsyncResult result = new AsyncResult(irequest, callback, state, synchronized, signer, unmarshaller);
Invoke(result);
return result;
}
/// <summary>
/// <para> Returns detailed configuration information for the specified LoadBalancers. If no LoadBalancers are specified, the operation returns
/// configuration information for all LoadBalancers created by the caller. </para> <para><b>NOTE:</b> The client must have created the specified
/// input LoadBalancers in order to retrieve this information; the client must provide the same account credentials as those that were used to
/// create the LoadBalancer. </para>
/// </summary>
///
/// <returns>The response from the DescribeLoadBalancers service method, as returned by AmazonElasticLoadBalancing.</returns>
///
/// <exception cref="LoadBalancerNotFoundException"/>
public DescribeLoadBalancersResponse DescribeLoadBalancers()
{
return DescribeLoadBalancers(new DescribeLoadBalancersRequest());
}
#endregion
}
}
|
emcvipr/dataservices-sdk-dotnet
|
AWSSDK/Amazon.ElasticLoadBalancing/AmazonElasticLoadBalancingClient.cs
|
C#
|
apache-2.0
| 111,516 |
(function(){'use strict';
module.exports = (function () {
if (process.argv.indexOf('--no-color') !== -1) {
return false;
}
if (process.argv.indexOf('--color') !== -1) {
return true;
}
if (process.stdout && !process.stdout.isTTY) {
return false;
}
if (process.platform === 'win32') {
return true;
}
if ('COLORTERM' in process.env) {
return true;
}
if (process.env.TERM === 'dumb') {
return false;
}
if (/^screen|^xterm|^vt100|color|ansi|cygwin|linux/i.test(process.env.TERM)) {
return true;
}
return false;
})();
})();
|
durwasa-chakraborty/navigus
|
.demeteorized/bundle/programs/server/app/lib/node_modules/modulus/node_modules/update-notifier/node_modules/chalk/node_modules/has-color/index.js
|
JavaScript
|
apache-2.0
| 555 |
package com.nedap.archie.json;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.databind.DatabindContext;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.jsontype.impl.ClassNameIdResolver;
import com.fasterxml.jackson.databind.type.TypeFactory;
import com.nedap.archie.base.OpenEHRBase;
import com.nedap.archie.rminfo.ArchieAOMInfoLookup;
import com.nedap.archie.rminfo.ArchieRMInfoLookup;
import com.nedap.archie.rminfo.ModelInfoLookup;
import com.nedap.archie.rminfo.RMTypeInfo;
import java.io.IOException;
/**
* Class that handles naming of Archie RM and AOM objects for use in Jackson.
*
* The AOM class CComplexObject will get the type name "C_COMPLEX_OBJECT"
* The RM class DvDateTime will get the type name "DV_DATE_TIME"
*/
public class OpenEHRTypeNaming extends ClassNameIdResolver {
private ModelInfoLookup rmInfoLookup = ArchieRMInfoLookup.getInstance();
private ModelInfoLookup aomInfoLookup = ArchieAOMInfoLookup.getInstance();
protected OpenEHRTypeNaming() {
super(TypeFactory.defaultInstance().constructType(OpenEHRBase.class), TypeFactory.defaultInstance());
}
public JsonTypeInfo.Id getMechanism() {
return JsonTypeInfo.Id.NAME;
}
@Override
public String idFromValue(Object value) {
RMTypeInfo typeInfo = rmInfoLookup.getTypeInfo(value.getClass());
if(typeInfo == null) {
return rmInfoLookup.getNamingStrategy().getTypeName(value.getClass());
} else {
//this case is faster and should always work. If for some reason it does not, the above case works fine instead.
return typeInfo.getRmName();
}
// This should work in all cases for openEHR-classes and this should not be used for other classes
// Additional code for making this work on non-ehr-types:
// } else {
// return super.idFromValue(value);
// }
}
@Deprecated // since 2.3
@Override
public JavaType typeFromId(String id) {
return _typeFromId(id, null);
}
@Override
public JavaType typeFromId(DatabindContext context, String id) {
return _typeFromId(id, context);
}
@Override
protected JavaType _typeFromId(String typeName, DatabindContext ctxt) {
Class result = rmInfoLookup.getClass(typeName);
if(result == null) {
//AOM class?
result = aomInfoLookup.getClass(typeName);
}
if(result != null) {
TypeFactory typeFactory = (ctxt == null) ? _typeFactory : ctxt.getTypeFactory();
return typeFactory.constructSpecializedType(_baseType, result);
}
return super._typeFromId(typeName, ctxt);
}
}
|
nedap/archie
|
src/main/java/com/nedap/archie/json/OpenEHRTypeNaming.java
|
Java
|
apache-2.0
| 2,751 |
/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
* MACHINE GENERATED FILE, DO NOT EDIT
*/
package org.lwjgl.opencl;
/**
* Native bindings to the <a href="http://www.khronos.org/registry/cl/extensions/intel/cl_intel_advanced_motion_estimation.txt">intel_advanced_motion_estimation</a> extension.
*
* <p>This extension builds upon the cl_intel_motion_estimation extension by providing block-based estimation and greater control over the estimation
* algorithm.</p>
*
* <p>This extension reuses the set of host-callable functions and "motion estimation accelerator objects" defined in the cl_intel_motion_estimation
* extension. This extension depends on the OpenCL 1.2 built-in kernel infrastructure and on the cl_intel_accelerator extension, which provides an
* abstraction for domain-specific acceleration in the OpenCL runtime.</p>
*
* <p>Requires {@link INTELMotionEstimation intel_motion_estimation}.</p>
*/
public final class INTELAdvancedMotionEstimation {
/** Accepted as arguments to clGetDeviceInfo. */
public static final int CL_DEVICE_ME_VERSION_INTEL = 0x407E;
/** Accepted as flags passed to the kernel. */
public static final int
CL_ME_CHROMA_INTRA_PREDICT_ENABLED_INTEL = 0x1,
CL_ME_LUMA_INTRA_PREDICT_ENABLED_INTEL = 0x2,
CL_ME_COST_PENALTY_NONE_INTEL = 0x0,
CL_ME_COST_PENALTY_LOW_INTEL = 0x1,
CL_ME_COST_PENALTY_NORMAL_INTEL = 0x2,
CL_ME_COST_PENALTY_HIGH_INTEL = 0x3,
CL_ME_COST_PRECISION_QPEL_INTEL = 0x0,
CL_ME_COST_PRECISION_HEL_INTEL = 0x1,
CL_ME_COST_PRECISION_PEL_INTEL = 0x2,
CL_ME_COST_PRECISION_DPEL_INTEL = 0x3;
/** Valid intra-search predictor mode constants. */
public static final int
CL_ME_LUMA_PREDICTOR_MODE_VERTICAL_INTEL = 0x0,
CL_ME_LUMA_PREDICTOR_MODE_HORIZONTAL_INTEL = 0x1,
CL_ME_LUMA_PREDICTOR_MODE_DC_INTEL = 0x2,
CL_ME_LUMA_PREDICTOR_MODE_DIAGONAL_DOWN_LEFT_INTEL = 0x3,
CL_ME_LUMA_PREDICTOR_MODE_DIAGONAL_DOWN_RIGHT_INTEL = 0x4,
CL_ME_LUMA_PREDICTOR_MODE_PLANE_INTEL = 0x4,
CL_ME_LUMA_PREDICTOR_MODE_VERTICAL_RIGHT_INTEL = 0x5,
CL_ME_LUMA_PREDICTOR_MODE_HORIZONTAL_DOWN_INTEL = 0x6,
CL_ME_LUMA_PREDICTOR_MODE_VERTICAL_LEFT_INTEL = 0x7,
CL_ME_LUMA_PREDICTOR_MODE_HORIZONTAL_UP_INTEL = 0x8,
CL_ME_CHROMA_PREDICTOR_MODE_DC_INTEL = 0x0,
CL_ME_CHROMA_PREDICTOR_MODE_HORIZONTAL_INTEL = 0x1,
CL_ME_CHROMA_PREDICTOR_MODE_VERTICAL_INTEL = 0x2,
CL_ME_CHROMA_PREDICTOR_MODE_PLANE_INTEL = 0x3;
/** Valid constant values returned by clGetDeviceInfo. */
public static final int CL_ME_VERSION_ADVANCED_VER_1_INTEL = 0x1;
/** Valid macroblock type constants. */
public static final int
CL_ME_MB_TYPE_16x16_INTEL = 0x0,
CL_ME_MB_TYPE_8x8_INTEL = 0x1,
CL_ME_MB_TYPE_4x4_INTEL = 0x2;
private INTELAdvancedMotionEstimation() {}
}
|
VirtualGamer/SnowEngine
|
Dependencies/opencl/src/org/lwjgl/opencl/INTELAdvancedMotionEstimation.java
|
Java
|
apache-2.0
| 2,988 |
/*
* Copyright (c) 2017. Matsuda, Akihit (akihito104)
*
* 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.freshdigitable.udonroad;
import android.content.Context;
import android.support.v7.widget.AppCompatTextView;
import android.util.AttributeSet;
/**
* LinkableTextView is a TextView which is acceptable ClickableSpan and is colored at pressed.
*
* Created by akihit on 2017/01/05.
*/
public class LinkableTextView extends AppCompatTextView {
public LinkableTextView(Context context) {
this(context, null);
}
public LinkableTextView(Context context, AttributeSet attrs) {
this(context, attrs, android.R.attr.textViewStyle);
}
public LinkableTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
Utils.colorStateLinkify(this);
}
}
|
akihito104/UdonRoad
|
app/src/main/java/com/freshdigitable/udonroad/LinkableTextView.java
|
Java
|
apache-2.0
| 1,342 |
// Copyright 2014 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.syntax;
import com.google.common.base.Joiner;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Interner;
import com.google.devtools.build.lib.collect.nestedset.NestedSet;
import com.google.devtools.build.lib.concurrent.BlazeInterners;
import com.google.devtools.build.lib.events.Location;
import com.google.devtools.build.lib.skylarkinterface.SkylarkValue;
import com.google.devtools.build.lib.syntax.SkylarkList.MutableList;
import com.google.devtools.build.lib.syntax.SkylarkList.Tuple;
import com.google.devtools.build.lib.util.Preconditions;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.WildcardType;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import javax.annotation.Nullable;
/**
* A class representing types available in Skylark.
*
* <p>A SkylarkType can be one of:
* <ul>
* <li>a Simple type that contains exactly the objects in a given class,
* (including the special TOP and BOTTOM types that respectively contain
* all the objects (Simple type for Object.class) and no object at all
* (Simple type for EmptyType.class, isomorphic to Void.class).
* <li>a Combination of a generic class (one of SET, selector)
* and an argument type (that itself need not be Simple).
* <li>a Union of a finite set of types
* <li>a FunctionType associated with a name and a returnType
* </ul>
*
* <p>In a style reminiscent of Java's null, Skylark's None is in all the types
* as far as type inference goes, yet actually no type .contains(it).
*
* <p>The current implementation fails to distinguish between TOP and ANY,
* between BOTTOM and EMPTY (VOID, ZERO, FALSE):
* <ul>
* <li>In type analysis, we often distinguish a notion of "the type of this object"
* from the notion of "what I know about the type of this object".
* Some languages have a Universal Base Class that contains all objects, and would be the ANY type.
* The Skylark runtime, written in Java, has this ANY type, Java's Object.class.
* But the Skylark validation engine doesn't really have a concept of an ANY class;
* however, it does have a concept of a yet-undermined class, the TOP class
* (called UNKOWN in previous code). In the future, we may have to distinguish between the two,
* at which point type constructor classes would have to be generic in
* "actual type" vs "partial knowledge of type".
* <li>Similarly, and EMPTY type (also known as VOID, ZERO or FALSE, in other contexts)
* is a type that has no instance, whereas the BOTTOM type is the type analysis that says
* that there is no possible runtime type for the given object, which may imply that
* the point in the program at which the object is evaluated cannot be reached, etc.
* </ul>
* So for now, we have puns between TOP and ANY, BOTTOM and EMPTY, between runtime (eval) and
* validation-time (validate). Yet in the future, we may need to make a clear distinction,
* especially if we are to have types such List(Any) vs List(Top), which contains the former,
* but also plenty of other quite distinct types. And yet in a future future, the TOP type
* would not be represented explicitly, instead a new type variable would be inserted everywhere
* a type is unknown, to be unified with further type information as it becomes available.
*/
// TODO(bazel-team): move the FunctionType side-effect out of the type object
// and into the validation environment.
public abstract class SkylarkType implements Serializable {
// The main primitives to override in subclasses
/** Is the given value an element of this type? By default, no (empty type) */
public boolean contains(Object value) {
return false;
}
/**
* intersectWith() is the internal method from which function intersection(t1, t2) is computed.
* OVERRIDE this method in your classes, but DO NOT TO CALL it: only call intersection().
* When computing intersection(t1, t2), whichever type defined before the other
* knows nothing about the other and about their intersection, and returns BOTTOM;
* the other knows about the former, and returns their intersection (which may be BOTTOM).
* intersection() will call in one order then the other, and return whichever answer
* isn't BOTTOM, if any. By default, types are disjoint and their intersection is BOTTOM.
*/
// TODO(bazel-team): should we define and use an Exception instead?
protected SkylarkType intersectWith(SkylarkType other) {
return BOTTOM;
}
/** @return true if any object of this SkylarkType can be cast to that Java class */
public boolean canBeCastTo(Class<?> type) {
return SkylarkType.of(type).includes(this);
}
/** @return the smallest java Class known to contain all elements of this type */
// Note: most user-code should be using a variant that throws an Exception
// if the result is Object.class but the type isn't TOP.
public Class<?> getType() {
return Object.class;
}
// The actual intersection function for users to use
public static SkylarkType intersection(SkylarkType t1, SkylarkType t2) {
if (t1.equals(t2)) {
return t1;
}
SkylarkType t = t1.intersectWith(t2);
if (t == BOTTOM) {
return t2.intersectWith(t1);
} else {
return t;
}
}
public boolean includes(SkylarkType other) {
return intersection(this, other).equals(other);
}
public SkylarkType getArgType() {
return TOP;
}
private static final class Empty {}; // Empty type, used as basis for Bottom
// Notable types
/** A singleton for the TOP type, that at analysis time means that any type is possible. */
public static final Simple TOP = new Top();
/** A singleton for the BOTTOM type, that contains no element */
public static final Simple BOTTOM = new Bottom();
/** NONE, the Unit type, isomorphic to Void, except its unique element prints as None */
// Note that we currently consider at validation time that None is in every type,
// by declaring its type as TOP instead of NONE, even though at runtime,
// we reject None from all types but NONE, and in particular from e.g. lists of Files.
// TODO(bazel-team): resolve this inconsistency, one way or the other.
public static final Simple NONE = Simple.forClass(Runtime.NoneType.class);
/** The STRING type, for strings */
public static final Simple STRING = Simple.forClass(String.class);
/** The INTEGER type, for 32-bit signed integers */
public static final Simple INT = Simple.forClass(Integer.class);
/** The BOOLEAN type, that contains TRUE and FALSE */
public static final Simple BOOL = Simple.forClass(Boolean.class);
/** The FUNCTION type, that contains all functions, otherwise dynamically typed at call-time */
public static final SkylarkFunctionType FUNCTION = new SkylarkFunctionType("unknown", TOP);
/** The DICT type, that contains SkylarkDict */
public static final Simple DICT = Simple.forClass(SkylarkDict.class);
/** The SEQUENCE type, that contains lists and tuples */
// TODO(bazel-team): this was added for backward compatibility with the BUILD language,
// that doesn't make a difference between list and tuple, so that functions can be declared
// that keep not making the difference. Going forward, though, we should investigate whether
// we ever want to use this type, and if not, make sure no existing client code uses it.
public static final Simple SEQUENCE = Simple.forClass(SkylarkList.class);
/** The LIST type, that contains all MutableList-s */
public static final Simple LIST = Simple.forClass(MutableList.class);
/** The TUPLE type, that contains all Tuple-s */
public static final Simple TUPLE = Simple.forClass(Tuple.class);
/** The STRING_LIST type, a MutableList of strings */
public static final SkylarkType STRING_LIST = Combination.of(LIST, STRING);
/** The INT_LIST type, a MutableList of integers */
public static final SkylarkType INT_LIST = Combination.of(LIST, INT);
/** The SET type, that contains all SkylarkNestedSet-s, and the generic combinator for them */
public static final Simple SET = Simple.forClass(SkylarkNestedSet.class);
// Common subclasses of SkylarkType
/** the Top type contains all objects */
private static class Top extends Simple {
private Top() {
super(Object.class);
}
@Override public boolean contains(Object value) {
return true;
}
@Override public SkylarkType intersectWith(SkylarkType other) {
return other;
}
@Override public String toString() {
return "Object";
}
}
/** the Bottom type contains no element */
private static class Bottom extends Simple {
private Bottom() {
super(Empty.class);
}
@Override public SkylarkType intersectWith(SkylarkType other) {
return this;
}
@Override public String toString() {
return "EmptyType";
}
}
/** a Simple type contains the instance of a Java class */
public static class Simple extends SkylarkType {
private final Class<?> type;
private Simple(Class<?> type) {
this.type = type;
}
@Override public boolean contains(Object value) {
return value != null && type.isInstance(value);
}
@Override public Class<?> getType() {
return type;
}
@Override public boolean equals(Object other) {
return this == other
|| (this.getClass() == other.getClass() && this.type.equals(((Simple) other).getType()));
}
@Override public int hashCode() {
return 0x513973 + type.hashCode() * 503; // equal underlying types yield the same hashCode
}
@Override public String toString() {
return EvalUtils.getDataTypeNameFromClass(type);
}
@Override public boolean canBeCastTo(Class<?> type) {
return this.type == type || super.canBeCastTo(type);
}
private static final LoadingCache<Class<?>, Simple> simpleCache =
CacheBuilder.newBuilder()
.build(
new CacheLoader<Class<?>, Simple>() {
@Override
public Simple load(Class<?> type) {
return create(type);
}
});
private static Simple create(Class<?> type) {
Simple simple;
if (type == Object.class) {
// Note that this is a bad encoding for "anything", not for "everything", i.e.
// for skylark there isn't a type that contains everything, but there's a Top type
// that corresponds to not knowing yet which more special type it will be.
simple = TOP;
} else if (type == Empty.class) {
simple = BOTTOM;
} else {
// Consider all classes that have the same EvalUtils.getSkylarkType() as equivalent,
// as a substitute to handling inheritance.
Class<?> skylarkType = EvalUtils.getSkylarkType(type);
if (skylarkType != type) {
simple = Simple.forClass(skylarkType);
} else {
simple = new Simple(type);
}
}
return simple;
}
/**
* The way to create a Simple type.
*
* @param type a Class
* @return the Simple type that contains exactly the instances of that Class
*/
// Only call this method from SkylarkType. Calling it from outside SkylarkType leads to
// circular dependencies in class initialization, showing up as an NPE while initializing NONE.
// You actually want to call SkylarkType.of().
private static Simple forClass(Class<?> type) {
return simpleCache.getUnchecked(type);
}
}
/** Combination of a generic type and an argument type */
public static class Combination extends SkylarkType {
// For the moment, we can only combine a Simple type with a Simple type,
// and the first one has to be a Java generic class,
// and in practice actually one of SkylarkList or SkylarkNestedSet
private final SkylarkType genericType; // actually always a Simple, for now.
private final SkylarkType argType; // not always Simple
private Combination(SkylarkType genericType, SkylarkType argType) {
this.genericType = genericType;
this.argType = argType;
}
@Override
public boolean contains(Object value) {
// The empty collection is member of compatible types
if (value == null || !genericType.contains(value)) {
return false;
} else {
SkylarkType valueArgType = getGenericArgType(value);
return valueArgType == TOP // empty objects are universal
|| argType.includes(valueArgType);
}
}
@Override public SkylarkType intersectWith(SkylarkType other) {
// For now, we only accept generics with a single covariant parameter
if (genericType.equals(other)) {
return this;
}
if (other instanceof Combination) {
SkylarkType generic = genericType.intersectWith(((Combination) other).getGenericType());
if (generic == BOTTOM) {
return BOTTOM;
}
SkylarkType arg = intersection(argType, ((Combination) other).getArgType());
if (arg == BOTTOM) {
return BOTTOM;
}
return Combination.of(generic, arg);
}
if (other instanceof Simple) {
SkylarkType generic = genericType.intersectWith(other);
if (generic == BOTTOM) {
return BOTTOM;
}
return SkylarkType.of(generic, getArgType());
}
return BOTTOM;
}
@Override public boolean equals(Object other) {
if (this == other) {
return true;
} else if (this.getClass() == other.getClass()) {
Combination o = (Combination) other;
return genericType.equals(o.getGenericType())
&& argType.equals(o.getArgType());
} else {
return false;
}
}
@Override public int hashCode() {
// equal underlying types yield the same hashCode
return 0x20B14A71 + genericType.hashCode() * 1009 + argType.hashCode() * 1013;
}
@Override public Class<?> getType() {
return genericType.getType();
}
SkylarkType getGenericType() {
return genericType;
}
@Override
public SkylarkType getArgType() {
return argType;
}
@Override public String toString() {
return genericType + " of " + argType + "s";
}
private static final Interner<Combination> combinationInterner =
BlazeInterners.<Combination>newWeakInterner();
public static SkylarkType of(SkylarkType generic, SkylarkType argument) {
// assume all combinations with TOP are the same as the simple type, and canonicalize.
Preconditions.checkArgument(generic instanceof Simple);
if (argument == TOP) {
return generic;
} else {
return combinationInterner.intern(new Combination(generic, argument));
}
}
public static SkylarkType of(Class<?> generic, Class<?> argument) {
return of(Simple.forClass(generic), Simple.forClass(argument));
}
}
/** Union types, used a lot in "dynamic" languages such as Python or Skylark */
public static class Union extends SkylarkType {
private final ImmutableList<SkylarkType> types;
private Union(ImmutableList<SkylarkType> types) {
this.types = types;
}
@Override
public boolean contains(Object value) {
for (SkylarkType type : types) {
if (type.contains(value)) {
return true;
}
}
return false;
}
@Override public boolean equals(Object other) {
if (this.getClass() == other.getClass()) {
Union o = (Union) other;
if (types.containsAll(o.types) && o.types.containsAll(types)) {
return true;
}
}
return false;
}
@Override public int hashCode() {
// equal underlying types yield the same hashCode
int h = 0x4104;
for (SkylarkType type : types) {
// Important: addition is commutative, like Union
h += type.hashCode();
}
return h;
}
@Override public String toString() {
return Joiner.on(" or ").join(types);
}
public static List<SkylarkType> addElements(List<SkylarkType> list, SkylarkType type) {
if (type instanceof Union) {
list.addAll(((Union) type).types);
} else if (type != BOTTOM) {
list.add(type);
}
return list;
}
@Override public SkylarkType intersectWith(SkylarkType other) {
List<SkylarkType> otherTypes = addElements(new ArrayList<SkylarkType>(), other);
List<SkylarkType> results = new ArrayList<>();
for (SkylarkType element : types) {
for (SkylarkType otherElement : otherTypes) {
addElements(results, intersection(element, otherElement));
}
}
return Union.of(results);
}
public static SkylarkType of(List<SkylarkType> types) {
// When making the union of many types,
// canonicalize them into elementary (non-Union) types,
// and then eliminate trivially redundant types from the list.
// list of all types in the input
ArrayList<SkylarkType> elements = new ArrayList<>();
for (SkylarkType type : types) {
addElements(elements, type);
}
// canonicalized list of types
ArrayList<SkylarkType> canonical = new ArrayList<>();
for (SkylarkType newType : elements) {
boolean done = false; // done with this element?
int i = 0;
for (SkylarkType existingType : canonical) {
SkylarkType both = intersection(newType, existingType);
if (newType.equals(both)) { // newType already included
done = true;
break;
} else if (existingType.equals(both)) { // newType supertype of existingType
canonical.set(i, newType);
done = true;
break;
}
}
if (!done) {
canonical.add(newType);
}
}
if (canonical.isEmpty()) {
return BOTTOM;
} else if (canonical.size() == 1) {
return canonical.get(0);
} else {
return new Union(ImmutableList.<SkylarkType>copyOf(canonical));
}
}
public static SkylarkType of(SkylarkType... types) {
return of(Arrays.asList(types));
}
public static SkylarkType of(SkylarkType t1, SkylarkType t2) {
return of(ImmutableList.<SkylarkType>of(t1, t2));
}
public static SkylarkType of(Class<?> t1, Class<?> t2) {
return of(Simple.forClass(t1), Simple.forClass(t2));
}
}
public static SkylarkType of(Class<?> type) {
if (SkylarkNestedSet.class.isAssignableFrom(type)) {
return SET;
} else if (BaseFunction.class.isAssignableFrom(type)) {
return new SkylarkFunctionType("unknown", TOP);
} else {
return Simple.forClass(type);
}
}
public static SkylarkType of(SkylarkType t1, SkylarkType t2) {
return Combination.of(t1, t2);
}
public static SkylarkType of(Class<?> t1, Class<?> t2) {
return Combination.of(t1, t2);
}
/**
* A class representing the type of a Skylark function.
*/
public static final class SkylarkFunctionType extends SkylarkType {
private final String name;
@Nullable private final SkylarkType returnType;
@Override public SkylarkType intersectWith(SkylarkType other) {
// This gives the wrong result if both return types are incompatibly updated later!
if (other instanceof SkylarkFunctionType) {
SkylarkFunctionType fun = (SkylarkFunctionType) other;
SkylarkType type1 = returnType == null ? TOP : returnType;
SkylarkType type2 = fun.returnType == null ? TOP : fun.returnType;
SkylarkType bothReturnType = intersection(returnType, fun.returnType);
if (type1.equals(bothReturnType)) {
return this;
} else if (type2.equals(bothReturnType)) {
return fun;
} else {
return new SkylarkFunctionType(name, bothReturnType);
}
} else {
return BOTTOM;
}
}
@Override public Class<?> getType() {
return BaseFunction.class;
}
@Override public String toString() {
return (returnType == TOP || returnType == null ? "" : returnType + "-returning ")
+ "function";
}
@Override
public boolean contains(Object value) {
// This returns true a bit too much, not looking at the result type.
return value instanceof BaseFunction;
}
public static SkylarkFunctionType of(String name, SkylarkType returnType) {
return new SkylarkFunctionType(name, returnType);
}
private SkylarkFunctionType(String name, SkylarkType returnType) {
this.name = name;
this.returnType = returnType;
}
}
// Utility functions regarding types
public static SkylarkType typeOf(Object value) {
if (value == null) {
return BOTTOM;
} else if (value instanceof SkylarkNestedSet) {
return of(SET, ((SkylarkNestedSet) value).getContentType());
} else {
return Simple.forClass(value.getClass());
}
}
public static SkylarkType getGenericArgType(Object value) {
if (value instanceof SkylarkNestedSet) {
return ((SkylarkNestedSet) value).getContentType();
} else {
return TOP;
}
}
private static boolean isTypeAllowedInSkylark(Object object) {
if (object instanceof NestedSet<?>) {
return false;
} else if (object instanceof List<?> && !(object instanceof SkylarkList)) {
return false;
}
return true;
}
/**
* Throws EvalException if the type of the object is not allowed to be present in Skylark.
*/
static void checkTypeAllowedInSkylark(Object object, Location loc) throws EvalException {
if (!isTypeAllowedInSkylark(object)) {
throw new EvalException(
loc, "internal error: type '" + object.getClass().getSimpleName() + "' is not allowed");
}
}
/**
* General purpose type-casting facility.
*
* @param value - the actual value of the parameter
* @param type - the expected Class for the value
* @param loc - the location info used in the EvalException
* @param format - a format String
* @param args - arguments to format, in case there's an exception
*/
public static <T> T cast(Object value, Class<T> type,
Location loc, String format, Object... args) throws EvalException {
try {
return type.cast(value);
} catch (ClassCastException e) {
throw new EvalException(loc, String.format(format, args));
}
}
/**
* General purpose type-casting facility.
*
* @param value - the actual value of the parameter
* @param genericType - a generic class of one argument for the value
* @param argType - a covariant argument for the generic class
* @param loc - the location info used in the EvalException
* @param format - a format String
* @param args - arguments to format, in case there's an exception
*/
@SuppressWarnings("unchecked")
public static <T> T cast(Object value, Class<T> genericType, Class<?> argType,
Location loc, String format, Object... args) throws EvalException {
if (of(genericType, argType).contains(value)) {
return (T) value;
} else {
throw new EvalException(loc, String.format(format, args));
}
}
/**
* Cast a Map object into an Iterable of Map entries of the given key, value types.
* @param obj the Map object, where null designates an empty map
* @param keyType the class of map keys
* @param valueType the class of map values
* @param what a string indicating what this is about, to include in case of error
*/
@SuppressWarnings("unchecked")
public static <KEY_TYPE, VALUE_TYPE> Map<KEY_TYPE, VALUE_TYPE> castMap(Object obj,
Class<KEY_TYPE> keyType, Class<VALUE_TYPE> valueType, String what)
throws EvalException {
if (obj == null) {
return ImmutableMap.of();
}
if (!(obj instanceof Map<?, ?>)) {
throw new EvalException(
null,
String.format(
"expected a dictionary for '%s' but got '%s' instead",
what, EvalUtils.getDataTypeName(obj)));
}
for (Map.Entry<?, ?> input : ((Map<?, ?>) obj).entrySet()) {
if (!keyType.isAssignableFrom(input.getKey().getClass())
|| !valueType.isAssignableFrom(input.getValue().getClass())) {
throw new EvalException(
null,
String.format(
"expected <%s, %s> type for '%s' but got <%s, %s> instead",
keyType.getSimpleName(),
valueType.getSimpleName(),
what,
EvalUtils.getDataTypeName(input.getKey()),
EvalUtils.getDataTypeName(input.getValue())));
}
}
return (Map<KEY_TYPE, VALUE_TYPE>) obj;
}
private static Class<?> getGenericTypeFromMethod(Method method) {
// This is where we can infer generic type information, so SkylarkNestedSets can be
// created in a safe way. Eventually we should probably do something with Lists and Maps too.
ParameterizedType t = (ParameterizedType) method.getGenericReturnType();
Type type = t.getActualTypeArguments()[0];
if (type instanceof Class) {
return (Class<?>) type;
}
if (type instanceof WildcardType) {
WildcardType wildcard = (WildcardType) type;
Type upperBound = wildcard.getUpperBounds()[0];
if (upperBound instanceof Class) {
// i.e. List<? extends SuperClass>
return (Class<?>) upperBound;
}
}
// It means someone annotated a method with @SkylarkCallable with no specific generic type info.
// We shouldn't annotate methods which return List<?> or List<T>.
throw new IllegalStateException("Cannot infer type from method signature " + method);
}
/**
* Converts an object retrieved from a Java method to a Skylark-compatible type.
*/
static Object convertToSkylark(Object object, Method method, @Nullable Environment env) {
if (object instanceof NestedSet<?>) {
return new SkylarkNestedSet(getGenericTypeFromMethod(method), (NestedSet<?>) object);
}
return convertToSkylark(object, env);
}
/**
* Converts an object to a Skylark-compatible type if possible.
*/
public static Object convertToSkylark(Object object, @Nullable Environment env) {
if (object instanceof List && !(object instanceof SkylarkList)) {
return new MutableList<>((List<?>) object, env);
}
if (object instanceof SkylarkValue) {
return object;
}
if (object instanceof Map) {
return SkylarkDict.<Object, Object>copyOf(env, (Map<?, ?>) object);
}
// TODO(bazel-team): ensure everything is a SkylarkValue at all times.
// Preconditions.checkArgument(EvalUtils.isSkylarkAcceptable(
// object.getClass()),
// "invalid object %s of class %s not convertible to a Skylark value",
// object,
// object.getClass());
return object;
}
public static void checkType(Object object, Class<?> type, @Nullable Object description)
throws EvalException {
if (!type.isInstance(object)) {
throw new EvalException(
null,
Printer.format(
"expected type '%r' %sbut got type '%s' instead",
type,
description == null ? "" : String.format("for %s ", description),
EvalUtils.getDataTypeName(object)));
}
}
}
|
juhalindfors/bazel-patches
|
src/main/java/com/google/devtools/build/lib/syntax/SkylarkType.java
|
Java
|
apache-2.0
| 28,377 |
/*
* Copyright (c) 2016, WSO2 Inc. (http://wso2.com) 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 org.wso2.msf4j.internal.router;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import org.junit.Assert;
import org.junit.Test;
import java.util.List;
/**
* Test the routing logic using String as the destination.
*/
public class PathRouterTest {
@Test
public void testPathRoutings() {
PatternPathRouterWithGroups<String> pathRouter = PatternPathRouterWithGroups.create();
pathRouter.add("/foo/{baz}/b", "foobarb");
pathRouter.add("/foo/bar/baz", "foobarbaz");
pathRouter.add("/baz/bar", "bazbar");
pathRouter.add("/bar", "bar");
pathRouter.add("/foo/bar", "foobar");
pathRouter.add("//multiple/slash//route", "multipleslashroute");
pathRouter.add("/multi/match/**", "multi-match-*");
pathRouter.add("/multi/match/def", "multi-match-def");
pathRouter.add("/multi/maxmatch/**", "multi-max-match-*");
pathRouter.add("/multi/maxmatch/{id}", "multi-max-match-id");
pathRouter.add("/multi/maxmatch/foo", "multi-max-match-foo");
pathRouter.add("**/wildcard/{id}", "wildcard-id");
pathRouter.add("/**/wildcard/{id}", "slash-wildcard-id");
pathRouter.add("**/wildcard/**/foo/{id}", "wildcard-foo-id");
pathRouter.add("/**/wildcard/**/foo/{id}", "slash-wildcard-foo-id");
pathRouter.add("**/wildcard/**/foo/{id}/**", "wildcard-foo-id-2");
pathRouter.add("/**/wildcard/**/foo/{id}/**", "slash-wildcard-foo-id-2");
List<PatternPathRouterWithGroups.RoutableDestination<String>> routes;
routes = pathRouter.getDestinations("/foo/bar/baz");
Assert.assertEquals(1, routes.size());
Assert.assertEquals("foobarbaz", routes.get(0).getDestination());
Assert.assertTrue(routes.get(0).getGroupNameValues().isEmpty());
routes = pathRouter.getDestinations("/baz/bar");
Assert.assertEquals(1, routes.size());
Assert.assertEquals("bazbar", routes.get(0).getDestination());
Assert.assertTrue(routes.get(0).getGroupNameValues().isEmpty());
routes = pathRouter.getDestinations("/foo/bar/baz/moo");
Assert.assertTrue(routes.isEmpty());
routes = pathRouter.getDestinations("/bar/121");
Assert.assertTrue(routes.isEmpty());
routes = pathRouter.getDestinations("/foo/bar/b");
Assert.assertEquals(1, routes.size());
Assert.assertEquals("foobarb", routes.get(0).getDestination());
Assert.assertEquals(1, routes.get(0).getGroupNameValues().size());
Assert.assertEquals("bar", routes.get(0).getGroupNameValues().get("baz"));
routes = pathRouter.getDestinations("/foo/bar");
Assert.assertEquals(1, routes.size());
Assert.assertEquals("foobar", routes.get(0).getDestination());
Assert.assertTrue(routes.get(0).getGroupNameValues().isEmpty());
routes = pathRouter.getDestinations("/multiple/slash/route");
Assert.assertEquals(1, routes.size());
Assert.assertEquals("multipleslashroute", routes.get(0).getDestination());
Assert.assertTrue(routes.get(0).getGroupNameValues().isEmpty());
routes = pathRouter.getDestinations("/foo/bar/bazooka");
Assert.assertTrue(routes.isEmpty());
routes = pathRouter.getDestinations("/multi/match/def");
Assert.assertEquals(2, routes.size());
Assert.assertEquals(ImmutableSet.of("multi-match-def", "multi-match-*"),
ImmutableSet.of(routes.get(0).getDestination(), routes.get(1).getDestination()));
Assert.assertTrue(routes.get(0).getGroupNameValues().isEmpty());
Assert.assertTrue(routes.get(1).getGroupNameValues().isEmpty());
routes = pathRouter.getDestinations("/multi/match/ghi");
Assert.assertEquals(1, routes.size());
Assert.assertEquals("multi-match-*", routes.get(0).getDestination());
Assert.assertTrue(routes.get(0).getGroupNameValues().isEmpty());
routes = pathRouter.getDestinations("/multi/maxmatch/id1");
Assert.assertEquals(2, routes.size());
Assert.assertEquals(ImmutableSet.of("multi-max-match-id", "multi-max-match-*"),
ImmutableSet.of(routes.get(0).getDestination(), routes.get(1).getDestination()));
//noinspection Assert.assertEqualsBetweenInconvertibleTypes
Assert.assertEquals(ImmutableSet.of(ImmutableMap.of("id", "id1"), ImmutableMap.<String, String>of()),
ImmutableSet.of(routes.get(0).getGroupNameValues(), routes.get(1).getGroupNameValues())
);
routes = pathRouter.getDestinations("/multi/maxmatch/foo");
Assert.assertEquals(3, routes.size());
Assert.assertEquals(ImmutableSet.of("multi-max-match-id", "multi-max-match-*", "multi-max-match-foo"),
ImmutableSet.of(routes.get(0).getDestination(), routes.get(1).getDestination(),
routes.get(2).getDestination()));
//noinspection Assert.assertEqualsBetweenInconvertibleTypes
Assert.assertEquals(ImmutableSet.of(ImmutableMap.of("id", "foo"), ImmutableMap.<String, String>of()),
ImmutableSet.of(routes.get(0).getGroupNameValues(), routes.get(1).getGroupNameValues())
);
routes = pathRouter.getDestinations("/foo/bar/wildcard/id1");
Assert.assertEquals(2, routes.size());
Assert.assertEquals(ImmutableSet.of("wildcard-id", "slash-wildcard-id"),
ImmutableSet.of(routes.get(0).getDestination(), routes.get(1).getDestination()));
//noinspection Assert.assertEqualsBetweenInconvertibleTypes
Assert.assertEquals(ImmutableSet.of(ImmutableMap.of("id", "id1"), ImmutableMap.<String, String>of("id", "id1")),
ImmutableSet.of(routes.get(0).getGroupNameValues(), routes.get(1).getGroupNameValues())
);
routes = pathRouter.getDestinations("/wildcard/id1");
Assert.assertEquals(1, routes.size());
Assert.assertEquals("wildcard-id", routes.get(0).getDestination());
Assert.assertEquals(ImmutableMap.of("id", "id1"), routes.get(0).getGroupNameValues());
routes = pathRouter.getDestinations("/foo/bar/wildcard/bar/foo/id1");
Assert.assertEquals(2, routes.size());
Assert.assertEquals(ImmutableSet.of("wildcard-foo-id", "slash-wildcard-foo-id"),
ImmutableSet.of(routes.get(0).getDestination(), routes.get(1).getDestination()));
//noinspection Assert.assertEqualsBetweenInconvertibleTypes
Assert.assertEquals(ImmutableSet.of(ImmutableMap.of("id", "id1"), ImmutableMap.<String, String>of("id", "id1")),
ImmutableSet.of(routes.get(0).getGroupNameValues(), routes.get(1).getGroupNameValues())
);
routes = pathRouter.getDestinations("/foo/bar/wildcard/bar/foo/id1/baz/bar");
Assert.assertEquals(2, routes.size());
Assert.assertEquals(ImmutableSet.of("wildcard-foo-id-2", "slash-wildcard-foo-id-2"),
ImmutableSet.of(routes.get(0).getDestination(), routes.get(1).getDestination()));
//noinspection Assert.assertEqualsBetweenInconvertibleTypes
Assert.assertEquals(ImmutableSet.of(ImmutableMap.of("id", "id1"), ImmutableMap.<String, String>of("id", "id1")),
ImmutableSet.of(routes.get(0).getGroupNameValues(), routes.get(1).getGroupNameValues())
);
routes = pathRouter.getDestinations("/wildcard/bar/foo/id1/baz/bar");
Assert.assertEquals(1, routes.size());
Assert.assertEquals("wildcard-foo-id-2", routes.get(0).getDestination());
Assert.assertEquals(ImmutableMap.of("id", "id1"), routes.get(0).getGroupNameValues());
}
}
|
taniamahanama/product-msf4j
|
core/src/test/java/org/wso2/msf4j/internal/router/PathRouterTest.java
|
Java
|
apache-2.0
| 8,334 |
package org.soa;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.LinkedBlockingQueue;
import jmetal.core.Variable;
import jmetal.encodings.variable.Int;
import jmetal.util.JMException;
import java.util.Comparator;
import org.femosaa.core.SASSolution;
import org.ssase.objective.Objective;
import org.ssase.objective.optimization.bb.BranchAndBoundRegion;
import org.ssase.objective.optimization.femosaa.FEMOSAASolution;
import org.ssase.primitive.ControlPrimitive;
import org.ssase.primitive.EnvironmentalPrimitive;
import org.ssase.primitive.Primitive;
import org.ssase.primitive.SoftwareControlPrimitive;
import org.ssase.region.Region;
import org.ssase.util.Repository;
/**
* This is just for SOA case
* @author tao
*
*/
public class ExtendedBB extends Region{
protected static final long EXECUTION_TIME = 40000;
@Override
public LinkedHashMap<ControlPrimitive, Double> optimize() {
LinkedHashMap<ControlPrimitive, Double> current = new LinkedHashMap<ControlPrimitive, Double>();
synchronized (lock) {
while (waitingUpdateCounter != 0) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
isLocked = true;
List<ControlPrimitive> tempList = Repository
.getSortedControlPrimitives(objectives.get(0));
List<ControlPrimitive> list = new ArrayList<ControlPrimitive>();
list.addAll(tempList);
addRemoveFeatureFor01Representation(list);
sortForDependency(list);
Map<Objective, Double> map = getBasis();
double[] currentDecision = new double[list.size()];
Node best = null;
Double[] bestResult = null;
for (Objective obj : objectives) {
for (Primitive p : obj.getPrimitivesInput()) {
if (p instanceof ControlPrimitive) {
current.put((ControlPrimitive) p,
(double) p.getProvision());
currentDecision[list.indexOf((ControlPrimitive) p)] = (double) p
.getProvision();
}
}
}
for (ControlPrimitive cp : list) {
if (!current.containsKey(cp)) {
current.put(cp, (double) cp.getProvision());
currentDecision[list.indexOf(cp)] = cp.getProvision();
}
}
LinkedBlockingQueue<Node> q = new LinkedBlockingQueue<Node>();
// for (double d : list.get(0).getValueVector()) {
// q.offer(new Node(0, d, currentDecision));
// }
for (int i = list.get(0).getValueVector().length-1; i >= 0 ; i--) {
q.offer(new Node(0, list.get(0).getValueVector()[i], currentDecision));
}
long start = System.currentTimeMillis();
int count = 0;
do {
// To avoid an extrmely long runtime
if ((System.currentTimeMillis() - start) > EXECUTION_TIME) {
break;
}
count++;
// System.out.print("Run " + count + "\n");
Node node = q.poll();
Double[] v = doWeightSum(list, node.decision, map);
if (bestResult == null || v[0] > bestResult[0]) {
best = node;
bestResult = v;
}
if (node.index + 1 < list.size()) {
// for (double d : list.get(node.index + 1).getValueVector()) {
// q.offer(new Node(node.index + 1, d, node.decision));
// }
for (int i = list.get(0).getValueVector().length-1; i >= 0 ; i--) {
q.offer(new Node(node.index + 1, list.get(0).getValueVector()[i], node.decision));
}
}
} while (!q.isEmpty());
q.clear();
for (int i = 0; i < best.decision.length; i++) {
current.put(list.get(i), best.decision[i]);
}
for (ControlPrimitive cp : list) {
if (!tempList.contains(cp)) {
current.remove(cp);
}
}
list = tempList;
// Starting the dependency check and log
double[][] optionalVariables = new double[list.size()][];
for (int i = 0; i < optionalVariables.length; i++) {
optionalVariables[i] = list.get(i).getValueVector();
}
// This is a static method
SASSolution.init(optionalVariables);
SASSolution.clearAndStoreForValidationOnly();
FEMOSAASolution dummy = new FEMOSAASolution();
dummy.init(objectives, null);
Variable[] variables = new Variable[list.size()];
for (int i = 0; i < list.size(); i++) {
variables[i] = new Int(0,
list.get(i).getValueVector().length - 1);
}
dummy.setDecisionVariables(variables);
for (int i = 0; i < list.size(); i++) {
double v = current.get(list.get(i));
double value = 0;
for (int j = 0; j < list.get(i).getValueVector().length; j++) {
if (list.get(i).getValueVector()[j] == v) {
value = j;
break;
}
}
//System.out.print(list.get(i).getName() + ", v=" + v + ", index=" + value +"\n");
try {
dummy.getDecisionVariables()[i].setValue(value);
} catch (JMException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Region.logDependencyForFinalSolution(dummy);
if (!dummy.isSolutionValid()) {
try {
dummy.correctDependency();
current.clear();
for (int i = 0; i < list.size(); i++) {
current.put(list.get(i),
list.get(i).getValueVector()[ (int)dummy.getDecisionVariables()[i].getValue()]);
}
System.out
.print("The final result does not satisfy all dependency, thus correct it\n");
} catch (JMException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
print(current);
isLocked = false;
lock.notifyAll();
}
System.out
.print("================= Finish optimization ! =================\n");
return current;
}
private Double[] doWeightSum(List<ControlPrimitive> list,
double[] decision, Map<Objective, Double> map) {
double result = 0;
double satisfied = 1;
double[] xValue;
double w = 1.0 / objectives.size();
for (Objective obj : objectives) {
xValue = new double[obj.getPrimitivesInput().size()];
// System.out.print(obj.getPrimitivesInput().size()+"\n");
for (int i = 0; i < obj.getPrimitivesInput().size(); i++) {
if (obj.getPrimitivesInput().get(i) instanceof ControlPrimitive) {
xValue[i] = decision[list.indexOf(obj.getPrimitivesInput()
.get(i))];
} else {
xValue[i] = ((EnvironmentalPrimitive) obj
.getPrimitivesInput().get(i)).getLatest();
}
}
if (!obj.isSatisfied(xValue)) {
// System.out.print(obj.getName() + " is not satisfied " +
// obj.predict(xValue) + "\n");
// throw new RuntimeException();
satisfied = -1;
}
result = obj.isMin() ? result - w
* (obj.predict(xValue) / (1 + map.get(obj))) : result + w
* (obj.predict(xValue) / (1 + map.get(obj)));
}
return new Double[] { result, satisfied };
}
private Map<Objective, Double> getBasis() throws RuntimeException {
Map<Objective, Double> map = new HashMap<Objective, Double>();
double[] xValue;
for (Objective obj : objectives) {
xValue = new double[obj.getPrimitivesInput().size()];
// System.out.print(obj.getPrimitivesInput().size()+"\n");
for (int i = 0; i < obj.getPrimitivesInput().size(); i++) {
if (obj.getPrimitivesInput().get(i) instanceof ControlPrimitive) {
xValue[i] = obj.getPrimitivesInput().get(i).getProvision();
} else {
xValue[i] = ((EnvironmentalPrimitive) obj
.getPrimitivesInput().get(i)).getLatest();
}
}
map.put(obj, obj.predict(xValue));
}
return map;
}
protected double[] getValueVector(Node node, List<ControlPrimitive> list) {
//System.out.print("count " + list.get(node.index).getName() +"\n");
if (list.get(node.index).getName().equals("CS12")) {
double[] r = null;
for (int i = 0; i < node.index; i++) {
if (list.get(i).getName().equals("CS11")
&& node.decision[i] != 0.0) {
return new double[] { 0.0 };
}
if (r != null) {
return r;
}
}
}
if (list.get(node.index).getName().equals("CS15")) {
double[] r = null;
for (int i = 0; i < node.index; i++) {
if (list.get(i).getName().equals("CS11")
&& node.decision[i] != 0.0) {
return new double[] { 0.0 };
}
if (r != null) {
return r;
}
}
}
if (list.get(node.index).getName().equals("CS22")) {
double[] r = null;
for (int i = 0; i < node.index; i++) {
if (list.get(i).getName().equals("CS13")
&& node.decision[i] == 0.0) {
return new double[] { 0.0 };
}
if (r != null) {
return r;
}
}
}
if (list.get(node.index).getName().equals("CS14")) {
double[] r = null;
int count = 0;
for (int i = 0; i < node.index; i++) {
if (list.get(i).getName().equals("CS11")
&& node.decision[i] == 0.0) {
count++;
}
if (list.get(i).getName().equals("CS12")
&& node.decision[i] == 0.0) {
count++;
}
if (list.get(i).getName().equals("CS13")
&& node.decision[i] == 0.0) {
count++;
}
if (list.get(i).getName().equals("CS15")
&& node.decision[i] == 0.0) {
count++;
}
}
if(count == 4) {
return new double[] { 1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0 };
}
}
if (list.get(node.index).getName().equals("CS24")) {
double[] r = null;
int count = 0;
for (int i = 0; i < node.index; i++) {
if (list.get(i).getName().equals("CS21")
&& node.decision[i] == 0.0) {
count++;
}
if (list.get(i).getName().equals("CS22")
&& node.decision[i] == 0.0) {
count++;
}
if (list.get(i).getName().equals("CS23")
&& node.decision[i] == 0.0) {
count++;
}
}
if(count == 3) {
return new double[] { 1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0 };
}
}
if (list.get(node.index).getName().equals("CS34")) {
double[] r = null;
int count = 0;
for (int i = 0; i < node.index; i++) {
if (list.get(i).getName().equals("CS31")
&& node.decision[i] == 0.0) {
count++;
}
if (list.get(i).getName().equals("CS32")
&& node.decision[i] == 0.0) {
count++;
}
if (list.get(i).getName().equals("CS33")
&& node.decision[i] == 0.0) {
count++;
}
}
if(count == 3) {
return new double[] { 1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0 };
}
}
if (list.get(node.index).getName().equals("CS42")) {
double[] r = null;
int count = 0;
for (int i = 0; i < node.index; i++) {
if (list.get(i).getName().equals("CS41")
&& node.decision[i] == 0.0) {
count++;
}
}
if(count == 1) {
return new double[] { 1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0 };
}
}
if (list.get(node.index).getName().equals("CS53")) {
double[] r = null;
int count = 0;
for (int i = 0; i < node.index; i++) {
if (list.get(i).getName().equals("CS51")
&& node.decision[i] == 0.0) {
count++;
}
if (list.get(i).getName().equals("CS52")
&& node.decision[i] == 0.0) {
count++;
}
}
if(count == 2) {
return new double[] { 1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0 };
}
}
return list.get(node.index).getValueVector();
}
private void sortForDependency(List<ControlPrimitive> list) {
// Collections.sort(list, new Comparator(){
//
// public int compare(Object o1, Object o2) {
// //System.out.print(((ControlPrimitive)o1).getName() + "*****\n");
// int i1 = Integer.parseInt(((ControlPrimitive)o1).getName().substring(2, 3));
// int i2 = Integer.parseInt(((ControlPrimitive)o2).getName().substring(2, 3));
// return i1 < i2? -1 : 1;
// }
//
// });
//
// ControlPrimitive cp3 = list.get(3);
// list.remove(3);
// list.add(4, cp3);
//
// System.out.print("after sorted\n");
// for (ControlPrimitive cp : list) {
// System.out.print(cp.getName() + "\n");
// }
Collections.shuffle(list);
}
private void addRemoveFeatureFor01Representation(List<ControlPrimitive> list) {
// SoftwareControlPrimitive c = null;
//
// c = new SoftwareControlPrimitive("cache", "sas", false, null, null, 1,
// 1, 1, 1, 1, 1, 1, true);
// c.setValueVector(new double[] { 0, 1 });
// c.setProvision(1);
// list.add(c);
//
// c = new SoftwareControlPrimitive("cache_config", "sas", false, null,
// null, 1, 1, 1, 1, 1, 1, 1, true);
// c.setValueVector(new double[] { 1 });
// c.setProvision(1);
// list.add(c);
//
// c = new SoftwareControlPrimitive("thread_pool", "sas", false, null,
// null, 1, 1, 1, 1, 1, 1, 1, true);
// c.setValueVector(new double[] { 1 });
// c.setProvision(1);
// list.add(c);
//
// c = new SoftwareControlPrimitive("connection_pool", "sas", false, null,
// null, 1, 1, 1, 1, 1, 1, 1, true);
// c.setValueVector(new double[] { 1 });
// c.setProvision(1);
// list.add(c);
//
// c = new SoftwareControlPrimitive("database", "sas", false, null, null,
// 1, 1, 1, 1, 1, 1, 1, true);
// c.setValueVector(new double[] { 1 });
// c.setProvision(1);
// list.add(c);
//
// c = new SoftwareControlPrimitive("database", "sas", false, null, null,
// 1, 1, 1, 1, 1, 1, 1, true);
// c.setValueVector(new double[] { 1 });
// c.setProvision(1);
// list.add(c);
}
protected class Node {
protected int index;
protected double[] decision;
public Node(int index, double value, double[] given) {
this.index = index;
decision = new double[given.length];
for (int i = 0; i < given.length; i++) {
decision[i] = given[i];
}
decision[index] = value;
}
}
}
|
taochen/ssase
|
adaptable-software/soa/src/main/java/org/soa/ExtendedBB.java
|
Java
|
apache-2.0
| 13,454 |
// Code generated by go-swagger; DO NOT EDIT.
package cluster
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"net/http"
"time"
"github.com/go-openapi/errors"
"github.com/go-openapi/runtime"
cr "github.com/go-openapi/runtime/client"
"github.com/go-openapi/strfmt"
"github.com/go-openapi/swag"
"github.com/netapp/trident/storage_drivers/ontap/api/rest/models"
)
// NewClusterNtpServersCreateParams creates a new ClusterNtpServersCreateParams object,
// with the default timeout for this client.
//
// Default values are not hydrated, since defaults are normally applied by the API server side.
//
// To enforce default values in parameter, use SetDefaults or WithDefaults.
func NewClusterNtpServersCreateParams() *ClusterNtpServersCreateParams {
return &ClusterNtpServersCreateParams{
timeout: cr.DefaultTimeout,
}
}
// NewClusterNtpServersCreateParamsWithTimeout creates a new ClusterNtpServersCreateParams object
// with the ability to set a timeout on a request.
func NewClusterNtpServersCreateParamsWithTimeout(timeout time.Duration) *ClusterNtpServersCreateParams {
return &ClusterNtpServersCreateParams{
timeout: timeout,
}
}
// NewClusterNtpServersCreateParamsWithContext creates a new ClusterNtpServersCreateParams object
// with the ability to set a context for a request.
func NewClusterNtpServersCreateParamsWithContext(ctx context.Context) *ClusterNtpServersCreateParams {
return &ClusterNtpServersCreateParams{
Context: ctx,
}
}
// NewClusterNtpServersCreateParamsWithHTTPClient creates a new ClusterNtpServersCreateParams object
// with the ability to set a custom HTTPClient for a request.
func NewClusterNtpServersCreateParamsWithHTTPClient(client *http.Client) *ClusterNtpServersCreateParams {
return &ClusterNtpServersCreateParams{
HTTPClient: client,
}
}
/* ClusterNtpServersCreateParams contains all the parameters to send to the API endpoint
for the cluster ntp servers create operation.
Typically these are written to a http.Request.
*/
type ClusterNtpServersCreateParams struct {
/* Info.
Information specification
*/
Info *models.NtpServer
/* ReturnRecords.
The default is false. If set to true, the records are returned.
*/
ReturnRecordsQueryParameter *bool
/* ReturnTimeout.
The number of seconds to allow the call to execute before returning. When doing a POST, PATCH, or DELETE operation on a single record, the default is 0 seconds. This means that if an asynchronous operation is started, the server immediately returns HTTP code 202 (Accepted) along with a link to the job. If a non-zero value is specified for POST, PATCH, or DELETE operations, ONTAP waits that length of time to see if the job completes so it can return something other than 202.
*/
ReturnTimeoutQueryParameter *int64
timeout time.Duration
Context context.Context
HTTPClient *http.Client
}
// WithDefaults hydrates default values in the cluster ntp servers create params (not the query body).
//
// All values with no default are reset to their zero value.
func (o *ClusterNtpServersCreateParams) WithDefaults() *ClusterNtpServersCreateParams {
o.SetDefaults()
return o
}
// SetDefaults hydrates default values in the cluster ntp servers create params (not the query body).
//
// All values with no default are reset to their zero value.
func (o *ClusterNtpServersCreateParams) SetDefaults() {
var (
returnRecordsQueryParameterDefault = bool(false)
returnTimeoutQueryParameterDefault = int64(0)
)
val := ClusterNtpServersCreateParams{
ReturnRecordsQueryParameter: &returnRecordsQueryParameterDefault,
ReturnTimeoutQueryParameter: &returnTimeoutQueryParameterDefault,
}
val.timeout = o.timeout
val.Context = o.Context
val.HTTPClient = o.HTTPClient
*o = val
}
// WithTimeout adds the timeout to the cluster ntp servers create params
func (o *ClusterNtpServersCreateParams) WithTimeout(timeout time.Duration) *ClusterNtpServersCreateParams {
o.SetTimeout(timeout)
return o
}
// SetTimeout adds the timeout to the cluster ntp servers create params
func (o *ClusterNtpServersCreateParams) SetTimeout(timeout time.Duration) {
o.timeout = timeout
}
// WithContext adds the context to the cluster ntp servers create params
func (o *ClusterNtpServersCreateParams) WithContext(ctx context.Context) *ClusterNtpServersCreateParams {
o.SetContext(ctx)
return o
}
// SetContext adds the context to the cluster ntp servers create params
func (o *ClusterNtpServersCreateParams) SetContext(ctx context.Context) {
o.Context = ctx
}
// WithHTTPClient adds the HTTPClient to the cluster ntp servers create params
func (o *ClusterNtpServersCreateParams) WithHTTPClient(client *http.Client) *ClusterNtpServersCreateParams {
o.SetHTTPClient(client)
return o
}
// SetHTTPClient adds the HTTPClient to the cluster ntp servers create params
func (o *ClusterNtpServersCreateParams) SetHTTPClient(client *http.Client) {
o.HTTPClient = client
}
// WithInfo adds the info to the cluster ntp servers create params
func (o *ClusterNtpServersCreateParams) WithInfo(info *models.NtpServer) *ClusterNtpServersCreateParams {
o.SetInfo(info)
return o
}
// SetInfo adds the info to the cluster ntp servers create params
func (o *ClusterNtpServersCreateParams) SetInfo(info *models.NtpServer) {
o.Info = info
}
// WithReturnRecordsQueryParameter adds the returnRecords to the cluster ntp servers create params
func (o *ClusterNtpServersCreateParams) WithReturnRecordsQueryParameter(returnRecords *bool) *ClusterNtpServersCreateParams {
o.SetReturnRecordsQueryParameter(returnRecords)
return o
}
// SetReturnRecordsQueryParameter adds the returnRecords to the cluster ntp servers create params
func (o *ClusterNtpServersCreateParams) SetReturnRecordsQueryParameter(returnRecords *bool) {
o.ReturnRecordsQueryParameter = returnRecords
}
// WithReturnTimeoutQueryParameter adds the returnTimeout to the cluster ntp servers create params
func (o *ClusterNtpServersCreateParams) WithReturnTimeoutQueryParameter(returnTimeout *int64) *ClusterNtpServersCreateParams {
o.SetReturnTimeoutQueryParameter(returnTimeout)
return o
}
// SetReturnTimeoutQueryParameter adds the returnTimeout to the cluster ntp servers create params
func (o *ClusterNtpServersCreateParams) SetReturnTimeoutQueryParameter(returnTimeout *int64) {
o.ReturnTimeoutQueryParameter = returnTimeout
}
// WriteToRequest writes these params to a swagger request
func (o *ClusterNtpServersCreateParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error {
if err := r.SetTimeout(o.timeout); err != nil {
return err
}
var res []error
if o.Info != nil {
if err := r.SetBodyParam(o.Info); err != nil {
return err
}
}
if o.ReturnRecordsQueryParameter != nil {
// query param return_records
var qrReturnRecords bool
if o.ReturnRecordsQueryParameter != nil {
qrReturnRecords = *o.ReturnRecordsQueryParameter
}
qReturnRecords := swag.FormatBool(qrReturnRecords)
if qReturnRecords != "" {
if err := r.SetQueryParam("return_records", qReturnRecords); err != nil {
return err
}
}
}
if o.ReturnTimeoutQueryParameter != nil {
// query param return_timeout
var qrReturnTimeout int64
if o.ReturnTimeoutQueryParameter != nil {
qrReturnTimeout = *o.ReturnTimeoutQueryParameter
}
qReturnTimeout := swag.FormatInt64(qrReturnTimeout)
if qReturnTimeout != "" {
if err := r.SetQueryParam("return_timeout", qReturnTimeout); err != nil {
return err
}
}
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
|
NetApp/trident
|
storage_drivers/ontap/api/rest/client/cluster/cluster_ntp_servers_create_parameters.go
|
GO
|
apache-2.0
| 7,672 |
/**
* @module utils
*/
const crypto = require( 'crypto' );
const config = require( '../models/config-model' ).server;
const validUrl = require( 'valid-url' );
// var debug = require( 'debug' )( 'utils' );
/**
* Returns a unique, predictable openRosaKey from a survey oject
*
* @static
* @param {module:survey-model~SurveyObject} survey
* @param {string} [prefix]
* @return {string|null} openRosaKey
*/
function getOpenRosaKey( survey, prefix ) {
if ( !survey || !survey.openRosaServer || !survey.openRosaId ) {
return null;
}
prefix = prefix || 'or:';
// Server URL is not case sensitive, form ID is case-sensitive
return `${prefix + cleanUrl( survey.openRosaServer )},${survey.openRosaId.trim()}`;
}
/**
* Returns a XForm manifest hash.
*
* @static
* @param {Array} manifest
* @param {string} type - Webform type
* @return {string} Hash
*/
function getXformsManifestHash( manifest, type ) {
const hash = '';
if ( !manifest || manifest.length === 0 ) {
return hash;
}
if ( type === 'all' ) {
return md5( JSON.stringify( manifest ) );
}
if ( type ) {
const filtered = manifest.map( mediaFile => mediaFile[ type ] );
return md5( JSON.stringify( filtered ) );
}
return hash;
}
/**
* Cleans a Server URL so it becomes useful as a db key
* It strips the protocol, removes a trailing slash, removes www, and converts to lowercase
*
* @static
* @param {string} url - Url to be cleaned up
* @return {string} Cleaned up url
*/
function cleanUrl( url ) {
url = url.trim();
if ( url.lastIndexOf( '/' ) === url.length - 1 ) {
url = url.substring( 0, url.length - 1 );
}
const matches = url.match( /https?:\/\/(www\.)?(.+)/ );
if ( matches && matches.length > 2 ) {
return matches[ 2 ].toLowerCase();
}
return url;
}
/**
* The name of this function is deceiving. It checks for a valid server URL and therefore doesn't approve of:
* - fragment identifiers
* - query strings
*
* @static
* @param {string} url - Url to be validated
* @return {boolean} Whether the url is valid
*/
function isValidUrl( url ) {
return !!validUrl.isWebUri( url ) && !( /\?/.test( url ) ) && !( /#/.test( url ) );
}
/**
* Returns md5 hash of given message
*
* @static
* @param {string} message - Message to be hashed
* @return {string} Hash string
*/
function md5( message ) {
const hash = crypto.createHash( 'md5' );
hash.update( message );
return hash.digest( 'hex' );
}
/**
* This is not secure encryption as it doesn't use a random cipher. Therefore the result is
* always the same for each text & pw (which is desirable in this case).
* This means the password is vulnerable to be cracked,
* and we should use a dedicated low-importance password for this.
*
* @static
* @param {string} text - The text to be encrypted
* @param {string} pw - The password to use for encryption
* @return {string} The encrypted result
*/
function insecureAes192Encrypt( text, pw ) {
let encrypted;
const cipher = crypto.createCipher( 'aes192', pw );
encrypted = cipher.update( text, 'utf8', 'hex' );
encrypted += cipher.final( 'hex' );
return encrypted;
}
/**
* Decrypts encrypted text.
*
* @static
* @param {*} encrypted - The text to be decrypted
* @param {*} pw - The password to use for decryption
* @return {string} The decrypted result
*/
function insecureAes192Decrypt( encrypted, pw ) {
let decrypted;
const decipher = crypto.createDecipher( 'aes192', pw );
decrypted = decipher.update( encrypted, 'hex', 'utf8' );
decrypted += decipher.final( 'utf8' );
return decrypted;
}
/**
* Returns random howMany-lengthed string from provided characters.
*
* @static
* @param {number} [howMany] - Desired length of string
* @param {string} [chars] - Characters to use
* @return {string} Random string
*/
function randomString( howMany = 8, chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' ) {
const rnd = crypto.randomBytes( howMany );
return new Array( howMany )
.fill() // create indices, so map can iterate
.map( ( val, i ) => chars[ rnd[ i ] % chars.length ] )
.join( '' );
}
/**
* Returns random item from array.
*
* @static
* @param {Array} array - Target array
* @return {*|null} Random array item
*/
function pickRandomItemFromArray( array ) {
if ( !Array.isArray( array ) || array.length === 0 ) {
return null;
}
const random = Math.floor( Math.random() * array.length );
if ( !array[ random ] ) {
return null;
}
return array[ random ];
}
/**
* Compares two objects by shallow properties.
*
* @static
* @param {object} a - First object to be compared
* @param {object} b - Second object to be compared
* @return {null|boolean} Whether objects are equal (`null` for invalid arguments)
*/
function areOwnPropertiesEqual( a, b ) {
let prop;
const results = [];
if ( typeof a !== 'object' || typeof b !== 'object' ) {
return null;
}
for ( prop in a ) {
if ( Object.prototype.hasOwnProperty.call( a, prop ) ) {
if ( a[ prop ] !== b[ prop ] ) {
return false;
}
results[ prop ] = true;
}
}
for ( prop in b ) {
if ( !results[ prop ] && Object.prototype.hasOwnProperty.call( b, prop ) ) {
if ( b[ prop ] !== a[ prop ] ) {
return false;
}
}
}
return true;
}
/**
* Converts a url to a local (proxied) url.
*
* @static
* @param {string} url - The url to convert
* @return {string} The converted url
*/
function toLocalMediaUrl( url ) {
const localUrl = `${config[ 'base path' ]}/media/get/${url.replace( /(https?):\/\//, '$1/' )}`;
return localUrl;
}
module.exports = {
getOpenRosaKey,
getXformsManifestHash,
cleanUrl,
isValidUrl,
md5,
randomString,
pickRandomItemFromArray,
areOwnPropertiesEqual,
insecureAes192Decrypt,
insecureAes192Encrypt,
toLocalMediaUrl
};
|
kobotoolbox/enketo-express
|
app/lib/utils.js
|
JavaScript
|
apache-2.0
| 6,115 |
package org.spanna.reflect;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
public interface ReflectiveObject {
public boolean locate(ClassReader cr);
public boolean initializeReference();
public String getName();
public String getObfuscatedName();
public boolean isInitialized();
public boolean isFound();
}
|
SpannaProject/SpannaAPI
|
src/main/java/org/spanna/reflect/ReflectiveObject.java
|
Java
|
apache-2.0
| 371 |
package org.neotech.library.retainabletasks.internal;
import androidx.annotation.RestrictTo;
import org.neotech.library.retainabletasks.TaskManager;
/**
* Created by Rolf on 4-3-2016.
*/
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
public class TaskRetainingFragmentLogic {
private final BaseTaskManager taskManager = new BaseTaskManager();
public BaseTaskManager getTaskManager(){
return taskManager;
}
public void assertActivityTasksAreDetached(){
if(!TaskManager.isStrictDebugModeEnabled()){
return;
}
taskManager.assertAllTasksDetached();
}
}
|
NeoTech-Software/Android-Retainable-Tasks
|
library/src/main/java/org/neotech/library/retainabletasks/internal/TaskRetainingFragmentLogic.java
|
Java
|
apache-2.0
| 618 |
/*
* Copyright (C) 2014 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.phearom.um.playback;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.media.MediaMetadataCompat;
import android.support.v4.media.session.MediaSessionCompat;
import com.phearom.um.AlbumArtCache;
import com.phearom.um.R;
import com.phearom.um.model.MusicProvider;
import com.phearom.um.model.MyMusicProvider;
import com.phearom.um.utils.LogHelper;
import com.phearom.um.utils.MediaIDHelper;
import com.phearom.um.utils.QueueHelper;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* Simple data provider for queues. Keeps track of a current queue and a current index in the
* queue. Also provides methods to set the current queue based on common queries, relying on a
* given MusicProvider to provide the actual media metadata.
*/
public class QueueManager {
private static final String TAG = LogHelper.makeLogTag(QueueManager.class);
private MyMusicProvider mMusicProvider;
private MetadataUpdateListener mListener;
private Resources mResources;
// "Now playing" queue:
private List<MediaSessionCompat.QueueItem> mPlayingQueue;
private int mCurrentIndex;
public QueueManager(@NonNull MyMusicProvider musicProvider,
@NonNull Resources resources,
@NonNull MetadataUpdateListener listener) {
this.mMusicProvider = musicProvider;
this.mListener = listener;
this.mResources = resources;
mPlayingQueue = Collections.synchronizedList(new ArrayList<MediaSessionCompat.QueueItem>());
mCurrentIndex = 0;
}
public boolean isSameBrowsingCategory(@NonNull String mediaId) {
String[] newBrowseHierarchy = MediaIDHelper.getHierarchy(mediaId);
MediaSessionCompat.QueueItem current = getCurrentMusic();
if (current == null) {
return false;
}
String[] currentBrowseHierarchy = MediaIDHelper.getHierarchy(
current.getDescription().getMediaId());
return Arrays.equals(newBrowseHierarchy, currentBrowseHierarchy);
}
private void setCurrentQueueIndex(int index) {
if (index >= 0 && index < mPlayingQueue.size()) {
mCurrentIndex = index;
mListener.onCurrentQueueIndexUpdated(mCurrentIndex);
}
}
public boolean setCurrentQueueItem(long queueId) {
// set the current index on queue from the queue Id:
int index = QueueHelper.getMusicIndexOnQueue(mPlayingQueue, queueId);
setCurrentQueueIndex(index);
return index >= 0;
}
public boolean setCurrentQueueItem(String mediaId) {
// set the current index on queue from the music Id:
int index = QueueHelper.getMusicIndexOnQueue(mPlayingQueue, mediaId);
setCurrentQueueIndex(index);
return index >= 0;
}
public boolean skipQueuePosition(int amount) {
int index = mCurrentIndex + amount;
if (index < 0) {
// skip backwards before the first song will keep you on the first song
index = 0;
} else {
// skip forwards when in last song will cycle back to start of the queue
index %= mPlayingQueue.size();
}
if (!QueueHelper.isIndexPlayable(index, mPlayingQueue)) {
LogHelper.e(TAG, "Cannot increment queue index by ", amount,
". Current=", mCurrentIndex, " queue length=", mPlayingQueue.size());
return false;
}
mCurrentIndex = index;
return true;
}
public boolean setQueueFromSearch(String query, Bundle extras) {
List<MediaSessionCompat.QueueItem> queue =
QueueHelper.getPlayingQueueFromSearch(query, extras, mMusicProvider);
setCurrentQueue(mResources.getString(R.string.search_queue_title), queue);
return queue != null && !queue.isEmpty();
}
public void setRandomQueue() {
setCurrentQueue(mResources.getString(R.string.random_queue_title),
QueueHelper.getRandomQueue(mMusicProvider));
}
public void setQueueFromMusic(String mediaId) {
LogHelper.d(TAG, "setQueueFromMusic", mediaId);
// The mediaId used here is not the unique musicId. This one comes from the
// MediaBrowser, and is actually a "hierarchy-aware mediaID": a concatenation of
// the hierarchy in MediaBrowser and the actual unique musicID. This is necessary
// so we can build the correct playing queue, based on where the track was
// selected from.
boolean canReuseQueue = false;
if (isSameBrowsingCategory(mediaId)) {
canReuseQueue = setCurrentQueueItem(mediaId);
}
if (!canReuseQueue) {
String queueTitle = mResources.getString(R.string.browse_musics_by_genre_subtitle,
MediaIDHelper.extractBrowseCategoryValueFromMediaID(mediaId));
setCurrentQueue(queueTitle,
QueueHelper.getPlayingQueue(mediaId, mMusicProvider), mediaId);
}
updateMetadata();
}
public MediaSessionCompat.QueueItem getCurrentMusic() {
if (!QueueHelper.isIndexPlayable(mCurrentIndex, mPlayingQueue)) {
return null;
}
return mPlayingQueue.get(mCurrentIndex);
}
public int getCurrentQueueSize() {
if (mPlayingQueue == null) {
return 0;
}
return mPlayingQueue.size();
}
protected void setCurrentQueue(String title, List<MediaSessionCompat.QueueItem> newQueue) {
setCurrentQueue(title, newQueue, null);
}
protected void setCurrentQueue(String title, List<MediaSessionCompat.QueueItem> newQueue,
String initialMediaId) {
mPlayingQueue = newQueue;
int index = 0;
if (initialMediaId != null) {
index = QueueHelper.getMusicIndexOnQueue(mPlayingQueue, initialMediaId);
}
mCurrentIndex = Math.max(index, 0);
mListener.onQueueUpdated(title, newQueue);
}
public void updateMetadata() {
MediaSessionCompat.QueueItem currentMusic = getCurrentMusic();
if (currentMusic == null) {
mListener.onMetadataRetrieveError();
return;
}
final String musicId = MediaIDHelper.extractMusicIDFromMediaID(
currentMusic.getDescription().getMediaId());
MediaMetadataCompat metadata = mMusicProvider.getMusic(musicId);
if (metadata == null) {
throw new IllegalArgumentException("Invalid musicId " + musicId);
}
mListener.onMetadataChanged(metadata);
// Set the proper album artwork on the media session, so it can be shown in the
// locked screen and in other places.
if (metadata.getDescription().getIconBitmap() == null &&
metadata.getDescription().getIconUri() != null) {
String albumUri = metadata.getDescription().getIconUri().toString();
AlbumArtCache.getInstance().fetch(albumUri, new AlbumArtCache.FetchListener() {
@Override
public void onFetched(String artUrl, Bitmap bitmap, Bitmap icon) {
mMusicProvider.updateMusicArt(musicId, bitmap, icon);
// If we are still playing the same music, notify the listeners:
MediaSessionCompat.QueueItem currentMusic = getCurrentMusic();
if (currentMusic == null) {
return;
}
String currentPlayingId = MediaIDHelper.extractMusicIDFromMediaID(
currentMusic.getDescription().getMediaId());
if (musicId.equals(currentPlayingId)) {
mListener.onMetadataChanged(mMusicProvider.getMusic(currentPlayingId));
}
}
});
}
}
public interface MetadataUpdateListener {
void onMetadataChanged(MediaMetadataCompat metadata);
void onMetadataRetrieveError();
void onCurrentQueueIndexUpdated(int queueIndex);
void onQueueUpdated(String title, List<MediaSessionCompat.QueueItem> newQueue);
}
}
|
povphearom/UMusicPlayer
|
app/src/main/java/com/phearom/um/playback/QueueManager.java
|
Java
|
apache-2.0
| 8,980 |
#
# Cookbook Name:: tabelle
# Recipe:: default
#
# Copyright 2016, YOUR_COMPANY_NAME
#
# All rights reserved - Do Not Redistribute
#
|
pimu/chef-repo
|
cookbooks/tabelle/recipes/default.rb
|
Ruby
|
apache-2.0
| 133 |
// Copyright 2017 Jose Luis Rovira Martin
//
// 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.
using System.Collections.Generic;
namespace Essence.Util.Collections.Iterators
{
public struct ListIt<TValue>
{
public ListIt(IList<TValue> list, int i = 0)
{
this.list = list;
this.i = i;
}
public static bool operator ==(ListIt<TValue> it1, ListIt<TValue> it2)
{
return it1.i == it2.i;
}
public static bool operator !=(ListIt<TValue> it1, ListIt<TValue> it2)
{
return it1.i != it2.i;
}
public void Inc(int c)
{
this.i += c;
}
public void Inc()
{
this.i++;
}
public void Dec()
{
this.i--;
}
public TValue Get()
{
return this.list[this.i];
}
#region private
private readonly IList<TValue> list;
private int i;
#endregion
#region object
public override bool Equals(object obj)
{
if (!(obj is ListIt<TValue>))
{
return false;
}
ListIt<TValue> other = (ListIt<TValue>)obj;
return this.i == other.i;
}
public override int GetHashCode()
{
return this.i.GetHashCode();
}
public override string ToString()
{
return this.i.ToString();
}
#endregion
}
}
|
jlroviramartin/Essence
|
Essence.Util/Collections/Iterators/ListIt.cs
|
C#
|
apache-2.0
| 2,147 |
/*
* Copyright 2015 Open Networking Laboratory
*
* 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.onosproject.driver.query;
import java.util.Set;
import java.util.stream.IntStream;
import org.onlab.packet.VlanId;
import org.onlab.util.GuavaCollectors;
import org.onosproject.net.PortNumber;
import org.onosproject.net.behaviour.VlanQuery;
import org.onosproject.net.driver.AbstractHandlerBehaviour;
import com.google.common.annotations.Beta;
/**
* Driver which always responds that all VLAN IDs are available for the Device.
*/
@Beta
public class FullVlanAvailable
extends AbstractHandlerBehaviour
implements VlanQuery {
private static final int MAX_VLAN_ID = VlanId.MAX_VLAN;
private static final Set<VlanId> ENTIRE_VLAN = getEntireVlans();
@Override
public Set<VlanId> queryVlanIds(PortNumber port) {
return ENTIRE_VLAN;
}
private static Set<VlanId> getEntireVlans() {
return IntStream.range(0, MAX_VLAN_ID)
.mapToObj(x -> VlanId.vlanId((short) x))
.collect(GuavaCollectors.toImmutableSet());
}
}
|
sonu283304/onos
|
drivers/default/src/main/java/org/onosproject/driver/query/FullVlanAvailable.java
|
Java
|
apache-2.0
| 1,617 |
<?php
$cs = Yii::app()->getClientScript();
$cssAnsScriptFilesModule = array(
'/assets/css/rooms/header.css'
);
HtmlHelper::registerCssAndScriptsFiles($cssAnsScriptFilesModule, Yii::app()->theme->baseUrl);
$cssAnsScriptFilesModule = array(
// '/survey/css/mixitup/reset.css',
'/js/actionRooms/actionRooms.js'
);
HtmlHelper::registerCssAndScriptsFiles($cssAnsScriptFilesModule, $this->module->assetsUrl);
?>
<style>
.assemblyHeadSection {
<?php $bg = (@$archived) ? "assemblyParisDayArchived" : "assemblyParisDay";?>
/*background-image:url(<?php echo $this->module->assetsUrl; ?>/images/city/<?php echo $bg; ?>.jpg); */
background-image:url(<?php echo $this->module->assetsUrl; ?>/images/city/dda-connexion-lines.jpg);
background-repeat: no-repeat !important;
background-size: 100% 400px !important;
background-position: 0px 0px !important;
}
.bgDDA .modal .modal-header{
background-image:url(<?php echo $this->module->assetsUrl; ?>/images/city/dda-connexion-lines.jpg);
background-repeat: no-repeat !important;
background-size: auto;
}
.contentProposal{
background-color: white;
}
.header-parent-space{
margin: -15px 10px;
padding: 15px 8px 8px;
border-radius: 7px 7px 0px 0px;
background-color: rgba(255, 255, 255, 0);
}
#room-container{
min-height:300px;
}
.btn-select-room{
margin-top: 5px;
border: none;
font-size: 20px;
font-weight: 200;
width: 100%;
text-align: center;
border-radius:100px;
}
.btn-select-room.bg-dark:hover{
background-color:#58829B !important;
}
.modal .room-item{
width:100%;
padding:15px;
font-size:16px;
border-bottom:1px solid #DBDBDB;
border-top:1px solid rgba(230, 230, 230, 0);
float:left;
}
.modal .room-item:hover{
background-color: rgb(230, 230, 230) !important;
border-top:1px solid rgb(192, 192, 192);
}
.title-conseil-citoyen {
background-color: rgba(255, 255, 255, 0);
margin: 0px;
padding: 10px;
border-radius: 12px;
-moz-box-shadow: 0px 3px 10px 1px #656565;
-webkit-box-shadow: 0px 3px 10px 1px #656565;
-o-box-shadow: 0px 3px 10px 1px #656565;
box-shadow: 0px 3px 10px 1px rgb(101, 101, 101);
margin-bottom: 10px;
}
.link-tools a:hover{
text-decoration: underline;
}
.fileupload-new.thumbnail{
width:unset;
}
h1.citizenAssembly-header {
font-size: 30px;
}
.img-room-modal img{
max-width: 35px;
margin-top: -5px;
margin-right: 10px;
border-radius: 4px;
}
#room-container .badge-danger {
margin-bottom: 2px;
margin-left: 2px;
}
</style>
<h1 class="text-dark citizenAssembly-header">
<?php
$urlPhotoProfil = "";
if(!@$parent){
if($parentType == Project::COLLECTION) { $parent = Project::getById($parentId); }
if($parentType == Organization::COLLECTION) { $parent = Organization::getById($parentId); }
if($parentType == Person::COLLECTION) { $parent = Person::getById($parentId); }
if($parentType == City::COLLECTION) { $parent = City::getByUnikey($parentId); }
}
if(isset($parent['profilImageUrl']) && $parent['profilImageUrl'] != ""){
$urlPhotoProfil = Yii::app()->getRequest()->getBaseUrl(true).$parent['profilImageUrl'];
}
// else{
// if($parentType == Person::COLLECTION)
// $urlPhotoProfil = $this->module->assetsUrl.'/images/thumb/project-default-image.png';
// if($parentType == Organization::COLLECTION)
// $urlPhotoProfil = $this->module->assetsUrl.'/images/thumb/orga-default-image.png';
// if($parentType == Project::COLLECTION)
// $urlPhotoProfil = $this->module->assetsUrl.'/images/thumb/default.png';
// }
$icon = "comments";
$colorName = "dark";
if($parentType == Project::COLLECTION) { $icon = "lightbulb-o"; $colorName = "purple"; }
if($parentType == Organization::COLLECTION) { $icon = "group"; $colorName = "green"; }
if($parentType == Person::COLLECTION) { $icon = "user"; $colorName = "dark"; }
if($parentType == City::COLLECTION) { $icon = "university"; $colorName = "red"; }
?>
<?php //création de l'url sur le nom du parent
$urlParent = Element::getControlerByCollection($parentType).".detail.id.".$parentId;
if($parentType == City::COLLECTION)
$urlParent = Element::getControlerByCollection($parentType).".detail.insee.".$parent["insee"].".postalCode.".$parent["cp"];
?>
<div class="row header-parent-space">
<?php if($parentType != City::COLLECTION && $urlPhotoProfil != ""){ ?>
<div class="col-md-3 col-sm-3 col-xs-12 center">
<img class="thumbnail img-responsive" id="thumb-profil-parent" src="<?php echo $urlPhotoProfil; ?>" alt="image" >
</div>
<?php }else if($parentType == City::COLLECTION){ ?>
<div class="col-md-3 col-sm-3 col-xs-12 center">
<h1 class="homestead title-conseil-citoyen center text-red"><i class="fa fa-group"></i><br>Conseil Citoyen</h1>
</div>
<?php } ?>
<?php if($parentType == City::COLLECTION || $urlPhotoProfil != "")
$colSize="9"; else $colSize="12";
?>
<div class="col-md-<?php echo $colSize; ?> col-sm-<?php echo $colSize; ?>">
<div class="col-md-12 no-padding margin-bottom-15">
<a href="javascript:loadByHash('#<?php echo $urlParent; ?>');" class="text-<?php echo $colorName; ?> homestead">
<i class="fa fa-<?php echo $icon; ?>"></i>
<?php
if($parentType == City::COLLECTION) echo "Commune de ";
echo $parent['name'];
?>
</a>
</div>
<?php
if(!@$mainPage){
$rooms = ActionRoom::getAllRoomsByTypeId($parentType, $parentId);
$discussions = $rooms["discussions"];
$votes = $rooms["votes"];
$actions = $rooms["actions"];
$history = $rooms["history"];
}
?>
<div class="col-md-4 no-padding">
<button type="button" class="btn btn-default bg-dark btn-select-room" data-toggle="modal" data-target="#modal-select-room1">
<i class="fa fa-comments"></i> Discuter <span class="badge"><?php if(@$discussions) echo count($discussions); else echo "0"; ?></span>
</button><br>
</div>
<div class="col-md-4">
<button type="button" class="btn btn-default bg-dark btn-select-room" data-toggle="modal" data-target="#modal-select-room2">
<i class="fa fa-archive"></i> Décider <span class="badge"><?php if(@$votes) echo count($votes); else echo "0"; ?></span>
</button><br>
</div>
<div class="col-md-4 no-padding">
<button type="button" class="btn btn-default bg-dark btn-select-room" data-toggle="modal" data-target="#modal-select-room3">
<i class="fa fa-cogs"></i> Agir <span class="badge"><?php if(@$actions) echo count($actions); else echo "0"; ?></span>
</button>
</div>
<div class="col-md-12 margin-top-15 link-tools">
<a href="javascript:showRoom('all', '<?php echo $parentId; ?>')" class="pull-left text-dark" style="font-size:15px;"><i class="fa fa-list"></i> Afficher tout</a>
<?php if(@$_GET["archived"] == null){ ?>
<a href="javascript:loadByHash(location.hash+'.archived.1')" class="pull-left text-red" style="font-size:15px;margin-left:30px;"><i class="fa fa-times"></i> Archives</a>
<?php } ?>
<?php //if(@$history && !empty($history)){ ?>
<a href="javascript:" class="pull-right text-dark" style="font-size:15px;" data-toggle="modal" data-target="#modal-select-room4">
<i class="fa fa-clock-o"></i> Mon historique
</a>
<?php //} ?>
</div>
<div class="col-md-12 no-padding" style="margin: 15px 0 15px 0 !important;">
<?php
$btnLbl = "<i class='fa fa-sign-in'></i> ".Yii::t("rooms","JOIN TO PARTICIPATE", null, Yii::app()->controller->module->id);
$ctrl = Element::getControlerByCollection($parentType);
$btnUrl = "loadByHash('#".$ctrl.".detail.id.".$parentId."')";
if( $parentType == City::COLLECTION ||
($parentType != Person::COLLECTION &&
Authorisation::canParticipate(Yii::app()->session['userId'],$parentType,$parentId) ))
{
$btnLbl = "<i class='fa fa-plus'></i> ".Yii::t("rooms","Add an Action Room", null, Yii::app()->controller->module->id);
$btnUrl = "loadByHash('#rooms.editroom.type.".$parentType.".id.".$parentId."')";
}
if(!isset(Yii::app()->session['userId'])){
$btnLbl = "<i class='fa fa-sign-in'></i> ".Yii::t("rooms","LOGIN TO PARTICIPATE", null, Yii::app()->controller->module->id);
$btnUrl = "showPanel('box-login');";
}
$addBtn = ( $parentType != Person::COLLECTION ) ? ' <i class="fa fa-angle-right"></i> <a class="filter btn btn-xs btn-primary Helvetica" href="javascript:;" onclick="'.$btnUrl.'">'.$btnLbl.'</a>' : "";
?>
<!-- <span class="breadscrum">
<a class='text-dark' href='javascript:loadByHash("#rooms.index.type.<?php //echo $parentType ?>.id.<?php //echo $parentId ?>.tab.1")'>
<i class="fa fa-connectdevelop"></i> <?php //echo Yii::t("rooms","Action Rooms", null, Yii::app()->controller->module->id) ?>
</a>
<?php
//if( $parentType != Person::COLLECTION ){
// echo (@$textTitle) ? "/ ".$textTitle :
// ' <i class="fa fa-angle-right"></i> <a class="filter btn btn-default Helvetica" href="javascript:;" onclick="'.$btnUrl.'">'.$btnLbl.'</a>';
//}
?>
</span> -->
</div>
</div>
</h1>
<?php if( isset(Yii::app()->session['userId']) &&
Authorisation::canParticipate(Yii::app()->session['userId'], $parentType, $parentId ) ){ ?>
<div class="modal fade" id="modal-create-room" tabindex="-1" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header text-dark">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h2 class="modal-title text-left">
<i class="fa fa-angle-down"></i> <i class="fa fa-plus"></i> Créer un espace
</h2>
</div>
<div class="modal-body no-padding">
<div class="panel-body" id="form-create-room">
<?php
$listRoomTypes = Lists::getListByName("listRoomTypes");
foreach ($listRoomTypes as $key => $value) {
//error_log("translate ".$value);
$listRoomTypes[$key] = Yii::t("rooms",$value, null, Yii::app()->controller->module->id);
}
$tagsList = Lists::getListByName("tags");
$params = array(
"listRoomTypes" => $listRoomTypes,
"tagsList" => $tagsList,
"id" => $parentId,
"type" => $parentType
);
$this->renderPartial('../rooms/editRoomSV', $params);
?>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Annuler</button>
<button type="button" class="btn btn-success"
onclick="javascript:saveNewRoom();">
<i class="fa fa-save"></i> Enregistrer
</button>
</div>
</div>
</div>
</div>
</div>
<?php } ?>
<?php
createModalRoom($discussions,$parentType, $parentId, 1, "Sélectionnez un espace de discussion", "comments", "discuss", "Aucun espace de discussion");
createModalRoom($votes,$parentType, $parentId, 2, "Sélectionnez un espace de décision", "archive", "vote", "Aucun espace de décision");
createModalRoom($actions,$parentType, $parentId, 3, "Sélectionnez un espace d'action", "cogs", "actions", "Aucun espace d'action");
createModalRoom($history,$parentType, $parentId, 4, "Historique de votre activité", "clock-o", "history", "Aucune activité");
//$where = Yii::app()->controller->id.'.'.Yii::app()->controller->action->id;
//if( in_array($where, array("rooms.action","survey.entry"))){
createModalRoom( array_merge($votes,$actions) ,$parentType, $parentId, 5,
"Choisir un nouvel espace", "share-alt", "move", "Aucun espace","move",$faTitle);
//}
function createModalRoom($elements, $parentType, $parentId, $index, $title,
$icon, $typeNew, $endLbl,$action=null,$context=null){
$iconType = array("discuss"=>"comments", "entry" => "archive", "actions" => "cogs");
echo '<div class="panel panel-default no-margin">';
echo '<div class="modal fade" id="modal-select-room'.$index.'" tabindex="-1" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header text-dark">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h2 class="modal-title text-left">
<i class="fa fa-angle-down"></i> <i class="fa fa-'.$icon.'"></i>
<span class="">'.$title.' <span class="badge">'.count($elements).'</span>
</h2>
</div>
<div class="modal-body no-padding">
<div class="panel-body no-padding">';
if(!empty($elements))
foreach ($elements as $key => $value) { if(isset($value["_id"])) {
$created = ( @$value["created"] ) ? date("d/m/y h:i",$value["created"]) : "";
//if($typeNew == "history") var_dump($value); error_log($value["type"]);
if($typeNew == "history" && @$value["type"]){ //error_log($value["type"]);
$type = $value["type"];
if(@$iconType[$type]) $icon = $iconType[$type];
}
$col = Survey::COLLECTION;
$attr = 'survey';
if( @$value["type"] == ActionRoom::TYPE_ACTIONS ){
$col = ActionRoom::TYPE_ACTIONS;
$attr = 'room';
}
$onclick = 'showRoom(\''.$typeNew.'\', \''.(string)$value["_id"].'\')';
$skip = false;
if( $action == "move"){
$icon = ($value["type"] == ActionRoom::TYPE_ACTIONS) ? "cogs" : "archive";
$type = ($context == "cogs") ? "action" : "survey";
$onclick = 'move(\''.$type.'\', \''.(string)$value["_id"].'\')';
//remove the current context room destination
//if((string)$value["_id"] == ) //we are missing the current room object in header
}
$imgIcon = '';
if(isset($value['profilImageUrl']) && $value['profilImageUrl'] != ""){
$urlPhotoProfil = Yii::app()->getRequest()->getBaseUrl(true).$value['profilImageUrl'];
$imgIcon = '<img src="'.$urlPhotoProfil.'">';
}
$count = 0;
if( @$value["type"] == ActionRoom::TYPE_VOTE )
$count = PHDB::count(Survey::COLLECTION,array("survey"=>(string)$value["_id"]));
else if( @$value["type"] == ActionRoom::TYPE_ACTIONS )
$count = PHDB::count(Survey::COLLECTION,array("room"=>(string)$value["_id"]));
else if( @$value["type"] == ActionRoom::TYPE_DISCUSS )
$count = (empty($value["commentCount"])?0:$value["commentCount"]);
if(!$skip){
echo '<a href="javascript:" onclick="'.$onclick.'" class="text-dark room-item" data-dismiss="modal">'.
'<i class="fa fa-angle-right"></i> <i class="fa fa-'.$icon.'"></i> '.$value["name"].
" <span class='badge badge-success pull-right'>".
$count.
//PHDB::count($col,array($attr=>(string)$value["_id"])).
"</span>".
" <span class='pull-right img-room-modal'>".
$imgIcon.
"</span>".
'</a>';
}
} }
if(empty($elements))
echo '<div class="panel-body "><i class="fa fa-times"></i> '.$endLbl.'</div>';
echo '</div>';
echo '</div>';
echo '<div class="modal-footer">';
if($typeNew != "history" && $typeNew != "move" && Authorisation::canParticipate(Yii::app()->session['userId'],$parentType,$parentId) )
echo '<button type="button" class="btn btn-default pull-left" onclick="javascript:selectRoomType(\''.$typeNew.'\')"
data-dismiss="modal" data-toggle="modal" data-target="#modal-create-room">'.
'<i class="fa fa-plus"></i> <i class="fa fa-'.$icon.'"></i> Créer un nouvel espace'.
'</button>';
echo '<button type="button" class="btn btn-default" data-dismiss="modal">Annuler</button>';
echo '</div>';
echo '</div>';
echo '</div>';
echo '</div>';
echo '</div>';
}
?>
<script type="text/javascript">
jQuery(document).ready(function() {
$('#form-create-room #btn-submit-form').addClass("hidden");
});
function saveNewRoom(){
$('#form-create-room #btn-submit-form').click();
}
function selectRoomType(type){
mylog.log("selectRoomType",type);
$("#roomType").val(type);
var msg = "Nouvel espace";
if(type=="discuss") msg = "<i class='fa fa-comments'></i> " + msg + " de discussion";
if(type=="framapad") msg = "<i class='fa fa-file-text-o'></i> " + msg + " framapad";
if(type=="vote") msg = "<i class='fa fa-gavel'></i> " + msg + " de décision";
if(type=="actions") msg = "<i class='fa fa-cogs'></i> Nouvelle Liste d'actions";
$("#proposerloiFormLabel").html(msg);
$("#proposerloiFormLabel").addClass("text-dark");
// $("#btn-submit-form").html('<?php echo Yii::t("common", "Submit"); ?> <i class="fa fa-arrow-circle-right"></i>');
//$("#first-step-create-space").hide(400);
$(".roomTypeselect").addClass("hidden");
}
function showRoom(type, id){
var mapUrl = { "all":
{ "url" : "rooms/index/type/<?php echo $parentType; ?>",
"hash" : "rooms.index.type.<?php echo $parentType; ?>"
} ,
"discuss":
{ "url" : "comment/index/type/actionRooms",
"hash" : "comment.index.type.actionRooms"
} ,
"vote":
{ "url" : "survey/entries",
"hash" : "survey.entries"
} ,
"entry" :
{ "url" : "survey/entry",
"hash" : "survey.entry",
},
"actions":
{ "url" : "rooms/actions",
"hash" : "rooms.actions"
} ,
"action":
{
"url" : "rooms/action",
"hash" : "rooms.action",
}
}
var url = mapUrl[type]["url"]+"/id/"+id;
var hash = mapUrl[type]["hash"]+".id."+id;
$("#room-container").hide(200);
$.blockUI({
message : "<h4 style='font-weight:300' class='text-dark padding-10'><i class='fa fa-spin fa-circle-o-notch'></i><br>Chargement en cours ...</span></h4>"
});
getAjax('#room-container',baseUrl+'/'+moduleId+'/'+url+"?renderPartial=true",
function(){
history.pushState(null, "New Title", "communecter#" + hash);
$("#room-container").show(200);
$.unblockUI();
},"html");
}
</script>
|
pixelhumain/communecter
|
views/rooms/header.php
|
PHP
|
apache-2.0
| 18,400 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ignite.internal.processors.cache;
import java.nio.ByteBuffer;
import javax.cache.processor.EntryProcessor;
import javax.cache.processor.MutableEntry;
import org.apache.ignite.IgniteCheckedException;
import org.apache.ignite.internal.GridDirectTransient;
import org.apache.ignite.internal.util.tostring.GridToStringInclude;
import org.apache.ignite.internal.util.typedef.internal.S;
import org.apache.ignite.internal.util.typedef.internal.U;
import org.apache.ignite.plugin.extensions.communication.Message;
import org.apache.ignite.plugin.extensions.communication.MessageReader;
import org.apache.ignite.plugin.extensions.communication.MessageWriter;
import org.jetbrains.annotations.Nullable;
/**
*
*/
public class CacheInvokeDirectResult implements Message {
/** */
private static final long serialVersionUID = 0L;
/** */
private KeyCacheObject key;
/** */
@GridToStringInclude
private transient Object unprepareRes;
/** */
@GridToStringInclude
private CacheObject res;
/** */
@GridToStringInclude(sensitive = true)
@GridDirectTransient
private Exception err;
/** */
private byte[] errBytes;
/**
* Required for {@link Message}.
*/
public CacheInvokeDirectResult() {
// No-op.
}
/**
* @param key Key.
* @param res Result.
*/
public CacheInvokeDirectResult(KeyCacheObject key, CacheObject res) {
this.key = key;
this.res = res;
}
/**
* Constructs CacheInvokeDirectResult with unprepared res, to avoid object marshaling while holding topology locks.
*
* @param key Key.
* @param res Result.
* @return a new instance of CacheInvokeDirectResult.
*/
static CacheInvokeDirectResult lazyResult(KeyCacheObject key, Object res) {
CacheInvokeDirectResult res0 = new CacheInvokeDirectResult();
res0.key = key;
res0.unprepareRes = res;
return res0;
}
/**
* @param key Key.
* @param err Exception thrown by {@link EntryProcessor#process(MutableEntry, Object...)}.
*/
public CacheInvokeDirectResult(KeyCacheObject key, Exception err) {
this.key = key;
this.err = err;
}
/**
* @return Key.
*/
public KeyCacheObject key() {
return key;
}
/**
* @return Result.
*/
public CacheObject result() {
return res;
}
/**
* @return Error.
*/
@Nullable public Exception error() {
return err;
}
/**
* @param ctx Cache context.
* @throws IgniteCheckedException If failed.
*/
public void prepareMarshal(GridCacheContext ctx) throws IgniteCheckedException {
key.prepareMarshal(ctx.cacheObjectContext());
if (err != null && errBytes == null) {
try {
errBytes = U.marshal(ctx.marshaller(), err);
}
catch (IgniteCheckedException e) {
// Try send exception even if it's unable to marshal.
IgniteCheckedException exc = new IgniteCheckedException(err.getMessage());
exc.setStackTrace(err.getStackTrace());
exc.addSuppressed(e);
errBytes = U.marshal(ctx.marshaller(), exc);
}
}
if (unprepareRes != null) {
res = ctx.toCacheObject(unprepareRes);
unprepareRes = null;
}
if (res != null)
res.prepareMarshal(ctx.cacheObjectContext());
}
/**
* @param ctx Cache context.
* @param ldr Class loader.
* @throws IgniteCheckedException If failed.
*/
public void finishUnmarshal(GridCacheContext ctx, ClassLoader ldr) throws IgniteCheckedException {
key.finishUnmarshal(ctx.cacheObjectContext(), ldr);
if (errBytes != null && err == null)
err = U.unmarshal(ctx.marshaller(), errBytes, U.resolveClassLoader(ldr, ctx.gridConfig()));
if (res != null)
res.finishUnmarshal(ctx.cacheObjectContext(), ldr);
}
/** {@inheritDoc} */
@Override public void onAckReceived() {
// No-op.
}
/** {@inheritDoc} */
@Override public short directType() {
return 93;
}
/** {@inheritDoc} */
@Override public boolean writeTo(ByteBuffer buf, MessageWriter writer) {
writer.setBuffer(buf);
if (!writer.isHeaderWritten()) {
if (!writer.writeHeader(directType(), fieldsCount()))
return false;
writer.onHeaderWritten();
}
switch (writer.state()) {
case 0:
if (!writer.writeByteArray("errBytes", errBytes))
return false;
writer.incrementState();
case 1:
if (!writer.writeMessage("key", key))
return false;
writer.incrementState();
case 2:
if (!writer.writeMessage("res", res))
return false;
writer.incrementState();
}
return true;
}
/** {@inheritDoc} */
@Override public boolean readFrom(ByteBuffer buf, MessageReader reader) {
reader.setBuffer(buf);
if (!reader.beforeMessageRead())
return false;
switch (reader.state()) {
case 0:
errBytes = reader.readByteArray("errBytes");
if (!reader.isLastRead())
return false;
reader.incrementState();
case 1:
key = reader.readMessage("key");
if (!reader.isLastRead())
return false;
reader.incrementState();
case 2:
res = reader.readMessage("res");
if (!reader.isLastRead())
return false;
reader.incrementState();
}
return reader.afterMessageRead(CacheInvokeDirectResult.class);
}
/** {@inheritDoc} */
@Override public byte fieldsCount() {
return 3;
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(CacheInvokeDirectResult.class, this);
}
}
|
sk0x50/ignite
|
modules/core/src/main/java/org/apache/ignite/internal/processors/cache/CacheInvokeDirectResult.java
|
Java
|
apache-2.0
| 7,063 |
<?php
// +----------------------------------------------------------------------
// | Fanwe 方维o2o商业系统
// +----------------------------------------------------------------------
// | Copyright (c) 2011 http://www.fanwe.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: 云淡风轻(88522820@qq.com)
// +----------------------------------------------------------------------
//会员整合的接口
interface integrate{
//用户登录
/**
* 返回 array('status'=>'',data=>'',msg=>'') msg存放整合接口返回的字符串
* @param $user_data
*/
function login($user_name,$user_pwd);
//用户登出
/**
* 返回 array('status'=>'',data=>'',msg=>'') msg存放整合接口返回的字符串
*/
function logout();
//用户注册
/**
* 返回 array('status'=>'',data=>'',msg=>'') msg存放整合接口的消息
* @param $user_data
*/
function add_user($user_name,$user_pwd,$email);
//用户修改密码
/**
* 返回bool
* @param $user_data
*/
function edit_user($user_data,$user_new_pwd);
//删除会员
function delete_user($user_data);
//安装时执行的部份操作
//返回 array('status'=>'','msg'=>'')
function install($config_seralized);
//卸载时执行的部份操作
//无返回
function uninstall();
}
?>
|
hushulin/zsh_admin
|
system/libs/integrate.php
|
PHP
|
apache-2.0
| 1,402 |