repo_name
stringlengths 4
116
| path
stringlengths 3
942
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
resin-io-library/base-images
|
balena-base-images/python/generic-armv7ahf/debian/bullseye/3.10.0/run/Dockerfile
|
4101
|
# AUTOGENERATED FILE
FROM balenalib/generic-armv7ahf-debian:bullseye-run
# remove several traces of debian python
RUN apt-get purge -y python.*
# http://bugs.python.org/issue19846
# > At the moment, setting "LANG=C" on a Linux system *fundamentally breaks Python 3*, and that's not OK.
ENV LANG C.UTF-8
# install python dependencies
RUN apt-get update && apt-get install -y --no-install-recommends \
ca-certificates \
netbase \
&& rm -rf /var/lib/apt/lists/*
# key 63C7CC90: public key "Simon McVittie <[email protected]>" imported
# key 3372DCFA: public key "Donald Stufft (dstufft) <[email protected]>" imported
RUN gpg --batch --keyserver keyring.debian.org --recv-keys 4DE8FF2A63C7CC90 \
&& gpg --batch --keyserver keyserver.ubuntu.com --recv-key 6E3CBCE93372DCFA \
&& gpg --batch --keyserver keyserver.ubuntu.com --recv-keys 0x52a43a1e4b77b059
ENV PYTHON_VERSION 3.10.0
# if this is called "PIP_VERSION", pip explodes with "ValueError: invalid truth value '<VERSION>'"
ENV PYTHON_PIP_VERSION 21.2.4
ENV SETUPTOOLS_VERSION 58.0.0
RUN set -x \
&& buildDeps=' \
curl \
' \
&& apt-get update && apt-get install -y $buildDeps --no-install-recommends && rm -rf /var/lib/apt/lists/* \
&& curl -SLO "http://resin-packages.s3.amazonaws.com/python/v$PYTHON_VERSION/Python-$PYTHON_VERSION.linux-armv7hf-libffi3.3.tar.gz" \
&& echo "84875fbd8f39240a2d2299c6957ac3bf9eec6c0a34ebdc45e3ad73a5e97f8e6b Python-$PYTHON_VERSION.linux-armv7hf-libffi3.3.tar.gz" | sha256sum -c - \
&& tar -xzf "Python-$PYTHON_VERSION.linux-armv7hf-libffi3.3.tar.gz" --strip-components=1 \
&& rm -rf "Python-$PYTHON_VERSION.linux-armv7hf-libffi3.3.tar.gz" \
&& ldconfig \
&& if [ ! -e /usr/local/bin/pip3 ]; then : \
&& curl -SLO "https://raw.githubusercontent.com/pypa/get-pip/430ba37776ae2ad89f794c7a43b90dc23bac334c/get-pip.py" \
&& echo "19dae841a150c86e2a09d475b5eb0602861f2a5b7761ec268049a662dbd2bd0c get-pip.py" | sha256sum -c - \
&& python3 get-pip.py \
&& rm get-pip.py \
; fi \
&& pip3 install --no-cache-dir --upgrade --force-reinstall pip=="$PYTHON_PIP_VERSION" setuptools=="$SETUPTOOLS_VERSION" \
&& find /usr/local \
\( -type d -a -name test -o -name tests \) \
-o \( -type f -a -name '*.pyc' -o -name '*.pyo' \) \
-exec rm -rf '{}' + \
&& cd / \
&& rm -rf /usr/src/python ~/.cache
# make some useful symlinks that are expected to exist
RUN cd /usr/local/bin \
&& ln -sf pip3 pip \
&& { [ -e easy_install ] || ln -s easy_install-* easy_install; } \
&& ln -sf idle3 idle \
&& ln -sf pydoc3 pydoc \
&& ln -sf python3 python \
&& ln -sf python3-config python-config
# set PYTHONPATH to point to dist-packages
ENV PYTHONPATH /usr/lib/python3/dist-packages:$PYTHONPATH
CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"]
RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/[email protected]" \
&& echo "Running test-stack@python" \
&& chmod +x [email protected] \
&& bash [email protected] \
&& rm -rf [email protected]
RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v7 \nOS: Debian Bullseye \nVariant: run variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nPython v3.10.0, Pip v21.2.4, Setuptools v58.0.0 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info
RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \
&& chmod +x /bin/sh-shim \
&& cp /bin/sh /bin/sh.real \
&& mv /bin/sh-shim /bin/sh
|
apache-2.0
|
resin-io-library/base-images
|
balena-base-images/dotnet/generic-aarch64/debian/stretch/3.1-sdk/run/Dockerfile
|
2918
|
# AUTOGENERATED FILE
FROM balenalib/generic-aarch64-debian:stretch-run
RUN apt-get update \
&& apt-get install -y --no-install-recommends \
ca-certificates \
curl \
\
# .NET Core dependencies
libc6 \
libgcc1 \
libgssapi-krb5-2 \
libicu57 \
libssl1.1 \
libstdc++6 \
zlib1g \
&& rm -rf /var/lib/apt/lists/*
# Configure web servers to bind to port 80 when present
ENV ASPNETCORE_URLS=http://+:80 \
# Enable detection of running in a container
DOTNET_RUNNING_IN_CONTAINER=true
# Install .NET Core SDK
ENV DOTNET_SDK_VERSION 3.1.415
RUN curl -SL --output dotnet.tar.gz "https://dotnetcli.blob.core.windows.net/dotnet/Sdk/$DOTNET_SDK_VERSION/dotnet-sdk-$DOTNET_SDK_VERSION-linux-arm64.tar.gz" \
&& dotnet_sha512='7a5b9922988bcbde63d39f97e283ca1d373d5521cca0ab8946e2f86deaef6e21f00244228a0d5d8c38c2b9634b38bc7338b61984f0e12dd8fdb8b2e6eed5dd34' \
&& echo "$dotnet_sha512 dotnet.tar.gz" | sha512sum -c - \
&& mkdir -p /usr/share/dotnet \
&& tar -zxf dotnet.tar.gz -C /usr/share/dotnet \
&& rm dotnet.tar.gz \
&& ln -s /usr/share/dotnet/dotnet /usr/bin/dotnet
# Enable correct mode for dotnet watch (only mode supported in a container)
ENV DOTNET_USE_POLLING_FILE_WATCHER=true \
# Skip extraction of XML docs - generally not useful within an image/container - helps performance
NUGET_XMLDOC_MODE=skip \
DOTNET_NOLOGO=true
# Trigger first run experience by running arbitrary cmd to populate local package cache
RUN dotnet help
CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"]
RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/44e597e40f2010cdde15b3ba1e397aea3a5c5271/scripts/assets/tests/[email protected]" \
&& echo "Running test-stack@dotnet" \
&& chmod +x [email protected] \
&& bash [email protected] \
&& rm -rf [email protected]
RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v8 \nOS: Debian Stretch \nVariant: run variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \ndotnet 3.1-sdk \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info
RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \
&& chmod +x /bin/sh-shim \
&& cp /bin/sh /bin/sh.real \
&& mv /bin/sh-shim /bin/sh
|
apache-2.0
|
resin-io-library/base-images
|
balena-base-images/python/generic-aarch64/debian/sid/3.10.0/build/Dockerfile
|
4853
|
# AUTOGENERATED FILE
FROM balenalib/generic-aarch64-debian:sid-build
# remove several traces of debian python
RUN apt-get purge -y python.*
# http://bugs.python.org/issue19846
# > At the moment, setting "LANG=C" on a Linux system *fundamentally breaks Python 3*, and that's not OK.
ENV LANG C.UTF-8
# key 63C7CC90: public key "Simon McVittie <[email protected]>" imported
# key 3372DCFA: public key "Donald Stufft (dstufft) <[email protected]>" imported
RUN gpg --batch --keyserver keyring.debian.org --recv-keys 4DE8FF2A63C7CC90 \
&& gpg --batch --keyserver keyserver.ubuntu.com --recv-key 6E3CBCE93372DCFA \
&& gpg --batch --keyserver keyserver.ubuntu.com --recv-keys 0x52a43a1e4b77b059
ENV PYTHON_VERSION 3.10.0
# if this is called "PIP_VERSION", pip explodes with "ValueError: invalid truth value '<VERSION>'"
ENV PYTHON_PIP_VERSION 21.2.4
ENV SETUPTOOLS_VERSION 58.0.0
RUN set -x \
&& curl -SLO "http://resin-packages.s3.amazonaws.com/python/v$PYTHON_VERSION/Python-$PYTHON_VERSION.linux-aarch64-libffi3.3.tar.gz" \
&& echo "47c9b05b54b91145dc2b000ef0e86c159a208a3ae13ec1f43cf0a8ead2aadd91 Python-$PYTHON_VERSION.linux-aarch64-libffi3.3.tar.gz" | sha256sum -c - \
&& tar -xzf "Python-$PYTHON_VERSION.linux-aarch64-libffi3.3.tar.gz" --strip-components=1 \
&& rm -rf "Python-$PYTHON_VERSION.linux-aarch64-libffi3.3.tar.gz" \
&& ldconfig \
&& if [ ! -e /usr/local/bin/pip3 ]; then : \
&& curl -SLO "https://raw.githubusercontent.com/pypa/get-pip/430ba37776ae2ad89f794c7a43b90dc23bac334c/get-pip.py" \
&& echo "19dae841a150c86e2a09d475b5eb0602861f2a5b7761ec268049a662dbd2bd0c get-pip.py" | sha256sum -c - \
&& python3 get-pip.py \
&& rm get-pip.py \
; fi \
&& pip3 install --no-cache-dir --upgrade --force-reinstall pip=="$PYTHON_PIP_VERSION" setuptools=="$SETUPTOOLS_VERSION" \
&& find /usr/local \
\( -type d -a -name test -o -name tests \) \
-o \( -type f -a -name '*.pyc' -o -name '*.pyo' \) \
-exec rm -rf '{}' + \
&& cd / \
&& rm -rf /usr/src/python ~/.cache
# install "virtualenv", since the vast majority of users of this image will want it
RUN pip3 install --no-cache-dir virtualenv
ENV PYTHON_DBUS_VERSION 1.2.18
# install dbus-python dependencies
RUN apt-get update && apt-get install -y --no-install-recommends \
libdbus-1-dev \
libdbus-glib-1-dev \
&& rm -rf /var/lib/apt/lists/* \
&& apt-get -y autoremove
# install dbus-python
RUN set -x \
&& mkdir -p /usr/src/dbus-python \
&& curl -SL "http://dbus.freedesktop.org/releases/dbus-python/dbus-python-$PYTHON_DBUS_VERSION.tar.gz" -o dbus-python.tar.gz \
&& curl -SL "http://dbus.freedesktop.org/releases/dbus-python/dbus-python-$PYTHON_DBUS_VERSION.tar.gz.asc" -o dbus-python.tar.gz.asc \
&& gpg --verify dbus-python.tar.gz.asc \
&& tar -xzC /usr/src/dbus-python --strip-components=1 -f dbus-python.tar.gz \
&& rm dbus-python.tar.gz* \
&& cd /usr/src/dbus-python \
&& PYTHON_VERSION=$(expr match "$PYTHON_VERSION" '\([0-9]*\.[0-9]*\)') ./configure \
&& make -j$(nproc) \
&& make install -j$(nproc) \
&& cd / \
&& rm -rf /usr/src/dbus-python
# make some useful symlinks that are expected to exist
RUN cd /usr/local/bin \
&& ln -sf pip3 pip \
&& { [ -e easy_install ] || ln -s easy_install-* easy_install; } \
&& ln -sf idle3 idle \
&& ln -sf pydoc3 pydoc \
&& ln -sf python3 python \
&& ln -sf python3-config python-config
# set PYTHONPATH to point to dist-packages
ENV PYTHONPATH /usr/lib/python3/dist-packages:$PYTHONPATH
CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"]
RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/[email protected]" \
&& echo "Running test-stack@python" \
&& chmod +x [email protected] \
&& bash [email protected] \
&& rm -rf [email protected]
RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v8 \nOS: Debian Sid \nVariant: build variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nPython v3.10.0, Pip v21.2.4, Setuptools v58.0.0 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info
RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \
&& chmod +x /bin/sh-shim \
&& cp /bin/sh /bin/sh.real \
&& mv /bin/sh-shim /bin/sh
|
apache-2.0
|
jeroenvandijk/google-api-ruby-client
|
examples/sinatra/explorer.rb
|
13332
|
#!/usr/bin/env ruby
# INSTALL
# sudo gem install sinatra liquid
# RUN
# ruby examples/sinatra/buzz_api.rb
root_dir = File.expand_path("../../..", __FILE__)
lib_dir = File.expand_path("./lib", root_dir)
$LOAD_PATH.unshift(lib_dir)
$LOAD_PATH.uniq!
require 'rubygems'
begin
gem 'rack', '= 1.2.0'
require 'rack'
rescue LoadError
STDERR.puts "Missing dependencies."
STDERR.puts "sudo gem install rack -v 1.2.0"
exit(1)
end
begin
require 'sinatra'
require 'liquid'
require 'signet/oauth_1/client'
require 'google/api_client'
rescue LoadError
STDERR.puts "Missing dependencies."
STDERR.puts "sudo gem install sinatra liquid signet google-api-client"
exit(1)
end
enable :sessions
CSS = <<-CSS
/* http://meyerweb.com/eric/tools/css/reset/ */
/* v1.0 | 20080212 */
html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, font, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td {
margin: 0;
padding: 0;
border: 0;
outline: 0;
font-size: 100%;
vertical-align: baseline;
background: transparent;
}
body {
line-height: 1;
}
ol, ul {
list-style: none;
}
blockquote, q {
quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
content: '';
content: none;
}
/* remember to define focus styles! */
:focus {
outline: 0;
}
/* remember to highlight inserts somehow! */
ins {
text-decoration: none;
}
del {
text-decoration: line-through;
}
/* tables still need 'cellspacing="0"' in the markup */
table {
border-collapse: collapse;
border-spacing: 0;
}
/* End Reset */
body {
color: #555555;
background-color: #ffffff;
font-family: 'Helvetica', 'Arial', sans-serif;
font-size: 18px;
line-height: 27px;
padding: 27px 72px;
}
p {
margin-bottom: 27px;
}
h1 {
font-style: normal;
font-variant: normal;
font-weight: normal;
font-family: 'Helvetica', 'Arial', sans-serif;
font-size: 36px;
line-height: 54px;
margin-bottom: 0px;
}
h2 {
font-style: normal;
font-variant: normal;
font-weight: normal;
font-family: 'Monaco', 'Andale Mono', 'Consolas', 'Inconsolata', 'Courier New', monospace;
font-size: 14px;
line-height: 27px;
margin-top: 0px;
margin-bottom: 54px;
letter-spacing: 0.1em;
text-transform: none;
text-shadow: rgba(204, 204, 204, 0.75) 0px 1px 0px;
}
#output h3 {
font-style: normal;
font-variant: normal;
font-weight: bold;
font-size: 18px;
line-height: 27px;
margin: 27px 0px;
}
#output h3:first-child {
margin-top: 0px;
}
ul, ol, dl {
margin-bottom: 27px;
}
li {
margin: 0px 0px;
}
form {
float: left;
display: block;
}
form label, form input, form textarea {
font-family: 'Monaco', 'Andale Mono', 'Consolas', 'Inconsolata', 'Courier New', monospace;
display: block;
}
form label {
margin-bottom: 5px;
}
form input {
width: 300px;
font-size: 14px;
padding: 5px;
}
form textarea {
height: 150px;
min-height: 150px;
width: 300px;
min-width: 300px;
max-width: 300px;
}
#output {
font-family: 'Monaco', 'Andale Mono', 'Consolas', 'Inconsolata', 'Courier New', monospace;
display: inline-block;
margin-left: 27px;
padding: 27px;
border: 1px dotted #555555;
width: 1120px;
max-width: 100%;
min-height: 600px;
}
#output pre {
overflow: auto;
}
a {
color: #000000;
text-decoration: none;
border-bottom: 1px dotted rgba(112, 56, 56, 0.0);
}
a:hover {
-webkit-transition: all 0.3s linear;
color: #703838;
border-bottom: 1px dotted rgba(112, 56, 56, 1.0);
}
p a {
border-bottom: 1px dotted rgba(0, 0, 0, 1.0);
}
h1, h2 {
color: #000000;
}
h3, h4, h5, h6 {
color: #333333;
}
.block {
display: block;
}
button {
margin-bottom: 72px;
padding: 7px 11px;
font-size: 14px;
}
CSS
JAVASCRIPT = <<-JAVASCRIPT
var uriTimeout = null;
$(document).ready(function () {
$('#output').hide();
var rpcName = $('#rpc-name').text().trim();
var serviceId = $('#service-id').text().trim();
var getParameters = function() {
var parameters = {};
var fields = $('.parameter').parents('li');
for (var i = 0; i < fields.length; i++) {
var input = $(fields[i]).find('input');
var label = $(fields[i]).find('label');
if (input.val() && input.val() != "") {
parameters[label.text()] = input.val();
}
}
return parameters;
}
var updateOutput = function (event) {
var request = $('#request').text().trim();
var response = $('#response').text().trim();
if (request != '' || response != '') {
$('#output').show();
} else {
$('#output').hide();
}
}
var handleUri = function (event) {
updateOutput(event);
if (uriTimeout) {
clearTimeout(uriTimeout);
}
uriTimeout = setTimeout(function () {
$.ajax({
"url": "/template/" + serviceId + "/" + rpcName + "/",
"data": getParameters(),
"dataType": "text",
"ifModified": true,
"success": function (data, textStatus, xhr) {
updateOutput(event);
if (textStatus == 'success') {
$('#uri-template').html(data);
if (uriTimeout) {
clearTimeout(uriTimeout);
}
}
}
});
}, 350);
}
var getResponse = function (event) {
$.ajax({
"url": "/response/" + serviceId + "/" + rpcName + "/",
"type": "POST",
"data": getParameters(),
"dataType": "html",
"ifModified": true,
"success": function (data, textStatus, xhr) {
if (textStatus == 'success') {
$('#response').text(data);
}
updateOutput(event);
}
});
}
var getRequest = function (event) {
$.ajax({
"url": "/request/" + serviceId + "/" + rpcName + "/",
"type": "GET",
"data": getParameters(),
"dataType": "html",
"ifModified": true,
"success": function (data, textStatus, xhr) {
if (textStatus == 'success') {
$('#request').text(data);
updateOutput(event);
getResponse(event);
}
}
});
}
var transmit = function (event) {
$('#request').html('');
$('#response').html('');
handleUri(event);
updateOutput(event);
getRequest(event);
}
$('form').submit(function (event) { event.preventDefault(); });
$('button').click(transmit);
$('.parameter').keyup(handleUri);
$('.parameter').blur(handleUri);
});
JAVASCRIPT
def client
@client ||= Google::APIClient.new(
:service => 'buzz',
:authorization => Signet::OAuth1::Client.new(
:temporary_credential_uri =>
'https://www.google.com/accounts/OAuthGetRequestToken',
:authorization_uri =>
'https://www.google.com/buzz/api/auth/OAuthAuthorizeToken',
:token_credential_uri =>
'https://www.google.com/accounts/OAuthGetAccessToken',
:client_credential_key => 'anonymous',
:client_credential_secret => 'anonymous'
)
)
end
def service(service_name, service_version)
unless service_version
service_version = client.latest_service_version(service_name).version
end
client.discovered_service(service_name, service_version)
end
get '/template/:service/:method/' do
service_name, service_version = params[:service].split("-", 2)
method = service(service_name, service_version).to_h[params[:method].to_s]
parameters = method.parameters.inject({}) do |accu, parameter|
accu[parameter] = params[parameter.to_sym] if params[parameter.to_sym]
accu
end
uri = Addressable::URI.parse(
method.uri_template.partial_expand(parameters).pattern
)
template_variables = method.uri_template.variables
query_parameters = method.normalize_parameters(parameters).reject do |k, v|
template_variables.include?(k)
end
if query_parameters.size > 0
uri.query_values = (uri.query_values || {}).merge(query_parameters)
end
# Normalization is necessary because of undesirable percent-escaping
# during URI template expansion
return uri.normalize.to_s.gsub('%7B', '{').gsub('%7D', '}')
end
get '/request/:service/:method/' do
service_name, service_version = params[:service].split("-", 2)
method = service(service_name, service_version).to_h[params[:method].to_s]
parameters = method.parameters.inject({}) do |accu, parameter|
accu[parameter] = params[parameter.to_sym] if params[parameter.to_sym]
accu
end
body = ''
request = client.generate_request(
method, parameters.merge("pp" => "1"), body, [], {:signed => false}
)
method, uri, headers, body = request
merged_body = StringIO.new
body.each do |chunk|
merged_body << chunk
end
merged_body.rewind
<<-REQUEST.strip
#{method} #{uri} HTTP/1.1
#{(headers.map { |k,v| "#{k}: #{v}" }).join('\n')}
#{merged_body.string}
REQUEST
end
post '/response/:service/:method/' do
require 'rack/utils'
service_name, service_version = params[:service].split("-", 2)
method = service(service_name, service_version).to_h[params[:method].to_s]
parameters = method.parameters.inject({}) do |accu, parameter|
accu[parameter] = params[parameter.to_sym] if params[parameter.to_sym]
accu
end
body = ''
response = client.execute(
method, parameters.merge("pp" => "1"), body, [], {:signed => false}
)
status, headers, body = response
status_message = Rack::Utils::HTTP_STATUS_CODES[status.to_i]
merged_body = StringIO.new
body.each do |chunk|
merged_body << chunk
end
merged_body.rewind
<<-RESPONSE.strip
#{status} #{status_message}
#{(headers.map { |k,v| "#{k}: #{v}" }).join("\n")}
#{merged_body.string}
RESPONSE
end
get '/explore/:service/' do
service_name, service_version = params[:service].split("-", 2)
service_version = service(service_name, service_version).version
variables = {
"css" => CSS,
"service_name" => service_name,
"service_version" => service_version,
"methods" => service(service_name, service_version).to_h.keys.sort
}
Liquid::Template.parse(<<-HTML).render(variables)
<!DOCTYPE html>
<html>
<head>
<title>{{service_name}}</title>
<style type="text/css">
{{css}}
</style>
</head>
<body>
<h1>{{service_name}}</h1>
<ul>
{% for method in methods %}
<li>
<a href="/explore/{{service_name}}-{{service_version}}/{{method}}/">
{{method}}
</a>
</li>
{% endfor %}
</ul>
</body>
</html>
HTML
end
get '/explore/:service/:method/' do
service_name, service_version = params[:service].split("-", 2)
service_version = service(service_name, service_version).version
method = service(service_name, service_version).to_h[params[:method].to_s]
variables = {
"css" => CSS,
"javascript" => JAVASCRIPT,
"http_method" => (method.description['httpMethod'] || 'GET'),
"service_name" => service_name,
"service_version" => service_version,
"method" => params[:method].to_s,
"required_parameters" =>
method.required_parameters,
"optional_parameters" =>
method.optional_parameters.sort,
"template" => method.uri_template.pattern
}
Liquid::Template.parse(<<-HTML).render(variables)
<!DOCTYPE html>
<html>
<head>
<title>{{service_name}} - {{method}}</title>
<style type="text/css">
{{css}}
</style>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"
type="text/javascript">
</script>
<script type="text/javascript">
{{javascript}}
</script>
</head>
<body>
<h3 id="service-id">
<a href="/explore/{{service_name}}-{{service_version}}/">
{{service_name}}-{{service_version}}
</a>
</h3>
<h1 id="rpc-name">{{method}}</h1>
<h2>{{http_method}} <span id="uri-template">{{template}}</span></h2>
<form>
<ul>
{% for parameter in required_parameters %}
<li>
<label for="param-{{parameter}}">{{parameter}}</label>
<input id="param-{{parameter}}" name="param-{{parameter}}"
class="parameter" type="text" />
</li>
{% endfor %}
{% for parameter in optional_parameters %}
<li>
<label for="param-{{parameter}}">{{parameter}}</label>
<input id="param-{{parameter}}" name="param-{{parameter}}"
class="parameter" type="text" />
</li>
{% endfor %}
{% if http_method != 'GET' %}
<li>
<label for="http-body">body</label>
<textarea id="http-body" name="http-body"></textarea>
</li>
{% endif %}
</ul>
<button>Transmit</button>
</form>
<div id="output">
<h3>Request</h3>
<pre id="request"></pre>
<h3>Response</h3>
<pre id="response"></pre>
</div>
</body>
</html>
HTML
end
get '/favicon.ico' do
require 'httpadapter'
HTTPAdapter.transmit(
['GET', 'http://www.google.com/favicon.ico', [], ['']],
HTTPAdapter::NetHTTPRequestAdapter
)
end
get '/' do
redirect '/explore/buzz/'
end
|
apache-2.0
|
vietanhdev/HUST-ICT-website
|
_includes/enroll.html
|
1414
|
<section id="enroll" class="bg-dark">
<div class="container">
<div class="row lead wow bounceIn">
<div class="col-lg-8 col-lg-offset-2 text-center" style="margin-bottom: 20px;">
<h2 class="section-heading">TUYỂN SINH</h2>
<hr class="primary">
</div>
<div class="col-md-4 text-center">
<h2>Chỉ tiêu tuyển sinh</h2>
<p class="lead wow" style="color: #198AFF; font-size: 60px">200</p>
<p>(* Cùng với chương trình Việt-Nhật)</p>
</div>
<div class="col-md-4 text-center">
<h2>Mã đăng ký xét tuyển</h2>
<p class="lead wow" style="color: #198AFF; font-size: 60px">TT22</p>
<p>(* Điểm xét tuyển năm 2016: 7.53/10)</p>
</div>
<div class="col-md-4 text-center">
<h2>Website tuyển sinh</h2>
<a href="http://www.soict.hust.edu.vn" class="lead wow" style="color: #198AFF;">http://www.soict.hust.edu.vn</a>
<br>
<a href="http://ts.hust.edu.vn" class="lead wow" style="color: #198AFF;">http://ts.hust.edu.vn</a>
</div>
</div>
<a href="#contact" class="btn btn-default btn-xl page-scroll col-md-2 col-md-offset-5"><i class="fa fa-arrow-down" aria-hidden="true"></i></a>
</section>
|
apache-2.0
|
kousik/tidiit
|
models/faq_model.php
|
2958
|
<?php
class Faq_model extends CI_Model{
public $_table='faq';
public $_topics='faq_topics';
function __construct() {
parent::__construct();
}
public function get_all_admin(){
return $this->db->select('f.*,ft.faqTopics')->from($this->_table.' f')->join($this->_topics.' ft','f.faqTopicsId=ft.faqTopicsId')->get()->result();
}
function get_details($faqId){
return $this->db->select('f.*,ft.faqTopics')->from($this->_table.' f')->join($this->_topics.' ft','f.faqTopicsId=ft.faqTopicsId')->where('f.faqId',$faqId)->get()->result();
}
public function add($dataArr){
$this->db->insert($this->_table,$dataArr);
return $this->db->insert_id();
}
public function edit($DataArr,$faqId){
$this->db->where('faqId',$faqId);
$this->db->update($this->_table,$DataArr);
//echo $this->db->last_query();die;
return TRUE;
}
public function change_status($faqId,$status){
$this->db->where('faqId',$faqId);
$this->db->update($this->_table,array('status'=>$status));
return TRUE;
}
public function delete($faqId){
$this->db->delete($this->_table, array('faqId' => $faqId));
return TRUE;
}
public function get_all($type){
$this->db->select('*')->from($this->_table)->where('status',1)->where('type',$type);
return $this->db->get()->result();
}
function get_all_admin_topics(){
return $this->db->get($this->_topics)->result();
}
function get_all_active_topic(){
return $this->db->get_where($this->_topics,array('status'=>1))->result();
}
public function add_topics($dataArr){
$this->db->insert($this->_topics,$dataArr);
return $this->db->insert_id();
}
public function edit_topics($DataArr,$faqTopicsId){
$this->db->where('faqTopicsId',$faqTopicsId);
$this->db->update($this->_topics,$DataArr);
//echo $this->db->last_query();die;
return TRUE;
}
public function change_status_topics($faqTopicsId,$status){
$this->db->where('faqTopicsId',$faqTopicsId);
$this->db->update($this->_topics,array('status'=>$status));
return TRUE;
}
public function delete_topics($faqTopicsId){
$this->db->delete($this->_topics, array('faqTopicsId' => $faqTopicsId));
return TRUE;
}
function check_faq_topics_exist($faqTopics,$faqTopicsType){
$rs=$this->db->from($this->_topics)->where('faqTopics',$faqTopics)->where('faqTopicsType',$faqTopicsType)->get()->result();
if(count($rs)>0){
return TRUE;
}else{
return FALSE;
}
}
function get_topics_by_type($type){
return $this->db->get_where($this->_topics,array('faqTopicsType'=>$type))->result();
}
}
|
apache-2.0
|
kilel/DGraphMark
|
src/generator/GraphGenerator.h
|
1405
|
/*
* Copyright 2014 Kislitsyn Ilya
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef GRAPHGENERATOR_H
#define GRAPHGENERATOR_H
#include "../mpi/Communicable.h"
#include "../graph/Graph.h"
#include "../util/Random.h"
namespace dgmark {
/**
* Generates Graphs.<br />
* Parameters for generation passes with constructor.
*/
class GraphGenerator : public Communicable {
public:
GraphGenerator(Intracomm *comm) :
Communicable(comm)
{
}
virtual ~GraphGenerator()
{
}
/**
* Generates graph with specified parameters.
* @param grade Log[2] of total vertices count
* @param density Average edges count, connected to vertex.
* @return Graph.
*/
virtual Graph* generate(int grade, int density) = 0;
virtual double getGenerationTime() = 0;
virtual double getDistributionTime() = 0;
};
}
#endif /* GRAPHGENERATOR_H */
|
apache-2.0
|
earasoft/swing-database-learning1
|
src/main/java/com/earasoft/db/database/MySQLDatabase.java
|
2134
|
package com.earasoft.db.database;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import org.apache.commons.configuration.Configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.earasoft.learning1.Settings;
public class MySQLDatabase implements Database {
private static final Logger logger = LoggerFactory.getLogger(MySQLDatabase.class);
public static final String HOSTNAME_KEY = "hostname";
public static final String HOSTNAME_KEY_DEFAULT = "127.0.0.1";
public static final String DATABASE_KEY = "database";
public static final String DATABASE_KEY_DEFAULT = "database";
public static final String PORT_KEY = "port";
public static final String PORT_KEY_DEFAULT = "127.0.0.1";
public static final String USERNAME_KEY = "username";
public static final String USERNAME_KEY_DEFAULT = "root";
public static final String PASSWORD_KEY = "password";
public static final String PASSWORD_KEY_DEFAULT = "password";
protected final String hostname;
protected final String port;
protected final String database;
protected final String username;
protected final String password;
protected final String url;
public MySQLDatabase(Configuration storageConfig){
this.hostname = storageConfig.getString(HOSTNAME_KEY, HOSTNAME_KEY_DEFAULT).trim();
this.port = storageConfig.getString(PORT_KEY, PORT_KEY_DEFAULT).trim();
this.database = storageConfig.getString(DATABASE_KEY, DATABASE_KEY_DEFAULT).trim();
this.username = storageConfig.getString(USERNAME_KEY, USERNAME_KEY_DEFAULT).trim();
this.password = storageConfig.getString(PASSWORD_KEY, PASSWORD_KEY_DEFAULT).trim();
this.url = String.format("jdbc:mysql://%s:%s/%s", this.hostname, this.port, this.database);
logger.info("Connecting to Database [MySql ("+ this.url + ")]");
}
@Override
public Connection getConnection() throws SQLException {
return DriverManager.getConnection(url, username, password);
}
@Override
public String getName() {
return String.format("mysql");
}
}
|
apache-2.0
|
dremio/dremio-oss
|
dac/ui/src/components/Aggregate/AggregateContent.js
|
5729
|
/*
* Copyright (C) 2017-2019 Dremio Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { Component } from 'react';
import Radium from 'radium';
import PropTypes from 'prop-types';
import Immutable from 'immutable';
import classNames from 'classnames';
import DragColumnMenu from 'components/DragComponents/DragColumnMenu';
import ColumnDragItem from 'utils/ColumnDragItem';
import { base, inner, leftBorder, fullHeight, contentPadding } from '@app/uiTheme/less/Aggregate/AggregateContent.less';
import ColumnDragArea from './components/ColumnDragArea';
import MeasureDragArea, { MEASURE_DRAG_AREA_TEXT } from './components/MeasureDragArea';
export const NOT_SUPPORTED_TYPES = new Set(['MAP', 'LIST', 'STRUCT']);
@Radium
class AggregateContent extends Component {
static propTypes = {
fields: PropTypes.object,
canSelectMeasure: PropTypes.bool,
canUseFieldAsBothDimensionAndMeasure: PropTypes.bool,
allColumns: PropTypes.instanceOf(Immutable.List),
handleDragStart: PropTypes.func,
onDragEnd: PropTypes.func,
onDrop: PropTypes.func,
handleMeasureChange: PropTypes.func,
dragType: PropTypes.string,
path: PropTypes.string,
isDragInProgress: PropTypes.bool,
style: PropTypes.object,
dragItem: PropTypes.instanceOf(ColumnDragItem),
className: PropTypes.string,
canAlter: PropTypes.any
};
static defaultProps = {
allColumns: Immutable.List(),
canSelectMeasure: true,
canUseFieldAsBothDimensionAndMeasure: true
};
disabledColumnNames = undefined;
constructor(props) {
super(props);
this.receiveProps(props, {});
}
componentWillReceiveProps(nextProps) {
this.receiveProps(nextProps, this.props);
}
receiveProps(nextProps, oldProps) {
// disabledColumnNames is wholly derived from these props, so only recalculate it when one of them has changed
const propKeys = ['allColumns', 'fields', 'canSelectMeasure', 'canUseFieldAsBothDimensionAndMeasure'];
if (propKeys.some((key) => nextProps[key] !== oldProps[key])) {
this.disabledColumnNames = this.getDisabledColumnNames(nextProps);
}
}
getDisabledColumnNames(props) {
const {
allColumns, fields, canSelectMeasure, canUseFieldAsBothDimensionAndMeasure
} = props;
const dimensionColumnNames = Immutable.Set(fields.columnsDimensions.map(col => col.column.value));
const measuresColumnNames = Immutable.Set(fields.columnsMeasures.map(col => col.column.value));
const columnsInEither = dimensionColumnNames.concat(measuresColumnNames);
const columnsInBoth = dimensionColumnNames.intersect(measuresColumnNames);
const disabledColumns = allColumns.filter(
(column) =>
NOT_SUPPORTED_TYPES.has(column.get('type')) ||
(!canSelectMeasure && columnsInBoth.has(column.get('name'))) ||
(!canUseFieldAsBothDimensionAndMeasure && columnsInEither.has(column.get('name')))
);
return Immutable.Set(disabledColumns.map((column) => column.get('name')));
}
render() {
const {
allColumns, onDrop, fields, dragType, isDragInProgress, dragItem,
handleDragStart, onDragEnd, canUseFieldAsBothDimensionAndMeasure,
className, canAlter
} = this.props;
const commonDragAreaProps = {
allColumns,
disabledColumnNames: this.disabledColumnNames,
handleDragStart,
onDragEnd,
onDrop,
dragType,
isDragInProgress,
dragItem,
canUseFieldAsBothDimensionAndMeasure
};
const measurementCls = classNames(['aggregate-measurement', fullHeight]);
return (
<div className={classNames(['aggregate-content', base, className])} style={this.props.style}>
<div className={inner}>
<DragColumnMenu
items={allColumns}
className={fullHeight}
disabledColumnNames={this.disabledColumnNames}
columnType='column'
handleDragStart={handleDragStart}
onDragEnd={onDragEnd}
dragType={dragType}
name={`${this.props.path} (${la('Current')})`}
canAlter={canAlter}
/>
</div>
<div className={leftBorder}>
<ColumnDragArea
className={classNames(['aggregate-dimension', fullHeight])}
dragContentCls={contentPadding}
{...commonDragAreaProps}
columnsField={fields.columnsDimensions}
canAlter={canAlter}
/>
</div>
<div className={leftBorder}>
{
this.props.canSelectMeasure ?
<MeasureDragArea
dragContentCls={contentPadding}
className={measurementCls}
{...commonDragAreaProps}
columnsField={fields.columnsMeasures}/> :
<ColumnDragArea
dragContentCls={contentPadding}
className={measurementCls}
{...commonDragAreaProps}
dragOrigin='measures'
dragAreaText={MEASURE_DRAG_AREA_TEXT}
columnsField={fields.columnsMeasures}
canAlter={canAlter}
/>
}
</div>
</div>
);
}
}
export default AggregateContent;
|
apache-2.0
|
mdoering/backbone
|
life/Fungi/Basidiomycota/Agaricomycetes/Polyporales/Ganodermataceae/Ganoderma/Ganoderma albocinctum/README.md
|
220
|
# Ganoderma albocinctum Pat. & Morot SPECIES
#### Status
ACCEPTED
#### According to
Index Fungorum
#### Published in
J. Bot. Morot 8: 365 (1894)
#### Original name
Ganoderma albocinctum Pat. & Morot
### Remarks
null
|
apache-2.0
|
gyuho/etcdlabs
|
frontend/app/home/home.component.ts
|
654
|
import { Component } from '@angular/core';
import { Meta, Title } from '@angular/platform-browser';
import { OnInit } from '@angular/core';
@Component({
selector: 'app-home',
templateUrl: 'home.component.html',
styleUrls: ['home.component.css'],
})
export class HomeComponent implements OnInit {
constructor(meta: Meta, title: Title) {
title.setTitle('etcd Labs');
meta.addTags([
{ name: 'author', content: 'etcd'},
{ name: 'keywords', content: 'etcd, etcd demo, etcd setting, etcd cluster, etcd install'},
{ name: 'description', content: 'This is etcd demo, install guides!' }
]);
}
ngOnInit(): void {
}
}
|
apache-2.0
|
werneckpaiva/spark-to-tableau
|
src/test/scala/tableau/TestDataframeToTableau.scala
|
3223
|
package tableau
import java.io.File
import org.apache.spark.sql.SparkSession
import org.junit.Assert._
import org.junit._
object TestDataframeToTableau {
var spark: SparkSession = null
/**
* Create Spark context before tests
*/
@BeforeClass
def setUp(): Unit = {
spark = {
SparkSession.builder()
.appName("DataframeToTableauTest")
.master("local")
.getOrCreate()
}
}
/**
* Stop Spark context after tests
*/
@AfterClass
def tearDown(): Unit = {
spark.stop()
spark = null
}
}
class TestDataframeToTableau {
@Test
def testSaveNumbersToExtractor(): Unit = {
val spark = TestDataframeToTableau.spark
import TableauDataFrame._
import spark.implicits._
val df = List(1, 2, 3, 4, 5).toDF
assertEquals(5, df.count)
df.saveToTableau("numbers.tde")
val f = new File("numbers.tde")
assertTrue(f.exists())
f.delete()
}
@Test
def testSaveLongNumbersToExtractor(): Unit = {
val spark = TestDataframeToTableau.spark
import TableauDataFrame._
import spark.implicits._
val df = List(1111111111L, -222222222222L, 3333333333L).toDF
assertEquals(3, df.count)
df.saveToTableau("long-numbers.tde")
val f = new File("long-numbers.tde")
assertTrue(f.exists())
f.delete()
}
@Test
def testSaveDoubleToExtractor(): Unit = {
val spark = TestDataframeToTableau.spark
import TableauDataFrame._
import spark.implicits._
val df = List(2.3d, 2.4d, 3.5d).toDF
assertEquals(3, df.count)
df.saveToTableau("double-numbers.tde")
val f = new File("double-numbers.tde")
assertTrue(f.exists())
f.delete()
}
@Test
def testSaveFloatToExtractor(): Unit = {
val spark = TestDataframeToTableau.spark
import TableauDataFrame._
import spark.implicits._
val df = List(1.1f, 2.2f, 3.3f).toDF
assertEquals(3, df.count)
df.saveToTableau("float-numbers.tde")
val f = new File("float-numbers.tde")
assertTrue(f.exists())
f.delete()
}
@Test
def testSaveStringsToExtractor(): Unit = {
val spark = TestDataframeToTableau.spark
import TableauDataFrame._
import spark.implicits._
val df = List("a", "b", "c", "d").toDF
df.saveToTableau("letters.tde")
val f = new File("letters.tde")
assertTrue(f.exists())
f.delete()
}
@Test
def testSaveMultipleTypes(): Unit = {
import TableauDataFrame._
val jsonRDD = TestDataframeToTableau.spark.sparkContext.parallelize(Seq(
"""
{ "isActive": false,
"balance": 1431.73,
"picture": "http://placehold.it/32x32",
"age": 35,
"eyeColor": "blue"
}""",
"""{
"isActive": true,
"balance": 2515.60,
"picture": "http://placehold.it/32x32",
"age": 34,
"eyeColor": "blue"
}""",
"""{
"isActive": false,
"balance": 3765.29,
"picture": "http://placehold.it/32x32",
"age": 26,
"eyeColor": "blue"
}""")
)
val df = TestDataframeToTableau.spark.read.json(jsonRDD)
df.saveToTableau("users.tde")
val f = new File("users.tde")
assertTrue(f.exists())
f.delete()
}
}
|
apache-2.0
|
mffrench/fabric
|
protos/utils/proputils.go
|
19622
|
/*
Copyright IBM Corp. 2016 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 utils
import (
"errors"
"fmt"
"encoding/binary"
"encoding/hex"
"github.com/golang/protobuf/proto"
"github.com/hyperledger/fabric/bccsp"
"github.com/hyperledger/fabric/bccsp/factory"
"github.com/hyperledger/fabric/common/crypto"
"github.com/hyperledger/fabric/common/util"
"github.com/hyperledger/fabric/core/chaincode/platforms"
"github.com/hyperledger/fabric/protos/common"
"github.com/hyperledger/fabric/protos/peer"
)
// GetChaincodeInvocationSpec get the ChaincodeInvocationSpec from the proposal
func GetChaincodeInvocationSpec(prop *peer.Proposal) (*peer.ChaincodeInvocationSpec, error) {
txhdr := &common.Header{}
err := proto.Unmarshal(prop.Header, txhdr)
if err != nil {
return nil, err
}
ccPropPayload := &peer.ChaincodeProposalPayload{}
err = proto.Unmarshal(prop.Payload, ccPropPayload)
if err != nil {
return nil, err
}
cis := &peer.ChaincodeInvocationSpec{}
err = proto.Unmarshal(ccPropPayload.Input, cis)
if err != nil {
return nil, err
}
return cis, nil
}
// GetChaincodeProposalContext returns creator and transient
func GetChaincodeProposalContext(prop *peer.Proposal) ([]byte, map[string][]byte, error) {
if prop == nil {
return nil, nil, fmt.Errorf("Proposal is nil")
}
if len(prop.Header) == 0 {
return nil, nil, fmt.Errorf("Proposal's header is nil")
}
if len(prop.Payload) == 0 {
return nil, nil, fmt.Errorf("Proposal's payload is nil")
}
//// get back the header
hdr, err := GetHeader(prop.Header)
if err != nil {
return nil, nil, fmt.Errorf("Could not extract the header from the proposal: %s", err)
}
if hdr == nil {
return nil, nil, fmt.Errorf("Unmarshalled header is nil")
}
chdr, err := UnmarshalChannelHeader(hdr.ChannelHeader)
if err != nil {
return nil, nil, fmt.Errorf("Could not extract the channel header from the proposal: %s", err)
}
if common.HeaderType(chdr.Type) != common.HeaderType_ENDORSER_TRANSACTION &&
common.HeaderType(chdr.Type) != common.HeaderType_CONFIG {
return nil, nil, fmt.Errorf("Invalid proposal type expected ENDORSER_TRANSACTION or CONFIG. Was: %d", chdr.Type)
}
shdr, err := GetSignatureHeader(hdr.SignatureHeader)
if err != nil {
return nil, nil, fmt.Errorf("Could not extract the signature header from the proposal: %s", err)
}
ccPropPayload := &peer.ChaincodeProposalPayload{}
err = proto.Unmarshal(prop.Payload, ccPropPayload)
if err != nil {
return nil, nil, err
}
return shdr.Creator, ccPropPayload.TransientMap, nil
}
// GetHeader Get Header from bytes
func GetHeader(bytes []byte) (*common.Header, error) {
hdr := &common.Header{}
err := proto.Unmarshal(bytes, hdr)
if err != nil {
return nil, err
}
return hdr, nil
}
// GetNonce returns the nonce used in Proposal
func GetNonce(prop *peer.Proposal) ([]byte, error) {
// get back the header
hdr, err := GetHeader(prop.Header)
if err != nil {
return nil, fmt.Errorf("Could not extract the header from the proposal: %s", err)
}
chdr, err := UnmarshalChannelHeader(hdr.ChannelHeader)
if err != nil {
return nil, fmt.Errorf("Could not extract the channel header from the proposal: %s", err)
}
shdr, err := GetSignatureHeader(hdr.SignatureHeader)
if err != nil {
return nil, fmt.Errorf("Could not extract the signature header from the proposal: %s", err)
}
if common.HeaderType(chdr.Type) != common.HeaderType_ENDORSER_TRANSACTION &&
common.HeaderType(chdr.Type) != common.HeaderType_CONFIG {
return nil, fmt.Errorf("Invalid proposal type expected ENDORSER_TRANSACTION or CONFIG. Was: %d", chdr.Type)
}
if hdr.SignatureHeader == nil {
return nil, errors.New("Invalid signature header. It must be different from nil.")
}
ccPropPayload := &peer.ChaincodeProposalPayload{}
err = proto.Unmarshal(prop.Payload, ccPropPayload)
if err != nil {
return nil, err
}
return shdr.Nonce, nil
}
// GetChaincodeHeaderExtension get chaincode header extension given header
func GetChaincodeHeaderExtension(hdr *common.Header) (*peer.ChaincodeHeaderExtension, error) {
chdr, err := UnmarshalChannelHeader(hdr.ChannelHeader)
if err != nil {
return nil, err
}
chaincodeHdrExt := &peer.ChaincodeHeaderExtension{}
err = proto.Unmarshal(chdr.Extension, chaincodeHdrExt)
if err != nil {
return nil, err
}
return chaincodeHdrExt, nil
}
// GetProposalResponse given proposal in bytes
func GetProposalResponse(prBytes []byte) (*peer.ProposalResponse, error) {
proposalResponse := &peer.ProposalResponse{}
err := proto.Unmarshal(prBytes, proposalResponse)
if err != nil {
return nil, err
}
return proposalResponse, nil
}
// GetChaincodeDeploymentSpec returns a ChaincodeDeploymentSpec given args
func GetChaincodeDeploymentSpec(code []byte) (*peer.ChaincodeDeploymentSpec, error) {
cds := &peer.ChaincodeDeploymentSpec{}
err := proto.Unmarshal(code, cds)
if err != nil {
return nil, err
}
// FAB-2122: Validate the CDS according to platform specific requirements
platform, err := platforms.Find(cds.ChaincodeSpec.Type)
if err != nil {
return nil, err
}
err = platform.ValidateDeploymentSpec(cds)
if err != nil {
return nil, err
}
return cds, nil
}
// GetChaincodeAction gets the ChaincodeAction given chaicnode action bytes
func GetChaincodeAction(caBytes []byte) (*peer.ChaincodeAction, error) {
chaincodeAction := &peer.ChaincodeAction{}
err := proto.Unmarshal(caBytes, chaincodeAction)
if err != nil {
return nil, err
}
return chaincodeAction, nil
}
// GetResponse gets the Response given response bytes
func GetResponse(resBytes []byte) (*peer.Response, error) {
response := &peer.Response{}
err := proto.Unmarshal(resBytes, response)
if err != nil {
return nil, err
}
return response, nil
}
// GetChaincodeEvents gets the ChaincodeEvents given chaicnode event bytes
func GetChaincodeEvents(eBytes []byte) (*peer.ChaincodeEvent, error) {
chaincodeEvent := &peer.ChaincodeEvent{}
err := proto.Unmarshal(eBytes, chaincodeEvent)
if err != nil {
return nil, err
}
return chaincodeEvent, nil
}
// GetProposalResponsePayload gets the proposal response payload
func GetProposalResponsePayload(prpBytes []byte) (*peer.ProposalResponsePayload, error) {
prp := &peer.ProposalResponsePayload{}
err := proto.Unmarshal(prpBytes, prp)
if err != nil {
return nil, err
}
return prp, nil
}
// GetProposal returns a Proposal message from its bytes
func GetProposal(propBytes []byte) (*peer.Proposal, error) {
prop := &peer.Proposal{}
err := proto.Unmarshal(propBytes, prop)
if err != nil {
return nil, err
}
return prop, nil
}
// GetPayload Get Payload from Envelope message
func GetPayload(e *common.Envelope) (*common.Payload, error) {
payload := &common.Payload{}
err := proto.Unmarshal(e.Payload, payload)
if err != nil {
return nil, err
}
return payload, nil
}
// GetTransaction Get Transaction from bytes
func GetTransaction(txBytes []byte) (*peer.Transaction, error) {
tx := &peer.Transaction{}
err := proto.Unmarshal(txBytes, tx)
if err != nil {
return nil, err
}
return tx, nil
}
// GetChaincodeActionPayload Get ChaincodeActionPayload from bytes
func GetChaincodeActionPayload(capBytes []byte) (*peer.ChaincodeActionPayload, error) {
cap := &peer.ChaincodeActionPayload{}
err := proto.Unmarshal(capBytes, cap)
if err != nil {
return nil, err
}
return cap, nil
}
// GetChaincodeProposalPayload Get ChaincodeProposalPayload from bytes
func GetChaincodeProposalPayload(bytes []byte) (*peer.ChaincodeProposalPayload, error) {
cpp := &peer.ChaincodeProposalPayload{}
err := proto.Unmarshal(bytes, cpp)
if err != nil {
return nil, err
}
return cpp, nil
}
// GetSignatureHeader Get SignatureHeader from bytes
func GetSignatureHeader(bytes []byte) (*common.SignatureHeader, error) {
sh := &common.SignatureHeader{}
err := proto.Unmarshal(bytes, sh)
if err != nil {
return nil, err
}
return sh, nil
}
// GetSignaturePolicyEnvelope returns a SignaturePolicyEnvelope from bytes
func GetSignaturePolicyEnvelope(bytes []byte) (*common.SignaturePolicyEnvelope, error) {
p := &common.SignaturePolicyEnvelope{}
err := proto.Unmarshal(bytes, p)
if err != nil {
return nil, err
}
return p, nil
}
// CreateChaincodeProposal creates a proposal from given input.
// It returns the proposal and the transaction id associated to the proposal
func CreateChaincodeProposal(typ common.HeaderType, chainID string, cis *peer.ChaincodeInvocationSpec, creator []byte) (*peer.Proposal, string, error) {
return CreateChaincodeProposalWithTransient(typ, chainID, cis, creator, nil)
}
// CreateChaincodeProposalWithTransient creates a proposal from given input
// It returns the proposal and the transaction id associated to the proposal
func CreateChaincodeProposalWithTransient(typ common.HeaderType, chainID string, cis *peer.ChaincodeInvocationSpec, creator []byte, transientMap map[string][]byte) (*peer.Proposal, string, error) {
// generate a random nonce
nonce, err := crypto.GetRandomNonce()
if err != nil {
return nil, "", err
}
// compute txid
txid, err := ComputeProposalTxID(nonce, creator)
if err != nil {
return nil, "", err
}
return CreateChaincodeProposalWithTxIDNonceAndTransient(txid, typ, chainID, cis, nonce, creator, transientMap)
}
// CreateChaincodeProposalWithTxIDNonceAndTransient creates a proposal from given input
func CreateChaincodeProposalWithTxIDNonceAndTransient(txid string, typ common.HeaderType, chainID string, cis *peer.ChaincodeInvocationSpec, nonce, creator []byte, transientMap map[string][]byte) (*peer.Proposal, string, error) {
ccHdrExt := &peer.ChaincodeHeaderExtension{ChaincodeId: cis.ChaincodeSpec.ChaincodeId}
ccHdrExtBytes, err := proto.Marshal(ccHdrExt)
if err != nil {
return nil, "", err
}
cisBytes, err := proto.Marshal(cis)
if err != nil {
return nil, "", err
}
ccPropPayload := &peer.ChaincodeProposalPayload{Input: cisBytes, TransientMap: transientMap}
ccPropPayloadBytes, err := proto.Marshal(ccPropPayload)
if err != nil {
return nil, "", err
}
// TODO: epoch is now set to zero. This must be changed once we
// get a more appropriate mechanism to handle it in.
var epoch uint64 = 0
timestamp := util.CreateUtcTimestamp()
hdr := &common.Header{ChannelHeader: MarshalOrPanic(&common.ChannelHeader{
Type: int32(typ),
TxId: txid,
Timestamp: timestamp,
ChannelId: chainID,
Extension: ccHdrExtBytes,
Epoch: epoch}),
SignatureHeader: MarshalOrPanic(&common.SignatureHeader{Nonce: nonce, Creator: creator})}
hdrBytes, err := proto.Marshal(hdr)
if err != nil {
return nil, "", err
}
return &peer.Proposal{Header: hdrBytes, Payload: ccPropPayloadBytes}, txid, nil
}
// GetBytesProposalResponsePayload gets proposal response payload
func GetBytesProposalResponsePayload(hash []byte, response *peer.Response, result []byte, event []byte, ccid *peer.ChaincodeID) ([]byte, error) {
cAct := &peer.ChaincodeAction{Events: event, Results: result, Response: response, ChaincodeId: ccid}
cActBytes, err := proto.Marshal(cAct)
if err != nil {
return nil, err
}
prp := &peer.ProposalResponsePayload{Extension: cActBytes, ProposalHash: hash}
prpBytes, err := proto.Marshal(prp)
if err != nil {
return nil, err
}
return prpBytes, nil
}
// GetBytesChaincodeProposalPayload gets the chaincode proposal payload
func GetBytesChaincodeProposalPayload(cpp *peer.ChaincodeProposalPayload) ([]byte, error) {
cppBytes, err := proto.Marshal(cpp)
if err != nil {
return nil, err
}
return cppBytes, nil
}
// GetBytesResponse gets the bytes of Response
func GetBytesResponse(res *peer.Response) ([]byte, error) {
resBytes, err := proto.Marshal(res)
if err != nil {
return nil, err
}
return resBytes, nil
}
// GetBytesChaincodeEvent gets the bytes of ChaincodeEvent
func GetBytesChaincodeEvent(event *peer.ChaincodeEvent) ([]byte, error) {
eventBytes, err := proto.Marshal(event)
if err != nil {
return nil, err
}
return eventBytes, nil
}
// GetBytesChaincodeActionPayload get the bytes of ChaincodeActionPayload from the message
func GetBytesChaincodeActionPayload(cap *peer.ChaincodeActionPayload) ([]byte, error) {
capBytes, err := proto.Marshal(cap)
if err != nil {
return nil, err
}
return capBytes, nil
}
// GetBytesProposalResponse gets propoal bytes response
func GetBytesProposalResponse(pr *peer.ProposalResponse) ([]byte, error) {
respBytes, err := proto.Marshal(pr)
if err != nil {
return nil, err
}
return respBytes, nil
}
// GetBytesProposal returns the bytes of a proposal message
func GetBytesProposal(prop *peer.Proposal) ([]byte, error) {
propBytes, err := proto.Marshal(prop)
if err != nil {
return nil, err
}
return propBytes, nil
}
// GetBytesHeader get the bytes of Header from the message
func GetBytesHeader(hdr *common.Header) ([]byte, error) {
bytes, err := proto.Marshal(hdr)
if err != nil {
return nil, err
}
return bytes, nil
}
// GetBytesSignatureHeader get the bytes of SignatureHeader from the message
func GetBytesSignatureHeader(hdr *common.SignatureHeader) ([]byte, error) {
bytes, err := proto.Marshal(hdr)
if err != nil {
return nil, err
}
return bytes, nil
}
// GetBytesTransaction get the bytes of Transaction from the message
func GetBytesTransaction(tx *peer.Transaction) ([]byte, error) {
bytes, err := proto.Marshal(tx)
if err != nil {
return nil, err
}
return bytes, nil
}
// GetBytesPayload get the bytes of Payload from the message
func GetBytesPayload(payl *common.Payload) ([]byte, error) {
bytes, err := proto.Marshal(payl)
if err != nil {
return nil, err
}
return bytes, nil
}
// GetBytesEnvelope get the bytes of Envelope from the message
func GetBytesEnvelope(env *common.Envelope) ([]byte, error) {
bytes, err := proto.Marshal(env)
if err != nil {
return nil, err
}
return bytes, nil
}
// GetActionFromEnvelope extracts a ChaincodeAction message from a serialized Envelope
func GetActionFromEnvelope(envBytes []byte) (*peer.ChaincodeAction, error) {
env, err := GetEnvelopeFromBlock(envBytes)
if err != nil {
return nil, err
}
payl, err := GetPayload(env)
if err != nil {
return nil, err
}
tx, err := GetTransaction(payl.Data)
if err != nil {
return nil, err
}
if len(tx.Actions) == 0 {
return nil, fmt.Errorf("At least one TransactionAction is required")
}
_, respPayload, err := GetPayloads(tx.Actions[0])
return respPayload, err
}
// CreateProposalFromCIS returns a proposal given a serialized identity and a ChaincodeInvocationSpec
func CreateProposalFromCIS(typ common.HeaderType, chainID string, cis *peer.ChaincodeInvocationSpec, creator []byte) (*peer.Proposal, string, error) {
return CreateChaincodeProposal(typ, chainID, cis, creator)
}
// CreateInstallProposalFromCDS returns a install proposal given a serialized identity and a ChaincodeDeploymentSpec
func CreateInstallProposalFromCDS(ccpack proto.Message, creator []byte) (*peer.Proposal, string, error) {
return createProposalFromCDS("", ccpack, creator, nil, nil, nil, "install")
}
// CreateDeployProposalFromCDS returns a deploy proposal given a serialized identity and a ChaincodeDeploymentSpec
func CreateDeployProposalFromCDS(chainID string, cds *peer.ChaincodeDeploymentSpec, creator []byte, policy []byte, escc []byte, vscc []byte) (*peer.Proposal, string, error) {
return createProposalFromCDS(chainID, cds, creator, policy, escc, vscc, "deploy")
}
// CreateUpgradeProposalFromCDS returns a upgrade proposal given a serialized identity and a ChaincodeDeploymentSpec
func CreateUpgradeProposalFromCDS(chainID string, cds *peer.ChaincodeDeploymentSpec, creator []byte, policy []byte, escc []byte, vscc []byte) (*peer.Proposal, string, error) {
return createProposalFromCDS(chainID, cds, creator, policy, escc, vscc, "upgrade")
}
// createProposalFromCDS returns a deploy or upgrade proposal given a serialized identity and a ChaincodeDeploymentSpec
func createProposalFromCDS(chainID string, msg proto.Message, creator []byte, policy []byte, escc []byte, vscc []byte, propType string) (*peer.Proposal, string, error) {
//in the new mode, cds will be nil, "deploy" and "upgrade" are instantiates.
var ccinp *peer.ChaincodeInput
var b []byte
var err error
if msg != nil {
b, err = proto.Marshal(msg)
if err != nil {
return nil, "", err
}
}
switch propType {
case "deploy":
fallthrough
case "upgrade":
cds, ok := msg.(*peer.ChaincodeDeploymentSpec)
if !ok || cds == nil {
return nil, "", fmt.Errorf("invalid message for creating lifecycle chaincode proposal from")
}
ccinp = &peer.ChaincodeInput{Args: [][]byte{[]byte(propType), []byte(chainID), b, policy, escc, vscc}}
case "install":
ccinp = &peer.ChaincodeInput{Args: [][]byte{[]byte(propType), b}}
}
//wrap the deployment in an invocation spec to lscc...
lsccSpec := &peer.ChaincodeInvocationSpec{
ChaincodeSpec: &peer.ChaincodeSpec{
Type: peer.ChaincodeSpec_GOLANG,
ChaincodeId: &peer.ChaincodeID{Name: "lscc"},
Input: ccinp}}
//...and get the proposal for it
return CreateProposalFromCIS(common.HeaderType_ENDORSER_TRANSACTION, chainID, lsccSpec, creator)
}
// ComputeProposalTxID computes TxID as the Hash computed
// over the concatenation of nonce and creator.
func ComputeProposalTxID(nonce, creator []byte) (string, error) {
// TODO: Get the Hash function to be used from
// channel configuration
digest, err := factory.GetDefault().Hash(
append(nonce, creator...),
&bccsp.SHA256Opts{})
if err != nil {
return "", err
}
return hex.EncodeToString(digest), nil
}
// CheckProposalTxID checks that txid is equal to the Hash computed
// over the concatenation of nonce and creator.
func CheckProposalTxID(txid string, nonce, creator []byte) error {
computedTxID, err := ComputeProposalTxID(nonce, creator)
if err != nil {
return fmt.Errorf("Failed computing target TXID for comparison [%s]", err)
}
if txid != computedTxID {
return fmt.Errorf("Transaction is not valid. Got [%s], expected [%s]", txid, computedTxID)
}
return nil
}
// ComputeProposalBinding computes the binding of a proposal
func ComputeProposalBinding(proposal *peer.Proposal) ([]byte, error) {
if proposal == nil {
return nil, fmt.Errorf("Porposal is nil")
}
if len(proposal.Header) == 0 {
return nil, fmt.Errorf("Proposal's Header is nil")
}
h, err := GetHeader(proposal.Header)
if err != nil {
return nil, err
}
chdr, err := UnmarshalChannelHeader(h.ChannelHeader)
if err != nil {
return nil, err
}
shdr, err := GetSignatureHeader(h.SignatureHeader)
if err != nil {
return nil, err
}
return computeProposalBindingInternal(shdr.Nonce, shdr.Creator, chdr.Epoch)
}
func computeProposalBindingInternal(nonce, creator []byte, epoch uint64) ([]byte, error) {
epochBytes := make([]byte, 8)
binary.LittleEndian.PutUint64(epochBytes, epoch)
// TODO: add to genesis block the hash function used for the binding computation.
digest, err := factory.GetDefault().Hash(
append(append(nonce, creator...), epochBytes...),
&bccsp.SHA256Opts{})
if err != nil {
return nil, err
}
return digest, nil
}
|
apache-2.0
|
AVBaranov/abaranov
|
chapter_011/src/main/java/spring/store/Storage.java
|
170
|
package spring.store;
import java.util.List;
/**
* Created by Andrey on 02.02.2018.
*/
public interface Storage <T>{
void add(User user);
List<T> getAll();
}
|
apache-2.0
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Lamiales/Acanthaceae/Blepharis/Blepharis longifolia/README.md
|
177
|
# Blepharis longifolia Lindau SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null
|
apache-2.0
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Aster/Aster flaccidus/README.md
|
240
|
# Aster flaccidus Bunge SPECIES
#### Status
ACCEPTED
#### According to
Integrated Taxonomic Information System
#### Published in
Mém. Acad. Imp. Sci. St. -Pétersbourg Divers Savans 2:599. 1835
#### Original name
null
### Remarks
null
|
apache-2.0
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Gentianales/Rubiaceae/Psychotria/Psychotria berteroana/ Syn. Psychotria platyphylla angustior/README.md
|
194
|
# Psychotria platyphylla var. angustior VARIETY
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
apache-2.0
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Liliopsida/Alismatales/Potamogetonaceae/Potamogeton/Potamogeton innominatus/README.md
|
192
|
# Potamogeton innominatus Tisel. ex Almquist SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null
|
apache-2.0
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Liliopsida/Arecales/Arecaceae/Chamaedorea/Chamaedorea sartorii/ Syn. Eleutheropetalum sartorii/README.md
|
198
|
# Eleutheropetalum sartorii (Liebm.) Oerst. SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
apache-2.0
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Amaryllidaceae/Allium/Allium senescens/Allium senescens glaucum/README.md
|
219
|
# Allium senescens subsp. glaucum SUBSPECIES
#### Status
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
Allium glaucum Schrad. ex Poir.
### Remarks
null
|
apache-2.0
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Liliopsida/Alismatales/Alismataceae/Echinodorus/Echinodorus inpai/README.md
|
181
|
# Echinodorus inpai Rataj SPECIES
#### Status
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
apache-2.0
|
mdoering/backbone
|
life/Plantae/Rhodophyta/Florideophyceae/Gigartinales/Peyssonneliaceae/Peyssonnelia/Peyssonnelia bicolor/README.md
|
198
|
# Peyssonnelia bicolor (Børgesen) Denizot SPECIES
#### Status
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
apache-2.0
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Caryophyllales/Aizoaceae/Conophytum/Conophytum pubescens/README.md
|
191
|
# Conophytum pubescens (Tischer) G.D.Rowley SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null
|
apache-2.0
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Brassicales/Cleomaceae/Cleome/Cleome hirsuta/README.md
|
183
|
# Cleome hirsuta Ruiz & Pav. ex DC. SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null
|
apache-2.0
|
mdoering/backbone
|
life/Plantae/Bacillariophyta/Bacillariophyceae/Acnanthales/Achnanthidiaceae/Psammothidium/Psammothidium reversum/README.md
|
213
|
# Psammothidium reversum (Lange-Bertalot) L. Bukhtiyarova SPECIES
#### Status
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
apache-2.0
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Gentianales/Rubiaceae/Palicourea/Palicourea longistipulata/Palicourea longistipulata chrysorrhachis/README.md
|
208
|
# Palicourea longistipulata subsp. chrysorrhachis SUBSPECIES
#### Status
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
apache-2.0
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Ericales/Sapotaceae/Synsepalum/Synsepalum brevipes/ Syn. Pachystela cinerea/README.md
|
199
|
# Pachystela cinerea (Engl.) Pierre ex Engl. SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
apache-2.0
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Ericales/Ericaceae/Rhododendron/Rhododendron trichophorum/README.md
|
184
|
# Rhododendron trichophorum Balf. f. SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null
|
apache-2.0
|
red-hood/calendarserver
|
twistedcaldav/test/test_database.py
|
7176
|
##
# Copyright (c) 2009-2015 Apple 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.
##
from twistedcaldav.database import AbstractADBAPIDatabase, ADBAPISqliteMixin
import twistedcaldav.test.util
from twisted.internet.defer import inlineCallbacks
import os
import time
class Database (twistedcaldav.test.util.TestCase):
"""
Test abstract SQL DB class
"""
class TestDB(ADBAPISqliteMixin, AbstractADBAPIDatabase):
def __init__(self, path, persistent=False, version="1"):
self.version = version
self.dbpath = path
super(Database.TestDB, self).__init__("sqlite", "sqlite3", (path,), persistent, cp_min=3, cp_max=3)
def _db_version(self):
"""
@return: the schema version assigned to this index.
"""
return self.version
def _db_type(self):
"""
@return: the collection type assigned to this index.
"""
return "TESTTYPE"
def _db_init_data_tables(self):
"""
Initialise the underlying database tables.
@param q: a database cursor to use.
"""
#
# TESTTYPE table
#
return self._db_execute(
"""
create table TESTTYPE (
KEY text unique,
VALUE text
)
"""
)
def _db_remove_data_tables(self):
return self._db_execute("drop table TESTTYPE")
class TestDBRecreateUpgrade(TestDB):
class RecreateDBException(Exception):
pass
class UpgradeDBException(Exception):
pass
def __init__(self, path, persistent=False):
super(Database.TestDBRecreateUpgrade, self).__init__(path, persistent, version="2")
def _db_recreate(self):
raise self.RecreateDBException()
class TestDBCreateIndexOnUpgrade(TestDB):
def __init__(self, path, persistent=False):
super(Database.TestDBCreateIndexOnUpgrade, self).__init__(path, persistent, version="2")
def _db_upgrade_data_tables(self, old_version):
return self._db_execute(
"""
create index TESTING on TESTTYPE (VALUE)
"""
)
class TestDBPauseInInit(TestDB):
def _db_init(self):
time.sleep(1)
super(Database.TestDBPauseInInit, self)._db_init()
@inlineCallbacks
def inlineCallbackRaises(self, exc, f, *args, **kwargs):
try:
yield f(*args, **kwargs)
except exc:
pass
except Exception, e:
self.fail("Wrong exception raised: %s" % (e,))
else:
self.fail("%s not raised" % (exc,))
@inlineCallbacks
def test_connect(self):
"""
Connect to database and create table
"""
db = Database.TestDB(self.mktemp())
self.assertFalse(db.initialized)
yield db.open()
self.assertTrue(db.initialized)
@inlineCallbacks
def test_connectFailure(self):
"""
Failure to connect cleans up the pool
"""
db = Database.TestDB(self.mktemp())
# Make _db_init fail
db._db_init = lambda : 1 / 0
self.assertFalse(db.initialized)
try:
yield db.open()
except:
pass
self.assertFalse(db.initialized)
self.assertEquals(db.pool, None)
@inlineCallbacks
def test_readwrite(self):
"""
Add a record, search for it
"""
db = Database.TestDB(self.mktemp())
yield db.execute("INSERT into TESTTYPE (KEY, VALUE) values (:1, :2)", ("FOO", "BAR",))
items = (yield db.query("SELECT * from TESTTYPE"))
self.assertEqual(items, (("FOO", "BAR"),))
items = (yield db.queryList("SELECT * from TESTTYPE"))
self.assertEqual(items, ("FOO",))
@inlineCallbacks
def test_close(self):
"""
Close database
"""
db = Database.TestDB(self.mktemp())
self.assertFalse(db.initialized)
yield db.open()
db.close()
self.assertFalse(db.initialized)
db.close()
@inlineCallbacks
def test_version_upgrade_nonpersistent(self):
"""
Connect to database and create table
"""
db_file = self.mktemp()
db = Database.TestDB(db_file)
yield db.open()
yield db.execute("INSERT into TESTTYPE (KEY, VALUE) values (:1, :2)", ("FOO", "BAR",))
items = (yield db.query("SELECT * from TESTTYPE"))
self.assertEqual(items, (("FOO", "BAR"),))
db.close()
db = None
db = Database.TestDBRecreateUpgrade(db_file)
yield self.inlineCallbackRaises(Database.TestDBRecreateUpgrade.RecreateDBException, db.open)
items = (yield db.query("SELECT * from TESTTYPE"))
self.assertEqual(items, ())
@inlineCallbacks
def test_version_upgrade_persistent(self):
"""
Connect to database and create table
"""
db_file = self.mktemp()
db = Database.TestDB(db_file, persistent=True)
yield db.open()
yield db.execute("INSERT into TESTTYPE (KEY, VALUE) values (:1, :2)", ("FOO", "BAR",))
items = (yield db.query("SELECT * from TESTTYPE"))
self.assertEqual(items, (("FOO", "BAR"),))
db.close()
db = None
db = Database.TestDBRecreateUpgrade(db_file, persistent=True)
yield self.inlineCallbackRaises(NotImplementedError, db.open)
self.assertTrue(os.path.exists(db_file))
db.close()
db = None
db = Database.TestDB(db_file, persistent=True)
yield db.open()
items = (yield db.query("SELECT * from TESTTYPE"))
self.assertEqual(items, (("FOO", "BAR"),))
@inlineCallbacks
def test_version_upgrade_persistent_add_index(self):
"""
Connect to database and create table
"""
db_file = self.mktemp()
db = Database.TestDB(db_file, persistent=True)
yield db.open()
yield db.execute("INSERT into TESTTYPE (KEY, VALUE) values (:1, :2)", ("FOO", "BAR",))
items = (yield db.query("SELECT * from TESTTYPE"))
self.assertEqual(items, (("FOO", "BAR"),))
db.close()
db = None
db = Database.TestDBCreateIndexOnUpgrade(db_file, persistent=True)
yield db.open()
items = (yield db.query("SELECT * from TESTTYPE"))
self.assertEqual(items, (("FOO", "BAR"),))
|
apache-2.0
|
streamlio/heron
|
docker/scripts/ci-docker.sh
|
3729
|
#!/bin/sh
set -o errexit
realpath() {
echo "$(cd "$(dirname "$1")"; pwd)/$(basename "$1")"
}
DOCKER_DIR=$(dirname $(dirname $(realpath $0)))
PROJECT_DIR=$(dirname $DOCKER_DIR )
SCRATCH_DIR="$HOME/.heron-docker"
cleanup() {
if [ -d $SCRATCH_DIR ]; then
echo "Cleaning up scratch dir"
rm -rf $SCRATCH_DIR
fi
}
trap cleanup EXIT
setup_scratch_dir() {
if [ ! -f "$1" ]; then
mkdir $1
mkdir $1/artifacts
fi
cp -r $DOCKER_DIR/* $1
}
build_exec_image() {
INPUT_TARGET_PLATFORM=$1
HERON_VERSION=$2
DOCKER_TAG_PREFIX=$3
OUTPUT_DIRECTORY=$(realpath $4)
if [ "$INPUT_TARGET_PLATFORM" == "latest" ]; then
TARGET_PLATFORM="ubuntu14.04"
DOCKER_TAG="$DOCKER_TAG_PREFIX/heron:$HERON_VERSION"
DOCKER_LATEST_TAG="$DOCKER_TAG_PREFIX/heron:latest"
DOCKER_IMAGE_FILE="$OUTPUT_DIRECTORY/heron-$HERON_VERSION.tar"
else
TARGET_PLATFORM="$INPUT_TARGET_PLATFORM"
DOCKER_TAG="$DOCKER_TAG_PREFIX/heron-$TARGET_PLATFORM:$HERON_VERSION"
DOCKER_LATEST_TAG="$DOCKER_TAG_PREFIX/heron-$TARGET_PLATFORM:latest"
DOCKER_IMAGE_FILE="$OUTPUT_DIRECTORY/heron-$TARGET_PLATFORM-$HERON_VERSION.tar"
fi
DOCKER_FILE="$SCRATCH_DIR/dist/Dockerfile.dist.$TARGET_PLATFORM"
setup_scratch_dir $SCRATCH_DIR
# need to copy artifacts locally
TOOLS_FILE="$OUTPUT_DIRECTORY/heron-tools-install.sh"
TOOLS_OUT_FILE="$SCRATCH_DIR/artifacts/heron-tools-install.sh"
CORE_FILE="$OUTPUT_DIRECTORY/heron-core.tar.gz"
CORE_OUT_FILE="$SCRATCH_DIR/artifacts/heron-core.tar.gz"
cp $TOOLS_FILE $TOOLS_OUT_FILE
cp $CORE_FILE $CORE_OUT_FILE
export HERON_VERSION
# build the image
echo "Building docker image with tag:$DOCKER_TAG"
if [ "$HERON_VERSION" == "nightly" ]; then
docker build --build-arg heronVersion=$HERON_VERSION -t "$DOCKER_TAG" -f "$DOCKER_FILE" "$SCRATCH_DIR"
else
docker build --build-arg heronVersion=$HERON_VERSION -t "$DOCKER_TAG" -t "$DOCKER_LATEST_TAG" -f "$DOCKER_FILE" "$SCRATCH_DIR"
fi
# save the image as a tar file
echo "Saving docker image to $DOCKER_IMAGE_FILE"
docker save -o $DOCKER_IMAGE_FILE $DOCKER_TAG
}
publish_exec_image() {
INPUT_TARGET_PLATFORM=$1
HERON_VERSION=$2
DOCKER_TAG_PREFIX=$3
INPUT_DIRECTORY=$(realpath $4)
if [ "$INPUT_TARGET_PLATFORM" == "latest" ]; then
TARGET_PLATFORM="ubuntu14.04"
DOCKER_TAG="$DOCKER_TAG_PREFIX/heron:$HERON_VERSION"
DOCKER_LATEST_TAG="$DOCKER_TAG_PREFIX/heron:latest"
DOCKER_IMAGE_FILE="$INPUT_DIRECTORY/heron-$HERON_VERSION.tar"
else
TARGET_PLATFORM="$INPUT_TARGET_PLATFORM"
DOCKER_TAG="$DOCKER_TAG_PREFIX/heron-$TARGET_PLATFORM:$HERON_VERSION"
DOCKER_LATEST_TAG="$DOCKER_TAG_PREFIX/heron-$TARGET_PLATFORM:latest"
DOCKER_IMAGE_FILE="$INPUT_DIRECTORY/heron-$TARGET_PLATFORM-$HERON_VERSION.tar"
fi
# publish the image to docker hub
if [ "$HERON_VERSION" == "nightly" ]; then
docker load -i $DOCKER_IMAGE_FILE
docker push "$DOCKER_TAG"
else
docker load -i $DOCKER_IMAGE_FILE
docker push "$DOCKER_TAG"
docker push "$DOCKER_LATEST_TAG"
fi
}
docker_image() {
OPERATION=$1
if [ "$OPERATION" == "build" ]; then
build_exec_image $2 $3 $4 $5
elif [ "$OPERATION" == "publish" ]; then
publish_exec_image $2 $3 $4 $5
else
echo "invalid operation"
fi
}
case $# in
5)
docker_image $1 $2 $3 $4 $5
;;
*)
echo "Usage: $0 <operation> <platform> <version_string> <tag-prefix> <input-output-directory> "
echo " "
echo "Platforms Supported: latest ubuntu14.04, ubuntu15.10, ubuntu16.04 centos7"
echo " "
echo "Example:"
echo " $0 build ubuntu14.04 0.12.0 heron ."
echo " $0 publish ubuntu14.04 0.12.0 streamlio ~/ubuntu"
echo " "
exit 1
;;
esac
|
apache-2.0
|
danke-sra/GearVRf
|
GVRf/Framework/src/org/gearvrf/bulletphysics/dynamics/constraintsolver/Point2PointConstraint.java
|
7029
|
/*
* Java port of Bullet (c) 2008 Martin Dvorak <[email protected]>
*
* Bullet Continuous Collision Detection and Physics Library
* Copyright (c) 2003-2008 Erwin Coumans http://www.bulletphysics.com/
*
* This software is provided 'as-is', without any express or implied warranty.
* In no event will the authors be held liable for any damages arising from
* the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
package org.gearvrf.bulletphysics.dynamics.constraintsolver;
import javax.vecmath.Matrix3f;
import javax.vecmath.Vector3f;
import org.gearvrf.bulletphysics.dynamics.RigidBody;
import org.gearvrf.bulletphysics.linearmath.Transform;
import org.gearvrf.bulletphysics.linearmath.VectorUtil;
import org.gearvrf.bulletphysics.stack.Stack;
/**
* Point to point constraint between two rigid bodies each with a pivot point that
* descibes the "ballsocket" location in local space.
*
* @author jezek2
*/
public class Point2PointConstraint extends TypedConstraint {
private final JacobianEntry[] jac = new JacobianEntry[]/*[3]*/ { new JacobianEntry(), new JacobianEntry(), new JacobianEntry() }; // 3 orthogonal linear constraints
private final Vector3f pivotInA = new Vector3f();
private final Vector3f pivotInB = new Vector3f();
public ConstraintSetting setting = new ConstraintSetting();
public Point2PointConstraint() {
super(TypedConstraintType.POINT2POINT_CONSTRAINT_TYPE);
}
public Point2PointConstraint(RigidBody rbA, RigidBody rbB, Vector3f pivotInA, Vector3f pivotInB) {
super(TypedConstraintType.POINT2POINT_CONSTRAINT_TYPE, rbA, rbB);
this.pivotInA.set(pivotInA);
this.pivotInB.set(pivotInB);
}
public Point2PointConstraint(RigidBody rbA, Vector3f pivotInA) {
super(TypedConstraintType.POINT2POINT_CONSTRAINT_TYPE, rbA);
this.pivotInA.set(pivotInA);
this.pivotInB.set(pivotInA);
rbA.getCenterOfMassTransform(Stack.alloc(Transform.class)).transform(this.pivotInB);
}
@Override
public void buildJacobian() {
appliedImpulse = 0f;
Vector3f normal = Stack.alloc(Vector3f.class);
normal.set(0f, 0f, 0f);
Matrix3f tmpMat1 = Stack.alloc(Matrix3f.class);
Matrix3f tmpMat2 = Stack.alloc(Matrix3f.class);
Vector3f tmp1 = Stack.alloc(Vector3f.class);
Vector3f tmp2 = Stack.alloc(Vector3f.class);
Vector3f tmpVec = Stack.alloc(Vector3f.class);
Transform centerOfMassA = rbA.getCenterOfMassTransform(Stack.alloc(Transform.class));
Transform centerOfMassB = rbB.getCenterOfMassTransform(Stack.alloc(Transform.class));
for (int i = 0; i < 3; i++) {
VectorUtil.setCoord(normal, i, 1f);
tmpMat1.transpose(centerOfMassA.basis);
tmpMat2.transpose(centerOfMassB.basis);
tmp1.set(pivotInA);
centerOfMassA.transform(tmp1);
tmp1.sub(rbA.getCenterOfMassPosition(tmpVec));
tmp2.set(pivotInB);
centerOfMassB.transform(tmp2);
tmp2.sub(rbB.getCenterOfMassPosition(tmpVec));
jac[i].init(
tmpMat1,
tmpMat2,
tmp1,
tmp2,
normal,
rbA.getInvInertiaDiagLocal(Stack.alloc(Vector3f.class)),
rbA.getInvMass(),
rbB.getInvInertiaDiagLocal(Stack.alloc(Vector3f.class)),
rbB.getInvMass());
VectorUtil.setCoord(normal, i, 0f);
}
}
@Override
public void solveConstraint(float timeStep) {
Vector3f tmp = Stack.alloc(Vector3f.class);
Vector3f tmp2 = Stack.alloc(Vector3f.class);
Vector3f tmpVec = Stack.alloc(Vector3f.class);
Transform centerOfMassA = rbA.getCenterOfMassTransform(Stack.alloc(Transform.class));
Transform centerOfMassB = rbB.getCenterOfMassTransform(Stack.alloc(Transform.class));
Vector3f pivotAInW = Stack.alloc(pivotInA);
centerOfMassA.transform(pivotAInW);
Vector3f pivotBInW = Stack.alloc(pivotInB);
centerOfMassB.transform(pivotBInW);
Vector3f normal = Stack.alloc(Vector3f.class);
normal.set(0f, 0f, 0f);
//btVector3 angvelA = m_rbA.getCenterOfMassTransform().getBasis().transpose() * m_rbA.getAngularVelocity();
//btVector3 angvelB = m_rbB.getCenterOfMassTransform().getBasis().transpose() * m_rbB.getAngularVelocity();
for (int i = 0; i < 3; i++) {
VectorUtil.setCoord(normal, i, 1f);
float jacDiagABInv = 1f / jac[i].getDiagonal();
Vector3f rel_pos1 = Stack.alloc(Vector3f.class);
rel_pos1.sub(pivotAInW, rbA.getCenterOfMassPosition(tmpVec));
Vector3f rel_pos2 = Stack.alloc(Vector3f.class);
rel_pos2.sub(pivotBInW, rbB.getCenterOfMassPosition(tmpVec));
// this jacobian entry could be re-used for all iterations
Vector3f vel1 = rbA.getVelocityInLocalPoint(rel_pos1, Stack.alloc(Vector3f.class));
Vector3f vel2 = rbB.getVelocityInLocalPoint(rel_pos2, Stack.alloc(Vector3f.class));
Vector3f vel = Stack.alloc(Vector3f.class);
vel.sub(vel1, vel2);
float rel_vel;
rel_vel = normal.dot(vel);
/*
//velocity error (first order error)
btScalar rel_vel = m_jac[i].getRelativeVelocity(m_rbA.getLinearVelocity(),angvelA,
m_rbB.getLinearVelocity(),angvelB);
*/
// positional error (zeroth order error)
tmp.sub(pivotAInW, pivotBInW);
float depth = -tmp.dot(normal); //this is the error projected on the normal
float impulse = depth * setting.tau / timeStep * jacDiagABInv - setting.damping * rel_vel * jacDiagABInv;
float impulseClamp = setting.impulseClamp;
if (impulseClamp > 0f) {
if (impulse < -impulseClamp) {
impulse = -impulseClamp;
}
if (impulse > impulseClamp) {
impulse = impulseClamp;
}
}
appliedImpulse += impulse;
Vector3f impulse_vector = Stack.alloc(Vector3f.class);
impulse_vector.scale(impulse, normal);
tmp.sub(pivotAInW, rbA.getCenterOfMassPosition(tmpVec));
rbA.applyImpulse(impulse_vector, tmp);
tmp.negate(impulse_vector);
tmp2.sub(pivotBInW, rbB.getCenterOfMassPosition(tmpVec));
rbB.applyImpulse(tmp, tmp2);
VectorUtil.setCoord(normal, i, 0f);
}
}
public void updateRHS(float timeStep) {
}
public void setPivotA(Vector3f pivotA) {
pivotInA.set(pivotA);
}
public void setPivotB(Vector3f pivotB) {
pivotInB.set(pivotB);
}
public Vector3f getPivotInA(Vector3f out) {
out.set(pivotInA);
return out;
}
public Vector3f getPivotInB(Vector3f out) {
out.set(pivotInB);
return out;
}
////////////////////////////////////////////////////////////////////////////
public static class ConstraintSetting {
public float tau = 0.3f;
public float damping = 1f;
public float impulseClamp = 0f;
}
}
|
apache-2.0
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Malpighiales/Malpighiaceae/Tetrapteris/Tetrapteris latibracteolata/README.md
|
183
|
# Tetrapteris latibracteolata Nied. SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null
|
apache-2.0
|
aslakknutsen/arquillian-extension-warp
|
impl/src/main/java/org/jboss/arquillian/warp/client/proxy/ProxyURLProvider.java
|
2711
|
/**
* JBoss, Home of Professional Open Source
* Copyright 2012, Red Hat Middleware LLC, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* 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.jboss.arquillian.warp.client.proxy;
import java.lang.annotation.Annotation;
import java.net.URL;
import org.jboss.arquillian.container.test.impl.enricher.resource.URLResourceProvider;
import org.jboss.arquillian.core.api.Injector;
import org.jboss.arquillian.core.api.Instance;
import org.jboss.arquillian.core.api.annotation.Inject;
import org.jboss.arquillian.core.spi.ServiceLoader;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.arquillian.test.spi.enricher.resource.ResourceProvider;
import org.jboss.arquillian.warp.utils.URLUtils;
/**
* Provides the proxy URL instead of real URL.
*
* Stores the mapping between real URL and proxy URL in {@link URLMapping}.
*
* @author Lukas Fryc
*
*/
public class ProxyURLProvider implements ResourceProvider {
@Inject
Instance<ServiceLoader> serviceLoader;
@Inject
Instance<URLMapping> mapping;
@Inject
Instance<ProxyHolder> proxyHolder;
@Inject
Instance<Injector> injector;
URLResourceProvider urlResourceProvider = new URLResourceProvider();
@Override
public boolean canProvide(Class<?> type) {
return URL.class.isAssignableFrom(type);
}
@Override
public Object lookup(ArquillianResource resource, Annotation... qualifiers) {
injector.get().inject(urlResourceProvider);
URL realUrl = (URL) urlResourceProvider.lookup(resource, qualifiers);
if ("http".equals(realUrl.getProtocol())) {
return getProxyUrl(realUrl);
} else {
return realUrl;
}
}
private URL getProxyUrl(URL realUrl) {
URL baseRealUrl = URLUtils.getUrlBase(realUrl);
URL baseProxyUrl = mapping.get().getProxyURL(baseRealUrl);
URL proxyUrl = URLUtils.buildUrl(baseProxyUrl, realUrl.getPath());
proxyHolder.get().startProxyForUrl(baseProxyUrl, baseRealUrl);
return proxyUrl;
}
}
|
apache-2.0
|
inputx/code-ref-doc
|
bonfire/_functions/write_config.html
|
5495
|
<!doctype html public "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html>
<head>
<title>PHPXRef 0.7.1 : Unnamed Project : Function Reference: write_config()</title>
<link rel="stylesheet" href="../sample.css" type="text/css">
<link rel="stylesheet" href="../sample-print.css" type="text/css" media="print">
<style id="hilight" type="text/css"></style>
<meta http-equiv="content-type" content="text/html;charset=iso-8859-1">
</head>
<body bgcolor="#ffffff" text="#000000" link="#801800" vlink="#300540" alink="#ffffff">
<table class="pagetitle" width="100%">
<tr>
<td valign="top" class="pagetitle">
[ <a href="../index.html">Index</a> ]
</td>
<td align="right" class="pagetitle">
<h2 style="margin-bottom: 0px">PHP Cross Reference of Unnamed Project</h2>
</td>
</tr>
</table>
<!-- Generated by PHPXref 0.7.1 at Thu Oct 23 18:57:41 2014 -->
<!-- PHPXref (c) 2000-2010 Gareth Watts - [email protected] -->
<!-- http://phpxref.sourceforge.net/ -->
<script src="../phpxref.js" type="text/javascript"></script>
<script language="JavaScript" type="text/javascript">
<!--
ext='.html';
relbase='../';
subdir='_functions';
filename='index.html';
cookiekey='phpxref';
handleNavFrame(relbase, subdir, filename);
logFunction('write_config');
// -->
</script>
<script language="JavaScript" type="text/javascript">
if (gwGetCookie('xrefnav')=='off')
document.write('<p class="navlinks">[ <a href="javascript:navOn()">Show Explorer<\/a> ]<\/p>');
else
document.write('<p class="navlinks">[ <a href="javascript:navOff()">Hide Explorer<\/a> ]<\/p>');
</script>
<noscript>
<p class="navlinks">
[ <a href="../nav.html" target="_top">Show Explorer</a> ]
[ <a href="index.html" target="_top">Hide Navbar</a> ]
</p>
</noscript>
[<a href="../index.html">Top level directory</a>]<br>
<script language="JavaScript" type="text/javascript">
<!--
document.writeln('<table align="right" class="searchbox-link"><tr><td><a class="searchbox-link" href="javascript:void(0)" onMouseOver="showSearchBox()">Search</a><br>');
document.writeln('<table border="0" cellspacing="0" cellpadding="0" class="searchbox" id="searchbox">');
document.writeln('<tr><td class="searchbox-title">');
document.writeln('<a class="searchbox-title" href="javascript:showSearchPopup()">Search History +</a>');
document.writeln('<\/td><\/tr>');
document.writeln('<tr><td class="searchbox-body" id="searchbox-body">');
document.writeln('<form name="search" style="margin:0px; padding:0px" onSubmit=\'return jump()\'>');
document.writeln('<a class="searchbox-body" href="../_classes/index.html">Class<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="classname"><br>');
document.writeln('<a id="funcsearchlink" class="searchbox-body" href="../_functions/index.html">Function<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="funcname"><br>');
document.writeln('<a class="searchbox-body" href="../_variables/index.html">Variable<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="varname"><br>');
document.writeln('<a class="searchbox-body" href="../_constants/index.html">Constant<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="constname"><br>');
document.writeln('<a class="searchbox-body" href="../_tables/index.html">Table<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="tablename"><br>');
document.writeln('<input type="submit" class="searchbox-button" value="Search">');
document.writeln('<\/form>');
document.writeln('<\/td><\/tr><\/table>');
document.writeln('<\/td><\/tr><\/table>');
// -->
</script>
<div id="search-popup" class="searchpopup"><p id="searchpopup-title" class="searchpopup-title">title</p><div id="searchpopup-body" class="searchpopup-body">Body</div><p class="searchpopup-close"><a href="javascript:gwCloseActive()">[close]</a></p></div>
<h3>Function and Method Cross Reference</h3>
<h2><a href="index.html#write_config">write_config()</a></h2>
<b>Defined at:</b><ul>
<li><a href="../bonfire/helpers/config_file_helper.php.html#write_config">/bonfire/helpers/config_file_helper.php</a> -> <a onClick="logFunction('write_config', '/bonfire/helpers/config_file_helper.php.source.html#l101')" href="../bonfire/helpers/config_file_helper.php.source.html#l101"> line 101</a></li>
</ul>
<b>Referenced 4 times:</b><ul>
<li><a href="../bonfire/modules/ui/libraries/contexts.php.html">/bonfire/modules/ui/libraries/contexts.php</a> -> <a href="../bonfire/modules/ui/libraries/contexts.php.source.html#l508"> line 508</a></li>
<li><a href="../bonfire/docs/changelog.md.html">/bonfire/docs/changelog.md</a> -> <a href="../bonfire/docs/changelog.md.source.html#l331"> line 331</a></li>
<li><a href="../bonfire/libraries/installer_lib.php.html">/bonfire/libraries/installer_lib.php</a> -> <a href="../bonfire/libraries/installer_lib.php.source.html#l513"> line 513</a></li>
<li><a href="../bonfire/modules/logs/controllers/developer.php.html">/bonfire/modules/logs/controllers/developer.php</a> -> <a href="../bonfire/modules/logs/controllers/developer.php.source.html#l162"> line 162</a></li>
</ul>
<!-- A link to the phpxref site in your customized footer file is appreciated ;-) -->
<br><hr>
<table width="100%">
<tr><td>Generated: Thu Oct 23 18:57:41 2014</td>
<td align="right"><i>Cross-referenced by <a href="http://phpxref.sourceforge.net/">PHPXref 0.7.1</a></i></td>
</tr>
</table>
</body></html>
|
apache-2.0
|
ilantukh/ignite
|
examples/src/main/java/org/apache/ignite/examples/ml/tutorial/Step_2_Imputing.java
|
3986
|
/*
* 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.examples.ml.tutorial;
import java.io.FileNotFoundException;
import org.apache.ignite.Ignite;
import org.apache.ignite.IgniteCache;
import org.apache.ignite.Ignition;
import org.apache.ignite.ml.dataset.feature.extractor.Vectorizer;
import org.apache.ignite.ml.dataset.feature.extractor.impl.DummyVectorizer;
import org.apache.ignite.ml.math.primitives.vector.Vector;
import org.apache.ignite.ml.preprocessing.Preprocessor;
import org.apache.ignite.ml.preprocessing.imputing.ImputerTrainer;
import org.apache.ignite.ml.selection.scoring.evaluator.Evaluator;
import org.apache.ignite.ml.selection.scoring.metric.classification.Accuracy;
import org.apache.ignite.ml.tree.DecisionTreeClassificationTrainer;
import org.apache.ignite.ml.tree.DecisionTreeNode;
/**
* Usage of {@link ImputerTrainer} to fill missed data ({@code Double.NaN}) values in the chosen columns.
* <p>
* Code in this example launches Ignite grid and fills the cache with test data (based on Titanic passengers data).</p>
* <p>
* After that it defines preprocessors that extract features from an upstream data and
* <a href="https://en.wikipedia.org/wiki/Imputation_(statistics)">impute</a> missing values.</p>
* <p>
* Then, it trains the model based on the processed data using decision tree classification.</p>
* <p>
* Finally, this example uses {@link Evaluator} functionality to compute metrics from predictions.</p>
*/
public class Step_2_Imputing {
/** Run example. */
public static void main(String[] args) {
System.out.println();
System.out.println(">>> Tutorial step 2 (imputing) example started.");
try (Ignite ignite = Ignition.start("examples/config/example-ignite.xml")) {
try {
IgniteCache<Integer, Vector> dataCache = TitanicUtils.readPassengers(ignite);
final Vectorizer<Integer, Vector, Integer, Double> vectorizer = new DummyVectorizer<Integer>(0, 5, 6).labeled(1);
Preprocessor<Integer, Vector> imputingPreprocessor = new ImputerTrainer<Integer, Vector>()
.fit(ignite,
dataCache,
vectorizer // "pclass", "sibsp", "parch"
);
DecisionTreeClassificationTrainer trainer = new DecisionTreeClassificationTrainer(5, 0);
// Train decision tree model.
DecisionTreeNode mdl = trainer.fit(
ignite,
dataCache,
vectorizer
);
System.out.println("\n>>> Trained model: " + mdl);
double accuracy = Evaluator.evaluate(
dataCache,
mdl,
imputingPreprocessor,
new Accuracy<>()
);
System.out.println("\n>>> Accuracy " + accuracy);
System.out.println("\n>>> Test Error " + (1 - accuracy));
System.out.println(">>> Tutorial step 2 (imputing) example completed.");
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
}
|
apache-2.0
|
voten-co/voten
|
app/Http/Resources/FeedbackResource.php
|
656
|
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\Resource;
class FeedbackResource extends Resource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request
*
* @return array
*/
public function toArray($request)
{
return [
'id' => $this->id,
'subject' => $this->subject,
'user_id' => $this->user_id,
'description' => $this->description,
'created_at' => optional($this->created_at)->toDateTimeString(),
'author' => new UserResource($this->owner),
];
}
}
|
apache-2.0
|
akiskip/KoDeMat-Collaboration-Platform-Application
|
KoDeMat_TouchScreen/lib/hazelcast-3.4.2/hazelcast-3.4.2/docs/javadoc/com/hazelcast/map/impl/SizeEstimator.html
|
10020
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_45) on Thu Mar 26 16:48:27 UTC 2015 -->
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
SizeEstimator (Hazelcast Root 3.4.2 API)
</TITLE>
<META NAME="date" CONTENT="2015-03-26">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="SizeEstimator (Hazelcast Root 3.4.2 API)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/SizeEstimator.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../com/hazelcast/map/impl/SimpleEntryView.html" title="class in com.hazelcast.map.impl"><B>PREV CLASS</B></A>
<A HREF="../../../../com/hazelcast/map/impl/SizeEstimators.html" title="class in com.hazelcast.map.impl"><B>NEXT CLASS</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../index.html?com/hazelcast/map/impl/SizeEstimator.html" target="_top"><B>FRAMES</B></A>
<A HREF="SizeEstimator.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: NESTED | FIELD | CONSTR | <A HREF="#method_summary">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: FIELD | CONSTR | <A HREF="#method_detail">METHOD</A></FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<!-- ======== START OF CLASS DATA ======== -->
<H2>
<FONT SIZE="-1">
com.hazelcast.map.impl</FONT>
<BR>
Interface SizeEstimator<T></H2>
<DL>
<DT><DT><B>Type Parameters:</B><DD><CODE>T</CODE> - the type of object which's size going to be estimated.</DL>
<HR>
<DL>
<DT><PRE>public interface <B>SizeEstimator<T></B></DL>
</PRE>
<P>
Size estimator general contract.
<P>
<P>
<HR>
<P>
<!-- ========== METHOD SUMMARY =========== -->
<A NAME="method_summary"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Method Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../com/hazelcast/map/impl/SizeEstimator.html#add(long)">add</A></B>(long size)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> long</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../com/hazelcast/map/impl/SizeEstimator.html#getCost(T)">getCost</A></B>(<A HREF="../../../../com/hazelcast/map/impl/SizeEstimator.html" title="type parameter in SizeEstimator">T</A> record)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> long</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../com/hazelcast/map/impl/SizeEstimator.html#getSize()">getSize</A></B>()</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../com/hazelcast/map/impl/SizeEstimator.html#reset()">reset</A></B>()</CODE>
<BR>
</TD>
</TR>
</TABLE>
<P>
<!-- ============ METHOD DETAIL ========== -->
<A NAME="method_detail"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2">
<B>Method Detail</B></FONT></TH>
</TR>
</TABLE>
<A NAME="getSize()"><!-- --></A><H3>
getSize</H3>
<PRE>
long <B>getSize</B>()</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="add(long)"><!-- --></A><H3>
add</H3>
<PRE>
void <B>add</B>(long size)</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="getCost(java.lang.Object)"><!-- --></A><A NAME="getCost(T)"><!-- --></A><H3>
getCost</H3>
<PRE>
long <B>getCost</B>(<A HREF="../../../../com/hazelcast/map/impl/SizeEstimator.html" title="type parameter in SizeEstimator">T</A> record)</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="reset()"><!-- --></A><H3>
reset</H3>
<PRE>
void <B>reset</B>()</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<!-- ========= END OF CLASS DATA ========= -->
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/SizeEstimator.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../com/hazelcast/map/impl/SimpleEntryView.html" title="class in com.hazelcast.map.impl"><B>PREV CLASS</B></A>
<A HREF="../../../../com/hazelcast/map/impl/SizeEstimators.html" title="class in com.hazelcast.map.impl"><B>NEXT CLASS</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../index.html?com/hazelcast/map/impl/SizeEstimator.html" target="_top"><B>FRAMES</B></A>
<A HREF="SizeEstimator.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: NESTED | FIELD | CONSTR | <A HREF="#method_summary">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: FIELD | CONSTR | <A HREF="#method_detail">METHOD</A></FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
Copyright © 2015 <a href="http://www.hazelcast.com/">Hazelcast, Inc.</a>. All Rights Reserved.
</BODY>
</HTML>
|
apache-2.0
|
onechain/fabric-explorer
|
socket/websocketserver.js
|
801
|
/*
Copyright ONECHAIN 2017 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.
*/
var StompServer=require('stomp-broker-js')
var stompServer
function init(http){
stompServer=new StompServer({server:http})
}
module.exports.init=init
module.exports.stomp=function () {
return stompServer
}
|
apache-2.0
|
mldbai/mldb
|
plugins/jml/separation_stats.cc
|
10625
|
// This file is part of MLDB. Copyright 2015 mldb.ai inc. All rights reserved.
/* separation_stats.cc
Jeremy Barnes, 14 June 2011
Copyright (c) 2011 mldb.ai inc. All rights reserved.
*/
#include "separation_stats.h"
#include "mldb/arch/exception.h"
#include "mldb/base/exc_assert.h"
#include <boost/utility.hpp>
#include "mldb/vfs/filter_streams.h"
using namespace std;
namespace MLDB {
/*****************************************************************************/
/* BINARY STATS */
/*****************************************************************************/
double
BinaryStats::
rocAreaSince(const BinaryStats & other) const
{
double tp1 = other.truePositiveRate(), fp1 = other.falsePositiveRate();
double tp2 = truePositiveRate(), fp2 = falsePositiveRate();
double result = (fp2 - fp1) * (tp1 + tp2) * 0.5;
//cerr << "tp1 = " << tp1 << " tp2 = " << tp2 << " fp1 = " << fp1
// << " fp2 = " << fp2 << " area = " << result << endl;
return result;
}
void
BinaryStats::
add(const BinaryStats & other, double weight)
{
auto addCounts = [&] ( Array2D & local,
const Array2D & other,
float w)
{
local[0][0] += w * other[0][0];
local[0][1] += w * other[0][1];
local[1][0] += w * other[1][0];
local[1][1] += w * other[1][1];
};
addCounts(counts, other.counts, weight);
addCounts(unweighted_counts, other.unweighted_counts, 1);
threshold += weight * other.threshold;
}
Json::Value
BinaryStats::
toJson() const
{
Json::Value result;
result["population"]["included"] = includedPopulation();
result["population"]["excluded"] = excludedPopulation();
result["pr"]["accuracy"] = accuracy();
result["pr"]["precision"] = precision();
result["pr"]["recall"] = recall();
result["pr"]["f1Score"] = f();
result["mcc"] = mcc();
result["gain"] = gain();
result["counts"]["truePositives"] = truePositives();
result["counts"]["falsePositives"] = falsePositives();
result["counts"]["trueNegatives"] = trueNegatives();
result["counts"]["falseNegatives"] = falseNegatives();
result["threshold"] = threshold;
return result;
}
/*****************************************************************************/
/* SCORED STATS */
/*****************************************************************************/
ScoredStats::
ScoredStats()
: auc(1.0), isSorted(true)
{
}
BinaryStats
ScoredStats::
atThreshold(float threshold) const
{
struct FindThreshold {
bool operator () (const BinaryStats & e1, const BinaryStats & e2) const
{
return e1.threshold > e2.threshold;
}
bool operator () (const BinaryStats & e1, float e2) const
{
return e1.threshold > e2;
}
bool operator () (float e1, const BinaryStats & e2) const
{
return e1 > e2.threshold;
}
};
if (!std::is_sorted(stats.begin(), stats.end(), FindThreshold()))
throw Exception("stats not sorted on input");
if (stats.empty())
throw Exception("stats is empty");
// Lower bound means strictly above
auto lower
= std::lower_bound(stats.begin(), stats.end(), threshold,
FindThreshold());
if (lower == stats.end())
return stats.back();
return *lower;
}
BinaryStats
ScoredStats::
atPercentile(float percentile) const
{
struct FindPercentile {
bool operator () (const BinaryStats & e1, const BinaryStats & e2) const
{
return e1.proportionOfPopulation() < e2.proportionOfPopulation();
}
bool operator () (const BinaryStats & e1, float e2) const
{
return e1.proportionOfPopulation() < e2;
}
bool operator () (float e1, const BinaryStats & e2) const
{
return e1 < e2.proportionOfPopulation();
}
};
for (unsigned i = 1; i < stats.size(); ++i) {
if (stats[i -1].proportionOfPopulation() > stats[i].proportionOfPopulation()) {
cerr << "i = " << i << endl;
cerr << "prev = " << stats[i - 1].toJson() << endl;
cerr << "ours = " << stats[i].toJson() << endl;
throw MLDB::Exception("really not sorted on input");
}
}
if (!std::is_sorted(stats.begin(), stats.end(), FindPercentile()))
throw Exception("stats not sorted on input");
if (stats.empty())
throw Exception("stats is empty");
// Lower bound means strictly above
auto it
= std::lower_bound(stats.begin(), stats.end(), percentile,
FindPercentile());
if (it == stats.begin())
return *it;
if (it == stats.end())
return stats.back();
BinaryStats upper = *it, lower = *std::prev(it);
// Do an interpolation
double atUpper = upper.proportionOfPopulation(),
atLower = lower.proportionOfPopulation(),
range = atUpper - atLower;
ExcAssertLessEqual(percentile, atUpper);
ExcAssertGreaterEqual(percentile, atLower);
ExcAssertGreater(range, 0);
double weight1 = (atUpper - percentile) / range;
double weight2 = (percentile - atLower) / range;
//cerr << "atUpper = " << atUpper << " atLower = " << atLower
// << " range = " << range << " weight1 = " << weight1
// << " weight2 = " << weight2 << endl;
BinaryStats result;
result.add(upper, weight2);
result.add(lower, weight1);
//cerr << "result prop = " << result.proportionOfPopulation() << endl;
return result;
}
void
ScoredStats::
sort()
{
// Go from highest to lowest score
std::sort(entries.begin(), entries.end());
isSorted = true;
}
void
ScoredStats::
calculate()
{
BinaryStats current;
for (unsigned i = 0; i < entries.size(); ++i)
current.counts[entries[i].label][false] += entries[i].weight;
if (!isSorted)
sort();
bestF = current;
bestMcc = current;
double totalAuc = 0.0;
stats.clear();
// take the all point
stats.push_back(BinaryStats(current, INFINITY));
for (unsigned i = 0; i < entries.size(); ++i) {
const ScoredStats::ScoredEntry & entry = entries[i];
if (i > 0 && entries[i - 1].score != entry.score) {
totalAuc += current.rocAreaSince(stats.back());
stats.push_back
(BinaryStats(current, entries[i - 1].score, entry.key));
if (current.f() > bestF.f())
bestF = stats.back();
if (current.mcc() > bestMcc.mcc())
bestMcc = stats.back();
if (current.specificity() > bestSpecificity.specificity())
bestSpecificity = stats.back();
#if 0
cerr << "entry " << i << ": score " << entries[i - 1].score
<< " p " << current.precision() << " r " << current.recall()
<< " f " << current.f() << " mcc " << current.mcc() << endl;
#endif
}
bool label = entry.label;
// We transfer from a false positive to a true negative, or a
// true positive to a false negative
double weight = entry.weight;
current.counts[label][false] -= weight;
current.counts[label][true] += weight;
current.unweighted_counts[label][false] -= 1;
current.unweighted_counts[label][true] += 1;
}
totalAuc += current.rocAreaSince(stats.back());
if (!entries.empty())
stats.push_back(BinaryStats(current, entries.back().score));
auc = totalAuc;
}
void
ScoredStats::
add(const ScoredStats & other)
{
if (!isSorted)
throw MLDB::Exception("attempt to add to non-sorted separation stats");
if (!other.isSorted)
throw MLDB::Exception("attempt to add non-sorted separation stats");
size_t split = entries.size();
entries.insert(entries.end(), other.entries.begin(), other.entries.end());
std::inplace_merge(entries.begin(), entries.begin() + split,
entries.end());
// If we had already calculated, we recalculate
if (!stats.empty())
calculate();
}
void
ScoredStats::
dumpRocCurveJs(std::ostream & stream) const
{
if (stats.empty())
throw MLDB::Exception("can't dump ROC curve without calling calculate()");
stream << "this.data = {" << endl;
stream << MLDB::format(" \"aroc\": %8.05f , ", auc) << endl;
stream << " \"model\":{";
for(unsigned i = 0; i < stats.size(); ++i) {
const BinaryStats & x = stats[i];
stream << MLDB::format("\n \"%8.05f\": { ", x.threshold);
stream << MLDB::format("\n tpr : %8.05f,", x.recall());
stream << MLDB::format("\n accuracy : %8.05f,", x.accuracy());
stream << MLDB::format("\n precision : %8.05f,", x.precision());
stream << MLDB::format("\n fscore : %8.05f,", x.f());
stream << MLDB::format("\n fpr : %8.05f,", x.falsePositiveRate());
stream << MLDB::format("\n tp : %8.05f,", x.truePositives());
stream << MLDB::format("\n fp : %8.05f,", x.falsePositives());
stream << MLDB::format("\n fn : %8.05f,", x.falseNegatives());
stream << MLDB::format("\n tn : %8.05f,", x.trueNegatives());
stream << MLDB::format("}");
stream << ",";
}
stream << "\n}";
stream << "};";
}
void
ScoredStats::
saveRocCurveJs(const std::string & filename) const
{
filter_ostream stream(filename);
dumpRocCurveJs(stream);
}
Json::Value
ScoredStats::
getRocCurveJson() const
{
if (stats.empty())
throw MLDB::Exception("can't dump ROC curve without calling calculate()");
Json::Value modelJs;
for(unsigned i = 0; i < stats.size(); ++i) {
const BinaryStats & x = stats[i];
modelJs[MLDB::format("%8.05f", x.threshold)] = x.toJson();
}
Json::Value js;
js["aroc"] = auc;
js["model"] = modelJs;
js["bestF1Score"] = bestF.toJson();
js["bestMcc"] = bestMcc.toJson();
return js;
}
void
ScoredStats::
saveRocCurveJson(const std::string & filename) const
{
filter_ostream stream(filename);
stream << getRocCurveJson().toStyledString() << endl;
}
Json::Value
ScoredStats::
toJson() const
{
Json::Value result;
result["auc"] = auc;
result["bestF1Score"] = bestF.toJson();
result["bestMcc"] = bestMcc.toJson();
return result;
}
} // namespace MLDB
|
apache-2.0
|
dcarda/aba.route.validator
|
target13/site/clover/com/cardatechnologies/utils/validators/abaroutevalidator/Test_AbaRouteValidator_17b_testAbaNumberCheck_36696_bad_j6u.html
|
10992
|
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<link rel="SHORTCUT ICON" href="../../../../../img/clover.ico" />
<link rel="stylesheet" href="../../../../../aui/css/aui.min.css" media="all"/>
<link rel="stylesheet" href="../../../../../aui/css/aui-experimental.min.css" media="all"/>
<!--[if IE 9]><link rel="stylesheet" href="../../../../../aui/css/aui-ie9.min.css" media="all"/><![endif]-->
<style type="text/css" media="all">
@import url('../../../../../style.css');
@import url('../../../../../tree.css');
</style>
<script src="../../../../../jquery-1.8.3.min.js" type="text/javascript"></script>
<script src="../../../../../aui/js/aui.min.js" type="text/javascript"></script>
<script src="../../../../../aui/js/aui-experimental.min.js" type="text/javascript"></script>
<script src="../../../../../aui/js/aui-soy.min.js" type="text/javascript"></script>
<script src="../../../../../package-nodes-tree.js" type="text/javascript"></script>
<script src="../../../../../clover-tree.js" type="text/javascript"></script>
<script src="../../../../../clover.js" type="text/javascript"></script>
<script src="../../../../../clover-descriptions.js" type="text/javascript"></script>
<script src="../../../../../cloud.js" type="text/javascript"></script>
<title>ABA Route Transit Number Validator 1.0.1-SNAPSHOT</title>
</head>
<body>
<div id="page">
<header id="header" role="banner">
<nav class="aui-header aui-dropdown2-trigger-group" role="navigation">
<div class="aui-header-inner">
<div class="aui-header-primary">
<h1 id="logo" class="aui-header-logo aui-header-logo-clover">
<a href="http://openclover.org" title="Visit OpenClover home page"><span class="aui-header-logo-device">OpenClover</span></a>
</h1>
</div>
<div class="aui-header-secondary">
<ul class="aui-nav">
<li id="system-help-menu">
<a class="aui-nav-link" title="Open online documentation" target="_blank"
href="http://openclover.org/documentation">
<span class="aui-icon aui-icon-small aui-iconfont-help"> Help</span>
</a>
</li>
</ul>
</div>
</div>
</nav>
</header>
<div class="aui-page-panel">
<div class="aui-page-panel-inner">
<div class="aui-page-panel-nav aui-page-panel-nav-clover">
<div class="aui-page-header-inner" style="margin-bottom: 20px;">
<div class="aui-page-header-image">
<a href="http://cardatechnologies.com" target="_top">
<div class="aui-avatar aui-avatar-large aui-avatar-project">
<div class="aui-avatar-inner">
<img src="../../../../../img/clover_logo_large.png" alt="Clover icon"/>
</div>
</div>
</a>
</div>
<div class="aui-page-header-main" >
<h1>
<a href="http://cardatechnologies.com" target="_top">
ABA Route Transit Number Validator 1.0.1-SNAPSHOT
</a>
</h1>
</div>
</div>
<nav class="aui-navgroup aui-navgroup-vertical">
<div class="aui-navgroup-inner">
<ul class="aui-nav">
<li class="">
<a href="../../../../../dashboard.html">Project overview</a>
</li>
</ul>
<div class="aui-nav-heading packages-nav-heading">
<strong>Packages</strong>
</div>
<div class="aui-nav project-packages">
<form method="get" action="#" class="aui package-filter-container">
<input type="text" autocomplete="off" class="package-filter text"
placeholder="Type to filter packages..." name="package-filter" id="package-filter"
title="Start typing package name (or part of the name) to search through the tree. Use arrow keys and the Enter key to navigate."/>
</form>
<p class="package-filter-no-results-message hidden">
<small>No results found.</small>
</p>
<div class="packages-tree-wrapper" data-root-relative="../../../../../" data-package-name="com.cardatechnologies.utils.validators.abaroutevalidator">
<div class="packages-tree-container"></div>
<div class="clover-packages-lozenges"></div>
</div>
</div>
</div>
</nav> </div>
<section class="aui-page-panel-content">
<div class="aui-page-panel-content-clover">
<div class="aui-page-header-main"><ol class="aui-nav aui-nav-breadcrumbs">
<li><a href="../../../../../dashboard.html"> Project Clover database Sat Aug 7 2021 12:29:33 MDT</a></li>
<li><a href="test-pkg-summary.html">Package com.cardatechnologies.utils.validators.abaroutevalidator</a></li>
<li><a href="test-Test_AbaRouteValidator_17b.html">Class Test_AbaRouteValidator_17b</a></li>
</ol></div>
<h1 class="aui-h2-clover">
Test testAbaNumberCheck_36696_bad
</h1>
<table class="aui">
<thead>
<tr>
<th>Test</th>
<th><label title="The test result. Either a Pass, Fail or Error.">Status</label></th>
<th><label title="When the test execution was started">Start time</label></th>
<th><label title="The total time in seconds taken to run this test.">Time (seconds)</label></th>
<th><label title="A failure or error message if the test is not successful.">Message</label></th>
</tr>
</thead>
<tbody>
<tr>
<td>
<a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/Test_AbaRouteValidator_17b.html?line=38705#src-38705" >testAbaNumberCheck_36696_bad</a>
</td>
<td>
<span class="sortValue">1</span><span class="aui-lozenge aui-lozenge-success">PASS</span>
</td>
<td>
7 Aug 12:46:55
</td>
<td>
0.001 </td>
<td>
<div></div>
<div class="errorMessage"></div>
</td>
</tr>
</tbody>
</table>
<div> </div>
<table class="aui aui-table-sortable">
<thead>
<tr>
<th style="white-space:nowrap;"><label title="A class that was directly hit by this test.">Target Class</label></th>
<th colspan="4"><label title="The percentage of coverage contributed by each single test.">Coverage contributed by</label> testAbaNumberCheck_36696_bad</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<span class="sortValue">com.cardatechnologies.utils.validators.abaroutevalidator.exceptions.AbaRouteValidationException</span>
  <a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/exceptions/AbaRouteValidationException.html?id=24870#AbaRouteValidationException" title="AbaRouteValidationException" name="sl-43">com.cardatechnologies.utils.validators.abaroutevalidator.exceptions.AbaRouteValidationException</a>
</td>
<td>
<span class="sortValue">0.5714286</span>57.1%
</td>
<td class="align-middle" style="width: 100%" colspan="3">
<div>
<div title="57.1% Covered" style="min-width:40px;" class="barNegative contribBarNegative contribBarNegative"><div class="barPositive contribBarPositive contribBarPositive" style="width:57.1%"></div></div></div> </td>
</tr>
<tr>
<td>
<span class="sortValue">com.cardatechnologies.utils.validators.abaroutevalidator.ErrorCodes</span>
  <a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/ErrorCodes.html?id=24870#ErrorCodes" title="ErrorCodes" name="sl-42">com.cardatechnologies.utils.validators.abaroutevalidator.ErrorCodes</a>
</td>
<td>
<span class="sortValue">0.5714286</span>57.1%
</td>
<td class="align-middle" style="width: 100%" colspan="3">
<div>
<div title="57.1% Covered" style="min-width:40px;" class="barNegative contribBarNegative contribBarNegative"><div class="barPositive contribBarPositive contribBarPositive" style="width:57.1%"></div></div></div> </td>
</tr>
<tr>
<td>
<span class="sortValue">com.cardatechnologies.utils.validators.abaroutevalidator.AbaRouteValidator</span>
  <a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/AbaRouteValidator.html?id=24870#AbaRouteValidator" title="AbaRouteValidator" name="sl-47">com.cardatechnologies.utils.validators.abaroutevalidator.AbaRouteValidator</a>
</td>
<td>
<span class="sortValue">0.29411766</span>29.4%
</td>
<td class="align-middle" style="width: 100%" colspan="3">
<div>
<div title="29.4% Covered" style="min-width:40px;" class="barNegative contribBarNegative contribBarNegative"><div class="barPositive contribBarPositive contribBarPositive" style="width:29.4%"></div></div></div> </td>
</tr>
</tbody>
</table>
</div> <!-- class="aui-page-panel-content-clover" -->
<footer id="footer" role="contentinfo">
<section class="footer-body">
<ul>
<li>
Report generated by <a target="_new" href="http://openclover.org">OpenClover</a> v 4.4.1
on Sat Aug 7 2021 12:49:26 MDT using coverage data from Sat Aug 7 2021 12:47:23 MDT.
</li>
</ul>
<ul>
<li>OpenClover is free and open-source software. </li>
</ul>
</section>
</footer> </section> <!-- class="aui-page-panel-content" -->
</div> <!-- class="aui-page-panel-inner" -->
</div> <!-- class="aui-page-panel" -->
</div> <!-- id="page" -->
</body>
</html>
|
apache-2.0
|
ryugoo/TiGeoHash
|
Resources/style/app.style.js
|
898
|
/*jslint devel: true */
/*global Titanium, module */
(function (Ti) {
"use strict";
var style = {
win: {
backgroundColor: "#FFFFFF",
layout: "vertical"
},
btn: {
top: 44,
title: "Get GeoHash!"
},
label: {
top: 22,
color: "#666666",
font: {
fontFamily: "monospace"
}
},
map: {
top: 22,
mapType: Ti.Map.STANDARD_TYPE,
animate: true,
regionFit: true
},
extend: function (target, append) {
var key;
for (key in append) {
if (append.hasOwnProperty(key)) {
target[key] = append[key];
}
}
return target;
}
};
module.exports = style;
}(Titanium));
|
apache-2.0
|
alexradzin/JUnitlet
|
src/test/java/com/junitlet/rule/LoggingRuleTest.java
|
1672
|
package com.junitlet.rule;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Handler;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import com.junitlet.rule.LoggingRule.Phase;
public class LoggingRuleTest {
@Rule
public final LoggingRule<Logger> javaUtilLogger =
new LoggingRuleBuilder<Logger>().
with(Logger.class).
log(Phase.starting, "info").
log(Phase.succeeded, "info").
log(Phase.failed, "severe").
build();
private static List<String> logMessages = new ArrayList<>();
private static Handler javaUtilLoggerHandler = new Handler() {
@Override
public void publish(LogRecord record) {
logMessages.add(record.getMessage());
}
@Override
public void flush() {
}
@Override
public void close() throws SecurityException {
}
};
@BeforeClass
public static void logSetup() {
Logger.getLogger(LoggingRuleTest.class.getName()).addHandler(javaUtilLoggerHandler);
}
@Test
public void test1() {
assertTrue(true);
}
@Test
public void test2() {
assertTrue(true);
}
@AfterClass
public static void logCheck() {
Logger.getLogger(LoggingRuleTest.class.getName()).removeHandler(javaUtilLoggerHandler);
assertTrue(logMessages.get(0).matches(".*test1.*is starting"));
assertTrue(logMessages.get(1).matches(".*test1.*is succeeded"));
assertTrue(logMessages.get(2).matches(".*test2.*is starting"));
assertTrue(logMessages.get(3).matches(".*test2.*is succeeded"));
}
}
|
apache-2.0
|
google/caliper
|
caliper-runner/src/main/java/com/google/caliper/runner/worker/WorkerScoped.java
|
1098
|
/*
* Copyright (C) 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.caliper.runner.worker;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.TYPE;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.inject.Scope;
/** Scope annotation for per-{@link Worker} bindings, which should be unique per worker instance. */
@Target({TYPE, METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Scope
public @interface WorkerScoped {}
|
apache-2.0
|
ejona86/grpc-java
|
interop-testing/src/main/java/io/grpc/testing/integration/XdsTestServer.java
|
11452
|
/*
* Copyright 2020 The gRPC Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.grpc.testing.integration;
import io.grpc.Context;
import io.grpc.Contexts;
import io.grpc.ForwardingServerCall.SimpleForwardingServerCall;
import io.grpc.InsecureServerCredentials;
import io.grpc.Metadata;
import io.grpc.Server;
import io.grpc.ServerCall;
import io.grpc.ServerCallHandler;
import io.grpc.ServerInterceptor;
import io.grpc.ServerInterceptors;
import io.grpc.Status;
import io.grpc.StatusRuntimeException;
import io.grpc.health.v1.HealthCheckResponse.ServingStatus;
import io.grpc.netty.NettyServerBuilder;
import io.grpc.protobuf.services.HealthStatusManager;
import io.grpc.protobuf.services.ProtoReflectionService;
import io.grpc.services.AdminInterface;
import io.grpc.stub.StreamObserver;
import io.grpc.testing.integration.Messages.SimpleRequest;
import io.grpc.testing.integration.Messages.SimpleResponse;
import io.grpc.xds.XdsServerBuilder;
import io.grpc.xds.XdsServerCredentials;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
/** Interop test server that implements the xDS testing service. */
public final class XdsTestServer {
static final Metadata.Key<String> HOSTNAME_KEY =
Metadata.Key.of("hostname", Metadata.ASCII_STRING_MARSHALLER);
private static final Metadata.Key<String> CALL_BEHAVIOR_MD_KEY =
Metadata.Key.of("rpc-behavior", Metadata.ASCII_STRING_MARSHALLER);
private static final Context.Key<String> CALL_BEHAVIOR_KEY =
Context.key("rpc-behavior");
private static final String CALL_BEHAVIOR_KEEP_OPEN_VALUE = "keep-open";
private static final String CALL_BEHAVIOR_SLEEP_VALUE = "sleep-";
private static Logger logger = Logger.getLogger(XdsTestServer.class.getName());
private int port = 8080;
private int maintenancePort = 8080;
private boolean secureMode = false;
private String serverId = "java_server";
private HealthStatusManager health;
private Server server;
private Server maintenanceServer;
private String host;
/**
* The main application allowing this client to be launched from the command line.
*/
public static void main(String[] args) throws Exception {
final XdsTestServer server = new XdsTestServer();
server.parseArgs(args);
Runtime.getRuntime()
.addShutdownHook(
new Thread() {
@Override
@SuppressWarnings("CatchAndPrintStackTrace")
public void run() {
try {
System.out.println("Shutting down");
server.stop();
} catch (Exception e) {
e.printStackTrace();
}
}
});
server.start();
System.out.println("Server started on port " + server.port);
server.blockUntilShutdown();
}
private void parseArgs(String[] args) {
boolean usage = false;
for (String arg : args) {
if (!arg.startsWith("--")) {
System.err.println("All arguments must start with '--': " + arg);
usage = true;
break;
}
String[] parts = arg.substring(2).split("=", 2);
String key = parts[0];
if ("help".equals(key)) {
usage = true;
break;
}
if (parts.length != 2) {
System.err.println("All arguments must be of the form --arg=value");
usage = true;
break;
}
String value = parts[1];
if ("port".equals(key)) {
port = Integer.valueOf(value);
} else if ("maintenance_port".equals(key)) {
maintenancePort = Integer.valueOf(value);
} else if ("secure_mode".equals(key)) {
secureMode = Boolean.parseBoolean(value);
} else if ("server_id".equals(key)) {
serverId = value;
} else {
System.err.println("Unknown argument: " + key);
usage = true;
break;
}
}
if (secureMode && (port == maintenancePort)) {
System.err.println(
"port and maintenance_port should be different for secure mode: port="
+ port
+ ", maintenance_port="
+ maintenancePort);
usage = true;
}
if (usage) {
XdsTestServer s = new XdsTestServer();
System.err.println(
"Usage: [ARGS...]"
+ "\n"
+ "\n --port=INT listening port for test server."
+ "\n Default: "
+ s.port
+ "\n --maintenance_port=INT listening port for other servers."
+ "\n Default: "
+ s.maintenancePort
+ "\n --secure_mode=BOOLEAN Use true to enable XdsCredentials."
+ " port and maintenance_port should be different for secure mode."
+ "\n Default: "
+ s.secureMode
+ "\n --server_id=STRING server ID for response."
+ "\n Default: "
+ s.serverId);
System.exit(1);
}
}
private void start() throws Exception {
try {
host = InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException e) {
logger.log(Level.SEVERE, "Failed to get host", e);
throw new RuntimeException(e);
}
health = new HealthStatusManager();
if (secureMode) {
server =
XdsServerBuilder.forPort(
port, XdsServerCredentials.create(InsecureServerCredentials.create()))
.addService(
ServerInterceptors.intercept(
new TestServiceImpl(serverId, host), new TestInfoInterceptor(host)))
.build()
.start();
maintenanceServer =
NettyServerBuilder.forPort(maintenancePort)
.addService(new XdsUpdateHealthServiceImpl(health))
.addService(health.getHealthService())
.addService(ProtoReflectionService.newInstance())
.addServices(AdminInterface.getStandardServices())
.build()
.start();
} else {
server =
NettyServerBuilder.forPort(port)
.addService(
ServerInterceptors.intercept(
new TestServiceImpl(serverId, host), new TestInfoInterceptor(host)))
.addService(new XdsUpdateHealthServiceImpl(health))
.addService(health.getHealthService())
.addService(ProtoReflectionService.newInstance())
.addServices(AdminInterface.getStandardServices())
.build()
.start();
maintenanceServer = null;
}
health.setStatus("", ServingStatus.SERVING);
}
private void stop() throws Exception {
server.shutdownNow();
if (maintenanceServer != null) {
maintenanceServer.shutdownNow();
}
if (!server.awaitTermination(5, TimeUnit.SECONDS)) {
System.err.println("Timed out waiting for server shutdown");
}
if (maintenanceServer != null && !maintenanceServer.awaitTermination(5, TimeUnit.SECONDS)) {
System.err.println("Timed out waiting for maintenanceServer shutdown");
}
}
private void blockUntilShutdown() throws InterruptedException {
if (server != null) {
server.awaitTermination();
}
if (maintenanceServer != null) {
maintenanceServer.awaitTermination();
}
}
private static class TestServiceImpl extends TestServiceGrpc.TestServiceImplBase {
private final String serverId;
private final String host;
private TestServiceImpl(String serverId, String host) {
this.serverId = serverId;
this.host = host;
}
@Override
public void emptyCall(
EmptyProtos.Empty req, StreamObserver<EmptyProtos.Empty> responseObserver) {
responseObserver.onNext(EmptyProtos.Empty.getDefaultInstance());
if (!CALL_BEHAVIOR_KEEP_OPEN_VALUE.equals(CALL_BEHAVIOR_KEY.get())) {
responseObserver.onCompleted();
}
}
@Override
public void unaryCall(SimpleRequest req, StreamObserver<SimpleResponse> responseObserver) {
responseObserver.onNext(
SimpleResponse.newBuilder().setServerId(serverId).setHostname(host).build());
if (!CALL_BEHAVIOR_KEEP_OPEN_VALUE.equals(CALL_BEHAVIOR_KEY.get())) {
responseObserver.onCompleted();
}
}
}
private static class XdsUpdateHealthServiceImpl
extends XdsUpdateHealthServiceGrpc.XdsUpdateHealthServiceImplBase {
private HealthStatusManager health;
private XdsUpdateHealthServiceImpl(HealthStatusManager health) {
this.health = health;
}
@Override
public void setServing(
EmptyProtos.Empty req, StreamObserver<EmptyProtos.Empty> responseObserver) {
health.setStatus("", ServingStatus.SERVING);
responseObserver.onNext(EmptyProtos.Empty.getDefaultInstance());
responseObserver.onCompleted();
}
@Override
public void setNotServing(
EmptyProtos.Empty req, StreamObserver<EmptyProtos.Empty> responseObserver) {
health.setStatus("", ServingStatus.NOT_SERVING);
responseObserver.onNext(EmptyProtos.Empty.getDefaultInstance());
responseObserver.onCompleted();
}
}
private static class TestInfoInterceptor implements ServerInterceptor {
private final String host;
private TestInfoInterceptor(String host) {
this.host = host;
}
@Override
public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(
ServerCall<ReqT, RespT> call,
final Metadata requestHeaders,
ServerCallHandler<ReqT, RespT> next) {
String callBehavior = requestHeaders.get(CALL_BEHAVIOR_MD_KEY);
Context newContext = Context.current().withValue(CALL_BEHAVIOR_KEY, callBehavior);
if (callBehavior != null && callBehavior.startsWith(CALL_BEHAVIOR_SLEEP_VALUE)) {
try {
int timeout = Integer.parseInt(
callBehavior.substring(CALL_BEHAVIOR_SLEEP_VALUE.length()));
Thread.sleep(timeout * 1000);
} catch (NumberFormatException e) {
throw new StatusRuntimeException(
Status.INVALID_ARGUMENT.withDescription(
String.format("Invalid format for rpc-behavior header (%s)", callBehavior)));
} catch (InterruptedException e) {
throw new StatusRuntimeException(
Status.ABORTED.withDescription("execution of server interrupted"));
}
}
ServerCall<ReqT, RespT> newCall = new SimpleForwardingServerCall<ReqT, RespT>(call) {
@Override
public void sendHeaders(Metadata responseHeaders) {
responseHeaders.put(HOSTNAME_KEY, host);
super.sendHeaders(responseHeaders);
}
};
return Contexts.interceptCall(newContext, newCall, requestHeaders, next);
}
}
}
|
apache-2.0
|
egorlitvinenko/JavaLearning
|
src/org/egorlitvinenko/certification/oca/book1/assessment/Q3/HasTail.java
|
172
|
package org.egorlitvinenko.certification.oca.book1.assessment.Q3;
/**
* Created by Egor Litvinenko on 19.01.17.
*/
public interface HasTail {
int getTailLength();
}
|
apache-2.0
|
EUDAT-B2SAFE/PYHANDLE
|
pyhandle/utilhandle.py
|
5268
|
'''
This module provides some handle-related functions
that are needed across various modules of the
pyhandle library.
'''
from __future__ import absolute_import
import base64
from future.standard_library import install_aliases
install_aliases()
from urllib.parse import quote
from . import handleexceptions
from . import util
def remove_index_from_handle(handle_with_index):
'''
Returns index and handle separately, in a tuple.
:handle_with_index: The handle string with an index (e.g.
500:prefix/suffix)
:return: index and handle as a tuple, where index is integer.
'''
split = handle_with_index.split(':')
if len(split) == 2:
split[0] = int(split[0])
return split
elif len(split) == 1:
return (None, handle_with_index)
elif len(split) > 2:
raise handleexceptions.HandleSyntaxError(
msg='Too many colons',
handle=handle_with_index,
expected_syntax='index:prefix/suffix')
def check_handle_syntax(string):
'''
Checks the syntax of a handle without an index (are prefix
and suffix there, are there too many slashes?).
:string: The handle without index, as string prefix/suffix.
:raise: :exc:`~pyhandle.handleexceptions.handleexceptions.HandleSyntaxError`
:return: True. If it's not ok, exceptions are raised.
'''
expected = 'prefix/suffix'
try:
arr = string.split('/')
except AttributeError:
raise handleexceptions.HandleSyntaxError(msg='The provided handle is None', expected_syntax=expected)
if len(arr) < 2:
msg = 'No slash'
raise handleexceptions.HandleSyntaxError(msg=msg, handle=string, expected_syntax=expected)
if len(arr[0]) == 0:
msg = 'Empty prefix'
raise handleexceptions.HandleSyntaxError(msg=msg, handle=string, expected_syntax=expected)
if len(arr[1]) == 0:
msg = 'Empty suffix'
raise handleexceptions.HandleSyntaxError(msg=msg, handle=string, expected_syntax=expected)
if ':' in string:
check_handle_syntax_with_index(string, base_already_checked=True)
return True
def check_handle_syntax_with_index(string, base_already_checked=False):
'''
Checks the syntax of a handle with an index (is index there, is it an
integer?), and of the handle itself.
:string: The handle with index, as string index:prefix/suffix.
:raise: :exc:`~pyhandle.handleexceptions.handleexceptions.HandleSyntaxError`
:return: True. If it's not ok, exceptions are raised.
'''
expected = 'index:prefix/suffix'
try:
arr = string.split(':')
except AttributeError:
raise handleexceptions.HandleSyntaxError(msg='The provided handle is None.', expected_syntax=expected)
if len(arr) > 2:
msg = 'Too many colons'
raise handleexceptions.HandleSyntaxError(msg=msg, handle=string, expected_syntax=expected)
elif len(arr) < 2:
msg = 'No colon'
raise handleexceptions.HandleSyntaxError(msg=msg, handle=string, expected_syntax=expected)
try:
int(arr[0])
except ValueError:
msg = 'Index is not an integer'
raise handleexceptions.HandleSyntaxError(msg=msg, handle=string, expected_syntax=expected)
if not base_already_checked:
check_handle_syntax(string)
return True
def create_authentication_string(username, password):
'''
Creates an authentication string from the username and password.
:username: Username.
:password: Password.
:return: The encoded string.
'''
username_utf8 = username.encode('utf-8')
userpw_utf8 = password.encode('utf-8').decode('utf-8')
username_perc = quote(username_utf8)
authinfostring = username_perc + ':' + userpw_utf8
authinfostring_base64 = base64.b64encode(authinfostring.encode('utf-8')).decode('utf-8')
return authinfostring_base64
def make_request_log_message(**args):
'''
Creates a string containing all relevant information
about a request made to the Handle System, for
logging purposes.
:handle: The handle that the request is about.
:url: The url the request is sent to.
:headers: The headers sent along with the request.
:verify: Boolean parameter passed to the requests
module (https verification).
:resp: The request's response.
:op: The library operation during which the request
was sent.
:payload: Optional. The payload sent with the request.
:return: A formatted string.
'''
mandatory_args = ['op', 'handle', 'url', 'headers', 'verify', 'resp']
optional_args = ['payload']
util.check_presence_of_mandatory_args(args, mandatory_args)
util.add_missing_optional_args_with_value_none(args, optional_args)
space = '\n '
message = ''
message += '\n'+args['op']+' '+args['handle']
message += space+'URL: '+args['url']
message += space+'HEADERS: '+str(args['headers'])
message += space+'VERIFY: '+str(args['verify'])
if 'payload' in args.keys():
message += space+'PAYLOAD:'+space+str(args['payload'])
message += space+'RESPONSECODE: '+str(args['resp'].status_code)
message += space+'RESPONSE:'+space+str(args['resp'].content)
return message
|
apache-2.0
|
aws/aws-sdk-java
|
aws-java-sdk-cloudformation/src/main/java/com/amazonaws/services/cloudformation/model/GetTemplateSummaryResult.java
|
36945
|
/*
* 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.cloudformation.model;
import java.io.Serializable;
import javax.annotation.Generated;
/**
* <p>
* The output for the <a>GetTemplateSummary</a> action.
* </p>
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/cloudformation-2010-05-15/GetTemplateSummary" target="_top">AWS
* API Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class GetTemplateSummaryResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {
/**
* <p>
* A list of parameter declarations that describe various properties for each parameter.
* </p>
*/
private com.amazonaws.internal.SdkInternalList<ParameterDeclaration> parameters;
/**
* <p>
* The value that's defined in the <code>Description</code> property of the template.
* </p>
*/
private String description;
/**
* <p>
* The capabilities found within the template. If your template contains IAM resources, you must specify the
* <code>CAPABILITY_IAM</code> or <code>CAPABILITY_NAMED_IAM</code> value for this parameter when you use the
* <a>CreateStack</a> or <a>UpdateStack</a> actions with your template; otherwise, those actions return an
* <code>InsufficientCapabilities</code> error.
* </p>
* <p>
* For more information, see <a
* href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-iam-template.html#capabilities"
* >Acknowledging IAM Resources in CloudFormation Templates</a>.
* </p>
*/
private com.amazonaws.internal.SdkInternalList<String> capabilities;
/**
* <p>
* The list of resources that generated the values in the <code>Capabilities</code> response element.
* </p>
*/
private String capabilitiesReason;
/**
* <p>
* A list of all the template resource types that are defined in the template, such as
* <code>AWS::EC2::Instance</code>, <code>AWS::Dynamo::Table</code>, and <code>Custom::MyCustomInstance</code>.
* </p>
*/
private com.amazonaws.internal.SdkInternalList<String> resourceTypes;
/**
* <p>
* The Amazon Web Services template format version, which identifies the capabilities of the template.
* </p>
*/
private String version;
/**
* <p>
* The value that's defined for the <code>Metadata</code> property of the template.
* </p>
*/
private String metadata;
/**
* <p>
* A list of the transforms that are declared in the template.
* </p>
*/
private com.amazonaws.internal.SdkInternalList<String> declaredTransforms;
/**
* <p>
* A list of resource identifier summaries that describe the target resources of an import operation and the
* properties you can provide during the import to identify the target resources. For example,
* <code>BucketName</code> is a possible identifier property for an <code>AWS::S3::Bucket</code> resource.
* </p>
*/
private com.amazonaws.internal.SdkInternalList<ResourceIdentifierSummary> resourceIdentifierSummaries;
/**
* <p>
* A list of parameter declarations that describe various properties for each parameter.
* </p>
*
* @return A list of parameter declarations that describe various properties for each parameter.
*/
public java.util.List<ParameterDeclaration> getParameters() {
if (parameters == null) {
parameters = new com.amazonaws.internal.SdkInternalList<ParameterDeclaration>();
}
return parameters;
}
/**
* <p>
* A list of parameter declarations that describe various properties for each parameter.
* </p>
*
* @param parameters
* A list of parameter declarations that describe various properties for each parameter.
*/
public void setParameters(java.util.Collection<ParameterDeclaration> parameters) {
if (parameters == null) {
this.parameters = null;
return;
}
this.parameters = new com.amazonaws.internal.SdkInternalList<ParameterDeclaration>(parameters);
}
/**
* <p>
* A list of parameter declarations that describe various properties for each parameter.
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if any). Use
* {@link #setParameters(java.util.Collection)} or {@link #withParameters(java.util.Collection)} if you want to
* override the existing values.
* </p>
*
* @param parameters
* A list of parameter declarations that describe various properties for each parameter.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public GetTemplateSummaryResult withParameters(ParameterDeclaration... parameters) {
if (this.parameters == null) {
setParameters(new com.amazonaws.internal.SdkInternalList<ParameterDeclaration>(parameters.length));
}
for (ParameterDeclaration ele : parameters) {
this.parameters.add(ele);
}
return this;
}
/**
* <p>
* A list of parameter declarations that describe various properties for each parameter.
* </p>
*
* @param parameters
* A list of parameter declarations that describe various properties for each parameter.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public GetTemplateSummaryResult withParameters(java.util.Collection<ParameterDeclaration> parameters) {
setParameters(parameters);
return this;
}
/**
* <p>
* The value that's defined in the <code>Description</code> property of the template.
* </p>
*
* @param description
* The value that's defined in the <code>Description</code> property of the template.
*/
public void setDescription(String description) {
this.description = description;
}
/**
* <p>
* The value that's defined in the <code>Description</code> property of the template.
* </p>
*
* @return The value that's defined in the <code>Description</code> property of the template.
*/
public String getDescription() {
return this.description;
}
/**
* <p>
* The value that's defined in the <code>Description</code> property of the template.
* </p>
*
* @param description
* The value that's defined in the <code>Description</code> property of the template.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public GetTemplateSummaryResult withDescription(String description) {
setDescription(description);
return this;
}
/**
* <p>
* The capabilities found within the template. If your template contains IAM resources, you must specify the
* <code>CAPABILITY_IAM</code> or <code>CAPABILITY_NAMED_IAM</code> value for this parameter when you use the
* <a>CreateStack</a> or <a>UpdateStack</a> actions with your template; otherwise, those actions return an
* <code>InsufficientCapabilities</code> error.
* </p>
* <p>
* For more information, see <a
* href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-iam-template.html#capabilities"
* >Acknowledging IAM Resources in CloudFormation Templates</a>.
* </p>
*
* @return The capabilities found within the template. If your template contains IAM resources, you must specify the
* <code>CAPABILITY_IAM</code> or <code>CAPABILITY_NAMED_IAM</code> value for this parameter when you use
* the <a>CreateStack</a> or <a>UpdateStack</a> actions with your template; otherwise, those actions return
* an <code>InsufficientCapabilities</code> error.</p>
* <p>
* For more information, see <a href=
* "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-iam-template.html#capabilities"
* >Acknowledging IAM Resources in CloudFormation Templates</a>.
* @see Capability
*/
public java.util.List<String> getCapabilities() {
if (capabilities == null) {
capabilities = new com.amazonaws.internal.SdkInternalList<String>();
}
return capabilities;
}
/**
* <p>
* The capabilities found within the template. If your template contains IAM resources, you must specify the
* <code>CAPABILITY_IAM</code> or <code>CAPABILITY_NAMED_IAM</code> value for this parameter when you use the
* <a>CreateStack</a> or <a>UpdateStack</a> actions with your template; otherwise, those actions return an
* <code>InsufficientCapabilities</code> error.
* </p>
* <p>
* For more information, see <a
* href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-iam-template.html#capabilities"
* >Acknowledging IAM Resources in CloudFormation Templates</a>.
* </p>
*
* @param capabilities
* The capabilities found within the template. If your template contains IAM resources, you must specify the
* <code>CAPABILITY_IAM</code> or <code>CAPABILITY_NAMED_IAM</code> value for this parameter when you use the
* <a>CreateStack</a> or <a>UpdateStack</a> actions with your template; otherwise, those actions return an
* <code>InsufficientCapabilities</code> error.</p>
* <p>
* For more information, see <a href=
* "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-iam-template.html#capabilities"
* >Acknowledging IAM Resources in CloudFormation Templates</a>.
* @see Capability
*/
public void setCapabilities(java.util.Collection<String> capabilities) {
if (capabilities == null) {
this.capabilities = null;
return;
}
this.capabilities = new com.amazonaws.internal.SdkInternalList<String>(capabilities);
}
/**
* <p>
* The capabilities found within the template. If your template contains IAM resources, you must specify the
* <code>CAPABILITY_IAM</code> or <code>CAPABILITY_NAMED_IAM</code> value for this parameter when you use the
* <a>CreateStack</a> or <a>UpdateStack</a> actions with your template; otherwise, those actions return an
* <code>InsufficientCapabilities</code> error.
* </p>
* <p>
* For more information, see <a
* href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-iam-template.html#capabilities"
* >Acknowledging IAM Resources in CloudFormation Templates</a>.
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if any). Use
* {@link #setCapabilities(java.util.Collection)} or {@link #withCapabilities(java.util.Collection)} if you want to
* override the existing values.
* </p>
*
* @param capabilities
* The capabilities found within the template. If your template contains IAM resources, you must specify the
* <code>CAPABILITY_IAM</code> or <code>CAPABILITY_NAMED_IAM</code> value for this parameter when you use the
* <a>CreateStack</a> or <a>UpdateStack</a> actions with your template; otherwise, those actions return an
* <code>InsufficientCapabilities</code> error.</p>
* <p>
* For more information, see <a href=
* "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-iam-template.html#capabilities"
* >Acknowledging IAM Resources in CloudFormation Templates</a>.
* @return Returns a reference to this object so that method calls can be chained together.
* @see Capability
*/
public GetTemplateSummaryResult withCapabilities(String... capabilities) {
if (this.capabilities == null) {
setCapabilities(new com.amazonaws.internal.SdkInternalList<String>(capabilities.length));
}
for (String ele : capabilities) {
this.capabilities.add(ele);
}
return this;
}
/**
* <p>
* The capabilities found within the template. If your template contains IAM resources, you must specify the
* <code>CAPABILITY_IAM</code> or <code>CAPABILITY_NAMED_IAM</code> value for this parameter when you use the
* <a>CreateStack</a> or <a>UpdateStack</a> actions with your template; otherwise, those actions return an
* <code>InsufficientCapabilities</code> error.
* </p>
* <p>
* For more information, see <a
* href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-iam-template.html#capabilities"
* >Acknowledging IAM Resources in CloudFormation Templates</a>.
* </p>
*
* @param capabilities
* The capabilities found within the template. If your template contains IAM resources, you must specify the
* <code>CAPABILITY_IAM</code> or <code>CAPABILITY_NAMED_IAM</code> value for this parameter when you use the
* <a>CreateStack</a> or <a>UpdateStack</a> actions with your template; otherwise, those actions return an
* <code>InsufficientCapabilities</code> error.</p>
* <p>
* For more information, see <a href=
* "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-iam-template.html#capabilities"
* >Acknowledging IAM Resources in CloudFormation Templates</a>.
* @return Returns a reference to this object so that method calls can be chained together.
* @see Capability
*/
public GetTemplateSummaryResult withCapabilities(java.util.Collection<String> capabilities) {
setCapabilities(capabilities);
return this;
}
/**
* <p>
* The capabilities found within the template. If your template contains IAM resources, you must specify the
* <code>CAPABILITY_IAM</code> or <code>CAPABILITY_NAMED_IAM</code> value for this parameter when you use the
* <a>CreateStack</a> or <a>UpdateStack</a> actions with your template; otherwise, those actions return an
* <code>InsufficientCapabilities</code> error.
* </p>
* <p>
* For more information, see <a
* href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-iam-template.html#capabilities"
* >Acknowledging IAM Resources in CloudFormation Templates</a>.
* </p>
*
* @param capabilities
* The capabilities found within the template. If your template contains IAM resources, you must specify the
* <code>CAPABILITY_IAM</code> or <code>CAPABILITY_NAMED_IAM</code> value for this parameter when you use the
* <a>CreateStack</a> or <a>UpdateStack</a> actions with your template; otherwise, those actions return an
* <code>InsufficientCapabilities</code> error.</p>
* <p>
* For more information, see <a href=
* "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-iam-template.html#capabilities"
* >Acknowledging IAM Resources in CloudFormation Templates</a>.
* @return Returns a reference to this object so that method calls can be chained together.
* @see Capability
*/
public GetTemplateSummaryResult withCapabilities(Capability... capabilities) {
com.amazonaws.internal.SdkInternalList<String> capabilitiesCopy = new com.amazonaws.internal.SdkInternalList<String>(capabilities.length);
for (Capability value : capabilities) {
capabilitiesCopy.add(value.toString());
}
if (getCapabilities() == null) {
setCapabilities(capabilitiesCopy);
} else {
getCapabilities().addAll(capabilitiesCopy);
}
return this;
}
/**
* <p>
* The list of resources that generated the values in the <code>Capabilities</code> response element.
* </p>
*
* @param capabilitiesReason
* The list of resources that generated the values in the <code>Capabilities</code> response element.
*/
public void setCapabilitiesReason(String capabilitiesReason) {
this.capabilitiesReason = capabilitiesReason;
}
/**
* <p>
* The list of resources that generated the values in the <code>Capabilities</code> response element.
* </p>
*
* @return The list of resources that generated the values in the <code>Capabilities</code> response element.
*/
public String getCapabilitiesReason() {
return this.capabilitiesReason;
}
/**
* <p>
* The list of resources that generated the values in the <code>Capabilities</code> response element.
* </p>
*
* @param capabilitiesReason
* The list of resources that generated the values in the <code>Capabilities</code> response element.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public GetTemplateSummaryResult withCapabilitiesReason(String capabilitiesReason) {
setCapabilitiesReason(capabilitiesReason);
return this;
}
/**
* <p>
* A list of all the template resource types that are defined in the template, such as
* <code>AWS::EC2::Instance</code>, <code>AWS::Dynamo::Table</code>, and <code>Custom::MyCustomInstance</code>.
* </p>
*
* @return A list of all the template resource types that are defined in the template, such as
* <code>AWS::EC2::Instance</code>, <code>AWS::Dynamo::Table</code>, and
* <code>Custom::MyCustomInstance</code>.
*/
public java.util.List<String> getResourceTypes() {
if (resourceTypes == null) {
resourceTypes = new com.amazonaws.internal.SdkInternalList<String>();
}
return resourceTypes;
}
/**
* <p>
* A list of all the template resource types that are defined in the template, such as
* <code>AWS::EC2::Instance</code>, <code>AWS::Dynamo::Table</code>, and <code>Custom::MyCustomInstance</code>.
* </p>
*
* @param resourceTypes
* A list of all the template resource types that are defined in the template, such as
* <code>AWS::EC2::Instance</code>, <code>AWS::Dynamo::Table</code>, and
* <code>Custom::MyCustomInstance</code>.
*/
public void setResourceTypes(java.util.Collection<String> resourceTypes) {
if (resourceTypes == null) {
this.resourceTypes = null;
return;
}
this.resourceTypes = new com.amazonaws.internal.SdkInternalList<String>(resourceTypes);
}
/**
* <p>
* A list of all the template resource types that are defined in the template, such as
* <code>AWS::EC2::Instance</code>, <code>AWS::Dynamo::Table</code>, and <code>Custom::MyCustomInstance</code>.
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if any). Use
* {@link #setResourceTypes(java.util.Collection)} or {@link #withResourceTypes(java.util.Collection)} if you want
* to override the existing values.
* </p>
*
* @param resourceTypes
* A list of all the template resource types that are defined in the template, such as
* <code>AWS::EC2::Instance</code>, <code>AWS::Dynamo::Table</code>, and
* <code>Custom::MyCustomInstance</code>.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public GetTemplateSummaryResult withResourceTypes(String... resourceTypes) {
if (this.resourceTypes == null) {
setResourceTypes(new com.amazonaws.internal.SdkInternalList<String>(resourceTypes.length));
}
for (String ele : resourceTypes) {
this.resourceTypes.add(ele);
}
return this;
}
/**
* <p>
* A list of all the template resource types that are defined in the template, such as
* <code>AWS::EC2::Instance</code>, <code>AWS::Dynamo::Table</code>, and <code>Custom::MyCustomInstance</code>.
* </p>
*
* @param resourceTypes
* A list of all the template resource types that are defined in the template, such as
* <code>AWS::EC2::Instance</code>, <code>AWS::Dynamo::Table</code>, and
* <code>Custom::MyCustomInstance</code>.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public GetTemplateSummaryResult withResourceTypes(java.util.Collection<String> resourceTypes) {
setResourceTypes(resourceTypes);
return this;
}
/**
* <p>
* The Amazon Web Services template format version, which identifies the capabilities of the template.
* </p>
*
* @param version
* The Amazon Web Services template format version, which identifies the capabilities of the template.
*/
public void setVersion(String version) {
this.version = version;
}
/**
* <p>
* The Amazon Web Services template format version, which identifies the capabilities of the template.
* </p>
*
* @return The Amazon Web Services template format version, which identifies the capabilities of the template.
*/
public String getVersion() {
return this.version;
}
/**
* <p>
* The Amazon Web Services template format version, which identifies the capabilities of the template.
* </p>
*
* @param version
* The Amazon Web Services template format version, which identifies the capabilities of the template.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public GetTemplateSummaryResult withVersion(String version) {
setVersion(version);
return this;
}
/**
* <p>
* The value that's defined for the <code>Metadata</code> property of the template.
* </p>
*
* @param metadata
* The value that's defined for the <code>Metadata</code> property of the template.
*/
public void setMetadata(String metadata) {
this.metadata = metadata;
}
/**
* <p>
* The value that's defined for the <code>Metadata</code> property of the template.
* </p>
*
* @return The value that's defined for the <code>Metadata</code> property of the template.
*/
public String getMetadata() {
return this.metadata;
}
/**
* <p>
* The value that's defined for the <code>Metadata</code> property of the template.
* </p>
*
* @param metadata
* The value that's defined for the <code>Metadata</code> property of the template.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public GetTemplateSummaryResult withMetadata(String metadata) {
setMetadata(metadata);
return this;
}
/**
* <p>
* A list of the transforms that are declared in the template.
* </p>
*
* @return A list of the transforms that are declared in the template.
*/
public java.util.List<String> getDeclaredTransforms() {
if (declaredTransforms == null) {
declaredTransforms = new com.amazonaws.internal.SdkInternalList<String>();
}
return declaredTransforms;
}
/**
* <p>
* A list of the transforms that are declared in the template.
* </p>
*
* @param declaredTransforms
* A list of the transforms that are declared in the template.
*/
public void setDeclaredTransforms(java.util.Collection<String> declaredTransforms) {
if (declaredTransforms == null) {
this.declaredTransforms = null;
return;
}
this.declaredTransforms = new com.amazonaws.internal.SdkInternalList<String>(declaredTransforms);
}
/**
* <p>
* A list of the transforms that are declared in the template.
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if any). Use
* {@link #setDeclaredTransforms(java.util.Collection)} or {@link #withDeclaredTransforms(java.util.Collection)} if
* you want to override the existing values.
* </p>
*
* @param declaredTransforms
* A list of the transforms that are declared in the template.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public GetTemplateSummaryResult withDeclaredTransforms(String... declaredTransforms) {
if (this.declaredTransforms == null) {
setDeclaredTransforms(new com.amazonaws.internal.SdkInternalList<String>(declaredTransforms.length));
}
for (String ele : declaredTransforms) {
this.declaredTransforms.add(ele);
}
return this;
}
/**
* <p>
* A list of the transforms that are declared in the template.
* </p>
*
* @param declaredTransforms
* A list of the transforms that are declared in the template.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public GetTemplateSummaryResult withDeclaredTransforms(java.util.Collection<String> declaredTransforms) {
setDeclaredTransforms(declaredTransforms);
return this;
}
/**
* <p>
* A list of resource identifier summaries that describe the target resources of an import operation and the
* properties you can provide during the import to identify the target resources. For example,
* <code>BucketName</code> is a possible identifier property for an <code>AWS::S3::Bucket</code> resource.
* </p>
*
* @return A list of resource identifier summaries that describe the target resources of an import operation and the
* properties you can provide during the import to identify the target resources. For example,
* <code>BucketName</code> is a possible identifier property for an <code>AWS::S3::Bucket</code> resource.
*/
public java.util.List<ResourceIdentifierSummary> getResourceIdentifierSummaries() {
if (resourceIdentifierSummaries == null) {
resourceIdentifierSummaries = new com.amazonaws.internal.SdkInternalList<ResourceIdentifierSummary>();
}
return resourceIdentifierSummaries;
}
/**
* <p>
* A list of resource identifier summaries that describe the target resources of an import operation and the
* properties you can provide during the import to identify the target resources. For example,
* <code>BucketName</code> is a possible identifier property for an <code>AWS::S3::Bucket</code> resource.
* </p>
*
* @param resourceIdentifierSummaries
* A list of resource identifier summaries that describe the target resources of an import operation and the
* properties you can provide during the import to identify the target resources. For example,
* <code>BucketName</code> is a possible identifier property for an <code>AWS::S3::Bucket</code> resource.
*/
public void setResourceIdentifierSummaries(java.util.Collection<ResourceIdentifierSummary> resourceIdentifierSummaries) {
if (resourceIdentifierSummaries == null) {
this.resourceIdentifierSummaries = null;
return;
}
this.resourceIdentifierSummaries = new com.amazonaws.internal.SdkInternalList<ResourceIdentifierSummary>(resourceIdentifierSummaries);
}
/**
* <p>
* A list of resource identifier summaries that describe the target resources of an import operation and the
* properties you can provide during the import to identify the target resources. For example,
* <code>BucketName</code> is a possible identifier property for an <code>AWS::S3::Bucket</code> resource.
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if any). Use
* {@link #setResourceIdentifierSummaries(java.util.Collection)} or
* {@link #withResourceIdentifierSummaries(java.util.Collection)} if you want to override the existing values.
* </p>
*
* @param resourceIdentifierSummaries
* A list of resource identifier summaries that describe the target resources of an import operation and the
* properties you can provide during the import to identify the target resources. For example,
* <code>BucketName</code> is a possible identifier property for an <code>AWS::S3::Bucket</code> resource.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public GetTemplateSummaryResult withResourceIdentifierSummaries(ResourceIdentifierSummary... resourceIdentifierSummaries) {
if (this.resourceIdentifierSummaries == null) {
setResourceIdentifierSummaries(new com.amazonaws.internal.SdkInternalList<ResourceIdentifierSummary>(resourceIdentifierSummaries.length));
}
for (ResourceIdentifierSummary ele : resourceIdentifierSummaries) {
this.resourceIdentifierSummaries.add(ele);
}
return this;
}
/**
* <p>
* A list of resource identifier summaries that describe the target resources of an import operation and the
* properties you can provide during the import to identify the target resources. For example,
* <code>BucketName</code> is a possible identifier property for an <code>AWS::S3::Bucket</code> resource.
* </p>
*
* @param resourceIdentifierSummaries
* A list of resource identifier summaries that describe the target resources of an import operation and the
* properties you can provide during the import to identify the target resources. For example,
* <code>BucketName</code> is a possible identifier property for an <code>AWS::S3::Bucket</code> resource.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public GetTemplateSummaryResult withResourceIdentifierSummaries(java.util.Collection<ResourceIdentifierSummary> resourceIdentifierSummaries) {
setResourceIdentifierSummaries(resourceIdentifierSummaries);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getParameters() != null)
sb.append("Parameters: ").append(getParameters()).append(",");
if (getDescription() != null)
sb.append("Description: ").append(getDescription()).append(",");
if (getCapabilities() != null)
sb.append("Capabilities: ").append(getCapabilities()).append(",");
if (getCapabilitiesReason() != null)
sb.append("CapabilitiesReason: ").append(getCapabilitiesReason()).append(",");
if (getResourceTypes() != null)
sb.append("ResourceTypes: ").append(getResourceTypes()).append(",");
if (getVersion() != null)
sb.append("Version: ").append(getVersion()).append(",");
if (getMetadata() != null)
sb.append("Metadata: ").append(getMetadata()).append(",");
if (getDeclaredTransforms() != null)
sb.append("DeclaredTransforms: ").append(getDeclaredTransforms()).append(",");
if (getResourceIdentifierSummaries() != null)
sb.append("ResourceIdentifierSummaries: ").append(getResourceIdentifierSummaries());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof GetTemplateSummaryResult == false)
return false;
GetTemplateSummaryResult other = (GetTemplateSummaryResult) obj;
if (other.getParameters() == null ^ this.getParameters() == null)
return false;
if (other.getParameters() != null && other.getParameters().equals(this.getParameters()) == false)
return false;
if (other.getDescription() == null ^ this.getDescription() == null)
return false;
if (other.getDescription() != null && other.getDescription().equals(this.getDescription()) == false)
return false;
if (other.getCapabilities() == null ^ this.getCapabilities() == null)
return false;
if (other.getCapabilities() != null && other.getCapabilities().equals(this.getCapabilities()) == false)
return false;
if (other.getCapabilitiesReason() == null ^ this.getCapabilitiesReason() == null)
return false;
if (other.getCapabilitiesReason() != null && other.getCapabilitiesReason().equals(this.getCapabilitiesReason()) == false)
return false;
if (other.getResourceTypes() == null ^ this.getResourceTypes() == null)
return false;
if (other.getResourceTypes() != null && other.getResourceTypes().equals(this.getResourceTypes()) == false)
return false;
if (other.getVersion() == null ^ this.getVersion() == null)
return false;
if (other.getVersion() != null && other.getVersion().equals(this.getVersion()) == false)
return false;
if (other.getMetadata() == null ^ this.getMetadata() == null)
return false;
if (other.getMetadata() != null && other.getMetadata().equals(this.getMetadata()) == false)
return false;
if (other.getDeclaredTransforms() == null ^ this.getDeclaredTransforms() == null)
return false;
if (other.getDeclaredTransforms() != null && other.getDeclaredTransforms().equals(this.getDeclaredTransforms()) == false)
return false;
if (other.getResourceIdentifierSummaries() == null ^ this.getResourceIdentifierSummaries() == null)
return false;
if (other.getResourceIdentifierSummaries() != null && other.getResourceIdentifierSummaries().equals(this.getResourceIdentifierSummaries()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getParameters() == null) ? 0 : getParameters().hashCode());
hashCode = prime * hashCode + ((getDescription() == null) ? 0 : getDescription().hashCode());
hashCode = prime * hashCode + ((getCapabilities() == null) ? 0 : getCapabilities().hashCode());
hashCode = prime * hashCode + ((getCapabilitiesReason() == null) ? 0 : getCapabilitiesReason().hashCode());
hashCode = prime * hashCode + ((getResourceTypes() == null) ? 0 : getResourceTypes().hashCode());
hashCode = prime * hashCode + ((getVersion() == null) ? 0 : getVersion().hashCode());
hashCode = prime * hashCode + ((getMetadata() == null) ? 0 : getMetadata().hashCode());
hashCode = prime * hashCode + ((getDeclaredTransforms() == null) ? 0 : getDeclaredTransforms().hashCode());
hashCode = prime * hashCode + ((getResourceIdentifierSummaries() == null) ? 0 : getResourceIdentifierSummaries().hashCode());
return hashCode;
}
@Override
public GetTemplateSummaryResult clone() {
try {
return (GetTemplateSummaryResult) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
}
|
apache-2.0
|
excess-project/monitoring-agent
|
src/plugins/c/acme/setenv.sh
|
155
|
#!/bin/bash
PWD=`pwd`
export LD_LIBRARY_PATH=$PWD/../../../../bin/libiio/lib:$LD_LIBRARY_PATH
export LD_LIBRARY_PATH=$PWD/../../../../lib:$LD_LIBRARY_PATH
|
apache-2.0
|
tomecho/PrimeSpeedTest
|
prime.py
|
343
|
import sys
def test(suspect):
for i in range(2, suspect):
if suspect % i is 0:
return False
return True
if len(sys.argv) == 1:
print('please call me like "python prime.py range"')
sys.exit(0)
primes = []
for i in range(int(sys.argv[1])):
if test(i) == True:
primes.append(i)
print(len(primes))
|
apache-2.0
|
rouzwawi/flo
|
flo-runner/src/test/java/com/spotify/flo/context/FloRunnerTest.java
|
19567
|
/*-
* -\-\-
* Flo Runner
* --
* Copyright (C) 2016 - 2018 Spotify AB
* --
* 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.spotify.flo.context;
import static com.spotify.flo.context.FloRunner.runTask;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.not;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.argThat;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import com.google.common.collect.ImmutableMap;
import com.spotify.flo.FloTesting;
import com.spotify.flo.Serialization;
import com.spotify.flo.Task;
import com.spotify.flo.TaskId;
import com.spotify.flo.TestScope;
import com.spotify.flo.Tracing;
import com.spotify.flo.context.FloRunner.Result;
import com.spotify.flo.context.InstrumentedContext.Listener.Phase;
import com.spotify.flo.context.Jobs.JobOperator;
import com.spotify.flo.context.Mocks.DataProcessing;
import com.spotify.flo.context.Mocks.PublishingOutput;
import com.spotify.flo.context.Mocks.StorageLookup;
import com.spotify.flo.freezer.Persisted;
import com.spotify.flo.status.NotReady;
import com.spotify.flo.status.NotRetriable;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.lang.management.ManagementFactory;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Stream;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@RunWith(MockitoJUnitRunner.class)
public class FloRunnerTest {
private static final Logger log = LoggerFactory.getLogger(FloRunnerTest.class);
static volatile String listenerOutputDir;
private final Task<String> FOO_TASK = Task.named("task").ofType(String.class)
.process(() -> "foo");
private TerminationHook validTerminationHook;
private TerminationHook exceptionalTerminationHook;
@Rule public TemporaryFolder temporaryFolder = new TemporaryFolder();
@Mock InstrumentedContext.Listener listener;
@Before
public void setUp() throws IOException {
listenerOutputDir = temporaryFolder.newFolder().getAbsolutePath();
exceptionalTerminationHook = mock(TerminationHook.class);
doThrow(new RuntimeException("hook exception")).when(exceptionalTerminationHook).accept(any());
validTerminationHook = mock(TerminationHook.class);
doNothing().when(validTerminationHook).accept(any());
TestTerminationHookFactory.injectCreator((config) -> validTerminationHook);
}
@Test
public void nonBlockingRunnerDoesNotBlock() throws Exception {
final Path directory = temporaryFolder.newFolder().toPath();
final File startedFile = directory.resolve("started").toFile();
final File latchFile = directory.resolve("latch").toFile();
final File happenedFile = directory.resolve("happened").toFile();
final Task<Void> task = Task.named("task").ofType(Void.class)
.process(() -> {
try {
startedFile.createNewFile();
while (true) {
if (latchFile.exists()) {
happenedFile.createNewFile();
return null;
}
Thread.sleep(100);
}
} catch (IOException | InterruptedException e) {
throw new RuntimeException(e);
}
});
final Result<Void> result = runTask(task);
// Verify that the task ran at all
CompletableFuture.supplyAsync(() -> {
while (true) {
if (startedFile.exists()) {
return true;
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}).get(30, SECONDS);
// Wait a little more to ensure that the task process has some time to write the "happened" file
try {
result.future().get(2, SECONDS);
fail();
} catch (TimeoutException ignore) {
}
// If this file doesn't exist now, it's likely that runTask doesn't block
assertThat(happenedFile.exists(), is(false));
latchFile.createNewFile();
}
@Test
public void blockingRunnerBlocks() throws IOException {
final File file = temporaryFolder.newFile();
final Task<Void> task = Task.named("task").ofType(Void.class)
.process(() -> {
try {
Thread.sleep(10);
try {
Files.write(file.toPath(), "hello".getBytes(UTF_8));
} catch (IOException e) {
throw new RuntimeException(e);
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
return null;
});
runTask(task).waitAndExit(status -> { });
assertThat(new String(Files.readAllBytes(file.toPath()), UTF_8), is("hello"));
}
@Test
public void valueIsPassedInFuture() throws Exception {
final String result = runTask(FOO_TASK).future().get(30, SECONDS);
assertThat(result, is("foo"));
}
@Test
public void testSerializeException() throws Exception {
final File file = temporaryFolder.newFile();
file.delete();
Serialization.serialize(new RuntimeException("foo"), file.toPath());
}
@Test
public void exceptionsArePassed() throws Exception {
final Task<String> task = Task.named("foo").ofType(String.class)
.process(() -> {
throw new RuntimeException("foo");
});
Throwable exception = null;
try {
runTask(task).value();
} catch (ExecutionException e) {
exception = e.getCause();
}
assertThat(exception, is(instanceOf(RuntimeException.class)));
assertThat(exception.getMessage(), is("foo"));
}
@Test
public void errorsArePassed() throws Exception {
final Task<String> task = Task.named("foo").ofType(String.class)
.process(() -> {
throw new Error("foo");
});
Throwable exception = null;
try {
runTask(task).value();
} catch (ExecutionException e) {
exception = e.getCause();
}
assertThat(exception, is(instanceOf(Error.class)));
assertThat(exception.getMessage(), is("foo"));
}
@Test
public void persistedExitsZero() {
final Task<Void> task = Task.named("persisted").ofType(Void.class)
.process(() -> {
throw new Persisted();
});
AtomicInteger status = new AtomicInteger(1);
runTask(task).waitAndExit(status::set);
assertThat(status.get(), is(0));
}
@Test
public void valuesCanBeWaitedOn() throws Exception {
final String result = runTask(FOO_TASK).value();
assertThat(result, is("foo"));
}
@Test
public void notReadyExitsTwenty() {
final Task<String> task = Task.named("task").ofType(String.class)
.process(() -> {
throw new NotReady();
});
AtomicInteger status = new AtomicInteger();
runTask(task).waitAndExit(status::set);
assertThat(status.get(), is(20));
}
@Test
public void notRetriableExitsFifty() {
final Task<String> task = Task.named("task").ofType(String.class)
.process(() -> {
throw new NotRetriable();
});
AtomicInteger status = new AtomicInteger();
runTask(task).waitAndExit(status::set);
assertThat(status.get(), is(50));
}
@Test
public void exceptionsExitNonZero() {
final Task<String> task = Task.named("task").ofType(String.class)
.process(() -> {
throw new RuntimeException("this task should throw");
});
AtomicInteger status = new AtomicInteger();
runTask(task).waitAndExit(status::set);
assertThat(status.get(), is(1));
}
@Test
public void ignoreExceptionsFromTerminationHook() {
TestTerminationHookFactory.injectHook(exceptionalTerminationHook);
AtomicInteger status = new AtomicInteger();
runTask(FOO_TASK).waitAndExit(status::set);
verify(exceptionalTerminationHook, times(1)).accept(eq(0));
assertThat(status.get(), is(0));
}
@Test
public void validateTerminationHookInvocationOnTaskSuccess() {
TestTerminationHookFactory.injectHook(validTerminationHook);
AtomicInteger status = new AtomicInteger();
runTask(FOO_TASK).waitAndExit(status::set);
verify(validTerminationHook, times(1)).accept(eq(0));
assertThat(status.get(), is(0));
}
@Test
public void validateTerminationHookInvocationOnTaskFailure() {
final Task<String> task = Task.named("task").ofType(String.class)
.process(() -> {
throw new RuntimeException("this task should throw");
});
TestTerminationHookFactory.injectHook(validTerminationHook);
AtomicInteger status = new AtomicInteger();
runTask(task).waitAndExit(status::set);
verify(validTerminationHook, times(1)).accept(eq(1));
assertThat(status.get(), is(1));
}
@Test(expected = RuntimeException.class)
public void failOnExceptionalTerminationHookFactory() {
TestTerminationHookFactory.injectCreator((config) -> {
throw new RuntimeException("factory exception");
});
runTask(FOO_TASK);
}
@Test
public void taskIdIsInContext() throws Exception {
final Task<TaskId> task = Task.named("task").ofType(TaskId.class)
.process(() -> Tracing.currentTaskId());
final Result<TaskId> result = runTask(task);
assertThat(result.value(), is(task.id()));
}
@Test
public void tasksRunInProcesses() throws Exception {
final Instant today = Instant.now().truncatedTo(ChronoUnit.DAYS);
final Instant yesterday = today.minus(1, ChronoUnit.DAYS);
final Task<String> baz = Task.named("baz", today).ofType(String.class)
.process(() -> {
final String bazJvm = jvmName();
log.info("baz: bazJvm={}, today={}", bazJvm, today);
return bazJvm;
});
final Task<String[]> foo = Task.named("foo", yesterday).ofType(String[].class)
.input(() -> baz)
.process(bazJvm -> {
final String fooJvm = jvmName();
log.info("foo: fooJvm={}, bazJvm={}, yesterday={}", fooJvm, bazJvm, yesterday);
return new String[]{bazJvm, fooJvm};
});
final Task<String> quux = Task.named("quux", today).ofType(String.class)
.process(() -> {
final String quuxJvm = jvmName();
log.info("quux: quuxJvm={}, yesterday={}", quuxJvm, yesterday);
return quuxJvm;
});
final Task<String[]> bar = Task.named("bar", today, yesterday).ofType(String[].class)
.input(() -> foo)
.input(() -> quux)
.process((bazFooJvms, quuxJvm) -> {
final String barJvm = jvmName();
log.info("bar: barJvm={}, bazFooJvms={}, quuxJvm={} today={}, yesterday={}",
barJvm, bazFooJvms, quuxJvm, today, yesterday);
return Stream.concat(
Stream.of(barJvm),
Stream.concat(
Stream.of(bazFooJvms),
Stream.of(quuxJvm))
).toArray(String[]::new);
});
final List<String> jvms = Arrays.asList(runTask(bar).value());
final String mainJvm = jvmName();
log.info("main jvm: {}", mainJvm);
log.info("task jvms: {}", jvms);
final Set<String> uniqueJvms = new HashSet<>(jvms);
assertThat(uniqueJvms.size(), is(4));
assertThat(uniqueJvms, not(contains(mainJvm)));
}
@Test
public void isTestShouldBeTrueInTestScope() throws Exception {
assertThat(FloTesting.isTest(), is(false));
try (TestScope ts = FloTesting.scope()) {
assertThat(FloTesting.isTest(), is(true));
final Task<Boolean> isTest = Task.named("task").ofType(Boolean.class)
.process(FloTesting::isTest);
assertThat(runTask(isTest).future().get(30, SECONDS), is(true));
}
assertThat(FloTesting.isTest(), is(false));
}
@Test
public void mockingInputsOutputsAndContextShouldBePossibleInTestScope() throws Exception {
// Mock input, data processing results and verify lookups and publishing after the fact
try (TestScope ts = FloTesting.scope()) {
final URI barInput = URI.create("gs://bar/4711/");
final String jobResult = "42";
final URI publishResult = URI.create("meta://bar/4711/");
PublishingOutput.mock().publish(jobResult, publishResult);
StorageLookup.mock().data("bar", barInput);
DataProcessing.mock().result("quux.baz", barInput, jobResult);
final Task<String> task = Task.named("task").ofType(String.class)
.input(() -> StorageLookup.of("bar"))
.output(PublishingOutput.of("foo"))
.process((bar, publisher) -> {
// Run a data processing job and publish the result
final String result = DataProcessing.runJob("quux.baz", bar);
return publisher.publish(result);
});
assertThat(runTask(task).future().get(30, SECONDS), is(jobResult));
assertThat(DataProcessing.mock().jobRuns("quux.baz", barInput), is(1));
assertThat(StorageLookup.mock().lookups("bar"), is(1));
assertThat(PublishingOutput.mock().lookups("foo"), is(1));
assertThat(PublishingOutput.mock().published("foo"), contains(jobResult));
}
// Verify that all mocks are cleared when leaving scope
try (TestScope ts = FloTesting.scope()) {
assertThat(PublishingOutput.mock().published("foo"), is(empty()));
assertThat(PublishingOutput.mock().lookups("foo"), is(0));
}
}
@Test
public void mockingContextExistsShouldMakeProcessFnNotRunInTestScope() throws Exception {
// Mock a context lookup and verify that the process fn does not run
try (TestScope ts = FloTesting.scope()) {
PublishingOutput.mock().value("foo", "17");
final Task<String> task = Task.named("task").ofType(String.class)
.output(PublishingOutput.of("foo"))
.process(v -> { throw new AssertionError(); });
assertThat(runTask(task).future().get(30, SECONDS), is("17"));
assertThat(PublishingOutput.mock().lookups("foo"), is(1));
assertThat(PublishingOutput.mock().published("foo"), is(empty()));
}
}
@Test
public void shouldDryForkInTestMode() throws Exception {
final String mainJvmName = jvmName();
final Rock rock = new Rock();
final Task<Rock> task = Task.named("task").ofType(Rock.class)
.process(() -> rock);
final Rock result;
try (TestScope ts = FloTesting.scope()) {
result = FloRunner.runTask(task).future().get(30, SECONDS);
}
// Check that the identity of the value changed due to serialization (dry fork)
assertThat(result, is(not(rock)));
// Check that the process fn ran in the main jvm
assertThat(result.jvmName, is(mainJvmName));
}
@Test
public void testOperator() throws Exception {
final String mainJvm = jvmName();
final Instant today = Instant.now().truncatedTo(ChronoUnit.DAYS);
final Task<JobResult> task = Task.named("task", today).ofType(JobResult.class)
.operator(JobOperator.create())
.process(job -> job
.options(() -> ImmutableMap.of("quux", 17))
.pipeline(ctx -> ctx.readFrom("foo").map("x + y").writeTo("baz"))
.validation(result -> {
if (result.records < 5) {
throw new AssertionError("Too few records seen!");
}
})
.success(result -> new JobResult(jvmName(), "hdfs://foo/bar")));
final JobResult result = FloRunner.runTask(task)
.future().get(30, SECONDS);
assertThat(result.jvmName, is(not(mainJvm)));
assertThat(result.uri, is("hdfs://foo/bar"));
}
@Test
public void tasksAreObservedByInstrumentedContext() throws Exception {
final Task<String> fooTask = Task.named("foo").ofType(String.class)
.process(() -> "foo");
final Task<String> barTask = Task.named("bar").ofType(String.class)
.operator(JobOperator.create())
.input(() -> fooTask)
.process((op, bar) -> op.success(res -> "foo" + bar));
FloRunner.runTask(barTask).future().get(30, SECONDS);
RecordingListener.replay(listener);
verify(listener).task(argThat(task -> fooTask.id().equals(task.id())));
verify(listener).task(argThat(task -> barTask.id().equals(task.id())));
verify(listener).status(fooTask.id(), Phase.START);
verify(listener).status(fooTask.id(), Phase.SUCCESS);
verify(listener).status(barTask.id(), Phase.START);
verify(listener).status(barTask.id(), Phase.SUCCESS);
verify(listener).meta(barTask.id(), Collections.singletonMap("task-id", barTask.id().toString()));
verifyNoMoreInteractions(listener);
}
@Test
public void evaluatesTaskOnce() throws Exception {
final String fooRuns = temporaryFolder.newFolder().toString();
Task<String> foo = Task.named("foo").ofType(String.class)
.process(() -> {
final Path marker = Paths.get(fooRuns, UUID.randomUUID().toString());
try {
Files.createFile(marker);
} catch (IOException e) {
throw new RuntimeException(e);
}
return marker.toString();
});
Task<String> bar = Task.named("bar").ofType(String.class)
.input(() -> foo)
.input(() -> foo)
.process((foo1, foo2) -> foo1 + foo2);
FloRunner.runTask(bar).future().get();
assertThat(Files.list(Paths.get(fooRuns)).count(), is(1L));
}
private static String jvmName() {
return ManagementFactory.getRuntimeMXBean().getName();
}
private static class JobResult implements Serializable {
private static final long serialVersionUID = 1L;
private final String jvmName;
private final String uri;
JobResult(String jvmName, String uri) {
this.jvmName = jvmName;
this.uri = uri;
}
}
private static class Rock implements Serializable {
private static final long serialVersionUID = 1L;
final String jvmName = jvmName();
}
}
|
apache-2.0
|
aspnet/AspNetCore
|
src/Mvc/Mvc.RazorPages/src/MvcRazorPagesDiagnosticListenerExtensions.cs
|
17096
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure;
using Microsoft.AspNetCore.Mvc.Diagnostics;
namespace Microsoft.AspNetCore.Mvc.RazorPages
{
internal static class MvcRazorPagesDiagnosticListenerExtensions
{
public static void BeforeHandlerMethod(
this DiagnosticListener diagnosticListener,
ActionContext actionContext,
HandlerMethodDescriptor handlerMethodDescriptor,
IReadOnlyDictionary<string, object?> arguments,
object instance)
{
Debug.Assert(diagnosticListener != null);
Debug.Assert(actionContext != null);
Debug.Assert(handlerMethodDescriptor != null);
Debug.Assert(arguments != null);
Debug.Assert(instance != null);
// Inlinable fast-path check if Diagnositcs is enabled
if (diagnosticListener.IsEnabled())
{
BeforeHandlerMethodImpl(diagnosticListener, actionContext, handlerMethodDescriptor, arguments, instance);
}
}
private static void BeforeHandlerMethodImpl(DiagnosticListener diagnosticListener, ActionContext actionContext, HandlerMethodDescriptor handlerMethodDescriptor, IReadOnlyDictionary<string, object?> arguments, object instance)
{
if (diagnosticListener.IsEnabled(Diagnostics.BeforeHandlerMethodEventData.EventName))
{
diagnosticListener.Write(
Diagnostics.BeforeHandlerMethodEventData.EventName,
new BeforeHandlerMethodEventData(
actionContext,
arguments,
handlerMethodDescriptor,
instance
));
}
}
public static void AfterHandlerMethod(
this DiagnosticListener diagnosticListener,
ActionContext actionContext,
HandlerMethodDescriptor handlerMethodDescriptor,
IReadOnlyDictionary<string, object?> arguments,
object instance,
IActionResult? result)
{
Debug.Assert(diagnosticListener != null);
Debug.Assert(actionContext != null);
Debug.Assert(handlerMethodDescriptor != null);
Debug.Assert(arguments != null);
Debug.Assert(instance != null);
// Inlinable fast-path check if Diagnositcs is enabled
if (diagnosticListener.IsEnabled())
{
AfterHandlerMethodImpl(diagnosticListener, actionContext, handlerMethodDescriptor, arguments, instance, result);
}
}
private static void AfterHandlerMethodImpl(DiagnosticListener diagnosticListener, ActionContext actionContext, HandlerMethodDescriptor handlerMethodDescriptor, IReadOnlyDictionary<string, object?> arguments, object instance, IActionResult? result)
{
if (diagnosticListener.IsEnabled(Diagnostics.AfterHandlerMethodEventData.EventName))
{
diagnosticListener.Write(
Diagnostics.AfterHandlerMethodEventData.EventName,
new AfterHandlerMethodEventData(
actionContext,
arguments,
handlerMethodDescriptor,
instance,
result
));
}
}
public static void BeforeOnPageHandlerExecution(
this DiagnosticListener diagnosticListener,
PageHandlerExecutingContext handlerExecutionContext,
IAsyncPageFilter filter)
{
Debug.Assert(diagnosticListener != null);
Debug.Assert(handlerExecutionContext != null);
Debug.Assert(filter != null);
// Inlinable fast-path check if Diagnositcs is enabled
if (diagnosticListener.IsEnabled())
{
BeforeOnPageHandlerExecutionImpl(diagnosticListener, handlerExecutionContext, filter);
}
}
private static void BeforeOnPageHandlerExecutionImpl(DiagnosticListener diagnosticListener, PageHandlerExecutingContext handlerExecutionContext, IAsyncPageFilter filter)
{
if (diagnosticListener.IsEnabled(Diagnostics.BeforePageFilterOnPageHandlerExecutionEventData.EventName))
{
diagnosticListener.Write(
Diagnostics.BeforePageFilterOnPageHandlerExecutionEventData.EventName,
new BeforePageFilterOnPageHandlerExecutionEventData(
handlerExecutionContext.ActionDescriptor,
handlerExecutionContext,
filter
));
}
}
public static void AfterOnPageHandlerExecution(
this DiagnosticListener diagnosticListener,
PageHandlerExecutedContext handlerExecutedContext,
IAsyncPageFilter filter)
{
Debug.Assert(diagnosticListener != null);
Debug.Assert(handlerExecutedContext != null);
Debug.Assert(filter != null);
// Inlinable fast-path check if Diagnositcs is enabled
if (diagnosticListener.IsEnabled())
{
AfterOnPageHandlerExecutionImpl(diagnosticListener, handlerExecutedContext, filter);
}
}
private static void AfterOnPageHandlerExecutionImpl(DiagnosticListener diagnosticListener, PageHandlerExecutedContext handlerExecutedContext, IAsyncPageFilter filter)
{
if (diagnosticListener.IsEnabled(Diagnostics.AfterPageFilterOnPageHandlerExecutionEventData.EventName))
{
diagnosticListener.Write(
Diagnostics.AfterPageFilterOnPageHandlerExecutionEventData.EventName,
new AfterPageFilterOnPageHandlerExecutionEventData(
handlerExecutedContext.ActionDescriptor,
handlerExecutedContext,
filter
));
}
}
public static void BeforeOnPageHandlerExecuting(
this DiagnosticListener diagnosticListener,
PageHandlerExecutingContext handlerExecutingContext,
IPageFilter filter)
{
Debug.Assert(diagnosticListener != null);
Debug.Assert(handlerExecutingContext != null);
Debug.Assert(filter != null);
// Inlinable fast-path check if Diagnositcs is enabled
if (diagnosticListener.IsEnabled())
{
BeforeOnPageHandlerExecutingImpl(diagnosticListener, handlerExecutingContext, filter);
}
}
private static void BeforeOnPageHandlerExecutingImpl(DiagnosticListener diagnosticListener, PageHandlerExecutingContext handlerExecutingContext, IPageFilter filter)
{
if (diagnosticListener.IsEnabled(Diagnostics.BeforePageFilterOnPageHandlerExecutingEventData.EventName))
{
diagnosticListener.Write(
Diagnostics.BeforePageFilterOnPageHandlerExecutingEventData.EventName,
new BeforePageFilterOnPageHandlerExecutingEventData(
handlerExecutingContext.ActionDescriptor,
handlerExecutingContext,
filter
));
}
}
public static void AfterOnPageHandlerExecuting(
this DiagnosticListener diagnosticListener,
PageHandlerExecutingContext handlerExecutingContext,
IPageFilter filter)
{
Debug.Assert(diagnosticListener != null);
Debug.Assert(handlerExecutingContext != null);
Debug.Assert(filter != null);
// Inlinable fast-path check if Diagnositcs is enabled
if (diagnosticListener.IsEnabled())
{
AfterOnPageHandlerExecutingImpl(diagnosticListener, handlerExecutingContext, filter);
}
}
private static void AfterOnPageHandlerExecutingImpl(DiagnosticListener diagnosticListener, PageHandlerExecutingContext handlerExecutingContext, IPageFilter filter)
{
if (diagnosticListener.IsEnabled(Diagnostics.AfterPageFilterOnPageHandlerExecutingEventData.EventName))
{
diagnosticListener.Write(
Diagnostics.AfterPageFilterOnPageHandlerExecutingEventData.EventName,
new AfterPageFilterOnPageHandlerExecutingEventData(
handlerExecutingContext.ActionDescriptor,
handlerExecutingContext,
filter
));
}
}
public static void BeforeOnPageHandlerExecuted(
this DiagnosticListener diagnosticListener,
PageHandlerExecutedContext handlerExecutedContext,
IPageFilter filter)
{
Debug.Assert(diagnosticListener != null);
Debug.Assert(handlerExecutedContext != null);
Debug.Assert(filter != null);
// Inlinable fast-path check if Diagnositcs is enabled
if (diagnosticListener.IsEnabled())
{
BeforeOnPageHandlerExecutedImpl(diagnosticListener, handlerExecutedContext, filter);
}
}
private static void BeforeOnPageHandlerExecutedImpl(DiagnosticListener diagnosticListener, PageHandlerExecutedContext handlerExecutedContext, IPageFilter filter)
{
if (diagnosticListener.IsEnabled(Diagnostics.BeforePageFilterOnPageHandlerExecutedEventData.EventName))
{
diagnosticListener.Write(
Diagnostics.BeforePageFilterOnPageHandlerExecutedEventData.EventName,
new BeforePageFilterOnPageHandlerExecutedEventData(
handlerExecutedContext.ActionDescriptor,
handlerExecutedContext,
filter
));
}
}
public static void AfterOnPageHandlerExecuted(
this DiagnosticListener diagnosticListener,
PageHandlerExecutedContext handlerExecutedContext,
IPageFilter filter)
{
Debug.Assert(diagnosticListener != null);
Debug.Assert(handlerExecutedContext != null);
Debug.Assert(filter != null);
// Inlinable fast-path check if Diagnositcs is enabled
if (diagnosticListener.IsEnabled())
{
AfterOnPageHandlerExecutedImpl(diagnosticListener, handlerExecutedContext, filter);
}
}
private static void AfterOnPageHandlerExecutedImpl(DiagnosticListener diagnosticListener, PageHandlerExecutedContext handlerExecutedContext, IPageFilter filter)
{
if (diagnosticListener.IsEnabled(Diagnostics.AfterPageFilterOnPageHandlerExecutedEventData.EventName))
{
diagnosticListener.Write(
Diagnostics.AfterPageFilterOnPageHandlerExecutedEventData.EventName,
new AfterPageFilterOnPageHandlerExecutedEventData(
handlerExecutedContext.ActionDescriptor,
handlerExecutedContext,
filter
));
}
}
public static void BeforeOnPageHandlerSelection(
this DiagnosticListener diagnosticListener,
PageHandlerSelectedContext handlerSelectedContext,
IAsyncPageFilter filter)
{
Debug.Assert(diagnosticListener != null);
Debug.Assert(handlerSelectedContext != null);
Debug.Assert(filter != null);
// Inlinable fast-path check if Diagnositcs is enabled
if (diagnosticListener.IsEnabled())
{
BeforeOnPageHandlerSelectionImpl(diagnosticListener, handlerSelectedContext, filter);
}
}
private static void BeforeOnPageHandlerSelectionImpl(DiagnosticListener diagnosticListener, PageHandlerSelectedContext handlerSelectedContext, IAsyncPageFilter filter)
{
if (diagnosticListener.IsEnabled(Diagnostics.BeforePageFilterOnPageHandlerSelectionEventData.EventName))
{
diagnosticListener.Write(
Diagnostics.BeforePageFilterOnPageHandlerSelectionEventData.EventName,
new BeforePageFilterOnPageHandlerSelectionEventData(
handlerSelectedContext.ActionDescriptor,
handlerSelectedContext,
filter
));
}
}
public static void AfterOnPageHandlerSelection(
this DiagnosticListener diagnosticListener,
PageHandlerSelectedContext handlerSelectedContext,
IAsyncPageFilter filter)
{
Debug.Assert(diagnosticListener != null);
Debug.Assert(handlerSelectedContext != null);
Debug.Assert(filter != null);
// Inlinable fast-path check if Diagnositcs is enabled
if (diagnosticListener.IsEnabled())
{
AfterOnPageHandlerSelectionImpl(diagnosticListener, handlerSelectedContext, filter);
}
}
private static void AfterOnPageHandlerSelectionImpl(DiagnosticListener diagnosticListener, PageHandlerSelectedContext handlerSelectedContext, IAsyncPageFilter filter)
{
if (diagnosticListener.IsEnabled(Diagnostics.AfterPageFilterOnPageHandlerSelectionEventData.EventName))
{
diagnosticListener.Write(
Diagnostics.AfterPageFilterOnPageHandlerSelectionEventData.EventName,
new AfterPageFilterOnPageHandlerSelectionEventData(
handlerSelectedContext.ActionDescriptor,
handlerSelectedContext,
filter
));
}
}
public static void BeforeOnPageHandlerSelected(
this DiagnosticListener diagnosticListener,
PageHandlerSelectedContext handlerSelectedContext,
IPageFilter filter)
{
Debug.Assert(diagnosticListener != null);
Debug.Assert(handlerSelectedContext != null);
Debug.Assert(filter != null);
// Inlinable fast-path check if Diagnositcs is enabled
if (diagnosticListener.IsEnabled())
{
BeforeOnPageHandlerSelectedImpl(diagnosticListener, handlerSelectedContext, filter);
}
}
private static void BeforeOnPageHandlerSelectedImpl(DiagnosticListener diagnosticListener, PageHandlerSelectedContext handlerSelectedContext, IPageFilter filter)
{
if (diagnosticListener.IsEnabled(Diagnostics.BeforePageFilterOnPageHandlerSelectedEventData.EventName))
{
diagnosticListener.Write(
Diagnostics.BeforePageFilterOnPageHandlerSelectedEventData.EventName,
new BeforePageFilterOnPageHandlerSelectedEventData(
handlerSelectedContext.ActionDescriptor,
handlerSelectedContext,
filter
));
}
}
public static void AfterOnPageHandlerSelected(
this DiagnosticListener diagnosticListener,
PageHandlerSelectedContext handlerSelectedContext,
IPageFilter filter)
{
Debug.Assert(diagnosticListener != null);
Debug.Assert(handlerSelectedContext != null);
Debug.Assert(filter != null);
// Inlinable fast-path check if Diagnositcs is enabled
if (diagnosticListener.IsEnabled())
{
AfterOnPageHandlerSelectedImpl(diagnosticListener, handlerSelectedContext, filter);
}
}
private static void AfterOnPageHandlerSelectedImpl(DiagnosticListener diagnosticListener, PageHandlerSelectedContext handlerSelectedContext, IPageFilter filter)
{
if (diagnosticListener.IsEnabled(Diagnostics.AfterPageFilterOnPageHandlerSelectedEventData.EventName))
{
diagnosticListener.Write(
Diagnostics.AfterPageFilterOnPageHandlerSelectedEventData.EventName,
new AfterPageFilterOnPageHandlerSelectedEventData(
handlerSelectedContext.ActionDescriptor,
handlerSelectedContext,
filter
));
}
}
}
}
|
apache-2.0
|
amaas-fintech/amaas-core-sdk-python
|
amaascore/market_data/utils.py
|
723
|
from __future__ import absolute_import, division, print_function, unicode_literals
from amaascore.market_data.eod_price import EODPrice
from amaascore.market_data.fx_rate import FXRate
from amaascore.market_data.curve import Curve
from amaascore.market_data.corporate_action import CorporateAction
def json_to_eod_price(json_eod_price):
eod_price = EODPrice(**json_eod_price)
return eod_price
def json_to_fx_rate(json_fx_rate):
fx_rate = FXRate(**json_fx_rate)
return fx_rate
def json_to_curve(json_curve):
curve = Curve(**json_curve)
return curve
def json_to_corporate_action(json_corporate_action):
corporate_action = CorporateAction(**json_corporate_action)
return corporate_action
|
apache-2.0
|
AnEgg/DragonYun
|
src/org/jiucheng/web/Ctrl.java
|
1114
|
/*
* Copyright (c) jiucheng.org
*/
package org.jiucheng.web;
import java.lang.reflect.Method;
public class Ctrl {
private String route;
private Method method;
private RequestType requestType;
private String beanName;
private String handlerBeanName;
public void setRoute(String route) {
this.route = route;
}
public String getRoute() {
return route;
}
public Method getMethod() {
return method;
}
public void setRequestType(RequestType requestType) {
this.requestType = requestType;
}
public RequestType getRequestType() {
return requestType;
}
public void setMethod(Method method) {
this.method = method;
}
public void setBeanName(String beanName) {
this.beanName = beanName;
}
public String getBeanName() {
return beanName;
}
public String getHandlerBeanName() {
return handlerBeanName;
}
public void setHandlerBeanName(String handlerBeanName) {
this.handlerBeanName = handlerBeanName;
}
}
|
apache-2.0
|
baby-gnu/one
|
src/cli/one_helper/onedatastore_helper.rb
|
6796
|
# -------------------------------------------------------------------------- #
# Copyright 2002-2020, OpenNebula Project, OpenNebula Systems #
# #
# Licensed under the Apache License, Version 2.0 (the "License"); you may #
# not use this file except in compliance with the License. You may obtain #
# a copy of the License at #
# #
# http://www.apache.org/licenses/LICENSE-2.0 #
# #
# Unless required by applicable law or agreed to in writing, software #
# distributed under the License is distributed on an "AS IS" BASIS, #
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #
# See the License for the specific language governing permissions and #
# limitations under the License. #
#--------------------------------------------------------------------------- #
require 'one_helper'
class OneDatastoreHelper < OpenNebulaHelper::OneHelper
DATASTORE = {
:name => "datastore",
:short => "-d id|name",
:large => "--datastore id|name" ,
:description => "Selects the datastore",
:format => String,
:proc => lambda { |o, options|
OpenNebulaHelper.rname_to_id(o, "DATASTORE")
}
}
def self.rname
"DATASTORE"
end
def self.conf_file
"onedatastore.yaml"
end
def format_pool(options)
config_file = self.class.table_conf
table = CLIHelper::ShowTable.new(config_file, self) do
column :ID, "ONE identifier for the Datastore", :size=>4 do |d|
d["ID"]
end
column :USER, "Username of the Datastore owner", :left,
:size=>10 do |d|
helper.user_name(d, options)
end
column :GROUP, "Group of the Datastore", :left,
:size=>10 do |d|
helper.group_name(d, options)
end
column :NAME, "Name of the Datastore", :left, :size=>13 do |d|
d["NAME"]
end
column :SIZE, "Datastore total size", :size =>10 do |d|
shared = d['TEMPLATE']['SHARED']
if shared != nil && shared.upcase == 'NO'
"-"
else
OpenNebulaHelper.unit_to_str(d['TOTAL_MB'].to_i, {}, 'M')
end
end
column :AVAIL, "Datastore free size", :left, :size =>5 do |d|
if d['TOTAL_MB'].to_i == 0
"-"
else
"#{((d['FREE_MB'].to_f/d['TOTAL_MB'].to_f) * 100).round()}%"
end
end
column :CLUSTERS, "Cluster IDs", :left, :size=>12 do |d|
OpenNebulaHelper.clusters_str(d["CLUSTERS"]["ID"])
end
column :IMAGES, "Number of Images", :size=>6 do |d|
if d["IMAGES"]["ID"].nil?
"0"
else
[d["IMAGES"]["ID"]].flatten.size
end
end
column :TYPE, "Datastore type", :left, :size=>4 do |d|
type = OpenNebula::Datastore::DATASTORE_TYPES[d["TYPE"].to_i]
OpenNebula::Datastore::SHORT_DATASTORE_TYPES[type]
end
column :DS, "Datastore driver", :left, :size=>7 do |d|
d["DS_MAD"]
end
column :TM, "Transfer driver", :left, :size=>7 do |d|
d["TM_MAD"]
end
column :STAT, "State of the Datastore", :left, :size=>3 do |d|
state = OpenNebula::Datastore::DATASTORE_STATES[d["STATE"].to_i]
OpenNebula::Datastore::SHORT_DATASTORE_STATES[state]
end
default :ID, :USER, :GROUP, :NAME, :SIZE, :AVAIL, :CLUSTERS, :IMAGES,
:TYPE, :DS, :TM, :STAT
end
table
end
private
def factory(id=nil)
if id
OpenNebula::Datastore.new_with_id(id, @client)
else
xml=OpenNebula::Datastore.build_xml
OpenNebula::Datastore.new(xml, @client)
end
end
def factory_pool(user_flag=-2)
OpenNebula::DatastorePool.new(@client)
end
def format_resource(datastore, options = {})
str="%-15s: %-20s"
str_h1="%-80s"
CLIHelper.print_header(str_h1 % "DATASTORE #{datastore['ID']} INFORMATION")
puts str % ["ID", datastore.id.to_s]
puts str % ["NAME", datastore.name]
puts str % ["USER", datastore['UNAME']]
puts str % ["GROUP", datastore['GNAME']]
puts str % ["CLUSTERS",
OpenNebulaHelper.clusters_str(datastore.retrieve_elements("CLUSTERS/ID"))]
puts str % ["TYPE", datastore.type_str]
puts str % ["DS_MAD", datastore['DS_MAD']]
puts str % ["TM_MAD", datastore['TM_MAD']]
puts str % ["BASE PATH",datastore['BASE_PATH']]
puts str % ["DISK_TYPE",Image::DISK_TYPES[datastore['DISK_TYPE'].to_i]]
puts str % ["STATE", datastore.state_str]
puts
CLIHelper.print_header(str_h1 % "DATASTORE CAPACITY", false)
shared = datastore['TEMPLATE/SHARED']
local = shared != nil && shared.upcase == 'NO'
limit_mb = datastore['TEMPLATE/LIMIT_MB']
puts str % ["TOTAL:", local ? '-' : OpenNebulaHelper.unit_to_str(datastore['TOTAL_MB'].to_i, {},'M')]
puts str % ["FREE:", local ? '-' : OpenNebulaHelper.unit_to_str(datastore['FREE_MB'].to_i, {},'M')]
puts str % ["USED: ", local ? '-' : OpenNebulaHelper.unit_to_str(datastore['USED_MB'].to_i, {},'M')]
puts str % ["LIMIT:", local || limit_mb.nil? ? '-' : OpenNebulaHelper.unit_to_str(limit_mb.to_i, {},'M')]
puts
CLIHelper.print_header(str_h1 % "PERMISSIONS",false)
["OWNER", "GROUP", "OTHER"].each { |e|
mask = "---"
mask[0] = "u" if datastore["PERMISSIONS/#{e}_U"] == "1"
mask[1] = "m" if datastore["PERMISSIONS/#{e}_M"] == "1"
mask[2] = "a" if datastore["PERMISSIONS/#{e}_A"] == "1"
puts str % [e, mask]
}
puts
CLIHelper.print_header(str_h1 % "DATASTORE TEMPLATE", false)
puts datastore.template_str
puts
CLIHelper.print_header("%-15s" % "IMAGES")
datastore.img_ids.each do |id|
puts "%-15s" % [id]
end
end
end
|
apache-2.0
|
cuba-platform/cuba
|
modules/core-tests/src/com/haulmont/cuba/testsupport/TestDbUpdateManager.java
|
883
|
/*
* Copyright (c) 2008-2017 Haulmont.
*
* 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.haulmont.cuba.testsupport;
import com.haulmont.cuba.core.sys.dbupdate.DbUpdateManager;
public class TestDbUpdateManager extends DbUpdateManager {
@Override
protected void applicationInitialized() {
// don't do DB update in integration tests
}
}
|
apache-2.0
|
tensorflow/tfjs-examples
|
jena-weather/ui.js
|
4072
|
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
import {plotData} from './index';
const statusElement = document.getElementById('status');
const timeSpanSelect = document.getElementById('time-span');
const selectSeries1 = document.getElementById('data-series-1');
const selectSeries2 = document.getElementById('data-series-2');
const dataNormalizedCheckbox = document.getElementById('data-normalized');
const dateTimeRangeSpan = document.getElementById('date-time-range');
const dataPrevButton = document.getElementById('data-prev');
const dataNextButton = document.getElementById('data-next');
const dataScatterCheckbox = document.getElementById('data-scatter');
export function logStatus(message) {
statusElement.innerText = message;
}
export function populateSelects(dataObj) {
const columnNames = ['None'].concat(dataObj.getDataColumnNames());
for (const selectSeries of [selectSeries1, selectSeries2]) {
while (selectSeries.firstChild) {
selectSeries.removeChild(selectSeries.firstChild);
}
console.log(columnNames);
for (const name of columnNames) {
const option = document.createElement('option');
option.setAttribute('value', name);
option.textContent = name;
selectSeries.appendChild(option);
}
}
if (columnNames.indexOf('T (degC)') !== -1) {
selectSeries1.value = 'T (degC)';
}
if (columnNames.indexOf('p (mbar)') !== -1) {
selectSeries2.value = 'p (mbar)';
}
timeSpanSelect.value = 'week';
dataNormalizedCheckbox.checked = true;
}
export const TIME_SPAN_RANGE_MAP = {
hour: 6,
day: 6 * 24,
week: 6 * 24 * 7,
tenDays: 6 * 24 * 10,
month: 6 * 24 * 30,
year: 6 * 24 * 365,
full: null
};
export const TIME_SPAN_STRIDE_MAP = {
day: 1,
week: 1,
tenDays: 6,
month: 6,
year: 6 * 6,
full: 6 * 24
};
export let currBeginIndex = 0;
export function updateDateTimeRangeSpan(jenaWeatherData) {
const timeSpan = timeSpanSelect.value;
const currEndIndex = currBeginIndex + TIME_SPAN_RANGE_MAP[timeSpan];
const begin =
new Date(jenaWeatherData.getTime(currBeginIndex)).toLocaleDateString();
const end =
new Date(jenaWeatherData.getTime(currEndIndex)).toLocaleDateString();
dateTimeRangeSpan.textContent = `${begin} - ${end}`;
}
export function updateScatterCheckbox() {
const series1 = selectSeries1.value;
const series2 = selectSeries2.value;
dataScatterCheckbox.disabled = series1 === 'None' || series2 === 'None';
}
dataPrevButton.addEventListener('click', () => {
const timeSpan = timeSpanSelect.value;
currBeginIndex -= Math.round(TIME_SPAN_RANGE_MAP[timeSpan] / 8);
if (currBeginIndex >= 0) {
plotData();
} else {
currBeginIndex = 0;
}
});
dataNextButton.addEventListener('click', () => {
const timeSpan = timeSpanSelect.value;
currBeginIndex += Math.round(TIME_SPAN_RANGE_MAP[timeSpan] / 8);
plotData();
});
timeSpanSelect.addEventListener('change', () => {
plotData();
});
selectSeries1.addEventListener('change', plotData);
selectSeries2.addEventListener('change', plotData);
dataNormalizedCheckbox.addEventListener('change', plotData);
dataScatterCheckbox.addEventListener('change', plotData);
export function getDataVizOptions() {
return {
timeSpan: timeSpanSelect.value,
series1: selectSeries1.value,
series2: selectSeries2.value,
normalize: dataNormalizedCheckbox.checked,
scatter: dataScatterCheckbox.checked
};
}
|
apache-2.0
|
xiuxin/Huntering
|
common/src/main/java/com/huntering/common/entity/search/utils/SearchableConvertUtils.java
|
7912
|
/**
* Copyright (c) 2005-2012 https://github.com/zhangkaitao
*
* Licensed under the Apache License, Version 2.0 (the "License");
*/
package com.huntering.common.entity.search.utils;
import com.google.common.collect.Lists;
import com.huntering.common.entity.search.SearchOperator;
import com.huntering.common.entity.search.Searchable;
import com.huntering.common.entity.search.exception.InvalidSearchPropertyException;
import com.huntering.common.entity.search.exception.InvalidSearchValueException;
import com.huntering.common.entity.search.exception.SearchException;
import com.huntering.common.entity.search.filter.AndCondition;
import com.huntering.common.entity.search.filter.Condition;
import com.huntering.common.entity.search.filter.OrCondition;
import com.huntering.common.entity.search.filter.SearchFilter;
import com.huntering.common.utils.SpringUtils;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.beans.InvalidPropertyException;
import org.springframework.core.convert.ConversionService;
import org.springframework.util.CollectionUtils;
import java.util.Collection;
import java.util.List;
/**
* <p>User: Zhang Kaitao
* <p>Date: 13-1-15 上午11:46
* <p>Version: 1.0
*/
public final class SearchableConvertUtils {
private static volatile ConversionService conversionService;
/**
* 设置用于类型转换的conversionService
* 把如下代码放入spring配置文件即可
* <bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
* <property name="staticMethod"
* value="com.huntering.common.entity.search.utils.SearchableConvertUtils.setConversionService"/>
* <property name="arguments" ref="conversionService"/>
* </bean>
*
* @param conversionService
*/
public static void setConversionService(ConversionService conversionService) {
SearchableConvertUtils.conversionService = conversionService;
}
public static ConversionService getConversionService() {
if (conversionService == null) {
synchronized (SearchableConvertUtils.class) {
if (conversionService == null) {
try {
conversionService = SpringUtils.getBean(ConversionService.class);
} catch (Exception e) {
throw new SearchException("conversionService is null, " +
"search param convert must use conversionService. " +
"please see [com.huntering.common.entity.search.utils." +
"SearchableConvertUtils#setConversionService]");
}
}
}
}
return conversionService;
}
/**
* @param search 查询条件
* @param entityClass 实体类型
* @param <T>
*/
public static <T> void convertSearchValueToEntityValue(final Searchable search, final Class<T> entityClass) {
if (search.isConverted()) {
return;
}
Collection<SearchFilter> searchFilters = search.getSearchFilters();
BeanWrapperImpl beanWrapper = new BeanWrapperImpl(entityClass);
beanWrapper.setAutoGrowNestedPaths(true);
beanWrapper.setConversionService(getConversionService());
for (SearchFilter searchFilter : searchFilters) {
convertSearchValueToEntityValue(beanWrapper, searchFilter);
}
}
private static void convertSearchValueToEntityValue(BeanWrapperImpl beanWrapper, SearchFilter searchFilter) {
if (searchFilter instanceof Condition) {
Condition condition = (Condition) searchFilter;
convert(beanWrapper, condition);
return;
}
if (searchFilter instanceof OrCondition) {
for (SearchFilter orFilter : ((OrCondition) searchFilter).getOrFilters()) {
convertSearchValueToEntityValue(beanWrapper, orFilter);
}
return;
}
if (searchFilter instanceof AndCondition) {
for (SearchFilter andFilter : ((AndCondition) searchFilter).getAndFilters()) {
convertSearchValueToEntityValue(beanWrapper, andFilter);
}
return;
}
}
private static void convert(BeanWrapperImpl beanWrapper, Condition condition) {
String searchProperty = condition.getSearchProperty();
//自定义的也不转换
if (condition.getOperator() == SearchOperator.custom) {
return;
}
//一元运算符不需要计算
if (condition.isUnaryFilter()) {
return;
}
String entityProperty = condition.getEntityProperty();
Object value = condition.getValue();
Object newValue = null;
boolean isCollection = value instanceof Collection;
boolean isArray = value != null && value.getClass().isArray();
if (isCollection || isArray) {
List<Object> list = Lists.newArrayList();
if (isCollection) {
list.addAll((Collection) value);
} else {
list = Lists.newArrayList(CollectionUtils.arrayToList(value));
}
int length = list.size();
for (int i = 0; i < length; i++) {
list.set(i, getConvertedValue(beanWrapper, searchProperty, entityProperty, list.get(i)));
}
newValue = list;
} else {
newValue = getConvertedValue(beanWrapper, searchProperty, entityProperty, value);
}
condition.setValue(newValue);
}
private static Object getConvertedValue(
final BeanWrapperImpl beanWrapper,
final String searchProperty,
final String entityProperty,
final Object value) {
Object newValue;
try {
beanWrapper.setPropertyValue(entityProperty, value);
newValue = beanWrapper.getPropertyValue(entityProperty);
} catch (InvalidPropertyException e) {
throw new InvalidSearchPropertyException(searchProperty, entityProperty, e);
} catch (Exception e) {
throw new InvalidSearchValueException(searchProperty, entityProperty, value, e);
}
return newValue;
}
/* public static <T> void convertSearchValueToEntityValue(SearchRequest search, Class<T> domainClass) {
List<Condition> searchFilters = search.getSearchFilters();
for (Condition searchFilter : searchFilters) {
String property = searchFilter.getSearchProperty();
Class<? extends Comparable> targetPropertyType = getPropertyType(domainClass, property);
Object value = searchFilter.getValue();
Comparable newValue = convert(value, targetPropertyType);
searchFilter.setValue(newValue);
}
}*/
/*
private static <T> Class getPropertyType(Class<T> domainClass, String property) {
String[] names = StringUtils.split(property, ".");
Class<?> clazz = null;
for (String name : names) {
if (clazz == null) {
clazz = BeanUtils.findPropertyType(name, ArrayUtils.toArray(domainClass));
} else {
clazz = BeanUtils.findPropertyType(name, ArrayUtils.toArray(clazz));
}
}
return clazz;
}*/
/*
public static <S, T> T convert(S sourceValue, Class<T> targetClass) {
ConversionService conversionService = getConversionService();
if (!conversionService.canConvert(sourceValue.getClass(), targetClass)) {
throw new IllegalArgumentException(
"search param can not convert value:[" + sourceValue + "] to target type:[" + targetClass + "]");
}
return conversionService.convert(sourceValue, targetClass);
}
*/
}
|
apache-2.0
|
scalatest/scalatest-website
|
public/scaladoc/2.2.2/org/scalatest/path/package.html
|
8880
|
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html>
<head>
<title>path - ScalaTest 2.2.2-SNAPSHOT - org.scalatest.path</title>
<meta name="description" content="path - ScalaTest 2.2.2 - SNAPSHOT - org.scalatest.path" />
<meta name="keywords" content="path ScalaTest 2.2.2 SNAPSHOT org.scalatest.path" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<link href="../../../lib/template.css" media="screen" type="text/css" rel="stylesheet" />
<link href="../../../lib/diagrams.css" media="screen" type="text/css" rel="stylesheet" id="diagrams-css" />
<script type="text/javascript" src="../../../lib/jquery.js" id="jquery-js"></script>
<script type="text/javascript" src="../../../lib/jquery-ui.js"></script>
<script type="text/javascript" src="../../../lib/template.js"></script>
<script type="text/javascript" src="../../../lib/tools.tooltip.js"></script>
<script type="text/javascript">
if(top === self) {
var url = '../../../index.html';
var hash = 'org.scalatest.path.package';
var anchor = window.location.hash;
var anchor_opt = '';
if (anchor.length >= 1)
anchor_opt = '@' + anchor.substring(1);
window.location.href = url + '#' + hash + anchor_opt;
}
</script>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-71294502-3', 'auto');
ga('send', 'pageview');
</script>
</head>
<body class="value">
<!-- Top of doc.scalatest.org [javascript] -->
<script type="text/javascript">
var rnd = window.rnd || Math.floor(Math.random()*10e6);
var pid204546 = window.pid204546 || rnd;
var plc204546 = window.plc204546 || 0;
var abkw = window.abkw || '';
var absrc = 'http://ab167933.adbutler-ikon.com/adserve/;ID=167933;size=468x60;setID=204546;type=js;sw='+screen.width+';sh='+screen.height+';spr='+window.devicePixelRatio+';kw='+abkw+';pid='+pid204546+';place='+(plc204546++)+';rnd='+rnd+';click=CLICK_MACRO_PLACEHOLDER';
document.write('<scr'+'ipt src="'+absrc+'" type="text/javascript"></scr'+'ipt>');
</script>
<div id="definition">
<img src="../../../lib/package_big.png" />
<p id="owner"><a href="../../package.html" class="extype" name="org">org</a>.<a href="../package.html" class="extype" name="org.scalatest">scalatest</a></p>
<h1>path</h1>
</div>
<h4 id="signature" class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">package</span>
</span>
<span class="symbol">
<span class="name">path</span>
</span>
</h4>
<div id="comment" class="fullcommenttop"></div>
<div id="mbrsel">
<div id="textfilter"><span class="pre"></span><span class="input"><input id="mbrsel-input" type="text" accesskey="/" /></span><span class="post"></span></div>
<div id="visbl">
<span class="filtertype">Visibility</span>
<ol><li class="public in"><span>Public</span></li><li class="all out"><span>All</span></li></ol>
</div>
</div>
<div id="template">
<div id="allMembers">
<div id="types" class="types members">
<h3>Type Members</h3>
<ol><li name="org.scalatest.path.FreeSpec" visbl="pub" data-isabs="false" fullComment="no" group="Ungrouped">
<a id="FreeSpecextendsFreeSpecLike"></a>
<a id="FreeSpec:FreeSpec"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">class</span>
</span>
<span class="symbol">
<a href="FreeSpec.html"><span class="name">FreeSpec</span></a><span class="result"> extends <a href="FreeSpecLike.html" class="extype" name="org.scalatest.path.FreeSpecLike">FreeSpecLike</a></span>
</span>
</h4>
<p class="comment cmt">A sister class to <code>org.scalatest.FreeSpec</code> that isolates tests by running each test in its own
instance of the test class, and for each test, only executing the <em>path</em> leading to that test.</p>
</li><li name="org.scalatest.path.FreeSpecLike" visbl="pub" data-isabs="true" fullComment="no" group="Ungrouped">
<a id="FreeSpecLikeextendsSuitewithOneInstancePerTestwithInformingwithNotifyingwithAlertingwithDocumenting"></a>
<a id="FreeSpecLike:FreeSpecLike"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">trait</span>
</span>
<span class="symbol">
<a href="FreeSpecLike.html"><span class="name">FreeSpecLike</span></a><span class="result"> extends <a href="../Suite.html" class="extype" name="org.scalatest.Suite">Suite</a> with <a href="../OneInstancePerTest.html" class="extype" name="org.scalatest.OneInstancePerTest">OneInstancePerTest</a> with <a href="../Informing.html" class="extype" name="org.scalatest.Informing">Informing</a> with <a href="../Notifying.html" class="extype" name="org.scalatest.Notifying">Notifying</a> with <a href="../Alerting.html" class="extype" name="org.scalatest.Alerting">Alerting</a> with <a href="../Documenting.html" class="extype" name="org.scalatest.Documenting">Documenting</a></span>
</span>
</h4>
<p class="comment cmt">Implementation trait for class <code>path.FreeSpec</code>, which is
a sister class to <code>org.scalatest.FreeSpec</code> that isolates
tests by running each test in its own instance of the test class, and
for each test, only executing the <em>path</em> leading to that test.</p>
</li><li name="org.scalatest.path.FunSpec" visbl="pub" data-isabs="false" fullComment="no" group="Ungrouped">
<a id="FunSpecextendsFunSpecLike"></a>
<a id="FunSpec:FunSpec"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">class</span>
</span>
<span class="symbol">
<a href="FunSpec.html"><span class="name">FunSpec</span></a><span class="result"> extends <a href="FunSpecLike.html" class="extype" name="org.scalatest.path.FunSpecLike">FunSpecLike</a></span>
</span>
</h4>
<p class="comment cmt">A sister class to <code>org.scalatest.FunSpec</code> that isolates tests by running each test in its own
instance of the test class, and for each test, only executing the <em>path</em> leading to that test.</p>
</li><li name="org.scalatest.path.FunSpecLike" visbl="pub" data-isabs="true" fullComment="no" group="Ungrouped">
<a id="FunSpecLikeextendsSuitewithOneInstancePerTestwithInformingwithNotifyingwithAlertingwithDocumenting"></a>
<a id="FunSpecLike:FunSpecLike"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">trait</span>
</span>
<span class="symbol">
<a href="FunSpecLike.html"><span class="name">FunSpecLike</span></a><span class="result"> extends <a href="../Suite.html" class="extype" name="org.scalatest.Suite">Suite</a> with <a href="../OneInstancePerTest.html" class="extype" name="org.scalatest.OneInstancePerTest">OneInstancePerTest</a> with <a href="../Informing.html" class="extype" name="org.scalatest.Informing">Informing</a> with <a href="../Notifying.html" class="extype" name="org.scalatest.Notifying">Notifying</a> with <a href="../Alerting.html" class="extype" name="org.scalatest.Alerting">Alerting</a> with <a href="../Documenting.html" class="extype" name="org.scalatest.Documenting">Documenting</a></span>
</span>
</h4>
<p class="comment cmt">Implementation trait for class <code>path.FunSpec</code>, which is
a sister class to <code>org.scalatest.FunSpec</code> that isolates
tests by running each test in its own instance of the test class,
and for each test, only executing the <em>path</em> leading to that test.</p>
</li></ol>
</div>
</div>
<div id="inheritedMembers">
</div>
<div id="groupedMembers">
<div class="group" name="Ungrouped">
<h3>Ungrouped</h3>
</div>
</div>
</div>
<div id="tooltip"></div>
<div id="footer"> </div>
</body>
</html>
|
apache-2.0
|
RandomCodeOrg/ENetFramework
|
RandomCodeOrg.Pluto/Config/ApplicationDescriptor.cs
|
16670
|
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
//
// This source code was auto-generated by xsd, Version=4.6.1055.0.
//
namespace RandomCodeOrg.Pluto.Config {
using System.Xml.Serialization;
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.6.1055.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://randomcodeorg.github.com/ENetFramework/ApplicationDescriptor")]
[System.Xml.Serialization.XmlRootAttribute(Namespace="http://randomcodeorg.github.com/ENetFramework/ApplicationDescriptor", IsNullable=false)]
public partial class ApplicationDescriptor {
private ApplicationInformation informationField;
private Configuration[] configurationField;
/// <remarks/>
public ApplicationInformation Information {
get {
return this.informationField;
}
set {
this.informationField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("Configuration")]
public Configuration[] Configuration {
get {
return this.configurationField;
}
set {
this.configurationField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.6.1055.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://randomcodeorg.github.com/ENetFramework/ApplicationDescriptor")]
public partial class ApplicationInformation {
private string titleField;
private string descriptionField;
/// <remarks/>
public string Title {
get {
return this.titleField;
}
set {
this.titleField = value;
}
}
/// <remarks/>
public string Description {
get {
return this.descriptionField;
}
set {
this.descriptionField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.6.1055.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://randomcodeorg.github.com/ENetFramework/ApplicationDescriptor")]
public partial class Time {
private float valueField;
private TimeUnit unitField;
public Time() {
this.unitField = TimeUnit.Minutes;
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public float Value {
get {
return this.valueField;
}
set {
this.valueField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
[System.ComponentModel.DefaultValueAttribute(TimeUnit.Minutes)]
public TimeUnit Unit {
get {
return this.unitField;
}
set {
this.unitField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.6.1055.0")]
[System.SerializableAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://randomcodeorg.github.com/ENetFramework/ApplicationDescriptor")]
public enum TimeUnit {
/// <remarks/>
Hours,
/// <remarks/>
Minutes,
/// <remarks/>
Seconds,
/// <remarks/>
Milliseconds,
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.6.1055.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://randomcodeorg.github.com/ENetFramework/ApplicationDescriptor")]
public partial class SessionConfiguration {
private Time timeoutField;
private string cookieNameField;
private int maxSessionsField;
/// <remarks/>
public Time Timeout {
get {
return this.timeoutField;
}
set {
this.timeoutField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(DataType="token")]
public string CookieName {
get {
return this.cookieNameField;
}
set {
this.cookieNameField = value;
}
}
/// <remarks/>
public int MaxSessions {
get {
return this.maxSessionsField;
}
set {
this.maxSessionsField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.6.1055.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://randomcodeorg.github.com/ENetFramework/ApplicationDescriptor")]
public partial class NavigationRule {
private object targetField;
private string[] itemsField;
private ItemsChoiceType[] itemsElementNameField;
private string nameField;
/// <remarks/>
public object Target {
get {
return this.targetField;
}
set {
this.targetField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("FromOutcome", typeof(string))]
[System.Xml.Serialization.XmlElementAttribute("FromPath", typeof(string), DataType="anyURI")]
[System.Xml.Serialization.XmlChoiceIdentifierAttribute("ItemsElementName")]
public string[] Items {
get {
return this.itemsField;
}
set {
this.itemsField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("ItemsElementName")]
[System.Xml.Serialization.XmlIgnoreAttribute()]
public ItemsChoiceType[] ItemsElementName {
get {
return this.itemsElementNameField;
}
set {
this.itemsElementNameField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string Name {
get {
return this.nameField;
}
set {
this.nameField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.6.1055.0")]
[System.SerializableAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://randomcodeorg.github.com/ENetFramework/ApplicationDescriptor", IncludeInSchema=false)]
public enum ItemsChoiceType {
/// <remarks/>
FromOutcome,
/// <remarks/>
FromPath,
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.6.1055.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://randomcodeorg.github.com/ENetFramework/ApplicationDescriptor")]
public partial class NavigationConfiguration {
private string[] welcomeField;
private NavigationRule[] ruleField;
/// <remarks/>
[System.Xml.Serialization.XmlArrayItemAttribute("Alternative", IsNullable=false)]
public string[] Welcome {
get {
return this.welcomeField;
}
set {
this.welcomeField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("Rule")]
public NavigationRule[] Rule {
get {
return this.ruleField;
}
set {
this.ruleField = value;
}
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIncludeAttribute(typeof(TypeImport))]
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.6.1055.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://randomcodeorg.github.com/ENetFramework/ApplicationDescriptor")]
public partial class TypeReference {
private string nameField;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute(DataType="token")]
public string Name {
get {
return this.nameField;
}
set {
this.nameField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.6.1055.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://randomcodeorg.github.com/ENetFramework/ApplicationDescriptor")]
public partial class TypeImport : TypeReference {
private bool includePrivateField;
private bool includeProtectedField;
private bool includePublicField;
public TypeImport() {
this.includePrivateField = false;
this.includeProtectedField = false;
this.includePublicField = true;
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
[System.ComponentModel.DefaultValueAttribute(false)]
public bool IncludePrivate {
get {
return this.includePrivateField;
}
set {
this.includePrivateField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
[System.ComponentModel.DefaultValueAttribute(false)]
public bool IncludeProtected {
get {
return this.includeProtectedField;
}
set {
this.includeProtectedField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
[System.ComponentModel.DefaultValueAttribute(true)]
public bool IncludePublic {
get {
return this.includePublicField;
}
set {
this.includePublicField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.6.1055.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://randomcodeorg.github.com/ENetFramework/ApplicationDescriptor")]
public partial class AssemblyReference {
private string nameField;
private string locationField;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string Name {
get {
return this.nameField;
}
set {
this.nameField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string Location {
get {
return this.locationField;
}
set {
this.locationField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.6.1055.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://randomcodeorg.github.com/ENetFramework/ApplicationDescriptor")]
public partial class CompilationConfiguration {
private AssemblyReference[] referencesField;
private string[] namespacesField;
private TypeImport[] extensionsField;
/// <remarks/>
[System.Xml.Serialization.XmlArrayItemAttribute("Assembly", IsNullable=false)]
public AssemblyReference[] References {
get {
return this.referencesField;
}
set {
this.referencesField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlArrayItemAttribute("Import", DataType="token", IsNullable=false)]
public string[] Namespaces {
get {
return this.namespacesField;
}
set {
this.namespacesField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlArrayItemAttribute("Type", IsNullable=false)]
public TypeImport[] Extensions {
get {
return this.extensionsField;
}
set {
this.extensionsField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.6.1055.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://randomcodeorg.github.com/ENetFramework/ApplicationDescriptor")]
public partial class Configuration {
private CompilationConfiguration compilationField;
private NavigationConfiguration navigationField;
private SessionConfiguration sessionField;
private string nameField;
public Configuration() {
this.nameField = "Default";
}
/// <remarks/>
public CompilationConfiguration Compilation {
get {
return this.compilationField;
}
set {
this.compilationField = value;
}
}
/// <remarks/>
public NavigationConfiguration Navigation {
get {
return this.navigationField;
}
set {
this.navigationField = value;
}
}
/// <remarks/>
public SessionConfiguration Session {
get {
return this.sessionField;
}
set {
this.sessionField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
[System.ComponentModel.DefaultValueAttribute("Default")]
public string Name {
get {
return this.nameField;
}
set {
this.nameField = value;
}
}
}
}
|
apache-2.0
|
citrix/terraform-provider-netscaler
|
vendor/github.com/citrix/adc-nitro-go/resource/config/appfw/appfwxmlerrorpage.go
|
1434
|
/*
* Copyright (c) 2021 Citrix Systems, 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 appfw
/**
* Configuration for xml error page resource.
*/
type Appfwxmlerrorpage struct {
/**
* Indicates name of the imported xml error page to be removed.
*/
Name string `json:"name,omitempty"`
/**
* URL (protocol, host, path, and name) for the location at which to store the imported XML error object.
NOTE: The import fails if the object to be imported is on an HTTPS server that requires client certificate authentication for access.
*/
Src string `json:"src,omitempty"`
/**
* Any comments to preserve information about the XML error object.
*/
Comment string `json:"comment,omitempty"`
/**
* Overwrite any existing XML error object of the same name.
*/
Overwrite bool `json:"overwrite,omitempty"`
//------- Read only Parameter ---------;
Response string `json:"response,omitempty"`
}
|
apache-2.0
|
pearpai/java_action
|
src/main/java/com/action/jdxchxjs/ch03/stack_1/MyStack.java
|
1139
|
package com.action.jdxchxjs.ch03.stack_1;
import java.util.ArrayList;
import java.util.List;
/**
* Created by wuyunfeng on 2017/9/21.
*/
public class MyStack {
private List list = new ArrayList();
public synchronized void pubsh(){
try {
if (list.size() == 1){
this.wait();
}
list.add("anyString=" + Math.random());
this.notify();
System.out.println("push=" + list.size());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public synchronized String pop(){
String returnValue = "";
try {
if (list.size() == 0){
System.out.println("pop 操作中的:" + Thread.currentThread().getName()
+ " 线程呈wait状态");
this.wait();
}
returnValue = "" + list.get(0);
list.remove(0);
this.notify();
System.out.println("pop=" + list.size());
} catch (InterruptedException e) {
e.printStackTrace();
}
return returnValue;
}
}
|
apache-2.0
|
xiangzhuyuan/spring-security-oauth
|
spring-security-oauth2/src/test/java/org/springframework/security/oauth2/config/annotation/ClientConfigurationTests.java
|
3983
|
/*
* Copyright 2006-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package org.springframework.security.oauth2.config.annotation;
import org.hamcrest.CoreMatchers;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.*;
import org.springframework.mock.web.MockServletContext;
import org.springframework.security.oauth2.client.DefaultOAuth2ClientContext;
import org.springframework.security.oauth2.client.OAuth2RestOperations;
import org.springframework.security.oauth2.client.OAuth2RestTemplate;
import org.springframework.security.oauth2.client.filter.OAuth2ClientContextFilter;
import org.springframework.security.oauth2.client.token.AccessTokenRequest;
import org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeResourceDetails;
import org.springframework.security.oauth2.config.annotation.web.configuration.OAuth2ClientConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import javax.annotation.Resource;
/**
* @author Dave Syer
*/
public class ClientConfigurationTests {
@Test
public void testAuthCodeRedirect() throws Exception {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.setServletContext(new MockServletContext());
context.register(ClientContext.class);
context.refresh();
MockMvc mvc = MockMvcBuilders.webAppContextSetup(context).addFilters(new OAuth2ClientContextFilter()).build();
mvc.perform(MockMvcRequestBuilders.get("/photos"))
.andExpect(MockMvcResultMatchers.status().isFound())
.andExpect(
MockMvcResultMatchers.header().string("Location",
CoreMatchers.startsWith("http://example.com/authorize")));
context.close();
}
@Controller
@Configuration
@EnableWebMvc
@Import(OAuth2ClientConfiguration.class)
protected static class ClientContext {
@Resource
@Qualifier("accessTokenRequest")
private AccessTokenRequest accessTokenRequest;
@RequestMapping("/photos")
@ResponseBody
public String photos() {
return restTemplate().getForObject("http://example.com/photos", String.class);
}
@Bean
@Lazy
@Scope(value = "session", proxyMode = ScopedProxyMode.INTERFACES)
public OAuth2RestOperations restTemplate() {
AuthorizationCodeResourceDetails resource = new AuthorizationCodeResourceDetails();
resource.setClientId("client");
resource.setAccessTokenUri("http://example.com/token");
resource.setUserAuthorizationUri("http://example.com/authorize");
return new OAuth2RestTemplate(resource, new DefaultOAuth2ClientContext(accessTokenRequest));
}
}
}
|
apache-2.0
|
eSDK/esdk_tp_native_java
|
test/demo/eSDK_TP_Demo_BS_Java/src/com/huawei/esdk/demo/autogen/BroadInfoEx.java
|
4017
|
package com.huawei.esdk.demo.autogen;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
/**
* <p>Java class for BroadInfoEx complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="BroadInfoEx">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="directBroad" type="{http://www.w3.org/2001/XMLSchema}int"/>
* <element name="recordBroad" type="{http://www.w3.org/2001/XMLSchema}int"/>
* <element name="directBroadStatus" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
* <element name="recordBroadStatus" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "BroadInfoEx", propOrder = {
"directBroad",
"recordBroad",
"directBroadStatus",
"recordBroadStatus"
})
public class BroadInfoEx {
@XmlElement(required = true, type = String.class)
@XmlJavaTypeAdapter(Adapter2 .class)
@XmlSchemaType(name = "int")
protected Integer directBroad;
@XmlElement(required = true, type = String.class)
@XmlJavaTypeAdapter(Adapter2 .class)
@XmlSchemaType(name = "int")
protected Integer recordBroad;
@XmlElement(type = String.class)
@XmlJavaTypeAdapter(Adapter2 .class)
@XmlSchemaType(name = "int")
protected Integer directBroadStatus;
@XmlElement(type = String.class)
@XmlJavaTypeAdapter(Adapter2 .class)
@XmlSchemaType(name = "int")
protected Integer recordBroadStatus;
/**
* Gets the value of the directBroad property.
*
* @return
* possible object is
* {@link String }
*
*/
public Integer getDirectBroad() {
return directBroad;
}
/**
* Sets the value of the directBroad property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDirectBroad(Integer value) {
this.directBroad = value;
}
/**
* Gets the value of the recordBroad property.
*
* @return
* possible object is
* {@link String }
*
*/
public Integer getRecordBroad() {
return recordBroad;
}
/**
* Sets the value of the recordBroad property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setRecordBroad(Integer value) {
this.recordBroad = value;
}
/**
* Gets the value of the directBroadStatus property.
*
* @return
* possible object is
* {@link String }
*
*/
public Integer getDirectBroadStatus() {
return directBroadStatus;
}
/**
* Sets the value of the directBroadStatus property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDirectBroadStatus(Integer value) {
this.directBroadStatus = value;
}
/**
* Gets the value of the recordBroadStatus property.
*
* @return
* possible object is
* {@link String }
*
*/
public Integer getRecordBroadStatus() {
return recordBroadStatus;
}
/**
* Sets the value of the recordBroadStatus property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setRecordBroadStatus(Integer value) {
this.recordBroadStatus = value;
}
}
|
apache-2.0
|
feedhenry/fh-dotnet-sdk
|
Documentations/html/dir_0c96b3d0fc842fbb51d7afc18d90cdec.js
|
347
|
var dir_0c96b3d0fc842fbb51d7afc18d90cdec =
[
[ "design", "dir_b39402054b6f29d8059088b0004b64ee.html", "dir_b39402054b6f29d8059088b0004b64ee" ],
[ "v4", "dir_b1530cc8b78b2d9923632461f396c71c.html", "dir_b1530cc8b78b2d9923632461f396c71c" ],
[ "v7", "dir_94bdcc46f12b2beb2dba250b68a1fa32.html", "dir_94bdcc46f12b2beb2dba250b68a1fa32" ]
];
|
apache-2.0
|
wontfix-org/wtf
|
docs/apidoc/wtf.impl.http._request-module.html
|
12532
|
<?xml version="1.0" encoding="ascii"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>wtf.impl.http._request</title>
<link rel="stylesheet" href="epydoc.css" type="text/css" />
<script type="text/javascript" src="epydoc.js"></script>
</head>
<body bgcolor="white" text="black" link="blue" vlink="#204080"
alink="#204080">
<!-- ==================== NAVIGATION BAR ==================== -->
<table class="navbar" border="0" width="100%" cellpadding="0"
bgcolor="#a0c0ff" cellspacing="0">
<tr valign="middle">
<!-- Home link -->
<th> <a
href="wtf-module.html">Home</a> </th>
<!-- Tree link -->
<th> <a
href="module-tree.html">Trees</a> </th>
<!-- Index link -->
<th> <a
href="identifier-index.html">Indices</a> </th>
<!-- Help link -->
<th> <a
href="help.html">Help</a> </th>
<!-- Project homepage -->
<th class="navbar" align="right" width="100%">
<table border="0" cellpadding="0" cellspacing="0">
<tr><th class="navbar" align="center"
><a href="http://opensource.perlig.de/wtf/">Visit WTF Online</a></th>
</tr></table></th>
</tr>
</table>
<table width="100%" cellpadding="0" cellspacing="0">
<tr valign="top">
<td width="100%">
<span class="breadcrumbs">
<a href="wtf-module.html">Package wtf</a> ::
<a href="wtf.impl-module.html">Package impl</a> ::
<a href="wtf.impl.http-module.html">Package http</a> ::
Module _request
</span>
</td>
<td>
<table cellpadding="0" cellspacing="0">
<!-- hide/show private -->
<tr><td align="right"><span class="options">[<a href="javascript:void(0);" class="privatelink"
onclick="toggle_private();">hide private</a>]</span></td></tr>
<tr><td align="right"><span class="options"
>[<a href="frames.html" target="_top">frames</a
>] | <a href="wtf.impl.http._request-module.html"
target="_top">no frames</a>]</span></td></tr>
</table>
</td>
</tr>
</table>
<!-- ==================== MODULE DESCRIPTION ==================== -->
<h1 class="epydoc">Module _request</h1><p class="nomargin-top"><span class="codelink"><a href="wtf.impl.http._request-pysrc.html">source code</a></span></p>
<p>This is a simple state pattern implementing the request flow.</p>
<hr />
<div class="fields"> <p><strong>Author:</strong>
André Malo
</p>
</div><!-- ==================== CLASSES ==================== -->
<a name="section-Classes"></a>
<table class="summary" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr bgcolor="#70b0f0" class="table-header">
<td colspan="2" class="table-header">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr valign="top">
<td align="left"><span class="table-header">Classes</span></td>
<td align="right" valign="top"
><span class="options">[<a href="#section-Classes"
class="privatelink" onclick="toggle_private();"
>hide private</a>]</span></td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a href="wtf.impl.http._request.RequestTimeout-class.html" class="summary-name">RequestTimeout</a><br />
Request timed out
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a href="wtf.impl.http._request.ExpectationFailed-class.html" class="summary-name">ExpectationFailed</a><br />
Expectation failed
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a href="wtf.impl.http._request.UnsupportedHTTPVersion-class.html" class="summary-name">UnsupportedHTTPVersion</a><br />
HTTP Version not supported
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a href="wtf.impl.http._request.UnImplemented-class.html" class="summary-name">UnImplemented</a><br />
A feature is unimplemented
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a href="wtf.impl.http._request.InvalidRequestLine-class.html" class="summary-name">InvalidRequestLine</a><br />
Request line is invalid
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a href="wtf.impl.http._request.InvalidContentLength-class.html" class="summary-name">InvalidContentLength</a><br />
The supplied content length is invalid
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a href="wtf.impl.http._request.InvalidTransferEncoding-class.html" class="summary-name">InvalidTransferEncoding</a><br />
An invalid transfer encoding was supplied
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a href="wtf.impl.http._request.MissingHostHeader-class.html" class="summary-name">MissingHostHeader</a><br />
Host header is mandatory with HTTP/1.1
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a href="wtf.impl.http._request.StateError-class.html" class="summary-name">StateError</a><br />
HTTP request state error
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a href="wtf.impl.http._request.BaseState-class.html" class="summary-name">BaseState</a><br />
Base state class
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a href="wtf.impl.http._request.RequestInitialState-class.html" class="summary-name">RequestInitialState</a><br />
Initial state of a request, for example on a fresh connection.
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a href="wtf.impl.http._request.RequestLineReadyState-class.html" class="summary-name">RequestLineReadyState</a><br />
The headers can be read now
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a href="wtf.impl.http._request.RequestHeadersReadyState-class.html" class="summary-name">RequestHeadersReadyState</a><br />
The body can be read now and/or the response can be started
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a href="wtf.impl.http._request.ResponseContinueWaitState-class.html" class="summary-name">ResponseContinueWaitState</a><br />
We're waiting for either 100 continue emission of send_status
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a href="wtf.impl.http._request.ResponseStatusWaitState-class.html" class="summary-name">ResponseStatusWaitState</a><br />
Waiting for status line
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a href="wtf.impl.http._request.ResponseHeadersWaitState-class.html" class="summary-name">ResponseHeadersWaitState</a><br />
We're waiting for headers to be set and sent
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a href="wtf.impl.http._request.ResponseBodyWaitState-class.html" class="summary-name">ResponseBodyWaitState</a><br />
We're waiting for someone to send the response body
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a href="wtf.impl.http._request.ResponseDoneState-class.html" class="summary-name">ResponseDoneState</a><br />
Nothing can be done here anymore
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a href="wtf.impl.http._request.HTTPRequest-class.html" class="summary-name">HTTPRequest</a><br />
HTTP Request abstraction
</td>
</tr>
</table>
<!-- ==================== VARIABLES ==================== -->
<a name="section-Variables"></a>
<table class="summary" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr bgcolor="#70b0f0" class="table-header">
<td colspan="2" class="table-header">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr valign="top">
<td align="left"><span class="table-header">Variables</span></td>
<td align="right" valign="top"
><span class="options">[<a href="#section-Variables"
class="privatelink" onclick="toggle_private();"
>hide private</a>]</span></td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"><tt class="rst-docutils literal">str</tt></span>
</td><td class="summary">
<a name="CRLF"></a><span class="summary-name">CRLF</span> = <code title="'''\r
'''"><code class="variable-quote">'</code><code class="variable-string">\r\n</code><code class="variable-quote">'</code></code><br />
ASCII CRLF sequence (rn)
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="__package__"></a><span class="summary-name">__package__</span> = <code title="'wtf.impl.http'"><code class="variable-quote">'</code><code class="variable-string">wtf.impl.http</code><code class="variable-quote">'</code></code>
</td>
</tr>
</table>
<!-- ==================== NAVIGATION BAR ==================== -->
<table class="navbar" border="0" width="100%" cellpadding="0"
bgcolor="#a0c0ff" cellspacing="0">
<tr valign="middle">
<!-- Home link -->
<th> <a
href="wtf-module.html">Home</a> </th>
<!-- Tree link -->
<th> <a
href="module-tree.html">Trees</a> </th>
<!-- Index link -->
<th> <a
href="identifier-index.html">Indices</a> </th>
<!-- Help link -->
<th> <a
href="help.html">Help</a> </th>
<!-- Project homepage -->
<th class="navbar" align="right" width="100%">
<table border="0" cellpadding="0" cellspacing="0">
<tr><th class="navbar" align="center"
><a href="http://opensource.perlig.de/wtf/">Visit WTF Online</a></th>
</tr></table></th>
</tr>
</table>
<script type="text/javascript">
<!--
// Private objects are initially displayed (because if
// javascript is turned off then we want them to be
// visible); but by default, we want to hide them. So hide
// them unless we have a cookie that says to show them.
checkCookie();
// -->
</script>
</body>
</html>
|
apache-2.0
|
Project34/Raptored
|
README.md
|
24
|
# Raptored
Text editor
|
apache-2.0
|
mogotest/selenium
|
remote/server/src/java/org/openqa/selenium/remote/server/DriverServlet.java
|
14199
|
/*
Copyright 2007-2009 WebDriver committers
Copyright 2007-2009 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.openqa.selenium.remote.server;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.openqa.selenium.remote.server.handler.AddConfig;
import org.openqa.selenium.remote.server.handler.AddCookie;
import org.openqa.selenium.remote.server.handler.CaptureScreenshot;
import org.openqa.selenium.remote.server.handler.ChangeUrl;
import org.openqa.selenium.remote.server.handler.ClearElement;
import org.openqa.selenium.remote.server.handler.ClickElement;
import org.openqa.selenium.remote.server.handler.CloseWindow;
import org.openqa.selenium.remote.server.handler.DeleteCookie;
import org.openqa.selenium.remote.server.handler.DeleteNamedCookie;
import org.openqa.selenium.remote.server.handler.DeleteSession;
import org.openqa.selenium.remote.server.handler.DescribeElement;
import org.openqa.selenium.remote.server.handler.DragElement;
import org.openqa.selenium.remote.server.handler.ExecuteScript;
import org.openqa.selenium.remote.server.handler.FindActiveElement;
import org.openqa.selenium.remote.server.handler.FindChildElement;
import org.openqa.selenium.remote.server.handler.FindChildElements;
import org.openqa.selenium.remote.server.handler.FindElement;
import org.openqa.selenium.remote.server.handler.FindElements;
import org.openqa.selenium.remote.server.handler.GetAllCookies;
import org.openqa.selenium.remote.server.handler.GetAllWindowHandles;
import org.openqa.selenium.remote.server.handler.GetCssProperty;
import org.openqa.selenium.remote.server.handler.GetCurrentUrl;
import org.openqa.selenium.remote.server.handler.GetCurrentWindowHandle;
import org.openqa.selenium.remote.server.handler.GetElementAttribute;
import org.openqa.selenium.remote.server.handler.GetElementDisplayed;
import org.openqa.selenium.remote.server.handler.GetElementEnabled;
import org.openqa.selenium.remote.server.handler.GetElementLocation;
import org.openqa.selenium.remote.server.handler.GetElementSelected;
import org.openqa.selenium.remote.server.handler.GetElementSize;
import org.openqa.selenium.remote.server.handler.GetElementText;
import org.openqa.selenium.remote.server.handler.GetElementValue;
import org.openqa.selenium.remote.server.handler.GetMouseSpeed;
import org.openqa.selenium.remote.server.handler.GetPageSource;
import org.openqa.selenium.remote.server.handler.GetSessionCapabilities;
import org.openqa.selenium.remote.server.handler.GetTagName;
import org.openqa.selenium.remote.server.handler.GetTitle;
import org.openqa.selenium.remote.server.handler.GoBack;
import org.openqa.selenium.remote.server.handler.GoForward;
import org.openqa.selenium.remote.server.handler.HoverOverElement;
import org.openqa.selenium.remote.server.handler.NewSession;
import org.openqa.selenium.remote.server.handler.RefreshPage;
import org.openqa.selenium.remote.server.handler.SendKeys;
import org.openqa.selenium.remote.server.handler.SetElementSelected;
import org.openqa.selenium.remote.server.handler.SetMouseSpeed;
import org.openqa.selenium.remote.server.handler.SubmitElement;
import org.openqa.selenium.remote.server.handler.SwitchToFrame;
import org.openqa.selenium.remote.server.handler.SwitchToWindow;
import org.openqa.selenium.remote.server.handler.ToggleElement;
import org.openqa.selenium.remote.server.handler.ElementEquality;
import org.openqa.selenium.remote.server.renderer.EmptyResult;
import org.openqa.selenium.remote.server.renderer.ForwardResult;
import org.openqa.selenium.remote.server.renderer.JsonErrorExceptionResult;
import org.openqa.selenium.remote.server.renderer.JsonResult;
import org.openqa.selenium.remote.server.renderer.RedirectResult;
import org.openqa.selenium.remote.server.rest.Handler;
import org.openqa.selenium.remote.server.rest.ResultConfig;
import org.openqa.selenium.remote.server.rest.ResultType;
import org.openqa.selenium.remote.server.rest.UrlMapper;
public class DriverServlet extends HttpServlet {
private UrlMapper getMapper;
private UrlMapper postMapper;
private UrlMapper deleteMapper;
@Override
public void init() throws ServletException {
super.init();
DriverSessions driverSessions = new DriverSessions();
ServletLogTo logger = new ServletLogTo();
setupMappings(driverSessions, logger);
}
private void setupMappings(DriverSessions driverSessions, ServletLogTo logger) {
getMapper = new UrlMapper(driverSessions, logger);
postMapper = new UrlMapper(driverSessions, logger);
deleteMapper = new UrlMapper(driverSessions, logger);
getMapper.addGlobalHandler(ResultType.EXCEPTION,
new JsonErrorExceptionResult(":exception", ":response"));
postMapper.addGlobalHandler(ResultType.EXCEPTION,
new JsonErrorExceptionResult(":exception", ":response"));
deleteMapper.addGlobalHandler(ResultType.EXCEPTION,
new JsonErrorExceptionResult(":exception", ":response"));
postMapper.bind("/config/drivers", AddConfig.class).on(ResultType.SUCCESS, new EmptyResult());
postMapper.bind("/session", NewSession.class)
.on(ResultType.SUCCESS, new RedirectResult("/session/:sessionId"));
getMapper.bind("/session/:sessionId", GetSessionCapabilities.class)
.on(ResultType.SUCCESS, new ForwardResult("/WEB-INF/views/sessionCapabilities.jsp"))
.on(ResultType.SUCCESS, new JsonResult(":response"), "application/json");
deleteMapper.bind("/session/:sessionId", DeleteSession.class)
.on(ResultType.SUCCESS, new EmptyResult());
getMapper.bind("/session/:sessionId/window_handle", GetCurrentWindowHandle.class)
.on(ResultType.SUCCESS, new JsonResult(":response"));
getMapper.bind("/session/:sessionId/window_handles", GetAllWindowHandles.class)
.on(ResultType.SUCCESS, new JsonResult(":response"));
postMapper.bind("/session/:sessionId/url", ChangeUrl.class)
.on(ResultType.SUCCESS, new EmptyResult());
getMapper.bind("/session/:sessionId/url", GetCurrentUrl.class)
.on(ResultType.SUCCESS, new JsonResult(":response"));
postMapper.bind("/session/:sessionId/forward", GoForward.class)
.on(ResultType.SUCCESS, new EmptyResult());
postMapper.bind("/session/:sessionId/back", GoBack.class)
.on(ResultType.SUCCESS, new EmptyResult());
postMapper.bind("/session/:sessionId/refresh", RefreshPage.class)
.on(ResultType.SUCCESS, new EmptyResult());
postMapper.bind("/session/:sessionId/execute", ExecuteScript.class)
.on(ResultType.SUCCESS, new JsonResult(":response"));
getMapper.bind("/session/:sessionId/source", GetPageSource.class)
.on(ResultType.SUCCESS, new JsonResult(":response"));
getMapper.bind("/session/:sessionId/screenshot", CaptureScreenshot.class)
.on(ResultType.SUCCESS, new JsonResult(":response"));
getMapper.bind("/session/:sessionId/title", GetTitle.class)
.on(ResultType.SUCCESS, new JsonResult(":response"));
postMapper.bind("/session/:sessionId/element", FindElement.class)
.on(ResultType.SUCCESS, new JsonResult(":response"));
getMapper.bind("/session/:sessionId/element/:id", DescribeElement.class)
.on(ResultType.SUCCESS, new JsonResult(":response"));
postMapper.bind("/session/:sessionId/elements", FindElements.class)
.on(ResultType.SUCCESS, new JsonResult(":response"));
postMapper.bind("/session/:sessionId/element/active", FindActiveElement.class)
.on(ResultType.SUCCESS, new JsonResult(":response"));
postMapper.bind("/session/:sessionId/element/:id/element", FindChildElement.class)
.on(ResultType.SUCCESS, new JsonResult(":response"));
postMapper.bind("/session/:sessionId/element/:id/elements", FindChildElements.class)
.on(ResultType.SUCCESS, new JsonResult(":response"));
postMapper.bind("/session/:sessionId/element/:id/click", ClickElement.class)
.on(ResultType.SUCCESS, new EmptyResult());
getMapper.bind("/session/:sessionId/element/:id/text", GetElementText.class)
.on(ResultType.SUCCESS, new JsonResult(":response"));
postMapper.bind("/session/:sessionId/element/:id/submit", SubmitElement.class)
.on(ResultType.SUCCESS, new EmptyResult());
postMapper.bind("/session/:sessionId/element/:id/value", SendKeys.class)
.on(ResultType.SUCCESS, new EmptyResult());
getMapper.bind("/session/:sessionId/element/:id/value", GetElementValue.class)
.on(ResultType.SUCCESS, new JsonResult(":response"));
getMapper.bind("/session/:sessionId/element/:id/name", GetTagName.class)
.on(ResultType.SUCCESS, new JsonResult(":response"));
postMapper.bind("/session/:sessionId/element/:id/clear", ClearElement.class)
.on(ResultType.SUCCESS, new EmptyResult());
getMapper.bind("/session/:sessionId/element/:id/selected", GetElementSelected.class)
.on(ResultType.SUCCESS, new JsonResult(":response"));
postMapper.bind("/session/:sessionId/element/:id/selected", SetElementSelected.class)
.on(ResultType.SUCCESS, new EmptyResult());
postMapper.bind("/session/:sessionId/element/:id/toggle", ToggleElement.class)
.on(ResultType.SUCCESS, new JsonResult(":response"));
getMapper.bind("/session/:sessionId/element/:id/enabled", GetElementEnabled.class)
.on(ResultType.SUCCESS, new JsonResult(":response"));
getMapper.bind("/session/:sessionId/element/:id/displayed", GetElementDisplayed.class)
.on(ResultType.SUCCESS, new JsonResult(":response"));
getMapper.bind("/session/:sessionId/element/:id/location", GetElementLocation.class)
.on(ResultType.SUCCESS, new JsonResult(":response"));
getMapper.bind("/session/:sessionId/element/:id/size", GetElementSize.class)
.on(ResultType.SUCCESS, new JsonResult(":response"));
getMapper.bind("/session/:sessionId/element/:id/css/:propertyName", GetCssProperty.class)
.on(ResultType.SUCCESS, new JsonResult(":response"));
postMapper.bind("/session/:sessionId/element/:id/hover", HoverOverElement.class)
.on(ResultType.SUCCESS, new EmptyResult());
postMapper.bind("/session/:sessionId/element/:id/drag", DragElement.class)
.on(ResultType.SUCCESS, new EmptyResult());
getMapper.bind("/session/:sessionId/element/:id/attribute/:name", GetElementAttribute.class)
.on(ResultType.SUCCESS, new JsonResult(":response"));
getMapper.bind("/session/:sessionId/element/:id/equals/:other", ElementEquality.class)
.on(ResultType.SUCCESS, new JsonResult(":response"));
getMapper.bind("/session/:sessionId/cookie", GetAllCookies.class)
.on(ResultType.SUCCESS, new JsonResult(":response"));
postMapper.bind("/session/:sessionId/cookie", AddCookie.class)
.on(ResultType.SUCCESS, new EmptyResult());
deleteMapper.bind("/session/:sessionId/cookie", DeleteCookie.class)
.on(ResultType.SUCCESS, new EmptyResult());
deleteMapper.bind("/session/:sessionId/cookie/:name", DeleteNamedCookie.class)
.on(ResultType.SUCCESS, new EmptyResult());
postMapper.bind("/session/:sessionId/frame", SwitchToFrame.class)
.on(ResultType.SUCCESS, new EmptyResult());
postMapper.bind("/session/:sessionId/window", SwitchToWindow.class)
.on(ResultType.SUCCESS, new EmptyResult());
deleteMapper.bind("/session/:sessionId/window", CloseWindow.class)
.on(ResultType.SUCCESS, new EmptyResult());
getMapper.bind("/session/:sessionId/speed", GetMouseSpeed.class)
.on(ResultType.SUCCESS, new JsonResult(":response"));
postMapper.bind("/session/:sessionId/speed", SetMouseSpeed.class)
.on(ResultType.SUCCESS, new EmptyResult());
}
protected ResultConfig addNewGetMapping(String path, Class<? extends Handler> implementationClass) {
return getMapper.bind(path, implementationClass);
}
protected ResultConfig addNewPostMapping(String path, Class<? extends Handler> implementationClass) {
return postMapper.bind(path, implementationClass);
}
protected ResultConfig addNewDeleteMapping(String path, Class<? extends Handler> implementationClass) {
return deleteMapper.bind(path, implementationClass);
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
handleRequest(getMapper, request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
handleRequest(postMapper, request, response);
}
@Override
protected void doDelete(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
handleRequest(deleteMapper, request, response);
}
protected void handleRequest(UrlMapper mapper, HttpServletRequest request,
HttpServletResponse response)
throws ServletException {
try {
ResultConfig config = mapper.getConfig(request.getPathInfo());
if (config == null) {
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
} else {
config.handle(request.getPathInfo(), request, response);
}
} catch (Exception e) {
log("Fatal, unhandled exception: " + request.getPathInfo() + ": " + e);
throw new ServletException(e);
}
}
private class ServletLogTo implements LogTo {
public void log(String message) {
DriverServlet.this.log(message);
}
}
}
|
apache-2.0
|
mdoering/backbone
|
life/Fungi/Ascomycota/Sordariomycetes/Xylariales/Xylariaceae/Sphaeria/Sphaeria calthaecola/README.md
|
234
|
# Sphaeria calthaecola (DC.) Fr. SPECIES
#### Status
ACCEPTED
#### According to
Index Fungorum
#### Published in
Syst. mycol. (Lundae) 2(2): 532 (1823)
#### Original name
Sphaeria lichenoides var. calthaecola DC.
### Remarks
null
|
apache-2.0
|
freeVM/freeVM
|
enhanced/archive/classlib/modules/rmi2.1.4/src/main/java/org/apache/harmony/rmi/internal/runtime/RMIDefaultClassLoaderSpi.java
|
14748
|
/*
* Copyright 2005 The Apache Software Foundation or its licensors, as applicable.
*
* 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.apache.harmony.rmi.internal.runtime;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.lang.reflect.Modifier;
import java.lang.reflect.Proxy;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.rmi.server.RMIClassLoader;
import java.rmi.server.RMIClassLoaderSpi;
import java.util.Arrays;
import java.util.HashMap;
import org.apache.harmony.rmi.internal.utils.Pair;
import org.apache.harmony.rmi.internal.utils.PropertiesReader;
/**
* This is the default RMI implementation of the
* {@link java.rmi.server.RMIClassLoaderSpi} interface. The implementation of
* these method it is specified in the
* {@link RMIClassLoader}
* API.
*
* @author Gustavo Petri
*
*/
public class RMIDefaultClassLoaderSpi extends RMIClassLoaderSpi {
/**
* A <code>String</code> that serves as a cache fot the codebaseProp
* property.
*/
private String codebaseProp;
/**
* A flag that represents the unexistence of a <code>SecurityManager</code>.
*/
private boolean noSecurityManager;
/**
* The actual <code>SecurityManager</code> instance of the class.
*/
private SecurityManager securityManager;
/**
* This is a mapping between pairs of sorted codebase Strings and
* <code>ClassLoader</code> instances to <code>WeakReferences</code> to
* the <code>URLClassLoader</code> cached in this table.
*/
private HashMap<Pair<String, ClassLoader>, WeakReference<URLClassLoader>> classLoaderMap;
/**
* Constructs a default {@link java.rmi.server.RMIClassLoaderSpi}
* instance and it initializes the private variables.
*/
public RMIDefaultClassLoaderSpi() {
super();
codebaseProp = PropertiesReader.readString("java.rmi.server.codebase");
securityManager = System.getSecurityManager();
if (securityManager == null) {
noSecurityManager = true;
} else {
noSecurityManager = false;
}
classLoaderMap =
new HashMap<Pair<String, ClassLoader>, WeakReference<URLClassLoader>>();
}
@Override
/**
* Should construct a Proxy Class that implements all the interfaces passed
* as parameter.
*
* @param codebase
* a <code>String</code> that represent the specified directory
* @param interfaces
* a array of <code>Strings</code> interfaces
* @param defaultLoader
* responsible for loading classes
* @return a Proxy Class that implements all the interfaces
* @throws MalformedURLException
* no legal protocol could be found in a specification string
* @throws ClassNotFoundException
* if there is no Classloader for the specified interfaces
*/
public final Class<?> loadProxyClass(String codebase, String[] interfaces,
ClassLoader defaultLoader) throws MalformedURLException,
ClassNotFoundException {
Class<?>[] interfaceClasses = new Class[interfaces.length];
ClassLoader notPublicClassloader = null;
for (int i = 0; i < interfaces.length; i++) {
interfaceClasses[i] = loadClass(codebase, interfaces[i],
defaultLoader);
int modifier = interfaceClasses[i].getModifiers();
if (!Modifier.isPublic(modifier)) {
if (notPublicClassloader == null) {
notPublicClassloader = interfaceClasses[i].getClassLoader();
} else if (!notPublicClassloader.equals(interfaceClasses[i]
.getClassLoader())) {
throw new LinkageError(
"There is no Classloader for the specified interfaces");
}
}
}
if (notPublicClassloader != null) {
try {
return Proxy.getProxyClass(notPublicClassloader,
interfaceClasses);
} catch (Exception e) {
throw new LinkageError(
"There is no Classloader for the specified interfaces");
}
}
try {
ClassLoader cl = getClassLoader(codebase);
return Proxy.getProxyClass(cl, interfaceClasses);
} catch (IllegalArgumentException e) {
try {
return Proxy.getProxyClass(defaultLoader, interfaceClasses);
} catch (IllegalArgumentException e1) {
throw new ClassNotFoundException(
"There is no Classloader for the specified interfaces",
e);
}
}
}
@Override
/**
* Specified in the
* {@link java.rmi.server.RMIClassLoader#getDefaultProviderInstance} Method.
* Returns the
* {@link <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/ClassLoader.html"><code>ClassLoader</code></a>}
* which has loaded the Class.
*
* @param cl
* the specified Class
* @return the
* {@link <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/ClassLoader.html"><code>ClassLoader</code></a>}
* which has loaded the Class.
*/
public final String getClassAnnotation(Class cl) {
java.lang.ClassLoader classLoader = cl.getClassLoader();
String codebase =
PropertiesReader.readString("java.rmi.server.codebase");
if (classLoader == null) {
return codebase;
}
java.lang.ClassLoader cLoader = classLoader;
while (cLoader != null) {
if (ClassLoader.getSystemClassLoader().equals(classLoader)) {
return codebase;
}
if (cl != null) {
cLoader = cLoader.getParent();
}
}
if (classLoader instanceof URLClassLoader
&& !ClassLoader.getSystemClassLoader().equals(classLoader)) {
try {
URL urls[] = ((URLClassLoader) classLoader).getURLs();
String ret = null;
/*
* FIXME HARD: Check Permissions: If the URLClassLoader was
* created by this provider to service an invocation of its
* loadClass or loadProxyClass methods, then no permissions are
* required to get the associated codebase string. If it is an
* arbitrary other URLClassLoader instance, then if there is a
* security manager, its checkPermission method will be invoked
* once for each URL returned by the getURLs method, with the
* permission returned by invoking
* openConnection().getPermission() on each URL
*/
if (urls != null) {
for (URL url : urls) {
if (ret == null) {
ret = new String(url.toExternalForm());
} else {
ret += " " + url.toExternalForm();
}
}
}
return ret;
} catch (SecurityException e) {
return codebase;
}
}
return codebase;
}
@Override
/**
* Specified in the {@link java.rmi.server.RMIClassLoader#loadClass(String)}
* Method. It loads the class directly.
*
* @param codebase
* a <code>String</code> that represent the specified directory
* @param name
* of the class.
* @param defaultLoader
* responsible for loading classes
* @return a Proxy Class
* @throws MalformedURLException
* no legal protocol could be found in a specification string
* @throws ClassNotFoundException
* if there is no Classloader for the specified interfaces
*/
public final Class<?> loadClass(String codebase, String name,
ClassLoader defaultLoader) throws MalformedURLException,
ClassNotFoundException {
Class<?> ret;
if (defaultLoader != null) {
try {
ret = Class.forName(name, false, defaultLoader);
} catch (ClassNotFoundException e) {
try {
ret = Class.forName(name, false, getClassLoader(codebase));
} catch (SecurityException e1) {
ret = Class.forName(name, false, Thread.currentThread()
.getContextClassLoader());
}
}
} else {
try {
ret = Class.forName(name, false, getClassLoader(codebase));
} catch (SecurityException e1) {
ret = Class.forName(name, false, Thread.currentThread()
.getContextClassLoader());
}
}
return ret;
}
@Override
/**
* Specified in the
* {@link java.rmi.server.RMIClassLoader#getClassLoader(String)} Method.
* Returns the corresponding
* {@link <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/ClassLoader.html"><code>ClassLoader</code></a>}
* to the codebase
*
* @param codebase
* a <code>String</code> that represent the specified directory
* @return the corresponding
* {@link <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/ClassLoader.html"><code>ClassLoader</code></a>}
* @throws MalformedURLException
* no legal protocol could be found in a specification string
*/
public final ClassLoader getClassLoader(String codebase)
throws MalformedURLException {
if (!noSecurityManager) {
securityManager.checkPermission(
new RuntimePermission("getClassLoader"));
} else {
return Thread.currentThread().getContextClassLoader();
}
return getClassLoaderFromCodebase(codebase);
}
/**
* Specified in the {@link java.rmi.server.RMIClassLoader}.
*
* @param codebase
* a <code>String</code> that represent the specified directory
* @return the corresponding
* {@link ClassLoader}
* @throws MalformedURLException
* no legal protocol could be found in a specification string
*/
private final ClassLoader getClassLoaderFromCodebase(String codebase)
throws MalformedURLException {
ClassLoader classLoader = null;
String tempCodebase = (codebase == null) ? codebaseProp : codebase;
/*
* The API Specification always assumes that the property
* java.rmi.server.codebase is correctly setted, and it does not specify
* what to do when returns null. In this case we always return
* Thread.currentThread().getContextClassLoader();
*/
if (tempCodebase == null) {
return Thread.currentThread().getContextClassLoader();
}
tempCodebase = sortURLs(tempCodebase);
Pair<String, ClassLoader> key = new Pair<String, ClassLoader>(
tempCodebase, Thread.currentThread().getContextClassLoader());
if (classLoaderMap.containsKey(key)) {
classLoader = classLoaderMap.get(key).get();
}
if (classLoader == null) {
URL[] urls = getURLs(codebase);
if (urls == null) {
return null;
}
for (URL url : urls) {
try {
securityManager.checkPermission(url.openConnection()
.getPermission());
} catch (IOException e) {
throw new SecurityException(e);
}
}
classLoader = new URLClassLoader(urls);
classLoaderMap.put(key, new WeakReference<URLClassLoader>(
(URLClassLoader) classLoader));
}
return classLoader;
}
/**
* Takes a <EM>space separated</EM> list of URL's as a String, and sorts
* it. For that purpose the String must be parsed.
*
* @param urls
* a list of URL's
* @return an alphabetic order list of URL's
*/
private final static String sortURLs(String urls) {
String ret = null;
if (urls != null) {
String[] codebaseSplit = urls.split("( )+");
if (codebaseSplit.length > 0) {
ret = new String();
Arrays.sort(codebaseSplit);
for (String url : codebaseSplit) {
ret += url + " ";
}
}
}
return ret;
}
/**
* Takes a <EM>space separated</EM> list of URL's as a <code>String</code>,
* and returns an array of URL's.
*
* @param urls
* a list of URL's as a <code>String</code>
* @return an array of URL's
* @throws MalformedURLException
* no legal protocol could be found in a specification string
*/
private final static URL[] getURLs(String urls) throws MalformedURLException {
URL[] realURLs = null;
if (urls == null) {
return realURLs;
}
String[] codebaseSplit = urls.split("( )+");
if (codebaseSplit.length > 0) {
realURLs = new URL[codebaseSplit.length];
for (int i = 0; i < codebaseSplit.length; i++) {
realURLs[i] = new URL(codebaseSplit[i]);
}
}
return realURLs;
}
}
|
apache-2.0
|
Squeezer-software/java-design-patterns
|
src/com/squeezer/designpatterns/abstractfactory/ProductA1.java
|
211
|
package com.squeezer.designpatterns.abstractfactory;
public class ProductA1 implements AbstractProductA {
@Override
public void display() {
System.out.println("Product A 1 display");
}
}
|
apache-2.0
|
spoon-bot/RxJava
|
src/test/java/io/reactivex/internal/operators/OperatorZipCompletionTest.java
|
3401
|
/**
* Copyright 2015 Netflix, 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.reactivex.internal.operators;
import static org.mockito.Mockito.*;
import java.util.function.BiFunction;
import org.junit.*;
import org.mockito.InOrder;
import org.reactivestreams.Subscriber;
import io.reactivex.*;
import io.reactivex.subjects.PublishSubject;
/**
* Systematically tests that when zipping an infinite and a finite Observable,
* the resulting Observable is finite.
*
*/
public class OperatorZipCompletionTest {
BiFunction<String, String, String> concat2Strings;
PublishSubject<String> s1;
PublishSubject<String> s2;
Observable<String> zipped;
Subscriber<String> observer;
InOrder inOrder;
@Before
public void setUp() {
concat2Strings = new BiFunction<String, String, String>() {
@Override
public String apply(String t1, String t2) {
return t1 + "-" + t2;
}
};
s1 = PublishSubject.create();
s2 = PublishSubject.create();
zipped = Observable.zip(s1, s2, concat2Strings);
observer = TestHelper.mockSubscriber();
inOrder = inOrder(observer);
zipped.subscribe(observer);
}
@Test
public void testFirstCompletesThenSecondInfinite() {
s1.onNext("a");
s1.onNext("b");
s1.onComplete();
s2.onNext("1");
inOrder.verify(observer, times(1)).onNext("a-1");
s2.onNext("2");
inOrder.verify(observer, times(1)).onNext("b-2");
inOrder.verify(observer, times(1)).onComplete();
inOrder.verifyNoMoreInteractions();
}
@Test
public void testSecondInfiniteThenFirstCompletes() {
s2.onNext("1");
s2.onNext("2");
s1.onNext("a");
inOrder.verify(observer, times(1)).onNext("a-1");
s1.onNext("b");
inOrder.verify(observer, times(1)).onNext("b-2");
s1.onComplete();
inOrder.verify(observer, times(1)).onComplete();
inOrder.verifyNoMoreInteractions();
}
@Test
public void testSecondCompletesThenFirstInfinite() {
s2.onNext("1");
s2.onNext("2");
s2.onComplete();
s1.onNext("a");
inOrder.verify(observer, times(1)).onNext("a-1");
s1.onNext("b");
inOrder.verify(observer, times(1)).onNext("b-2");
inOrder.verify(observer, times(1)).onComplete();
inOrder.verifyNoMoreInteractions();
}
@Test
public void testFirstInfiniteThenSecondCompletes() {
s1.onNext("a");
s1.onNext("b");
s2.onNext("1");
inOrder.verify(observer, times(1)).onNext("a-1");
s2.onNext("2");
inOrder.verify(observer, times(1)).onNext("b-2");
s2.onComplete();
inOrder.verify(observer, times(1)).onComplete();
inOrder.verifyNoMoreInteractions();
}
}
|
apache-2.0
|
realityforge/arez
|
processor/src/test/fixtures/input/com/example/reference/LazyLoadObservableReferenceModel.java
|
490
|
package com.example.reference;
import arez.annotations.ArezComponent;
import arez.annotations.LinkType;
import arez.annotations.Observable;
import arez.annotations.Reference;
import arez.annotations.ReferenceId;
@ArezComponent
abstract class LazyLoadObservableReferenceModel
{
@Reference( load = LinkType.LAZY )
abstract MyEntity getMyEntity();
@ReferenceId
@Observable
abstract int getMyEntityId();
abstract void setMyEntityId( int id );
static class MyEntity
{
}
}
|
apache-2.0
|
linzhaoming/origin
|
vendor/github.com/Azure/azure-sdk-for-go/services/advisor/mgmt/2017-04-19/advisor/models.go
|
25984
|
package advisor
// Copyright (c) Microsoft and contributors. 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.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"encoding/json"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/date"
"github.com/Azure/go-autorest/autorest/to"
"github.com/satori/go.uuid"
"net/http"
)
// Category enumerates the values for category.
type Category string
const (
// Cost ...
Cost Category = "Cost"
// HighAvailability ...
HighAvailability Category = "HighAvailability"
// Performance ...
Performance Category = "Performance"
// Security ...
Security Category = "Security"
)
// PossibleCategoryValues returns an array of possible values for the Category const type.
func PossibleCategoryValues() []Category {
return []Category{Cost, HighAvailability, Performance, Security}
}
// Impact enumerates the values for impact.
type Impact string
const (
// High ...
High Impact = "High"
// Low ...
Low Impact = "Low"
// Medium ...
Medium Impact = "Medium"
)
// PossibleImpactValues returns an array of possible values for the Impact const type.
func PossibleImpactValues() []Impact {
return []Impact{High, Low, Medium}
}
// Risk enumerates the values for risk.
type Risk string
const (
// Error ...
Error Risk = "Error"
// None ...
None Risk = "None"
// Warning ...
Warning Risk = "Warning"
)
// PossibleRiskValues returns an array of possible values for the Risk const type.
func PossibleRiskValues() []Risk {
return []Risk{Error, None, Warning}
}
// ARMErrorResponseBody ARM error response body.
type ARMErrorResponseBody struct {
autorest.Response `json:"-"`
// Message - Gets or sets the string that describes the error in detail and provides debugging information.
Message *string `json:"message,omitempty"`
// Code - Gets or sets the string that can be used to programmatically identify the error.
Code *string `json:"code,omitempty"`
}
// ConfigData the Advisor configuration data structure.
type ConfigData struct {
// ID - The resource Id of the configuration resource.
ID *string `json:"id,omitempty"`
// Type - The type of the configuration resource.
Type *string `json:"type,omitempty"`
// Name - The name of the configuration resource.
Name *string `json:"name,omitempty"`
// Properties - The list of property name/value pairs.
Properties *ConfigDataProperties `json:"properties,omitempty"`
}
// ConfigDataProperties the list of property name/value pairs.
type ConfigDataProperties struct {
// AdditionalProperties - Unmatched properties from the message are deserialized this collection
AdditionalProperties map[string]interface{} `json:""`
// Exclude - Exclude the resource from Advisor evaluations. Valid values: False (default) or True.
Exclude *bool `json:"exclude,omitempty"`
// LowCPUThreshold - Minimum percentage threshold for Advisor low CPU utilization evaluation. Valid only for subscriptions. Valid values: 5 (default), 10, 15 or 20.
LowCPUThreshold *string `json:"low_cpu_threshold,omitempty"`
}
// MarshalJSON is the custom marshaler for ConfigDataProperties.
func (cd ConfigDataProperties) MarshalJSON() ([]byte, error) {
objectMap := make(map[string]interface{})
if cd.Exclude != nil {
objectMap["exclude"] = cd.Exclude
}
if cd.LowCPUThreshold != nil {
objectMap["low_cpu_threshold"] = cd.LowCPUThreshold
}
for k, v := range cd.AdditionalProperties {
objectMap[k] = v
}
return json.Marshal(objectMap)
}
// ConfigurationListResult the list of Advisor configurations.
type ConfigurationListResult struct {
autorest.Response `json:"-"`
// Value - The list of configurations.
Value *[]ConfigData `json:"value,omitempty"`
// NextLink - The link used to get the next page of configurations.
NextLink *string `json:"nextLink,omitempty"`
}
// ConfigurationListResultIterator provides access to a complete listing of ConfigData values.
type ConfigurationListResultIterator struct {
i int
page ConfigurationListResultPage
}
// Next advances to the next value. If there was an error making
// the request the iterator does not advance and the error is returned.
func (iter *ConfigurationListResultIterator) Next() error {
iter.i++
if iter.i < len(iter.page.Values()) {
return nil
}
err := iter.page.Next()
if err != nil {
iter.i--
return err
}
iter.i = 0
return nil
}
// NotDone returns true if the enumeration should be started or is not yet complete.
func (iter ConfigurationListResultIterator) NotDone() bool {
return iter.page.NotDone() && iter.i < len(iter.page.Values())
}
// Response returns the raw server response from the last page request.
func (iter ConfigurationListResultIterator) Response() ConfigurationListResult {
return iter.page.Response()
}
// Value returns the current value or a zero-initialized value if the
// iterator has advanced beyond the end of the collection.
func (iter ConfigurationListResultIterator) Value() ConfigData {
if !iter.page.NotDone() {
return ConfigData{}
}
return iter.page.Values()[iter.i]
}
// IsEmpty returns true if the ListResult contains no values.
func (clr ConfigurationListResult) IsEmpty() bool {
return clr.Value == nil || len(*clr.Value) == 0
}
// configurationListResultPreparer prepares a request to retrieve the next set of results.
// It returns nil if no more results exist.
func (clr ConfigurationListResult) configurationListResultPreparer() (*http.Request, error) {
if clr.NextLink == nil || len(to.String(clr.NextLink)) < 1 {
return nil, nil
}
return autorest.Prepare(&http.Request{},
autorest.AsJSON(),
autorest.AsGet(),
autorest.WithBaseURL(to.String(clr.NextLink)))
}
// ConfigurationListResultPage contains a page of ConfigData values.
type ConfigurationListResultPage struct {
fn func(ConfigurationListResult) (ConfigurationListResult, error)
clr ConfigurationListResult
}
// Next advances to the next page of values. If there was an error making
// the request the page does not advance and the error is returned.
func (page *ConfigurationListResultPage) Next() error {
next, err := page.fn(page.clr)
if err != nil {
return err
}
page.clr = next
return nil
}
// NotDone returns true if the page enumeration should be started or is not yet complete.
func (page ConfigurationListResultPage) NotDone() bool {
return !page.clr.IsEmpty()
}
// Response returns the raw server response from the last page request.
func (page ConfigurationListResultPage) Response() ConfigurationListResult {
return page.clr
}
// Values returns the slice of values for the current page or nil if there are no values.
func (page ConfigurationListResultPage) Values() []ConfigData {
if page.clr.IsEmpty() {
return nil
}
return *page.clr.Value
}
// OperationDisplayInfo the operation supported by Advisor.
type OperationDisplayInfo struct {
// Description - The description of the operation.
Description *string `json:"description,omitempty"`
// Operation - The action that users can perform, based on their permission level.
Operation *string `json:"operation,omitempty"`
// Provider - Service provider: Microsoft Advisor.
Provider *string `json:"provider,omitempty"`
// Resource - Resource on which the operation is performed.
Resource *string `json:"resource,omitempty"`
}
// OperationEntity the operation supported by Advisor.
type OperationEntity struct {
// Name - Operation name: {provider}/{resource}/{operation}.
Name *string `json:"name,omitempty"`
// Display - The operation supported by Advisor.
Display *OperationDisplayInfo `json:"display,omitempty"`
}
// OperationEntityListResult the list of Advisor operations.
type OperationEntityListResult struct {
autorest.Response `json:"-"`
// NextLink - The link used to get the next page of operations.
NextLink *string `json:"nextLink,omitempty"`
// Value - The list of operations.
Value *[]OperationEntity `json:"value,omitempty"`
}
// OperationEntityListResultIterator provides access to a complete listing of OperationEntity values.
type OperationEntityListResultIterator struct {
i int
page OperationEntityListResultPage
}
// Next advances to the next value. If there was an error making
// the request the iterator does not advance and the error is returned.
func (iter *OperationEntityListResultIterator) Next() error {
iter.i++
if iter.i < len(iter.page.Values()) {
return nil
}
err := iter.page.Next()
if err != nil {
iter.i--
return err
}
iter.i = 0
return nil
}
// NotDone returns true if the enumeration should be started or is not yet complete.
func (iter OperationEntityListResultIterator) NotDone() bool {
return iter.page.NotDone() && iter.i < len(iter.page.Values())
}
// Response returns the raw server response from the last page request.
func (iter OperationEntityListResultIterator) Response() OperationEntityListResult {
return iter.page.Response()
}
// Value returns the current value or a zero-initialized value if the
// iterator has advanced beyond the end of the collection.
func (iter OperationEntityListResultIterator) Value() OperationEntity {
if !iter.page.NotDone() {
return OperationEntity{}
}
return iter.page.Values()[iter.i]
}
// IsEmpty returns true if the ListResult contains no values.
func (oelr OperationEntityListResult) IsEmpty() bool {
return oelr.Value == nil || len(*oelr.Value) == 0
}
// operationEntityListResultPreparer prepares a request to retrieve the next set of results.
// It returns nil if no more results exist.
func (oelr OperationEntityListResult) operationEntityListResultPreparer() (*http.Request, error) {
if oelr.NextLink == nil || len(to.String(oelr.NextLink)) < 1 {
return nil, nil
}
return autorest.Prepare(&http.Request{},
autorest.AsJSON(),
autorest.AsGet(),
autorest.WithBaseURL(to.String(oelr.NextLink)))
}
// OperationEntityListResultPage contains a page of OperationEntity values.
type OperationEntityListResultPage struct {
fn func(OperationEntityListResult) (OperationEntityListResult, error)
oelr OperationEntityListResult
}
// Next advances to the next page of values. If there was an error making
// the request the page does not advance and the error is returned.
func (page *OperationEntityListResultPage) Next() error {
next, err := page.fn(page.oelr)
if err != nil {
return err
}
page.oelr = next
return nil
}
// NotDone returns true if the page enumeration should be started or is not yet complete.
func (page OperationEntityListResultPage) NotDone() bool {
return !page.oelr.IsEmpty()
}
// Response returns the raw server response from the last page request.
func (page OperationEntityListResultPage) Response() OperationEntityListResult {
return page.oelr
}
// Values returns the slice of values for the current page or nil if there are no values.
func (page OperationEntityListResultPage) Values() []OperationEntity {
if page.oelr.IsEmpty() {
return nil
}
return *page.oelr.Value
}
// RecommendationProperties the properties of the recommendation.
type RecommendationProperties struct {
// Category - The category of the recommendation. Possible values include: 'HighAvailability', 'Security', 'Performance', 'Cost'
Category Category `json:"category,omitempty"`
// Impact - The business impact of the recommendation. Possible values include: 'High', 'Medium', 'Low'
Impact Impact `json:"impact,omitempty"`
// ImpactedField - The resource type identified by Advisor.
ImpactedField *string `json:"impactedField,omitempty"`
// ImpactedValue - The resource identified by Advisor.
ImpactedValue *string `json:"impactedValue,omitempty"`
// LastUpdated - The most recent time that Advisor checked the validity of the recommendation.
LastUpdated *date.Time `json:"lastUpdated,omitempty"`
// Metadata - The recommendation metadata.
Metadata map[string]interface{} `json:"metadata"`
// RecommendationTypeID - The recommendation-type GUID.
RecommendationTypeID *string `json:"recommendationTypeId,omitempty"`
// Risk - The potential risk of not implementing the recommendation. Possible values include: 'Error', 'Warning', 'None'
Risk Risk `json:"risk,omitempty"`
// ShortDescription - A summary of the recommendation.
ShortDescription *ShortDescription `json:"shortDescription,omitempty"`
// SuppressionIds - The list of snoozed and dismissed rules for the recommendation.
SuppressionIds *[]uuid.UUID `json:"suppressionIds,omitempty"`
}
// MarshalJSON is the custom marshaler for RecommendationProperties.
func (rp RecommendationProperties) MarshalJSON() ([]byte, error) {
objectMap := make(map[string]interface{})
if rp.Category != "" {
objectMap["category"] = rp.Category
}
if rp.Impact != "" {
objectMap["impact"] = rp.Impact
}
if rp.ImpactedField != nil {
objectMap["impactedField"] = rp.ImpactedField
}
if rp.ImpactedValue != nil {
objectMap["impactedValue"] = rp.ImpactedValue
}
if rp.LastUpdated != nil {
objectMap["lastUpdated"] = rp.LastUpdated
}
if rp.Metadata != nil {
objectMap["metadata"] = rp.Metadata
}
if rp.RecommendationTypeID != nil {
objectMap["recommendationTypeId"] = rp.RecommendationTypeID
}
if rp.Risk != "" {
objectMap["risk"] = rp.Risk
}
if rp.ShortDescription != nil {
objectMap["shortDescription"] = rp.ShortDescription
}
if rp.SuppressionIds != nil {
objectMap["suppressionIds"] = rp.SuppressionIds
}
return json.Marshal(objectMap)
}
// Resource an Azure resource.
type Resource struct {
// ID - The resource ID.
ID *string `json:"id,omitempty"`
// Name - The name of the resource.
Name *string `json:"name,omitempty"`
// Type - The type of the resource.
Type *string `json:"type,omitempty"`
}
// ResourceRecommendationBase advisor Recommendation.
type ResourceRecommendationBase struct {
autorest.Response `json:"-"`
// RecommendationProperties - The properties of the recommendation.
*RecommendationProperties `json:"properties,omitempty"`
// ID - The resource ID.
ID *string `json:"id,omitempty"`
// Name - The name of the resource.
Name *string `json:"name,omitempty"`
// Type - The type of the resource.
Type *string `json:"type,omitempty"`
}
// MarshalJSON is the custom marshaler for ResourceRecommendationBase.
func (rrb ResourceRecommendationBase) MarshalJSON() ([]byte, error) {
objectMap := make(map[string]interface{})
if rrb.RecommendationProperties != nil {
objectMap["properties"] = rrb.RecommendationProperties
}
if rrb.ID != nil {
objectMap["id"] = rrb.ID
}
if rrb.Name != nil {
objectMap["name"] = rrb.Name
}
if rrb.Type != nil {
objectMap["type"] = rrb.Type
}
return json.Marshal(objectMap)
}
// UnmarshalJSON is the custom unmarshaler for ResourceRecommendationBase struct.
func (rrb *ResourceRecommendationBase) UnmarshalJSON(body []byte) error {
var m map[string]*json.RawMessage
err := json.Unmarshal(body, &m)
if err != nil {
return err
}
for k, v := range m {
switch k {
case "properties":
if v != nil {
var recommendationProperties RecommendationProperties
err = json.Unmarshal(*v, &recommendationProperties)
if err != nil {
return err
}
rrb.RecommendationProperties = &recommendationProperties
}
case "id":
if v != nil {
var ID string
err = json.Unmarshal(*v, &ID)
if err != nil {
return err
}
rrb.ID = &ID
}
case "name":
if v != nil {
var name string
err = json.Unmarshal(*v, &name)
if err != nil {
return err
}
rrb.Name = &name
}
case "type":
if v != nil {
var typeVar string
err = json.Unmarshal(*v, &typeVar)
if err != nil {
return err
}
rrb.Type = &typeVar
}
}
}
return nil
}
// ResourceRecommendationBaseListResult the list of Advisor recommendations.
type ResourceRecommendationBaseListResult struct {
autorest.Response `json:"-"`
// NextLink - The link used to get the next page of recommendations.
NextLink *string `json:"nextLink,omitempty"`
// Value - The list of recommendations.
Value *[]ResourceRecommendationBase `json:"value,omitempty"`
}
// ResourceRecommendationBaseListResultIterator provides access to a complete listing of ResourceRecommendationBase
// values.
type ResourceRecommendationBaseListResultIterator struct {
i int
page ResourceRecommendationBaseListResultPage
}
// Next advances to the next value. If there was an error making
// the request the iterator does not advance and the error is returned.
func (iter *ResourceRecommendationBaseListResultIterator) Next() error {
iter.i++
if iter.i < len(iter.page.Values()) {
return nil
}
err := iter.page.Next()
if err != nil {
iter.i--
return err
}
iter.i = 0
return nil
}
// NotDone returns true if the enumeration should be started or is not yet complete.
func (iter ResourceRecommendationBaseListResultIterator) NotDone() bool {
return iter.page.NotDone() && iter.i < len(iter.page.Values())
}
// Response returns the raw server response from the last page request.
func (iter ResourceRecommendationBaseListResultIterator) Response() ResourceRecommendationBaseListResult {
return iter.page.Response()
}
// Value returns the current value or a zero-initialized value if the
// iterator has advanced beyond the end of the collection.
func (iter ResourceRecommendationBaseListResultIterator) Value() ResourceRecommendationBase {
if !iter.page.NotDone() {
return ResourceRecommendationBase{}
}
return iter.page.Values()[iter.i]
}
// IsEmpty returns true if the ListResult contains no values.
func (rrblr ResourceRecommendationBaseListResult) IsEmpty() bool {
return rrblr.Value == nil || len(*rrblr.Value) == 0
}
// resourceRecommendationBaseListResultPreparer prepares a request to retrieve the next set of results.
// It returns nil if no more results exist.
func (rrblr ResourceRecommendationBaseListResult) resourceRecommendationBaseListResultPreparer() (*http.Request, error) {
if rrblr.NextLink == nil || len(to.String(rrblr.NextLink)) < 1 {
return nil, nil
}
return autorest.Prepare(&http.Request{},
autorest.AsJSON(),
autorest.AsGet(),
autorest.WithBaseURL(to.String(rrblr.NextLink)))
}
// ResourceRecommendationBaseListResultPage contains a page of ResourceRecommendationBase values.
type ResourceRecommendationBaseListResultPage struct {
fn func(ResourceRecommendationBaseListResult) (ResourceRecommendationBaseListResult, error)
rrblr ResourceRecommendationBaseListResult
}
// Next advances to the next page of values. If there was an error making
// the request the page does not advance and the error is returned.
func (page *ResourceRecommendationBaseListResultPage) Next() error {
next, err := page.fn(page.rrblr)
if err != nil {
return err
}
page.rrblr = next
return nil
}
// NotDone returns true if the page enumeration should be started or is not yet complete.
func (page ResourceRecommendationBaseListResultPage) NotDone() bool {
return !page.rrblr.IsEmpty()
}
// Response returns the raw server response from the last page request.
func (page ResourceRecommendationBaseListResultPage) Response() ResourceRecommendationBaseListResult {
return page.rrblr
}
// Values returns the slice of values for the current page or nil if there are no values.
func (page ResourceRecommendationBaseListResultPage) Values() []ResourceRecommendationBase {
if page.rrblr.IsEmpty() {
return nil
}
return *page.rrblr.Value
}
// ShortDescription a summary of the recommendation.
type ShortDescription struct {
// Problem - The issue or opportunity identified by the recommendation.
Problem *string `json:"problem,omitempty"`
// Solution - The remediation action suggested by the recommendation.
Solution *string `json:"solution,omitempty"`
}
// SuppressionContract the details of the snoozed or dismissed rule; for example, the duration, name, and GUID
// associated with the rule.
type SuppressionContract struct {
autorest.Response `json:"-"`
// SuppressionProperties - The properties of the suppression.
*SuppressionProperties `json:"properties,omitempty"`
// ID - The resource ID.
ID *string `json:"id,omitempty"`
// Name - The name of the resource.
Name *string `json:"name,omitempty"`
// Type - The type of the resource.
Type *string `json:"type,omitempty"`
}
// MarshalJSON is the custom marshaler for SuppressionContract.
func (sc SuppressionContract) MarshalJSON() ([]byte, error) {
objectMap := make(map[string]interface{})
if sc.SuppressionProperties != nil {
objectMap["properties"] = sc.SuppressionProperties
}
if sc.ID != nil {
objectMap["id"] = sc.ID
}
if sc.Name != nil {
objectMap["name"] = sc.Name
}
if sc.Type != nil {
objectMap["type"] = sc.Type
}
return json.Marshal(objectMap)
}
// UnmarshalJSON is the custom unmarshaler for SuppressionContract struct.
func (sc *SuppressionContract) UnmarshalJSON(body []byte) error {
var m map[string]*json.RawMessage
err := json.Unmarshal(body, &m)
if err != nil {
return err
}
for k, v := range m {
switch k {
case "properties":
if v != nil {
var suppressionProperties SuppressionProperties
err = json.Unmarshal(*v, &suppressionProperties)
if err != nil {
return err
}
sc.SuppressionProperties = &suppressionProperties
}
case "id":
if v != nil {
var ID string
err = json.Unmarshal(*v, &ID)
if err != nil {
return err
}
sc.ID = &ID
}
case "name":
if v != nil {
var name string
err = json.Unmarshal(*v, &name)
if err != nil {
return err
}
sc.Name = &name
}
case "type":
if v != nil {
var typeVar string
err = json.Unmarshal(*v, &typeVar)
if err != nil {
return err
}
sc.Type = &typeVar
}
}
}
return nil
}
// SuppressionContractListResult the list of Advisor suppressions.
type SuppressionContractListResult struct {
autorest.Response `json:"-"`
// NextLink - The link used to get the next page of suppressions.
NextLink *string `json:"nextLink,omitempty"`
// Value - The list of suppressions.
Value *[]SuppressionContract `json:"value,omitempty"`
}
// SuppressionContractListResultIterator provides access to a complete listing of SuppressionContract values.
type SuppressionContractListResultIterator struct {
i int
page SuppressionContractListResultPage
}
// Next advances to the next value. If there was an error making
// the request the iterator does not advance and the error is returned.
func (iter *SuppressionContractListResultIterator) Next() error {
iter.i++
if iter.i < len(iter.page.Values()) {
return nil
}
err := iter.page.Next()
if err != nil {
iter.i--
return err
}
iter.i = 0
return nil
}
// NotDone returns true if the enumeration should be started or is not yet complete.
func (iter SuppressionContractListResultIterator) NotDone() bool {
return iter.page.NotDone() && iter.i < len(iter.page.Values())
}
// Response returns the raw server response from the last page request.
func (iter SuppressionContractListResultIterator) Response() SuppressionContractListResult {
return iter.page.Response()
}
// Value returns the current value or a zero-initialized value if the
// iterator has advanced beyond the end of the collection.
func (iter SuppressionContractListResultIterator) Value() SuppressionContract {
if !iter.page.NotDone() {
return SuppressionContract{}
}
return iter.page.Values()[iter.i]
}
// IsEmpty returns true if the ListResult contains no values.
func (sclr SuppressionContractListResult) IsEmpty() bool {
return sclr.Value == nil || len(*sclr.Value) == 0
}
// suppressionContractListResultPreparer prepares a request to retrieve the next set of results.
// It returns nil if no more results exist.
func (sclr SuppressionContractListResult) suppressionContractListResultPreparer() (*http.Request, error) {
if sclr.NextLink == nil || len(to.String(sclr.NextLink)) < 1 {
return nil, nil
}
return autorest.Prepare(&http.Request{},
autorest.AsJSON(),
autorest.AsGet(),
autorest.WithBaseURL(to.String(sclr.NextLink)))
}
// SuppressionContractListResultPage contains a page of SuppressionContract values.
type SuppressionContractListResultPage struct {
fn func(SuppressionContractListResult) (SuppressionContractListResult, error)
sclr SuppressionContractListResult
}
// Next advances to the next page of values. If there was an error making
// the request the page does not advance and the error is returned.
func (page *SuppressionContractListResultPage) Next() error {
next, err := page.fn(page.sclr)
if err != nil {
return err
}
page.sclr = next
return nil
}
// NotDone returns true if the page enumeration should be started or is not yet complete.
func (page SuppressionContractListResultPage) NotDone() bool {
return !page.sclr.IsEmpty()
}
// Response returns the raw server response from the last page request.
func (page SuppressionContractListResultPage) Response() SuppressionContractListResult {
return page.sclr
}
// Values returns the slice of values for the current page or nil if there are no values.
func (page SuppressionContractListResultPage) Values() []SuppressionContract {
if page.sclr.IsEmpty() {
return nil
}
return *page.sclr.Value
}
// SuppressionProperties the properties of the suppression.
type SuppressionProperties struct {
// SuppressionID - The GUID of the suppression.
SuppressionID *string `json:"suppressionId,omitempty"`
// TTL - The duration for which the suppression is valid.
TTL *string `json:"ttl,omitempty"`
}
|
apache-2.0
|
erocci/erocci
|
doc/occi_renderer_xml.md
|
1057
|
# Module occi_renderer_xml #
* [Description](#description)
* [Function Index](#index)
* [Function Details](#functions)
.
Copyright (c) (C) 2016, Jean Parpaillon
__Authors:__ Jean Parpaillon ([`[email protected]`](mailto:[email protected])).
<a name="index"></a>
## Function Index ##
<table width="100%" border="1" cellspacing="0" cellpadding="2" summary="function index"><tr><td valign="top"><a href="#render-2">render/2</a></td><td></td></tr><tr><td valign="top"><a href="#to_xml-3">to_xml/3</a></td><td></td></tr></table>
<a name="functions"></a>
## Function Details ##
<a name="render-2"></a>
### render/2 ###
<pre><code>
render(T::<a href="occi_type.md#type-t">occi_type:t()</a>, Ctx::<a href="occi_uri.md#type-t">occi_uri:t()</a>) -> iolist()
</code></pre>
<br />
<a name="to_xml-3"></a>
### to_xml/3 ###
<pre><code>
to_xml(TypeName::<a href="occi_type.md#type-name">occi_type:name()</a>, T::<a href="occi_type.md#type-t">occi_type:t()</a>, Ctx::<a href="uri.md#type-t">uri:t()</a>) -> tuple()
</code></pre>
<br />
|
apache-2.0
|
diegobqb/veboMaven
|
src/main/java/br/com/vebo/dados/mapeamento/MovimentacaoEstoqueEnum.java
|
236
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package br.com.vebo.dados.mapeamento;
/**
*
* @author mohfus
*/
public enum MovimentacaoEstoqueEnum {
ENTRADA,
RETIRADA;
}
|
apache-2.0
|
BitGo/BitGoJS
|
modules/express/test/unit/bitgoExpress.ts
|
14766
|
import * as should from 'should';
import 'should-http';
import 'should-sinon';
import '../lib/asserts';
import * as nock from 'nock';
import * as sinon from 'sinon';
import * as fs from 'fs';
import * as http from 'http';
import * as https from 'https';
import * as debugLib from 'debug';
import * as path from 'path';
import { Environments } from 'bitgo';
import { coroutine as co } from 'bluebird';
import { SSL_OP_NO_TLSv1 } from 'constants';
import { TlsConfigurationError, NodeEnvironmentError } from '../../src/errors';
nock.disableNetConnect();
import {
app as expressApp,
startup,
createServer,
createBaseUri,
prepareIpc,
} from '../../src/expressApp';
import * as clientRoutes from '../../src/clientRoutes';
describe('Bitgo Express', function () {
describe('server initialization', function () {
const validPrvJSON =
'{"61f039aad587c2000745c687373e0fa9":"xprv9s21ZrQH143K3EuPWCBuqnWxydaQV6et9htQige4EswvcHKEzNmkVmwTwKoadyHzJYppuADB7Us7AbaNLToNvoFoSxuWqndQRYtnNy5DUY2"}';
it('should require NODE_ENV to be production when running against prod env', function () {
const envStub = sinon.stub(process, 'env').value({ NODE_ENV: 'production' });
try {
(() => expressApp({
env: 'prod',
bind: 'localhost',
} as any)).should.not.throw();
process.env.NODE_ENV = 'dev';
(() => expressApp({
env: 'prod',
bind: 'localhost',
} as any)).should.throw(NodeEnvironmentError);
} finally {
envStub.restore();
}
});
it('should disable NODE_ENV check if disableenvcheck argument is given', function () {
const envStub = sinon.stub(process, 'env').value({ NODE_ENV: 'dev' });
try {
(() => expressApp({
env: 'prod',
bind: 'localhost',
disableEnvCheck: true,
} as any)).should.not.throw();
} finally {
envStub.restore();
}
});
it('should require TLS for prod env when listening on external interfaces', function () {
const args: any = {
env: 'prod',
bind: '1',
disableEnvCheck: true,
disableSSL: false,
crtPath: undefined as string | undefined,
keyPath: undefined as string | undefined,
};
(() => expressApp(args)).should.throw(TlsConfigurationError);
args.bind = 'localhost';
(() => expressApp(args)).should.not.throw();
args.bind = '1';
args.env = 'test';
(() => expressApp(args)).should.not.throw();
args.disableSSL = true;
args.env = 'prod';
(() => expressApp(args)).should.not.throw();
delete args.disableSSL;
args.crtPath = '/tmp/cert.pem';
(() => expressApp(args)).should.throw(TlsConfigurationError);
delete args.crtPath;
args.keyPath = '/tmp/key.pem';
(() => expressApp(args)).should.throw(TlsConfigurationError);
});
it('should require both keypath and crtpath when using TLS, but TLS is not required', function () {
const args: any = {
env: 'test',
bind: '1',
keyPath: '/tmp/key.pem',
crtPath: undefined as string | undefined,
};
(() => expressApp(args)).should.throw(TlsConfigurationError);
delete args.keyPath;
args.crtPath = '/tmp/cert.pem';
(() => expressApp(args)).should.throw(TlsConfigurationError);
});
it('should create an http server when not using TLS', co(function *() {
const createServerStub = sinon.stub(http, 'createServer');
const args: any = {
env: 'prod',
bind: 'localhost',
};
createServer(args, null as any);
createServerStub.should.be.calledOnce();
createServerStub.restore();
}));
it('should create an https server when using TLS', co(function *() {
const createServerStub = sinon.stub(https, 'createServer');
const readFileAsyncStub = sinon.stub(fs.promises, 'readFile' as any)
.onFirstCall().resolves('key')
.onSecondCall().resolves('cert');
const args: any = {
env: 'prod',
bind: '1.2.3.4',
crtPath: '/tmp/crt.pem',
keyPath: '/tmp/key.pem',
};
yield createServer(args, null as any);
https.createServer.should.be.calledOnce();
https.createServer.should.be.calledWith({ secureOptions: SSL_OP_NO_TLSv1, key: 'key', cert: 'cert' });
createServerStub.restore();
readFileAsyncStub.restore();
}));
it('should output basic information upon server startup', () => {
const logStub = sinon.stub(console, 'log');
const args: any = {
env: 'test',
};
startup(args, 'base')();
logStub.should.have.callCount(3);
logStub.should.have.been.calledWith('BitGo-Express running');
logStub.should.have.been.calledWith(`Environment: ${args.env}`);
logStub.should.have.been.calledWith('Base URI: base');
logStub.restore();
});
it('should output custom root uri information upon server startup', () => {
const logStub = sinon.stub(console, 'log');
const args: any = {
env: 'test',
customRootUri: 'customuri',
};
startup(args, 'base')();
logStub.should.have.callCount(4);
logStub.should.have.been.calledWith('BitGo-Express running');
logStub.should.have.been.calledWith(`Environment: ${args.env}`);
logStub.should.have.been.calledWith('Base URI: base');
logStub.should.have.been.calledWith(`Custom root URI: ${args.customRootUri}`);
logStub.restore();
});
it('should output custom bitcoin network information upon server startup', () => {
const logStub = sinon.stub(console, 'log');
const args: any = {
env: 'test',
customBitcoinNetwork: 'customnetwork',
};
startup(args, 'base')();
logStub.should.have.callCount(4);
logStub.should.have.been.calledWith('BitGo-Express running');
logStub.should.have.been.calledWith(`Environment: ${args.env}`);
logStub.should.have.been.calledWith('Base URI: base');
logStub.should.have.been.calledWith(`Custom bitcoin network: ${args.customBitcoinNetwork}`);
logStub.restore();
});
it('should output signer mode upon server startup', () => {
const logStub = sinon.stub(console, 'log');
const args: any = {
env: 'test',
signerMode: 'signerMode',
};
startup(args, 'base')();
logStub.should.have.callCount(4);
logStub.should.have.been.calledWith('BitGo-Express running');
logStub.should.have.been.calledWith(`Environment: ${args.env}`);
logStub.should.have.been.calledWith('Base URI: base');
logStub.should.have.been.calledWith(`External signer mode: ${args.signerMode}`);
logStub.restore();
});
it('should create http base URIs', () => {
const args: any = {
bind: '1',
port: 2,
};
createBaseUri(args).should.equal(`http://${args.bind}:${args.port}`);
args.port = 80;
createBaseUri(args).should.equal(`http://${args.bind}`);
args.port = 443;
createBaseUri(args).should.equal(`http://${args.bind}:443`);
});
it('should create https base URIs', () => {
const args: any = {
bind: '6',
port: 8,
keyPath: '3',
crtPath: '4',
};
createBaseUri(args).should.equal(`https://${args.bind}:${args.port}`);
args.port = 80;
createBaseUri(args).should.equal(`https://${args.bind}:80`);
args.port = 443;
createBaseUri(args).should.equal(`https://${args.bind}`);
});
it('should set up logging with a logfile', () => {
const resolveSpy = sinon.spy(path, 'resolve');
const createWriteStreamSpy = sinon.spy(fs, 'createWriteStream');
const logStub = sinon.stub(console, 'log');
const args: any = {
logFile: '/dev/null',
disableProxy: true,
};
expressApp(args);
path.resolve.should.have.been.calledWith(args.logFile);
fs.createWriteStream.should.have.been.calledOnceWith(args.logFile, { flags: 'a' });
logStub.should.have.been.calledOnceWith(`Log location: ${args.logFile}`);
resolveSpy.restore();
createWriteStreamSpy.restore();
logStub.restore();
});
it('should enable specified debug namespaces', () => {
const enableStub = sinon.stub(debugLib, 'enable');
const args: any = {
debugNamespace: ['a', 'b'],
disableProxy: true,
};
expressApp(args);
enableStub.should.have.been.calledTwice();
enableStub.should.have.been.calledWith(args.debugNamespace[0]);
enableStub.should.have.been.calledWith(args.debugNamespace[1]);
enableStub.restore();
});
it('should configure a custom root URI', () => {
const args: any = {
customRootUri: 'customroot',
env: undefined as string | undefined,
};
expressApp(args);
should(args.env).equal('custom');
Environments.custom.uri.should.equal(args.customRootUri);
});
it('should configure a custom bitcoin network', () => {
const args: any = {
customBitcoinNetwork: 'custombitcoinnetwork',
env: undefined as string | undefined,
};
expressApp(args);
should(args.env).equal('custom');
Environments.custom.network.should.equal(args.customBitcoinNetwork);
});
it('should fail if IPC option is used on windows', async () => {
const platformStub = sinon.stub(process, 'platform').value('win32');
await prepareIpc('testipc').should.be.rejectedWith(/^IPC option is not supported on platform/);
platformStub.restore();
});
it('should not remove the IPC socket if it doesn\'t exist', async () => {
const statStub = sinon.stub(fs, 'statSync').throws({ code: 'ENOENT' });
const unlinkStub = sinon.stub(fs, 'unlinkSync');
await prepareIpc('testipc').should.be.resolved();
unlinkStub.notCalled.should.be.true();
statStub.restore();
unlinkStub.restore();
});
it('should remove the socket before binding if IPC socket exists and is a socket', async () => {
const statStub = sinon.stub(fs, 'statSync').returns(
{ isSocket: () => true } as unknown as fs.Stats,
);
const unlinkStub = sinon.stub(fs, 'unlinkSync');
await prepareIpc('testipc').should.be.resolved();
unlinkStub.calledWithExactly('testipc').should.be.true();
unlinkStub.calledOnce.should.be.true();
statStub.restore();
unlinkStub.restore();
});
it('should fail if IPC socket is not actually a socket', async () => {
const statStub = sinon.stub(fs, 'statSync').returns(
{ isSocket: () => false } as unknown as fs.Stats,
);
const unlinkStub = sinon.stub(fs, 'unlinkSync');
await prepareIpc('testipc').should.be.rejectedWith(/IPC socket is not actually a socket/);
unlinkStub.notCalled.should.be.true();
statStub.restore();
unlinkStub.restore();
});
it('should print the IPC socket path on startup', async () => {
const logStub = sinon.stub(console, 'log');
const args: any = {
env: 'test',
customRootUri: 'customuri',
ipc: 'expressIPC',
};
startup(args, 'base')();
logStub.should.have.been.calledWith('IPC path: expressIPC');
logStub.restore();
});
it('should only call setupAPIRoutes when running in regular mode', () => {
const args: any = {
env: 'test',
signerMode: undefined,
};
const apiStub = sinon.stub(clientRoutes, 'setupAPIRoutes');
const signerStub = sinon.stub(clientRoutes, 'setupSigningRoutes');
expressApp(args);
apiStub.should.have.been.calledOnce();
signerStub.called.should.be.false();
apiStub.restore();
signerStub.restore();
});
it('should only call setupSigningRoutes when running in signer mode', () => {
const args: any = {
env: 'test',
signerMode: 'signerMode',
signerFileSystemPath: 'signerFileSystemPath',
};
const apiStub = sinon.stub(clientRoutes, 'setupAPIRoutes');
const signerStub = sinon.stub(clientRoutes, 'setupSigningRoutes');
const readFileStub = sinon.stub(fs, 'readFileSync').returns(validPrvJSON);
expressApp(args);
signerStub.should.have.been.calledOnce();
apiStub.called.should.be.false();
apiStub.restore();
signerStub.restore();
readFileStub.restore();
});
it('should require a signerFileSystemPath and signerMode are both set when running in signer mode', function () {
const args: any = {
env: 'test',
signerMode: 'signerMode',
signerFileSystemPath: undefined,
};
(() => expressApp(args)).should.throw({
name: 'ExternalSignerConfigError',
message: 'signerMode and signerFileSystemPath must both be set in order to run in external signing mode.'
});
args.signerMode = undefined;
args.signerFileSystemPath = 'signerFileSystemPath';
(() => expressApp(args)).should.throw({
name: 'ExternalSignerConfigError',
message: 'signerMode and signerFileSystemPath must both be set in order to run in external signing mode.'
});
const readFileStub = sinon.stub(fs, 'readFileSync').returns(validPrvJSON);
args.signerMode = 'signerMode';
(() => expressApp(args)).should.not.throw();
readFileStub.restore();
});
it('should require that an externalSignerUrl and signerMode are not both set', function () {
const args: any = {
env: 'test',
signerMode: 'signerMode',
externalSignerUrl: 'externalSignerUrl',
};
(() => expressApp(args)).should.throw({
name: 'ExternalSignerConfigError',
message: 'signerMode or signerFileSystemPath is set, but externalSignerUrl is also set.'
});
args.signerMode = undefined;
(() => expressApp(args)).should.not.throw();
});
it('should require that an signerFileSystemPath contains a parsable json', function () {
const args: any = {
env: 'test',
signerMode: 'signerMode',
signerFileSystemPath: 'invalidSignerFileSystemPath',
};
(() => expressApp(args)).should.throw();
const invalidPrv = '{"invalid json"}';
const readInvalidStub = sinon.stub(fs, 'readFileSync').returns(invalidPrv);
(() => expressApp(args)).should.throw();
readInvalidStub.restore();
const readValidStub = sinon.stub(fs, 'readFileSync').returns(validPrvJSON);
(() => expressApp(args)).should.not.throw();
readValidStub.restore();
});
});
});
|
apache-2.0
|
clement-elbaz/somedamnmusic
|
src/main/webapp/PostMusicModal.html
|
1383
|
<html>
<body>
<!-- Modal -->
<div class="modal fade" id="youtubeModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<form role="form" action="/postmusic" method="post">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title" id="myModalLabel">Post a damn youtube video</h4>
</div>
<div class="modal-body">
<img src="imgs/youtubeLogo.png" width="250px" alt="youtube logo">
<label for="inputYoutube">Enter a full youtube URL here : </label>
<input type="text" class="form-control" id="inputYoutube" name="youtubeURL" value="" placeholder="http://www.youtube.com/watch?v=UhlbUEwF5QU" required/>
<br/>
<label for="inputDescription">Short description : </label>
<input type="text" class="form-control" maxlength="200" id="inputDescription" name="description" value="" placeholder="Why do you like this music ?"/>
<input type="hidden" id="inputReturnURL" name="returnURL" value="${returnURL}" required/>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-success">Post some damn music !</button>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
|
apache-2.0
|
nimbus-cloud/cli
|
src/cf/requirements/targeted_space_test.go
|
1273
|
package requirements_test
import (
"cf/models"
. "cf/requirements"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
testassert "testhelpers/assert"
testconfig "testhelpers/configuration"
testterm "testhelpers/terminal"
)
var _ = Describe("Testing with ginkgo", func() {
It("TestSpaceRequirement", func() {
ui := new(testterm.FakeUI)
org := models.OrganizationFields{}
org.Name = "my-org"
org.Guid = "my-org-guid"
space := models.SpaceFields{}
space.Name = "my-space"
space.Guid = "my-space-guid"
config := testconfig.NewRepositoryWithDefaults()
req := NewTargetedSpaceRequirement(ui, config)
success := req.Execute()
Expect(success).To(BeTrue())
config.SetSpaceFields(models.SpaceFields{})
testassert.AssertPanic(testterm.FailedWasCalled, func() {
NewTargetedSpaceRequirement(ui, config).Execute()
})
testassert.SliceContains(ui.Outputs, testassert.Lines{
{"FAILED"},
{"No space targeted"},
})
ui.ClearOutputs()
config.SetOrganizationFields(models.OrganizationFields{})
testassert.AssertPanic(testterm.FailedWasCalled, func() {
NewTargetedSpaceRequirement(ui, config).Execute()
})
testassert.SliceContains(ui.Outputs, testassert.Lines{
{"FAILED"},
{"No org and space targeted"},
})
})
})
|
apache-2.0
|
mfursov/wicket7template
|
src/main/java/com/github/mfursov/w7/page/signin/ForgotPasswordPage.java
|
4068
|
package com.github.mfursov.w7.page.signin;
import com.github.mfursov.w7.Context;
import com.github.mfursov.w7.Mounts;
import com.github.mfursov.w7.annotation.MountPath;
import com.github.mfursov.w7.component.CaptchaField;
import com.github.mfursov.w7.component.Feedback;
import com.github.mfursov.w7.component.RefreshCaptchaLink;
import com.github.mfursov.w7.db.dbi.UsersDbi;
import com.github.mfursov.w7.model.User;
import com.github.mfursov.w7.model.VerificationRecord;
import com.github.mfursov.w7.model.VerificationRecordType;
import com.github.mfursov.w7.page.BasePage;
import com.github.mfursov.w7.util.MailClient;
import com.github.mfursov.w7.util.UserSessionUtils;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.form.AjaxSubmitLink;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.image.Image;
import org.apache.wicket.markup.html.image.NonCachingImage;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.util.MapModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.HashMap;
import static java.util.Collections.singletonMap;
/**
*/
@MountPath("/password/restore")
public class ForgotPasswordPage extends BasePage {
private static final Logger log = LoggerFactory.getLogger(ForgotPasswordPage.class);
public ForgotPasswordPage() {
UserSessionUtils.redirectToHomeIfSignedIn();
Feedback feedback = new Feedback("feedback");
add(feedback);
Form form = new Form("reset_from");
add(form);
CaptchaField captchaField = new CaptchaField("captcha_value");
TextField<String> loginOrEmailField = new TextField<>("login_or_email_field", Model.of(""));
form.add(captchaField);
form.add(loginOrEmailField);
Image captchaImage = new NonCachingImage("captcha_image", captchaField.getCaptchaImageResource());
captchaImage.setOutputMarkupId(true);
form.add(captchaImage);
form.add(new RefreshCaptchaLink("change_captcha", captchaField, captchaImage));
form.add(new AjaxSubmitLink("submit", form) {
protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
feedback.reset(target);
String captcha = captchaField.getUserText();
if (!captchaField.getOriginalText().equals(captcha)) {
feedback.errorKey("error_invalid_captcha_code");
return;
}
UsersDbi dao = Context.getUsersDbi();
String loginOrEmail = loginOrEmailField.getModelObject();
User user = dao.getUserByLoginOrEmail(loginOrEmail);
if (user == null) {
user = dao.getUserByEmail(loginOrEmail);
}
if (user == null) {
feedback.errorKey("error_user_not_found");
return;
}
VerificationRecord resetRequest = new VerificationRecord(user, VerificationRecordType.PasswordReset, "");
Context.getUsersDbi().createVerificationRecord(resetRequest);
feedback.infoKey("info_password_reset_info_was_sent", new MapModel<>(singletonMap("email", user.email)));
sendEmail(user, resetRequest);
}
});
}
private void sendEmail(User user, VerificationRecord resetRequest) {
try {
MailClient.sendMail(user.email, getString("info_password_reset_email_subject"),
getString("info_password_reset_email_body", new MapModel<>(new HashMap<String, String>() {{
put("username", user.login);
put("link", Mounts.urlFor(ResetPasswordPage.class) + "?" + ResetPasswordPage.HASH_PARAM + "=" + resetRequest.hash);
}})));
} catch (IOException e) {
log.error("", e);
//todo:
}
}
}
|
apache-2.0
|
ProteanBear/ProteanBear_Java
|
source/PbJExpress/test/pb/text/LoveCalculator.java
|
19881
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* LoveCalculator.java
*
* Created on 2011-11-24, 9:27:40
*/
package pb.text;
/**
* @author maqiang
*/
public class LoveCalculator extends javax.swing.JFrame
{
/**
* 域(私有)<br>
* 名称: dp<br>
* 描述: 日期处理对象<br>
*/
private DateProcessor dp;
/**
* 域()<br>
* 名称: <br>
* 描述: <br>
*/
private String curDate;
private String knowDate;
private String loveDate;
private String marryDate;
/** Creates new form LoveCalculator */
public LoveCalculator()
{
initComponents();
this.dp=new DateProcessor();
this.curDate=this.dp.getCurrent();
this.knowDate="2001-09-10";
this.loveDate="2002-02-24";
this.marryDate="2011-03-22";
this.currentDateField.setText(curDate);
this.knowDateField.setText(this.knowDate);
this.loveDateField.setText(this.loveDate);
this.marryDateField.setText(this.marryDate);
}
/**
* 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()
{
loveDateLabel=new javax.swing.JLabel();
loveDateField=new javax.swing.JTextField();
marryDateField=new javax.swing.JTextField();
marryDateLabel=new javax.swing.JLabel();
currentDateLabel=new javax.swing.JLabel();
currentDateField=new javax.swing.JTextField();
loveTimeField=new javax.swing.JTextField();
loveTimeLabel=new javax.swing.JLabel();
marryTimeLabel=new javax.swing.JLabel();
marryTimeField=new javax.swing.JTextField();
calculateButton=new javax.swing.JButton();
knowDateField=new javax.swing.JTextField();
knowDateLabel=new javax.swing.JLabel();
knowTimeLabel=new javax.swing.JLabel();
knowTimeField=new javax.swing.JTextField();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("爱情计算器");
setBackground(new java.awt.Color(255,255,255));
loveDateLabel.setFont(new java.awt.Font("微软雅黑",0,14)); // NOI18N
loveDateLabel.setText("恋爱日期:");
loveDateField.setEditable(false);
loveDateField.setFont(new java.awt.Font("微软雅黑",0,14)); // NOI18N
marryDateField.setEditable(false);
marryDateField.setFont(new java.awt.Font("微软雅黑",0,14)); // NOI18N
marryDateLabel.setFont(new java.awt.Font("微软雅黑",0,14)); // NOI18N
marryDateLabel.setText("结婚日期:");
currentDateLabel.setFont(new java.awt.Font("微软雅黑",0,14)); // NOI18N
currentDateLabel.setText("当前日期:");
currentDateField.setEditable(false);
currentDateField.setFont(new java.awt.Font("微软雅黑",0,14)); // NOI18N
loveTimeField.setEditable(false);
loveTimeField.setFont(new java.awt.Font("微软雅黑",0,14)); // NOI18N
loveTimeLabel.setFont(new java.awt.Font("微软雅黑",0,14)); // NOI18N
loveTimeLabel.setText("恋爱时间:");
marryTimeLabel.setFont(new java.awt.Font("微软雅黑",0,14)); // NOI18N
marryTimeLabel.setText("结婚时间:");
marryTimeField.setEditable(false);
marryTimeField.setFont(new java.awt.Font("微软雅黑",0,14)); // NOI18N
calculateButton.setText("计算");
calculateButton.addMouseListener(
new java.awt.event.MouseAdapter()
{
public void mouseClicked(java.awt.event.MouseEvent evt)
{
calculateButtonMouseClicked(evt);
}
}
);
knowDateField.setEditable(false);
knowDateField.setFont(new java.awt.Font("微软雅黑",0,14)); // NOI18N
knowDateLabel.setFont(new java.awt.Font("微软雅黑",0,14)); // NOI18N
knowDateLabel.setText("结识日期:");
knowTimeLabel.setFont(new java.awt.Font("微软雅黑",0,14)); // NOI18N
knowTimeLabel.setText("结识时间:");
knowTimeField.setEditable(false);
knowTimeField.setFont(new java.awt.Font("微软雅黑",0,14)); // NOI18N
javax.swing.GroupLayout layout=new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(
layout.createSequentialGroup()
.addContainerGap()
.addGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(
layout.createParallelGroup(
javax.swing.GroupLayout.Alignment.TRAILING
)
.addComponent(marryTimeLabel)
.addComponent(loveTimeLabel)
.addComponent(knowTimeLabel)
.addComponent(currentDateLabel)
.addComponent(marryDateLabel)
)
.addComponent(loveDateLabel)
.addComponent(knowDateLabel)
)
.addGap(10,10,10)
.addGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(calculateButton)
.addComponent(
marryTimeField,javax.swing.GroupLayout.DEFAULT_SIZE,194,
Short.MAX_VALUE
)
.addComponent(
knowTimeField,javax.swing.GroupLayout.DEFAULT_SIZE,194,
Short.MAX_VALUE
)
.addComponent(
knowDateField,javax.swing.GroupLayout.Alignment.LEADING,
javax.swing.GroupLayout.DEFAULT_SIZE,194,Short.MAX_VALUE
)
.addComponent(
loveDateField,javax.swing.GroupLayout.Alignment.LEADING,
javax.swing.GroupLayout.DEFAULT_SIZE,194,Short.MAX_VALUE
)
.addComponent(
marryDateField,javax.swing.GroupLayout.DEFAULT_SIZE,194,
Short.MAX_VALUE
)
.addComponent(
currentDateField,javax.swing.GroupLayout.DEFAULT_SIZE,
194,Short.MAX_VALUE
)
.addComponent(
loveTimeField,javax.swing.GroupLayout.DEFAULT_SIZE,194,
Short.MAX_VALUE
)
)
.addContainerGap()
)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(
javax.swing.GroupLayout.Alignment.TRAILING,layout.createSequentialGroup()
.addContainerGap(29,Short.MAX_VALUE)
.addGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(
knowDateField,javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE
)
.addComponent(knowDateLabel)
)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(
loveDateField,javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE
)
.addComponent(loveDateLabel)
)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(
marryDateField,javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE
)
.addComponent(marryDateLabel)
)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(
currentDateField,javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE
)
.addComponent(currentDateLabel)
)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(
knowTimeField,javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE
)
.addComponent(knowTimeLabel)
)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(
loveTimeField,javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE
)
.addComponent(loveTimeLabel)
)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(
marryTimeField,javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE
)
.addComponent(marryTimeLabel)
)
.addGap(14,14,14)
.addComponent(calculateButton)
.addContainerGap()
)
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void calculateButtonMouseClicked(java.awt.event.MouseEvent evt)//GEN-FIRST:event_calculateButtonMouseClicked
{//GEN-HEADEREND:event_calculateButtonMouseClicked
// TODO add your handling code here:
this.knowTimeField.setText(this.calculateDate(curDate,this.knowDate));
this.loveTimeField.setText(this.calculateDate(curDate,this.loveDate));
this.marryTimeField.setText(this.calculateDate(curDate,this.marryDate));
}//GEN-LAST:event_calculateButtonMouseClicked
private String calculateDate(String currentDate,String oldDate)
{
String result="";
int first=4;
int last=7;
//计算年
int cur=Integer.parseInt(currentDate.substring(0,first));
int old=Integer.parseInt(oldDate.substring(0,first));
int diff=cur-old;
result+=(diff<1)?"":(diff+"年");
//计算月
cur=Integer.parseInt(currentDate.substring(first+1,last));
old=Integer.parseInt(oldDate.substring(first+1,last));
diff=cur-old;
result+=(diff<1)?"":(diff+"个月");
//计算天
cur=Integer.parseInt(currentDate.substring(last+1));
old=Integer.parseInt(oldDate.substring(last+1));
diff=cur-old;
result+=(diff<1)?"":(diff+"天");
return result;
}
/**
* @param args the command line arguments
*/
public static void main(String args[])
{
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try
{
for(javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels())
{
if("Nimbus".equals(info.getName()))
{
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
}
catch(ClassNotFoundException ex)
{
java.util.logging.Logger.getLogger(LoveCalculator.class.getName())
.log(java.util.logging.Level.SEVERE,null,ex);
}
catch(InstantiationException ex)
{
java.util.logging.Logger.getLogger(LoveCalculator.class.getName())
.log(java.util.logging.Level.SEVERE,null,ex);
}
catch(IllegalAccessException ex)
{
java.util.logging.Logger.getLogger(LoveCalculator.class.getName())
.log(java.util.logging.Level.SEVERE,null,ex);
}
catch(javax.swing.UnsupportedLookAndFeelException ex)
{
java.util.logging.Logger.getLogger(LoveCalculator.class.getName())
.log(java.util.logging.Level.SEVERE,null,ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(
new Runnable()
{
public void run()
{
new LoveCalculator().setVisible(true);
}
}
);
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton calculateButton;
private javax.swing.JTextField currentDateField;
private javax.swing.JLabel currentDateLabel;
private javax.swing.JTextField knowDateField;
private javax.swing.JLabel knowDateLabel;
private javax.swing.JTextField knowTimeField;
private javax.swing.JLabel knowTimeLabel;
private javax.swing.JTextField loveDateField;
private javax.swing.JLabel loveDateLabel;
private javax.swing.JTextField loveTimeField;
private javax.swing.JLabel loveTimeLabel;
private javax.swing.JTextField marryDateField;
private javax.swing.JLabel marryDateLabel;
private javax.swing.JTextField marryTimeField;
private javax.swing.JLabel marryTimeLabel;
// End of variables declaration//GEN-END:variables
}
|
apache-2.0
|
Nicksteal/ShopR
|
Android/Shopr/src/main/java/com/uwetrottmann/shopr/context/algorithm/ContextualPostFiltering.java
|
10688
|
package com.uwetrottmann.shopr.context.algorithm;
import android.database.Cursor;
import android.util.Log;
import com.uwetrottmann.shopr.ShoprApp;
import com.uwetrottmann.shopr.algorithm.model.Item;
import com.uwetrottmann.shopr.context.model.Company;
import com.uwetrottmann.shopr.context.model.DayOfTheWeek;
import com.uwetrottmann.shopr.context.model.DistanceMetric;
import com.uwetrottmann.shopr.context.model.ItemSelectedContext;
import com.uwetrottmann.shopr.context.model.ScenarioContext;
import com.uwetrottmann.shopr.context.model.Temperature;
import com.uwetrottmann.shopr.context.model.TimeOfTheDay;
import com.uwetrottmann.shopr.context.model.Weather;
import com.uwetrottmann.shopr.provider.ShoprContract;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
/**
* Created by yannick on 17.02.15.
*
* In this class the post-filtering of the recommended cases is done. We will retrieve several different
* items from the recommendation algorithm. Based on the current active context and the contexts in which these items
* were selected, there is going to be a re-ordered list of the top x items.
*/
public class ContextualPostFiltering {
/*
* This variable can be between 0 and 1.
* It states the distance of items, that were not selected in any context, to the currently
* active context. Meaning that if you set 0.5 here, all items that were not selected yet, are
* going to get a distance of 0.5 Therefore you can influence the exploration/exploitation parameter.
*/
private static final double DISTANCE_OF_NON_SELECTED_ITEMS = 0.6;
private static final double THRESHOLD_FREQUENTLY_USED_ITEMS = 0.3; // Items that are selected in more than this numbers times of cases
private static final double IMPROVEMENT_FREQUENTLY_USED_ITEMS = 0.2; // will get a bonus in distance of this
private static String[] sSelectionColumns = new String[]{ShoprContract.ContextItemRelation.REF_ITEM_ID, ShoprContract.ContextItemRelation.CONTEXT_TIME, ShoprContract.ContextItemRelation.CONTEXT_DAY, ShoprContract.ContextItemRelation.CONTEXT_TEMPERATURE, ShoprContract.ContextItemRelation.CONTEXT_HUMIDITY, ShoprContract.ContextItemRelation.CONTEXT_COMPANY};
/**
* This method shall postFilter the provided item set of the case base in order to return better recommendations.
* Therefore it takes a list of current preferred items by the algorithm and searches for contexts in which this item
* was selected. It then checks these contexts with the current context and compares them based on the context's distance metric.
*
* @param currentRecommendation the current recommendations as set by the algorithm
* @param numberOfRecommendations the number of recommendations that should be outputted
* @return an updated list with only the number of items that should be outputted.
*/
public static List<Item> postFilterItems(List<Item> currentRecommendation, int numberOfRecommendations){
List<Item> updatedRecommendation = new ArrayList<Item>();
//Updates the items, such that we can see in which contexts these items were selected
retrieveContextInformationForItems(currentRecommendation);
ScenarioContext scenarioContext = ScenarioContext.getInstance();
//Check that we have a scenario (real test)
if (scenarioContext.isSet()) {
int contexts = 0;
//For each item: Calculate the distances
for (Item item : currentRecommendation) {
//Get the context for the item
ItemSelectedContext itemContext = item.getItemContext();
Map<DistanceMetric, Integer> distanceMetrics = itemContext.getContextsForItem(); //Get the contexts for the item
int overallContextsSet = 0; // The number of context factors which are set for this item
double overallItemDistance = 0; // The overall distance after summation of all factors without dividing
for (DistanceMetric metric : distanceMetrics.keySet()) { //For each metric for the item
int times = distanceMetrics.get(metric);
overallContextsSet += times;
//Multiply the distance with its weight, as they should not have their full weight
overallItemDistance = overallItemDistance + getDistance(times, metric, scenarioContext) * metric.getWeight();
} // End for each metric within the contexts of a item
// Set the distance to the current context
// Items that were not selected in any context are the very far away and will first of all be attached to the end, afterwards they will get the median.
if (overallItemDistance != 0 || overallContextsSet != 0){
overallItemDistance = overallItemDistance / overallContextsSet;
}
item.setDistanceToContext(itemContext.normalizeDistance(overallItemDistance));
//The variable times selected states how often this item was (overall) selected. This is necessary,
// because we might want to improve the scores for products that are very frequently selected.
item.setTimesSelected(overallContextsSet / ItemSelectedContext.getNumberOfDifferentContextFactors());
contexts = contexts + item.getTimesSelected();
} // End for each item
adjustDistances(contexts, currentRecommendation);
//The maximum distance for a product is 1 and the minimum 0 (closest).
//We want the closest items to be at the top of the list (screen)
Collections.sort(currentRecommendation, new DistanceComparator());
} //End check for scenario
int i = 1;
for (Item item : currentRecommendation){
if (updatedRecommendation.size() < numberOfRecommendations) {
updatedRecommendation.add(item);
Log.d("Distance " + i++, "" + item.getDistanceToContext() + " " + item);
} else {
break;
}
}
return updatedRecommendation;
}
/**
* This method returns the distance of this scenario context compared to the context in which the
* item has been selected.
* @param timesSelected the times in which the item has been selected in this context
* @param metric the distance metric to check
* @param scenarioContext the current scenario context
* @return the distance of the metric to the scenario multiplied by the times it was selected
*/
private static double getDistance(int timesSelected, DistanceMetric metric, ScenarioContext scenarioContext){
double distance;
if (metric.isMetricWithEuclideanDistance()){
// The -1 makes sure that we can have 1 as a distance, as when min is 0 and max 5, the number of items is 6, but should be 5 for the maximum distance.
distance = getAdaptedEuclideanDistance(scenarioContext.getMetric(metric).currentOrdinal(), metric.currentOrdinal(), metric.numberOfItems() - 1.0);
distance = timesSelected * distance;
} else {
distance = timesSelected * metric.distanceToContext(scenarioContext);
}
return distance;
}
/**
* This method adjusts the distances for over-performing articles as well as for articles
* that do not sell at all.
* @param contexts the number of times an item was (successfully) recommended
* @param currentRecommendation the list of current recommendations.
*/
private static void adjustDistances(int contexts, List<Item> currentRecommendation){
if (contexts > 0) {
for (Item item : currentRecommendation) {
//Improve items that are very frequently selected
if ( (item.getTimesSelected() / contexts) > THRESHOLD_FREQUENTLY_USED_ITEMS) {
item.setDistanceToContext(item.getDistanceToContext() * (1 - IMPROVEMENT_FREQUENTLY_USED_ITEMS));
}
//Items that were never selected.
if (item.getTimesSelected() == 0){
item.setDistanceToContext(DISTANCE_OF_NON_SELECTED_ITEMS); // Set the distance for items that were not selected in any context
}
}
}
}
/**
* Updates the items and sets the context scenarios in which these items have been selected.
* @param currentRecommendation A list of items, that shall be part of the current recommendation cycle.
*/
private static void retrieveContextInformationForItems(List<Item> currentRecommendation){
for (Item item : currentRecommendation){
//Set a new context for the item(s)
ItemSelectedContext itemContext = new ItemSelectedContext();
item.setItemContext(itemContext);
//Query the database
String selectionString = ShoprContract.ContextItemRelation.REF_ITEM_ID + " = " + item.id();
Cursor query = ShoprApp.getContext().getContentResolver().query(ShoprContract.ContextItemRelation.CONTENT_URI,
sSelectionColumns, selectionString, null, null);
//Move the information from the database into the data structure
if (query != null){
while (query.moveToNext()){
itemContext.increaseDistanceMetric(TimeOfTheDay.getTimeOfTheDay(query.getInt(1)));
itemContext.increaseDistanceMetric(DayOfTheWeek.getDayOfTheWeek(query.getInt(2)));
itemContext.increaseDistanceMetric(Temperature.getTemperature(query.getInt(3)));
itemContext.increaseDistanceMetric(Weather.getWeather(query.getInt(4)));
itemContext.increaseDistanceMetric(Company.getCompany(query.getInt(5)));
}
query.close();
}
// Log.d("Item Context: ", ""+ itemContext);
}
}
/**
* This method returns the adapted euclidean distance as described in the HEOM
* @param p the value for the coordinate of the first object
* @param q the value for the coordinate of the second object
* @param range the difference between the highest and the lowest number in the range
* @return a double with the distance
*/
private static double getAdaptedEuclideanDistance(double p, double q, double range){
double result = ( p - q ) / range;
result = Math.pow(result, 2); // square it
return Math.sqrt(result);
}
}
|
apache-2.0
|
songboriceboy/cnblogsbywojilu
|
wojilu.Controller/Content/Binder/MyShareBinderController.cs
|
1649
|
/*
* Copyright (c) 2010, www.wojilu.com. All rights reserved.
*/
using System;
using System.Collections;
using System.Text;
using wojilu.Web.Mvc;
using wojilu.Apps.Content.Interface;
using wojilu.Apps.Content.Domain;
using wojilu.Common.Feeds.Service;
using wojilu.Common.Feeds.Domain;
using wojilu.Apps.Content.Service;
using wojilu.Web.Controller.Content.Utils;
namespace wojilu.Web.Controller.Content.Binder {
public class MyShareBinderController : ControllerBase, ISectionBinder {
public FeedService feedService { get; set; }
public IContentCustomTemplateService ctService { get; set; }
public MyShareBinderController() {
feedService = new FeedService();
ctService = new ContentCustomTemplateService();
}
public void Bind( ContentSection section, IList serviceData ) {
TemplateUtil.loadTemplate( this, section, ctService );
IBlock block = getBlock( "list" );
foreach (Share share in serviceData) {
String creatorInfo = string.Format( "<a href='{0}'>{1}</a>", Link.ToMember( share.Creator ), share.Creator.Name );
block.Set( "share.Title", feedService.GetHtmlValue( share.TitleTemplate, share.TitleData, creatorInfo ) );
block.Set( "share.Created", cvt.ToTimeString( share.Created ) );
block.Set( "share.DataTypeImg", strUtil.Join( sys.Path.Img, "/app/s/" + typeof( Share ).FullName + ".gif" ) );
block.Bind( "share", share );
block.Next();
}
}
}
}
|
apache-2.0
|
mdoering/backbone
|
life/Fungi/Ascomycota/Lecanoromycetes/Lecanorales/Parmeliaceae/Alectoria/Bryopogon lanestris/Bryopogon lanestris lanestris/README.md
|
190
|
# Bryopogon lanestris f. lanestris FORM
#### Status
ACCEPTED
#### According to
Index Fungorum
#### Published in
null
#### Original name
Bryopogon lanestris f. lanestris
### Remarks
null
|
apache-2.0
|
mdoering/backbone
|
life/Plantae/Pteridophyta/Polypodiopsida/Polypodiales/Aspleniaceae/Asplenium/Asplenium achilleifolium/Asplenium achilleifolium achilleifolium/README.md
|
186
|
# Asplenium achilleifolium var. achilleifolium VARIETY
#### Status
ACCEPTED
#### According to
NUB Generator [autonym]
#### Published in
null
#### Original name
null
### Remarks
null
|
apache-2.0
|
mdoering/backbone
|
life/Fungi/Basidiomycota/Agaricomycetes/Polyporales/Ganodermataceae/Ganoderma/Ganoderma adspersum/ Syn. Polyporus adspersus/README.md
|
242
|
# Polyporus adspersus Schulzer, 1878 SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
Flora, Jena 61: 11 (1878)
#### Original name
Polyporus adspersus Schulzer, 1878
### Remarks
null
|
apache-2.0
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Caryophyllales/Caryophyllaceae/Stellaria/Alsine valida/README.md
|
169
|
# Alsine valida House SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null
|
apache-2.0
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Liliopsida/Zingiberales/Cannaceae/Canna/Canna liliiflora/README.md
|
236
|
# Canna liliiflora Warsz. ex Planch. SPECIES
#### Status
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
Fl. Serres Jard. Eur. 10:211, t. 1055-1056. 1855
#### Original name
null
### Remarks
null
|
apache-2.0
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Malpighiales/Phyllanthaceae/Sauropus/Sauropus bacciformis/ Syn. Diplomorpha bacciformis/README.md
|
192
|
# Diplomorpha bacciformis (L.) Kuntze SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
apache-2.0
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Malpighiales/Podostemaceae/Ledermanniella/Ledermanniella fluitans/README.md
|
191
|
# Ledermanniella fluitans (H.Hess) C.Cusset SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null
|
apache-2.0
|
viltgroup/minium
|
minium-webelements/src/main/java/minium/web/internal/drivers/WindowWebDriver.java
|
2217
|
/*
* Copyright (C) 2015 The Minium Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package minium.web.internal.drivers;
import static com.google.common.base.MoreObjects.toStringHelper;
import org.openqa.selenium.WebDriver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Objects;
public class WindowWebDriver extends BaseDocumentWebDriver {
private static final Logger LOGGER = LoggerFactory.getLogger(WindowWebDriver.class);
private final String windowHandle;
public WindowWebDriver(WebDriver webDriver) {
this(webDriver, null);
}
public WindowWebDriver(WebDriver webDriver, String windowHandle) {
super(webDriver);
this.windowHandle = windowHandle == null ? webDriver.getWindowHandle() : windowHandle;
}
@Override
public void ensureSwitch() {
webDriver.switchTo().window(windowHandle);
LOGGER.trace("Switched to window {}", windowHandle);
}
@Override
public boolean isClosed() {
return !getWindowHandles().contains(windowHandle);
}
@Override
public String toString() {
return toStringHelper(WindowWebDriver.class.getSimpleName())
.addValue(windowHandle)
.toString();
}
@Override
public int hashCode() {
return Objects.hashCode(super.hashCode(), windowHandle);
}
@Override
public boolean equals(Object obj) {
return obj != null && obj.getClass() == WindowWebDriver.class && equalFields((WindowWebDriver) obj);
}
protected boolean equalFields(WindowWebDriver obj) {
return super.equalFields(obj) && Objects.equal(windowHandle, obj.windowHandle);
}
}
|
apache-2.0
|
gchq/stroom
|
stroom-util/src/main/java/stroom/util/validation/IsSubsetOfValidatorImpl.java
|
2147
|
package stroom.util.validation;
import stroom.util.shared.validation.IsSubsetOf;
import stroom.util.shared.validation.IsSubsetOfValidator;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import javax.validation.ConstraintValidatorContext;
public class IsSubsetOfValidatorImpl implements IsSubsetOfValidator {
private Set<String> allowedValues;
@Override
public void initialize(IsSubsetOf constraintAnnotation) {
allowedValues = new HashSet<>(Arrays.asList(constraintAnnotation.allowedValues()));
}
/**
* Implements the validation logic.
* The state of {@code value} must not be altered.
* <p>
* This method can be accessed concurrently, thread-safety must be ensured
* by the implementation.
*
* @param values object to validate
* @param context context in which the constraint is evaluated
* @return {@code false} if {@code value} does not pass the constraint
*/
@Override
public boolean isValid(final Collection<String> values,
final ConstraintValidatorContext context) {
boolean result = true;
if (values != null && !values.isEmpty()) {
final Set<String> invalidValues = new HashSet<>(values);
invalidValues.removeAll(allowedValues);
if (!invalidValues.isEmpty()) {
// We want the exception details in the message so bin the default constraint
// violation and make a new one.
final String plural = invalidValues.size() > 1
? "s"
: "";
final String msg = "Set contains invalid value"
+ plural
+ " ["
+ String.join(",", invalidValues) + "]";
context.disableDefaultConstraintViolation();
context
.buildConstraintViolationWithTemplate(msg)
.addConstraintViolation();
result = false;
}
}
return result;
}
}
|
apache-2.0
|
ivetech/binlog-mysql
|
src/main/java/xyz/vopen/mysql/binlog/network/protocol/command/DumpBinaryLogCommand.java
|
1645
|
/*
* Copyright 2016 VOPEN.CN
*
* 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 xyz.vopen.mysql.binlog.network.protocol.command;
import xyz.vopen.mysql.binlog.nio.ByteArrayOutputStream;
import java.io.IOException;
/**
* @author <a href="mailto:[email protected]">CiNC</a>
*/
public class DumpBinaryLogCommand implements Command {
private long serverId;
private String binlogFilename;
private long binlogPosition;
public DumpBinaryLogCommand (long serverId, String binlogFilename, long binlogPosition) {
this.serverId = serverId;
this.binlogFilename = binlogFilename;
this.binlogPosition = binlogPosition;
}
@SuppressWarnings("resource")
@Override
public byte[] toByteArray () throws IOException {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
buffer.writeInteger(CommandType.BINLOG_DUMP.ordinal(), 1);
buffer.writeLong(this.binlogPosition, 4);
buffer.writeInteger(0, 2); // flag
buffer.writeLong(this.serverId, 4);
buffer.writeString(this.binlogFilename);
return buffer.toByteArray();
}
}
|
apache-2.0
|
kryoz/sociochat
|
src/SocioChat/DAO/NameChangeDAO.php
|
2379
|
<?php
namespace SocioChat\DAO;
use Core\DAO\DAOBase;
use Core\Utils\DbQueryHelper;
use SocioChat\Clients\User;
class NameChangeDAO extends DAOBase
{
const USER_ID = 'user_id';
const OLD_NAME = 'old_name';
const DATE_CHANGE = 'date_change';
public function __construct()
{
parent::__construct(
[
self::USER_ID,
self::OLD_NAME,
self::DATE_CHANGE,
]
);
$this->dbTable = 'name_change_history';
}
public function getName()
{
return $this[self::OLD_NAME];
}
public function getDateRaw()
{
return $this[self::DATE_CHANGE];
}
public function getDate()
{
return strtotime($this[self::DATE_CHANGE]);
}
public function getUserId()
{
return strtotime($this[self::USER_ID]);
}
public function setUser(User $user)
{
$this[self::USER_ID] = $user->getId();
$this[self::OLD_NAME] = $user->getProperties()->getName();
$this[self::DATE_CHANGE] = DbQueryHelper::timestamp2date();
return $this;
}
/**
* @param User $user
* @return $this
*/
public function getLastByUser(User $user)
{
$list = $this->getListByQuery(
"SELECT * FROM {$this->dbTable} WHERE " . self::USER_ID . " = :user_id ORDER BY " . self::DATE_CHANGE . " DESC LIMIT 1",
['user_id' => $user->getId()]);
return !empty($list) ? $list[0] : null;
}
/**
* @param string $name
* @return $this
*/
public function getLastByName($name)
{
$list = $this->getListByQuery(
"SELECT * FROM {$this->dbTable} WHERE " . self::OLD_NAME . " = :oldname ORDER BY " . self::DATE_CHANGE . " ASC LIMIT 1",
['oldname' => $name]);
return !empty($list) ? $list[0] : null;
}
public function getHistoryByUserId($userId)
{
return $this->getListByQuery(
"SELECT * FROM {$this->dbTable} WHERE " . self::USER_ID . " = :user_id ORDER BY " . self::DATE_CHANGE . " DESC",
['user_id' => $userId]);
}
public function dropByUserId($id)
{
$this->db->exec("DELETE FROM {$this->dbTable} WHERE " . self::USER_ID . " = :0", [$id]);
}
protected function getForeignProperties()
{
return [];
}
}
|
apache-2.0
|
SuperMap/iClient9
|
src/mapboxgl/services/ImageService.js
|
3968
|
/* Copyright© 2000 - 2022 SuperMap Software Co.Ltd. All rights reserved.
* This program are made available under the terms of the Apache License, Version 2.0
* which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/
import mapboxgl from 'mapbox-gl';
import { ServiceBase } from './ServiceBase';
import '../core/Base';
import { ImageService as CommonMatchImageService } from '@supermap/iclient-common';
/**
* @class mapboxgl.supermap.ImageService
* @version 10.2.0
* @constructs mapboxgl.supermap.ImageService
* @classdesc 影像服务类
* @category iServer Image
* @example
* mapboxgl.supermap.ImageService(url,options)
* .getCollections(function(result){
* //doSomething
* })
* @param {string} url - 服务地址。例如: http://{ip}:{port}/iserver/{imageservice-imageserviceName}/restjsr/
* @param {Object} options - 参数。
* @param {string} [options.proxy] - 服务代理地址。
* @param {boolean} [options.withCredentials=false] - 请求是否携带 cookie。
* @param {boolean} [options.crossOrigin] - 是否允许跨域请求。
* @param {Object} [options.headers] - 请求头。
* @extends {mapboxgl.supermap.ServiceBase}
*/
export class ImageService extends ServiceBase {
constructor(url, options) {
super(url, options);
}
/**
* @function mapboxgl.supermap.ImageService.prototype.getCollections
* @description 返回当前影像服务中的影像集合列表(Collections)。
* @param {RequestCallback} callback - 请求结果的回调函数。
*/
getCollections(callback) {
var me = this;
var ImageService = new CommonMatchImageService(this.url, {
proxy: me.options.proxy,
withCredentials: me.options.withCredentials,
crossOrigin: me.options.crossOrigin,
headers: me.options.headers,
eventListeners: {
scope: me,
processCompleted: callback,
processFailed: callback
}
});
ImageService.getCollections();
}
/**
* @function mapboxgl.supermap.ImageService.prototype.getCollectionByID
* @description ID值等于`collectionId`参数值的影像集合(Collection)。 ID值用于在服务中唯一标识该影像集合。
* @param {string} collectionId 影像集合(Collection)的ID,在一个影像服务中唯一标识影像集合。
* @param {RequestCallback} callback - 请求结果的回调函数。
*/
getCollectionByID(collectionId, callback) {
var me = this;
var ImageService = new CommonMatchImageService(me.url, {
proxy: me.options.proxy,
withCredentials: me.options.withCredentials,
crossOrigin: me.options.crossOrigin,
headers: me.options.headers,
eventListeners: {
scope: me,
processCompleted: callback,
processFailed: callback
}
});
ImageService.getCollectionByID(collectionId);
}
/**
* @function mapboxgl.supermap.ImageService.prototype.search
* @description 查询与过滤条件匹配的影像数据。
* @param {SuperMap.ImageSearchParameter} [itemSearch] 查询参数
* @param {RequestCallback} callback - 请求结果的回调函数。
*/
search(itemSearch, callback) {
var me = this;
var ImageService = new CommonMatchImageService(me.url, {
proxy: me.options.proxy,
withCredentials: me.options.withCredentials,
crossOrigin: me.options.crossOrigin,
headers: me.options.headers,
eventListeners: {
scope: me,
processCompleted: callback,
processFailed: callback
}
});
ImageService.search(itemSearch);
}
}
mapboxgl.supermap.ImageService = ImageService;
|
apache-2.0
|
raspibo/eventman
|
angular_app/js/services.js
|
9665
|
'use strict';
/* Services that are used to interact with the backend. */
var eventManServices = angular.module('eventManServices', ['ngResource']);
/* Modify, in place, an object to convert datetime. */
function convert_dates(obj) {
angular.forEach(['begin_date', 'end_date', 'ticket_sales_begin_date', 'ticket_sales_end_date'], function(key, key_idx) {
if (!obj[key]) {
return;
}
obj[key] = obj[key].getTime();
});
return obj;
}
eventManServices.factory('Event', ['$resource', '$rootScope',
function($resource, $rootScope) {
return $resource('events/:id', {id: '@_id'}, {
all: {
method: 'GET',
interceptor: {responseError: $rootScope.errorHandler},
isArray: true,
transformResponse: function(data, headers) {
data = angular.fromJson(data);
if (data.error) {
return data;
}
angular.forEach(data.events || [], function(event_, event_idx) {
convert_dates(event_);
});
return data.events;
}
},
get: {
method: 'GET',
interceptor: {responseError: $rootScope.errorHandler},
transformResponse: function(data, headers) {
data = angular.fromJson(data);
convert_dates(data);
// strip empty keys.
angular.forEach(data.tickets || [], function(ticket, ticket_idx) {
angular.forEach(ticket, function(value, key) {
if (value === "") {
delete ticket[key];
}
});
});
return data;
}
},
update: {
method: 'PUT',
interceptor: {responseError: $rootScope.errorHandler},
transformResponse: function(data, headers) {
data = angular.fromJson(data);
convert_dates(data);
return data;
}
},
group_persons: {
method: 'GET',
url: 'events/:id/group_persons',
isArray: true,
transformResponse: function(data, headers) {
data = angular.fromJson(data);
return data.persons || [];
}
}
});
}]
);
eventManServices.factory('EventTicket', ['$resource', '$rootScope',
function($resource, $rootScope) {
return $resource('events/:id/tickets', {event_id: '@event_id', ticket_id: '@_id'}, {
all: {
method: 'GET',
url: '/tickets',
interceptor: {responseError: $rootScope.errorHandler},
isArray: true,
transformResponse: function(data, headers) {
data = angular.fromJson(data);
return data.tickets;
}
},
get: {
method: 'GET',
url: 'events/:id/tickets/:ticket_id',
interceptor: {responseError: $rootScope.errorHandler},
transformResponse: function(data, headers) {
data = angular.fromJson(data);
if (data.error) {
return data;
}
return data.ticket;
}
},
add: {
method: 'POST',
interceptor: {responseError: $rootScope.errorHandler},
isArray: false,
url: 'events/:event_id/tickets',
params: {uuid: $rootScope.app_uuid},
transformResponse: function(data, headers) {
data = angular.fromJson(data);
if (data.error) {
return data;
}
return data.ticket;
}
},
update: {
method: 'PUT',
interceptor: {responseError: $rootScope.errorHandler},
isArray: false,
url: 'events/:event_id/tickets/:ticket_id',
params: {uuid: $rootScope.app_uuid},
transformResponse: function(data, headers) {
if (data.error) {
return data;
}
return angular.fromJson(data);
}
},
'delete': {
method: 'DELETE',
interceptor: {responseError: $rootScope.errorHandler},
isArray: false,
url: 'events/:event_id/tickets/:ticket_id',
params: {uuid: $rootScope.app_uuid},
transformResponse: function(data, headers) {
return angular.fromJson(data);
}
}
});
}]
);
eventManServices.factory('Setting', ['$resource', '$rootScope',
function($resource, $rootScope) {
return $resource('settings/', {}, {
query: {
method: 'GET',
interceptor: {responseError: $rootScope.errorHandler},
isArray: true,
transformResponse: function(data, headers) {
data = angular.fromJson(data);
if (data.error) {
return data;
}
return data.settings;
}
},
update: {
method: 'PUT',
interceptor: {responseError: $rootScope.errorHandler}
}
});
}]
);
eventManServices.factory('Info', ['$resource', '$rootScope',
function($resource, $rootScope) {
return $resource('info/', {}, {
get: {
method: 'GET',
interceptor: {responseError: $rootScope.errorHandler},
isArray: false,
transformResponse: function(data, headers) {
data = angular.fromJson(data);
if (data.error) {
return data;
}
return data.info || {};
}
}
});
}]
);
eventManServices.factory('EbAPI', ['$resource', '$rootScope',
function($resource, $rootScope) {
return $resource('ebapi/', {}, {
apiImport: {
method: 'POST',
interceptor: {responseError: $rootScope.errorHandler},
isArray: false,
transformResponse: function(data, headers) {
return angular.fromJson(data);
}
}
});
}]
);
eventManServices.factory('User', ['$resource', '$rootScope',
function($resource, $rootScope) {
return $resource('users/:id', {id: '@_id'}, {
all: {
method: 'GET',
interceptor: {responseError: $rootScope.errorHandler},
isArray: true,
transformResponse: function(data, headers) {
data = angular.fromJson(data);
if (data.error) {
return data;
}
return data.users;
}
},
get: {
method: 'GET',
interceptor: {responseError: $rootScope.errorHandler},
transformResponse: function(data, headers) {
return angular.fromJson(data);
}
},
add: {
method: 'POST',
interceptor: {responseError: $rootScope.errorHandler}
},
update: {
method: 'PUT',
interceptor: {responseError: $rootScope.errorHandler}
},
login: {
method: 'POST',
url: '/login',
interceptor: {responseError: $rootScope.errorHandler}
},
logout: {
method: 'GET',
url: '/logout',
interceptor: {responseError: $rootScope.errorHandler}
}
});
}]
);
/* WebSocket collection used to update the list of tickets of an Event. */
eventManApp.factory('EventUpdates', ['$websocket', '$location', '$log', '$rootScope',
function($websocket, $location, $log, $rootScope) {
var dataStream = null;
var data = {};
var methods = {
data: data,
close: function() {
$log.debug('close WebSocket connection');
dataStream.close();
},
open: function() {
var proto = $location.protocol() == 'https' ? 'wss' : 'ws';
var url = proto + '://' + $location.host() + ':' + $location.port() +
'/ws/' + $location.path() + '/updates?uuid=' + $rootScope.app_uuid;
$log.debug('open WebSocket connection to ' + url);
//dataStream && dataStream.close();
dataStream = $websocket(url);
dataStream.onMessage(function(message) {
$log.debug('EventUpdates message received');
data.update = angular.fromJson(message.data);
});
}
};
return methods;
}]
);
|
apache-2.0
|
cocoatomo/asakusafw
|
hive-project/asakusa-hive-info/src/main/java/com/asakusafw/directio/hive/annotation/HiveTable.java
|
1243
|
/**
* Copyright 2011-2017 Asakusa Framework Team.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.asakusafw.directio.hive.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import com.asakusafw.directio.hive.info.TableInfo;
/**
* Hive table annotation.
* @since 0.7.0
* @version 0.8.1
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface HiveTable {
/**
* The table schema providers.
*/
Class<? extends TableInfo.Provider>[] value();
}
|
apache-2.0
|
0xkag/alpine
|
regex/Makefile
|
16123
|
# Makefile.in generated by automake 1.11.1 from Makefile.am.
# regex/Makefile. Generated from Makefile.in by configure.
# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
# 2003, 2004, 2005, 2006, 2007, 2008, 2009 Free Software Foundation,
# Inc.
# This Makefile.in is free software; the Free Software Foundation
# gives unlimited permission to copy and/or distribute it,
# with or without modifications, as long as this notice is preserved.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY, to the extent permitted by law; without
# even the implied warranty of MERCHANTABILITY or FITNESS FOR A
# PARTICULAR PURPOSE.
# ========================================================================
# Copyright 2006-2007 University of Washington
#
# 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
#
# ========================================================================
pkgdatadir = $(datadir)/alpine
pkgincludedir = $(includedir)/alpine
pkglibdir = $(libdir)/alpine
pkglibexecdir = $(libexecdir)/alpine
am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
install_sh_DATA = $(install_sh) -c -m 644
install_sh_PROGRAM = $(install_sh) -c
install_sh_SCRIPT = $(install_sh) -c
INSTALL_HEADER = $(INSTALL_DATA)
transform = $(program_transform_name)
NORMAL_INSTALL = :
PRE_INSTALL = :
POST_INSTALL = :
NORMAL_UNINSTALL = :
PRE_UNINSTALL = :
POST_UNINSTALL = :
build_triplet = x86_64-unknown-linux-gnu
host_triplet = x86_64-unknown-linux-gnu
subdir = regex
DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in
ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
am__aclocal_m4_deps = $(top_srcdir)/m4/acx_pthread.m4 \
$(top_srcdir)/m4/gettext.m4 $(top_srcdir)/m4/iconv.m4 \
$(top_srcdir)/m4/lib-ld.m4 $(top_srcdir)/m4/lib-link.m4 \
$(top_srcdir)/m4/lib-prefix.m4 $(top_srcdir)/m4/libtool.m4 \
$(top_srcdir)/m4/ltoptions.m4 $(top_srcdir)/m4/ltsugar.m4 \
$(top_srcdir)/m4/ltversion.m4 $(top_srcdir)/m4/lt~obsolete.m4 \
$(top_srcdir)/m4/nls.m4 $(top_srcdir)/m4/po.m4 \
$(top_srcdir)/m4/progtest.m4 $(top_srcdir)/VERSION \
$(top_srcdir)/VERSION $(top_srcdir)/VERSION \
$(top_srcdir)/VERSION $(top_srcdir)/VERSION \
$(top_srcdir)/VERSION $(top_srcdir)/VERSION \
$(top_srcdir)/VERSION $(top_srcdir)/VERSION \
$(top_srcdir)/VERSION $(top_srcdir)/VERSION \
$(top_srcdir)/configure.ac
am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
$(ACLOCAL_M4)
mkinstalldirs = $(SHELL) $(top_srcdir)/mkinstalldirs
CONFIG_CLEAN_FILES =
CONFIG_CLEAN_VPATH_FILES =
LIBRARIES = $(noinst_LIBRARIES)
ARFLAGS = cru
libregex_a_AR = $(AR) $(ARFLAGS)
libregex_a_LIBADD =
am_libregex_a_OBJECTS = regcomp.$(OBJEXT) regerror.$(OBJEXT) \
regexec.$(OBJEXT) regfree.$(OBJEXT)
libregex_a_OBJECTS = $(am_libregex_a_OBJECTS)
DEFAULT_INCLUDES =
depcomp = $(SHELL) $(top_srcdir)/depcomp
am__depfiles_maybe = depfiles
am__mv = mv -f
COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \
$(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
LTCOMPILE = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \
--mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \
$(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
CCLD = $(CC)
LINK = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \
--mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) \
$(LDFLAGS) -o $@
SOURCES = $(libregex_a_SOURCES)
DIST_SOURCES = $(libregex_a_SOURCES)
ETAGS = etags
CTAGS = ctags
DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
ACLOCAL = ${SHELL} /run/media/echappa/Work/alpine/alpinegit/missing aclocal-1.15
AMTAR = $${TAR-tar}
AM_CFLAGS = -g
AM_LDFLAGS =
AR = /usr/bin/ar
AUTOCONF = ${SHELL} /run/media/echappa/Work/alpine/alpinegit/missing autoconf
AUTOHEADER = ${SHELL} /run/media/echappa/Work/alpine/alpinegit/missing autoheader
AUTOMAKE = ${SHELL} /run/media/echappa/Work/alpine/alpinegit/missing automake-1.15
AWK = gawk
CC = gcc
CCDEPMODE = depmode=gcc3
CFLAGS = -g
CP = /usr/bin/cp
CPP = gcc -E
CPPFLAGS = -I/usr/include -I/regex
CYGPATH_W = echo
C_CLIENT_CFLAGS = EXTRACFLAGS=" -DTLSV1_2 -I/usr/include -I/regex -g"
C_CLIENT_GCCOPTLEVEL = GCCOPTLEVEL="-O0"
C_CLIENT_LDFLAGS = EXTRALDFLAGS=" -L/usr/lib -L/regex -lgssapi_krb5 -lpam -lldap -lssl -lcrypto -ldl -ltinfo -llber -lpam -lkrb5"
C_CLIENT_SPECIALS = SSLDIR=/usr SSLCERTS=/etc/ssl/certs
C_CLIENT_TARGET = lnp
C_CLIENT_WITH_IPV6 = touch imap/ip6
DEFS = -DHAVE_CONFIG_H
DEPDIR = .deps
DSYMUTIL =
DUMPBIN =
ECHO_C =
ECHO_N = -n
ECHO_T =
EGREP = /usr/bin/grep -E
EXEEXT =
FGREP = /usr/bin/grep -F
GMSGFMT = /usr/bin/msgfmt
GMSGFMT_015 = /usr/bin/msgfmt
GREP = /usr/bin/grep
INSTALL = /usr/bin/install -c
INSTALL_DATA = ${INSTALL} -m 644
INSTALL_PROGRAM = ${INSTALL}
INSTALL_SCRIPT = ${INSTALL}
INSTALL_STRIP_PROGRAM = $(install_sh) -c -s
INTLLIBS =
INTL_MACOSX_LIBS =
ISPELLPROG =
Includedir = @Includedir@
LD = /usr/x86_64-suse-linux/bin/ld -m elf_x86_64
LDFLAGS = -L/usr/lib -L/regex
LIBICONV = -liconv
LIBINTL =
LIBOBJS =
LIBS = -lgssapi_krb5 -lpam -lldap -lssl -lcrypto -ldl -ltinfo -llber -lpam -lkrb5
LIBTOOL = $(SHELL) $(top_builddir)/libtool
LIBTOOL_DEPS = ./ltmain.sh
LIPO =
LN = /usr/bin/ln
LN_S = ln -s
LTLIBICONV = -liconv
LTLIBINTL =
LTLIBOBJS =
MAINT = #
MAKE = /usr/bin/make
MAKEINFO = ${SHELL} /run/media/echappa/Work/alpine/alpinegit/missing makeinfo
MKDIR_P = /usr/bin/mkdir -p
MSGFMT = /usr/bin/msgfmt
MSGFMT_015 = /usr/bin/msgfmt
MSGMERGE = /usr/bin/msgmerge
NM = /usr/bin/nm -B
NMEDIT =
NPA_PROG =
OBJDUMP = objdump
OBJEXT = o
OTOOL =
OTOOL64 =
PACKAGE = alpine
PACKAGE_BUGREPORT = [email protected]
PACKAGE_NAME = alpine
PACKAGE_STRING = alpine 2.21
PACKAGE_TARNAME = alpine
PACKAGE_URL =
PACKAGE_VERSION = 2.21
PATH_SEPARATOR = :
POSUB = po
PTHREAD_CC = gcc
PTHREAD_CFLAGS =
PTHREAD_LIBS =
PWPROG = /usr/bin/passwd
RANLIB = ranlib
REGEX_BUILD = regex
RM = /usr/bin/rm
SED = /usr/bin/sed
SENDMAIL = /usr/sbin/sendmail
SET_MAKE =
SHELL = /bin/sh
SPELLPROG = spell
STRIP = strip
USE_NLS = yes
VERSION = 2.21
WEB_BINDIR =
WEB_BUILD =
WEB_PUBCOOKIE_BUILD =
WEB_PUBCOOKIE_LIB =
WEB_PUBCOOKIE_LINK =
XGETTEXT = /usr/bin/xgettext
XGETTEXT_015 = /usr/bin/xgettext
abs_builddir = /run/media/echappa/Work/alpine/alpinegit/regex
abs_srcdir = /run/media/echappa/Work/alpine/alpinegit/regex
abs_top_builddir = /run/media/echappa/Work/alpine/alpinegit
abs_top_srcdir = /run/media/echappa/Work/alpine/alpinegit
ac_ct_CC = gcc
ac_ct_DUMPBIN =
acx_pthread_config = no
alpine_interactive_spellcheck =
alpine_simple_spellcheck =
am__include = include
am__leading_dot = .
am__quote =
am__tar = $${TAR-tar} chof - "$$tardir"
am__untar = $${TAR-tar} xf -
bindir = ${exec_prefix}/bin
build = x86_64-unknown-linux-gnu
build_alias =
build_cpu = x86_64
build_os = linux-gnu
build_vendor = unknown
builddir = .
datadir = ${datarootdir}
datarootdir = ${prefix}/share
docdir = ${datarootdir}/doc/${PACKAGE_TARNAME}
dvidir = ${docdir}
exec_prefix = ${prefix}
host = x86_64-unknown-linux-gnu
host_alias =
host_cpu = x86_64
host_os = linux-gnu
host_vendor = unknown
htmldir = ${docdir}
infodir = ${datarootdir}/info
install_sh = ${SHELL} /run/media/echappa/Work/alpine/alpinegit/install-sh
libdir = ${exec_prefix}/lib
libexecdir = ${exec_prefix}/libexec
localedir = ${datadir}/locale
localstatedir = ${prefix}/var
lt_ECHO = @lt_ECHO@
mandir = ${datarootdir}/man
mkdir_p = $(MKDIR_P)
oldIncludedir = @oldIncludedir@
pdfdir = ${docdir}
prefix = /usr/local
program_transform_name = s,x,x,
psdir = ${docdir}
sbindir = ${exec_prefix}/sbin
sharedstatedir = ${prefix}/com
srcdir = .
sysconfdir = ${prefix}/etc
target_alias =
top_build_prefix = ../
top_builddir = ..
top_srcdir = ..
noinst_LIBRARIES = libregex.a
libregex_a_SOURCES = regcomp.c regerror.c regexec.c regfree.c
AM_CPPFLAGS = -I../include -I../include
all: all-am
.SUFFIXES:
.SUFFIXES: .c .lo .o .obj
$(srcdir)/Makefile.in: # $(srcdir)/Makefile.am $(am__configure_deps)
@for dep in $?; do \
case '$(am__configure_deps)' in \
*$$dep*) \
( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
&& { if test -f $@; then exit 0; else break; fi; }; \
exit 1;; \
esac; \
done; \
echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign regex/Makefile'; \
$(am__cd) $(top_srcdir) && \
$(AUTOMAKE) --foreign regex/Makefile
.PRECIOUS: Makefile
Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
@case '$?' in \
*config.status*) \
cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \
*) \
echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \
cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \
esac;
$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES)
cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
$(top_srcdir)/configure: # $(am__configure_deps)
cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
$(ACLOCAL_M4): # $(am__aclocal_m4_deps)
cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
$(am__aclocal_m4_deps):
clean-noinstLIBRARIES:
-test -z "$(noinst_LIBRARIES)" || rm -f $(noinst_LIBRARIES)
libregex.a: $(libregex_a_OBJECTS) $(libregex_a_DEPENDENCIES)
-rm -f libregex.a
$(libregex_a_AR) libregex.a $(libregex_a_OBJECTS) $(libregex_a_LIBADD)
$(RANLIB) libregex.a
mostlyclean-compile:
-rm -f *.$(OBJEXT)
distclean-compile:
-rm -f *.tab.c
include ./$(DEPDIR)/regcomp.Po
include ./$(DEPDIR)/regerror.Po
include ./$(DEPDIR)/regexec.Po
include ./$(DEPDIR)/regfree.Po
.c.o:
$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $<
$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
# source='$<' object='$@' libtool=no \
# DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \
# $(COMPILE) -c $<
.c.obj:
$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ `$(CYGPATH_W) '$<'`
$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
# source='$<' object='$@' libtool=no \
# DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \
# $(COMPILE) -c `$(CYGPATH_W) '$<'`
.c.lo:
$(LTCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $<
$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo
# source='$<' object='$@' libtool=yes \
# DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \
# $(LTCOMPILE) -c -o $@ $<
mostlyclean-libtool:
-rm -f *.lo
clean-libtool:
-rm -rf .libs _libs
ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES)
list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
unique=`for i in $$list; do \
if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
done | \
$(AWK) '{ files[$$0] = 1; nonempty = 1; } \
END { if (nonempty) { for (i in files) print i; }; }'`; \
mkid -fID $$unique
tags: TAGS
TAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \
$(TAGS_FILES) $(LISP)
set x; \
here=`pwd`; \
list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
unique=`for i in $$list; do \
if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
done | \
$(AWK) '{ files[$$0] = 1; nonempty = 1; } \
END { if (nonempty) { for (i in files) print i; }; }'`; \
shift; \
if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \
test -n "$$unique" || unique=$$empty_fix; \
if test $$# -gt 0; then \
$(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
"$$@" $$unique; \
else \
$(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
$$unique; \
fi; \
fi
ctags: CTAGS
CTAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \
$(TAGS_FILES) $(LISP)
list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
unique=`for i in $$list; do \
if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
done | \
$(AWK) '{ files[$$0] = 1; nonempty = 1; } \
END { if (nonempty) { for (i in files) print i; }; }'`; \
test -z "$(CTAGS_ARGS)$$unique" \
|| $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
$$unique
GTAGS:
here=`$(am__cd) $(top_builddir) && pwd` \
&& $(am__cd) $(top_srcdir) \
&& gtags -i $(GTAGS_ARGS) "$$here"
distclean-tags:
-rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
distdir: $(DISTFILES)
@srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
list='$(DISTFILES)'; \
dist_files=`for file in $$list; do echo $$file; done | \
sed -e "s|^$$srcdirstrip/||;t" \
-e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \
case $$dist_files in \
*/*) $(MKDIR_P) `echo "$$dist_files" | \
sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \
sort -u` ;; \
esac; \
for file in $$dist_files; do \
if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \
if test -d $$d/$$file; then \
dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
if test -d "$(distdir)/$$file"; then \
find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
fi; \
if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \
cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
fi; \
cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
else \
test -f "$(distdir)/$$file" \
|| cp -p $$d/$$file "$(distdir)/$$file" \
|| exit 1; \
fi; \
done
check-am: all-am
check: check-am
all-am: Makefile $(LIBRARIES)
installdirs:
install: install-am
install-exec: install-exec-am
install-data: install-data-am
uninstall: uninstall-am
install-am: all-am
@$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am
installcheck: installcheck-am
install-strip:
$(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
`test -z '$(STRIP)' || \
echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install
mostlyclean-generic:
clean-generic:
distclean-generic:
-test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
-test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES)
maintainer-clean-generic:
@echo "This command is intended for maintainers to use"
@echo "it deletes files that may require special tools to rebuild."
clean: clean-am
clean-am: clean-generic clean-libtool clean-noinstLIBRARIES \
mostlyclean-am
distclean: distclean-am
-rm -rf ./$(DEPDIR)
-rm -f Makefile
distclean-am: clean-am distclean-compile distclean-generic \
distclean-tags
dvi: dvi-am
dvi-am:
html: html-am
html-am:
info: info-am
info-am:
install-data-am:
install-dvi: install-dvi-am
install-dvi-am:
install-exec-am:
install-html: install-html-am
install-html-am:
install-info: install-info-am
install-info-am:
install-man:
install-pdf: install-pdf-am
install-pdf-am:
install-ps: install-ps-am
install-ps-am:
installcheck-am:
maintainer-clean: maintainer-clean-am
-rm -rf ./$(DEPDIR)
-rm -f Makefile
maintainer-clean-am: distclean-am maintainer-clean-generic
mostlyclean: mostlyclean-am
mostlyclean-am: mostlyclean-compile mostlyclean-generic \
mostlyclean-libtool
pdf: pdf-am
pdf-am:
ps: ps-am
ps-am:
uninstall-am:
.MAKE: install-am install-strip
.PHONY: CTAGS GTAGS all all-am check check-am clean clean-generic \
clean-libtool clean-noinstLIBRARIES ctags distclean \
distclean-compile distclean-generic distclean-libtool \
distclean-tags distdir dvi dvi-am html html-am info info-am \
install install-am install-data install-data-am install-dvi \
install-dvi-am install-exec install-exec-am install-html \
install-html-am install-info install-info-am install-man \
install-pdf install-pdf-am install-ps install-ps-am \
install-strip installcheck installcheck-am installdirs \
maintainer-clean maintainer-clean-generic mostlyclean \
mostlyclean-compile mostlyclean-generic mostlyclean-libtool \
pdf pdf-am ps ps-am tags uninstall uninstall-am
# Tell versions [3.59,3.63) of GNU make to not export all variables.
# Otherwise a system limit (for SysV at least) may be exceeded.
.NOEXPORT:
|
apache-2.0
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Rosales/Rosaceae/Prunus/Prunus padus/Padus asiatica subglabra/README.md
|
202
|
# Padus asiatica var. subglabra Y.L.Han & Chang Y.Yang VARIETY
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null
|
apache-2.0
|
mdoering/backbone
|
life/Fungi/Ascomycota/Arthoniomycetes/Arthoniales/Arthoniaceae/Arthonia/Arthonia obscurior/README.md
|
209
|
# Arthonia obscurior Triebel SPECIES
#### Status
ACCEPTED
#### According to
Index Fungorum
#### Published in
Biblthca Lichenol. 35: 62 (1989)
#### Original name
Arthonia obscurior Triebel
### Remarks
null
|
apache-2.0
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Orchidaceae/Thrixspermum/Thrixspermum centipeda/ Syn. Sarcochilus auriferus/README.md
|
195
|
# Sarcochilus auriferus (Lindl.) Rchb.f. SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
apache-2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.