text stringlengths 1 1.05M |
|---|
import { format, parse } from './kustomize-image';
test('parse image version override', () => {
const image = parse('foo/bar:v1.0.0');
expect(image.name).toBe('foo/bar');
expect(image.newTag).toBe('v1.0.0');
});
test('format image version override', () => {
const formatted = format({ name: 'foo/bar', newTag: 'v1.0.0' });
expect(formatted).toBe('foo/bar:v1.0.0');
});
test('parse image name override', () => {
const image = parse('foo/bar=foo/bar1:v1.0.0');
expect(image.name).toBe('foo/bar');
expect(image.newName).toBe('foo/bar1');
expect(image.newTag).toBe('v1.0.0');
});
test('format image name override', () => {
const formatted = format({ name: 'foo/bar', newTag: 'v1.0.0', newName: 'foo/bar1' });
expect(formatted).toBe('foo/bar=foo/bar1:v1.0.0');
});
test('parse image digest override', () => {
const image = parse('foo/bar@sha:123');
expect(image.name).toBe('foo/bar');
expect(image.digest).toBe('sha:123');
});
test('format image digest override', () => {
const formatted = format({ name: 'foo/bar', digest: 'sha:123' });
expect(formatted).toBe('foo/bar@sha:123');
});
|
#!/usr/bin/env bash
# set -e: exit asap if a command exits with a non-zero status
set -e
echoerr() { printf "%s\n" "$*" >&2; }
# print error and exit
die () {
echoerr "ERROR: $1"
# if $2 is defined AND NOT EMPTY, use $2; otherwise, set to "150"
errnum=${2-110}
exit $errnum
}
# Required params (some)
[ -z "${WAIT_TIMEOUT}" ] && die "Required env var WAIT_TIMEOUT"
[ -z "${COMMON_CAPS}" ] && die "Required env var COMMON_CAPS"
[ -z "${SELENIUM_JAR_PATH}" ] && die "Required env var SELENIUM_JAR_PATH"
[ -z "${SELENIUM_NODE_HOST}" ] && die "Required env var SELENIUM_NODE_HOST"
[ -z "${CHROME_VERSION}" ] && die "Required env var CHROME_VERSION"
[ -z "${CHROME_PATH}" ] && die "Required env var CHROME_PATH"
if [ "${ZALENIUM}" != "true" ]; then
timeout --foreground ${WAIT_TIMEOUT} wait-selenium-hub.sh || \
shutdown "Failed while waiting for selenium hub to start!"
fi
JAVA_OPTS="$(java-dynamic-memory-opts.sh) ${JAVA_OPTS}"
echo "INFO: JAVA_OPTS are '${JAVA_OPTS}'"
# See standalone params docs at
# https://code.google.com/p/selenium/wiki/Grid2
# https://github.com/pilwon/selenium-webdriver/blob/master/java/server/src/org/openqa/grid/common/defaults/GridParameters.properties
# See node defaults at
# https://github.com/pilwon/selenium-webdriver/blob/master/java/server/src/org/openqa/grid/common/defaults/DefaultNode.json
CHROME_BROWSER_CAPS="browserName=chrome,${COMMON_CAPS}"
CHROME_BROWSER_CAPS="${CHROME_BROWSER_CAPS},version=${CHROME_VERSION}"
CHROME_BROWSER_CAPS="${CHROME_BROWSER_CAPS},chrome_binary=${CHROME_PATH}"
java \
-Dwebdriver.chrome.driver="/home/seluser/chromedriver" \
-Dwebdriver.chrome.logfile="${LOGS_DIR}/chrome_driver.log" \
-Dwebdriver.chrome.verboseLogging="${CHROME_VERBOSELOGGING}" \
${JAVA_OPTS} \
-jar ${SELENIUM_JAR_PATH} \
-port ${SELENIUM_NODE_CH_PORT} \
-host ${SELENIUM_NODE_HOST} \
-role node \
-hub "${SELENIUM_HUB_PROTO}://${SELENIUM_HUB_HOST}:${SELENIUM_HUB_PORT}/grid/register" \
-browser "${CHROME_BROWSER_CAPS}" \
-maxSession ${MAX_SESSIONS} \
-timeout ${SEL_RELEASE_TIMEOUT_SECS} \
-browserTimeout ${SEL_BROWSER_TIMEOUT_SECS} \
-cleanUpCycle ${SEL_CLEANUPCYCLE_MS} \
-nodePolling ${SEL_NODEPOLLING_MS} \
-unregisterIfStillDownAfter ${SEL_UNREGISTER_IF_STILL_DOWN_AFTER} \
${SELENIUM_NODE_PARAMS} \
${CUSTOM_SELENIUM_NODE_PROXY_PARAMS} \
${CUSTOM_SELENIUM_NODE_REGISTER_CYCLE} \
&
NODE_PID=$!
function shutdown {
echo "-- INFO: Shutting down Chrome NODE gracefully..."
kill -SIGINT ${NODE_PID} || true
kill -SIGTERM ${NODE_PID} || true
kill -SIGKILL ${NODE_PID} || true
wait ${NODE_PID}
echo "-- INFO: Chrome node shutdown complete."
# First stop video recording because it needs some time to flush it
supervisorctl -c /etc/supervisor/supervisord.conf stop video-rec || true
exit 0
}
function trappedFn {
echo "-- INFO: Trapped SIGTERM/SIGINT on Chrome NODE"
shutdown
}
# Run function shutdown() when this process receives a killing signal
trap trappedFn SIGTERM SIGINT SIGKILL
# tells bash to wait until child processes have exited
wait ${NODE_PID}
echo "-- INFO: Passed after wait java Chrome node"
# Always shutdown if the node dies
shutdown
# Note to double pipe output and keep this process logs add at the end:
# 2>&1 | tee $SELENIUM_LOG
# But is no longer required because individual logs are maintained by
# supervisord right now.
|
#!/bin/bash
export KSI_CONF=test/test.cfg
@test "CDM test: use invalid stdin combination" {
run src/logksi verify --log-from-stdin --input-hash - test/resource/interlink/ok-testlog-interlink-1.logsig
[ "$status" -eq 3 ]
[[ "$output" =~ "Error: Multiple different simultaneous inputs from stdin (--input-hash -, --log-from-stdin)" ]]
}
@test "CDM test: use invalid stdout combination" {
run src/logksi verify test/resource/interlink/ok-testlog-interlink-1 --log - --output-hash -
[ "$status" -eq 3 ]
[[ "$output" =~ "Error: Multiple different simultaneous outputs to stdout (--log -, --output-hash -)." ]]
}
@test "verify CMD test: use invalid stdin combination" {
run src/logksi verify --log-from-stdin --input-hash - test/resource/interlink/ok-testlog-interlink-1.logsig
[ "$status" -eq 3 ]
[[ "$output" =~ "Error: Multiple different simultaneous inputs from stdin (--input-hash -, --log-from-stdin)" ]]
}
@test "verify CMD test: use invalid stdout combination" {
run src/logksi verify test/resource/interlink/ok-testlog-interlink-1 --log - --output-hash -
[ "$status" -eq 3 ]
[[ "$output" =~ "Error: Multiple different simultaneous outputs to stdout (--log -, --output-hash -)." ]]
}
@test "verify CMD test: try to use only one not existing input file" {
run src/logksi verify i_do_not_exist
[ "$status" -eq 3 ]
[[ "$output" =~ (File does not exist).*(Parameter).*(--input).*(i_do_not_exist) ]]
}
@test "verify CMD test: try to use two not existing input files" {
run src/logksi verify i_do_not_exist_1 i_do_not_exist_2
[ "$status" -eq 3 ]
[[ "$output" =~ (File does not exist).*(Parameter).*(--input).*(i_do_not_exist_1) ]]
[[ "$output" =~ (File does not exist).*(Parameter).*(--input).*(i_do_not_exist_2) ]]
}
@test "verify CMD test: try to use two not existing input files after --" {
run src/logksi verify -- i_do_not_exist_1 i_do_not_exist_2
[ "$status" -eq 3 ]
[[ "$output" =~ (File does not exist).*(Parameter).*(--input).*(i_do_not_exist_1) ]]
[[ "$output" =~ (File does not exist).*(Parameter).*(--input).*(i_do_not_exist_2) ]]
}
@test "verify CMD test: existing explicitly specified log and log signature file with one unexpected but existing extra file" {
run src/logksi verify test/resource/logs_and_signatures/log_repaired test/resource/logs_and_signatures/log_repaired.logsig test/resource/logfiles/unsigned
[ "$status" -eq 3 ]
[[ "$output" =~ "Error: Only two inputs (log and log signature file) are required, but there are 3!" ]]
}
@test "verify CMD test: existing explicitly specified log and log signature file with one unexpected token that is not existing file" {
run src/logksi verify test/resource/logs_and_signatures/log_repaired i_do_not_exist
[ "$status" -eq 3 ]
[[ "$output" =~ (File does not exist).*(Parameter).*(--input).*(i_do_not_exist) ]]
}
@test "verify CMD test: Try to verify log file from stdin and specify multiple input files" {
run bash -c "echo dummy signature | ./src/logksi verify --log-from-stdin -ddd test/resource/logfiles/unsigned test/resource/logfiles/unsigned"
[ "$status" -eq 3 ]
[[ "$output" =~ (Error).*(Log file from stdin [(]--log-from-stdin[)] needs only ONE explicitly specified log signature file, but there are 2) ]]
}
@test "verify CMD test: Try to verify log file from stdin and from input after --" {
run bash -c "echo dummy signature | ./src/logksi verify --log-from-stdin -ddd -- test/resource/logfiles/unsigned"
[ "$status" -eq 3 ]
[[ "$output" =~ (Error).*(It is not possible to verify both log file from stdin [(]--log-from-stdin[)] and log file[(]s[)] specified after [-][-]) ]]
}
@test "verify CMD test: Try to use invalid publication string: Invalid character" {
run ./src/logksi verify --ver-pub test/resource/logs_and_signatures/log_repaired --pub-str AAAAAA-C2PMAF-IAISKD-4JLNKD-ZFCF5L-4OWMS5-DMJLTC-DCJ6SS-QDFBC4-ELLWTM-5BO7WF-I7W2J#
[ "$status" -eq 3 ]
[[ "$output" =~ (Invalid base32 character).*(Parameter).*(--pub-str).*(AAAAAA-C2PMAF-IAISKD-4JLNKD-ZFCF5L-4OWMS5-DMJLTC-DCJ6SS-QDFBC4-ELLWTM-5BO7WF-I7W2J#) ]]
}
@test "verify CMD test: Try to use invalid publication string: Too short" {
run ./src/logksi verify --ver-pub test/resource/logs_and_signatures/log_repaired --pub-str AAAAAA-C2PMAF-IAISKD-4JLNKD-ZFCF5L-4OWMS5-DMJLTC-DCJ6SS-QDFBC4-ELLWTM-5BO7WF
[ "$status" -eq 4 ]
[[ "$output" =~ (Error).*(Unable parse publication string) ]]
}
@test "verify CMD test: Try to use invalid certificate constraints: Invalid constraints format" {
run ./src/logksi verify --ver-key test/resource/logs_and_signatures/log_repaired -ddd --ignore-desc-block-time --cnstr = --cnstr =A --cnstr B=
[ "$status" -eq 3 ]
[[ "$output" =~ (Parameter is invalid).*(Parameter).*(--cnstr).*(=) ]]
[[ "$output" =~ (Parameter is invalid).*(Parameter).*(--cnstr).*(=A) ]]
[[ "$output" =~ (Parameter is invalid).*(Parameter).*(--cnstr).*(B=) ]]
}
@test "verify CMD test: Try to use invalid certificate constraints: Invalid constraints OID" {
run ./src/logksi verify --ver-key test/resource/logs_and_signatures/log_repaired -ddd --ignore-desc-block-time --cnstr dummy=nothing
[ "$status" -eq 3 ]
[[ "$output" =~ (OID is invalid).*(Parameter).*(--cnstr).*(dummy=nothing) ]]
}
@test "verify CMD test: Try to use invalid --time-diff 1" {
run ./src/logksi verify --ver-key test/resource/logs_and_signatures/log_repaired -d --time-diff "" --time-diff " " --time-diff S --time-diff M --time-diff H --time-diff d --time-diff s --time-diff m --time-diff h --time-diff D --time-diff - --time-diff o
[ "$status" -eq 3 ]
[[ "$output" =~ (Parameter has no content).*(Parameter).*(--time-diff).*(\'\') ]]
[[ "$output" =~ (Only digits and 1x d, H, M and S allowed).*(Parameter).*(--time-diff).*(\' \') ]]
[[ "$output" =~ (Only digits and 1x d, H, M and S allowed).*(Parameter).*(--time-diff).*(\'S\') ]]
[[ "$output" =~ (Only digits and 1x d, H, M and S allowed).*(Parameter).*(--time-diff).*(\'M\') ]]
[[ "$output" =~ (Only digits and 1x d, H, M and S allowed).*(Parameter).*(--time-diff).*(\'H\') ]]
[[ "$output" =~ (Only digits and 1x d, H, M and S allowed).*(Parameter).*(--time-diff).*(\'d\') ]]
[[ "$output" =~ (Only digits and 1x d, H, M and S allowed).*(Parameter).*(--time-diff).*(\'s\') ]]
[[ "$output" =~ (Only digits and 1x d, H, M and S allowed).*(Parameter).*(--time-diff).*(\'m\') ]]
[[ "$output" =~ (Only digits and 1x d, H, M and S allowed).*(Parameter).*(--time-diff).*(\'h\') ]]
[[ "$output" =~ (Only digits and 1x d, H, M and S allowed).*(Parameter).*(--time-diff).*(\'D\') ]]
[[ "$output" =~ (Only digits and 1x d, H, M and S allowed).*(Parameter).*(--time-diff).*(\'-\') ]]
[[ "$output" =~ (Only digits and 1x d, H, M and S allowed).*(Parameter).*(--time-diff).*(\'o\') ]]
}
@test "verify CMD test: Try to use invalid --time-diff 2" {
run ./src/logksi verify --ver-key test/resource/logs_and_signatures/log_repaired -d --time-diff 1S2 --time-diff 1S3S --time-diff 1M3M --time-diff 1H3H --time-diff 1d3d --time-diff "2 2" --time-diff dHMS --time-diff S5 --time-diff M6 --time-diff H7 --time-diff d8 --time-diff --2 --time-diff 2d-1 --time-diff 2D
[ "$status" -eq 3 ]
[[ "$output" =~ (Only digits and 1x d, H, M and S allowed).*(Parameter).*(--time-diff).*(1S2) ]]
[[ "$output" =~ (Only digits and 1x d, H, M and S allowed).*(Parameter).*(--time-diff).*(1S3S) ]]
[[ "$output" =~ (Only digits and 1x d, H, M and S allowed).*(Parameter).*(--time-diff).*(1M3M) ]]
[[ "$output" =~ (Only digits and 1x d, H, M and S allowed).*(Parameter).*(--time-diff).*(1H3H) ]]
[[ "$output" =~ (Only digits and 1x d, H, M and S allowed).*(Parameter).*(--time-diff).*(1d3d) ]]
[[ "$output" =~ (Only digits and 1x d, H, M and S allowed).*(Parameter).*(--time-diff).*(2 2) ]]
[[ "$output" =~ (Only digits and 1x d, H, M and S allowed).*(Parameter).*(--time-diff).*(dHMS) ]]
[[ "$output" =~ (Only digits and 1x d, H, M and S allowed).*(Parameter).*(--time-diff).*(S5) ]]
[[ "$output" =~ (Only digits and 1x d, H, M and S allowed).*(Parameter).*(--time-diff).*(M6) ]]
[[ "$output" =~ (Only digits and 1x d, H, M and S allowed).*(Parameter).*(--time-diff).*(H7) ]]
[[ "$output" =~ (Only digits and 1x d, H, M and S allowed).*(Parameter).*(--time-diff).*(d8) ]]
[[ "$output" =~ (Only digits and 1x d, H, M and S allowed).*(Parameter).*(--time-diff).*(--2) ]]
[[ "$output" =~ (Only digits and 1x d, H, M and S allowed).*(Parameter).*(--time-diff).*(2d-1) ]]
[[ "$output" =~ (Only digits and 1x d, H, M and S allowed).*(Parameter).*(--time-diff).*(2D) ]]
}
@test "verify CMD test: Try to use invalid --time-diff range (n,m)" {
run ./src/logksi verify --ver-key test/resource/logs_and_signatures/log_repaired -d --time-diff , --time-diff 5, --time-diff ,5 --time-diff 5,4 --time-diff -5,-4 --time-diff -3,2, --time-diff 5,oo --time-diff -oo,oo
[ "$status" -eq 3 ]
[[ "$output" =~ (Time range should be -<int>,<int>.).*(Parameter).*(--time-diff).*(,) ]]
[[ "$output" =~ (Time range should be -<int>,<int>.).*(Parameter).*(--time-diff).*(5,) ]]
[[ "$output" =~ (Time range should be -<int>,<int>.).*(Parameter).*(--time-diff).*(,5) ]]
[[ "$output" =~ (Time range should be -<int>,<int>.).*(Parameter).*(--time-diff).*(5,4) ]]
[[ "$output" =~ (Time range should be -<int>,<int>.).*(Parameter).*(--time-diff).*(-5,-4) ]]
[[ "$output" =~ (Time range should be -<int>,<int>.).*(Parameter).*(--time-diff).*(-3,2,) ]]
[[ "$output" =~ (Time range should be -<int>,<int>.).*(Parameter).*(--time-diff).*(5,oo) ]]
[[ "$output" =~ (Time range should be -<int>,<int>.).*(Parameter).*(--time-diff).*(-oo,oo) ]]
}
@test "verify CMD test: Try to use invalid --block-time-diff range" {
run ./src/logksi verify --ver-key test/resource/logs_and_signatures/log_repaired -d --block-time-diff -oo,-oo --block-time-diff oo,oo --block-time-diff ,oo --block-time-diff oo, --block-time-diff o --block-time-diff -o --block-time-diff 5,o --block-time-diff o,5 --block-time-diff o,o
[ "$status" -eq 3 ]
[[ "$output" =~ (Time range with infinity can be -oo,oo, <int>,oo or -oo,<int>).*(Parameter).*(--block-time-diff).*(-oo,-oo) ]]
[[ "$output" =~ (Time range with infinity can be -oo,oo, <int>,oo or -oo,<int>).*(Parameter).*(--block-time-diff).*(oo,oo) ]]
[[ "$output" =~ (Time range should be -<int>,<int>).*(Parameter).*(--block-time-diff).*(,oo) ]]
[[ "$output" =~ (Time range with infinity can be -oo,oo, <int>,oo or -oo,<int>).*(Parameter).*(--block-time-diff).*(oo,) ]]
[[ "$output" =~ (Only digits, oo and 1x d, H, M and S allowed).*(Parameter).*(--block-time-diff).*(o) ]]
[[ "$output" =~ (Only digits, oo and 1x d, H, M and S allowed).*(Parameter).*(--block-time-diff).*(-o) ]]
[[ "$output" =~ (Only digits, oo and 1x d, H, M and S allowed).*(Parameter).*(--block-time-diff).*(5,o) ]]
[[ "$output" =~ (Only digits, oo and 1x d, H, M and S allowed).*(Parameter).*(--block-time-diff).*(o,5) ]]
[[ "$output" =~ (Only digits, oo and 1x d, H, M and S allowed).*(Parameter).*(--block-time-diff).*(o,o) ]]
}
@test "verify CMD test: Check if --time-disordered has the same type as --time-diff but does not allow comma nor minus nor infinity" {
run ./src/logksi verify --ver-key test/resource/logs_and_signatures/log_repaired -d --time-disordered 1S2
[ "$status" -eq 3 ]
[[ "$output" =~ (Only digits and 1x d, H, M and S allowed).*(Parameter).*(--time-disordered).*(1S2) ]]
run ./src/logksi verify --ver-key test/resource/logs_and_signatures/log_repaired -d --time-disordered 1,1
[ "$status" -eq 3 ]
[[ "$output" =~ (No comma .,. supported for range).*(Parameter).*(--time-disordered).*(1,1) ]]
run ./src/logksi verify --ver-key test/resource/logs_and_signatures/log_repaired -d --time-disordered -5
[ "$status" -eq 3 ]
[[ "$output" =~ (Only unsigned value allowed).*(Parameter).*(--time-disordered).*(-5) ]]
run ./src/logksi verify --ver-key test/resource/logs_and_signatures/log_repaired -d --time-disordered oo
[ "$status" -eq 3 ]
[[ "$output" =~ (Only digits and 1x d, H, M and S allowe).*(Parameter).*(--time-disordered).*(oo) ]]
}
@test "verify CMD test: Check parsing of --time-diff S" {
run ./src/logksi verify --ver-key test/resource/logs_and_signatures/signed --time-form "%B %d %H:%M:%S" --time-base 2018 --time-diff -2
[[ "$output" =~ (Expected time window).*(-00:00:02) ]]
run ./src/logksi verify --ver-key test/resource/logs_and_signatures/signed --time-form "%B %d %H:%M:%S" --time-base 2018 --time-diff -2S
[[ "$output" =~ (Expected time window).*(-00:00:02) ]]
run ./src/logksi verify --ver-key test/resource/logs_and_signatures/signed --time-form "%B %d %H:%M:%S" --time-base 2018 --time-diff -59S
[[ "$output" =~ (Expected time window).*(-00:00:59) ]]
run ./src/logksi verify --ver-key test/resource/logs_and_signatures/signed --time-form "%B %d %H:%M:%S" --time-base 2018 --time-diff -60S
[[ "$output" =~ (Expected time window).*(-00:01:00) ]]
run ./src/logksi verify --ver-key test/resource/logs_and_signatures/signed --time-form "%B %d %H:%M:%S" --time-base 2018 --time-diff -121
[[ "$output" =~ (Expected time window).*(-00:02:01) ]]
run ./src/logksi verify --ver-key test/resource/logs_and_signatures/signed --time-form "%B %d %H:%M:%S" --time-base 2018 --time-diff -3599
[[ "$output" =~ (Expected time window).*(-00:59:59) ]]
run ./src/logksi verify --ver-key test/resource/logs_and_signatures/signed --time-form "%B %d %H:%M:%S" --time-base 2018 --time-diff -3600
[[ "$output" =~ (Expected time window).*(-01:00:00) ]]
run ./src/logksi verify --ver-key test/resource/logs_and_signatures/signed --time-form "%B %d %H:%M:%S" --time-base 2018 --time-diff -86400
[[ "$output" =~ (Expected time window).*(-1d 00:00:00) ]]
run ./src/logksi verify --ver-key test/resource/logs_and_signatures/signed --time-form "%B %d %H:%M:%S" --time-base 2018 --time-diff -6048000
[[ "$output" =~ (Expected time window).*(-70d 00:00:00) ]]
}
@test "verify CMD test: Check parsing of --time-diff M" {
run ./src/logksi verify --ver-key test/resource/logs_and_signatures/signed --time-form "%B %d %H:%M:%S" --time-base 2018 --time-diff -2M
[[ "$output" =~ (Expected time window).*(-00:02:00) ]]
run ./src/logksi verify --ver-key test/resource/logs_and_signatures/signed --time-form "%B %d %H:%M:%S" --time-base 2018 --time-diff -59M
[[ "$output" =~ (Expected time window).*(-00:59:00) ]]
run ./src/logksi verify --ver-key test/resource/logs_and_signatures/signed --time-form "%B %d %H:%M:%S" --time-base 2018 --time-diff -60M
[[ "$output" =~ (Expected time window).*(-01:00:00) ]]
run ./src/logksi verify --ver-key test/resource/logs_and_signatures/signed --time-form "%B %d %H:%M:%S" --time-base 2018 --time-diff -61M
[[ "$output" =~ (Expected time window).*(-01:01:00) ]]
run ./src/logksi verify --ver-key test/resource/logs_and_signatures/signed --time-form "%B %d %H:%M:%S" --time-base 2018 --time-diff -121M
[[ "$output" =~ (Expected time window).*(-02:01:00) ]]
run ./src/logksi verify --ver-key test/resource/logs_and_signatures/signed --time-form "%B %d %H:%M:%S" --time-base 2018 --time-diff -1440M
[[ "$output" =~ (Expected time window).*(-1d 00:00:00) ]]
}
@test "verify CMD test: Check parsing of --time-diff H" {
run ./src/logksi verify --ver-key test/resource/logs_and_signatures/signed --time-form "%B %d %H:%M:%S" --time-base 2018 --time-diff -2H
[[ "$output" =~ (Expected time window).*(-02:00:00) ]]
run ./src/logksi verify --ver-key test/resource/logs_and_signatures/signed --time-form "%B %d %H:%M:%S" --time-base 2018 --time-diff -23H
[[ "$output" =~ (Expected time window).*(-23:00:00) ]]
run ./src/logksi verify --ver-key test/resource/logs_and_signatures/signed --time-form "%B %d %H:%M:%S" --time-base 2018 --time-diff -24H
[[ "$output" =~ (Expected time window).*(-1d 00:00:00) ]]
run ./src/logksi verify --ver-key test/resource/logs_and_signatures/signed --time-form "%B %d %H:%M:%S" --time-base 2018 --time-diff -48H
[[ "$output" =~ (Expected time window).*(-2d 00:00:00) ]]
run ./src/logksi verify --ver-key test/resource/logs_and_signatures/signed --time-form "%B %d %H:%M:%S" --time-base 2018 --time-diff -49H
[[ "$output" =~ (Expected time window).*(-2d 01:00:00) ]]
}
@test "verify CMD test: Check parsing of --time-diff d" {
run ./src/logksi verify --ver-key test/resource/logs_and_signatures/signed --time-form "%B %d %H:%M:%S" --time-base 2018 --time-diff -2d
[[ "$output" =~ (Expected time window).*(-2d 00:00:00) ]]
run ./src/logksi verify --ver-key test/resource/logs_and_signatures/signed --time-form "%B %d %H:%M:%S" --time-base 2018 --time-diff -70d
[[ "$output" =~ (Expected time window).*(-70d 00:00:00) ]]
}
@test "verify CMD test: Check parsing of --time-diff S M H d" {
run ./src/logksi verify --ver-key test/resource/logs_and_signatures/signed --time-form "%B %d %H:%M:%S" --time-base 2018 --time-diff -0d3H5M0S
[[ "$output" =~ (Expected time window).*(-03:05:00) ]]
run ./src/logksi verify --ver-key test/resource/logs_and_signatures/signed --time-form "%B %d %H:%M:%S" --time-base 2018 --time-diff -0S0d5M3H
[[ "$output" =~ (Expected time window).*(-03:05:00) ]]
run ./src/logksi verify --ver-key test/resource/logs_and_signatures/signed --time-form "%B %d %H:%M:%S" --time-base 2018 --time-diff -10d59
[[ "$output" =~ (Expected time window).*(-10d 00:00:59) ]]
run ./src/logksi verify --ver-key test/resource/logs_and_signatures/signed --time-form "%B %d %H:%M:%S" --time-base 2018 --time-diff -1H59M60S
[[ "$output" =~ (Expected time window).*(-02:00:00) ]]
run ./src/logksi verify --ver-key test/resource/logs_and_signatures/signed --time-form "%B %d %H:%M:%S" --time-base 2018 --time-diff -23H59M60S
[[ "$output" =~ (Expected time window).*(-1d 00:00:00) ]]
}
@test "verify CMD test: Check parsing of --time-diff with 2 values (range)" {
run ./src/logksi verify test/resource/log_rec_time/log-line-embedded-date-higher-and-lower-from-ksig test/resource/log_rec_time/log-line-embedded-date-changed.logsig --use-stored-hash-on-fail --time-form "%B %d %H:%M:%S" --time-base 2018 --time-diff 1d,-1d17
[[ "$output" =~ (Expected time window).*(-1d 00:00:17 - 1d 00:00:00) ]]
run ./src/logksi verify test/resource/log_rec_time/log-line-embedded-date-higher-and-lower-from-ksig test/resource/log_rec_time/log-line-embedded-date-changed.logsig --use-stored-hash-on-fail --time-form "%B %d %H:%M:%S" --time-base 2018 --time-diff -1d17,1d
[[ "$output" =~ (Expected time window).*(-1d 00:00:17 - 1d 00:00:00) ]]
}
@test "verify CMD test: Check parsing of --block-time-diff" {
run ./src/logksi verify --ver-key test/resource/logs_and_signatures/signed -d --block-time-diff 1d1M32S,2
[[ "$output" =~ (Expected time diff).*(00:00:02 - 1d 00:01:32) ]]
run ./src/logksi verify --ver-key test/resource/logs_and_signatures/signed -d --block-time-diff 2,1d1M32S
[[ "$output" =~ (Expected time diff).*(00:00:02 - 1d 00:01:32) ]]
run ./src/logksi verify --ver-key test/resource/logs_and_signatures/signed -d --block-time-diff 2,oo
[[ "$output" =~ (Expected time diff).*(00:00:02 - oo) ]]
run ./src/logksi verify --ver-key test/resource/logs_and_signatures/signed -d --block-time-diff -oo
[[ "$output" =~ (Expected time diff).*(-oo - 0) ]]
run ./src/logksi verify --ver-key test/resource/logs_and_signatures/signed -d --block-time-diff -5
[[ "$output" =~ (Expected time diff).*(-00:00:05 - 0) ]]
run ./src/logksi verify --ver-key test/resource/logs_and_signatures/signed -d --block-time-diff -oo,-5
[[ "$output" =~ (Expected time diff).*(-oo - -00:00:05) ]]
run ./src/logksi verify --ver-key test/resource/logs_and_signatures/signed -d --block-time-diff 2,oo
[[ "$output" =~ (Expected time diff).*(00:00:02 - oo) ]]
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package colegio;
import java.awt.HeadlessException;
import javax.swing.JOptionPane;
/**
*
* @author CesarCuellar
*/
public class FrmAgregarAlumno extends javax.swing.JFrame {
/**
* Creates new form FrmAgregarAlumno
*/
public FrmAgregarAlumno() {
initComponents();
setLocationRelativeTo(this);
}
/**
* 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() {
txtCorreo1 = new javax.swing.JTextField();
jLabel8 = new javax.swing.JLabel();
txtCorreo2 = new javax.swing.JTextField();
jLabel9 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
txtIdentificacion = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
txtNombre = new javax.swing.JTextField();
jLabel4 = new javax.swing.JLabel();
txtCorreo = new javax.swing.JTextField();
jLabel5 = new javax.swing.JLabel();
cbGenero = new javax.swing.JComboBox<>();
btnAgregarAlumno = new javax.swing.JButton();
btnRegresar = new javax.swing.JButton();
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
txtIdentificacion1 = new javax.swing.JTextField();
jLabel10 = new javax.swing.JLabel();
txtNombre1 = new javax.swing.JTextField();
jLabel11 = new javax.swing.JLabel();
txtNombre2 = new javax.swing.JTextField();
txtCorreo3 = new javax.swing.JTextField();
jLabel12 = new javax.swing.JLabel();
txtCorreo1.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel8.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
jLabel8.setText("Correo:");
txtCorreo2.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel9.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
jLabel9.setText("Correo:");
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setUndecorated(true);
jLabel2.setFont(new java.awt.Font("Sinhala MN", 1, 14)); // NOI18N
jLabel2.setText("Matrícula:");
txtIdentificacion.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel3.setFont(new java.awt.Font("Sinhala MN", 1, 14)); // NOI18N
jLabel3.setText("Nombre(s):");
txtNombre.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel4.setFont(new java.awt.Font("Sinhala MN", 1, 14)); // NOI18N
jLabel4.setText("Correo:");
txtCorreo.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel5.setFont(new java.awt.Font("Sinhala MN", 1, 14)); // NOI18N
jLabel5.setText("Género:");
cbGenero.setFont(new java.awt.Font("Sinhala MN", 0, 14)); // NOI18N
cbGenero.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Femenino", "Masculino", "Otro" }));
cbGenero.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cbGeneroActionPerformed(evt);
}
});
btnAgregarAlumno.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
btnAgregarAlumno.setIcon(new javax.swing.ImageIcon(getClass().getResource("/colegio/Imagenes/file_add.png"))); // NOI18N
btnAgregarAlumno.setText("AGREGAR");
btnAgregarAlumno.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnAgregarAlumnoActionPerformed(evt);
}
});
btnRegresar.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
btnRegresar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/colegio/Imagenes/exit1.png"))); // NOI18N
btnRegresar.setText("REGRESAR");
btnRegresar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnRegresarActionPerformed(evt);
}
});
jPanel1.setBackground(new java.awt.Color(0, 0, 102));
jLabel1.setBackground(new java.awt.Color(0, 153, 204));
jLabel1.setFont(new java.awt.Font("Sinhala MN", 1, 18)); // NOI18N
jLabel1.setForeground(new java.awt.Color(255, 255, 255));
jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel1.setText("<NAME>");
jLabel1.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel1)
.addContainerGap())
);
jLabel7.setFont(new java.awt.Font("Sinhala MN", 1, 14)); // NOI18N
jLabel7.setText("Dirección:");
txtIdentificacion1.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel10.setFont(new java.awt.Font("Sinhala MN", 1, 14)); // NOI18N
jLabel10.setText("Edad:");
txtNombre1.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
txtNombre1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtNombre1ActionPerformed(evt);
}
});
jLabel11.setFont(new java.awt.Font("Sinhala MN", 1, 14)); // NOI18N
jLabel11.setText("Apellidos:");
txtNombre2.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
txtCorreo3.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel12.setFont(new java.awt.Font("Sinhala MN", 1, 14)); // NOI18N
jLabel12.setText("Semestre:");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel6)
.addGap(28, 28, 28))
.addGroup(layout.createSequentialGroup()
.addGap(16, 16, 16)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addGap(1, 1, 1)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 99, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3))
.addGap(31, 31, 31)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(btnAgregarAlumno, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(54, 54, 54)
.addComponent(btnRegresar, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(txtIdentificacion, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 173, Short.MAX_VALUE)
.addComponent(txtNombre, javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(txtNombre2))))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addGap(2, 2, 2)
.addComponent(jLabel11))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addGap(130, 130, 130)
.addComponent(txtNombre1, javax.swing.GroupLayout.PREFERRED_SIZE, 173, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 99, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel4)
.addGroup(layout.createSequentialGroup()
.addGap(1, 1, 1)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel5)
.addComponent(jLabel10)))
.addComponent(jLabel12))
.addGap(32, 32, 32)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(cbGenero, javax.swing.GroupLayout.PREFERRED_SIZE, 173, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtCorreo, javax.swing.GroupLayout.PREFERRED_SIZE, 173, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtIdentificacion1, javax.swing.GroupLayout.PREFERRED_SIZE, 173, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtCorreo3, javax.swing.GroupLayout.PREFERRED_SIZE, 173, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addGap(44, 44, 44)))
.addContainerGap(37, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel2)
.addComponent(txtIdentificacion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(txtNombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(121, 121, 121)
.addComponent(jLabel6))
.addGroup(layout.createSequentialGroup()
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel11)
.addComponent(txtNombre2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txtNombre1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel10))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(23, 23, 23)
.addComponent(jLabel5))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(cbGenero, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel7)
.addComponent(txtIdentificacion1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(26, 26, 26)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4)
.addComponent(txtCorreo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txtCorreo3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel12))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 26, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(btnRegresar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btnAgregarAlumno, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(21, 21, 21))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void btnRegresarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRegresarActionPerformed
// TODO add your handling code here:
this.dispose();
}//GEN-LAST:event_btnRegresarActionPerformed
/**
* Método que agrega un alumno a la lista de Alumnos
* @param evt
*/
private void btnAgregarAlumnoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAgregarAlumnoActionPerformed
// TODO add your handling code here:
if (!txtCorreo.getText().isEmpty() && !txtIdentificacion.getText().isEmpty()
&& !txtNombre.getText().isEmpty()){
try{
int identifica= Integer.parseInt(txtIdentificacion.getText());
String nombre = txtNombre.getText();
String correo = txtCorreo.getText();
String genero = cbGenero.getSelectedItem().toString();
Alumno unAlumno = new Alumno(genero, txtIdentificacion.getText(), nombre, correo);
if (GestionColegio.existeAlumno(txtIdentificacion.getText())==false){
GestionColegio.agregarAlumno(unAlumno);
JOptionPane.showMessageDialog(null, "Alumno Agregado");
txtCorreo.setText("");
txtIdentificacion.setText("");
txtNombre.setText("");
}else{
JOptionPane.showMessageDialog(null, "Ya existe un alumno con esa identificación");
}
}catch(NumberFormatException | HeadlessException ex){
JOptionPane.showMessageDialog(null, "Error " + ex.getMessage());
}
}else{
JOptionPane.showMessageDialog(null, "Faltan Datos");
}
}//GEN-LAST:event_btnAgregarAlumnoActionPerformed
private void cbGeneroActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbGeneroActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_cbGeneroActionPerformed
private void txtNombre1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtNombre1ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtNombre1ActionPerformed
/**
* @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(FrmAgregarAlumno.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(FrmAgregarAlumno.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(FrmAgregarAlumno.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(FrmAgregarAlumno.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 FrmAgregarAlumno().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnAgregarAlumno;
private javax.swing.JButton btnRegresar;
private javax.swing.JComboBox<String> cbGenero;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel11;
private javax.swing.JLabel jLabel12;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JPanel jPanel1;
private javax.swing.JTextField txtCorreo;
private javax.swing.JTextField txtCorreo1;
private javax.swing.JTextField txtCorreo2;
private javax.swing.JTextField txtCorreo3;
private javax.swing.JTextField txtIdentificacion;
private javax.swing.JTextField txtIdentificacion1;
private javax.swing.JTextField txtNombre;
private javax.swing.JTextField txtNombre1;
private javax.swing.JTextField txtNombre2;
// End of variables declaration//GEN-END:variables
}
|
package com.inner.lovetao.loginregister.di.module;
import com.inner.lovetao.loginregister.mvp.contract.BindPhoneActivityContract;
import com.inner.lovetao.loginregister.mvp.model.BindPhoneActivityModel;
import dagger.Binds;
import dagger.Module;
/**
* desc:
* Created by xcz
* on 2019/01/28
*/
@Module
public abstract class BindPhoneActivityModule {
@Binds
abstract BindPhoneActivityContract.Model bindBindPhoneActivityModel(BindPhoneActivityModel model);
} |
<gh_stars>10-100
import React, {Component} from 'react'
import {Map} from 'immutable'
import {List, Icon, Tag} from 'antd'
import {send} from 'sockets/socket-actions'
import {API_ACTIONS} from 'consts'
import {connect} from 'react-redux'
import {createStructuredSelector} from 'reselect'
import {filesSelector, filterSelector, hasPendingRequest, indexSelector, locationSelect} from 'selectors'
import {setCurrentPath} from 'file-tree/file-actions'
import {Link} from 'react-router-dom'
import FileView from 'file-view/file-view'
import Loader from 'loader/loader'
import filesize from 'file-size'
const File = ({path, is_dir, instances, key, showFullPath = false}) => {
const filename = showFullPath ? '/' + path.join('/') : path[path.length - 1]
let content
if (is_dir) {
content = <span>
<Icon type={'folder'}/><Link to={`/${path.join('/')}`}>{filename}</Link>
{instances.map(instance => <Tag key={instance.fs}>{instance.fs}</Tag>)}
</span>
} else {
const viewURL = `/${path.join('/')}`
content = <span>
<Icon type={'file'}/> <Link to={viewURL}>{filename}</Link>
{instances.map(instance => <Tag key={instance.fs}><Link to={`${viewURL}?fs=${instance.fs}`}>{instance.fs} <span className="size">({filesize(instance.size, {fixed: 0}).human()})</span></Link></Tag>)}
<a href={`${window.location.origin}${window.__INIT__.basePath}/_dl/${path.join('/')}`} target="_blank" title="Download logs"><Icon type="download"/></a>
</span>
}
return (
<List.Item className="file">
{content}
</List.Item>
)
}
@connect(createStructuredSelector({
files: filesSelector,
index: indexSelector,
location: locationSelect,
filter: filterSelector,
requesting: hasPendingRequest(API_ACTIONS.GET_FILE_TREE),
}), {
send,
setCurrentPath,
})
class FileTree extends Component {
render() {
const {index, files, requesting, match: {params}, filter} = this.props
const path = (params[0] || '').split('/').filter(Boolean)
const isDir = path.length === 0 || index.getIn([path.join('/'), 'is_dir'])
let data
let content = <FileView path={path} key={path}/>
if (isDir) {
data = files.getIn(path.concat(['files']), Map()).valueSeq().toJS()
if (filter) {
if (path.length) {
data = index.filter((value, key) => key.startsWith(path.join('/') + '/'))
} else {
data = index
}
data = data.filter((value, key) => key.includes(filter)).valueSeq().toJS()
}
if (requesting) {
content = <Loader/>
} else {
content = <List
dataSource={data}
renderItem={file => <File {...file} showFullPath={filter}/>}
/>
}
}
return content
}
}
export default FileTree |
REMOTE_URL="https://git.webkit.org/git/WebKit.git"
BASE_BRANCH="master"
BASE_REVISION="633b5f0dd3b32d0cfdcae97e191c5b010e18a0e0"
|
#!/bin/bash
# Copyright (c) 2011 The WebRTC project authors. All Rights Reserved.
#
# Use of this source code is governed by a BSD-style license
# that can be found in the LICENSE file in the root of the source
# tree. An additional intellectual property rights grant can be found
# in the file PATENTS. All contributing project authors may
# be found in the AUTHORS file in the root of the source tree.
# Set up some paths and re-direct the arguments to webrtc_tests.py
# This script is a copy of the chrome_tests.sh wrapper script with the following
# changes:
# - The locate_valgrind.sh of Chromium's Valgrind scripts dir is used to locate
# the Valgrind framework install. If it fails a fallback path is used instead
# (../../chromium/src/third_party/valgrind/linux_x64) and a warning message
# is showed by |show_locate_valgrind_failed_warning|.
# - webrtc_tests.py is invoked instead of chrome_tests.py.
# - Chromium's Valgrind scripts directory is added to the PYTHONPATH to make it
# possible to execute the Python scripts properly.
export THISDIR=`dirname $0`
ARGV_COPY="$@"
# We need to set CHROME_VALGRIND iff using Memcheck:
# tools_webrtc/valgrind/webrtc_tests.sh --tool memcheck
# or
# tools_webrtc/valgrind/webrtc_tests.sh --tool=memcheck
tool="memcheck" # Default to memcheck.
while (( "$#" ))
do
if [[ "$1" == "--tool" ]]
then
tool="$2"
shift
elif [[ "$1" =~ --tool=(.*) ]]
then
tool="${BASH_REMATCH[1]}"
fi
shift
done
NEEDS_VALGRIND=0
case "$tool" in
"memcheck")
NEEDS_VALGRIND=1
;;
esac
# For WebRTC, we'll use the locate_valgrind.sh script in Chromium's Valgrind
# scripts dir to locate the Valgrind framework install
CHROME_VALGRIND_SCRIPTS=$THISDIR/../../tools/valgrind
if [ "$NEEDS_VALGRIND" == "1" ]
then
CHROME_VALGRIND=`sh $THISDIR/locate_valgrind.sh`
if [ "$CHROME_VALGRIND" = "" ]
then
CHROME_VALGRIND=../../src/third_party/valgrind/linux_x64
echo
echo "-------------------- WARNING ------------------------"
echo "locate_valgrind.sh failed."
echo "Using $CHROME_VALGRIND as a fallback location."
echo "This might be because:"
echo "1) This is a swarming bot"
echo "2) You haven't set up the valgrind binaries correctly."
echo "In this case, please make sure you have followed the instructions at"
echo "http://www.chromium.org/developers/how-tos/using-valgrind/get-valgrind"
echo "Notice: In the .gclient file, you need to add this for the 'src'"
echo "solution since our directory structure is different from Chromium's:"
echo "\"custom_deps\": {"
echo " \"src/third_party/valgrind\":"
echo " \"https://chromium.googlesource.com/chromium/deps/valgrind/binaries\","
echo "},"
echo "-----------------------------------------------------"
echo
fi
echo "Using valgrind binaries from ${CHROME_VALGRIND}"
PATH="${CHROME_VALGRIND}/bin:$PATH"
# We need to set these variables to override default lib paths hard-coded into
# Valgrind binary.
export VALGRIND_LIB="$CHROME_VALGRIND/lib/valgrind"
export VALGRIND_LIB_INNER="$CHROME_VALGRIND/lib/valgrind"
# Clean up some /tmp directories that might be stale due to interrupted
# chrome_tests.py execution.
# FYI:
# -mtime +1 <- only print files modified more than 24h ago,
# -print0/-0 are needed to handle possible newlines in the filenames.
echo "Cleanup /tmp from Valgrind stuff"
find /tmp -maxdepth 1 \(\
-name "vgdb-pipe-*" -or -name "vg_logs_*" -or -name "valgrind.*" \
\) -mtime +1 -print0 | xargs -0 rm -rf
fi
# Add Chrome's Valgrind scripts dir to the PYTHON_PATH since it contains
# the scripts that are needed for this script to run
PYTHONPATH=$THISDIR/../../tools/python/google:$CHROME_VALGRIND_SCRIPTS python \
"$THISDIR/webrtc_tests.py" $ARGV_COPY
|
import numpy as np
from keras.models import Sequential
from keras.layers import Dense
from keras.optimizers import Adam
# prepare data
X = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
y = np.array([0.5, 3.5, 6.5])
# build model
model = Sequential()
model.add(Dense(1, input_dim=3))
# compile model
model.compile(optimizer=Adam(lr=0.01), loss='mse')
# train model
model.fit(X, y, epochs=500, verbose=0) |
<filename>src/benchmarks/ReactBenchmark.js
import React, { Component } from "react";
import ButtonsRow from "../ButtonsRow";
const N = 1000;
class ReactBenchmark extends Component {
beforeTime = 0;
afterTime = 0;
times = [];
state = {
nodes: []
};
componentWillUpdate() {
this.before();
}
componentWillMount() {
this.before();
}
componentDidUpdate() {
this.after();
}
componentDidMount() {
this.after();
}
before() {
this.beforeTime = new Date();
}
after() {
this.afterTime = new Date();
const delta = this.afterTime - this.beforeTime;
this.refs.time.innerHTML = `<code>${delta}ms</code>`;
this.times.push(delta);
}
get newNodes() {
return new Array(N)
.fill()
.map(() => `${Math.random()}:${new Date().getTime()}`);
}
get averageTime() {
return Math.round(
this.times.reduce((m, n) => m + n, 0) / this.times.length
);
}
prepend = () =>
this.setState({
nodes: [...this.newNodes, ...this.state.nodes]
});
append = () =>
this.setState({
nodes: [...this.state.nodes, ...this.newNodes]
});
insert = () => {
const { nodes } = this.state;
this.setState({
nodes: [
...nodes.slice(0, nodes.length / 2),
...this.newNodes,
...nodes.slice(nodes.length / 2, nodes.length)
]
});
};
drop = () => this.setState({ nodes: [] });
remove = () => {
const { nodes } = this.state,
pivot = Math.floor(Math.random() * nodes.length);
this.setState({
nodes: [
...nodes.slice(0, pivot),
...nodes.slice(pivot + 1, nodes.length)
]
});
};
render() {
const { nodes } = this.state;
return (
<div className="benchmark">
<h2>React</h2>
<p>
Implemented as a single component, no state management lib.
Time measured time is between{" "}
<code>componentWillUpdate</code> and{" "}
<code>componentDidUpdate</code>
</p>
<p>
Time to render: <b ref="time" />
<br />
Current count: <code>{nodes.length}</code>
<br />
Average time: <code>{this.averageTime}ms</code>
</p>
<ButtonsRow
prepend={this.prepend}
insert={this.insert}
append={this.append}
drop={this.drop}
remove={this.remove}
N={N}
/>
<div className="row benchmark-scratchpad">
{nodes.map((k, i) => <div key={k}>{k}</div>)}
</div>
<h3>My results</h3>
<p>Each test repeated 3 times on a prod build of React.</p>
<p>
Avg of Avg time to prepend 1000 nodes up to 30,000:{" "}
<code>21ms</code>
<br />
Avg of Avg time to insert 1000 nodes up to 30,000:{" "}
<code>18ms</code>
<br />
Avg of Avg time to append 1000 nodes up to 30,000:{" "}
<code>15ms</code>
<br />
Avg time to drop 30,000 nodes: <code>195ms</code>
<br />
Avg time to remove 1 node from 30,000: <code>27ms</code>
</p>
</div>
);
}
}
export default ReactBenchmark;
|
#!/bin/bash
# -------------------------------------------------------
# (1) setup orderer-ca
# -------------------------------------------------------
# create install dir
mkdir -p ca/server
mkdir -p ca/client/admin
# start ca
docker-compose up -d
cp ./ca/server/crypto/ca-cert.pem ./ca/client/admin/tls-ca-cert.pem
export FABRIC_CA_CLIENT_HOME=./ca/client/admin
export FABRIC_CA_CLIENT_TLS_CERTFILES=tls-ca-cert.pem
# enroll the ca admin
fabric-ca-client enroll -d -u https://ca-solo.orderer.alpha.at-admin:ca-orderer-adminpw@0.0.0.0:7053
# register the orderer
fabric-ca-client register -d --id.name solo.orderer.alpha.at --id.secret ordererpw --id.type orderer -u https://0.0.0.0:7053
# register the admin of the orderer
fabric-ca-client register -d --id.name admin-solo.orderer.alpha.at --id.secret org0adminpw --id.type admin --id.attrs "hf.Registrar.Roles=client,hf.Registrar.Attributes=*,hf.Revoker=true,hf.GenCRL=true,admin=true:ecert,abac.init=true:ecert" -u https://0.0.0.0:7053
# -------------------------------------------------------
# (2) setup orderer-admin
# -------------------------------------------------------
mkdir -p admin/ca
# cp ./ca/server/crypto/ca-cert.pem ./admin/ca/org0-ca-cert.pem
cp ./ca/server/crypto/ca-cert.pem ./admin/ca/solo.orderer.alpha.at-ca-cert.pem
export FABRIC_CA_CLIENT_HOME=./admin
export FABRIC_CA_CLIENT_TLS_CERTFILES=ca/solo.orderer.alpha.at-ca-cert.pem
export FABRIC_CA_CLIENT_MSPDIR=msp
# enroll the admin of the orderer
fabric-ca-client enroll -d -u https://admin-solo.orderer.alpha.at:org0adminpw@0.0.0.0:7053
# -------------------------------------------------------
###### copy the certificate from this admin MSP
###### and move it to the orderer MSP in the admincerts folder
mkdir -p orderer/msp/admincerts
mkdir -p admin/msp/admincerts
cp ./admin/msp/signcerts/cert.pem ./orderer/msp/admincerts/solo.orderer.alpha.at-admin-cert.pem
cp ./admin/msp/signcerts/cert.pem ./admin/msp/admincerts/solo.orderer.alpha.at-admin-cert.pem
# -------------------------------------------------------
# (3) setup orderer
# ------------------------------------------------------
mkdir -p orderer/assets/ca
mkdir orderer/assets/tls.alpha.at
cp ./ca/server/crypto/ca-cert.pem ./orderer/assets/ca/solo.orderer.alpha.at-ca-cert.pem
cp ../tls.alpha.at/ca/server/crypto/ca-cert.pem ./orderer/assets/tls.alpha.at/tls-ca-cert.pem
#################################################################
################ configuring the environment ####################
#################################################################
# enroll the orderer
export FABRIC_CA_CLIENT_HOME=./orderer
export FABRIC_CA_CLIENT_TLS_CERTFILES=assets/ca/solo.orderer.alpha.at-ca-cert.pem
fabric-ca-client enroll -d -u https://solo.orderer.alpha.at:ordererpw@0.0.0.0:7053
#enroll the tls for the orderer
export FABRIC_CA_CLIENT_MSPDIR=tls-msp
export FABRIC_CA_CLIENT_TLS_CERTFILES=assets/tls.alpha.at/tls-ca-cert.pem
fabric-ca-client enroll -d -u https://solo.orderer.alpha.at:ordererPW@0.0.0.0:7052 --enrollment.profile tls --csr.hosts solo.orderer.alpha.at
mv ./orderer/tls-msp/keystore/*_sk ./orderer/tls-msp/keystore/key.pem
# -------------------------------------------------------
# (4) setup orderer-msp
# ------------------------------------------------------
mkdir -p msp/admincerts
mkdir msp/cacerts
mkdir msp/tlscacerts
mkdir msp/users
# cp ./ca/server/crypto/ca-cert.pem ./msp/cacerts/org0-ca-cert.pem
cp ./ca/server/crypto/ca-cert.pem ./msp/cacerts/solo.orderer.alpha.at-ca-cert.pem
cp ../tls.alpha.at/ca/server/crypto/ca-cert.pem ./msp/tlscacerts/tls-ca-cert.pem
cp ./admin/msp/signcerts/cert.pem ./msp/admincerts/solo.orderer.alpha.at-admin-cert.pem
# -------------------------------------------------------
# (5) add config.yaml into msp
# ------------------------------------------------------
vi msp/config.yaml
NodeOUs:
Enable: true
ClientOUIdentifier:
Certificate: cacerts/solo.orderer.alpha.at-ca-cert.pem
OrganizationalUnitIdentifier: client
PeerOUIdentifier:
Certificate: cacerts/solo.orderer.alpha.at-ca-cert.pem
OrganizationalUnitIdentifier: peer
AdminOUIdentifier:
Certificate: cacerts/solo.orderer.alpha.at-ca-cert.pem
OrganizationalUnitIdentifier: admin
OrdererOUIdentifier:
Certificate: cacerts/solo.orderer.alpha.at-ca-cert.pem
OrganizationalUnitIdentifier: orderer
vi admin/msp/config.yaml
NodeOUs:
Enable: true
ClientOUIdentifier:
Certificate: cacerts/0-0-0-0-7053.pem
OrganizationalUnitIdentifier: client
PeerOUIdentifier:
Certificate: cacerts/0-0-0-0-7053.pem
OrganizationalUnitIdentifier: peer
AdminOUIdentifier:
Certificate: cacerts/0-0-0-0-7053.pem
OrganizationalUnitIdentifier: admin
OrdererOUIdentifier:
Certificate: cacerts/0-0-0-0-7053.pem
OrganizationalUnitIdentifier: orderer |
#!/usr/bin/env bash
# Install goenv
reset_goenv() {
eval "$(goenv init -)"
GO_VER="$(goenv install --list | grep -v [a-z] | grep 1.11 | tail -n1 | awk '{ print $1 }')"
if [ ! -d ${HOME}/.goenv/versions/${GO_VER} ]; then
goenv install ${GO_VER}
goenv global ${GO_VER}
fi
}
# Source for jenv from ~/.extra
reset_java() {
for i in 1.6 1.7 1.8 10 11 12; do
if [ -d /Library/Java/JavaVirtualMachines/$( ls /Library/Java/JavaVirtualMachines | grep ${i} )/Contents/Home ]; then
jenv add /Library/Java/JavaVirtualMachines/$( ls /Library/Java/JavaVirtualMachines | grep ${i} )/Contents/Home
fi
done
}
# Install pyenv
reset_python() {
eval "$(pyenv init -)"
PY_VER="$(pyenv install --list | grep -v [a-z] | grep 3.7 | tail -n1 | awk '{ print $1 }')"
if [ ! -d ${HOME}/.pyenv/versions/${PY_VER} ]; then
pyenv install ${PY_VER}
pyenv global ${PY_VER}
eval "$(pyenv init -)"
curl -o- https://bootstrap.pypa.io/get-pip.py | python -
pip install --upgrade pip setuptools
fi
}
# Install Renv
# https://github.com/viking/Renv
reset_r() {
pushd ${HOME}/.Renv
git pull
pushd ${HOME}/.Renv/plugins/R-build
git pull
popd
popd
eval "$(${HOME}/.Renv/bin/Renv init -)"
R_VER="$(${HOME}/.Renv/bin/Renv install --list | grep -v [a-z] | sort -n | tail -n1 | awk '{ print $1 }')"
if [ ! -d {HOME}/.Renv/versions/${R_VER} ]; then
$( CONFIGURE_OPTS="--without-x --includedir=$(brew --prefix xz)/include --enable-memory-profiling" \
Renv install --keep ${R_VER} 2> /dev/null ) \
|| true
pushd ${HOME}/.Renv/sources/${R_VER}/R-${R_VER}
./configure --prefix=${HOME}/.Renv/versions/${R_VER} --without-x --includedir=$(brew --prefix xz)/include --enable-memory-profiling
make
make install
popd
rm -rf ${HOME}/.Renv/sources/${R_VER}/R-${R_VER}
Renv global ${R_VER}
fi
}
# Install rbenv
reset_ruby() {
eval "$(rbenv init -)"
RB_VERSION=$(rbenv install -l | grep -v [a-z] | sort -n | tail -n1 | awk '{ print $1 }')
if [ ! -d ${HOME}/.rbenv/versions/${RB_VERSION} ]; then
rbenv install ${RB_VERSION}
rbenv global ${RB_VERSION}
eval "$(rbenv init -)"
fi
}
# The main program lah
OPT=$1
case $OPT in
"go")
echo "Resetting Go"
reset_go
;;
"java")
echo "Resetting Java"
reset_java
;;
"python")
echo "Resetting Python"
reset_python
;;
"r")
echo "Resetting R"
reset_r
;;
"ruby")
echo "Running Ruby"
reset_ruby
;;
"all"|*)
echo "Running Everything"
reset_goenv
reset_java
reset_pyenv
reset_r
reset_ruby
;;
esac
|
#!/bin/bash
# --------------------------------------------------------------------------------
# Assignment 1 finder.sh script
# Make executable with chmod u+x and run with ./finder.sh <filedir> <searchstr>
# Author: Jake Michael
# --------------------------------------------------------------------------------
# ensure 2 arguments are passed (filesdir and searchstr)
if [ $# -lt 2 ]; then
echo "error: $# arguments given, 2 expected"
exit 1
else
FILESDIR=$1
SEARCHSTR=$2
fi
# check if filesdir exists on filesystem
if [[ ! -d $FILESDIR ]]; then
echo "$FILESDIR is not a directory or does not exist"
exit 1
fi
# use find command with pipe to wc (to count lines)
NUM_FILES=$(find "$FILESDIR" -type f | wc -l)
# use grep command -r (recursive) with pipe to wc (to count lines)
NUM_LINES=$(grep -re "$SEARCHSTR" "$FILESDIR" | wc -l)
echo "The number of files are $NUM_FILES and the number of matching lines are $NUM_LINES"
exit 0
|
from alembic.config import Config
from alembic.runtime.migration import MigrationContext
from alembic.autogenerate import produce_migrations
from alembic.operations import Operations
from alembic import command
def generate_alembic_migration_script(base_dir, database_uri):
alembic_cfg = Config()
alembic_cfg.set_main_option("script_location", f"{base_dir}/src/database/migration")
alembic_cfg.set_main_option("sqlalchemy.url", database_uri)
with open(f"{base_dir}/alembic/env.py", "w") as env_file:
env_file.write("# Example Alembic Migration Script\n")
env_file.write("# Auto-generated by Alembic\n\n")
env_file.write("from alembic import op\n")
env_file.write("import sqlalchemy as sa\n\n")
# Additional logic to generate migration script content based on the provided base_dir and database_uri
# Return the generated Alembic migration script as a string
with open(f"{base_dir}/alembic/env.py", "r") as env_file:
return env_file.read() |
export OCUSER=$1
export OCPASSWD=$2
export MASTERPUBLICHOSTNAME=$3
export NAMESPACE=$4
export APIKEYUSERNAME=$5
export APIKEY=$6
export STORAGEOPTION=$7
export ARTIFACTSLOCATION=${8::-1}
export ARTIFACTSTOKEN="$9"
export HOME=/root
# Download Installer files
assembly="wml"
version="2.1.0.0"
storageclass=$STORAGEOPTION
namespace=$NAMESPACE
mkdir -p /ibm/$assembly
export INSTALLERHOME=/ibm/$assembly
(cd $INSTALLERHOME && wget $ARTIFACTSLOCATION/scripts/cpd-linux$ARTIFACTSTOKEN -O cpd-linux)
if [[ $APIKEY == "" ]]; then
echo $(date) "- APIKey not provided. See README on how to get it."
exit 12
else
(cd $INSTALLERHOME &&
cat > repo.yaml << EOF
registry:
- url: cp.icr.io/cp/cpd
username: $APIKEYUSERNAME
apikey: $APIKEY
name: base-registry
fileservers:
- url: https://raw.github.com/IBM/cloud-pak/master/repo/cpd
EOF
)
fi
chmod +x $INSTALLERHOME/cpd-linux
# Authenticate and Install
oc login -u ${OCUSER} -p ${OCPASSWD} ${MASTERPUBLICHOSTNAME} --insecure-skip-tls-verify=true
registry=$(oc get routes -n default | grep docker-registry | awk '{print $2}')
#Docker login
echo "$(date) Get SA token"
token=$(oc serviceaccounts get-token cpdtoken)
echo "Docker login to $registry registry"
docker login -u $(oc whoami) -p $token $registry
echo "Docker login complete"
#Run installer
cd $INSTALLERHOME
# Install CPD
echo "$(date) Begin Install"
./cpd-linux adm -r repo.yaml -a $assembly -n $namespace --accept-all-licenses --apply
./cpd-linux -c $storageclass -r repo.yaml -a $assembly -n $namespace \
--transfer-image-to=$registry/$namespace --target-registry-username=$(oc whoami) \
--target-registry-password=$token --accept-all-licenses
if [ $? -eq 0 ]
then
echo $(date) " - Installation completed successfully"
else
echo $(date) "- Installation failed"
exit 11
fi
echo "Sleep for 30 seconds"
sleep 30
echo "Script Complete"
#============================================================== |
<gh_stars>1-10
/*
* Copyright 2016 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* 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.keycloak.storage.ldap;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.naming.AuthenticationException;
import org.jboss.logging.Logger;
import org.keycloak.common.constants.KerberosConstants;
import org.keycloak.component.ComponentModel;
import org.keycloak.credential.CredentialAuthentication;
import org.keycloak.credential.CredentialInput;
import org.keycloak.credential.CredentialInputUpdater;
import org.keycloak.credential.CredentialInputValidator;
import org.keycloak.credential.CredentialModel;
import org.keycloak.federation.kerberos.impl.KerberosUsernamePasswordAuthenticator;
import org.keycloak.federation.kerberos.impl.SPNEGOAuthenticator;
import org.keycloak.models.*;
import org.keycloak.models.cache.CachedUserModel;
import org.keycloak.models.credential.PasswordCredentialModel;
import org.keycloak.models.utils.DefaultRoles;
import org.keycloak.models.utils.ReadOnlyUserModelDelegate;
import org.keycloak.policy.PasswordPolicyManagerProvider;
import org.keycloak.policy.PolicyError;
import org.keycloak.models.cache.UserCache;
import org.keycloak.storage.ReadOnlyException;
import org.keycloak.storage.StorageId;
import org.keycloak.storage.UserStorageProvider;
import org.keycloak.storage.UserStorageProviderModel;
import org.keycloak.storage.adapter.InMemoryUserAdapter;
import org.keycloak.storage.ldap.idm.model.LDAPObject;
import org.keycloak.storage.ldap.idm.query.Condition;
import org.keycloak.storage.ldap.idm.query.EscapeStrategy;
import org.keycloak.storage.ldap.idm.query.internal.LDAPQuery;
import org.keycloak.storage.ldap.idm.query.internal.LDAPQueryConditionsBuilder;
import org.keycloak.storage.ldap.idm.store.ldap.LDAPIdentityStore;
import org.keycloak.storage.ldap.kerberos.LDAPProviderKerberosConfig;
import org.keycloak.storage.ldap.mappers.LDAPOperationDecorator;
import org.keycloak.storage.ldap.mappers.LDAPStorageMapper;
import org.keycloak.storage.ldap.mappers.LDAPStorageMapperManager;
import org.keycloak.storage.ldap.mappers.PasswordUpdateCallback;
import org.keycloak.storage.user.ImportedUserValidation;
import org.keycloak.storage.user.UserLookupProvider;
import org.keycloak.storage.user.UserQueryProvider;
import org.keycloak.storage.user.UserRegistrationProvider;
/**
* @author <a href="mailto:<EMAIL>"><NAME></a>
* @author <a href="mailto:<EMAIL>"><NAME></a>
* @version $Revision: 1 $
*/
public class LDAPStorageProvider implements UserStorageProvider,
CredentialInputValidator,
CredentialInputUpdater,
CredentialAuthentication,
UserLookupProvider,
UserRegistrationProvider,
UserQueryProvider,
ImportedUserValidation {
private static final Logger logger = Logger.getLogger(LDAPStorageProvider.class);
protected LDAPStorageProviderFactory factory;
protected KeycloakSession session;
protected UserStorageProviderModel model;
protected LDAPIdentityStore ldapIdentityStore;
protected EditMode editMode;
protected LDAPProviderKerberosConfig kerberosConfig;
protected PasswordUpdateCallback updater;
protected LDAPStorageMapperManager mapperManager;
protected LDAPStorageUserManager userManager;
// these exist to make sure that we only hit ldap once per transaction
//protected Map<String, UserModel> noImportSessionCache = new HashMap<>();
protected final Set<String> supportedCredentialTypes = new HashSet<>();
public LDAPStorageProvider(LDAPStorageProviderFactory factory, KeycloakSession session, ComponentModel model, LDAPIdentityStore ldapIdentityStore) {
this.factory = factory;
this.session = session;
this.model = new UserStorageProviderModel(model);
this.ldapIdentityStore = ldapIdentityStore;
this.kerberosConfig = new LDAPProviderKerberosConfig(model);
this.editMode = ldapIdentityStore.getConfig().getEditMode();
this.mapperManager = new LDAPStorageMapperManager(this);
this.userManager = new LDAPStorageUserManager(this);
supportedCredentialTypes.add(PasswordCredentialModel.TYPE);
if (kerberosConfig.isAllowKerberosAuthentication()) {
supportedCredentialTypes.add(UserCredentialModel.KERBEROS);
}
}
public void setUpdater(PasswordUpdateCallback updater) {
this.updater = updater;
}
public KeycloakSession getSession() {
return session;
}
public LDAPIdentityStore getLdapIdentityStore() {
return this.ldapIdentityStore;
}
public EditMode getEditMode() {
return editMode;
}
public UserStorageProviderModel getModel() {
return model;
}
public LDAPStorageMapperManager getMapperManager() {
return mapperManager;
}
public LDAPStorageUserManager getUserManager() {
return userManager;
}
@Override
public UserModel validate(RealmModel realm, UserModel local) {
LDAPObject ldapObject = loadAndValidateUser(realm, local);
if (ldapObject == null) {
return null;
}
return proxy(realm, local, ldapObject);
}
protected UserModel proxy(RealmModel realm, UserModel local, LDAPObject ldapObject) {
UserModel existing = userManager.getManagedProxiedUser(local.getId());
if (existing != null) {
return existing;
}
// We need to avoid having CachedUserModel as cache is upper-layer then LDAP. Hence having CachedUserModel here may cause StackOverflowError
if (local instanceof CachedUserModel) {
local = session.userStorageManager().getUserById(local.getId(), realm);
existing = userManager.getManagedProxiedUser(local.getId());
if (existing != null) {
return existing;
}
}
UserModel proxied = local;
checkDNChanged(realm, local, ldapObject);
switch (editMode) {
case READ_ONLY:
if (model.isImportEnabled()) {
proxied = new ReadonlyLDAPUserModelDelegate(local, this);
} else {
proxied = new ReadOnlyUserModelDelegate(local);
}
break;
case WRITABLE:
proxied = new WritableLDAPUserModelDelegate(local, this, ldapObject);
break;
case UNSYNCED:
proxied = new UnsyncedLDAPUserModelDelegate(local, this);
}
List<ComponentModel> mappers = realm.getComponents(model.getId(), LDAPStorageMapper.class.getName());
List<ComponentModel> sortedMappers = mapperManager.sortMappersAsc(mappers);
for (ComponentModel mapperModel : sortedMappers) {
LDAPStorageMapper ldapMapper = mapperManager.getMapper(mapperModel);
proxied = ldapMapper.proxy(ldapObject, proxied, realm);
}
userManager.setManagedProxiedUser(proxied, ldapObject);
return proxied;
}
private void checkDNChanged(RealmModel realm, UserModel local, LDAPObject ldapObject) {
String dnFromDB = local.getFirstAttribute(LDAPConstants.LDAP_ENTRY_DN);
String ldapDn = ldapObject.getDn().toString();
if (!ldapDn.equals(dnFromDB)) {
logger.debugf("Updated LDAP DN of user '%s' to '%s'", local.getUsername(), ldapDn);
local.setSingleAttribute(LDAPConstants.LDAP_ENTRY_DN, ldapDn);
UserCache userCache = session.userCache();
if (userCache != null) {
userCache.evict(realm, local);
}
}
}
@Override
public boolean supportsCredentialAuthenticationFor(String type) {
return type.equals(UserCredentialModel.KERBEROS) && kerberosConfig.isAllowKerberosAuthentication();
}
@Override
public List<UserModel> searchForUserByUserAttribute(String attrName, String attrValue, RealmModel realm) {
try (LDAPQuery ldapQuery = LDAPUtils.createQueryForUserSearch(this, realm)) {
LDAPQueryConditionsBuilder conditionsBuilder = new LDAPQueryConditionsBuilder();
Condition attrCondition = conditionsBuilder.equal(attrName, attrValue, EscapeStrategy.DEFAULT);
ldapQuery.addWhereCondition(attrCondition);
List<LDAPObject> ldapObjects = ldapQuery.getResultList();
if (ldapObjects == null || ldapObjects.isEmpty()) {
return Collections.emptyList();
}
List<UserModel> searchResults = new LinkedList<UserModel>();
for (LDAPObject ldapUser : ldapObjects) {
String ldapUsername = LDAPUtils.getUsername(ldapUser, this.ldapIdentityStore.getConfig());
if (session.userLocalStorage().getUserByUsername(ldapUsername, realm) == null) {
UserModel imported = importUserFromLDAP(session, realm, ldapUser);
searchResults.add(imported);
}
}
return searchResults;
}
}
public boolean synchronizeRegistrations() {
return "true".equalsIgnoreCase(model.getConfig().getFirst(LDAPConstants.SYNC_REGISTRATIONS)) && editMode == UserStorageProvider.EditMode.WRITABLE;
}
@Override
public UserModel addUser(RealmModel realm, String username) {
if (!synchronizeRegistrations()) {
return null;
}
UserModel user = null;
if (model.isImportEnabled()) {
user = session.userLocalStorage().addUser(realm, username);
user.setFederationLink(model.getId());
} else {
user = new InMemoryUserAdapter(session, realm, new StorageId(model.getId(), username).getId());
user.setUsername(username);
}
LDAPObject ldapUser = LDAPUtils.addUserToLDAP(this, realm, user);
LDAPUtils.checkUuid(ldapUser, ldapIdentityStore.getConfig());
user.setSingleAttribute(LDAPConstants.LDAP_ID, ldapUser.getUuid());
user.setSingleAttribute(LDAPConstants.LDAP_ENTRY_DN, ldapUser.getDn().toString());
// Add the user to the default groups and add default required actions
UserModel proxy = proxy(realm, user, ldapUser);
DefaultRoles.addDefaultRoles(realm, proxy);
for (GroupModel g : realm.getDefaultGroups()) {
proxy.joinGroup(g);
}
for (RequiredActionProviderModel r : realm.getRequiredActionProviders()) {
if (r.isEnabled() && r.isDefaultAction()) {
proxy.addRequiredAction(r.getAlias());
}
}
return proxy;
}
@Override
public boolean removeUser(RealmModel realm, UserModel user) {
if (editMode == UserStorageProvider.EditMode.READ_ONLY || editMode == UserStorageProvider.EditMode.UNSYNCED) {
logger.warnf("User '%s' can't be deleted in LDAP as editMode is '%s'. Deleting user just from Keycloak DB, but he will be re-imported from LDAP again once searched in Keycloak", user.getUsername(), editMode.toString());
return true;
}
LDAPObject ldapObject = loadAndValidateUser(realm, user);
if (ldapObject == null) {
logger.warnf("User '%s' can't be deleted from LDAP as it doesn't exist here", user.getUsername());
return false;
}
ldapIdentityStore.remove(ldapObject);
userManager.removeManagedUserEntry(user.getId());
return true;
}
@Override
public UserModel getUserById(String id, RealmModel realm) {
UserModel alreadyLoadedInSession = userManager.getManagedProxiedUser(id);
if (alreadyLoadedInSession != null) return alreadyLoadedInSession;
StorageId storageId = new StorageId(id);
return getUserByUsername(storageId.getExternalId(), realm);
}
@Override
public int getUsersCount(RealmModel realm) {
return 0;
}
@Override
public List<UserModel> getUsers(RealmModel realm) {
return Collections.EMPTY_LIST;
}
@Override
public List<UserModel> getUsers(RealmModel realm, int firstResult, int maxResults) {
return Collections.EMPTY_LIST;
}
@Override
public List<UserModel> searchForUser(String search, RealmModel realm) {
return searchForUser(search, realm, 0, Integer.MAX_VALUE - 1);
}
@Override
public List<UserModel> searchForUser(String search, RealmModel realm, int firstResult, int maxResults) {
Map<String, String> attributes = new HashMap<String, String>();
int spaceIndex = search.lastIndexOf(' ');
if (spaceIndex > -1) {
String firstName = search.substring(0, spaceIndex).trim();
String lastName = search.substring(spaceIndex).trim();
attributes.put(UserModel.FIRST_NAME, firstName);
attributes.put(UserModel.LAST_NAME, lastName);
} else if (search.indexOf('@') > -1) {
attributes.put(UserModel.USERNAME, search.trim().toLowerCase());
attributes.put(UserModel.EMAIL, search.trim().toLowerCase());
} else {
attributes.put(UserModel.LAST_NAME, search.trim());
attributes.put(UserModel.USERNAME, search.trim().toLowerCase());
}
return searchForUser(attributes, realm, firstResult, maxResults);
}
@Override
public List<UserModel> searchForUser(Map<String, String> params, RealmModel realm) {
return searchForUser(params, realm, 0, Integer.MAX_VALUE - 1);
}
@Override
public List<UserModel> searchForUser(Map<String, String> params, RealmModel realm, int firstResult, int maxResults) {
List<UserModel> searchResults =new LinkedList<UserModel>();
List<LDAPObject> ldapUsers = searchLDAP(realm, params, maxResults + firstResult);
int counter = 0;
for (LDAPObject ldapUser : ldapUsers) {
if (counter++ < firstResult) continue;
String ldapUsername = LDAPUtils.getUsername(ldapUser, this.ldapIdentityStore.getConfig());
if (session.userLocalStorage().getUserByUsername(ldapUsername, realm) == null) {
UserModel imported = importUserFromLDAP(session, realm, ldapUser);
searchResults.add(imported);
}
}
return searchResults;
}
@Override
public List<UserModel> getGroupMembers(RealmModel realm, GroupModel group) {
return getGroupMembers(realm, group, 0, Integer.MAX_VALUE - 1);
}
@Override
public List<UserModel> getGroupMembers(RealmModel realm, GroupModel group, int firstResult, int maxResults) {
List<ComponentModel> mappers = realm.getComponents(model.getId(), LDAPStorageMapper.class.getName());
List<ComponentModel> sortedMappers = mapperManager.sortMappersAsc(mappers);
for (ComponentModel mapperModel : sortedMappers) {
LDAPStorageMapper ldapMapper = mapperManager.getMapper(mapperModel);
List<UserModel> users = ldapMapper.getGroupMembers(realm, group, firstResult, maxResults);
// Sufficient for now
if (users.size() > 0) {
return users;
}
}
return Collections.emptyList();
}
public List<UserModel> loadUsersByUsernames(List<String> usernames, RealmModel realm) {
List<UserModel> result = new ArrayList<>();
for (String username : usernames) {
UserModel kcUser = session.users().getUserByUsername(username, realm);
if (kcUser == null) {
logger.warnf("User '%s' referenced by membership wasn't found in LDAP", username);
} else if (model.isImportEnabled() && !model.getId().equals(kcUser.getFederationLink())) {
logger.warnf("Incorrect federation provider of user '%s'", kcUser.getUsername());
} else {
result.add(kcUser);
}
}
return result;
}
protected List<LDAPObject> searchLDAP(RealmModel realm, Map<String, String> attributes, int maxResults) {
List<LDAPObject> results = new ArrayList<LDAPObject>();
if (attributes.containsKey(UserModel.USERNAME)) {
try (LDAPQuery ldapQuery = LDAPUtils.createQueryForUserSearch(this, realm)) {
LDAPQueryConditionsBuilder conditionsBuilder = new LDAPQueryConditionsBuilder();
// Mapper should replace "username" in parameter name with correct LDAP mapped attribute
Condition usernameCondition = conditionsBuilder.equal(UserModel.USERNAME, attributes.get(UserModel.USERNAME), EscapeStrategy.NON_ASCII_CHARS_ONLY);
ldapQuery.addWhereCondition(usernameCondition);
List<LDAPObject> ldapObjects = ldapQuery.getResultList();
results.addAll(ldapObjects);
}
}
if (attributes.containsKey(UserModel.EMAIL)) {
try (LDAPQuery ldapQuery = LDAPUtils.createQueryForUserSearch(this, realm)) {
LDAPQueryConditionsBuilder conditionsBuilder = new LDAPQueryConditionsBuilder();
// Mapper should replace "email" in parameter name with correct LDAP mapped attribute
Condition emailCondition = conditionsBuilder.equal(UserModel.EMAIL, attributes.get(UserModel.EMAIL), EscapeStrategy.NON_ASCII_CHARS_ONLY);
ldapQuery.addWhereCondition(emailCondition);
List<LDAPObject> ldapObjects = ldapQuery.getResultList();
results.addAll(ldapObjects);
}
}
if (attributes.containsKey(UserModel.FIRST_NAME) || attributes.containsKey(UserModel.LAST_NAME)) {
try (LDAPQuery ldapQuery = LDAPUtils.createQueryForUserSearch(this, realm)) {
LDAPQueryConditionsBuilder conditionsBuilder = new LDAPQueryConditionsBuilder();
// Mapper should replace parameter with correct LDAP mapped attributes
if (attributes.containsKey(UserModel.FIRST_NAME)) {
ldapQuery.addWhereCondition(conditionsBuilder.equal(UserModel.FIRST_NAME, attributes.get(UserModel.FIRST_NAME), EscapeStrategy.NON_ASCII_CHARS_ONLY));
}
if (attributes.containsKey(UserModel.LAST_NAME)) {
ldapQuery.addWhereCondition(conditionsBuilder.equal(UserModel.LAST_NAME, attributes.get(UserModel.LAST_NAME), EscapeStrategy.NON_ASCII_CHARS_ONLY));
}
List<LDAPObject> ldapObjects = ldapQuery.getResultList();
results.addAll(ldapObjects);
}
}
return results;
}
/**
* @param local
* @return ldapUser corresponding to local user or null if user is no longer in LDAP
*/
protected LDAPObject loadAndValidateUser(RealmModel realm, UserModel local) {
LDAPObject existing = userManager.getManagedLDAPUser(local.getId());
if (existing != null) {
return existing;
}
LDAPObject ldapUser = loadLDAPUserByUsername(realm, local.getUsername());
if (ldapUser == null) {
return null;
}
LDAPUtils.checkUuid(ldapUser, ldapIdentityStore.getConfig());
if (ldapUser.getUuid().equals(local.getFirstAttribute(LDAPConstants.LDAP_ID))) {
return ldapUser;
} else {
logger.warnf("LDAP User invalid. ID doesn't match. ID from LDAP [%s], LDAP ID from local DB: [%s]", ldapUser.getUuid(), local.getFirstAttribute(LDAPConstants.LDAP_ID));
return null;
}
}
@Override
public UserModel getUserByUsername(String username, RealmModel realm) {
LDAPObject ldapUser = loadLDAPUserByUsername(realm, username);
if (ldapUser == null) {
return null;
}
return importUserFromLDAP(session, realm, ldapUser);
}
protected UserModel importUserFromLDAP(KeycloakSession session, RealmModel realm, LDAPObject ldapUser) {
String ldapUsername = LDAPUtils.getUsername(ldapUser, ldapIdentityStore.getConfig());
LDAPUtils.checkUuid(ldapUser, ldapIdentityStore.getConfig());
UserModel imported = null;
if (model.isImportEnabled()) {
imported = session.userLocalStorage().addUser(realm, ldapUsername);
} else {
InMemoryUserAdapter adapter = new InMemoryUserAdapter(session, realm, new StorageId(model.getId(), ldapUsername).getId());
adapter.addDefaults();
imported = adapter;
}
imported.setEnabled(true);
List<ComponentModel> mappers = realm.getComponents(model.getId(), LDAPStorageMapper.class.getName());
List<ComponentModel> sortedMappers = mapperManager.sortMappersDesc(mappers);
for (ComponentModel mapperModel : sortedMappers) {
if (logger.isTraceEnabled()) {
logger.tracef("Using mapper %s during import user from LDAP", mapperModel);
}
LDAPStorageMapper ldapMapper = mapperManager.getMapper(mapperModel);
ldapMapper.onImportUserFromLDAP(ldapUser, imported, realm, true);
}
String userDN = ldapUser.getDn().toString();
if (model.isImportEnabled()) imported.setFederationLink(model.getId());
imported.setSingleAttribute(LDAPConstants.LDAP_ID, ldapUser.getUuid());
imported.setSingleAttribute(LDAPConstants.LDAP_ENTRY_DN, userDN);
if(getLdapIdentityStore().getConfig().isTrustEmail()){
imported.setEmailVerified(true);
}
logger.debugf("Imported new user from LDAP to Keycloak DB. Username: [%s], Email: [%s], LDAP_ID: [%s], LDAP Entry DN: [%s]", imported.getUsername(), imported.getEmail(),
ldapUser.getUuid(), userDN);
UserModel proxy = proxy(realm, imported, ldapUser);
return proxy;
}
protected LDAPObject queryByEmail(RealmModel realm, String email) {
try (LDAPQuery ldapQuery = LDAPUtils.createQueryForUserSearch(this, realm)) {
LDAPQueryConditionsBuilder conditionsBuilder = new LDAPQueryConditionsBuilder();
// Mapper should replace "email" in parameter name with correct LDAP mapped attribute
Condition emailCondition = conditionsBuilder.equal(UserModel.EMAIL, email, EscapeStrategy.DEFAULT);
ldapQuery.addWhereCondition(emailCondition);
return ldapQuery.getFirstResult();
}
}
@Override
public UserModel getUserByEmail(String email, RealmModel realm) {
LDAPObject ldapUser = queryByEmail(realm, email);
if (ldapUser == null) {
return null;
}
// Check here if user already exists
String ldapUsername = LDAPUtils.getUsername(ldapUser, ldapIdentityStore.getConfig());
UserModel user = session.userLocalStorage().getUserByUsername(ldapUsername, realm);
if (user != null) {
LDAPUtils.checkUuid(ldapUser, ldapIdentityStore.getConfig());
// If email attribute mapper is set to "Always Read Value From LDAP" the user may be in Keycloak DB with an old email address
if (ldapUser.getUuid().equals(user.getFirstAttribute(LDAPConstants.LDAP_ID))) return user;
throw new ModelDuplicateException("User with username '" + ldapUsername + "' already exists in Keycloak. It conflicts with LDAP user with email '" + email + "'");
}
return importUserFromLDAP(session, realm, ldapUser);
}
@Override
public void preRemove(RealmModel realm) {
// complete Don't think we have to do anything
}
@Override
public void preRemove(RealmModel realm, RoleModel role) {
// TODO: Maybe mappers callback to ensure role deletion propagated to LDAP by RoleLDAPFederationMapper?
}
@Override
public void preRemove(RealmModel realm, GroupModel group) {
}
public boolean validPassword(RealmModel realm, UserModel user, String password) {
if (kerberosConfig.isAllowKerberosAuthentication() && kerberosConfig.isUseKerberosForPasswordAuthentication()) {
// Use Kerberos JAAS (Krb5LoginModule)
KerberosUsernamePasswordAuthenticator authenticator = factory.createKerberosUsernamePasswordAuthenticator(kerberosConfig);
return authenticator.validUser(user.getUsername(), password);
} else {
// Use Naming LDAP API
LDAPObject ldapUser = loadAndValidateUser(realm, user);
try {
ldapIdentityStore.validatePassword(ldapUser, password);
return true;
} catch (AuthenticationException ae) {
boolean processed = false;
List<ComponentModel> mappers = realm.getComponents(model.getId(), LDAPStorageMapper.class.getName());
List<ComponentModel> sortedMappers = mapperManager.sortMappersDesc(mappers);
for (ComponentModel mapperModel : sortedMappers) {
if (logger.isTraceEnabled()) {
logger.tracef("Using mapper %s during import user from LDAP", mapperModel);
}
LDAPStorageMapper ldapMapper = mapperManager.getMapper(mapperModel);
processed = processed || ldapMapper.onAuthenticationFailure(ldapUser, user, ae, realm);
}
return processed;
}
}
}
@Override
public boolean updateCredential(RealmModel realm, UserModel user, CredentialInput input) {
if (!PasswordCredentialModel.TYPE.equals(input.getType()) || ! (input instanceof UserCredentialModel)) return false;
if (editMode == UserStorageProvider.EditMode.READ_ONLY) {
throw new ReadOnlyException("Federated storage is not writable");
} else if (editMode == UserStorageProvider.EditMode.WRITABLE) {
LDAPIdentityStore ldapIdentityStore = getLdapIdentityStore();
String password = <PASSWORD>();
LDAPObject ldapUser = loadAndValidateUser(realm, user);
if (ldapIdentityStore.getConfig().isValidatePasswordPolicy()) {
PolicyError error = session.getProvider(PasswordPolicyManagerProvider.class).validate(realm, user, password);
if (error != null) throw new ModelException(error.getMessage(), error.getParameters());
}
try {
LDAPOperationDecorator operationDecorator = null;
if (updater != null) {
operationDecorator = updater.beforePasswordUpdate(user, ldapUser, (UserCredentialModel)input);
}
ldapIdentityStore.updatePassword(ldapUser, password, operationDecorator);
if (updater != null) updater.passwordUpdated(user, ldapUser, (UserCredentialModel)input);
return true;
} catch (ModelException me) {
if (updater != null) {
updater.passwordUpdateFailed(user, ldapUser, (UserCredentialModel)input, me);
return false;
} else {
throw me;
}
}
} else {
return false;
}
}
@Override
public void disableCredentialType(RealmModel realm, UserModel user, String credentialType) {
}
@Override
public Set<String> getDisableableCredentialTypes(RealmModel realm, UserModel user) {
return Collections.EMPTY_SET;
}
public Set<String> getSupportedCredentialTypes() {
return new HashSet<String>(this.supportedCredentialTypes);
}
@Override
public boolean supportsCredentialType(String credentialType) {
return getSupportedCredentialTypes().contains(credentialType);
}
@Override
public boolean isConfiguredFor(RealmModel realm, UserModel user, String credentialType) {
return getSupportedCredentialTypes().contains(credentialType);
}
@Override
public boolean isValid(RealmModel realm, UserModel user, CredentialInput input) {
if (!(input instanceof UserCredentialModel)) return false;
if (input.getType().equals(PasswordCredentialModel.TYPE) && !session.userCredentialManager().isConfiguredLocally(realm, user, PasswordCredentialModel.TYPE)) {
return validPassword(realm, user, input.getChallengeResponse());
} else {
return false; // invalid cred type
}
}
@Override
public CredentialValidationOutput authenticate(RealmModel realm, CredentialInput cred) {
if (!(cred instanceof UserCredentialModel)) CredentialValidationOutput.failed();
UserCredentialModel credential = (UserCredentialModel)cred;
if (credential.getType().equals(UserCredentialModel.KERBEROS)) {
if (kerberosConfig.isAllowKerberosAuthentication()) {
String spnegoToken = credential.getChallengeResponse();
SPNEGOAuthenticator spnegoAuthenticator = factory.createSPNEGOAuthenticator(spnegoToken, kerberosConfig);
spnegoAuthenticator.authenticate();
Map<String, String> state = new HashMap<String, String>();
if (spnegoAuthenticator.isAuthenticated()) {
// TODO: This assumes that LDAP "uid" is equal to kerberos principal name. Like uid "hnelson" and kerberos principal "<EMAIL>".
// Check if it's correct or if LDAP attribute for mapping kerberos principal should be available (For ApacheDS it seems to be attribute "krb5PrincipalName" but on MSAD it's likely different)
String username = spnegoAuthenticator.getAuthenticatedUsername();
UserModel user = findOrCreateAuthenticatedUser(realm, username);
if (user == null) {
logger.warnf("Kerberos/SPNEGO authentication succeeded with username [%s], but couldn't find or create user with federation provider [%s]", username, model.getName());
return CredentialValidationOutput.failed();
} else {
String delegationCredential = spnegoAuthenticator.getSerializedDelegationCredential();
if (delegationCredential != null) {
state.put(KerberosConstants.GSS_DELEGATION_CREDENTIAL, delegationCredential);
}
return new CredentialValidationOutput(user, CredentialValidationOutput.Status.AUTHENTICATED, state);
}
} else {
state.put(KerberosConstants.RESPONSE_TOKEN, spnegoAuthenticator.getResponseToken());
return new CredentialValidationOutput(null, CredentialValidationOutput.Status.CONTINUE, state);
}
}
}
return CredentialValidationOutput.failed();
}
@Override
public void close() {
}
/**
* Called after successful kerberos authentication
*
* @param realm realm
* @param username username without realm prefix
* @return finded or newly created user
*/
protected UserModel findOrCreateAuthenticatedUser(RealmModel realm, String username) {
UserModel user = session.userLocalStorage().getUserByUsername(username, realm);
if (user != null) {
logger.debugf("Kerberos authenticated user [%s] found in Keycloak storage", username);
if (!model.getId().equals(user.getFederationLink())) {
logger.warnf("User with username [%s] already exists, but is not linked to provider [%s]", username, model.getName());
return null;
} else {
LDAPObject ldapObject = loadAndValidateUser(realm, user);
if (ldapObject != null) {
return proxy(realm, user, ldapObject);
} else {
logger.warnf("User with username [%s] aready exists and is linked to provider [%s] but is not valid. Stale LDAP_ID on local user is: %s",
username, model.getName(), user.getFirstAttribute(LDAPConstants.LDAP_ID));
logger.warn("Will re-create user");
UserCache userCache = session.userCache();
if (userCache != null) {
userCache.evict(realm, user);
}
new UserManager(session).removeUser(realm, user, session.userLocalStorage());
}
}
}
// Creating user to local storage
logger.debugf("Kerberos authenticated user [%s] not in Keycloak storage. Creating him", username);
return getUserByUsername(username, realm);
}
public LDAPObject loadLDAPUserByUsername(RealmModel realm, String username) {
try (LDAPQuery ldapQuery = LDAPUtils.createQueryForUserSearch(this, realm)) {
LDAPQueryConditionsBuilder conditionsBuilder = new LDAPQueryConditionsBuilder();
String usernameMappedAttribute = this.ldapIdentityStore.getConfig().getUsernameLdapAttribute();
Condition usernameCondition = conditionsBuilder.equal(usernameMappedAttribute, username, EscapeStrategy.DEFAULT);
ldapQuery.addWhereCondition(usernameCondition);
LDAPObject ldapUser = ldapQuery.getFirstResult();
if (ldapUser == null) {
return null;
}
return ldapUser;
}
}
}
|
import { ClipPath } from '../../vector/clippath/clippath'
import { SVGWrapperAnimator } from './wrapper'
@SVGClipPathAnimator.register('ClipPath')
export class SVGClipPathAnimator extends SVGWrapperAnimator<
SVGClipPathElement,
ClipPath
> {}
|
#!/bin/bash
# Created by: Emanuele Bugliarello (@e-bug)
# Date created: 9/4/2019
# Date last modified: 9/4/2019
PROJDIR=$HOME/pascal
INDIR=$PROJDIR/data/wmt17deen/corpus
OUTDIR=$PROJDIR/data/wmt17deen/tags_root
lang=en
TRAIN=train.tok.tok.bpe.32000.$lang
VALID=valid.tok.tok.bpe.32000.$lang
TEST=test.tok.tok.bpe.32000.$lang
SCRIPTSDIR=$PROJDIR/scripts
source activate pascal
mkdir -p $OUTDIR
size=195100
i=0
python $SCRIPTSDIR/bpe_tags_root.py $lang $INDIR/$TEST $OUTDIR/test.$lang $size $i &
python $SCRIPTSDIR/bpe_tags_root.py $lang $INDIR/$VALID $OUTDIR/valid.$lang $size $i &
for i in {0..29}; do
python $SCRIPTSDIR/bpe_tags_root.py $lang $INDIR/$TRAIN $OUTDIR/train.$lang.$i $size $i &
done
wait
rm $OUTDIR/train.$lang
for i in {0..29}; do
cat $OUTDIR/train.$lang.$i >> $OUTDIR/train.$lang
done
rm $OUTDIR/train.$lang.*
conda deactivate
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.curso.factorialwsmvn;
import java.util.stream.Stream;
import javax.jws.WebService;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.ejb.Stateless;
/**
*
* @author khepherer
*/
@WebService(serviceName = "FactorialWebService")
@Stateless
public class FactorialWebService {
/**
* Web service operation
*
* @param numero
* @return el factorial de numero como Double
*/
@WebMethod(operationName = "factorial")
public Double factorial(@WebParam(name = "numero") final Double numero) {
return calcFactorial(numero);
}
private Double calcFactorial(Double numero) {
return Stream.iterate(1.0d, n -> n + 1).parallel()
.limit(numero.longValue()).reduce(1.0d, (a, b) -> a * b);
}
}
|
<reponame>tabris233/go_study
package main
import (
"fmt"
"net/http"
"os"
"strings"
"golang.org/x/net/html"
)
// forEachNode针对每个结点x,都会调用pre(x)和post(x)。
// pre和post都是可选的。
// 遍历孩子结点之前,pre被调用
// 遍历孩子结点之后,post被调用
func forEachNode(n *html.Node, pre, post func(n *html.Node)) {
if pre != nil {
pre(n)
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
forEachNode(c, pre, post)
}
if post != nil {
post(n)
}
}
var depth int
func startElement(n *html.Node) {
if n.Type == html.ElementNode {
attr := make([]string, 0, len(n.Attr))
for _, a := range n.Attr {
attr = append(attr, a.Key+"=\""+a.Val+"\"")
}
tail := ""
if n.FirstChild == nil {
tail = " /"
}
fmt.Printf("%*s<%s %s%s>\n", depth*2, "", n.Data, strings.Join(attr, " "), tail)
depth++
} else if n.Type == html.CommentNode {
fmt.Printf("%*s<%s>\n", depth*2, "", "[comment]")
}
}
func endElement(n *html.Node) {
if n.Type == html.ElementNode {
depth--
if n.FirstChild == nil {
return
}
fmt.Printf("%*s</%s>\n", depth*2, "", n.Data)
}
}
func getDoc(url string) (*html.Node, error) {
resp, err := http.Get(url)
if err != nil {
return nil, err
}
doc, err := html.Parse(resp.Body)
defer resp.Body.Close()
if err != nil {
err = fmt.Errorf("parsing HTML: %s", err)
return nil, err
}
return doc, nil
}
func main() {
doc, err := getDoc("https://golang.org")
if err != nil {
fmt.Fprintf(os.Stderr, "findlinks: %v\n", err)
os.Exit(1)
}
forEachNode(doc, startElement, endElement)
}
|
<filename>metals/src/main/scala/scala/meta/metals/providers/DefinitionProvider.scala<gh_stars>0
package scala.meta.metals.providers
import scala.meta.metals.ScalametaEnrichments._
import scala.meta.metals.Uri
import org.langmeta.lsp.Location
import org.langmeta.lsp.Position
import scala.meta.metals.search.SymbolIndex
import com.typesafe.scalalogging.LazyLogging
import org.langmeta.io.AbsolutePath
object DefinitionProvider extends LazyLogging {
def definition(
symbolIndex: SymbolIndex,
uri: Uri,
position: Position,
tempSourcesDir: AbsolutePath
): List[Location] = {
val locations = for {
data <- symbolIndex.findDefinition(uri, position.line, position.character)
pos <- data.definition
_ = logger.info(s"Found definition ${pos.pretty} ${data.symbol}")
} yield pos.toLocation.toNonJar(tempSourcesDir)
locations.toList
}
}
|
#!/bin/sh
# Many of neutron's repos suffer from the problem of depending on neutron,
# but it not existing on pypi.
# This wrapper for tox's package installer will use the existing package
# if it exists, else use zuul-cloner if that program exists, else grab it
# from neutron master via a hard-coded URL. That last case should only
# happen with devs running unit tests locally.
# From the tox.ini config page:
# install_command=ARGV
# default:
# pip install {opts} {packages}
PROJ=$1
MOD=$2
shift 2
ZUUL_CLONER=/usr/zuul-env/bin/zuul-cloner
neutron_installed=$(echo "import ${MOD}" | python 2>/dev/null ; echo $?)
BRANCH_NAME=master
set -e
CONSTRAINTS_FILE=$1
shift
install_cmd="pip install"
if [ $CONSTRAINTS_FILE != "unconstrained" ]; then
install_cmd="$install_cmd -c$CONSTRAINTS_FILE"
fi
if [ $neutron_installed -eq 0 ]; then
echo "ALREADY INSTALLED" > /tmp/tox_install-${PROJ}.txt
echo "${PROJ} already installed; using existing package"
elif [ -x "$ZUUL_CLONER" ]; then
echo "ZUUL CLONER" > /tmp/tox_install-${PROJ}.txt
cwd=$(/bin/pwd)
cd /tmp
$ZUUL_CLONER --cache-dir \
/opt/git \
--branch ${BRANCH_NAME} \
git://git.openstack.org \
openstack/${PROJ}
cd openstack/${PROJ}
$install_cmd -e .
cd "$cwd"
else
echo "PIP HARDCODE" > /tmp/tox_install-${PROJ}.txt
$install_cmd -U -egit+https://git.openstack.org/openstack/${PROJ}@${BRANCH_NAME}#egg=${PROJ}
fi
|
package dk.kvalitetsit.hjemmebehandling.service;
import dk.kvalitetsit.hjemmebehandling.service.access.AccessValidator;
import dk.kvalitetsit.hjemmebehandling.service.exception.AccessValidationException;
import org.hl7.fhir.r4.model.DomainResource;
import java.util.List;
public abstract class AccessValidatingService {
private AccessValidator accessValidator;
public AccessValidatingService(AccessValidator accessValidator) {
this.accessValidator = accessValidator;
}
protected void validateAccess(DomainResource resource) throws AccessValidationException {
accessValidator.validateAccess(resource);
}
protected void validateAccess(List<? extends DomainResource> resources) throws AccessValidationException {
accessValidator.validateAccess(resources);
}
}
|
import { Component, ChangeDetectionStrategy, forwardRef } from "@angular/core";
import { MjDynamicFormBase, provideFormGroupDirective } from "@mjamin/dynamic-form";
@Component({
selector: "mj-dynamic-card-form",
templateUrl: "./card-form.component.html",
styleUrls: ["./card-form.component.scss"],
changeDetection: ChangeDetectionStrategy.OnPush,
providers: [ provideFormGroupDirective(forwardRef(() => MjCardFormComponent)) ]
})
export class MjCardFormComponent extends MjDynamicFormBase { }
|
#!/bin/bash
# source: https://docs.gitlab.com/ee/ci/examples/php.html
# We need to install dependencies only for Docker
[[ ! -e /.dockerenv ]] && exit 0
set -xe
# Install git (the php image doesn't have it) which is required by composer
apt-get update -yqq
apt-get install git unzip -yqq
(pecl install xdebug-2.9.8 || pecl install xdebug-2.5.5) \
&& docker-php-ext-enable xdebug
curl -sS https://raw.githubusercontent.com/composer/getcomposer.org/d3e09029468023aa4e9dcd165e9b6f43df0a9999/web/installer | php -- --install-dir=/usr/local/bin --filename=composer
|
#!/bin/bash
set -e
RETCODE=$(fw_exists $IROOT/mono.installed)
[ ! "$RETCODE" == 0 ] || { return 0; }
# what do we want? latest mono
# how do we want it? already compiled from packages but without sudo
# save environment
cat > $IROOT/mono.installed <<'END'
export SNAPDATE=20141220092712
export MONO_HOME=$IROOT/mono-snapshot-$SNAPDATE
export MONO_PATH=$MONO_HOME/lib/mono/4.5
export MONO_CFG_DIR=$MONO_HOME/etc
export PATH=$MONO_HOME/bin:$PATH
export LD_LIBRARY_PATH=$MONO_HOME/lib:$LD_LIBRARY_PATH
export PKG_CONFIG_PATH=$MONO_HOME/lib/pkgconfig:$PKG_CONFIG_PATH
END
# load environment
. $IROOT/mono.installed
# temp dir for extracting archives
TEMP=$IROOT/mono-snapshot-${SNAPDATE}-temp
# start fresh
rm -rf $TEMP && mkdir -p $TEMP
rm -rf $MONO_HOME && mkdir -p $MONO_HOME
# download .debs and extract them into $TEMP dir
fw_get http://jenkins.mono-project.com/repo/debian/pool/main/m/mono-snapshot-${SNAPDATE}/mono-snapshot-${SNAPDATE}_${SNAPDATE}-1_amd64.deb
fw_get http://jenkins.mono-project.com/repo/debian/pool/main/m/mono-snapshot-${SNAPDATE}/mono-snapshot-${SNAPDATE}-assemblies_${SNAPDATE}-1_all.deb
dpkg-deb -x mono-*amd64.deb $TEMP
dpkg-deb -x mono-*assemblies*.deb $TEMP
# move /opt/mono-$SNAPDATE to /installs
mv $TEMP/opt/mono-*/* $MONO_HOME
# cleanup
rm mono-*.deb
rm -rf $TEMP
# replace /opt/mono-$SNAPDATE path
file $MONO_HOME/bin/* | grep "POSIX shell script" | awk -F: '{print $1}' | xargs sed -i "s|/opt/mono-$SNAPDATE|$MONO_HOME|g"
sed -i "s|/opt/mono-$SNAPDATE|$MONO_HOME|g" $MONO_HOME/lib/pkgconfig/*.pc $MONO_HOME/etc/mono/config
# import SSL certificates
mozroots --import --sync
#echo -e 'y\ny\ny\n' | certmgr -ssl https://nuget.org
touch $IROOT/mono.installed
|
<reponame>ralfbox/AndroidQuickDialog
package com.ralfbox.quickdialog.core;
import android.content.DialogInterface;
import android.util.Log;
import com.ralfbox.quickdialog.QuickDialog;
/**
* @author <NAME>
* Created by Admin on 30.08.2016.
*/
public class CallResultQuickDialogEngineer {
private static final String TAG = CallResultQuickDialogEngineer.class.getSimpleName();
private final QuickDialog quickDialog;
private final MethodSearcher.Filter methodFilter;
private final int whichButton;
public CallResultQuickDialogEngineer(QuickDialog quickDialog, int whichButton) {
this.quickDialog = quickDialog;
this.whichButton = whichButton;
this.methodFilter = getMethodFilter(quickDialog, whichButton);
}
private static MethodSearcher.Filter getMethodFilter(QuickDialog quickDialog, int whichButton) {
String requestTag = quickDialog.getRequestTag();
switch (whichButton){
case DialogInterface.BUTTON_NEGATIVE:
return new MethodFilter.NegativeButtonFilter(requestTag);
case DialogInterface.BUTTON_NEUTRAL:
return new MethodFilter.NeutralButtonFilter(requestTag);
case DialogInterface.BUTTON_POSITIVE:
return new MethodFilter.PositiveButtonFilter(requestTag);
default:
return null;
}
}
public void execute() {
if (methodFilter == null) {
loge(TAG, "execute: methodFilter is null!");
return;
}
MethodSearcher methodSearcher = new MethodSearcher(quickDialog.getBaseObjectToCallResult(), methodFilter);
CallMethodEngineer callMethodEngineer = new CallMethodEngineer(
quickDialog.getBaseObjectToCallResult(),
methodSearcher, new Object[]{quickDialog, whichButton, quickDialog.getDialog(), quickDialog.getControllerQD()}
);
try {
callMethodEngineer.execute();
} catch (Exception e) {
Log.w(TAG, null, e);
}
}
private static void loge(String tag, String s) {
Log.e(tag, s);
}
private static void loge(String tag, String s, Throwable e) {
Log.e(tag, s, e);
}
}
|
<reponame>IanGClifton/MoreEssentials<filename>complete-project/app/src/main/java/com/iangclifton/moreessentials/LessonDetailActivity.java
package com.iangclifton.moreessentials;
import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
/**
* Activity to display a single Lesson Fragment, used for phones.
*
* @author <NAME>
*/
public class LessonDetailActivity extends AppCompatActivity {
private static final String ARG_FRAGMENT_CLASS = "fragmentClass";
private static final String ARG_LESSON_NAME = "lessonName";
/**
* Static helper method to start the LessonDetailActivity with the right Intent extras
*
* @param context Context to create the Intent with
* @param lessonName String name of the Lesson to display
* @param fragmentClass String name of the Fragment class
*/
public static void startActivity(Context context, String lessonName, String fragmentClass) {
final Intent intent = new Intent(context, LessonDetailActivity.class);
intent.putExtra(ARG_FRAGMENT_CLASS, fragmentClass);
intent.putExtra(ARG_LESSON_NAME, lessonName);
context.startActivity(intent);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle(getIntent().getStringExtra(ARG_LESSON_NAME));
setContentView(R.layout.activity_lesson_detail);
Toolbar toolbar = (Toolbar) findViewById(R.id.detail_toolbar);
setSupportActionBar(toolbar);
// Show the Up button in the action bar.
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// savedInstanceState is non-null when there is fragment state
// saved from previous configurations of this activity
// (e.g. when rotating the screen from portrait to landscape).
// In this case, the fragment will automatically be re-added
// to its container so we don't need to manually add it.
// For more information, see the Fragments API guide at:
//
// http://developer.android.com/guide/components/fragments.html
//
if (savedInstanceState == null) {
// Create the detail fragment and add it to the activity
// using a fragment transaction.
String fragmentClassString = getIntent().getStringExtra(ARG_FRAGMENT_CLASS);
Class<Fragment> fragmentClass;
try {
fragmentClass = (Class<Fragment>) Class.forName(fragmentClassString);
} catch (ClassNotFoundException e) {
e.printStackTrace();
return;
}
Fragment fragment = null;
try {
fragment = fragmentClass.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
e.printStackTrace();
return;
}
getSupportFragmentManager().beginTransaction()
.add(R.id.lesson_detail_container, fragment)
.commit();
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
navigateUpTo(new Intent(this, LessonListActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
}
|
CREATE TABLE users (
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(255) NOT NULL,
email VARCHAR(255) NOT NULL,
username VARCHAR(255) NOT NULL,
password VARCHAR(255) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE UNIQUE INDEX users_username_uindex ON users (username); |
export const enum FilterValue {
All = "All",
Active = "Active",
Completed = "Done",
}
export class Filter {
private _selected = FilterValue.All;
get selected(): FilterValue {
return this._selected;
}
set selected(value: FilterValue) {
this._selected = value;
}
get all(): FilterValue {
return FilterValue.All;
}
get active(): string {
return FilterValue.Active;
}
get completed(): string {
return FilterValue.Completed;
}
}
|
<filename>node_modules/discord-youtube-api/src/Video.js
const duration = require("iso8601-duration");
class Video {
constructor(data) {
const durationObj = duration.parse(data.items[0].contentDetails.duration);
this.duration = durationObj;
this.durationSeconds = duration.toSeconds(durationObj);
this.title = data.items[0].snippet.title;
this.id = data.items[0].id;
this.description = data.items[0].snippet.description;
this.data = data;
}
get url() {
return `https://www.youtube.com/watch?v=${this.id}`;
}
get thumbnail() {
return `https://img.youtube.com/vi/${this.id}/default.jpg`;
}
get length() {
const time = this.durationSeconds;
const hours = ~~(time / 3600);
const minutes = ~~((time % 3600) / 60);
const seconds = time % 60;
let length = "";
if (hours > 0) length += `${hours}:${minutes < 10 ? "0" : ""}`;
length += `${minutes}:${seconds < 10 ? "0" : ""}${seconds}`;
return length;
}
}
module.exports = Video; |
#!/bin/bash
vendor/bin/phpcbf
|
package com.cjy.flb.event;
import java.util.HashMap;
/**
* Created by Administrator on 2015/12/25 0025.
*/
public class PerodOfDayEvent {
private String week;
private HashMap<String, Boolean> hasMap;
public PerodOfDayEvent() {
}
public PerodOfDayEvent(String week, HashMap<String, Boolean> hasMap) {
this.week = week;
this.hasMap = hasMap;
}
public String getWeek() {
return week;
}
public void setWeek(String week) {
this.week = week;
}
public HashMap<String, Boolean> getHasMap() {
return hasMap;
}
public void setHasMap(HashMap<String, Boolean> hasMap) {
this.hasMap = hasMap;
}
}
|
<filename>app/components/BackgroundButton.js<gh_stars>0
import React from 'react';
import {
View,
Text,
Image,
Button
} from 'react-native';
export default class BackgroundButton extends React.Component {
constructor(props){
super(props);
}
_renderIcon(){
if(this.props.icon){
return <Image
source={this.props.icon}
style={{
width: 60,
marginRight: 20,
maxHeight: 100
}}
/>
}
}
render(){
const resizeMode = 'cover';
return(
<View
style={{
flex: 1,
backgroundColor: 'transparent',
width: (!this.props.icon)? 162: 190,
height: (!this.props.icon)? 35 : 63,
borderRadius: 15
}}
>
<View
style={{
position: 'absolute',
top: 0,
left: 0,
width: "100%",
height: '100%'
}}
>
<Image
style={{
flex: 1,
resizeMode,
width: "100%",
borderRadius: (!this.props.icon)? 2: 7
}}
source={require('../assets/img/banda.png')}
/>
</View>
<View
style={{
flex: 1,
backgroundColor: 'transparent',
justifyContent: 'center'
}}
>
<Text
style={{
textAlign: 'center',
fontSize: this.props.font_size,
color: "#ffffff"
}}
>
{this.props.text}
</Text>
</View>
</View>
);
}
} |
<filename>src/main/java/com/devaneios/turmadeelite/entities/ExternalClassConfig.java
package com.devaneios.turmadeelite.entities;
import lombok.*;
import javax.persistence.*;
@Entity
@Table(name = "external_class_config")
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
@Builder
public class ExternalClassConfig {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String externalClassId;
private Boolean isClosed;
private Float goldPercent;
private Float silverPercent;
private Float bronzePercent;
}
|
<reponame>GigaMax007/PersonalFinance<filename>src/personalfinance/model/Transfer.java
package personalfinance.model;
import personalfinance.exception.ModelException;
import personalfinance.saveload.SaveData;
import java.util.Date;
public class Transfer extends Common {
private Account fromAccount; // откуда переводим деньги
private Account toAccount; // куда переводим деньги
private double fromAmount; // сколько ушло
private double toAmount; // сколько пришло
private String notice;
private Date date;
public Transfer() {
}
public Transfer(Account fromAccount, Account toAccount, double fromAmount, double toAmount, String notice, Date date) throws ModelException {
if (fromAccount == null) throw new ModelException(ModelException.ACCOUNT_EMPTY);
if (toAccount == null) throw new ModelException(ModelException.ACCOUNT_EMPTY);
if (fromAmount < 0 || toAmount < 0) throw new ModelException(ModelException.AMOUNT_FORMAT);
this.fromAccount = fromAccount;
this.toAccount = toAccount;
this.fromAmount = fromAmount;
this.toAmount = toAmount;
this.notice = notice;
this.date = date;
}
public Transfer(Account fromAccount, Account toAccount, double fromAmount, double toAmount, String notice) throws ModelException {
this(fromAccount, toAccount, fromAmount, toAmount, notice, new Date());
}
public Transfer(Account fromAccount, Account toAccount, double fromAmount, double toAmount, Date date) throws ModelException {
this(fromAccount, toAccount, fromAmount, toAmount, "", date);
}
public Transfer(Account fromAccount, Account toAccount, double fromAmount, double toAmount) throws ModelException {
this(fromAccount, toAccount, fromAmount, toAmount, "", new Date());
}
public Account getFromAccount() {
return fromAccount;
}
public void setFromAccount(Account fromAccount) {
this.fromAccount = fromAccount;
}
public Account getToAccount() {
return toAccount;
}
public void setToAccount(Account toAccount) {
this.toAccount = toAccount;
}
public double getFromAmount() {
return fromAmount;
}
public void setFromAmount(double fromAmount) {
this.fromAmount = fromAmount;
}
public double getToAmount() {
return toAmount;
}
public void setToAmount(double toAmount) {
this.toAmount = toAmount;
}
public String getNotice() {
return notice;
}
public void setNotice(String notice) {
this.notice = notice;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
@Override
public String toString() {
return "Transfer{" +
"fromAccount=" + fromAccount +
", toAccount=" + toAccount +
", fromAmount=" + fromAmount +
", toAmount=" + toAmount +
", notice='" + notice + '\'' +
", date=" + date +
'}';
}
@Override
public void postAdd(SaveData sd) {
setAmounts(sd);
}
@Override
public void postEdit(SaveData sd) {
setAmounts(sd);
}
@Override
public void postRemove(SaveData sd) {
setAmounts(sd);
}
private void setAmounts(SaveData sd) {
for (Account a :
sd.getAccounts()) {
a.setAmountFromTransactionsAndTransfers(sd.getTransactions(), sd.getTransfers());
}
}
}
|
'use strict';
import ComponentHelper from '../helpers/ComponentHelper.js';
import EventMappers from '../helpers/EventMappers.js';
import {Surface} from 'js-surface';
import {SurfaceX} from 'js-surface-x';
import {Arrays, Seq, Strings} from 'js-prelude';
const dom = Surface.createElement;
export default SurfaceX.createFactory({
typeName: 'FKButton',
properties: {
text: {
type: 'string',
defaultValue: ''
},
icon: {
type: 'string',
defaultValue: ''
},
type: {
type: 'string',
options: ['default', 'link', 'info', 'warning', 'danger', 'success'],
defaultValue: 'default'
},
disabled: {
type: 'boolean',
defaultValue: false
},
size: {
type: 'string',
options: ['normal', 'large', 'small', 'tiny'],
defaultValue: 'normal'
},
iconPosition: {
type: 'string',
options: ['top', 'bottom', 'left', 'right'],
defaultValue: 'left'
},
tooltip: {
type: 'string',
defaultValue: ''
},
className: {
type: 'string',
defaultValue: ''
},
menu: {
type: Array,
defaultValue: []
},
onClick: {
type: 'function',
defaultValue: null
}
},
render: renderButton
});
function renderButton({props}) {
const
key = props.get('key', null),
onClick = props.get('onClick'),
icon = Strings.trimToNull(props.get('icon')),
iconPosition = props.get('iconPosition'),
iconElement =
ComponentHelper.createIconElement(
icon,
'fk-button-icon fk-icon fk-' + iconPosition),
type =
Arrays.selectValue(
['default', 'primary', 'success', 'info', 'warning', 'danger', 'link'],
props.get('type'),
'default'),
text = Strings.trimToNull(props.get('text')),
textElement =
text === null
? null
: dom('span',
{className: 'fk-button-text'},
text),
tooltip = props.get('tooltip'), // TODO
disabled = props.get('disabled'),
menu =
Seq.from(props.getObject('menu'))
.toArray(),
hasMenu = menu.length > 0,
isDropdown = hasMenu && !onClick,
isSplitButton = hasMenu && onClick,
caret =
hasMenu
? dom('span', {className: 'caret'})
: null,
sizeClass = props.get('size'),
className =
ComponentHelper.buildCssClass(
'btn btn-' + type,
sizeClass,
(text === null ? null : 'fk-has-text'),
(iconElement === null ? null : 'fk-has-icon'),
(!isDropdown ? null : 'dropdown-toggle')),
doOnClick = event => {
const onClick = props.get('onClick');
if (onClick) {
onClick(EventMappers.mapClickEvent(event));
}
},
button =
dom('button', {
type: 'button',
className: className,
title: tooltip,
disabled: disabled,
onClick: doOnClick,
key: key
},
(iconPosition === 'left' || iconPosition === 'top'
? [iconElement, (text !== null && icon !== null ? ' ' : null), textElement]
: [textElement, (text !== null && icon !== null ? ' ' : null), iconElement]),
(isDropdown ? caret : null));
let ret;
if (isDropdown) {
ret =
dom('div',
{className: 'fk-button btn-group ' + props.get('className')},
button,
dom('ul',
{className: 'dropdown-menu'},
dom('li',
null,
dom('a',
null,
'Juhu'))));
} else if (isSplitButton) {
ret =
dom('div',
{className: 'fk-button btn-group ' + props.get('className')},
button,
dom('button',
{className: 'btn dropdown-toggle btn-' + type},
' ',
caret),
dom('ul',
{className: 'dropdown-menu'},
dom('li',
null,
dom('a',
null,
'Juhu'))));
} else {
ret =
dom('div',
{className: 'fk-button btn-group ' + props.get('className')},
button);
}
return ret;
}
|
//
// ViewController.h
// NewProjectPrepareDemo
//
// Created by KDB on 16/7/27.
// Copyright © 2016年 Will-Z. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@end
|
import React, { useCallback } from 'react';
import FlashMessage, { showMessage } from 'react-native-flash-message';
import IToastContext from 'shared/domain/providers/IToastContext';
import { ToastContextProvider } from 'shared/view/contexts/ToastContext/hooks/useToastContext';
const FlashMessageToastContext: React.FC = ({ children }) => {
const showError = useCallback<IToastContext['showError']>(
message =>
showMessage({
message,
type: 'danger',
}),
[],
);
const showInfo = useCallback<IToastContext['showInfo']>(
message =>
showMessage({
message,
type: 'info',
}),
[],
);
const showSuccess = useCallback<IToastContext['showSuccess']>(
message =>
showMessage({
message,
type: 'success',
}),
[],
);
return (
<ToastContextProvider.Provider value={{ showError, showInfo, showSuccess }}>
{children}
<FlashMessage position="bottom" />
</ToastContextProvider.Provider>
);
};
export default FlashMessageToastContext;
|
/*RTL8188E PHY Parameters*/
#define SVN_COMMIT_VERSION_8188E 65
#define RELEASE_DATE_8188E 20150610
#define COMMIT_BY_8188E "BB_LUKE"
#define RELEASE_VERSION_8188E 63
|
/*
* Copyright 2015 Groupon.com
*
* 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.arpnetworking.tsdcore.sinks;
import com.arpnetworking.logback.annotations.LogValue;
import com.arpnetworking.steno.LogValueMapFactory;
import com.arpnetworking.tsdcore.model.PeriodicData;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.Sets;
import net.sf.oval.constraint.NotNull;
import java.time.Duration;
import java.util.Collections;
import java.util.Optional;
import java.util.Set;
/**
* A publisher that wraps another, filters the metrics with specific periods,
* and forwards included metrics to the wrapped sink. This class is thread
* safe.
*
* @author <NAME> (ville dot koskela at inscopemetrics dot io)
*/
public final class PeriodFilteringSink extends BaseSink {
@Override
public void recordAggregateData(final PeriodicData periodicData) {
if (_cachedFilterResult.getUnchecked(periodicData.getPeriod())) {
_sink.recordAggregateData(periodicData);
}
}
@Override
public void close() {
_sink.close();
}
@LogValue
@Override
public Object toLogValue() {
return LogValueMapFactory.builder(this)
.put("super", super.toLogValue())
.put("include", _include)
.put("exclude", _exclude)
.put("excludeLessThan", _excludeLessThan)
.put("excludeGreaterThan", _excludeGreaterThan)
.put("sink", _sink)
.build();
}
private PeriodFilteringSink(final Builder builder) {
super(builder);
_cachedFilterResult = CacheBuilder.newBuilder()
.maximumSize(10)
.build(new CacheLoader<Duration, Boolean>() {
@Override
public Boolean load(final Duration key) {
if (_include.contains(key)) {
return true;
}
if (_exclude.contains(key)) {
return false;
}
if (_excludeLessThan.isPresent()
&& key.compareTo(_excludeLessThan.get()) < 0) {
return false;
}
if (_excludeGreaterThan.isPresent()
&& key.compareTo(_excludeGreaterThan.get()) > 0) {
return false;
}
return true;
}
});
_exclude = Sets.newConcurrentHashSet(builder._exclude);
_include = Sets.newConcurrentHashSet(builder._include);
_excludeLessThan = Optional.ofNullable(builder._excludeLessThan);
_excludeGreaterThan = Optional.ofNullable(builder._excludeGreaterThan);
_sink = builder._sink;
}
private final LoadingCache<Duration, Boolean> _cachedFilterResult;
private final Set<Duration> _exclude;
private final Set<Duration> _include;
private final Optional<Duration> _excludeLessThan;
private final Optional<Duration> _excludeGreaterThan;
private final Sink _sink;
/**
* Base {@link Builder} implementation.
*
* @author <NAME> (ville dot koskela at inscopemetrics dot io)
*/
public static final class Builder extends BaseSink.Builder<Builder, PeriodFilteringSink> {
/**
* Public constructor.
*/
public Builder() {
super(PeriodFilteringSink::new);
}
/**
* Sets excluded periods. Optional. Default is no excluded periods.
*
* @param value The excluded periods.
* @return This instance of {@link Builder}.
*/
public Builder setExclude(final Set<Duration> value) {
_exclude = value;
return self();
}
/**
* Sets included periods. Included periods supercede all other
* settings. Optional. Default is no included periods.
*
* @param value The included periods.
* @return This instance of {@link Builder}.
*/
public Builder setInclude(final Set<Duration> value) {
_include = value;
return self();
}
/**
* Sets excluded periods less than this period. Optional. Default is no threshold.
*
* @param value The excluded period threshold.
* @return This instance of {@link Builder}.
*/
public Builder setExcludeLessThan(final Duration value) {
_excludeLessThan = value;
return self();
}
/**
* Sets excluded periods greater than this period. Optional. Default is no threshold.
*
* @param value The excluded period threshold.
* @return This instance of {@link Builder}.
*/
public Builder setExcludeGreaterThan(final Duration value) {
_excludeGreaterThan = value;
return self();
}
/**
* The aggregated data sink to filter. Cannot be null.
*
* @param value The aggregated data sink to filter.
* @return This instance of {@link Builder}.
*/
public Builder setSink(final Sink value) {
_sink = value;
return this;
}
@Override
protected Builder self() {
return this;
}
@NotNull
private Set<Duration> _exclude = Collections.emptySet();
@NotNull
private Set<Duration> _include = Collections.emptySet();
private Duration _excludeLessThan;
private Duration _excludeGreaterThan;
@NotNull
private Sink _sink;
}
}
|
package com.hedera.services.bdd.suites.token;
/*-
*
* Hedera Services Test Clients
*
* Copyright (C) 2018 - 2021 <NAME>, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
import com.google.protobuf.ByteString;
import com.hedera.services.bdd.spec.HapiApiSpec;
import com.hedera.services.bdd.spec.transactions.TxnUtils;
import com.hedera.services.bdd.spec.transactions.token.TokenMovement;
import com.hedera.services.bdd.spec.utilops.UtilVerbs;
import com.hedera.services.bdd.suites.HapiApiSuite;
import com.hederahashgraph.api.proto.java.AccountID;
import com.hederahashgraph.api.proto.java.ResponseCodeEnum;
import com.hederahashgraph.api.proto.java.TokenSupplyType;
import com.hederahashgraph.api.proto.java.TokenType;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.junit.Assert;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;
import java.util.stream.LongStream;
import static com.hedera.services.bdd.spec.HapiApiSpec.defaultHapiSpec;
import static com.hedera.services.bdd.spec.queries.QueryVerbs.getAccountBalance;
import static com.hedera.services.bdd.spec.queries.QueryVerbs.getAccountInfo;
import static com.hedera.services.bdd.spec.queries.QueryVerbs.getAccountNftInfos;
import static com.hedera.services.bdd.spec.queries.QueryVerbs.getReceipt;
import static com.hedera.services.bdd.spec.queries.QueryVerbs.getTokenInfo;
import static com.hedera.services.bdd.spec.queries.QueryVerbs.getTokenNftInfo;
import static com.hedera.services.bdd.spec.queries.QueryVerbs.getTokenNftInfos;
import static com.hedera.services.bdd.spec.queries.QueryVerbs.getTxnRecord;
import static com.hedera.services.bdd.spec.queries.crypto.ExpectedTokenRel.relationshipWith;
import static com.hedera.services.bdd.spec.queries.token.HapiTokenNftInfo.newTokenNftInfo;
import static com.hedera.services.bdd.spec.transactions.TxnVerbs.burnToken;
import static com.hedera.services.bdd.spec.transactions.TxnVerbs.cryptoCreate;
import static com.hedera.services.bdd.spec.transactions.TxnVerbs.cryptoDelete;
import static com.hedera.services.bdd.spec.transactions.TxnVerbs.cryptoTransfer;
import static com.hedera.services.bdd.spec.transactions.TxnVerbs.mintToken;
import static com.hedera.services.bdd.spec.transactions.TxnVerbs.tokenAssociate;
import static com.hedera.services.bdd.spec.transactions.TxnVerbs.tokenCreate;
import static com.hedera.services.bdd.spec.transactions.TxnVerbs.tokenDelete;
import static com.hedera.services.bdd.spec.transactions.TxnVerbs.wipeTokenAccount;
import static com.hedera.services.bdd.spec.transactions.token.TokenMovement.movingUnique;
import static com.hedera.services.bdd.spec.utilops.CustomSpecAssert.allRunFor;
import static com.hedera.services.bdd.spec.utilops.UtilVerbs.newKeyNamed;
import static com.hederahashgraph.api.proto.java.ResponseCodeEnum.ACCOUNT_DELETED;
import static com.hederahashgraph.api.proto.java.ResponseCodeEnum.BATCH_SIZE_LIMIT_EXCEEDED;
import static com.hederahashgraph.api.proto.java.ResponseCodeEnum.FAIL_INVALID;
import static com.hederahashgraph.api.proto.java.ResponseCodeEnum.INVALID_ACCOUNT_ID;
import static com.hederahashgraph.api.proto.java.ResponseCodeEnum.INVALID_NFT_ID;
import static com.hederahashgraph.api.proto.java.ResponseCodeEnum.INVALID_QUERY_RANGE;
import static com.hederahashgraph.api.proto.java.ResponseCodeEnum.INVALID_TOKEN_NFT_SERIAL_NUMBER;
import static com.hederahashgraph.api.proto.java.ResponseCodeEnum.INVALID_WIPING_AMOUNT;
import static com.hederahashgraph.api.proto.java.ResponseCodeEnum.NOT_SUPPORTED;
import static com.hederahashgraph.api.proto.java.ResponseCodeEnum.OK;
import static com.hederahashgraph.api.proto.java.ResponseCodeEnum.TOKEN_WAS_DELETED;
import static com.hederahashgraph.api.proto.java.TokenType.NON_FUNGIBLE_UNIQUE;
public class UniqueTokenManagementSpecs extends HapiApiSuite {
private static final org.apache.logging.log4j.Logger log = LogManager.getLogger(UniqueTokenManagementSpecs.class);
private static final String A_TOKEN = "TokenA";
private static final String NFT = "nft";
private static final String FUNGIBLE_TOKEN = "<PASSWORD>";
private static final String SUPPLY_KEY = "supplyKey";
private static final String FIRST_USER = "Client1";
private static final int BIGGER_THAN_LIMIT = 11;
public static void main(String... args) {
new UniqueTokenManagementSpecs().runSuiteSync();
}
@Override
protected List<HapiApiSpec> getSpecsInSuite() {
return List.of(
getTokenNftInfoWorks(),
mintHappyPath(),
tokenMintWorksWhenAccountsAreFrozenByDefault(),
mintFailsWithDeletedToken(),
mintWorksWithRepeatedMetadata(),
failsGetTokenNftInfoWithNoNft(),
mintRespectsConstraints(),
mintFailsWithTooLargeMetadata(),
mintFailsWithInvalidMetadata(),
distinguishesFeeSubTypes(),
burnHappyPath(),
burnFailsOnInvalidSerialNumber(),
burnRespectsConstraints(),
treasuryBalanceCorrectAfterBurn(),
burnWorksWhenAccountsAreFrozenByDefault(),
wipeHappyPath(),
wipeFailsWithInvalidSerialNumber(),
wipeRespectsConstraints(),
uniqueWipeFailsWhenInvokedOnFungibleToken(),
commonWipeFailsWhenInvokedOnUniqueToken(),
uniqueTokenMintReceiptCheck(),
associatesNftAsExpected(),
failsWithAccountWithoutNfts(),
validatesQueryOutOfRange(),
failsWithInvalidQueryBoundaries(),
getAccountNftsInfoFailsWithDeletedAccount(),
getAccountNftsInfoFailsWithInexistentAccount(),
associatesNftAsExpected(),
failsWithAccountWithoutNfts(),
validatesQueryOutOfRange(),
failsWithInvalidQueryBoundaries(),
getAccountNftsInfoFailsWithDeletedAccount(),
getAccountNftsInfoFailsWithInexistentAccount());
}
private HapiApiSpec associatesNftAsExpected() {
return defaultHapiSpec("AssociatesNftAsExpected")
.given(
newKeyNamed(SUPPLY_KEY),
cryptoCreate(TOKEN_TREASURY),
tokenCreate(NFT)
.initialSupply(0)
.tokenType(TokenType.NON_FUNGIBLE_UNIQUE)
.supplyType(TokenSupplyType.INFINITE)
.supplyKey(SUPPLY_KEY)
.treasury(TOKEN_TREASURY)
).when(
mintToken(NFT, List.of(
metadata("some metadata"),
metadata("some metadata2"),
metadata("some metadata3")
))
).then(
getAccountNftInfos(TOKEN_TREASURY, 0, 2)
.hasNfts(
newTokenNftInfo(NFT, 1, TOKEN_TREASURY, metadata("some metadata")),
newTokenNftInfo(NFT, 2, TOKEN_TREASURY, metadata("some metadata2"))
)
.logged()
);
}
private HapiApiSpec validatesQueryOutOfRange() {
return defaultHapiSpec("ValidatesQueryOutOfRange")
.given(
newKeyNamed(SUPPLY_KEY),
cryptoCreate(TOKEN_TREASURY),
tokenCreate(NFT)
.initialSupply(0)
.tokenType(TokenType.NON_FUNGIBLE_UNIQUE)
.supplyType(TokenSupplyType.INFINITE)
.supplyKey(SUPPLY_KEY)
.treasury(TOKEN_TREASURY)
).when(
mintToken(NFT, List.of(
metadata("some metadata"),
metadata("some metadata2"),
metadata("some metadata3")
))
).then(
getAccountNftInfos(TOKEN_TREASURY, 0, 6)
.hasCostAnswerPrecheck(INVALID_QUERY_RANGE)
);
}
private HapiApiSpec failsWithAccountWithoutNfts() {
return defaultHapiSpec("FailsWithAccountWithoutNfts")
.given(
cryptoCreate(FIRST_USER)
).when().then(
getAccountNftInfos(FIRST_USER, 0, 2)
.hasCostAnswerPrecheck(INVALID_QUERY_RANGE)
);
}
private HapiApiSpec getAccountNftsInfoFailsWithDeletedAccount() {
return defaultHapiSpec("GetAccountNftsInfoFailsWithDeletedAccount")
.given(
cryptoCreate(FIRST_USER),
cryptoDelete(FIRST_USER)
).when().then(
getAccountNftInfos(FIRST_USER, 0, 2)
.hasCostAnswerPrecheck(ACCOUNT_DELETED)
);
}
private HapiApiSpec getAccountNftsInfoFailsWithInexistentAccount() {
return defaultHapiSpec("GetAccountNftsInfoFailsWithInexistentAccount")
.given().when().then(
getAccountNftInfos("0.0.123", 0, 2)
.hasCostAnswerPrecheck(INVALID_ACCOUNT_ID)
);
}
private HapiApiSpec failsWithInvalidQueryBoundaries() {
return defaultHapiSpec("FailsWithInvalidQueryBoundaries")
.given(
cryptoCreate(FIRST_USER)
).when().then(
getAccountNftInfos(FIRST_USER, 2, 0)
.hasCostAnswerPrecheck(INVALID_QUERY_RANGE),
getAccountNftInfos(FIRST_USER, 0, 100000000)
.hasCostAnswerPrecheck(INVALID_QUERY_RANGE)
);
}
private HapiApiSpec burnWorksWhenAccountsAreFrozenByDefault() {
return defaultHapiSpec("burnWorksWhenAccountsAreFrozenByDefault")
.given(
newKeyNamed(SUPPLY_KEY),
cryptoCreate(TOKEN_TREASURY),
tokenCreate(NFT)
.tokenType(NON_FUNGIBLE_UNIQUE)
.supplyType(TokenSupplyType.INFINITE)
.initialSupply(0)
.supplyKey(SUPPLY_KEY)
.treasury(TOKEN_TREASURY),
mintToken(NFT, List.of(metadata("memo")))
)
.when(
burnToken(NFT, List.of(1L)).via("burnTxn").logged()
)
.then(
getTxnRecord("burnTxn")
.hasCostAnswerPrecheck(OK),
getTokenNftInfo(NFT, 1)
.hasCostAnswerPrecheck(INVALID_NFT_ID),
getTokenNftInfos(NFT, 0, 1).hasCostAnswerPrecheck(INVALID_QUERY_RANGE),
getAccountInfo(TOKEN_TREASURY).hasOwnedNfts(0),
getAccountNftInfos(TOKEN_TREASURY, 0, 1).hasCostAnswerPrecheck(INVALID_QUERY_RANGE)
);
}
private HapiApiSpec burnFailsOnInvalidSerialNumber() {
return defaultHapiSpec("burnFailsOnInvalidSerialNumber")
.given(
newKeyNamed(SUPPLY_KEY),
cryptoCreate(TOKEN_TREASURY),
tokenCreate(NFT)
.tokenType(NON_FUNGIBLE_UNIQUE)
.supplyType(TokenSupplyType.INFINITE)
.initialSupply(0)
.supplyKey(SUPPLY_KEY)
.treasury(TOKEN_TREASURY),
mintToken(NFT, List.of(metadata("memo"))))
.when()
.then(
burnToken(NFT, List.of(0L, 1L, 2L)).via("burnTxn").hasPrecheck(INVALID_NFT_ID),
getAccountInfo(TOKEN_TREASURY).hasOwnedNfts(1),
getAccountNftInfos(TOKEN_TREASURY, 0, 1)
.hasNfts(
newTokenNftInfo(NFT, 1, TOKEN_TREASURY, metadata("memo"))
)
.logged()
);
}
private HapiApiSpec burnRespectsConstraints() {
return defaultHapiSpec("respectsBurnBatchConstraints")
.given(
newKeyNamed(SUPPLY_KEY),
cryptoCreate(TOKEN_TREASURY),
tokenCreate(NFT)
.tokenType(NON_FUNGIBLE_UNIQUE)
.supplyType(TokenSupplyType.INFINITE)
.initialSupply(0)
.supplyKey(SUPPLY_KEY)
.treasury(TOKEN_TREASURY),
mintToken(NFT, List.of(metadata("memo"))))
.when(
)
.then(
burnToken(NFT, LongStream.range(0, 1000).boxed().collect(Collectors.toList())).via("burnTxn")
.hasPrecheck(BATCH_SIZE_LIMIT_EXCEEDED)
);
}
private HapiApiSpec burnHappyPath() {
return defaultHapiSpec("burnHappyEnd")
.given(
newKeyNamed(SUPPLY_KEY),
cryptoCreate(TOKEN_TREASURY),
tokenCreate(NFT)
.tokenType(NON_FUNGIBLE_UNIQUE)
.supplyType(TokenSupplyType.INFINITE)
.initialSupply(0)
.supplyKey(SUPPLY_KEY)
.treasury(TOKEN_TREASURY),
mintToken(NFT, List.of(metadata("memo")))
).when(
burnToken(NFT, List.of(1L)).via("burnTxn")
).then(
getTokenNftInfo(NFT, 1)
.hasCostAnswerPrecheck(INVALID_NFT_ID),
getTokenInfo(NFT)
.hasTotalSupply(0),
getAccountBalance(TOKEN_TREASURY)
.hasTokenBalance(NFT, 0),
getAccountInfo(TOKEN_TREASURY).hasToken(relationshipWith(NFT)).hasOwnedNfts(0)
);
}
private HapiApiSpec treasuryBalanceCorrectAfterBurn() {
return defaultHapiSpec("burnsExactGivenTokens")
.given(
newKeyNamed(SUPPLY_KEY),
cryptoCreate(TOKEN_TREASURY),
tokenCreate(NFT)
.tokenType(NON_FUNGIBLE_UNIQUE)
.supplyType(TokenSupplyType.INFINITE)
.initialSupply(0)
.supplyKey(SUPPLY_KEY)
.treasury(TOKEN_TREASURY),
mintToken(NFT,
List.of(metadata("1"), metadata("2"), metadata("3"), metadata("4"), metadata("5")))
)
.when(
burnToken(NFT, List.of(3L, 4L, 5L)).via("burnTxn")
)
.then(
getTokenNftInfo(NFT, 1)
.hasSerialNum(1)
.hasCostAnswerPrecheck(OK),
getTokenNftInfo(NFT, 2)
.hasSerialNum(2)
.hasCostAnswerPrecheck(OK),
getTokenNftInfo(NFT, 3)
.hasCostAnswerPrecheck(INVALID_NFT_ID),
getTokenNftInfo(NFT, 4)
.hasCostAnswerPrecheck(INVALID_NFT_ID),
getTokenNftInfo(NFT, 5)
.hasCostAnswerPrecheck(INVALID_NFT_ID),
getTokenInfo(NFT)
.hasTotalSupply(2),
getAccountBalance(TOKEN_TREASURY)
.hasTokenBalance(NFT, 2),
getAccountInfo(TOKEN_TREASURY)
.hasOwnedNfts(2),
getTokenNftInfos(NFT, 0, 2)
.hasNfts(
newTokenNftInfo(NFT, 1, TOKEN_TREASURY, metadata("1")),
newTokenNftInfo(NFT, 2, TOKEN_TREASURY, metadata("2"))
)
.logged(),
getAccountNftInfos(TOKEN_TREASURY, 0, 2)
.hasNfts(
newTokenNftInfo(NFT, 1, TOKEN_TREASURY, metadata("1")),
newTokenNftInfo(NFT, 2, TOKEN_TREASURY, metadata("2"))
)
.logged()
);
}
private HapiApiSpec distinguishesFeeSubTypes() {
return defaultHapiSpec("happyPathFiveMintOneMetadata")
.given(
newKeyNamed(SUPPLY_KEY),
cryptoCreate(TOKEN_TREASURY),
cryptoCreate("customPayer"),
tokenCreate(NFT)
.tokenType(NON_FUNGIBLE_UNIQUE)
.supplyType(TokenSupplyType.INFINITE)
.initialSupply(0)
.supplyKey(SUPPLY_KEY)
.treasury(TOKEN_TREASURY),
tokenCreate(FUNGIBLE_TOKEN)
.tokenType(TokenType.FUNGIBLE_COMMON)
.supplyType(TokenSupplyType.FINITE)
.initialSupply(10)
.maxSupply(1100)
.supplyKey(SUPPLY_KEY)
.treasury(TOKEN_TREASURY)
).when(
mintToken(NFT, List.of(metadata("memo"))).payingWith("customPayer").signedBy("customPayer",
"supplyKey").via("mintNFT"),
mintToken(FUNGIBLE_TOKEN, 100L).payingWith("customPayer").signedBy("customPayer",
"supplyKey").via("mintFungible")
).then(
UtilVerbs.withOpContext((spec, opLog) -> {
var mintNFT = getTxnRecord("mintNFT");
var mintFungible = getTxnRecord("mintFungible");
allRunFor(spec, mintNFT, mintFungible);
var nftFee = mintNFT.getResponseRecord().getTransactionFee();
var fungibleFee = mintFungible.getResponseRecord().getTransactionFee();
Assert.assertNotEquals(
"NFT Fee should NOT equal to the Fungible Fee!",
nftFee,
fungibleFee);
})
);
}
private HapiApiSpec mintFailsWithTooLargeMetadata() {
return defaultHapiSpec("failsWithTooLongMetadata")
.given(
newKeyNamed(SUPPLY_KEY),
cryptoCreate(TOKEN_TREASURY),
tokenCreate(NFT)
.tokenType(NON_FUNGIBLE_UNIQUE)
.supplyType(TokenSupplyType.INFINITE)
.initialSupply(0)
.supplyKey(SUPPLY_KEY)
.treasury(TOKEN_TREASURY)
).when().then(
mintToken(NFT, List.of(
metadataOfLength(101)
)).hasPrecheck(ResponseCodeEnum.METADATA_TOO_LONG)
);
}
private HapiApiSpec mintFailsWithInvalidMetadata() {
return defaultHapiSpec("failsWithInvalidMetadataFromBatch")
.given(
newKeyNamed(SUPPLY_KEY),
cryptoCreate(TOKEN_TREASURY),
tokenCreate(NFT)
.tokenType(NON_FUNGIBLE_UNIQUE)
.supplyType(TokenSupplyType.INFINITE)
.initialSupply(0)
.supplyKey(SUPPLY_KEY)
.treasury(TOKEN_TREASURY)
).when().then(
mintToken(NFT, List.of(
metadataOfLength(101),
metadataOfLength(1)
)).hasPrecheck(ResponseCodeEnum.METADATA_TOO_LONG)
);
}
private HapiApiSpec mintRespectsConstraints() {
return defaultHapiSpec("failsWithLargeBatchSize")
.given(
newKeyNamed(SUPPLY_KEY),
cryptoCreate(TOKEN_TREASURY),
tokenCreate(NFT)
.tokenType(NON_FUNGIBLE_UNIQUE)
.supplyType(TokenSupplyType.INFINITE)
.initialSupply(0)
.supplyKey(SUPPLY_KEY)
.treasury(TOKEN_TREASURY)
).when().then(
mintToken(NFT, batchOfSize(BIGGER_THAN_LIMIT))
.hasPrecheck(BATCH_SIZE_LIMIT_EXCEEDED)
);
}
private List<ByteString> batchOfSize(int size) {
var batch = new ArrayList<ByteString>();
for (int i = 0; i < size; i++) {
batch.add(metadata("memo" + i));
}
return batch;
}
private ByteString metadataOfLength(int length) {
return ByteString.copyFrom(genRandomBytes(length));
}
private ByteString metadata(String contents) {
return ByteString.copyFromUtf8(contents);
}
private HapiApiSpec mintHappyPath() {
return defaultHapiSpec("UniqueTokenHappyPath")
.given(
newKeyNamed(SUPPLY_KEY),
cryptoCreate(TOKEN_TREASURY),
tokenCreate(NFT)
.tokenType(NON_FUNGIBLE_UNIQUE)
.supplyKey(SUPPLY_KEY)
.supplyType(TokenSupplyType.INFINITE)
.initialSupply(0)
.supplyKey(SUPPLY_KEY)
.treasury(TOKEN_TREASURY)
).when(
mintToken(NFT,
List.of(metadata("memo"), metadata("memo1"))).via("mintTxn")
).then(
getReceipt("mintTxn").logged(),
getTokenNftInfo(NFT, 1)
.hasSerialNum(1)
.hasMetadata(metadata("memo"))
.hasTokenID(NFT)
.hasAccountID(TOKEN_TREASURY)
.hasValidCreationTime(),
getTokenNftInfo(NFT, 2)
.hasSerialNum(2)
.hasMetadata(metadata("memo1"))
.hasTokenID(NFT)
.hasAccountID(TOKEN_TREASURY)
.hasValidCreationTime(),
getTokenNftInfo(NFT, 3)
.hasCostAnswerPrecheck(INVALID_NFT_ID),
getTokenNftInfos(NFT, 0, 1)
.hasNfts(
newTokenNftInfo(NFT, 1, TOKEN_TREASURY, metadata("memo"))
)
.logged(),
getTokenNftInfos(NFT, 1, 2)
.hasNfts(
newTokenNftInfo(NFT, 2, TOKEN_TREASURY, metadata("memo1"))
)
.logged(),
getTokenNftInfos(NFT, 0, 2)
.hasNfts(
newTokenNftInfo(NFT, 1, TOKEN_TREASURY, metadata("memo")),
newTokenNftInfo(NFT, 2, TOKEN_TREASURY, metadata("memo1"))
)
.logged(),
getAccountBalance(TOKEN_TREASURY)
.hasTokenBalance(NFT, 2),
getTokenInfo(NFT)
.hasTreasury(TOKEN_TREASURY)
.hasTotalSupply(2),
getAccountInfo(TOKEN_TREASURY)
.hasToken(relationshipWith(NFT)).hasOwnedNfts(2),
getAccountNftInfos(TOKEN_TREASURY, 0, 2)
.hasNfts(
newTokenNftInfo(NFT, 1, TOKEN_TREASURY, metadata("memo")),
newTokenNftInfo(NFT, 2, TOKEN_TREASURY, metadata("memo1"))
)
.logged()
);
}
private HapiApiSpec tokenMintWorksWhenAccountsAreFrozenByDefault() {
return defaultHapiSpec("happyPathWithFrozenToken")
.given(
newKeyNamed(SUPPLY_KEY),
newKeyNamed("tokenFreezeKey"),
cryptoCreate(TOKEN_TREASURY).balance(0L),
tokenCreate(NFT)
.tokenType(NON_FUNGIBLE_UNIQUE)
.supplyKey(SUPPLY_KEY)
.freezeKey("tokenFreezeKey")
.freezeDefault(true)
.initialSupply(0)
.treasury(TOKEN_TREASURY)
).when(
mintToken(NFT, List.of(metadata("memo")))
.via("mintTxn")
).then(
getTokenNftInfo(NFT, 1)
.hasTokenID(NFT)
.hasAccountID(TOKEN_TREASURY)
.hasMetadata(metadata("memo"))
.hasValidCreationTime(),
getTokenNftInfos(NFT, 0, 1)
.hasNfts(
newTokenNftInfo(NFT, 1, TOKEN_TREASURY, metadata("memo"))
)
.logged(),
getAccountInfo(TOKEN_TREASURY).hasOwnedNfts(1),
getAccountNftInfos(TOKEN_TREASURY, 0, 1)
.hasNfts(
newTokenNftInfo(NFT, 1, TOKEN_TREASURY, metadata("memo"))
)
.logged()
);
}
private HapiApiSpec mintFailsWithDeletedToken() {
return defaultHapiSpec("failsWithDeletedToken").given(
newKeyNamed(SUPPLY_KEY),
newKeyNamed("adminKey"),
cryptoCreate(TOKEN_TREASURY),
tokenCreate(NFT)
.supplyKey(SUPPLY_KEY)
.adminKey("adminKey")
.treasury(TOKEN_TREASURY)
).when(
tokenDelete(NFT)
).then(
mintToken(NFT, List.of(metadata("memo")))
.via("mintTxn")
.hasKnownStatus(TOKEN_WAS_DELETED),
getTokenNftInfo(NFT, 1)
.hasCostAnswerPrecheck(INVALID_NFT_ID),
getTokenInfo(NFT)
.isDeleted()
);
}
private HapiApiSpec failsGetTokenNftInfoWithNoNft() {
return defaultHapiSpec("failsGetTokenNftInfoWithNoNft")
.given(
newKeyNamed(SUPPLY_KEY),
cryptoCreate(TOKEN_TREASURY)
)
.when(
tokenCreate(NFT)
.tokenType(NON_FUNGIBLE_UNIQUE)
.supplyType(TokenSupplyType.INFINITE)
.supplyKey(SUPPLY_KEY)
.initialSupply(0)
.treasury(TOKEN_TREASURY),
mintToken(NFT, List.of(metadata("memo"))).via("mintTxn")
)
.then(
getTokenNftInfo(NFT, 0)
.hasCostAnswerPrecheck(INVALID_TOKEN_NFT_SERIAL_NUMBER),
getTokenNftInfo(NFT, -1)
.hasCostAnswerPrecheck(INVALID_TOKEN_NFT_SERIAL_NUMBER),
getTokenNftInfo(NFT, 2)
.hasCostAnswerPrecheck(INVALID_NFT_ID)
);
}
private HapiApiSpec getTokenNftInfoWorks() {
return defaultHapiSpec("getTokenNftInfoWorks")
.given(
newKeyNamed(SUPPLY_KEY),
cryptoCreate(TOKEN_TREASURY)
).when(
tokenCreate(NFT)
.tokenType(NON_FUNGIBLE_UNIQUE)
.supplyType(TokenSupplyType.INFINITE)
.supplyKey(SUPPLY_KEY)
.initialSupply(0)
.treasury(TOKEN_TREASURY),
mintToken(NFT, List.of(metadata("memo")))
).then(
getTokenNftInfo(NFT, 0)
.hasCostAnswerPrecheck(INVALID_TOKEN_NFT_SERIAL_NUMBER),
getTokenNftInfo(NFT, -1)
.hasCostAnswerPrecheck(INVALID_TOKEN_NFT_SERIAL_NUMBER),
getTokenNftInfo(NFT, 2)
.hasCostAnswerPrecheck(INVALID_NFT_ID),
getTokenNftInfo(NFT, 1)
.hasTokenID(NFT)
.hasAccountID(TOKEN_TREASURY)
.hasMetadata(metadata("memo"))
.hasSerialNum(1)
.hasValidCreationTime()
);
}
private HapiApiSpec mintWorksWithRepeatedMetadata() {
return defaultHapiSpec("happyPathWithRepeatedMetadata")
.given(
newKeyNamed(SUPPLY_KEY),
cryptoCreate(TOKEN_TREASURY),
tokenCreate(NFT)
.tokenType(NON_FUNGIBLE_UNIQUE)
.supplyType(TokenSupplyType.INFINITE)
.supplyKey(SUPPLY_KEY)
.initialSupply(0)
.treasury(TOKEN_TREASURY)
).when(
mintToken(NFT, List.of(metadata("memo"), metadata("memo")))
.via("mintTxn")
).then(
getTokenNftInfo(NFT, 1)
.hasSerialNum(1)
.hasMetadata(metadata("memo"))
.hasAccountID(TOKEN_TREASURY)
.hasTokenID(NFT)
.hasValidCreationTime(),
getTokenNftInfo(NFT, 2)
.hasSerialNum(2)
.hasMetadata(metadata("memo"))
.hasAccountID(TOKEN_TREASURY)
.hasTokenID(NFT)
.hasValidCreationTime(),
getTokenNftInfos(NFT, 0, 2)
.hasNfts(
newTokenNftInfo(NFT, 1, TOKEN_TREASURY, metadata("memo")),
newTokenNftInfo(NFT, 2, TOKEN_TREASURY, metadata("memo"))
)
.logged(),
getAccountInfo(TOKEN_TREASURY).hasOwnedNfts(2),
getAccountNftInfos(TOKEN_TREASURY, 0, 2)
.hasNfts(
newTokenNftInfo(NFT, 1, TOKEN_TREASURY, metadata("memo")),
newTokenNftInfo(NFT, 2, TOKEN_TREASURY, metadata("memo"))
)
.logged()
);
}
private HapiApiSpec wipeHappyPath() {
return defaultHapiSpec("wipeHappyEnd")
.given(
newKeyNamed(SUPPLY_KEY),
newKeyNamed("wipeKey"),
newKeyNamed("treasuryKey"),
newKeyNamed("accKey"),
cryptoCreate(TOKEN_TREASURY).key("treasuryKey"),
cryptoCreate("account").key("accKey"),
tokenCreate(NFT)
.tokenType(NON_FUNGIBLE_UNIQUE)
.supplyType(TokenSupplyType.INFINITE)
.supplyKey(SUPPLY_KEY)
.initialSupply(0)
.treasury(TOKEN_TREASURY)
.wipeKey("wipeKey"),
tokenAssociate("account", NFT),
mintToken(NFT, List.of(ByteString.copyFromUtf8("memo"), ByteString.copyFromUtf8("memo2"))),
cryptoTransfer(
movingUnique(2L, NFT).between(TOKEN_TREASURY, "account")
)
)
.when(
wipeTokenAccount(NFT, "account", List.of(2L)).via("wipeTxn")
)
.then(
getAccountInfo("account").hasOwnedNfts(0),
getAccountInfo(TOKEN_TREASURY).hasOwnedNfts(1),
getTokenInfo(NFT).hasTotalSupply(1),
getTokenNftInfo(NFT, 2).hasCostAnswerPrecheck(INVALID_NFT_ID),
getTokenNftInfo(NFT, 1).hasSerialNum(1),
wipeTokenAccount(NFT, "account", List.of(1L)).hasKnownStatus(FAIL_INVALID)
);
}
private HapiApiSpec wipeRespectsConstraints() {
return defaultHapiSpec("wipeRespectsConstraints").given(
newKeyNamed(SUPPLY_KEY),
newKeyNamed("wipeKey"),
cryptoCreate(TOKEN_TREASURY),
cryptoCreate("account"),
tokenCreate(NFT)
.tokenType(NON_FUNGIBLE_UNIQUE)
.supplyType(TokenSupplyType.INFINITE)
.supplyKey(SUPPLY_KEY)
.initialSupply(0)
.treasury(TOKEN_TREASURY)
.wipeKey("wipeKey"),
tokenAssociate("account", NFT),
mintToken(NFT, List.of(
metadata("memo"),
metadata("memo2")))
.via("mintTxn"),
cryptoTransfer(
movingUnique(1, NFT).between(TOKEN_TREASURY, "account"),
movingUnique(2, NFT).between(TOKEN_TREASURY, "account")
)
).when(
wipeTokenAccount(NFT, "account", LongStream.range(0, 1000).boxed().collect(Collectors.toList()))
.hasPrecheck(BATCH_SIZE_LIMIT_EXCEEDED),
getAccountNftInfos("account", 0, 2).hasNfts(
newTokenNftInfo(NFT, 1, "account", metadata("memo")),
newTokenNftInfo(NFT, 1, "account", metadata("memo2"))
)
).then();
}
private HapiApiSpec commonWipeFailsWhenInvokedOnUniqueToken() {
return defaultHapiSpec("commonWipeFailsWhenInvokedOnUniqueToken")
.given(
newKeyNamed(SUPPLY_KEY),
newKeyNamed("wipeKey"),
cryptoCreate(TOKEN_TREASURY),
cryptoCreate("account"),
tokenCreate(NFT)
.tokenType(NON_FUNGIBLE_UNIQUE)
.supplyType(TokenSupplyType.INFINITE)
.supplyKey(SUPPLY_KEY)
.initialSupply(0)
.treasury(TOKEN_TREASURY)
.wipeKey("wipeKey"),
tokenAssociate("account", NFT),
mintToken(NFT, List.of(metadata("memo"))),
cryptoTransfer(
movingUnique(1, NFT).between(TOKEN_TREASURY, "account")
)
).when()
.then(
wipeTokenAccount(NFT, "account", 1L)
.hasKnownStatus(FAIL_INVALID)
.via("wipeTxn"),
// no new totalSupply
getTokenInfo(NFT).hasTotalSupply(1),
// no tx record
getTxnRecord("wipeTxn").showsNoTransfers(),
//verify balance not decreased
getAccountInfo("account").hasOwnedNfts(1),
getAccountBalance("account").hasTokenBalance(NFT, 1)
);
}
private HapiApiSpec uniqueWipeFailsWhenInvokedOnFungibleToken() { // invokes unique wipe on fungible tokens
return defaultHapiSpec("uniqueWipeFailsWhenInvokedOnFungibleToken")
.given(
newKeyNamed("wipeKey"),
cryptoCreate(TOKEN_TREASURY),
cryptoCreate("account"),
tokenCreate(A_TOKEN)
.tokenType(TokenType.FUNGIBLE_COMMON)
.initialSupply(10)
.treasury(TOKEN_TREASURY)
.wipeKey("wipeKey"),
tokenAssociate("account", A_TOKEN),
cryptoTransfer(
TokenMovement.moving(5, A_TOKEN).between(TOKEN_TREASURY, "account")
)
)
.when(
wipeTokenAccount(A_TOKEN, "account", List.of(1L, 2L))
.hasKnownStatus(INVALID_WIPING_AMOUNT)
.via("wipeTx")
)
.then(
getTokenInfo(A_TOKEN).hasTotalSupply(10),
getTxnRecord("wipeTx").showsNoTransfers(),
getAccountBalance("account").hasTokenBalance(A_TOKEN, 5)
);
}
private HapiApiSpec wipeFailsWithInvalidSerialNumber() {
return defaultHapiSpec("wipeFailsWithInvalidSerialNumber")
.given(
newKeyNamed(SUPPLY_KEY),
newKeyNamed("wipeKey"),
cryptoCreate(TOKEN_TREASURY),
cryptoCreate("account"),
tokenCreate(NFT)
.tokenType(NON_FUNGIBLE_UNIQUE)
.supplyType(TokenSupplyType.INFINITE)
.supplyKey(SUPPLY_KEY)
.initialSupply(0)
.treasury(TOKEN_TREASURY)
.wipeKey("wipeKey"),
tokenAssociate("account", NFT),
mintToken(NFT, List.of(
metadata("memo"),
metadata("memo")))
.via("mintTxn")
).when().then(
wipeTokenAccount(NFT, "account", List.of(-5L, -6L)).hasPrecheck(INVALID_NFT_ID)
);
}
private HapiApiSpec uniqueTokenMintReceiptCheck() {
return defaultHapiSpec("UniqueTokenMintReceiptCheck")
.given(
cryptoCreate(TOKEN_TREASURY),
cryptoCreate(FIRST_USER),
newKeyNamed("supplyKey"),
tokenCreate(A_TOKEN)
.tokenType(TokenType.NON_FUNGIBLE_UNIQUE)
.initialSupply(0)
.supplyKey("supplyKey")
.treasury(TOKEN_TREASURY)
)
.when(
mintToken(A_TOKEN, List.of(metadata("memo"))).via("mintTransferTxn")
)
.then(
UtilVerbs.withOpContext((spec, opLog) -> {
var mintNft = getTxnRecord("mintTransferTxn");
allRunFor(spec, mintNft);
var tokenTransferLists = mintNft.getResponseRecord().getTokenTransferListsList();
Assert.assertEquals(1, tokenTransferLists.size());
tokenTransferLists.stream().forEach(tokenTransferList -> {
Assert.assertEquals(1, tokenTransferList.getNftTransfersList().size());
tokenTransferList.getNftTransfersList().stream().forEach(nftTransfers -> {
Assert.assertEquals(AccountID.getDefaultInstance(),
nftTransfers.getSenderAccountID());
Assert.assertEquals(TxnUtils.asId(TOKEN_TREASURY, spec),
nftTransfers.getReceiverAccountID());
Assert.assertEquals(1L, nftTransfers.getSerialNumber());
});
});
}),
getTxnRecord("mintTransferTxn").logged(),
getReceipt("mintTransferTxn").logged()
);
}
private HapiApiSpec associatesTokenNftInfosAsExpected() {
return defaultHapiSpec("AssociatesTokenNftInfosAsExpected")
.given(
newKeyNamed(SUPPLY_KEY),
cryptoCreate(TOKEN_TREASURY),
tokenCreate(NFT)
.initialSupply(0)
.tokenType(TokenType.NON_FUNGIBLE_UNIQUE)
.supplyType(TokenSupplyType.INFINITE)
.supplyKey(SUPPLY_KEY)
.treasury(TOKEN_TREASURY)
).when(
mintToken(NFT, List.of(
metadata("some metadata"),
metadata("some metadata2"),
metadata("some metadata3")
))
).then(
getTokenNftInfos(NFT, 0, 3)
.hasNfts(
newTokenNftInfo(NFT, 1, TOKEN_TREASURY, metadata("some metadata")),
newTokenNftInfo(NFT, 2, TOKEN_TREASURY, metadata("some metadata2")),
newTokenNftInfo(NFT, 3, TOKEN_TREASURY, metadata("some metadata3"))
)
.logged()
);
}
private HapiApiSpec validateTokenNftInfosOutOfRange() {
return defaultHapiSpec("ValidateTokenNftInfosOutOfRange")
.given(
newKeyNamed(SUPPLY_KEY),
cryptoCreate(TOKEN_TREASURY),
tokenCreate(NFT)
.initialSupply(0)
.tokenType(TokenType.NON_FUNGIBLE_UNIQUE)
.supplyType(TokenSupplyType.INFINITE)
.supplyKey(SUPPLY_KEY)
.treasury(TOKEN_TREASURY)
).when(
mintToken(NFT, List.of(
metadata("some metadata"),
metadata("some metadata2"),
metadata("some metadata3")
))
).then(
getTokenNftInfos(NFT, 0, 6)
.hasCostAnswerPrecheck(INVALID_QUERY_RANGE)
);
}
private HapiApiSpec failsWithTokenWithoutNfts() {
return defaultHapiSpec("FailsWithTokenWithoutNfts")
.given(
newKeyNamed(SUPPLY_KEY),
cryptoCreate(TOKEN_TREASURY),
tokenCreate(NFT)
.initialSupply(0)
.tokenType(TokenType.NON_FUNGIBLE_UNIQUE)
.supplyType(TokenSupplyType.INFINITE)
.supplyKey(SUPPLY_KEY)
.treasury(TOKEN_TREASURY)
).when()
.then(
getTokenNftInfos(NFT, 0, 2)
.hasCostAnswerPrecheck(INVALID_QUERY_RANGE)
);
}
private HapiApiSpec failsWithTokenNftsInvalidQueryBoundaries() {
return defaultHapiSpec("FailsWithTokenNftsInvalidQueryBoundaries")
.given(
newKeyNamed(SUPPLY_KEY),
cryptoCreate(TOKEN_TREASURY),
tokenCreate(NFT)
.initialSupply(0)
.tokenType(TokenType.NON_FUNGIBLE_UNIQUE)
.supplyType(TokenSupplyType.INFINITE)
.supplyKey(SUPPLY_KEY)
.treasury(TOKEN_TREASURY)
).when().then(
getTokenNftInfos(NFT, 2, 0)
.hasCostAnswerPrecheck(INVALID_QUERY_RANGE),
getTokenNftInfos(NFT, 0, 100000000)
.hasCostAnswerPrecheck(INVALID_QUERY_RANGE)
);
}
private HapiApiSpec failsWithDeletedTokenNft() {
return defaultHapiSpec("FailsWithDeletedTokenNft")
.given(
newKeyNamed(SUPPLY_KEY),
newKeyNamed("nftAdmin"),
cryptoCreate(TOKEN_TREASURY),
tokenCreate(NFT)
.initialSupply(0)
.tokenType(TokenType.NON_FUNGIBLE_UNIQUE)
.supplyType(TokenSupplyType.INFINITE)
.supplyKey(SUPPLY_KEY)
.adminKey("nftAdmin")
.treasury(TOKEN_TREASURY)
).when(
tokenDelete(NFT)
)
.then(
getTokenNftInfos(NFT, 0, 2)
.hasCostAnswerPrecheck(TOKEN_WAS_DELETED)
);
}
public HapiApiSpec failsWithFungibleTokenGetNftInfos() {
return defaultHapiSpec("FailsWithFungibleTokenGetNftInfos")
.given(
cryptoCreate(TOKEN_TREASURY).balance(0L)
).when(
tokenCreate(A_TOKEN)
.initialSupply(1_000)
.treasury(TOKEN_TREASURY)
).then(
getTokenNftInfos(A_TOKEN, 0, 2)
.hasCostAnswerPrecheck(NOT_SUPPORTED)
);
}
protected Logger getResultsLogger() {
return log;
}
private byte[] genRandomBytes(int numBytes) {
byte[] contents = new byte[numBytes];
(new Random()).nextBytes(contents);
return contents;
}
} |
/*
* BDSup2Sub++ (C) 2012 <NAME>.
* Based on code from BDSup2Sub by Copyright 2009 <NAME> (0xdeadbeef)
* and Copyright 2012 <NAME> (mjuhasz)
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "suphd.h"
#include "subtitleprocessor.h"
#include "subpicturehd.h"
#include "Tools/filebuffer.h"
#include "Tools/bitstream.h"
#include "Tools/timeutil.h"
#include "bitmap.h"
#include "palette.h"
#include <QImage>
SupHD::SupHD(QString fileName, SubtitleProcessor *subtitleProcessor) :
supFileName(fileName)
{
this->subtitleProcessor = subtitleProcessor;
}
SupHD::~SupHD()
{
if (!fileBuffer.isNull())
{
fileBuffer.reset();
}
}
QImage SupHD::image()
{
return _bitmap.image(_palette);
}
QImage SupHD::image(Bitmap &bitmap)
{
return bitmap.image(_palette);
}
void SupHD::decode(int index)
{
if (index < subPictures.size())
{
decode(subPictures[index]);
}
else
{
throw QString("Index: %1 out of bounds.\n").arg(QString::number(index));
}
}
int SupHD::numFrames()
{
return subPictures.size();
}
qint64 SupHD::endTime(int index)
{
return subPictures[index].endTime();
}
qint64 SupHD::startTime(int index)
{
return subPictures[index].startTime();
}
qint64 SupHD::startOffset(int index)
{
return subPictures[index].imageBufferOffsetEven();
}
SubPicture *SupHD::subPicture(int index)
{
return &subPictures[index];
}
void SupHD::readAllSupFrames()
{
fileBuffer.reset(new FileBuffer(supFileName));
int index = 0;
int bufsize = (int)fileBuffer->getSize();
SubPictureHD pic;
subPictures.clear();
try
{
while (index < bufsize)
{
if (subtitleProcessor->isCancelled())
{
throw QString("Cancelled by user!");
}
emit currentProgressChanged(index);
if (fileBuffer->getWord(index) != 0x5350)
{
throw QString("ID 'SP' missing at index ").arg(QString::number(index, 16), 8, QChar('0'));
}
int masterIndex = index + 10; //end of header
pic = SubPictureHD();
// hard code size since it's not part of the format???
pic.setScreenWidth(1920);
pic.setScreenHeight(1080);
subtitleProcessor->printX(QString("#%1\n").arg(QString::number(subPictures.size() + 1)));;
pic.setStartTime(fileBuffer->getDWordLE(index += 2)); // read PTS
int packetSize = fileBuffer->getDWord(index += 10);
// offset to command buffer
int ofsCmd = fileBuffer->getDWord(index += 4) + masterIndex;
pic.setImageBufferSize(ofsCmd - (index + 4));
index = ofsCmd;
int dcsq = fileBuffer->getWord(index);
pic.setStartTime(pic.startTime() + (dcsq * 1024));
subtitleProcessor->printX(QString("DCSQ start ofs: %1 (%2)\n")
.arg(QString::number(index, 16), 8, QChar('0'))
.arg(TimeUtil::ptsToTimeStr(pic.startTime())));
index+=2; // 2 bytes: dcsq
int nextIndex = fileBuffer->getDWord(index) + masterIndex; // offset to next dcsq
index += 5; // 4 bytes: offset, 1 byte: start
int cmd = 0;
bool stopDisplay = false;
bool stopCommand = false;
int alphaSum = 0;
int minAlphaSum = 256 * 256; // 256 fully transparent entries
while (!stopDisplay)
{
cmd = fileBuffer->getByte(index++);
switch (cmd)
{
case 0x01:
{
subtitleProcessor->printX(QString("DCSQ start ofs: %1 (%2)\n")
.arg(QString::number(index, 16), 8, QChar('0'))
.arg(TimeUtil::ptsToTimeStr(pic.startTime() + (dcsq * 1024))));
subtitleProcessor->printWarning("DCSQ start ignored due to missing DCSQ stop\n");
} break;
case 0x02:
{
stopDisplay = true;
pic.setEndTime(pic.startTime() + (dcsq * 1024));
subtitleProcessor->printX(QString("DCSQ stop ofs: %1 (%2)\n")
.arg(QString::number(index, 16), 8, QChar('0'))
.arg(TimeUtil::ptsToTimeStr(pic.endTime())));
} break;
case 0x83: // palette
{
subtitleProcessor->print(QString("Palette info ofs: %1\n").arg(QString::number(index, 16), 8, QChar('0')));
pic.setPaletteOffset(index);
index += 0x300;
} break;
case 0x84: // alpha
{
subtitleProcessor->print(QString("Alpha info ofs: %1\n").arg(QString::number(index, 16), 8, QChar('0'))); alphaSum = 0;
for (int i = index; i < index + 0x100; ++i)
{
alphaSum += fileBuffer->getByte(i);
}
if (alphaSum < minAlphaSum)
{
pic.setAlphaOffset(index);
minAlphaSum = alphaSum;
}
else
{
subtitleProcessor->printWarning(QString("Found faded alpha buffer -> alpha buffer skipped\n"));
}
index += 0x100;
} break;
case 0x85: // area
{
int x = (fileBuffer->getByte(index) << 4) | (fileBuffer->getByte(index + 1) >> 4);
int imageWidth = (((fileBuffer->getByte(index + 1) &0xf) << 8) | (fileBuffer->getByte(index + 2)));
int y = (fileBuffer->getByte(index + 3) <<4 ) | (fileBuffer->getByte(index + 4) >> 4);
int imageHeight = (((fileBuffer->getByte(index + 4) &0xf) << 8) | (fileBuffer->getByte(index + 5)));
QMap<int, QRect> imageRects;
QRect rect = QRect(x, y, (imageWidth - pic.x()) + 1, (imageHeight - pic.y()) + 1);
imageRects[0] = rect;
pic.setWindowSizes(imageRects);
pic.setNumCompObjects(imageRects.size());
pic.setImageSizes(imageRects);
pic.setNumberOfWindows(imageRects.size());
pic.objectIDs().push_back(0);
subtitleProcessor->print(QString("Area info ofs: %1 (%2, %3) - (%4, %5)\n")
.arg(QString::number(index, 16), 8, QChar('0'))
.arg(QString::number(pic.x()))
.arg(QString::number(pic.y()))
.arg(QString::number(pic.x() + pic.imageWidth()))
.arg(QString::number(pic.y() + pic.imageHeight())));
index += 6;
} break;
case 0x86: // even/odd offsets
{
pic.setImageBufferOffsetEven(fileBuffer->getDWord(index) + masterIndex);
pic.setImageBufferOffsetOdd(fileBuffer->getDWord(index + 4) + masterIndex);
subtitleProcessor->print(QString("RLE buffers ofs: %1 (even: %2, odd: %3)\n")
.arg(QString::number(index, 16), 8, QChar('0'))
.arg(QString::number(pic.imageBufferOffsetEven(), 16), 8, QChar('0'))
.arg(QString::number(pic.imageBufferOffsetOdd(), 16), 8, QChar('0')));
index += 8;
} break;
case 0xff:
{
if (stopCommand)
{
subtitleProcessor->printWarning(QString("DCSQ stop missing.\n"));
for (++index; index < bufsize; ++index)
{
if (fileBuffer->getByte(index++) != 0xff)
{
index--;
break;
}
}
stopDisplay = true;
} else {
index = nextIndex;
// add to display time
int d = fileBuffer->getWord(index);
dcsq = d;
nextIndex = fileBuffer->getDWord(index + 2) + masterIndex;
stopCommand = (index == nextIndex);
subtitleProcessor->print(QString("DCSQ ofs: %1 (%2ms), next DCSQ at ofs: %3\n")
.arg(QString::number(index, 16), 8, QChar('0'))
.arg(QString::number((d * 1024) / 90))
.arg(QString::number(nextIndex, 16), 8, QChar('0')));
index += 6;
}
} break;
default:
{
throw QString("Unexpected command %1 at index %2").arg(cmd).arg(QString::number(index, 16), 8, QChar('0'));
}
}
}
index = masterIndex + packetSize;
subPictures.push_back(pic);
}
}
catch (QString &e)
{
if (subPictures.size() == 0)
{
throw e;
}
subtitleProcessor->printError(QString(e + "\n"));
subtitleProcessor->print(QString("Probably not all caption imported due to error.\n"));
}
emit currentProgressChanged(bufsize);
}
void SupHD::decode(SubPictureHD &subPicture)
{
_palette = decodePalette(subPicture);
_bitmap = decodeImage(subPicture, _palette.transparentIndex());
_primaryColorIndex = _bitmap.primaryColorIndex(_palette, subtitleProcessor->getAlphaThreshold());
}
void SupHD::decodeLine(QImage &trg, int trgOfs, int width, int maxPixels, BitStream* src)
{
int x = 0;
int pixelsLeft = 0;
int sumPixels = 0;
bool lf = false;
while (src->bitsLeft() > 0 && sumPixels < maxPixels)
{
int rleType = src->readBits(1);
int colorType = src->readBits(1);
int color;
int numPixels;
if (colorType == 1)
{
color = src->readBits(8);
}
else
{
color = src->readBits(2); // Colors between 0 and 3 are stored in two bits
}
if (rleType == 1)
{
int rleSize = src->readBits(1);
if (rleSize == 1)
{
numPixels = src->readBits(7) + 9;
if (numPixels == 9)
{
numPixels = width - x;
}
}
else
{
numPixels = src->readBits(3) + 2;
}
}
else
{
numPixels = 1;
}
if ((x + numPixels) == width)
{
src->syncToByte();
lf = true;
}
sumPixels += numPixels;
// write pixels to target
if ((x + numPixels) > width)
{
pixelsLeft = (x + numPixels) - width;
numPixels = width - x;
lf = true;
}
else
{
pixelsLeft = 0;
}
uchar* pixels = trg.bits();
for (int i = 0; i < numPixels; ++i)
{
pixels[trgOfs + x + i] = (uchar)color;
}
if (lf == true)
{
trgOfs += ((x + numPixels + (trg.bytesPerLine() - (x + numPixels)))
+ (width + (trg.bytesPerLine() - width))); // skip odd/even line
x = pixelsLeft;
lf = false;
}
else
{
x += numPixels;
}
// copy remaining pixels to new line
for (int i = 0; i < pixelsLeft; ++i)
{
pixels[trgOfs + i] = (uchar)color;
}
}
}
Palette SupHD::decodePalette(SubPictureHD &subPicture)
{
int ofs = subPicture.paletteOffset();
int alphaOfs = subPicture.alphaOffset();
Palette palette(256);
for (int i = 0; i < palette.size(); ++i)
{
// each palette entry consists of 3 bytes
int y = fileBuffer->getByte(ofs++);
int cr, cb;
if (subtitleProcessor->getSwapCrCb())
{
cb = fileBuffer->getByte(ofs++);
cr = fileBuffer->getByte(ofs++);
}
else
{
cr = fileBuffer->getByte(ofs++);
cb = fileBuffer->getByte(ofs++);
}
// each alpha entry consists of 1 byte
int alpha = 0xff - fileBuffer->getByte(alphaOfs++);
if (alpha < subtitleProcessor->getAlphaCrop()) // to not mess with scaling algorithms, make transparent color black
{
palette.setRGB(i, qRgb(0, 0, 0));
}
else
{
palette.setYCbCr(i, y, cb, cr);
}
palette.setAlpha(i, alpha);
}
return palette;
}
Bitmap SupHD::decodeImage(SubPictureHD &subPicture, int transparentIndex)
{
int w = subPicture.imageWidth();
int h = subPicture.imageHeight();
int warnings = 0;
if (w > subPicture.screenWidth() || h > subPicture.screenHeight())
{
throw QString("Subpicture too large: %1x%2 at offset %3")
.arg(QString::number(w))
.arg(QString::number(h))
.arg(QString::number(subPicture.imageBufferOffsetEven(), 16), 8, QChar('0'));
}
Bitmap bm(w, h, transparentIndex);
int sizeEven = subPicture.imageBufferOffsetOdd() - subPicture.imageBufferOffsetEven();
int sizeOdd = (subPicture.imageBufferSize() + subPicture.imageBufferOffsetEven()) - subPicture.imageBufferOffsetOdd();
if (sizeEven <= 0 || sizeOdd <= 0)
{
throw QString("Corrupt buffer offset information");
}
QVector<uchar> evenBuf = QVector<uchar>(sizeEven);
QVector<uchar> oddBuf = QVector<uchar>(sizeOdd);
for (int i = 0; i < evenBuf.size(); i++)
{
evenBuf.replace(i, (uchar)fileBuffer->getByte(subPicture.imageBufferOffsetEven() + i));
}
for (int i = 0; i < oddBuf.size(); ++i)
{
oddBuf.replace(i, (uchar)fileBuffer->getByte(subPicture.imageBufferOffsetOdd() + i));
}
// decode even lines
BitStream even = BitStream(evenBuf);
decodeLine(bm.image(), 0, w, w * ((h / 2) + (h & 1)), &even);
// decode odd lines
BitStream odd = BitStream(oddBuf);
decodeLine(bm.image(), w + (bm.image().bytesPerLine() - w), w, (h / 2) * w, &odd);
if (warnings > 0)
{
subtitleProcessor->printWarning(QString("problems during RLE decoding of picture at offset %1\n")
.arg(QString::number(subPicture.imageBufferOffsetEven(), 16), 8, QChar('0')));
}
return bm;
}
|
<filename>app/models/eligibility_determination.rb
class EligibilityDetermination
include Mongoid::Document
include Mongoid::Timestamps
embedded_in :tax_household
include HasFamilyMembers
PDC_STATUSES = %w{active approved submitted open suspended pending_closure planned canceled_planned
delayed_processing_pending canceled appeal_submitted rejected in_progress completed plan_submitted}
field :e_pdc_id, type: String
field :benchmark_plan_id, type: Moped::BSON::ObjectId
# Premium tax credit assistance eligibility.
# Available to household with income between 100% and 400% of the Federal Poverty Level (FPL)
field :max_aptc_in_cents, type: Integer, default: 0
# Cost-sharing reduction assistance eligibility for co-pays, etc.
# Available to households with income between 100-250% of FPL and enrolled in Silver plan.
field :csr_percent_as_integer, type: Integer, default: 0 #values in DC: 0, 73, 87, 94
field :determination_date, type: DateTime
field :household_state, type: String
validates_presence_of :determination_date, :max_aptc_in_cents, :csr_percent_as_integer
validates :household_state, presence: true,
inclusion: { in: PDC_STATUSES, message: "%{value} is not a valid PDC Status" }
def family
return nil unless tax_household
tax_household.family
end
def benchmark_plan=(benchmark_plan_instance)
return unless benchmark_plan_instance.is_a? Plan
self.benchmark_plan_id = benchmark_plan_instance._id
end
def benchmark_plan
Plan.find(self.benchmark_plan_id) unless self.benchmark_plan_id.blank?
end
def max_aptc_in_dollars=(dollars)
self.max_aptc_in_cents = Rational(dollars) * Rational(100)
end
def max_aptc_in_dollars
(Rational(max_aptc_in_cents) / Rational(100)).to_f if max_aptc_in_cents
end
def csr_percent=(value)
value ||= 0 #to handle value = nil
raise "value out of range" if (value < 0 || value > 1)
self.csr_percent_as_integer = Rational(value) * Rational(100)
end
def csr_percent
(Rational(csr_percent_as_integer) / Rational(100)).to_f
end
end
|
const messages = {
"app": {
"name": "企鹅物流数据统计",
"name_line1": "企鹅物流数据统计",
"name_line2": ""
},
"server": {
"name": "服务器",
"switch": "服务器切换",
"selected": "已选择",
"servers": {
"CN": "国服",
"US": "美服",
"JP": "日服",
"KR": "韩服"
}
},
"menu": {
"_beta": "公测",
"home": "首页",
"report": {
"_name": "掉落汇报",
"stage": "按章节",
"recognition": "截图识别"
},
"search": "全局搜索",
"stats": {
"_name": "素材掉率",
"stage": "按作战",
"item": "按素材",
"advanced": "高级查询"
},
"about": {
"_name": "关于本站",
"members": "团队成员",
"contribute": "参与开发",
"changelog": "更新记录",
"contact": "联系我们",
"donate": "捐助",
"links": "友情链接",
"bulletin": "公告",
"credits": "内容来源"
},
"siteStats": "全站数据一览",
"planner": "刷图规划器",
"v1": "访问旧版",
"refreshData": "刷新数据",
"languages": "语言切换",
"settings": {
"name": "设置",
"themeStyles": {
"name": "切换主题",
"disabled": "(已禁用:活跃的特殊主题)",
"default": "默认主题",
"miku2021": "初音未来 2021 生日特别主题"
},
"appearances": {
"name": "切换外观",
"system": "跟随系统设置",
"dark": "总是使用暗色",
"light": "总是使用亮色"
}
},
"overline": {
"planner": "ArkPlanner"
}
},
"meta": {
"details": "详细信息",
"loading": "正在加载...",
"notfound": "???",
"footer": {
"copyright": {
"title": "许可协议",
"content": "素材掉落统计数据由企鹅物流统计,采用知识共享 署名-非商业性使用 4.0 国际 许可协议进行许可。转载、公开或以任何形式复制、发行、再传播本站任何内容时,必须注明从企鹅物流数据统计转载,并提供版权标识、许可协议标识、免责标识和作品链接;且未经许可,不得将本站内容或由其衍生作品用于商业目的。"
},
"credit": "企鹅物流数据统计 | {date}"
},
"separator": "、",
"quotation": {
"start": "“",
"end": "”"
},
"boolean": {
"true": "是",
"false": "否"
},
"hasNorNot": {
"true": "有",
"false": "无"
},
"dialog": {
"cancel": "取消",
"confirm": "确认",
"submit": "提交",
"save": "保存",
"close": "关闭"
},
"time": {
"minute": "{m}分 ",
"second": "{s}秒"
},
"copyWarning": "\n\n以上数据来自企鹅物流数据统计({site})"
},
"stats": {
"headers": {
"pattern": "组合",
"stage": "作战",
"apCost": "理智",
"item": "物品",
"itemDrops": "掉落情况合计",
"times": "样本数",
"quantity": "掉落数",
"percentage": "百分比",
"apPPR": "单件期望理智",
"clearTime": "最短通关用时",
"itemPerTime": "单件期望用时",
"timeRange": "统计区间"
},
"headerDesc": {
"apCost": "完成单次该作战的所需理智数量",
"quantity": "在该作战中,所有提交到企鹅物流数据统计的样本内,该物品的出现次数",
"times": "在该作战中,所有提交到企鹅物流数据统计的样本提交次数",
"percentage": "期望掉落概率;计算方式为 (掉落数 / 样本数)",
"patternPercentage": "此掉落组合占所有掉落汇报的百分比;计算方式为 (掉落数 / 样本数)",
"apPPR": "根据当前的「百分比」项,计算出的在该作战获得「1x对应物品」所需的期望理智,即 (作战理智消耗 / (掉落数 / 样本数))",
"clearTime": "来源为 PRTS Wiki 中的「最短通关用时」;其中,PRTS Wiki 对此的计算方法为:由「作战开始」直至「最后出怪」期间,使用 1 倍速的最短所需游戏时间总长",
"itemPerTime": "根据当前的「百分比」项,计算出的在该作战获得「1x对应物品」所需的期望时间消耗,即 (作战最短通关用时 / (掉落数 / 样本数))",
"timeRange": "由于存在掉落物列表变动故引入的「统计区间」概念。在本表所展示的数据中,其将仅包含已标注时间段内所提交的样本统计数据。若欲查看其它统计区间内的样本统计情况,请使用「高级查询」"
},
"filter": {
"title": "数据过滤",
"indicator": "已应用 {count} 个过滤器",
"stats": "过滤后 {filtered} / 过滤前 {total}",
"overview": "过滤概览",
"type": {
"_name": "作战类型",
"showPermanent": "常驻",
"showActivity": "活动"
},
"status": {
"_name": "作战状态",
"onlyOpen": "仅正在开放"
}
},
"itemPreview": {
"more": "共 {count} 个作战含有此掉落"
},
"timeRange": {
"inBetween": "{0} ~ {1}",
"toPresent": "{date} 至今",
"endsAt": "{date} 之前",
"unknown": "未知",
"notSelected": "(暂未选择)"
},
"trends": {
"name": "掉落历史趋势",
"set": {
"rate": "掉落率",
"sample": "当日样本量",
"drops": "掉落数"
}
},
"lastUpdated": "最后更新:{date}",
"site": {
"viewMore": "查看更多",
"total": {
"sanity": "所有掉落汇报消耗理智",
"report": "掉落汇报总数",
"items": "物品掉落总数"
},
"stages": "作战掉落汇报排行",
"items": "物品掉落汇报排行",
"all": "全时段",
"24hr": "最近 24hr",
"generating": {
"title": "全站数据一览正在计算中...",
"subtitle": "神经网络信息:由于数据量庞大,全站数据一览需要大约 5 分钟进行计算。请稍后再来。",
"refresh": "刷新全站数据一览"
}
}
},
"contribute": {
"repo": "项目仓库:",
"frontend": "前端",
"frontendV4": "前端 v4",
"backend": "后端",
"recognizer": "截图识别",
"newFolder": "锐意新建文件夹中",
"caption": "企鹅物流数据统计是一项非盈利的社区项目,我们的发展离不开大家的共同维护与支持。欢迎前往上方 GitHub 为我们点 Star、提出 Issues,我们当然同时也欢迎 Pull Requests。",
"contribute_0": "如果您有以下一项或多项经验,愿意为企鹅数据贡献自己的一份力量,请加QQ群:747099627",
"contribute_1": "本项目为无偿开源项目",
"skills": {
"frontend": "网站前端开发(React)",
"backend": "网站后端开发(Go, PostgreSQL)",
"mobile": "移动端 App 开发(iOS、Android)",
"maintenance": "网站运维",
"design": "UI/UX设计",
"analysis": "数据统计分析",
"others": "..."
}
},
"fetch": {
"loading": "正在刷新数据...",
"chunk": {
"title": "正在从扩展神经网络传输数据",
"subtitle": "页面模块项正在加载中,请稍等..."
},
"failed": {
"title": "神经网络连接异常",
"subtitle": "未能与神经网络建立对等连接,部分资源丢失",
"retry": "重试",
"deploying": "新版部署中,最多将持续 5 分钟,请耐心等待",
"error": {
"zones": "章节元数据",
"stages": "作战元数据",
"items": "物品数据",
"limitations": "汇报数据校验规则",
"trends": "汇报历史数据",
"globalMatrix": "全平台掉落数据",
"personalMatrix": "个人掉落数据",
"globalPatternMatrix": "全平台掉落组合数据",
"personalPatternMatrix": "个人掉落组合数据",
"stats": "全站概览数据",
"period": "服务器事件数据"
}
}
},
"report": {
"alert": {
"title": {
"first": "检测到失误风险",
"repeat": "警告"
},
"continue": {
"first": "确定要继续吗?",
"repeat": "真的确定要继续吗?"
},
"contact": {
"before": "如果您认为这是一次误判,欢迎",
"activator": "联系作者",
"after": "(请附作战名称、实际掉落、若有掉落截图更佳),确认后我们会尽快予以修正。"
},
"causes": {
"noDrop": "尚未选择任何掉落物品",
"limitation": "本次汇报与现有数据差距较大,继续提交可能导致此次汇报被判定为异常,无法计入全部统计数据中。"
}
},
"specialSideStory": {
"dialog": {
"title": "「多索雷斯假日」活动特殊掉落汇报策略提示",
"cancel": "关闭",
"confirmTimerPending": "我已知晓并继续 ({timer})",
"confirmTimerDone": "我已知晓并继续"
}
},
"recognition": {
"step": {
"select": "选择",
"recognize": "识别",
"confirm": "确认",
"report": "汇报"
},
"tips": {
"fileTooBig": "\"{name}\" ({size}MB) 超出大小限制",
"fileTooOld": "\"{name}\" 的截图时间超过了 36h 内的时间限制",
"chooseImage": "点击以选择并加入图片、或直接向框内区域拖拽以加入图片",
"dragImage": "将图片拖拽到此处",
"addImage": "点击此处加入图片",
"copyImage": "右键图片或长按图片可拷贝到剪贴板或保存图片;再次点击图片即可关闭",
"abnormal": "您提交识别的截图中有 {count} 张截图由于未成功通过质量监测,被标记为了「汇报排除」并将无法上传至本站",
"notImageFile": "{files} 不是图片文件,无法使用",
"emptyResult": "无可用识别结果",
"unsatisfiedStart": "无法开始识别",
"emptyFile": "暂未选择任何图片",
"hasInvalidFile": "含有无效文件"
},
"status": {
"success": "成功",
"warning": "警告",
"error": "异常"
},
"description": "仅需选择结算页面截图,即可自动识别并上传所有掉落结果。",
"recognize": {
"noFilename": "暂无文件名",
"elapsed": "已用时间",
"remaining": "预计剩余",
"speed": "识别速度",
"imagePerSecond": "{count} 图/秒"
},
"confirm": {
"loadingImage": "正在加载截图预览",
"overview": {
"_name": "结果概览",
"total": "共识别了",
"success": "检测通过",
"error": "检测异常",
"count": "{count} 张",
"server": "数据集服务器",
"duration": "每张图片平均识别用时"
},
"details": "结果详情",
"unknownStage": "无法识别",
"abnormal": {
"error": "此张图片未通过质量监测",
"fatal": "此张图片无法被识别",
"details": "详细异常列表",
"hover": "鼠标悬浮以查看识别内容"
},
"cherryPick": {
"disabled": "无法选择异常图片",
"accepted": "上传本图结果",
"rejected": "不上传本图结果"
},
"noResult": "暂时没有识别结果",
"submit": "确认已勾选的 {count} 次结算记录",
"itemsTotal": "物品数合计"
},
"report": {
"title": "汇报详情",
"total": "总计",
"submit": "汇报 {count} 次结算记录",
"reporting": "正在批量上传掉落汇报...",
"allSucceeded": "已成功上传 {count} 次结算记录",
"partialSucceeded": "仅成功上传共 {count} 次的部分结算记录",
"partialFailed": "共计 {count} 次结算记录上传失败。请依照下方步骤排查可能出现的错误原因",
"partialFailedDesc": [
"检查您的网络连接:质量较差的网络连接或网络中断可能造成上传失败。",
"为保证全站数据集免受外部攻击的影响,若您在多次重试后依然无法上传,则可能您的提交量已触发汇报上限、请于 24 小时后再重试上传剩余的掉落汇报。",
"由于 IP 性质并不能定位到您个体,在宽带热门区域,您的 IP 有可能与他人共享使用。此种情况下,请尝试切换您的移动网络或 WiFi 重试识别,亦或您可以于 24 小时后重试上传。",
"为防止重传攻击,我们会对您的请求附加时间戳;若您的设备的时间与正常时间差距过大,则可能导致上传失败,请尝试校准设备时间后重试。"
],
"caption": "感谢您的掉落汇报;由于缓存原因,您汇报的数据可能需要最多 20 分钟即可于全站数据集生效"
},
"states": {
"pending": "正等待初始化...",
"initializing": "初始化中...",
"recognizing": "正在识别...",
"rendering": "渲染确认内容中...",
"submitting": "正在提交记录..."
},
"cost": "耗时",
"filename": "文件名",
"result": "识别结果",
"queue": "识别图片队列",
"start": "识别 {count} 张图片",
"progress": "进度",
"retry": "提交失败,正在重试",
"filter": "结果过滤",
"notices": {
"welcome": [
"新版截图识别已适配于 2022 年 4 月的国服新游戏内 UI。",
"您所有提供的图片均仅会通过使用 WebAssembly 技术于您的浏览器**本地**进行识别、不会向服务器上传,因此不产生额外流量开销。",
"为保证本站数据集准确度,请仅选择**截图时间在 36 小时内**、通关评价为 **3 星**的**结算界面**截图。",
"请**不要**选择首次通关截图,并请如实汇报**所有**发生的掉落情况。"
],
"confirm": [
"点击图片可以放大以便于核对;再次点击图片即可关闭",
"成功识别的截图已被自动选中上传",
"为保证本站数据集准确度,您将**不可**选中发生识别错误的截图"
]
},
"exceptions": {
"Fingerprint::Same": {
"title": "存在完全一致的图片",
"subtitle": "请检查是否选择了重复的截图"
},
"FileTimestamp::TooClose": {
"title": "存在截图相隔时间过短的图片",
"subtitle": "请检查是否选择了重复截图"
},
"DropInfos::Violation": "识别结果验证失败",
"StageChar::LowConfidence": {
"title": "关卡识别可能存在错误",
"subtitle": "识别置信度低,请核对识别结果是否与图片一致"
},
"DropQuantityChar::LowConfidence": {
"title": "物品数量识别可能存在错误",
"subtitle": "识别置信度低,请核对识别结果是否与图片一致"
},
"DropAreaDropsQuantity::NotFound": {
"title": "存在未识别到数量的掉落",
"subtitle": "分辨率或质量较差的图片可能会导致此问题。请检查图片是否经过压缩处理"
},
"DropAreaDrops::LowConfidence": {
"title": "存在未知掉落",
"subtitle": "此问题通常是由于非活动期间的活动掉落的导致的。"
},
"DropAreaDrops::Illegal": {
"title": "存在非法掉落",
"subtitle": "此关卡目前不应存在任何掉落,但图片中存在。这通常是由于非活动期间的活动掉落的导致的。"
},
"Result::False": {
"title": "非结算页面截图或内部错误",
"subtitle": "若这确实是一张结算页面截图,请检查您是否选择了正确的服务器"
},
"Stage::NotFound": {
"title": "未知关卡",
"subtitle": "这可能是关卡识别出现了错误,或此关卡不被收录(如剿灭作战、绝境作战等)"
},
"Stage::Illegal": {
"title": "非法关卡",
"subtitle": "此关卡目前不开放"
},
"3stars::False": "非三星评价",
"DropType::Illegal": {
"title": "非法掉落类型",
"subtitle": "截图中存在首次掉落、理智返还等非法掉落类型,或存在识别失败的掉落类型"
},
"DropType::NotFound": "未找到任何掉落类型"
}
},
"rules": {
"item": {
"_name": "物品项",
"now": "已于 “{stage}” 选择了 {quantity} 个 “{item}”",
"gte": "“{stage}” 内的 “{item}” 应至少有 {should} 个",
"lte": "“{stage}” 内的 “{item}” 应至多有 {should} 个",
"not": "“{stage}” 内的 “{item}” 数量不应等于 {should}"
},
"type": {
"_name": "物品种类",
"now": "于 “{stage}” 已选 {quantity} 种物品",
"gte": "“{stage}” 内应至少有 {should} 种物品",
"lte": "“{stage}” 内应至多有 {should} 种物品",
"not": "“{stage}” 内的物品种类数应总计不为 {should}"
}
},
"clear": "清空",
"closedReason": {
"EXPIRED": "不在可汇报时间区间内:作战已结束或暂未开启",
"NOT_FOUND": "作战不存在:于所选服务器未找到此作战",
"INVALID": "无法汇报:此作战未包含掉落汇报元数据"
},
"furniture": "家具掉落:{state}",
"name": "汇报结果",
"submit": "提交",
"success": "汇报成功",
"unable": "无法提交:",
"undo": "撤销",
"undoSuccess": "撤销成功",
"gacha": "本作战允许在一次汇报内包含多个结果。",
"notices": {
"rule_1": "这是单次作战的提交,请注意核对数目;",
"rule_2": "若无素材掉落,请直接点击提交;",
"rule_3": "请不要汇报首次通关奖励,不要只汇报比较“欧”的掉落;",
"rule_4": "请保证通关评价是3星;",
"rule_5": "请只汇报国服的掉落,谢谢。"
},
"dossolesHoliday": {
"title": {
"inner": "确保集齐所有标志物",
"tmpl": "请{0}后再进行汇报"
},
"content": "根据初步数据统计推测,标志物掉率计算事件可能不满足独立前提,即:在所有标志物被集齐前、其掉率可能会产生动态变化。因此,我们决定仅收集集齐所有标志物后的掉率数据"
},
"usage": "左键增加,右键减少"
},
"mirrors": {
"global": {
"notification": "推荐使用海外镜像站 {0},可以提升访问速度哦!"
},
"cn": {
"notification": "推荐使用国内镜像站 {0},可以提升访问速度哦!"
},
"_notification": {
"ignore": {
"title": "不再显示镜像提示?",
"subtitle": "确定要忽略所有镜像提示吗?网站加载性能可能会受到影响。"
}
}
},
"settings": {
"storageIssue": "本地缓存存储出现问题,应用可能不稳定;若持续出现此警告,请尝试通过「菜单 - 设置 - 重置本地数据与设置」清空缓存以修复",
"category": {
"appearance": "外观",
"data": "设置与数据",
"about": "关于"
},
"iosSystemSettings": "语言与隐私设置",
"optimization": {
"lowData": {
"title": "低数据模式",
"active": "低数据模式已启用",
"subtitle": "低数据模式将停止加载诸如作战列表背景图、全站背景立绘等不必要资源以减少网络数据的使用。"
}
},
"data": {
"server": "本地缓存数据包含服务器:",
"size": "本地数据大小:",
"reset": {
"title": "重置本地数据与设置",
"subtitle": "将会删除所有本地数据与设置。删除后,所有本地设置均会重置至默认值并刷新页面,数据将需要重新加载。确定要继续吗?"
}
},
"push": {
"language": "消息语言",
"categories": {
"_name": "推送类型",
"NewStage": {
"title": "新章节加入",
"subtitle": "在新章节加入本 App 时通知您"
},
"ImportantTimePoint": {
"title": "防侠客",
"subtitle": "在活动即将结束时通知您"
},
"Maintenance": {
"title": "上游闪断更新",
"subtitle": "在新的游戏服务器闪断更新公告发布后通知您"
},
"ClientUpgrade": {
"title": "客户端强制更新",
"subtitle": "在新的客户端强制更新公告发布后通知您"
}
}
}
},
"zone": {
"name": "章节",
"types": {
"MAINLINE": "主题曲",
"WEEKLY": "资源收集",
"ACTIVITY": "限时活动",
"ACTIVITY_OPEN": "限时活动 — 开放中",
"ACTIVITY_CLOSED": "限时活动 — 已结束",
"ACTIVITY_PENDING": "限时活动 — 即将开放",
"ACTIVITY_PERMANENT": "插曲 & 别传",
"GACHABOX": "物资补给箱"
},
"subTypes": {
"2019": "2019",
"2020": "2020",
"2021": "2021",
"2022": "2022",
"AWAKENING_HOUR": {
"title": "觉醒",
"subtitle": "0~3 章"
},
"VISION_SHATTER": {
"title": "幻灭",
"subtitle": "4~8 章"
},
"DYING_SUN": {
"title": "残阳",
"subtitle": "9~10 章"
},
"INTERLUDE": "插曲",
"SIDESTORY": "别传"
},
"status": {
"0": "开放中",
"1": "已结束",
"-1": "即将开放",
"permanentOpen": "常驻开放"
},
"opensAt": "开放时间:{0} - {1}"
},
"stage": {
"name": "作战",
"about": "关于此作战",
"apCost": "{apCost} 点理智",
"actions": {
"_name": {
"selector": "快速访问",
"selectorEmpty": "暂无任何快速访问记录",
"panel": "快速操作"
},
"star": {
"name": "星标作战",
"activate": "星标此作战",
"activated": "已星标此作战",
"deactivate": "点击以取消",
"empty": [
"暂无已星标的作战",
"使用作战详情中的「快速操作」即可星标作战并于此处显示"
]
},
"history": {
"name": "最近选择作战",
"empty": [
"暂无最近选择作战",
"访问任何作战页面后,记录即会于此处显示"
],
"clear": "清空"
},
"links": {
"prts-wiki": "Wiki",
"map-arknights-com": "地图"
},
"advanced": {
"activator": "进行高级查询"
}
},
"loots": {
"NORMAL_DROP": "常规掉落",
"EXTRA_DROP": "额外物资",
"SPECIAL_DROP": "特殊掉落",
"FURNITURE": "家具"
},
"selector": {
"plannerExclude": "排除规划作战",
"excludeAll": "排除全部",
"includeAll": "选中全部",
"title": "作战选择"
}
},
"planner": {
"notices": {
"autoExistence": "刷图规划器现将会自动隐藏未于已选择服务器出现或开放的作战"
},
"options": {
"_name": "选项",
"byProduct": "考虑合成副产物",
"requireExp": "大量需求经验",
"requireLmb": "大量需求龙门币",
"excludeStage": {
"_name": "计算排除",
"title": "选择",
"selected": "已排除 {stages} 关"
}
},
"reset": {
"name": "重置",
"success": "成功重置所选数据项",
"dialog": {
"title": "重置刷图规划器数据",
"subtitle": "将会删除所选部分的相关刷图规划器数据项",
"options": {
"options": {
"name": "规划选项",
"indicator": "将清除所有规划选项"
},
"excludes": {
"name": "计算排除",
"indicator": "将清除所有排除作战"
},
"items": {
"name": "物品数据",
"indicator": "将清除所有物品数据"
}
}
}
},
"actions": {
"_name": "数据",
"import": "导入",
"export": "导出",
"importExport": "@:(planner.actions.import)/@:(planner.actions.export)",
"calculate": "计算规划",
"calculating": "少女计算中...",
"link": {
"generate": "获取分享链接",
"generating": "正在生成",
"share": "分享链接"
},
"config": {
"_name": "配置代码",
"share": "分享配置代码",
"import": "导入配置代码"
}
},
"craft": {
"do": "合成",
"unable": "无法合成",
"errors": {
"title": "合成缺少所需物品",
"notEnough": "需要 {need} 个「{item}」以合成,但仅已有 {have} 个"
},
"plans": {
"title": "合成规划",
"plan": "将使用 {cost} 个「{item}」合成并剩余 {remain} 个"
},
"success": "已使用 {sourceItems} 合成 {amount} 个 {productItem}"
},
"have": "已有",
"need": "需要",
"copy": "复制到剪贴板",
"calculation": {
"title": "规划结果",
"tabs": {
"stages": "作战列表",
"syntheses": "合成列表",
"values": "素材理智价值"
},
"lmb": "预计龙门币收益",
"sanity": "预计需要理智",
"exp": "预计获得录像带经验",
"times": "次",
"level": "材料等级",
"noStage": "未找到需要进行的作战。",
"noSyntheses": "未找到需要合成的素材。"
}
},
"item": {
"name": "素材",
"choose": {
"name": "素材选择"
},
"categories": {
"ACTIVITY_ITEM": "活动道具",
"CARD_EXP": "作战记录",
"CHIP": "芯片",
"FURN": "家具",
"MATERIAL": "材料"
},
"related": "相关物品",
"undefined": "未知物品"
},
"query": {
"panel": {
"builder": "查询编辑器",
"results": "查询结果",
"footer": {
"cache": "现在显示的查询结果数据为缓存数据。若需要获取最新数据,请再次「执行查询」。",
"disclaimer": "「高级查询」功能所产出的所有数据信息均受本站「数据许可协议」保护;本站不对「高级查询」功能所产出的所有数据信息做任何形式的承诺或背书。"
}
},
"disclaimer": {
"title": "使用前必读",
"content": "「高级查询」意在为有更复杂数据分析需求的用户提供以更高自由度使用企鹅物流数据统计内相关数据集之可能性。由于本功能的高自由度属性,在不了解统计学等相关学科的学术内容前,尝试分析此功能的查询结果可能会存在误导性。企鹅物流数据统计提醒各位对数据进行二次分析的刀客塔:请在分析时不要断章取义、故意使用本站数据引导舆论。高级查询功能的受众群体是熟悉统计学等学科的用户,开放后便于他们以更多维度分析数据集。我们欢迎对掉落数据感兴趣并进行客观与科学分析的刀客塔,但我们不欢迎带有个人情绪或既定立场的情况下、尝试错误地从本站数据中得出对任何实体不利结论的用户。"
},
"title": {
"main": "主查询",
"comparison": "对比查询 #{index}"
},
"type": {
"matrix": "统计数据",
"trend": "历史趋势"
},
"selector": {
"item": {
"title": "素材选择",
"subtitle": "用于将查询结果过滤为此作战内的特定素材。",
"unspecified": "显示作战全部掉落素材",
"selected": "仅查询 {length} 种素材"
},
"stage": {
"title": "选择作战",
"subtitle": "(必填)用于将查询结果过滤为一特定作战。"
},
"timeRange": {
"title": "时间段",
"subtitle": "(必填)用于将查询结果过滤为于一特定时间段内。",
"presets": {
"title": "预设时间",
"start": "开始",
"end": "结束"
}
},
"interval": {
"title": "分段间隔",
"subtitle": "用于设置历史趋势的分段间隔。",
"unspecified": "不分段"
}
},
"operation": {
"add": "添加对比查询",
"execute": "执行查询",
"inProgress": "正在执行查询"
},
"result": {
"main": "主查询结果",
"comparison": "对比查询 #{index} 结果",
"empty": "此查询返回了 0 个结果,请检查对应查询条件后重试",
"hideTime": "隐藏详细时间"
}
},
"version": {
"upgrade": {
"title": "版本已过期",
"subtitle": "由于接口升级,您现在使用的版本已过期。请在升级后重试",
"action": "升级",
"unable": "无法升级?"
}
},
"notice": {
"failed": "获取公告失败:{error}",
"loading": "正在加载公告"
},
"dataSource": {
"switch": "数据源",
"global": "全平台",
"loginNotice": "查看个人掉落数据前,请先登录",
"personal": "个人",
"title": "需要登录"
},
"validator": {
"required": "必填"
},
"quotes": {
"doYouKnow": [
"你知道吗?白面鸮头上的那一撮毛超级可爱!o(*≧▽≦)ツ"
]
},
"credits": {
"material": {
"title": "网站内容声明",
"content": [
"企鹅物流数据统计网站内所使用的游戏资源(包括但不限于:游戏图片、动画、音频、文本原文或其转译版本等),其目的仅为更好地反映游戏内对应元素、增强用户体验,相关作品之版权仍属于上海鹰角网络科技有限公司和/或其关联公司,即鹰角网络游戏软件和/或鹰角网络游戏服务的提供方(包括但不限于:YOSTAR (HONG KONG) LIMITED, 株式会社Yostar, YOSTAR LIMITED, 龍成網路 等)",
"企鹅物流数据统计网站内所使用的部分资源来源于 PRTS Wiki ([http://prts.wiki](http://prts.wiki)) 并同时对部分资源进行了非歧义性的更改",
"企鹅物流数据统计网站内使用了经细微修改的、由 Free Fonts Project 提供的 Bender 字体([http://jovanny.ru](http://jovanny.ru)),该字体特别说明使用者可将相关字体以任何用途、没有任何限制地使用,在此特别表示感谢。",
"企鹅物流数据统计网站的「掉落识别」功能中,嵌入了经格式转换的、由 Synthview Type Design 提供的 Novecento Sans Bold 字体([http://typography.synthview.com/novecento-sans-font-family.php](http://typography.synthview.com/novecento-sans-font-family.php)),以供非展示性用途的模板匹配使用。"
]
},
"source": {
"title": "开源许可列表"
}
},
"auth": {
"forgot": {
"activator": "忘记 PenguinID",
"title": "无法登录?",
"subtitle": "找回登录信息",
"penguinIdHistory": {
"title": "此前曾登录的 PenguinID",
"lastLoginAt": "最后于 {time} 在本设备登录",
"loginAsUserId": "以此 PenguinID 登录",
"deleteUserId": "删除此 PenguinID 登录记录",
"noData": "暂无数据",
"tips": "本功能仅可找回于 v3.3.1 及更新版本客户端所登录的 PenguinID"
}
}
},
"members": {
"categories": {
"owner": "站长",
"maintainer": "主要贡献者",
"contributors": "内容贡献者",
"others": "其他",
"translators": "翻译"
},
"responsibilities": {
"_name": "贡献项目",
"arkplanner": "ArkPlanner 作者",
"backend": "后端",
"bulkupload": "批量汇报",
"customersupport": "客服",
"v1frontend": "v1.0 前端",
"frontend": "前端",
"localization_en": "英语本地化",
"localization_ja": "日语本地化",
"localization_ko": "韩语本地化",
"logo": "Logo 画师",
"maintenance": "运维",
"materials": "素材提供",
"statistics": "统计分析",
"widget": "小组件开发",
"native": "App 开发",
"recognition": "截图识别"
},
"socials": {
"email": "Email",
"github": "GitHub",
"qq": "QQ",
"twitter": "Twitter",
"weibo": "微博"
}
},
"pattern": {
"name": "掉落组合",
"empty": "无掉落",
"error": [
"暂无本作战",
"掉落组合数据"
]
},
"share": {
"name": "分享",
"shortlink": {
"name": "短链接"
},
"text": {
"_tmpl": "查看企鹅物流数据统计中「{name}」的掉落统计数据",
"stage": "作战 {name}",
"item": "素材 {name}"
},
"success": "分享成功"
},
"search": {
"placeholder": "搜索...",
"hint": "键入 物品全拼 拼音首字母 作战名 章节名 关卡编号 或 部分关卡/物品昵称"
},
"confirmLeave": {
"title": "确定要离开此页面吗?",
"subtitle": "未保存的更改可能会丢失"
},
"specials": {
"mikubirthday2021": {
"caption": "祝公主殿下生日快乐"
}
}
}
export default Object.freeze(messages)
|
<gh_stars>0
/*
import {isObjectInclude} from './object';
export function arrayMove(list: Array<unknown>, fromIndex: number, toIndex: number): void {
const item = list[fromIndex];
list.splice(fromIndex, 1);
list.splice(toIndex, 0, item);
}
export function findInArray<ItemType>(list: Array<ItemType>, query: {[key: string]: unknown}): ItemType | null {
return list.find((item: ItemType): boolean => isObjectInclude<ItemType>(item, query)) || null;
}
export function findInArrayEnsure<ItemType>(
list: Array<ItemType>,
query: {[key: string]: unknown},
defaultValue: ItemType
): ItemType {
return findInArray<ItemType>(list, query) || defaultValue;
}
export function findManyInArray<ItemType>(list: Array<ItemType>, query: {[key: string]: unknown}): Array<ItemType> {
return list.filter((item: ItemType): boolean => isObjectInclude<ItemType>(item, query));
}
export function findByValue<ItemType>(list: Array<ItemType>, value: unknown): ItemType | null {
return list.find((item: ItemType): boolean => item === value) || null;
}
export function findByValueEnsure<ItemType>(list: Array<ItemType>, value: unknown, defaultValue: ItemType): ItemType {
return findByValue<ItemType>(list, value) || defaultValue;
}
*/
|
<gh_stars>1-10
const SpritesmithPlugin = require('webpack-spritesmith')
module.exports = (api, projectOptions) => {
const {
sprite
} = projectOptions.pluginOptions || {}
const { enabled, ...options } = sprite
if (enabled) return
api.configureWebpack(webpackConfig => {
// 修改 webpack 配置
// 或返回通过 webpack-merge 合并的配置对象
return {
plugins: [
new SpritesmithPlugin(options)
]
}
})
api.registerCommand('sprite', {
description: 'sprite',
usage: 'vue-cli-service test',
options: {}
}, args => {
console.log(projectOptions)
})
}
|
# Setup XiangShan environment variables
export XS_PROJECT_ROOT=$(pwd)
export NEMU_HOME=$(pwd)/NEMU
export AM_HOME=$(pwd)/nexus-am
export NOOP_HOME=$(pwd)/XiangShan
export WAVE_PATH=$(pwd)/wave
# export NOOP_HOME=$(pwd)/NutShell |
import { hasMany, Model } from 'miragejs';
export default Model.extend({
followedCrates: hasMany('crate'),
});
|
package com.home.demo.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.home.demo.bean.User;
import com.home.demo.dao.UserDao;
import com.home.demo.service.UserService;
import com.home.demo.util.Result;
import com.home.demo.util.ResultGenerator;
@Service
public class UserServiceImpl implements UserService{
@Autowired
private UserDao userDao;
@Override
public Result findAll() {
try {
return ResultGenerator.getSuccessResult(userDao.findAll());
}catch(Exception e) {
e.printStackTrace();
return ResultGenerator.getFailResult("获取员工列表失败!");
}
}
@Override
public Result findById(int id) {
try {
return ResultGenerator.getSuccessResult(userDao.findById(id));
}catch(Exception e) {
e.printStackTrace();
return ResultGenerator.getFailResult("获取员工信息失败!");
}
}
@Override
public Result save(User user) {
try {
userDao.save(user);
return ResultGenerator.getSuccessResult();
}catch(Exception e) {
e.printStackTrace();
return ResultGenerator.getFailResult("保存员工信息失败!");
}
}
@Override
public Result modify(User user) {
try {
userDao.modify(user);
return ResultGenerator.getSuccessResult();
}catch(Exception e) {
e.printStackTrace();
return ResultGenerator.getFailResult("修改员工信息失败!");
}
}
@Override
public Result deleteById(int id) {
try {
userDao.deleteById(id);
return ResultGenerator.getSuccessResult();
}catch(Exception e) {
e.printStackTrace();
return ResultGenerator.getFailResult("删除员工信息失败!");
}
}
@Override
public Result findByUserName(String username) {
try {
return ResultGenerator.getSuccessResult(userDao.findByUserName(username));
}catch(Exception e) {
e.printStackTrace();
return ResultGenerator.getFailResult("获取员工信息失败!");
}
}
}
|
<!DOCTYPE html>
<html>
<head>
<title>Blog Post Form</title>
</head>
<body>
<h1>Submit New Blog Post</h1>
<form action="new-post.php" method="POST">
<label for="title">Title:</label><br>
<input type="text" name="title" id="title"><br><br>
<label for="content">Content:</label><br>
<textarea name="content" id="content" cols="30" rows="10"></textarea><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html> |
package cyclops.container.traversable;
import static cyclops.container.immutable.tuple.Tuple.tuple;
import static java.util.Arrays.asList;
import static java.util.Comparator.comparing;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.hasItems;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.lessThan;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import cyclops.function.companion.Reducers;
import cyclops.function.companion.Semigroups;
import cyclops.container.immutable.impl.Seq;
import cyclops.container.immutable.impl.Vector;
import cyclops.container.immutable.tuple.Tuple;
import cyclops.container.immutable.tuple.Tuple2;
import cyclops.container.immutable.tuple.Tuple3;
import cyclops.container.immutable.tuple.Tuple4;
import cyclops.function.combiner.Monoid;
import cyclops.reactive.ReactiveSeq;
import cyclops.reactive.companion.Spouts;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
import java.util.stream.Stream;
import org.junit.Before;
import org.junit.Test;
public abstract class AbstractTraversableTest {
Traversable<Integer> empty;
Traversable<Integer> nonEmpty;
public abstract <T> Traversable<T> of(T... elements);
public abstract <T> Traversable<T> empty();
@Test
public void publishAndSubscribe() {
assertThat(Spouts.from(of(1,
2,
3))
.toList(),
hasItems(1,
2,
3));
}
@Test
public void stream() {
assertThat(of(1,
2,
3).stream()
.collect(java.util.stream.Collectors.toList()),
hasItems(1,
2,
3));
}
@Test
public void dropRight() {
assertThat(of(1,
2,
3).dropRight(1)
.stream()
.toList(),
hasItems(1,
2));
}
@Test
public void dropRightEmpty() {
assertThat(of().dropRight(1)
.stream()
.toList(),
equalTo(Arrays.asList()));
}
@Test
public void dropUntil() {
assertThat(of(1,
2,
3,
4,
5).dropUntil(p -> p == 2)
.stream()
.toList()
.size(),
lessThan(5));
}
@Test
public void dropUntilEmpty() {
assertThat(of().dropUntil(p -> true)
.stream()
.toList(),
equalTo(Arrays.asList()));
}
@Test
public void dropWhile() {
assertThat(of(1,
2,
3,
4,
5).dropWhile(p -> p < 6)
.stream()
.toList()
.size(),
lessThan(1));
}
@Test
public void dropWhileEmpty() {
assertThat(of().dropWhile(p -> true)
.stream()
.toList(),
equalTo(Arrays.asList()));
}
@Before
public void setup() {
empty = of();
nonEmpty = of(1);
}
protected Object value() {
return "jello";
}
private int value2() {
return 200;
}
@Test
public void batchBySize() {
System.out.println(of(1,
2,
3,
4,
5,
6).grouped(3)
.stream()
.collect(java.util.stream.Collectors.toList()));
assertThat(of(1,
2,
3,
4,
5,
6).grouped(3)
.stream()
.collect(java.util.stream.Collectors.toList())
.size(),
is(2));
}
@Test
public void limitWhileTest() {
List<Integer> list = new ArrayList<>();
while (list.size() == 0) {
list = of(1,
2,
3,
4,
5,
6).takeWhile(it -> it < 4)
.stream()
.peek(it -> System.out.println(it))
.collect(java.util.stream.Collectors.toList());
}
assertThat(Arrays.asList(1,
2,
3,
4,
5,
6),
hasItem(list.get(0)));
}
@Test
public void testScanLeftStringConcat() {
assertThat(of("a",
"b",
"c").scanLeft("",
String::concat)
.stream()
.toList()
.size(),
is(4));
}
@Test
public void testScanRightStringConcatMonoid() {
assertThat(of("a",
"b",
"c").scanRight(Monoid.of("",
String::concat))
.stream()
.toList()
.size(),
is(asList("",
"c",
"bc",
"abc").size()));
}
@Test
public void testScanRightStringConcat() {
assertThat(of("a",
"b",
"c").scanRight("",
String::concat)
.stream()
.toList()
.size(),
is(asList("",
"c",
"bc",
"abc").size()));
}
@Test
public void testIterable() {
List<Integer> list = of(1,
2,
3).stream()
.to()
.collection(LinkedList::new);
for (Integer i : of(1,
2,
3)) {
assertThat(list,
hasItem(i));
}
}
@Test
public void testSkipWhile() {
Supplier<Traversable<Integer>> s = () -> of(1,
2,
3,
4,
5);
assertTrue(s.get()
.dropWhile(i -> false)
.stream()
.toList()
.containsAll(asList(1,
2,
3,
4,
5)));
assertEquals(asList(),
s.get()
.dropWhile(i -> true)
.stream()
.toList());
}
@Test
public void testSkipUntil() {
Supplier<Traversable<Integer>> s = () -> of(1,
2,
3,
4,
5);
assertEquals(asList(),
s.get()
.dropUntil(i -> false)
.stream()
.toList());
assertTrue(s.get()
.dropUntil(i -> true)
.stream()
.toList()
.containsAll(asList(1,
2,
3,
4,
5)));
}
@Test
public void testLimitWhile() {
Supplier<Traversable<Integer>> s = () -> of(1,
2,
3,
4,
5);
assertEquals(asList(),
s.get()
.takeWhile(i -> false)
.stream()
.toList());
assertTrue(s.get()
.takeWhile(i -> i < 3)
.stream()
.toList()
.size() != 5);
assertTrue(s.get()
.takeWhile(i -> true)
.stream()
.toList()
.containsAll(asList(1,
2,
3,
4,
5)));
}
@Test
public void testLimitUntil() {
assertTrue(of(1,
2,
3,
4,
5).takeUntil(i -> false)
.stream()
.toList()
.containsAll(asList(1,
2,
3,
4,
5)));
assertFalse(of(1,
2,
3,
4,
5).takeUntil(i -> i % 3 == 0)
.stream()
.toList()
.size() == 5);
assertEquals(asList(),
of(1,
2,
3,
4,
5).takeUntil(i -> true)
.stream()
.toList());
}
@Test
public void zip() {
List<Tuple2<Integer, Integer>> list = ((Traversable<Tuple2<Integer, Integer>>) of(1,
2,
3,
4,
5,
6).zip(of(100,
200,
300,
400).stream())).stream()
.peek(it -> System.out.println(it))
.collect(java.util.stream.Collectors.toList());
System.out.println("list = " + list);
List<Integer> right = list.stream()
.map(t -> t._2())
.collect(java.util.stream.Collectors.toList());
assertThat(right,
hasItem(100));
assertThat(right,
hasItem(200));
assertThat(right,
hasItem(300));
assertThat(right,
hasItem(400));
List<Integer> left = list.stream()
.map(t -> t._1())
.collect(java.util.stream.Collectors.toList());
assertThat(Arrays.asList(1,
2,
3,
4,
5,
6),
hasItem(left.get(0)));
}
@Test
public void testScanLeftStringConcatMonoid() {
assertThat(of("a",
"b",
"c").scanLeft(Reducers.toString(""))
.stream()
.toList(),
is(asList("",
"a",
"ab",
"abc")));
}
@Test
public void limitTimeEmpty() {
List<Integer> result = ReactiveSeq.<Integer>of().peek(i -> sleep(i * 100))
.take(1000,
TimeUnit.MILLISECONDS)
.toList();
assertThat(result,
equalTo(Arrays.asList()));
}
@Test
public void skipTimeEmpty() {
List<Integer> result = ReactiveSeq.<Integer>of().peek(i -> sleep(i * 100))
.drop(1000,
TimeUnit.MILLISECONDS)
.toList();
assertThat(result,
equalTo(Arrays.asList()));
}
private int sleep(Integer i) {
try {
Thread.currentThread()
.sleep(i);
} catch (InterruptedException e) {
}
return i;
}
@Test
public void testSkipLast() {
assertThat(of(1,
2,
3,
4,
5).dropRight(2)
.stream()
.toList(),
equalTo(Arrays.asList(1,
2,
3)));
}
@Test
public void testSkipLastEmpty() {
assertThat(of().dropRight(2)
.stream()
.collect(java.util.stream.Collectors.toList()),
equalTo(Arrays.asList()));
}
@Test
public void testLimitLast() {
assertThat(of(1,
2,
3,
4,
5).takeRight(2)
.stream()
.collect(java.util.stream.Collectors.toList()),
equalTo(Arrays.asList(4,
5)));
}
@Test
public void testLimitLastEmpty() {
assertThat(of().takeRight(2)
.stream()
.collect(java.util.stream.Collectors.toList()),
equalTo(Arrays.asList()));
}
@Test
public void zip2of() {
List<Tuple2<Integer, Integer>> list = ReactiveSeq.fromIterable(of(1,
2,
3,
4,
5,
6).zip(of(100,
200,
300,
400).stream()))
.stream()
.toList();
List<Integer> right = list.stream()
.map(t -> t._2())
.collect(java.util.stream.Collectors.toList());
assertThat(right,
hasItem(100));
assertThat(right,
hasItem(200));
assertThat(right,
hasItem(300));
assertThat(right,
hasItem(400));
List<Integer> left = list.stream()
.map(t -> t._1())
.collect(java.util.stream.Collectors.toList());
assertThat(Arrays.asList(1,
2,
3,
4,
5,
6),
hasItem(left.get(0)));
}
@Test
public void zipInOrder() {
List<Tuple2<Integer, Integer>> list = ReactiveSeq.fromIterable(of(1,
2,
3,
4,
5,
6).zip(of(100,
200,
300,
400).stream()))
.toList();
assertThat(asList(1,
2,
3,
4,
5,
6),
hasItem(list.get(0)
._1()));
assertThat(asList(100,
200,
300,
400),
hasItem(list.get(0)
._2()));
}
@Test
public void zipEmpty() throws Exception {
final Traversable<Integer> zipped = this.<Integer>empty().zip(ReactiveSeq.<Integer>of(),
(a, b) -> a + b);
assertTrue(zipped.stream()
.collect(java.util.stream.Collectors.toList())
.isEmpty());
}
@Test
public void shouldReturnEmptySeqWhenZipEmptyWithNonEmpty() throws Exception {
final Traversable<Integer> zipped = this.<Integer>empty().zip(of(1,
2),
(a, b) -> a + b);
assertTrue(zipped.stream()
.collect(java.util.stream.Collectors.toList())
.isEmpty());
}
@Test
public void shouldReturnEmptySeqWhenZipNonEmptyWithEmpty() throws Exception {
final Traversable<Integer> zipped = of(1,
2,
3).zip(this.<Integer>empty(),
(a, b) -> a + b);
assertTrue(zipped.stream()
.collect(java.util.stream.Collectors.toList())
.isEmpty());
}
@Test
public void shouldZipTwoFiniteSequencesOfSameSize() throws Exception {
final Traversable<String> first = of("A",
"B",
"C");
final Traversable<Integer> second = of(1,
2,
3);
final Traversable<String> zipped = first.zip(second,
(a, b) -> a + b);
assertThat(zipped.stream()
.collect(java.util.stream.Collectors.toList())
.size(),
is(3));
}
@Test
public void shouldTrimSecondFixedSeqIfLonger() throws Exception {
final Traversable<String> first = of("A",
"B",
"C");
final Traversable<Integer> second = of(1,
2,
3,
4);
final Traversable<String> zipped = first.zip(second,
(a, b) -> a + b);
assertThat(zipped.stream()
.collect(java.util.stream.Collectors.toList())
.size(),
is(3));
}
@Test
public void shouldTrimFirstFixedSeqIfLonger() throws Exception {
final Traversable<String> first = of("A",
"B",
"C",
"D");
final Traversable<Integer> second = of(1,
2,
3);
final Traversable<String> zipped = first.zip(second,
(a, b) -> a + b);
assertThat(zipped.stream()
.collect(java.util.stream.Collectors.toList())
.size(),
equalTo(3));
}
@Test
public void testZipDifferingLength() {
List<Tuple2<Integer, String>> list = ReactiveSeq.fromIterable(of(1,
2).zip(of("a",
"b",
"c",
"d").stream())
)
.stream()
.toList();
assertEquals(2,
list.size());
assertTrue(asList(1,
2).contains(list.get(0)
._1()));
assertTrue("" + list.get(1)
._2(),
asList(1,
2).contains(list.get(1)
._1()));
assertTrue(asList("a",
"b",
"c",
"d").contains(list.get(0)
._2()));
assertTrue(asList("a",
"b",
"c",
"d").contains(list.get(1)
._2()));
}
@Test
public void shouldTrimSecondFixedSeqIfLongerStream() throws Exception {
final Traversable<String> first = of("A",
"B",
"C");
final Traversable<Integer> second = of(1,
2,
3,
4);
final Traversable<String> zipped = first.zip(second,
(a, b) -> a + b);
assertThat(zipped.stream()
.collect(java.util.stream.Collectors.toList())
.size(),
is(3));
}
@Test
public void shouldTrimFirstFixedSeqIfLongerStream() throws Exception {
final Traversable<String> first = of("A",
"B",
"C",
"D");
final Traversable<Integer> second = of(1,
2,
3);
final Traversable<String> zipped = first.zip(second,
(a, b) -> a + b);
assertThat(zipped.stream()
.collect(java.util.stream.Collectors.toList())
.size(),
equalTo(3));
}
@Test
public void testZipDifferingLengthStream() {
List<Tuple2<Integer, String>> list = ReactiveSeq.fromIterable(of(1,
2).zip(of("a",
"b",
"c",
"d").stream()))
.stream()
.toList();
assertEquals(2,
list.size());
assertTrue(asList(1,
2).contains(list.get(0)
._1()));
assertTrue("" + list.get(1)
._2(),
asList(1,
2).contains(list.get(1)
._1()));
assertTrue(asList("a",
"b",
"c",
"d").contains(list.get(0)
._2()));
assertTrue(asList("a",
"b",
"c",
"d").contains(list.get(1)
._2()));
}
@Test
public void shouldTrimSecondFixedSeqIfLongerSequence() throws Exception {
final Traversable<String> first = of("A",
"B",
"C");
final Traversable<Integer> second = of(1,
2,
3,
4);
final Traversable<String> zipped = first.zip(second,
(a, b) -> a + b);
assertThat(zipped.stream()
.collect(java.util.stream.Collectors.toList())
.size(),
is(3));
}
@Test
public void shouldTrimFirstFixedSeqIfLongerSequence() throws Exception {
final Traversable<String> first = of("A",
"B",
"C",
"D");
final Traversable<Integer> second = of(1,
2,
3);
final Traversable<String> zipped = first.zip(second,
(a, b) -> a + b);
assertThat(zipped.stream()
.collect(java.util.stream.Collectors.toList())
.size(),
equalTo(3));
}
@Test
public void testZipWithIndex() {
assertEquals(asList(),
of().zipWithIndex()
.stream()
.toList());
assertThat(of("a").zipWithIndex()
.stream()
.map(t -> t._2())
.findFirst()
.get(),
is(0l));
assertEquals(asList(Tuple.tuple("a",
0L)),
of("a").zipWithIndex()
.stream()
.toList());
}
@Test
public void batchBySizeCollection() {
assertThat(of(1,
2,
3,
4,
5,
6).grouped(3,
() -> Vector.<Integer>empty())
.stream()
.elementAt(0)
.toOptional()
.get()
.size(),
is(3));
// assertThat(of(1,1,1,1,1,1).grouped(3,()->new ListXImpl<>()).getValue(1).getValue().size(),is(1));
}
@Test
public void batchBySizeInternalSize() {
assertThat(of(1,
2,
3,
4,
5,
6).grouped(3)
.stream()
.collect(java.util.stream.Collectors.toList())
.get(0)
.size(),
is(3));
}
@Test
public void testSorted() {
Traversable<Tuple2<Integer, Integer>> t1 = of(tuple(2,
2),
tuple(1,
1));
List<Tuple2<Integer, Integer>> s1 = t1.sorted()
.stream()
.toList();
assertEquals(tuple(1,
1),
s1.get(0));
assertEquals(tuple(2,
2),
s1.get(1));
Traversable<Tuple2<Integer, String>> t2 = of(tuple(2,
"two"),
tuple(1,
"replaceWith"));
List<Tuple2<Integer, String>> s2 = t2.sorted(comparing(t -> t._1()))
.stream()
.toList();
assertEquals(tuple(1,
"replaceWith"),
s2.get(0));
assertEquals(tuple(2,
"two"),
s2.get(1));
Traversable<Tuple2<Integer, String>> t3 = of(tuple(2,
"two"),
tuple(1,
"replaceWith"));
List<Tuple2<Integer, String>> s3 = t3.sorted(t -> t._1())
.stream()
.toList();
assertEquals(tuple(1,
"replaceWith"),
s3.get(0));
assertEquals(tuple(2,
"two"),
s3.get(1));
}
@Test
public void zip2() {
List<Tuple2<Integer, Integer>> list = of(1,
2,
3,
4,
5,
6).zipWithStream(Stream.of(100,
200,
300,
400))
.stream()
.peek(it -> System.out.println(it))
.collect(java.util.stream.Collectors.toList());
List<Integer> right = list.stream()
.map(t -> t._2())
.collect(java.util.stream.Collectors.toList());
assertThat(right,
hasItem(100));
assertThat(right,
hasItem(200));
assertThat(right,
hasItem(300));
assertThat(right,
hasItem(400));
List<Integer> left = list.stream()
.map(t -> t._1())
.collect(java.util.stream.Collectors.toList());
assertThat(Arrays.asList(1,
2,
3,
4,
5,
6),
hasItem(left.get(0)));
}
@Test
public void testReverse() {
assertThat(of(1,
2,
3).reverse()
.stream()
.toList()
.size(),
is(asList(3,
2,
1).size()));
}
@Test
public void testShuffle() {
Supplier<Traversable<Integer>> s = () -> of(1,
2,
3);
assertEquals(3,
s.get()
.shuffle()
.stream()
.toList()
.size());
assertThat(s.get()
.shuffle()
.stream()
.toList(),
hasItems(1,
2,
3));
}
@Test
public void testShuffleRandom() {
Random r = new Random();
Supplier<Traversable<Integer>> s = () -> of(1,
2,
3);
assertEquals(3,
s.get()
.shuffle(r)
.stream()
.toList()
.size());
assertThat(s.get()
.shuffle(r)
.stream()
.toList(),
hasItems(1,
2,
3));
}
@Test
public void batchUntil() {
assertThat(of(1,
2,
3,
4,
5,
6).groupedUntil(i -> false)
.stream()
.toList()
.get(0)
.size(),
equalTo(6));
}
@Test
public void batchWhile() {
assertThat(of(1,
2,
3,
4,
5,
6).stream()
.peek(System.out::println)
.groupedWhile(i -> true)
.toList()
.get(0)
.size(),
equalTo(6));
}
@Test
public void batchUntilSupplier() {
assertThat(of(1,
2,
3,
4,
5,
6).groupedUntil(i -> false,
() -> Vector.empty())
.stream()
.toList()
.size(),
equalTo(1));
}
@Test
public void batchWhileSupplier() {
assertThat(of(1,
2,
3,
4,
5,
6).groupedWhile(i -> true,
() -> Vector.empty())
.stream()
.toList()
.size(),
equalTo(1));
}
@Test
public void slidingNoOrder() {
List<Seq<Integer>> list = of(1,
2,
3,
4,
5,
6).sliding(2)
.stream()
.toList();
System.out.println(list);
assertThat(list.get(0)
.size(),
equalTo(2));
assertThat(list.get(1)
.size(),
equalTo(2));
}
@Test
public void slidingIncrementNoOrder() {
List<Seq<Integer>> list = of(1,
2,
3,
4,
5,
6).sliding(3,
2)
.stream()
.collect(java.util.stream.Collectors.toList());
System.out.println(list);
assertThat(list.get(1)
.size(),
greaterThan(1));
}
@Test
public void combineNoOrder() {
assertThat(of(1,
2,
3).combine((a, b) -> a.equals(b),
Semigroups.intSum)
.stream()
.toList(),
equalTo(Arrays.asList(1,
2,
3)));
}
@Test
public void zip3NoOrder() {
List<Tuple3<Integer, Integer, Character>> list = of(1,
2,
3,
4).zip3(of(100,
200,
300,
400).stream(),
of('a',
'b',
'c',
'd').stream())
.stream()
.toList();
System.out.println(list);
List<Integer> right = list.stream()
.map(t -> t._2())
.collect(java.util.stream.Collectors.toList());
assertThat(right,
hasItem(100));
assertThat(right,
hasItem(200));
assertThat(right,
hasItem(300));
assertThat(right,
hasItem(400));
List<Integer> left = list.stream()
.map(t -> t._1())
.collect(java.util.stream.Collectors.toList());
assertThat(Arrays.asList(1,
2,
3,
4),
hasItem(left.get(0)));
List<Character> three = list.stream()
.map(t -> t._3())
.collect(java.util.stream.Collectors.toList());
assertThat(Arrays.asList('a',
'b',
'c',
'd'),
hasItem(three.get(0)));
}
@Test
public void zip4NoOrder() {
List<Tuple4<Integer, Integer, Character, String>> list = of(1,
2,
3,
4).zip4(of(100,
200,
300,
400).stream(),
of('a',
'b',
'c',
'd').stream(),
of("hello",
"world",
"boo!",
"2").stream())
.stream()
.toList();
System.out.println(list);
List<Integer> right = list.stream()
.map(t -> t._2())
.collect(java.util.stream.Collectors.toList());
assertThat(right,
hasItem(100));
assertThat(right,
hasItem(200));
assertThat(right,
hasItem(300));
assertThat(right,
hasItem(400));
List<Integer> left = list.stream()
.map(t -> t._1())
.collect(java.util.stream.Collectors.toList());
assertThat(Arrays.asList(1,
2,
3,
4),
hasItem(left.get(0)));
List<Character> three = list.stream()
.map(t -> t._3())
.collect(java.util.stream.Collectors.toList());
assertThat(Arrays.asList('a',
'b',
'c',
'd'),
hasItem(three.get(0)));
List<String> four = list.stream()
.map(t -> t._4())
.collect(java.util.stream.Collectors.toList());
assertThat(Arrays.asList("hello",
"world",
"boo!",
"2"),
hasItem(four.get(0)));
}
@Test
public void testIntersperseNoOrder() {
assertThat((of(1,
2,
3).intersperse(0)).stream()
.toList(),
hasItem(0));
}
}
|
package net.bambooslips.demo.jpa.service.Impl;
import net.bambooslips.demo.exception.CompetitionEntireNotFoundException;
import net.bambooslips.demo.exception.LegalRepresentativeNotFoundException;
import net.bambooslips.demo.exception.PostNotFoundException;
import net.bambooslips.demo.jpa.model.CompetitionEntire;
import net.bambooslips.demo.jpa.model.LegalRepresentative;
import net.bambooslips.demo.jpa.model.UnitEssential;
import net.bambooslips.demo.jpa.repository.CompetitionEntireRepository;
import net.bambooslips.demo.jpa.repository.LegalRepresentativeRepository;
import net.bambooslips.demo.jpa.service.CompetitionEntireService;
import net.bambooslips.demo.jpa.service.LegalRepresentativeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.List;
/**
* Created by Administrator on 2017/4/21.
*/
@Service
public class LegalRepresentativeServiceImpl implements LegalRepresentativeService{
private static final Logger LOG = LoggerFactory.getLogger(LegalRepresentativeServiceImpl.class);
@Resource
private LegalRepresentativeRepository legalRepresentativeRepository;
@Transactional
@Override
public Long create(LegalRepresentative legalRepresentative) {
LOG.debug("Creating a new legalRepresentative with information: " + legalRepresentative);
LegalRepresentative result = legalRepresentativeRepository.save(legalRepresentative);
if(result != null){
return legalRepresentative.getLegalId();
}
return null;
}
/**
* 更新作品状态
* @param updated
* @return
* @throws LegalRepresentativeNotFoundException
*/
@Transactional(rollbackFor = LegalRepresentativeNotFoundException.class)
@Override
public LegalRepresentative update(LegalRepresentative updated) throws LegalRepresentativeNotFoundException {
LOG.debug("Updating LegalRepresentative with information: " + updated);
LegalRepresentative legalRepresentative = legalRepresentativeRepository.findOne(updated.getLegalId());
if (legalRepresentative == null) {
LOG.debug("No post found with id: " + updated.getLegalId());
throw new PostNotFoundException("Post "+updated.getLegalId()+" not found.");
}
legalRepresentative.update(updated);
return legalRepresentative;
}
@Transactional(readOnly = true)
@Override
public Long findByEntireId(Long entireId) {
LOG.debug("Finding legalRepresentative by id: " + entireId);
LegalRepresentative legalRepresentative = legalRepresentativeRepository.findByEntireId(entireId);
if (legalRepresentative !=null){
Long legalId = legalRepresentative.getLegalId();
return legalId;
}else {
return null;
}
}
@Transactional(readOnly = true)
@Override
public LegalRepresentative findListByEntireId(Long entireId) {
LOG.debug("Finding legalRepresentative by id: " + entireId);
LegalRepresentative legalRepresentative = legalRepresentativeRepository.findByEntireId(entireId);
return legalRepresentative;
}
@Override
public LegalRepresentative delete(Long id) {
return null;
}
}
|
#!/bin/bash
# credit: https://gist.github.com/oneohthree/f528c7ae1e701ad990e6
function slugify () {
echo "$1" | iconv -t ascii//TRANSLIT | sed -r s/[^a-zA-Z0-9]+/-/g | sed -r s/^-+\|-+$//g | tr '[:upper:]' '[:lower:]'
}
title="${1:-'title'}"
slug="$(slugify "$title")"
folder="./content/posts/$(date +%F)--$slug"
# echo "title: $title"
# echo "slug: $slug"
# echo "folder: $folder"
if [ -d "$folder" ]; then
printf "\\nWARNING: Post already exists: \"%s\"\\n\\n" "$title"
printf "To delete current post: \\n rm -rf %s\\n\\n" "$folder"
exit -1
fi
if [ "" != "$2" ]; then
subtitle="$2"
else
read -rp "Enter post subtitle: " subtitle
fi
if [ "" != "$3" ]; then
category="$3"
else
read -rp "Enter post category: " category
fi
if [ "" != "$4" ]; then
tags="$4"
else
read -rp "Enter post tags (comma delimited): " tags
fi
mkdir "$folder"
cat << EOF > "$folder/index.md"
---
title: "$title"
subTitle: $subtitle
date: $(date +%F)
modified: null
tags: [$tags]
category: $category
cover: null
---
# $title
EOF
printf "\\nDone: Post created at %s/index.md\\n\\n" "$folder"
|
#!/bin/bash
# Copyright 2020 Xilinx 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.
XCLBIN_URL="https://www.xilinx.com/bin/public/openDownload?filename=U50_xclbins_1_3_0.tar.gz"
XCLBIN_INSTALLER="/tmp/xclbins.tar.gz"
INSTALLER=tar
INSTALL_PATH=/
wget $XCLBIN_URL -O $XCLBIN_INSTALLER && sudo ${INSTALLER} -xzf $XCLBIN_INSTALLER --directory $INSTALL_PATH && rm $XCLBIN_INSTALLER
XCLBIN_URL="https://www.xilinx.com/bin/public/openDownload?filename=U50-V3ME_xclbins_1_3_0.tar.gz"
XCLBIN_INSTALLER="/tmp/xclbins.tar.gz"
INSTALLER=tar
INSTALL_PATH=/
wget $XCLBIN_URL -O $XCLBIN_INSTALLER && sudo ${INSTALLER} -xzf $XCLBIN_INSTALLER --directory $INSTALL_PATH && rm $XCLBIN_INSTALLER
echo "Alveo U50 XCLBINS have beein installed to /opt/xilinx/overlaybins/"
echo "You may need to copy them or link them to /usr/lib/dpu.xclbin"
|
<table>
<tr>
<th>Name</th>
<th>Age</th>
<th>Location</th>
</tr>
<tr>
<td>John</td>
<td>30</td>
<td>New York</td>
</tr>
<tr>
<td>Mary</td>
<td>25</td>
<td>Chicago</td>
</tr>
</table> |
<reponame>wolfchinaliu/gameCenter
package weixin.mailmanager.Service.impl;
import org.jeecgframework.core.common.service.impl.CommonServiceImpl;
import weixin.mailmanager.Service.MailManagerServiceI;
import weixin.mailmanager.entity.OperationData;
import java.io.Serializable;
/**
* Created by aa on 2016/6/6.
*/
public class MailManagerServiceImpl extends CommonServiceImpl implements MailManagerServiceI {
public <T> Serializable save(T entity) {
Serializable t = super.save(entity);
//执行新增操作配置的sql增强
this.doAddSql((OperationData)entity);
return t;
}
/**
* 默认按钮-sql增强-新增操作
* @param id
* @return
*/
public boolean doAddSql(OperationData t){
return true;
}
}
|
<reponame>th3r3alandr3/Sudoku
import javax.swing.JTextField;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.PlainDocument;
public class JTextFieldLimit extends JTextField {
private int limit;
JTextFieldLimit(int limit) {
super();
this.limit = limit;
}
@Override
protected Document createDefaultModel() {
return new LimitDocument();
}
private class LimitDocument extends PlainDocument {
@Override
public void insertString(int offset, String str, AttributeSet attr) throws BadLocationException {
if (str == null) {
return;
}
if ((getLength() + str.length()) <= limit && str.charAt(0) >= 49 && str.charAt(0) <= 57) {
super.insertString(offset, str, attr);
}
}
}
}
|
#! /bin/bash
usage() {
echo "
build <options>
-b build code
-i install as a product in $PRODUCTDIR/codetools/$VERSION
-v VERSION
-d PRODUCTDIR
-h print this help
"
}
build() {
echo "
This product is only scripts, so does not ned building
"
return 1
}
install() {
local RC
local DD=$PRODUCTDIR/$PRODUCT/$VERSION
local DU=$DD/ups
local DV=$PRODUCTDIR/$PRODUCT/${VERSION}.version
echo "Will install in $DD"
if ! mkdir -p $DD ; then
echo "ERROR - failed to make release dir $DD"
return 1
fi
mkdir -p $DD
mkdir -p $DU
mkdir -p $DV
# install UPS files
cat $SOURCEDIR/prd/NULL \
| sed 's/REPLACE_VERSION/'$VERSION'/' \
> $DV/NULL
cat $SOURCEDIR/prd/codetools.table \
| sed 's/REPLACE_VERSION/'$VERSION'/' \
> $DD/ups/codetools.table
# install scripts
cp -r $SOURCEDIR/bin $SOURCEDIR/clangtools_utilities $DD
RC=$?
if [ $RC -ne 0 ]; then
echo "ERROR - failed to cp scripts from $SOURCEDIR to $DD"
return 1
fi
return 0
}
# ********** main **********
PRODUCT=codetools
THISDIR=`dirname $(readlink -f $0)`
SOURCEDIR=`readlink -f $THISDIR/..`
DOBUILD=""
DOINSTALL=""
PRODUCTDIR="$PWD"
VERSION="v0"
while getopts bd:iv:h OPT; do
case $OPT in
b)
export DOBUILD=true
;;
d)
export PRODUCTDIR=$OPTARG
;;
i)
export DOINSTALL=true
;;
v)
export VERSION=$OPTARG
;;
h)
usage
exit 0
;;
*)
echo unknown option, exiting
usage
exit 1
;;
esac
done
if [[ -z "$DOBUILD" && -z "$DOINSTALL" ]]; then
echo "ERROR - no actions requested"
usage
exit 2
fi
if [ -n "$DOBUILD" ]; then
if ! build ; then
exit 3
fi
fi
if [ -n "$DOINSTALL" ]; then
if ! install ; then
exit 4
fi
fi
echo "Done"
|
#!/usr/bin/env python3
import argparse
import math
from collections import defaultdict
from src.backend.common.nttxtraction import *
from src.backend.common.dbmanager import DBManager
import numpy as np
logger = logging.getLogger(__name__)
def main():
parser = argparse.ArgumentParser(description="Script to calculate the monthly response rate for the old AFP")
parser.add_argument("-N", "--db-name", metavar="db_name", dest="db_name", type=str)
parser.add_argument("-U", "--db-user", metavar="db_user", dest="db_user", type=str)
parser.add_argument("-P", "--db-password", metavar="db_password", dest="db_password", type=str, default="")
parser.add_argument("-H", "--db-host", metavar="db_host", dest="db_host", type=str)
args = parser.parse_args()
db_manager = DBManager(dbname=args.db_name, user=args.db_user, password=args.db_password, host=args.db_host)
num_years_per_month = [10, 10, 10, 11, 11, 10, 10, 11, 10, 11, 10, 11]
monthly_submissions = defaultdict(lambda: defaultdict(int))
for year in range(2008, 2020, 1):
for month in range(1, 13, 1):
monthly_submissions[month][year] = db_manager.get_num_submissions_year_month_old_afp(year, month)
month_totals = [sum(months_counts.values()) for months_counts in monthly_submissions.values()]
means = [tot / n_years for tot, n_years in zip(month_totals, num_years_per_month)]
sumsq = [sum([(month_count - means[month])**2 for month_count in months_counts.values() if month_count > 0]) for
month, months_counts in enumerate(monthly_submissions.values())]
deviations = [math.sqrt(ss / (n - 1)) for ss, n in zip(sumsq, num_years_per_month)]
print(means)
print(deviations)
print([min([m_count for m_count in months_counts.values() if m_count > 0]) for months_counts in monthly_submissions.values()])
print([max(months_counts.values()) for months_counts in monthly_submissions.values()])
if __name__ == '__main__':
main()
|
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.repoTemplate = void 0;
var repoTemplate = {
"viewBox": "0 0 14 16",
"children": [{
"name": "path",
"attribs": {
"fill-rule": "evenodd",
"d": "M12 8V1c0-.55-.45-1-1-1H1C.45 0 0 .45 0 1v12c0 .55.45 1 1 1h2v2l1.5-1.5L6 16v-4H3v1H1v-2h7v-1H2V1h9v7h1zM4 2H3v1h1V2zM3 4h1v1H3V4zm1 2H3v1h1V6zm0 3H3V8h1v1zm6 3H8v2h2v2h2v-2h2v-2h-2v-2h-2v2z"
},
"children": []
}],
"attribs": {}
};
exports.repoTemplate = repoTemplate; |
#!/bin/bash
kubectl exec -n spire spire-server-0 -- \
/opt/spire/bin/spire-server entry create \
-registrationUDSPath /run/spire/sockets/registration.sock \
-spiffeID spiffe://example.org/ns/spire/sa/spire-agent \
-selector k8s_sat:cluster:demo-cluster \
-selector k8s_sat:agent_ns:spire \
-selector k8s_sat:agent_sa:spire-agent \
-node
kubectl exec -n spire spire-server-0 -- \
/opt/spire/bin/spire-server entry create \
-registrationUDSPath /run/spire/sockets/registration.sock \
-spiffeID spiffe://example.org/ns/default/sa/default \
-parentID spiffe://example.org/ns/spire/sa/spire-agent \
-selector k8s:ns:default \
-selector k8s:sa:default
kubectl exec -n spire spire-server-0 -- \
/opt/spire/bin/spire-server entry create \
-registrationUDSPath /run/spire/sockets/registration.sock \
-spiffeID spiffe://example.org/ns/kafkaconsumer/sa/default \
-parentID spiffe://example.org/ns/spire/sa/spire-agent \
-selector k8s:ns:kafkaconsumer \
-selector k8s:sa:default
kubectl exec -n spire spire-server-0 -- \
/opt/spire/bin/spire-server entry create \
-registrationUDSPath /run/spire/sockets/registration.sock \
-spiffeID spiffe://example.org/ns/default/sa/default \
-parentID spiffe://example.org/ns/spire/sa/spire-agent \
-selector k8s:ns:default \
-selector k8s:sa:default
kubectl exec -n spire spire-server-0 -- \
/opt/spire/bin/spire-server entry create \
-registrationUDSPath /run/spire/sockets/registration.sock \
-spiffeID spiffe://example.org/ns/sslfactory/sa/sslfactory \
-parentID spiffe://example.org/ns/spire/sa/spire-agent \
-selector k8s:ns:sslfactory \
-selector k8s:sa:sslfactory
kubectl exec -n spire spire-server-0 -- \
/opt/spire/bin/spire-server entry create \
-registrationUDSPath /run/spire/sockets/registration.sock \
-spiffeID spiffe://example.org/ns/sslfactory/sa/consumer \
-parentID spiffe://example.org/ns/spire/sa/spire-agent \
-selector k8s:ns:sslfactory \
-selector k8s:sa:sslfactory
kubectl exec -n spire spire-server-0 -- \
/opt/spire/bin/spire-server entry create \
-registrationUDSPath /run/spire/sockets/registration.sock \
-spiffeID spiffe://example.org/ns/sslfactory/sa/producer \
-parentID spiffe://example.org/ns/spire/sa/spire-agent \
-selector k8s:ns:sslfactory \
-selector k8s:sa:sslfactory
kubectl exec -n spire spire-server-0 -- \
/opt/spire/bin/spire-server entry create \
-registrationUDSPath /run/spire/sockets/registration.sock \
-spiffeID spiffe://example.org/ns/kafka/sa/default \
-parentID spiffe://example.org/ns/spire/sa/spire-agent \
-selector k8s:ns:kafka \
-selector k8s:sa:default |
/**
* @license
* Copyright Akveo. All Rights Reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*/
import { Component } from '@angular/core';
import { NbThemeService } from '@nebular/theme';
@Component({
selector: 'ngd-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.scss'],
})
export class NgdHomeComponent {
features = [
{
title: 'Introduction',
description: 'Install from scratch or based on ngx-admin',
icon: 'assets/img/intro.svg',
link: 'docs',
},
{
title: 'Guides',
description: 'Theme System configuration, customisation and other articles',
icon: 'assets/img/guides.svg',
link: 'docs/guides/install-based-on-starter-kit',
},
{
title: 'Components',
description: 'Native Angular components with configurable styles',
icon: 'assets/img/components.svg',
link: 'docs/components/components-overview',
},
{
title: 'Theme System',
description: `Three built-in themes & hundreds of variables to create your own.
With hot-reload out of the box`,
icon: 'assets/img/themes.svg',
link: 'docs/guides/theme-system',
},
{
title: 'Auth',
description: 'Authentication layer with configurable Strategies',
icon: 'assets/img/auth.svg',
link: 'docs/auth/introduction',
},
{
title: 'Security',
description: 'ACL list with helpful directives',
icon: 'assets/img/security.svg',
link: 'docs/security/introduction',
},
];
advantages = [
{
title: 'Modular',
description: `Each feature is a separate npm module. Use only what you need.`,
},
{
title: 'Native',
description: `Components are written in pure Angular with no 3rd-party dependencies.`,
},
{
title: 'Open',
description: `Modules source code is free and available under MIT licence.`,
},
{
title: 'Extendable',
description: `Can be used in a mix with any UI library.`,
},
];
constructor(themeService: NbThemeService) {
themeService.changeTheme('docs-home');
}
}
|
"""
__init__ creates a Blueprint component for use in the views and error
files which makes it easier to make different URLs
Returns:
main is returned as the Blueprint Component
"""
from flask import Blueprint
# pylint: disable=invalid-name
main = Blueprint('main', __name__)
from . import views, errors
|
<reponame>wangmengcn/JavaLearning
package com.eclipsesv.controller;
import com.eclipsesv.model.Member;
import com.eclipsesv.model.MemberRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.validation.Valid;
/**
* Created by eclipse on 16/8/24.
*/
@Controller
@RequestMapping("/")
public class MemberController {
@Autowired
private MemberRepository repository;
@RequestMapping(method = RequestMethod.GET)
public String registerUser(ModelMap model){
Member member = new Member();
model.addAttribute("member",member);
return "group";
}
@RequestMapping(method = RequestMethod.POST)
public String newUser(@Valid Member member, BindingResult result, ModelMap model){
Member olduser = repository.findByusername(member.getUsername());
if(olduser!=null){
return "login";
}
repository.save(member);
System.out.println(member.getId());
model.addAttribute("username",member.getUsername());
return "chatroom";
}
@RequestMapping(method = RequestMethod.POST,value = "/login")
public String loginUser(@Valid Member member, BindingResult result, ModelMap model){
Member currentUser = repository.findByusername(member.getUsername());
System.out.println(currentUser.getId());
if(currentUser.getPassword().equals(member.getPassword())){
model.addAttribute("username",member.getUsername());
return "chatroom";
}
return "login";
}
}
|
#!/bin/bash
# Codesign and build a dmg file
if [ $# -lt 1 ]; then
echo "usage: $0 <app_path>"
exit 1
fi
SRC_APP_PATH="${1}"
APP_NAME=`basename "${SRC_APP_PATH}"`
if [ "${APP_NAME}" != "JoyKeyMapper.app" ]; then
echo "error: App name must be 'JoyKeyMapper.app'"
exit 2
fi
VERSION=`git describe --tags --abbrev=0 --match "v*.*.*"`
if [ "${VERSION}" == "" ]; then
echo "error: version tag not found"
exit 3
fi
echo "Source app path: ${SRC_APP_PATH}"
PROJECT_ROOT="`dirname $0`/.."
TMP_DIR="${PROJECT_ROOT}/dmg"
APP_PATH="${TMP_DIR}/JoyKeyMapper.app"
LAUNCHER_ENTITLEMENTS="${PROJECT_ROOT}/JoyKeyMapperLauncher/JoyKeyMapperLauncher.entitlements"
APP_ENTITLEMENTS="${PROJECT_ROOT}/JoyKeyMapper/JoyKeyMapper.entitlements"
DMG_PATH="${TMP_DIR}/JoyKeyMapper-${VERSION}.dmg"
BUNDLE_ID="jp.0spec.JoyKeyMapper"
if [ "${APP_API_USER}" == "" ]; then
read -p "App Connect User: " APP_API_USER
fi
if [ "${APP_API_ISSUER}" == "" ]; then
read -p "App Connect Issuer: " APP_API_ISSUER
fi
if [ "${APP_API_KEY_ID}" == "" ]; then
read -p "App Connect Key ID: " APP_API_KEY_ID
fi
# Copy App
echo "Copying app..."
rm -rf "${TMP_DIR}"
mkdir "${TMP_DIR}"
cp -Rp "${SRC_APP_PATH}" "${APP_PATH}"
# Verify
echo "Verifying..."
codesign -dv --verbose=4 "${APP_PATH}"
if [ $? -ne 0 ]; then
echo "error: The app is not correctly signed"
exit 4
fi
# Create a dmg file
echo "Creating a dmg file at ${DMG_PATH}"
dmgbuild -s "${PROJECT_ROOT}/scripts/dmg_settings.py" JoyKeyMapper "${DMG_PATH}"
if [ $? -ne 0 ]; then
echo "error: Failed to build a dmg file"
exit 5
fi
echo "Code signing to the dmg file..."
codesign -f -o runtime --timestamp -s "Developer ID Application" "${DMG_PATH}"
if [ $? -ne 0 ]; then
echo "error: Failed to sign to the dmg file"
exit 6
fi
# Notarize the dmg file
echo "Notarizing the dmg file..."
RESULT=`xcrun altool --notarize-app \
--primary-bundle-id "${BUNDLE_ID}" \
-u "${APP_API_USER}" \
--apiKey "${APP_API_KEY_ID}" \
--apiIssuer "${APP_API_ISSUER}" \
-t osx -f "${DMG_PATH}"`
echo "${RESULT}"
REQUEST_UUID=`echo "${RESULT}" | grep "RequestUUID = " | sed "s/RequestUUID = \(.*\)$/\1/"`
if [ "${REQUEST_UUID}" == "" ]; then
echo "error: Failed to notarize the dmg file"
exit 7
fi
echo "Waiting for the approval..."
echo "It would take few minutes"
RETRY=20
APPROVED=false
for i in `seq ${RETRY}`; do
sleep 30
RESULT=`xcrun altool --notarization-history 0 \
-u "${APP_API_USER}" \
--apiKey "${APP_API_KEY_ID}" \
--apiIssuer "${APP_API_ISSUER}"`
STATUS=`echo "${RESULT}" | grep "${REQUEST_UUID}" | cut -f 5- -d " "`
if `echo "${STATUS}" | grep "Package Approved" > /dev/null`; then
APPROVED=true
break
elif [ "${STATUS}" == "" ]; then
echo "waiting for updating the notarization history..."
elif `echo "${STATUS}" | grep "in progress" > /dev/null`; then
echo "in progress..."
else
echo "${RESULT}"
echo "error: Invalid notarization status: ${STATUS}"
exit 8
fi
done
echo "${RESULT}"
if [ ${APPROVED} = false ] ; then
echo "error: Approval timeout"
exit 9
fi
# Staple a ticket to the dmg file
xcrun stapler staple "${DMG_PATH}"
if [ $? -ne 0 ]; then
echo "error: Failed to staple a ticket"
exit 10
fi
echo "Done."
|
<gh_stars>10-100
// Autogenerated from library/elements.i
package ideal.library.elements;
public interface function2<R, A0, A1> extends procedure2<R, A0, A1>, deeply_immutable_data { }
|
#! /bin/bash
npm install
npm run build:demo
docker build -t mathijsblok/ngx-alerts-demo:latest .
rm -rf ./node_modules
rm -rf ./dist
docker-compose up -d
|
<reponame>darddan/libelektra<gh_stars>0
"use strict";
module.exports = function(
$stateProvider,
$urlRouterProvider,
$locationProvider,
webStructure
) {
var self = this;
// configure html5mode for URLs (no #)
$locationProvider.html5Mode({
enabled: true
});
// configure default route
$urlRouterProvider.when("", "/home");
$urlRouterProvider.when("/", "/home");
$urlRouterProvider.otherwise("/error/404");
// configure application states
$stateProvider
.state("main", {
abstract: true,
templateUrl: "pages/main/template.html",
controller: "MainController as ctrl"
})
.state("main.error", {
abstract: true,
url: "/error",
templateUrl: "pages/main/error/template.html",
ncyBreadcrumb: {
label: "APP.BREADCRUMBS.MAIN.ERROR",
parent: "main.home"
}
})
.state("main.error.404", {
url: "/404",
templateUrl: "pages/main/error/404.html",
ncyBreadcrumb: {
label: "APP.BREADCRUMBS.MAIN.ERROR.404",
parent: "main.error"
}
})
.state("main.auth", {
abstract: true,
url: "/auth",
templateUrl: "pages/main/auth/template.html",
ncyBreadcrumb: {
parent: "main.home"
}
})
.state("main.auth.login", {
url: "/login",
templateUrl: "pages/main/auth/login.html",
controller: "AuthLoginController as ctrl",
ncyBreadcrumb: {
label: "APP.BREADCRUMBS.MAIN.AUTH.LOGIN",
parent: "main.auth"
}
})
.state("main.auth.logout", {
url: "/logout",
controller: [
"$rootScope",
"$auth",
"$state",
"Notification",
function($rootScope, $auth, $state, Notification) {
$auth.logout().then(function() {
// Flip authenticated to false so that we no longer
// show UI elements dependant on the user being logged in
$rootScope.authenticated = false;
$rootScope.currentUser = {};
Notification.success({
title: "APP.AUTH.LOGOUT.NOTIFICATION.HEADER",
message: "APP.AUTH.LOGOUT.NOTIFICATION.MESSAGE.SUCCESS"
});
$state.go("main.home");
});
}
]
})
.state("main.auth.register", {
url: "/register",
templateUrl: "pages/main/auth/registration.html",
controller: "AuthRegistrationController as ctrl",
ncyBreadcrumb: {
label: "APP.BREADCRUMBS.MAIN.AUTH.REGISTER",
parent: "main.auth"
}
})
.state("main.home", {
url: "/home",
templateUrl: "pages/main/website/home.html",
controller: "WebsiteHomeController as ctrl",
ncyBreadcrumb: {
label: "APP.BREADCRUMBS.MAIN.HOME"
}
})
.state("main.news", {
url: "/news/:file",
templateUrl: "pages/main/website/news.html",
controller: "WebsiteListfilesController as ctrl",
params: {
file: null
},
resolve: {
files: [
"news",
function(news) {
return news;
}
],
currentFile: [
"$q",
"$timeout",
"$state",
"$stateParams",
"WebsiteService",
"files",
function($q, $timeout, $state, $stateParams, WebsiteService, files) {
var deferred = $q.defer();
$timeout(function() {
if ($stateParams.file === null) {
$state.go("main.news", {
file: files.filter(function(elem) {
return elem.type === "file";
})[0].slug
});
deferred.reject();
} else {
var filtered = files.filter(function(elem) {
return (
elem.type === "file" && elem.slug === $stateParams.file
);
});
if (filtered.length === 0) {
$state.go("main.news", {
file: files[0].slug
});
deferred.reject();
} else {
WebsiteService.loadFile(filtered[0].file).then(function(
data
) {
var file = filtered[0];
file.content = data;
deferred.resolve(file);
});
}
}
});
return deferred.promise;
}
]
},
ncyBreadcrumb: {
label: "APP.BREADCRUMBS.MAIN.NEWS",
parent: "main.home"
}
})
.state("main.dyn", {
abstract: true,
template: "<div ui-view></div>",
ncyBreadcrumb: {
parent: "main.home"
}
})
.state("main.account", {
url: "/account",
templateUrl: "pages/main/users/details.html",
controller: "UserDetailsController as ctrl",
params: {
username: "",
useAuthUser: true
},
resolve: {
user: [
"$stateParams",
"UserService",
function($stateParams, UserService) {
return UserService.get("", $stateParams.useAuthUser);
}
]
},
ncyBreadcrumb: {
label: "APP.BREADCRUMBS.MAIN.ACCOUNT",
parent: "main.home"
}
})
.state("main.conversion", {
url: "/conversion",
templateUrl: "pages/main/website/conversion.html",
controller: "WebsiteConversionController as ctrl",
resolve: {
formats: [
"EntryService",
function(EntryService) {
return EntryService.loadAvailableFormats();
}
]
},
ncyBreadcrumb: {
label: "APP.BREADCRUMBS.MAIN.CONVERSION",
parent: "main.home"
}
})
.state("main.entries", {
abstract: true,
url: "/entries",
templateUrl: "pages/main/entries/template.html",
ncyBreadcrumb: {
parent: "main.home"
}
})
.state("main.entries.search", {
url: "/search",
templateUrl: "pages/main/entries/search.html",
controller: "EntrySearchController as ctrl",
ncyBreadcrumb: {
label: "APP.BREADCRUMBS.MAIN.ENTRIES.SEARCH",
parent: "main.entries"
}
})
.state("main.entries.details", {
url: "/details/:entry",
templateUrl: "pages/main/entries/details.html",
controller: "EntryDetailsController as ctrl",
params: {
entry: ""
},
resolve: {
entry: [
"$stateParams",
"EntryService",
function($stateParams, EntryService) {
return EntryService.get($stateParams.entry);
}
]
},
ncyBreadcrumb: {
label: "APP.BREADCRUMBS.MAIN.ENTRIES.DETAILS",
parent: "main.entries.search"
}
})
.state("main.entries.edit", {
url: "/edit/:entry",
templateUrl: "pages/main/entries/edit.html",
controller: "EntryEditController as ctrl",
params: {
entry: ""
},
resolve: {
formats: [
"EntryService",
function(EntryService) {
return EntryService.loadAvailableFormats();
}
],
typeaheads: [
"EntryService",
function(EntryService) {
return EntryService.loadAvailableTypeaheads();
}
],
entry: [
"$stateParams",
"EntryService",
function($stateParams, EntryService) {
return EntryService.get($stateParams.entry);
}
],
hasPermission: [
"$rootScope",
"entry",
"$q",
function($rootScope, entry, $q) {
var deferred = $q.defer();
if (
$rootScope.currentUser &&
($rootScope.currentUser.rank >= 50 ||
$rootScope.currentUser.username === entry.meta.author)
) {
deferred.resolve(true);
} else {
deferred.reject(false);
}
return deferred.promise;
}
]
},
data: {
// rank: 50 // this check has to be done by the resolver as well
},
ncyBreadcrumb: {
label: "APP.BREADCRUMBS.MAIN.ENTRIES.EDIT",
parent: "main.entries.details"
}
})
.state("main.entries.create", {
url: "/create",
templateUrl: "pages/main/entries/create.html",
controller: "EntryCreateController as ctrl",
resolve: {
formats: [
"EntryService",
function(EntryService) {
return EntryService.loadAvailableFormats();
}
],
typeaheads: [
"EntryService",
function(EntryService) {
return EntryService.loadAvailableTypeaheads();
}
]
},
data: {
rank: 10
},
ncyBreadcrumb: {
label: "APP.BREADCRUMBS.MAIN.ENTRIES.CREATE",
parent: "main.entries"
}
})
.state("main.users", {
abstract: true,
url: "/users",
templateUrl: "pages/main/users/template.html",
ncyBreadcrumb: {
parent: "main.home"
}
})
.state("main.users.search", {
url: "/search",
templateUrl: "pages/main/users/search.html",
controller: "UserSearchController as ctrl",
data: {
rank: 100
},
ncyBreadcrumb: {
label: "APP.BREADCRUMBS.MAIN.USERS.SEARCH",
parent: "main.users"
}
})
.state("main.users.details", {
url: "/details/:username",
templateUrl: "pages/main/users/details.html",
controller: "UserDetailsController as ctrl",
params: {
username: "",
useAuthUser: false
},
data: {
rank: 100
},
resolve: {
user: [
"$stateParams",
"UserService",
function($stateParams, UserService) {
return UserService.get($stateParams.username);
}
]
},
ncyBreadcrumb: {
label: "APP.BREADCRUMBS.MAIN.USERS.DETAILS",
parent: "main.users"
}
});
/* CONFIGURE DYNAMIC PAGES */
// read the structure file and handle entries
webStructure.forEach(function(entry) {
consumeEntry(entry);
});
// main parse function
function consumeEntry(entry) {
switch (entry.type) {
case "submenu":
entry.children.forEach(function(child) {
consumeEntry(child);
});
break;
case "listfiles":
$stateProvider.state("main.dyn." + entry.ref, {
url: "/" + entry.ref + "/:file",
templateUrl: "pages/main/website/listfiles.html",
controller: "WebsiteListfilesController as ctrl",
params: {
file: null
},
data: {
name: entry.name,
ref: entry.ref
},
resolve: {
files: [
function() {
return entry.children;
}
],
currentFile: [
"$q",
"$timeout",
"$state",
"$stateParams",
"WebsiteService",
"files",
function(
$q,
$timeout,
$state,
$stateParams,
WebsiteService,
files
) {
var deferred = $q.defer();
$timeout(function() {
if ($stateParams.file === null) {
$state.go("main.dyn." + entry.ref, {
file: files.filter(function(elem) {
return elem.type === "file";
})[0].slug
});
deferred.reject();
} else {
var filtered = files.filter(function(elem) {
return (
elem.type === "file" && elem.slug === $stateParams.file
);
});
if (filtered.length === 0) {
$state.go("main.dyn." + entry.ref, {
file: files.filter(function(elem) {
return elem.type === "file";
})[0].slug
});
deferred.reject();
} else {
WebsiteService.loadFile(filtered[0].options.path).then(
function(data) {
var file = filtered[0];
file.content = data;
deferred.resolve(file);
}
);
}
}
});
return deferred.promise;
}
]
},
ncyBreadcrumb: {
label: "APP.BREADCRUMBS.MAIN.DYN." + entry.ref.toUpperCase(),
parent: "main.dyn"
}
});
break;
default:
break;
}
}
};
|
#!/bin/bash
# Module specific variables go here
# Files: file=/path/to/file
# Arrays: declare -a array_name
# Strings: foo="bar"
# Integers: x=9
###############################################
# Bootstrapping environment setup
###############################################
# Get our working directory
cwd="$(pwd)"
# Define our bootstrapper location
bootstrap="${cwd}/tools/bootstrap.sh"
# Bail if it cannot be found
if [ ! -f ${bootstrap} ]; then
echo "Unable to locate bootstrap; ${bootstrap}" && exit 1
fi
# Load our bootstrap
source ${bootstrap}
###############################################
# Metrics start
###############################################
# Get EPOCH
s_epoch="$(gen_epoch)"
# Create a timestamp
timestamp="$(gen_date)"
# Whos is calling? 0 = singular, 1 is as group
caller=$(ps $PPID | grep -c stigadm)
###############################################
# Perform restoration
###############################################
# If ${restore} = 1 go to restoration mode
if [ ${restore} -eq 1 ]; then
report "Not yet implemented" && exit 1
fi
###############################################
# STIG validation/remediation
###############################################
# Module specific validation code should go here
# Errors should go in ${errors[@]} array (which on remediation get handled)
# All inspected items should go in ${inspected[@]} array
errors=("${stigid}")
# If ${change} = 1
#if [ ${change} -eq 1 ]; then
# Create the backup env
#backup_setup_env "${backup_path}"
# Create a backup (configuration output, file/folde permissions output etc
#bu_configuration "${backup_path}" "${author}" "${stigid}" "$(echo "${array_values[@]}" | tr ' ' '\n')"
#bu_file "${backup_path}" "${author}" "${stigid}" "${file}"
#if [ $? -ne 0 ]; then
# Stop, we require a backup
#report "Unable to create backup" && exit 1
#fi
# Iterate ${errors[@]}
#for error in ${errors[@]}; do
# Work to remediate ${error} should go here
#done
#fi
# Remove dupes
#inspected=( $(remove_duplicates "${inspected[@]}") )
###############################################
# Results for printable report
###############################################
# If ${#errors[@]} > 0
if [ ${#errors[@]} -gt 0 ]; then
# Set ${results} error message
#results="Failed validation" UNCOMMENT ONCE WORK COMPLETE!
results="Not yet implemented!"
fi
# Set ${results} passed message
[ ${#errors[@]} -eq 0 ] && results="Passed validation"
###############################################
# Report generation specifics
###############################################
# Apply some values expected for report footer
[ ${#errors[@]} -eq 0 ] && passed=1 || passed=0
[ ${#errors[@]} -gt 0 ] && failed=1 || failed=0
# Calculate a percentage from applied modules & errors incurred
percentage=$(percent ${passed} ${failed})
# If the caller was only independant
if [ ${caller} -eq 0 ]; then
# Show failures
[ ${#errors[@]} -gt 0 ] && print_array ${log} "errors" "${errors[@]}"
# Provide detailed results to ${log}
if [ ${verbose} -eq 1 ]; then
# Print array of failed & validated items
[ ${#inspected[@]} -gt 0 ] && print_array ${log} "validated" "${inspected[@]}"
fi
# Generate the report
report "${results}"
# Display the report
cat ${log}
else
# Since we were called from stigadm
module_header "${results}"
# Show failures
[ ${#errors[@]} -gt 0 ] && print_array ${log} "errors" "${errors[@]}"
# Provide detailed results to ${log}
if [ ${verbose} -eq 1 ]; then
# Print array of failed & validated items
[ ${#inspected[@]} -gt 0 ] && print_array ${log} "validated" "${inspected[@]}"
fi
# Finish up the module specific report
module_footer
fi
###############################################
# Return code for larger report
###############################################
# Return an error/success code (0/1)
exit ${#errors[@]}
# Date: 2018-07-18
#
# Severity: CAT-II
# Classification: UNCLASSIFIED
# STIG_ID: V0075907
# STIG_Version: SV-90587r2
# Rule_ID: UBTU-16-030820
#
# OS: Ubuntu
# Version: 16.04
# Architecture: LTS
#
# Title: The Ubuntu operating system must implement certificate status checking for multifactor authentication.
# Description: The Ubuntu operating system must implement certificate status checking for multifactor authentication.
|
import sys
import click
def choose(items):
click.echo(
"####################################################################")
for i in range(0, len(items)):
j = i + 1
click.echo(str(j) + ": " + items[i])
click.echo(
"####################################################################")
try:
selection = click.prompt("Enter your choice", type=click.INT)
return selection - 1
except click.Abort:
return 0
def exitSuccess(msg):
message(msg)
message("Exiting.")
sys.exit(0)
def message(msg):
click.echo("Message: " + msg)
def removeSpecialChars(string):
string = string.replace(".", "").replace(",", "").replace("(", "").replace(
")", "").replace("{", "").replace("}", "").replace("[", "").replace("]", "").replace(
":", "").replace(";", "").replace("'", "").replace("/", "").replace("|", "").replace(
"<", "").replace(">", "").replace("-", "").replace("_", "").replace("=", "").replace("+", "")
return string
def getRootPath(filepath):
y = -1
for x, slashes in enumerate(reversed(filepath)):
if(slashes == "\\" or slashes == "/"):
y = len(filepath) - 1 - x
break
return filepath[:1 + y]
def getTitle(filepath):
y = -1
for x, slashes in enumerate(reversed(filepath)):
if(slashes == "\\" or slashes == "/"):
y = len(filepath) - 1 - x
break
return filepath[y + 1:]
def getSearchString(movietitle):
searchStr = ""
movietitle = movietitle.replace(".", " ")
movietitle = removeSpecialChars(movietitle)
words = movietitle.split(" ")
for word in words:
try:
if(any(w.isdigit() for w in word) == True and len(word) != 1):
break
else:
searchStr += word + " "
except ValueError:
pass
searchStr = searchStr[:-1]
return searchStr
|
/*
* This software is licensed under the Apache 2 license, quoted below.
*
* Copyright (c) 1999-2021, Algorithmx 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.algorithmx.rulii.spring.script;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.EvaluationException;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.SpelCompilerMode;
import org.springframework.expression.spel.SpelParserConfiguration;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.util.Assert;
import javax.script.Bindings;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineFactory;
import javax.script.ScriptException;
import javax.script.SimpleBindings;
import javax.script.SimpleScriptContext;
import java.io.IOException;
import java.io.Reader;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class SpringElScriptEngine implements ScriptEngine {
private static final Map<String, Expression> EXPRESSION_CACHE = new ConcurrentHashMap<>();
private final ExpressionParser parser;
private ScriptContext context = new SimpleScriptContext();
public SpringElScriptEngine() {
this(new SpelParserConfiguration(SpelCompilerMode.MIXED, null));
}
public SpringElScriptEngine(SpelParserConfiguration configuration) {
super();
Assert.notNull(configuration, "configuration cannot be null");
this.parser = new SpelExpressionParser(new SpelParserConfiguration(SpelCompilerMode.MIXED, null));
}
@Override
public Object eval(String script, ScriptContext context) throws ScriptException {
return evalInternal(script, createEvaluationContext(context));
}
public Object evalInternal(String script, EvaluationContext context) throws ScriptException {
Assert.notNull(script, "script cannot be null");
Assert.notNull(context, "context cannot be null");
Expression expression = EXPRESSION_CACHE.get(script);
// Make sure to cache the expressions
if (expression == null) {
expression = parser.parseExpression(script);
EXPRESSION_CACHE.put(script, expression);
}
try {
return expression.getValue(context);
} catch (EvaluationException e) {
throw new ScriptException(e);
}
}
protected EvaluationContext createEvaluationContext(ScriptContext context) {
if (context instanceof EvaluationContext) return (EvaluationContext) context;
return new DelegatingEvaluationContext(context.getBindings(ScriptContext.GLOBAL_SCOPE));
}
@Override
public Object eval(String script, Bindings bindings) throws ScriptException {
return evalInternal(script, new DelegatingEvaluationContext(bindings));
}
@Override
public Object eval(String script) throws ScriptException {
return eval(script, new SimpleBindings());
}
@Override
public Object eval(Reader reader) throws ScriptException {
String script = readScript(reader);
return eval(script);
}
@Override
public Object eval(Reader reader, Bindings bindings) throws ScriptException {
String script = readScript(reader);
return eval(script, bindings);
}
@Override
public Object eval(Reader reader, ScriptContext context) throws ScriptException {
String script = readScript(reader);
return eval(script, context);
}
@Override
public void put(String key, Object value) {
getBindings(ScriptContext.ENGINE_SCOPE).put(key, value);
}
@Override
public Object get(String key) {
return getBindings(ScriptContext.ENGINE_SCOPE).get(key);
}
@Override
public Bindings getBindings(int scope) {
return this.context.getBindings(scope);
}
@Override
public void setBindings(Bindings bindings, int scope) {
this.context.setBindings(bindings, scope);
}
@Override
public Bindings createBindings() {
return new SimpleBindings();
}
@Override
public ScriptContext getContext() {
return context;
}
@Override
public void setContext(ScriptContext context) {
Assert.notNull(context, "context cannot be null.");
this.context = context;
}
@Override
public ScriptEngineFactory getFactory() {
return null;
}
private String readScript(Reader reader) throws ScriptException {
StringBuilder result = new StringBuilder();
char[] data = new char[4 * 1024];
int read;
try {
while ((read = reader.read(data, 0, data.length)) != -1) {
result.append(data, 0, read);
}
reader.close();
} catch (IOException e) {
throw new ScriptException(e);
}
return result.toString();
}
@Override
public String toString() {
return "SpringElScriptEngine{}";
}
}
|
<filename>com/firax/tetris/bricks/OBrick.java<gh_stars>0
package com.firax.tetris.bricks;
import java.util.ArrayList;
import java.util.List;
public class OBrick extends Brick {
private List<int[][]> brickMatrix = new ArrayList<>();
public OBrick() {
super(O_BRICK_ID);
brickMatrix.add(new int[][]{
{0, 0, 0, 0},
{0, 5, 5, 0},
{0, 5, 5, 0},
{0, 0, 0, 0}
});
}
@Override
public List<int[][]> getMatrixShapes() {
return brickMatrix;
}
}
|
/*
* Copyright (c) 2014, <NAME>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name "TwelveMonkeys" nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.twelvemonkeys.imageio.plugins.psd;
import javax.imageio.stream.ImageInputStream;
import javax.imageio.IIOException;
import java.io.IOException;
/**
* PSDResolutionInfo
*
* @author <a href="mailto:<EMAIL>"><NAME></a>
* @author last modified by $Author: haraldk$
* @version $Id: PSDResolutionInfo.java,v 1.0 May 2, 2008 3:58:19 PM haraldk Exp$
*/
final class PSDResolutionInfo extends PSDImageResource {
// typedef struct _ResolutionInfo
// {
// LONG hRes; /* Fixed-point number: pixels per inch */
// WORD hResUnit; /* 1=pixels per inch, 2=pixels per centimeter */
// WORD WidthUnit; /* 1=in, 2=cm, 3=pt, 4=picas, 5=columns */
// LONG vRes; /* Fixed-point number: pixels per inch */
// WORD vResUnit; /* 1=pixels per inch, 2=pixels per centimeter */
// WORD HeightUnit; /* 1=in, 2=cm, 3=pt, 4=picas, 5=columns */
// } RESOLUTIONINFO;
float hRes;
short hResUnit;
short widthUnit;
float vRes;
short vResUnit;
short heightUnit;
PSDResolutionInfo(final short pId, final ImageInputStream pInput) throws IOException {
super(pId, pInput);
}
@Override
protected void readData(ImageInputStream pInput) throws IOException {
if (size != 16) {
throw new IIOException("Resolution info length expected to be 16: " + size);
}
hRes = PSDUtil.fixedPointToFloat(pInput.readInt());
hResUnit = pInput.readShort();
widthUnit = pInput.readShort();
vRes = PSDUtil.fixedPointToFloat(pInput.readInt());
vResUnit = pInput.readShort();
heightUnit = pInput.readShort();
}
@Override
public String toString() {
StringBuilder builder = toStringBuilder();
builder.append(", hRes: ").append(hRes);
builder.append(" ");
builder.append(resUnit(hResUnit));
builder.append(", width unit: ");
builder.append(dimUnit(widthUnit));
builder.append(", vRes: ").append(vRes);
builder.append(" ");
builder.append(resUnit(vResUnit));
builder.append(", height unit: ");
builder.append(dimUnit(heightUnit));
builder.append("]");
return builder.toString();
}
private String resUnit(final short pResUnit) {
switch (pResUnit) {
case 1:
return "pixels/inch";
case 2:
return "pixels/cm";
default:
return "unknown unit " + pResUnit;
}
}
private String dimUnit(final short pUnit) {
switch (pUnit) {
case 1:
return "in";
case 2:
return "cm";
case 3:
return "pt";
case 4:
return "pica";
case 5:
return "column";
default:
return "unknown unit " + pUnit;
}
}
}
|
package com.zte.zakker.find;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.ImageView;
public class StoreDeviceChooseDetailActivity extends Activity {
private ImageView mAddShoppingCartButtonView;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.store_device_choose_detail);
mAddShoppingCartButtonView = findViewById(R.id.add_to_shopping_cart);
mAddShoppingCartButtonView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent mFragmentStore = new Intent(getApplicationContext(), ShoppingCartActivity.class);
startActivity(mFragmentStore);
}
});
}
}
|
using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(YourScript))]
public class YourScriptEditor : Editor
{
SerializedObject serializedObject;
SerializedProperty disableOnMobilePlatforms;
private void OnEnable()
{
serializedObject = new SerializedObject(target);
disableOnMobilePlatforms = serializedObject.FindProperty("disableOnMobilePlatforms");
}
public override void OnInspectorGUI()
{
serializedObject.UpdateIfRequiredOrScript();
EditorGUILayout.PropertyField(disableOnMobilePlatforms, new GUIContent("Disable On Mobile Platforms"));
serializedObject.ApplyModifiedProperties();
if (Application.isMobilePlatform && disableOnMobilePlatforms.boolValue)
{
(target as YourScript).gameObject.SetActive(false);
}
}
} |
def countDigitOnes(n: int) -> int:
count = 0
for digit in str(n):
if digit == '1':
count += 1
return count |
<gh_stars>0
package br.com.zup.mercadolivre.categoria;
import br.com.zup.mercadolivre.config.validacao.annotation.ExistsId;
import br.com.zup.mercadolivre.config.validacao.annotation.UniqueValue;
import com.fasterxml.jackson.annotation.JsonCreator;
import org.springframework.util.Assert;
import javax.persistence.EntityManager;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Positive;
public class NovaCategoriaRequest {
@NotBlank
@UniqueValue(domainClass = Categoria.class, fieldName = "nome", message = "Essa categoria já existe")
private String nome;
@Positive
@ExistsId(domainClass = Categoria.class, fieldName = "id", message = "Essa supercategoria não existe")
private Long superCategoriaId;
public NovaCategoriaRequest() {
}
@JsonCreator(mode = JsonCreator.Mode.PROPERTIES)
public NovaCategoriaRequest(String nome, Long superCategoriaId) {
this.nome = nome;
this.superCategoriaId = superCategoriaId;
}
public Categoria toModel(EntityManager entityManager){
if(superCategoriaId != null){
Categoria supercategoria = entityManager.find(Categoria.class, superCategoriaId);
Assert.notNull(superCategoriaId, "O id da supercategoria não existe");
Categoria categoria = new Categoria(nome, supercategoria);
return categoria;
}else {
Categoria categoria = new Categoria(nome);
return categoria;
}
}
}
|
def count_words(sentence):
# Split the sentence into words
words = sentence.split()
# Set initial result to 0
result = 0
# Iterate all the words
for word in words:
# Add the number of words
result += 1
# Return the result
return result
# Call the function
result = count_words("This is an example sentence")
# Print the result
print("Number of words:", result) |
import java.util.Scanner;
public class Reverse {
public static void main(String[] args){
// Declare the array
int[] num_array = new int[5];
// Get user input
Scanner scanner = new Scanner(System.in);
for (int i = 0; i < num_array.length; i++){
System.out.print("Enter an integer: ");
num_array[i] = scanner.nextInt();
}
scanner.close();
// Print the array in reverse
System.out.println("\nReversed array:");
for (int i = num_array.length - 1; i >= 0; i--){
System.out.print(num_array[i] + " ");
}
System.out.println();
}
} |
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.arrowsH = void 0;
var arrowsH = {
"viewBox": "0 0 1792 1792",
"children": [{
"name": "path",
"attribs": {
"d": "M1792 896q0 26-19 45l-256 256q-19 19-45 19t-45-19-19-45v-128h-1024v128q0 26-19 45t-45 19-45-19l-256-256q-19-19-19-45t19-45l256-256q19-19 45-19t45 19 19 45v128h1024v-128q0-26 19-45t45-19 45 19l256 256q19 19 19 45z"
}
}]
};
exports.arrowsH = arrowsH; |
package cz.metacentrum.perun.spRegistration.persistence.models;
import com.fasterxml.jackson.annotation.JsonIgnore;
import cz.metacentrum.perun.spRegistration.persistence.enums.RequestAction;
import cz.metacentrum.perun.spRegistration.persistence.enums.RequestStatus;
import org.json.JSONArray;
import org.json.JSONObject;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
/**
* Class represents request made by user. It contains all the data that needs to be stored.
* It also keeps track of the modification time.
*
* @author <NAME> <<EMAIL>>
*/
public class Request {
private Long reqId;
private Long facilityId;
private RequestStatus status;
private RequestAction action;
private Long reqUserId;
private Map<String, PerunAttribute> attributes = new HashMap<>();
private Timestamp modifiedAt;
private Long modifiedBy;
public Long getReqId() {
return reqId;
}
public void setReqId(Long reqId) {
this.reqId = reqId;
}
public Long getFacilityId() {
return facilityId;
}
public void setFacilityId(Long facilityId) {
this.facilityId = facilityId;
}
public RequestStatus getStatus() {
return status;
}
public void setStatus(RequestStatus status) {
this.status = status;
}
public RequestAction getAction() {
return action;
}
public void setAction(RequestAction action) {
this.action = action;
}
public Long getReqUserId() {
return reqUserId;
}
public void setReqUserId(Long reqUserId) {
this.reqUserId = reqUserId;
}
public Map<String, PerunAttribute> getAttributes() {
return attributes;
}
public void setAttributes(Map<String, PerunAttribute> attributes) {
this.attributes = attributes;
}
public Timestamp getModifiedAt() {
return modifiedAt;
}
public void setModifiedAt(Timestamp modifiedAt) {
this.modifiedAt = modifiedAt;
}
public Long getModifiedBy() {
return modifiedBy;
}
public void setModifiedBy(Long modifiedBy) {
this.modifiedBy = modifiedBy;
}
@JsonIgnore
public String getFacilityName() {
PerunAttribute attr = attributes.get("urn:perun:facility:attribute-def:def:serviceName");
if (attr == null) {
return null;
}
Map<String, String> value = attr.valueAsMap();
return value.get("en");
}
@JsonIgnore
public String getFacilityDescription() {
PerunAttribute attr = attributes.get("urn:perun:facility:attribute-def:def:serviceDescription");
if (attr == null) {
return null;
}
Map<String, String> value = attr.valueAsMap();
return value.get("en");
}
/**
* Convert attributes to JSON format suitable for storing into DB.
* @return JSON with attributes.
*/
@JsonIgnore
public String getAttributesAsJsonForDb() {
JSONObject obj = new JSONObject();
for (Map.Entry<String ,PerunAttribute> a: attributes.entrySet()) {
obj.put(a.getKey(), a.getValue().toJsonForDb());
}
return obj.toString();
}
/**
* Convert attributes to JSON format suitable for storing into Perun.
* @return JSON with attributes or null.
*/
@JsonIgnore
public JSONArray getAttributesAsJsonArrayForPerun() {
if (attributes == null || attributes.isEmpty()) {
return null;
}
JSONArray res = new JSONArray();
for (PerunAttribute a: attributes.values()) {
res.put(a.toJson());
}
return res;
}
/**
* Extract administrator contact from attributes
* @param attrKey name of attribute containing administrator contact
* @return Administrator contact
*/
public String getAdminContact(String attrKey) {
if (attributes == null || !attributes.containsKey(attrKey) || attributes.get(attrKey) == null) {
return null;
}
return attributes.get(attrKey).valueAsString();
}
@Override
public String toString() {
return "Request{" +
"reqId=" + reqId +
", facilityId=" + facilityId +
", status=" + status +
", action=" + action +
", reqUserId=" + reqUserId +
", attributes=" + attributes +
", modifiedAt=" + modifiedAt +
", modifiedBy=" + modifiedBy +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Request request = (Request) o;
return Objects.equals(reqId, request.reqId) &&
status == request.status &&
action == request.action &&
Objects.equals(reqUserId, request.reqUserId);
}
@Override
public int hashCode() {
long res = 31 * reqId;
res *= 31 * action.hashCode();
res *= 31 * status.hashCode();
if (facilityId!= null) res *= 31 * facilityId;
return (int) res;
}
public void updateAttributes(Map<String, PerunAttribute> attrsToUpdate, boolean clearComment) {
for (Map.Entry<String, PerunAttribute> entry: attrsToUpdate.entrySet()) {
if (this.attributes.containsKey(entry.getKey())) {
PerunAttribute old = this.attributes.get(entry.getKey());
old.setValue(entry.getValue().getValue());
if (clearComment) {
old.setComment(null);
} else {
old.setComment(entry.getValue().getComment());
}
} else {
this.attributes.put(entry.getKey(), entry.getValue());
if (clearComment) {
entry.getValue().setComment(null);
}
}
}
}
}
|
#!/usr/bin/env bash
PWD_DIR=$(pwd)
function cleanup {
cd "$PWD_DIR"
}
trap cleanup EXIT
# Feth the three required files
if ! wget --no-check-certificate https://raw.githubusercontent.com/noloader/cryptopp-cmake/master/CMakeLists.txt -O CMakeLists.txt; then
echo "CMakeLists.txt download failed"
[[ "$0" = "${BASH_SOURCE[0]}" ]] && exit 1 || return 1
fi
if ! wget --no-check-certificate https://github.com/noloader/cryptopp-cmake/blob/master/cryptopp-config.cmake -O cryptopp-config.cmake; then
echo "cryptopp-config.cmake download failed"
[[ "$0" = "${BASH_SOURCE[0]}" ]] && exit 1 || return 1
fi
# TODO: Remove this. It is for debugging changes before check-in
# cp ~/cryptopp-cmake/CMakeLists.txt $(pwd)
PWD_DIR=$(pwd)
rm -rf "$PWD_DIR/build"
mkdir -p "$PWD_DIR/build"
cd "$PWD_DIR/build"
if ! cmake ../; then
echo "cmake failed"
[[ "$0" = "${BASH_SOURCE[0]}" ]] && exit 1 || return 1
fi
if ! make -j2 -f Makefile VERBOSE=1; then
echo "make failed"
[[ "$0" = "${BASH_SOURCE[0]}" ]] && exit 1 || return 1
fi
if ! ./cryptest.exe v; then
echo "cryptest.exe v failed"
[[ "$0" = "${BASH_SOURCE[0]}" ]] && exit 1 || return 1
fi
if ! ./cryptest.exe tv all; then
echo "cryptest.exe v failed"
[[ "$0" = "${BASH_SOURCE[0]}" ]] && exit 1 || return 1
fi
# Return success
[[ "$0" = "${BASH_SOURCE[0]}" ]] && exit 0 || return 0
|
package com.telenav.osv.manager.network;
import android.content.Context;
import androidx.annotation.NonNull;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.telenav.osv.R;
import com.telenav.osv.application.PreferenceTypes;
import com.telenav.osv.data.user.datasource.UserDataSource;
import com.telenav.osv.data.user.model.User;
import com.telenav.osv.data.user.model.details.gamification.GamificationDetails;
import com.telenav.osv.data.user.model.details.gamification.GamificationLevel;
import com.telenav.osv.data.user.model.details.gamification.GamificationRank;
import com.telenav.osv.event.EventBus;
import com.telenav.osv.event.network.LoginChangedEvent;
import com.telenav.osv.http.DeleteSequenceRequest;
import com.telenav.osv.http.LeaderboardRequest;
import com.telenav.osv.http.ListPhotosRequest;
import com.telenav.osv.http.ListSequencesRequest;
import com.telenav.osv.http.ProfileRequest;
import com.telenav.osv.http.requestFilters.LeaderboardRequestFilter;
import com.telenav.osv.http.requestFilters.ListRequestFilter;
import com.telenav.osv.item.network.ApiResponse;
import com.telenav.osv.item.network.PhotoCollection;
import com.telenav.osv.item.network.TrackCollection;
import com.telenav.osv.item.network.UserCollection;
import com.telenav.osv.item.network.UserData;
import com.telenav.osv.jarvis.login.utils.LoginUtils;
import com.telenav.osv.listener.network.KVRequestResponseListener;
import com.telenav.osv.listener.network.NetworkResponseDataListener;
import com.telenav.osv.manager.network.parser.HttpResponseParser;
import com.telenav.osv.manager.network.parser.LeaderboardParser;
import com.telenav.osv.manager.network.parser.PhotoCollectionParser;
import com.telenav.osv.manager.network.parser.SequenceParser;
import com.telenav.osv.manager.network.parser.UserDataParser;
import com.telenav.osv.network.endpoint.UrlProfile;
import com.telenav.osv.utils.Log;
import com.telenav.osv.utils.Utils;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
/**
* *
* Created by Kalman on 10/6/2015.
*/
@SuppressWarnings("ResultOfMethodCallIgnored")
public class UserDataManager extends NetworkManager implements Response.ErrorListener {
public static final String SERVER_STATUS_UPLOADING = "NEW";
public static final String SERVER_STATUS_UPLOADED = "UPLOAD_FINISHED";
public static final String SERVER_STATUS_PROCESSED = "PROCESSING_FINISHED";
public static final String SERVER_STATUS_APPROVED = "APPROVED";
public static final String SERVER_STATUS_REJECTED = "REJECTED";
public static final String SERVER_STATUS_TBD = "TBD";
private static final String TAG = "UserDataManager";
private UserDataParser mUserDataParser = new UserDataParser();
private SequenceParser mUserTrackParser = new SequenceParser(factoryServerEndpointUrl);
private LeaderboardParser mLeaderboardParser = new LeaderboardParser();
private PhotoCollectionParser mPhotoCollectionParser = new PhotoCollectionParser(factoryServerEndpointUrl);
private HttpResponseParser mHttpResponseParser = new HttpResponseParser();
/**
* Container for Rx disposables which will automatically dispose them after execute.
*/
@NonNull
private CompositeDisposable compositeDisposable;
/**
* Instance for {@code UserDataSource} which represents the user repository.
*/
private UserDataSource userRepository;
public UserDataManager(Context context, UserDataSource userRepository) {
super(context);
this.userRepository = userRepository;
compositeDisposable = new CompositeDisposable();
EventBus.register(this);
VolleyLog.DEBUG = Utils.isDebugEnabled(mContext);
}
@Override
public void destroy() {
super.destroy();
}
/**
* error listener for volley
* @param error error thrown
*/
@Override
public void onErrorResponse(VolleyError error) {
try {
Log.e(TAG, "onErrorResponse" + new String(error.networkResponse.data));
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* lists a certain amount of sequences from the server from the given page
* @param listener request listener
* @param pageNumber number of the page
* @param itemsPerPage number of items per page
*/
public void listSequences(final NetworkResponseDataListener<TrackCollection> listener, int pageNumber, int itemsPerPage) {
ListSequencesRequest seqRequest = new ListSequencesRequest(factoryServerEndpointUrl.getProfileEndpoint(UrlProfile.LIST_MY_SEQUENCES),
new KVRequestResponseListener<SequenceParser, TrackCollection>(
mUserTrackParser) {
@Override
public void onSuccess(final int status,
final TrackCollection trackCollection) {
runInBackground(() -> {
listener.requestFinished(status, trackCollection);
Log.d(TAG, "listSequences: successful");
});
}
@Override
public void onFailure(final int status,
final TrackCollection trackCollection) {
runInBackground(() -> {
listener.requestFailed(status, trackCollection);
Log.d(TAG, "listSequences: successful");
});
}
}, getAccessToken(), pageNumber, itemsPerPage, LoginUtils.isLoginTypePartner(appPrefs), appPrefs.getStringPreference(PreferenceTypes.JARVIS_ACCESS_TOKEN));
seqRequest.setRetryPolicy(new DefaultRetryPolicy(3500, 5, 1f));
seqRequest.setShouldCache(false);
cancelListTasks();
mQueue.add(seqRequest);
}
/**
* deletes a sequence from the server, together with the images that it contains
* @param sequenceId online id of the sequence
* @param listener request listener
*/
public void deleteSequence(final long sequenceId, final NetworkResponseDataListener<ApiResponse> listener) {
DeleteSequenceRequest seqRequest = new DeleteSequenceRequest(factoryServerEndpointUrl.getProfileEndpoint(UrlProfile.DELETE_SEQUENCE),
new KVRequestResponseListener<HttpResponseParser, ApiResponse>(
mHttpResponseParser) {
@Override
public void onSuccess(final int status, final ApiResponse apiResponse) {
runInBackground(new Runnable() {
@Override
public void run() {
listener.requestFinished(status, apiResponse);
Log.d(TAG, "deleteSequenceRecord: " + apiResponse);
}
});
}
@Override
public void onFailure(final int status, final ApiResponse apiResponse) {
runInBackground(new Runnable() {
@Override
public void run() {
listener.requestFailed(status, apiResponse);
Log.d(TAG, "deleteSequenceRecord: " + apiResponse);
}
});
}
}, sequenceId, getAccessToken(), LoginUtils.isLoginTypePartner(appPrefs), appPrefs.getStringPreference(PreferenceTypes.JARVIS_ACCESS_TOKEN));
seqRequest.setRetryPolicy(new DefaultRetryPolicy(2500, 5, 1f));
mQueue.add(seqRequest);
}
public void getUserProfileDetails(final NetworkResponseDataListener<UserData> listener) {
compositeDisposable.clear();
Disposable disposable = userRepository
.getUser()
.subscribeOn(Schedulers.io())
.observeOn(Schedulers.io())
.subscribe(
//onSuccess
user -> {
Log.d(TAG, "getUserProfileDetails. Status: success. Message: User found. Requesting profile details");
requestUserProfileDetails(user, listener);
},
//onError
throwable -> Log.d(TAG, String.format("getUserProfileDetails. Status: error. Message: %s", throwable.getMessage())),
//onComplete
() -> {
Log.d(TAG, "getUserProfileDetails. Status: complete. Message: User not found.");
listener.requestFinished(NetworkResponseDataListener.HTTP_UNAUTHORIZED,
mUserDataParser.parse(new VolleyError(mContext.getString(R.string.not_logged_in))));
}
);
compositeDisposable.add(disposable);
}
public void getLeaderboardData(final NetworkResponseDataListener<UserCollection> listener, String date, String countryCode) {
LeaderboardRequest leaderboardRequest =
new LeaderboardRequest(factoryServerEndpointUrl.getProfileEndpoint(UrlProfile.LEADERBOARD), new KVRequestResponseListener<LeaderboardParser, UserCollection>(mLeaderboardParser) {
@Override
public void onSuccess(final int status, final UserCollection userCollection) {
runInBackground(new Runnable() {
@Override
public void run() {
listener.requestFinished(status, userCollection);
Log.d(TAG, "getLeaderboardData: success");
}
});
}
@Override
public void onFailure(final int status, final UserCollection userCollection) {
runInBackground(new Runnable() {
@Override
public void run() {
listener.requestFailed(status, userCollection);
Log.d(TAG, "getLeaderboardData: success");
}
});
}
}, date, countryCode, null, LoginUtils.isLoginTypePartner(appPrefs), appPrefs.getStringPreference(PreferenceTypes.JARVIS_ACCESS_TOKEN));
mQueue.cancelAll(new LeaderboardRequestFilter());
leaderboardRequest.setShouldCache(false);
mQueue.add(leaderboardRequest);
}
/**
* lists the details of the images in an online sequence
* @param sequenceId online sequence id
* @param listener request listener
*/
public void listImages(final long sequenceId, final NetworkResponseDataListener<PhotoCollection> listener) {
ListPhotosRequest seqRequest = new ListPhotosRequest(factoryServerEndpointUrl.getProfileEndpoint(UrlProfile.LIST_PHOTOS),
new KVRequestResponseListener<PhotoCollectionParser, PhotoCollection>(
mPhotoCollectionParser) {
@Override
public void onSuccess(final int status, final PhotoCollection photoCollection) {
runInBackground(new Runnable() {
@Override
public void run() {
listener.requestFinished(status, photoCollection);
Log.d(TAG, "listImages: success");
}
});
}
@Override
public void onFailure(final int status, final PhotoCollection photoCollection) {
runInBackground(new Runnable() {
@Override
public void run() {
listener.requestFailed(status, photoCollection);
Log.d(TAG, "listImages: success");
}
});
}
}, sequenceId, getAccessToken(), LoginUtils.isLoginTypePartner(appPrefs), appPrefs.getStringPreference(PreferenceTypes.JARVIS_ACCESS_TOKEN));
mQueue.add(seqRequest);
}
@Subscribe(sticky = true, threadMode = ThreadMode.BACKGROUND)
public void onLoginChanged(LoginChangedEvent event) {
mAccessToken = null;
}
/**
* Requests the gamification details for the current signed in user. On success this will also persist those changed in the cache.
* @param user the user for which the details will be persisted on success of the request.
* @param listener the listener which will be notified with the request status.
*/
private void requestUserProfileDetails(User user, final NetworkResponseDataListener<UserData> listener) {
ProfileRequest profileRequest =
new ProfileRequest(factoryServerEndpointUrl.getProfileEndpoint(UrlProfile.PROFILE_DETAILS), new KVRequestResponseListener<UserDataParser, UserData>(mUserDataParser) {
@Override
public void onSuccess(final int status, final UserData userData) {
runInBackground(() -> {
userRepository.updateCacheUserDetails(new GamificationDetails(
(int) userData.getTotalPhotos(),
(int) userData.getTotalTracks(),
userData.getObdDistance(),
userData.getTotalDistance(),
userData.getTotalPoints(),
new GamificationLevel(
userData.getLevel(),
userData.getLevelTarget(),
userData.getLevelProgress(),
userData.getLevelName()
),
new GamificationRank(
userData.getWeeklyRank(),
userData.getOverallRank()
)));
listener.requestFinished(status, userData);
Log.d(TAG, "getUserProfileDetails: success");
});
}
@Override
public void onFailure(final int status, final UserData userData) {
runInBackground(() -> {
listener.requestFailed(status, userData);
Log.d(TAG, "getUserProfileDetails: failed");
});
}
}, user.getUserName(), LoginUtils.isLoginTypePartner(appPrefs), appPrefs.getStringPreference(PreferenceTypes.JARVIS_ACCESS_TOKEN));
profileRequest.setShouldCache(false);
profileRequest.setRetryPolicy(new DefaultRetryPolicy(150000, 0, 0f));
mQueue.add(profileRequest);
}
/**
* cancells all upload request added
*/
private void cancelListTasks() {
Log.d(TAG, "cancelListTasks: cancelled map list tasks and listSegments");
ListRequestFilter listFilter = new ListRequestFilter();
mQueue.cancelAll(listFilter);
}
}
|
pkg_name=openresty-noroot
pkg_origin=chef
pkg_version=1.13.6.2
pkg_description="Scalable Web Platform by Extending NGINX with Lua"
pkg_maintainer="The Chef Server Maintainers <support@chef.io>"
pkg_license=('BSD-2-Clause')
pkg_source=https://openresty.org/download/openresty-${pkg_version}.tar.gz
pkg_dirname=openresty-${pkg_version}
pkg_filename=openresty-${pkg_version}.tar.gz
pkg_upstream_url=http://openresty.org/
pkg_shasum=946e1958273032db43833982e2cec0766154a9b5cb8e67868944113208ff2942
pkg_deps=(
core/bzip2
core/coreutils
core/gcc-libs
core/glibc
core/libxml2
core/libxslt
core/openssl
core/pcre
core/perl
core/zlib
)
pkg_build_deps=(
core/gcc
core/make
core/which
)
pkg_lib_dirs=(lib)
pkg_bin_dirs=(bin nginx/sbin luajit/bin)
pkg_include_dirs=(include)
pkg_svc_user="hab"
pkg_exports=(
[port]=http.listen.port
)
pkg_exposes=(port)
# TODO: current version is 1.0.1, we should try updating
lpeg_version="0.12"
lpeg_source="http://www.inf.puc-rio.br/~roberto/lpeg/lpeg-${lpeg_version}.tar.gz"
do_prepare() {
# The `/usr/bin/env` path is hardcoded, so we'll add a symlink.
if [[ ! -r /usr/bin/env ]]; then
ln -sv "$(pkg_path_for coreutils)/bin/env" /usr/bin/env
_clean_env=true
fi
}
do_build() {
./configure --prefix="$pkg_prefix" \
--user=hab \
--group=hab \
--http-log-path=stdout \
--error-log-path=stderr \
--with-ipv6 \
--with-debug \
--with-pcre \
--with-md5-asm \
--with-pcre-jit \
--with-sha1-asm \
--with-file-aio \
--with-luajit \
--with-stream=dynamic \
--with-mail=dynamic \
--with-http_gunzip_module \
--with-http_gzip_static_module \
--with-http_realip_module \
--with-http_v2_module \
--with-http_ssl_module \
--with-http_stub_status_module \
--with-http_addition_module \
--with-http_degradation_module \
--with-http_flv_module \
--with-http_mp4_module \
--with-http_secure_link_module \
--with-http_sub_module \
--with-http_slice_module \
--with-cc-opt="$CFLAGS" \
--with-ld-opt="$LDFLAGS" \
--without-http_ssi_module \
--without-mail_smtp_module \
--without-mail_imap_module \
--without-mail_pop3_module \
-j"$(nproc)"
make -j"$(nproc)"
}
do_install() {
make install
fix_interpreter "$pkg_prefix/bin/*" core/coreutils bin/env
cd $HAB_CACHE_SRC_PATH
wget $lpeg_source
tar --no-same-owner -xzf lpeg-${lpeg_version}.tar.gz
cd lpeg-${lpeg_version}
make "LUADIR=$pkg_prefix/luajit/include/luajit-2.1" || attach
install -p -m 0755 lpeg.so $pkg_prefix/luajit/lib/lua/5.1/ || attach
}
do_end() {
# Clean up the `env` link, if we set it up.
if [[ -n "$_clean_env" ]]; then
rm -fv /usr/bin/env
fi
}
|
#!/usr/bin/env bats
readonly cdf=$BATS_TEST_DIRNAME/../cdf
readonly tmpdir=$BATS_TEST_DIRNAME/../tmp
readonly stdout=$BATS_TEST_DIRNAME/../tmp/stdout
readonly stderr=$BATS_TEST_DIRNAME/../tmp/stderr
readonly exitcode=$BATS_TEST_DIRNAME/../tmp/exitcode
setup() {
mkdir -p -- "$tmpdir"
export PATH=$PATH:$(dirname "$BATS_TEST_DIRNAME")
export PATH=$(printf "%s\n" "$PATH" | awk '{gsub(":", "\n"); print}' | paste -sd:)
export CDFFILE=$tmpdir/cdf.json
printf "%s\n" "{}" > "$CDFFILE"
}
teardown() {
rm -rf -- "$tmpdir"
}
check() {
printf "%s\n" "" > "$stdout"
printf "%s\n" "" > "$stderr"
printf "%s\n" "0" > "$exitcode"
"$@" > "$stdout" 2> "$stderr" || printf "%s\n" "$?" > "$exitcode"
}
@test 'cdf supports sh' {
! command -v sh > /dev/null && skip
printf "%s\n" "{\"usr\":\"/usr\"}" > "$CDFFILE"
CDF="$cdf" check sh -c 'eval "$("$CDF" -w); cdf usr; pwd"'
[[ $(cat "$exitcode") == 0 ]]
[[ $(cat "$stdout") == "/usr" ]]
}
@test 'cdf supports ksh' {
! command -v ksh > /dev/null && skip
printf "%s\n" "{\"usr\":\"/usr\"}" > "$CDFFILE"
CDF="$cdf" check ksh -c 'eval "$("$CDF" -w); cdf usr; pwd"'
[[ $(cat "$exitcode") == 0 ]]
[[ $(cat "$stdout") == "/usr" ]]
}
@test 'cdf supports bash' {
! command -v bash > /dev/null && skip
printf "%s\n" "{\"usr\":\"/usr\"}" > "$CDFFILE"
CDF=$cdf check bash -c 'eval "$("$CDF" -w bash); cdf usr; pwd"'
[[ $(cat "$exitcode") == 0 ]]
[[ $(cat "$stdout") == "/usr" ]]
}
@test 'cdf supports zsh' {
! command -v zsh > /dev/null && skip
printf "%s\n" "{\"usr\":\"/usr\"}" > "$CDFFILE"
CDF=$cdf check zsh -c 'eval "$("$CDF" -w zsh); cdf usr; pwd"'
[[ $(cat "$exitcode") == 0 ]]
[[ $(cat "$stdout") == "/usr" ]]
}
@test 'cdf supports yash' {
! command -v yash > /dev/null && skip
printf "%s\n" "{\"usr\":\"/usr\"}" > "$CDFFILE"
CDF=$cdf check yash -c 'eval "$("$CDF" -w yash)"; cdf usr; pwd'
[[ $(cat "$exitcode") == 0 ]]
[[ $(cat "$stdout") == "/usr" ]]
}
@test 'cdf supports fish' {
! command -v fish > /dev/null && skip
printf "%s\n" "{\"usr\":\"/usr\"}" > "$CDFFILE"
CDF=$cdf check fish -c 'source (eval $CDF -w fish | psub); cdf usr; pwd'
[[ $(cat "$exitcode") == 0 ]]
[[ $(cat "$stdout") == "/usr" ]]
}
@test 'cdf supports tcsh' {
! command -v tcsh > /dev/null && skip
printf "%s\n" "{\"usr\":\"/usr\"}" > "$CDFFILE"
CDF=$cdf check tcsh -c 'printf '"'"'unalias cdf\n$CDF -w tcsh | source /dev/stdin\ncdf usr\npwd\n'"'"' | source /dev/stdin'
[[ $(cat "$exitcode") == 0 ]]
[[ $(cat "$stdout") == "/usr" ]]
}
@test 'cdf supports rc' {
! command -v rc > /dev/null && skip
printf "%s\n" "{\"usr\":\"/usr\"}" > "$CDFFILE"
CDF=$cdf check rc -c 'ifs='"'"''"'"' eval `{$CDF -w rc}; cdf usr; pwd'
[[ $(cat "$exitcode") == 0 ]]
[[ $(cat "$stdout") == "/usr" ]]
}
@test 'cdf supports nyagos' {
! command -v nyagos > /dev/null && skip
printf "%s\n" "{\"usr\":\"/usr\"}" > "$CDFFILE"
CDF=$cdf check nyagos <<< $'lua_e "loadstring(nyagos.eval(""%CDF% -w nyagos""))()"\ncdf usr\npwd'
[[ $(cat "$exitcode") == 0 ]]
[[ $(cat "$stdout") == "/usr" ]]
}
@test 'cdf supports xyzsh' {
! command -v xyzsh > /dev/null && skip
printf "%s\n" "{\"usr\":\"/usr\"}" > "$CDFFILE"
CDF=$cdf check xyzsh <<< $'eval "$(sys::command -- $CDF -w xyzsh)"\ncdf usr\npwd'
[[ $(cat "$exitcode") == 0 ]]
[[ $(cat "$stdout") =~ "/usr" ]]
}
@test 'cdf supports xonsh' {
! command -v xonsh > /dev/null && skip
printf "%s\n" "{\"usr\":\"/usr\"}" > "$CDFFILE"
CDF=$cdf check xonsh -c $'execx($($CDF -w xonsh))\ncdf usr\npwd'
[[ $(cat "$exitcode") == 0 ]]
[[ $(cat "$stdout") == "/usr" ]]
}
@test 'cdf supports powershell' {
! command -v pwsh > /dev/null && skip
printf "%s\n" "{\"usr\":\"/usr\"}" > "$CDFFILE"
CDF=$cdf check pwsh -Command 'Invoke-Expression (@(& $env:CDF "-w" powershell) -join "`n"); cdf usr; Write-Host @(pwd)'
[[ $(cat "$exitcode") == 0 ]]
[[ $(cat "$stdout") == "/usr" ]]
}
# vim: ft=bash
|
<gh_stars>0
// This is the starting point for the application
// This module starts executing as soon as parsing of the HTML has finished
// We will bootstrap the app and start the loading process for all components
// The CSS module
import './main.css'
// Logging support
import { log } from "./log";
// The micro-router for page transitions
import { goHome, gotoPage } from './router'
// We need to import the Service Worker notification screen
import './pages/SWNotify'
// Go to the home page
goHome()
// Get the version of the application and store in database
/**
*
* @returns undefined
*/
async function getAndUpdateVersion() {
let response = await fetch("./version.txt")
if (!response.ok) {
log.error("fetch for version.txt failed");
return;
}
// Store the version in global Window object and in local storage
window.appVersion = await response.text()
window.localStorage.setItem("VERSION", appVersion)
console.log("Version:", appVersion)
return;
}
// When called the DOM is fully loaded and safe to manipulate
window.addEventListener('DOMContentLoaded', async (event) => {
// Display ASAP the Header and a Splash Screen while loading
// Get the version of the application asynchronously
getAndUpdateVersion()
// Go to the home page
goHome()
});
var INSTALL_SERVICE_WORKER = true
// This function is called on first load and when a refresh is triggered in any page
// When called the DOM is fully loaded and safe to manipulate
window.addEventListener('load', async (event) => {
// Install Service Worker only when in Production
if (import.meta.env.DEV) {
console.log("In development")
INSTALL_SERVICE_WORKER = false
} else {
console.log("In production")
}
// Install service worker for off-line support
if (INSTALL_SERVICE_WORKER && ("serviceWorker" in navigator)) {
const {Workbox} = await import('workbox-window');
const wb = new Workbox("./sw.js");
wb.addEventListener("message", (event) => {
if (event.data.type === "CACHE_UPDATED") {
const { updatedURL } = event.data.payload;
console.log(`A newer version of ${updatedURL} is available!`);
}
});
wb.addEventListener("activated", async (event) => {
// `event.isUpdate` will be true if another version of the service
// worker was controlling the page when this version was registered.
if (event.isUpdate) {
console.log("Service worker has been updated.", event);
await performAppUpgrade(true)
} else {
console.log("Service worker has been installed for the first time.", event);
await performAppUpgrade(false)
}
});
wb.addEventListener("waiting", (event) => {
console.log(
`A new service worker has installed, but it can't activate` +
`until all tabs running the current version have fully unloaded.`
);
});
// Register the service worker after event listeners have been added.
wb.register();
// const swVersion = await wb.messageSW({ type: "GET_VERSION" });
// console.log("Service Worker version:", swVersion);
}
});
// This is called when a new version of the Service Worker has been activated.
// This means that a new version of the application has been installed
async function performAppUpgrade(isUpdate) {
console.log("Performing Upgrade");
// Notify the user and ask to refresh the application
gotoPage("SWNotify", {isUpdate: isUpdate})
}
|
/**
* Created by root on 7/12/17.
*/
class RequestsInfo {
constructor () {
this.count = {
in: 0,
out: 0
}
this.delay = {
send: 0,
reply: 0,
process: 0
}
this.timeouted = 0
}
sendRequest () {
this.count.out++
}
gotRequest () {
this.count.in++
}
addDelay ({sendTime, getTime, replyTime, replyGetTime}) {
this.delay.send = ((getTime - sendTime) + this.count.out * this.delay.send) / (this.count.out + 1)
this.delay.reply = ((replyGetTime - replyTime) + this.count.out * this.delay.reply) / (this.count.out + 1)
this.delay.process = ((replyTime - getTime) + this.count.out * this.delay.process) / (this.count.out + 1)
}
addTimeouted () {
this.timeouted++
}
}
export default class Metric {
constructor ({id}) {
this.id = id
this.requests = new Map()
this.ticks = new Map()
this.cpu = 0
this.memory = process.memoryUsage().heapTotal / 1000000
this.actualUsag = 0
}
getCpu (interval = 100) {
this.actualUsage = process.cpuUsage(this.actualUsag)
this.cpu = (this.actualUsage.user + this.actualUsage.system) / (100 * interval)
return this.cpu
}
getMemory () {
this.memory = process.memoryUsage().heapTotal / 1000000
}
sendRequest (id) {
if (!this.requests.has(id)) {
let requestInfo = new RequestsInfo()
requestInfo.sendRequest()
return this.requests.set(id, requestInfo)
}
this.requests.get(id).sendRequest()
}
gotRequest (id) {
if (!this.requests.has(id)) {
let requestInfo = new RequestsInfo()
requestInfo.gotRequest()
return this.requests.set(id, requestInfo)
}
this.requests.get(id).gotRequest()
}
gotReply ({id, sendTime, getTime, replyTime, replyGetTime}) {
if (!this.requests.has(id)) return
this.requests.get(id).addDelay({sendTime: sendTime[0] * 1000000000 + sendTime[1], getTime: getTime[0] * 1000000000 + getTime[1], replyTime: replyTime[0] * 1000000000 + replyTime[1], replyGetTime: replyGetTime[0] * 1000000000 + replyGetTime[1]})
}
sendTick (id) {
if (!this.ticks.get(id)) {
let tickInfo = {
in: 0,
out: 1
}
return this.ticks.set(id, tickInfo)
}
this.ticks.get(id).out++
}
gotTick (id) {
if (!this.ticks.get(id)) {
let tickInfo = {
in: 1,
out: 0
}
return this.ticks.set(id, tickInfo)
}
this.ticks.get(id).in++
}
requestTimeout (id) {
if (!this.requests.has(id)) return
this.requests.get(id).addTimeouted()
}
flush () {
this.requests = new Map()
this.ticks = new Map()
this.cpu = 0
this.memory = process.memoryUsage().heapTotal / 1000000
}
}
|
class Solution {
public String reverseWords(String s) {
ArrayList<String> res = new ArrayList<String>();
String[] words = s.trim().split(" ");
for (String x: words){
if (x == null || x.trim().isEmpty()){
continue;
}
else{
x = x.trim().replaceAll("\\s+","");
res.add(x);
}
}
Collections.reverse(res);
String r = String.join(" ",res);
return r;
}
} |
#!/bin/bash
# ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- #
# This script starts a series of Layer-3 connections across a series of stations #
# each station will wait $nap seconds, download $quantity KB and then remove #
# its old CX. #
# #
# INSTALL #
# Copy this script to to /home/lanforge/scripts/lf_staggered_dl.sh #
# If you are copying this via DOS/Windows, follow these steps: #
# 1) copy using samba or pscp or winscp or whatever this script to #
# /home/lanforge/scripts/lf_staggered_dl.sh #
# 2) in a terminal on the LANforge, run dos2unix and #
# $ cd /home/lanforge/sripts #
# $ dos2unix lf_staggered_dl.sh #
# 3) make the script executable: #
# $ chmod a+x lf_staggered_dl.sh #
# #
# ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- #
# . lanforge.profile
[ ! -f lf_firemod.pl ] && echo "Unable to find lf_firemod.pl." && exit 1
#set -e
q="'"
Q='"'
manager=localhost # :m
resource=1 # :m
first_sta= # :f
upstream=x # :u
last_sta=x # :l
num_sta=x # :n
naptime=x # :z
payload_kb=x # :s
tx_rate=x # :t
check_naptime=1.0 # seconds between lf_firemod check on endpoint stats
timer=1000 # report timer
function term_procs() {
echo -en "\nCleaning up background tasks: ";
for pid in "${childprocs[@]}"; do
echo -n "$pid, "
kill -9 $pid &>/dev/null || true
done
echo " done"
}
trap term_procs EXIT
function usage() {
cat <<__EOF__
${0}: starts a series of layer-3 connections and makes each start
downloading a fixed amount of data after a naptime.
-m # lanforge manager (defaults to localhost)
-r # lanforge resource (defaults to 1)
-f # first station/port
-n # number of stations/ports
-z # naptime before beginning download
-u # upstream port that will transmit
-t # transmit bps
-p # payload size in KB
Example: # 20 stations (sta100-sta120) nap 3 seconds before downloading 200KB
${0} -m 192.168.1.101 -r 1 -f sta100 -n 20 -z 3 -u eth1 -p 250 -t 1500000
__EOF__
}
while getopts ":f:m:n:p:r:t:u:z:" opt; do
case "${opt}" in
f)
first_sta="${OPTARG}"
;;
m)
manager="${OPTARG}"
;;
n)
num_sta="${OPTARG}"
;;
p)
payload_kb="${OPTARG}"
;;
r)
resource="${OPTARG}"
;;
t)
tx_rate="${OPTARG}"
;;
u)
upstream="${OPTARG}"
;;
z)
naptime="${OPTARG}"
;;
*)
usage
exit 1
;;
esac
done
shift $(( OPTIND - 1 ));
[ -z "$manager" -o "$manager" == x ] \
&& echo "Please specify LANforge manager ip or hostname." && usage && exit 1
[ -z "$resource" -o "$resource" == x ] \
&& echo "Please specify LANforge resource for stations." && usage && exit 1
[ -z "$first_sta" -o "$first_sta" == x ] \
&& echo "Please specify first station or port in series to download " && usage && exit 1
[ -z "$num_sta" -o "$num_sta" == x ] \
&& echo "Please specify number of stations to put connections on." && usage && exit 1
[ -z "$naptime" -o "$naptime" == x ] \
&& echo "Please specify number of seconds to wait before transmitting." && usage && exit 1
[ -z "$payload_kb" -o "$payload_kb" == x ] \
&& echo "Please specify kilobytes to transfer per connection." && usage && exit 1
[ -z "$upstream" -o "$upstream" == x ] \
&& echo "Please specify upstream port to transmit from" && usage && exit 1
[ -z "$tx_rate" -o "$tx_rate" == x ] \
&& echo "Please specify transmit rate in bps" && usage && exit 1
declare -a childprocs
declare -a stations
declare -a cx_names
declare -a cx_create_endp
declare -a cx_create_cx
declare -a cx_mod_endp
declare -a cx_start_cx
declare -a cx_started
declare -a cx_finished
declare -a cx_destroy_cx
declare -A map_destroy_cx
sta_pref=${first_sta//[0-9]/}
sta_start=${first_sta//[A-Za-z]/}
[ -z "$sta_pref" ] && echo "Unable to determine beginning station prefix" && exit 1
[ -z "$sta_start" -o $sta_start -lt 0 ] && echo "Unable to determine beginning station number." && exit 1
[ $num_sta -lt 1 ] && echo "Unable to deterine number of stations to create." && exit 1
packets=$(( 1 + $(( $payload_kb * 1000 / 1460 )) ))
[ -z "$packets" -o $packets -lt 2 ] && echo "Unable to calculate packets for transfer." && exit 1
# 111 is a trick number that we'll truncate to three digits later
expon=`echo "111 * 10^${#sta_start}" | bc -l`
counter=$(( expon + $sta_start ))
limit=$(( expon + $sta_start + $num_sta -1 ))
for i in `seq $counter $limit` ; do
stations+=("${sta_pref}${counter#111}")
cx_names+=("c-${upstream}-${sta_pref}${counter#111}");
counter=$(( counter + 1 ))
done
_act="./lf_firemod.pl --mgr $manager --resource $resource --quiet yes --action"
_cmd="./lf_firemod.pl --mgr $manager --resource $resource --quiet yes --cmd"
counter=0
for cx in "${cx_names[@]}"; do
cx_create_endp+=("$_act create_endp --endp_name ${cx}-A --speed $tx_rate --endp_type lf_tcp --port_name ${upstream} --report_timer $timer")
cx_create_endp+=("sleep 0.1")
cx_create_endp+=("$_act create_endp --endp_name ${cx}-B --speed 0 --endp_type lf_tcp --port_name ${stations[$counter]} --report_timer $timer")
cx_create_endp+=("sleep 0.1")
cx_create_cx+=("$_act create_cx --cx_name ${cx} --cx_endps ${cx}-A,${cx}-B --report_timer $timer")
cx_create_cx+=("sleep 0.2")
cx_mod_endp+=("${cx}-A NA NA NA ${packets}")
nap=$(( $naptime * $counter ))
cx_start_cx+=("sleep $nap; $_cmd ${Q}set_cx_state all ${cx} RUNNING${Q} &>/dev/null")
cx_destroy_cx+=("$_act delete_cx --cx_name ${cx}")
cx_destroy_cx+=("sleep 0.1")
cx_destroy_cx+=("$_act delete_endp --endp_name ${cx}-A")
cx_destroy_cx+=("$_act delete_endp --endp_name ${cx}-B")
cx_destroy_cx+=("sleep 0.1")
map_destroy_cx[${cx}]="$_act delete_cx --cx_name ${cx}; sleep 0.1; $_act delete_endp --endp_name ${cx}-A; $_act delete_endp --endp_name ${cx}-B";
counter=$(( counter + 1 ))
done
echo -n "Removing previous connections..."
for command in "${cx_destroy_cx[@]}" ; do
$command
done
sleep 1
echo "done"
echo -n "Creating new endpoints..."
for command in "${cx_create_endp[@]}" ; do
$command
done
echo "done"
echo -n "Creating new cross connects..."
sleep $(( 2 + $(( $counter /2 )) ))
for command in "${cx_create_cx[@]}" ; do
$command
done
./lf_firemod.pl --mgr $manager --quiet yes --cmd "nc_show_endp all" > /tmp/ep_count.txt
echo "done"
echo -n "Configuring payload sizes..."
outf="/tmp/cmd.$$.txt"
for command in "${cx_mod_endp[@]}" ; do
result=1
rm -f $outf
while [ $result -ne 0 ]; do
ep=${command%% *}
#$_cmd "nc_show_endp $ep"
$_cmd "set_endp_details $command" > $outf
result=$(awk '/RSLT:/{print $2}' $outf)
if [ $result -ne 0 ]; then
cat $outf
sleep 5
fi
done
#sleep 0.1
done
echo "done"
echo -n "Starting staggered transmissions..."
sleep $(( 2 + $(( $counter /2 )) ))
for command in "${cx_start_cx[@]}" ; do
bash -c "$command" &
childprocs+=($!)
sleep 0.1
done
echo "done"
echo "Monitoring staggered downloads for ports:"
echo -e "\t${cx_names[@]}"
echo "_R_unning _Q_uiesce _N_ot Running (Tx Packets/Requested Packets)"
echo "--------------------------------------------------------------"
counter=1
while [ $counter -ne 0 ]; do
messages=()
#echo -en ""
for cx in "${cx_names[@]}"; do
while read L ; do
endp_report+=("$L")
done < <($_act show_endp --endp_name ${cx}-A)
state="?"
for i in `seq 0 $((${#endp_report[@]}-1))`; do
ine="${endp_report[$i]}";
h=($ine);
case "${ine}" in
"Endpoint "*)
state="${h[2]:1:-1}"
;;
"Tx Pkts: "*)
txpkts="${h[3]}";
;;
esac
done
if [[ " ${cx_started[@]} " =~ " ${cx} " ]]; then # can inspect for finishing
if [[ ! " ${cx_finished[@]} " =~ " ${cx} " ]]; then
if [ ${txpkts} -ge ${packets} -a ${state} = "NOT_RUNNING" ] ; then
cx_finished+=(${cx})
messages+=("$cx: finished running")
cmd=${map_destroy_cx[${cx}]};
#messages+=(" CMD[ $cmd ]");
bash -c "$cmd"
cx_started=(${cx_started[@]/$cx})
fi
fi
elif [[ " ${cx_finished[@]} " =~ " ${cx} " ]]; then
:
else
if [ ${txpkts} -gt 0 ]; then
messages+=("$cx: started running")
cx_started+=(${cx})
fi
fi
case $state in
"RUNNING") st="R";;
"NOT_RUNNING") st="N";;
"QUIESCE") st="Q";;
*)
esac
echo -en "${cx}: ${st} ${txpkts}/${packets} "
done
echo ""
for m in "${messages[@]}"; do
echo -e "\t${m}"
done
# compare the number of finished stations to total number of stations
[ ${#cx_finished[@]} -eq ${#cx_names[@]} ] && break;
sleep $check_naptime
done
echo "Waiting for background jobs to finish..."
wait
#eof
|
<reponame>c-dante/thr33
import {
BoxGeometry, PlaneGeometry,
MeshBasicMaterial, MeshNormalMaterial, MeshLambertMaterial,
} from 'three';
export const newBox = (l = 100, w = l, h = l, ...rest) =>
new BoxGeometry(l, w, h, ...rest);
export const newPlane = (w = 10000, h = w, ws = 1, hs = ws) =>
new PlaneGeometry(w, h, ws, hs);
/**
* Some basic materials to reuse?
* @type {Object.<String, THREE.Material>}
*/
export const Materials = {
default: new MeshLambertMaterial({ color: 0x00ff00 }),
redWireframe: new MeshBasicMaterial({ color: 0xff0000, wireframe: true }),
};
export const Debug = {
normals: new MeshNormalMaterial({ wireframe: true }),
};
|
<filename>IDE/src/components/login/Auth.js
import auth0 from 'auth0-js';
import { AUTH_CONFIG } from './auth0-variables';
import { browserHistory } from 'react-router';
export default class Auth {
auth0 = new auth0.WebAuth({
domain: AUTH_CONFIG.domain,
clientID: AUTH_CONFIG.clientId,
redirectUri: AUTH_CONFIG.callbackUrl,
responseType: 'token id_token',
scope: 'openid email profile'
});
userProfile;
constructor() {
this.login = this.login.bind(this);
this.logout = this.logout.bind(this);
this.handleAuthentication = this.handleAuthentication.bind(this);
this.isAuthenticated = this.isAuthenticated.bind(this);
this.getAccessToken = this.getAccessToken.bind(this);
this.getProfile = this.getProfile.bind(this);
}
login() {
this.auth0.authorize();
}
handleAuthentication() {
return new Promise((resolve, reject) => {
this.auth0.parseHash((err, authResult) => {
if (authResult && authResult.accessToken && authResult.idToken) {
this.setSession(authResult);
resolve(authResult);
} else if (err) {
browserHistory.replace('/login');
reject(err);
}
});
});
}
setSession(authResult) {
// Set the time that the access token will expire at
let expiresAt = JSON.stringify(( authResult.expiresIn * 1000 ) + new Date().getTime());
localStorage.setItem('access_token', authResult.accessToken);
localStorage.setItem('id_token', authResult.idToken);
localStorage.setItem('expires_at', expiresAt);
}
getAccessToken() {
const accessToken = localStorage.getItem('access_token');
if (!accessToken) {
throw new Error('No access token found');
}
return accessToken;
}
getProfile(cb) {
let accessToken = this.getAccessToken();
this.auth0.client.userInfo(accessToken, (err, profile) => {
if (profile) {
this.userProfile = profile;
}
cb(err, profile);
});
}
logout() {
// Clear access token and ID token from local storage
localStorage.removeItem('access_token');
localStorage.removeItem('id_token');
localStorage.removeItem('expires_at');
}
isAuthenticated() {
// Check whether the current time is past the
// access token's expiry time
let expiresAt = JSON.parse(localStorage.getItem('expires_at'));
return new Date().getTime() < expiresAt;
}
}
|
// Expense model
struct Expense {
let amount: Double
let date: Date
let category: String
}
// Model controller
class ExpensesController {
private var expenses = [Expense]()
func addExpense(expense: Expense) {
expenses.append(expense)
}
func deleteExpenseAtIndex(index: Int) {
expenses.remove(at: index)
}
func getSummaryForPeriod(startDate: Date, endDate: Date) -> ExpenseSummary {
var total = 0.0
var groupedExpenses = [String: [Expense]]()
for expense in expenses {
total += expense.amount
let category = expense.category
if groupedExpenses[category] == nil {
groupedExpenses[category] = [Expense]()
}
groupedExpenses[category]!.append(expense)
}
return ExpenseSummary(total: total, groupedExpenses: groupedExpenses)
}
} |
package io.opensphere.core.pipeline.renderer.buffered;
import java.awt.Color;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import javax.media.opengl.GL;
import javax.media.opengl.GL2;
import javax.media.opengl.GL2ES1;
import org.apache.log4j.Logger;
import io.opensphere.core.geometry.AbstractGeometry;
import io.opensphere.core.geometry.AbstractGeometry.RenderMode;
import io.opensphere.core.geometry.Geometry;
import io.opensphere.core.geometry.PolygonMeshGeometry;
import io.opensphere.core.geometry.renderproperties.LightingModelConfigGL;
import io.opensphere.core.model.ScreenPosition;
import io.opensphere.core.pipeline.cache.CacheProvider;
import io.opensphere.core.pipeline.processor.PolygonMeshData;
import io.opensphere.core.pipeline.processor.TextureModelData;
import io.opensphere.core.pipeline.renderer.AbstractRenderer;
import io.opensphere.core.pipeline.renderer.GeometryRenderer;
import io.opensphere.core.pipeline.renderer.util.PolygonRenderUtil;
import io.opensphere.core.pipeline.util.GL2LightHandler;
import io.opensphere.core.pipeline.util.GL2Utilities;
import io.opensphere.core.pipeline.util.PickManager;
import io.opensphere.core.pipeline.util.RenderContext;
import io.opensphere.core.pipeline.util.TextureGroup;
import io.opensphere.core.pipeline.util.TextureHandle;
import io.opensphere.core.projection.Projection;
import io.opensphere.core.util.TimeBudget;
import io.opensphere.core.util.collections.New;
import io.opensphere.core.util.lang.Pair;
import io.opensphere.core.util.lang.UnexpectedEnumException;
import io.opensphere.core.viewer.impl.MapContext;
/**
* Polygon mesh renderer that uses server-side buffering.
*/
public class PolygonMeshRendererBuffered extends AbstractRenderer<PolygonMeshGeometry> implements Comparator<PolygonMeshGeometry>
{
/** Bits used for {@link GL2#glPushAttrib(int)}. */
private static final int ATTRIB_BITS = GL2.GL_CURRENT_BIT | GL2.GL_POLYGON_BIT | GL.GL_COLOR_BUFFER_BIT | GL2.GL_ENABLE_BIT
| GL2.GL_LIGHTING_BIT | GL.GL_DEPTH_BUFFER_BIT;
/** Bits used for {@link GL2#glPushClientAttrib(int)}. */
private static final int CLIENT_ATTRIB_BITS = GL2.GL_CLIENT_VERTEX_ARRAY_BIT;
/** Logger reference. */
private static final Logger LOGGER = Logger.getLogger(PolygonMeshRendererBuffered.class);
/**
* Construct the renderer.
*
* @param cache The geometry cache.
*/
public PolygonMeshRendererBuffered(CacheProvider cache)
{
super(cache);
}
@Override
public void doRender(RenderContext rc, Collection<? extends PolygonMeshGeometry> input,
Collection<? super PolygonMeshGeometry> rejected, PickManager pickManager, MapContext<?> mapContext,
ModelDataRetriever<PolygonMeshGeometry> dataRetriever)
{
PolygonMeshRenderData renderData = (PolygonMeshRenderData)getRenderData();
if (renderData == null)
{
return;
}
try
{
rc.getGL().glEnable(GL.GL_POLYGON_OFFSET_FILL);
rc.getGL().glEnable(GL.GL_BLEND);
rc.getGL().glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA);
PolygonRenderUtil.setupGL(rc.getGL(), rc.getRenderMode(),
ScreenPosition.class.isAssignableFrom(input.iterator().next().getPositionType()),
isDebugFeatureOn("TessellationLines"));
rc.getGL().glDisable(GL.GL_CULL_FACE);
LightingModelConfigGL lastLight = null;
List<? extends PolygonMeshGeometry> toRender = New.list(input);
toRender.sort(this);
for (final PolygonMeshGeometry geom : toRender)
{
try
{
Pair<PolygonMeshDataBuffered, TextureGroup> meshAndTexture = getMesh(rc, dataRetriever, renderData, geom);
PolygonMeshDataBuffered mesh = meshAndTexture.getFirstObject();
TextureGroup textureGroup = meshAndTexture.getSecondObject();
if (mesh != null)
{
if (rc.getRenderMode() == AbstractGeometry.RenderMode.DRAW)
{
lastLight = GL2LightHandler.setLight(rc, lastLight, geom.getRenderProperties().getLighting());
}
rc.glDepthMask(geom.getRenderProperties().isObscurant());
if (textureGroup != null)
{
rc.glColorARGB(Color.black.getRGB());
}
else
{
GL2Utilities.glColor(rc, pickManager, geom);
}
Object textureHandleKey = null;
TextureHandle handle = null;
if (geom.getTextureCoords() != null)
{
textureHandleKey = getTextureHandleKeyForMode(rc.getRenderMode(), textureGroup);
handle = textureHandleKey == null ? null
: getCache().getCacheAssociation(textureHandleKey, TextureHandle.class);
if (handle != null)
{
rc.getGL().glEnable(GL.GL_TEXTURE_2D);
rc.getGL().getGL2().glTexEnvfv(GL2ES1.GL_TEXTURE_ENV, GL2ES1.GL_TEXTURE_ENV_COLOR,
new float[] { 1f, 1f, 1f, 1f }, 0);
rc.getGL().getGL2().glTexEnvi(GL2ES1.GL_TEXTURE_ENV, GL2ES1.GL_TEXTURE_ENV_MODE, GL.GL_BLEND);
rc.getGL().glBindTexture(GL.GL_TEXTURE_2D, handle.getTextureId());
rc.getGL().glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_S, GL.GL_REPEAT);
rc.getGL().glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_T, GL.GL_REPEAT);
}
}
GL2Utilities.renderWithTransform(rc, geom.getRenderProperties().getTransform(), () -> mesh.draw(rc));
PolygonMeshData modelData = mesh.get(0).getPolygonMeshData();
// If the buffered data is not already in the cache,
// add
// it
// to enable the GPU memory to be cleaned up.
getCache().putCacheAssociation(modelData, mesh, PolygonMeshDataBuffered.class, 0L, mesh.getSizeGPU());
}
else
{
rejected.add(geom);
}
}
finally
{
rc.getGL().getGL2().glTexEnvi(GL2ES1.GL_TEXTURE_ENV, GL2ES1.GL_TEXTURE_ENV_MODE, GL.GL_REPLACE);
rc.getGL().getGL2().glTexEnvfv(GL2ES1.GL_TEXTURE_ENV, GL2ES1.GL_TEXTURE_ENV_COLOR,
new float[] { 0f, 0f, 0f, 0f }, 0);
rc.getGL().glDisable(GL.GL_TEXTURE_2D);
}
}
}
finally
{
rc.popAttributes();
}
}
@Override
public int getAttribBits()
{
return ATTRIB_BITS;
}
@Override
public int getClientAttribBits()
{
return CLIENT_ATTRIB_BITS;
}
@Override
public Class<?> getType()
{
return PolygonMeshGeometry.class;
}
@Override
public void preRender(Collection<? extends PolygonMeshGeometry> input, Collection<? extends PolygonMeshGeometry> drawable,
Collection<? extends PolygonMeshGeometry> pickable, PickManager pickManager,
ModelDataRetriever<PolygonMeshGeometry> dataRetriever, Projection projectionSnapshot)
{
super.preRender(input, drawable, pickable, pickManager, dataRetriever, projectionSnapshot);
Map<PolygonMeshGeometry, Pair<PolygonMeshDataBuffered, TextureGroup>> renderDataMap = New.weakMap(input.size());
for (PolygonMeshGeometry geom : input)
{
Pair<PolygonMeshDataBuffered, TextureGroup> meshAndTexture = getPolygonMeshBuffered(geom, dataRetriever,
projectionSnapshot, TimeBudget.ZERO);
if (meshAndTexture.getFirstObject() != null)
{
renderDataMap.put(geom, meshAndTexture);
}
}
setRenderData(new PolygonMeshRenderData(renderDataMap, projectionSnapshot));
}
@Override
protected Logger getLogger()
{
return LOGGER;
}
/**
* Get the mesh from the render data or request it from the data retriever
* if it's missing.
*
* @param rc The render context.
* @param dataRetriever The data retriever.
* @param renderData The render data.
* @param geom The geometry.
* @return The mesh.
*/
private Pair<PolygonMeshDataBuffered, TextureGroup> getMesh(RenderContext rc,
ModelDataRetriever<PolygonMeshGeometry> dataRetriever, PolygonMeshRenderData renderData,
final PolygonMeshGeometry geom)
{
Pair<PolygonMeshDataBuffered, TextureGroup> meshAndTexture = renderData.getData().get(geom);
if (meshAndTexture == null || meshAndTexture.getFirstObject() == null)
{
meshAndTexture = getPolygonMeshBuffered(geom, dataRetriever, renderData.getProjection(), rc.getTimeBudget());
if (meshAndTexture.getFirstObject() != null)
{
renderData.getData().put(geom, meshAndTexture);
}
}
return meshAndTexture;
}
/**
* Retrieve the buffer data from the cache or try to create it if it is
* absent from the cache.
*
* @param geom The geometry.
* @param dataRetriever A retriever for the model data.
* @param projectionSnapshot The projection snapshot to use when generating
* any missing model data.
* @param timeBudget The time budget.
* @return The buffer data.
*/
private Pair<PolygonMeshDataBuffered, TextureGroup> getPolygonMeshBuffered(PolygonMeshGeometry geom,
ModelDataRetriever<PolygonMeshGeometry> dataRetriever, Projection projectionSnapshot, TimeBudget timeBudget)
{
PolygonMeshDataBuffered bufferedData = null;
TextureModelData textureModel = (TextureModelData)dataRetriever.getModelData(geom, projectionSnapshot, null,
TimeBudget.ZERO);
TextureGroup textureGroup = null;
if (textureModel != null)
{
textureGroup = textureModel.getTextureGroup();
PolygonMeshData modelData = (PolygonMeshData)textureModel.getModelData();
if (modelData != null)
{
bufferedData = getCache().getCacheAssociation(modelData, PolygonMeshDataBuffered.class);
if (bufferedData == null)
{
bufferedData = new PolygonMeshDataBuffered(modelData);
}
}
}
return new Pair<>(bufferedData, textureGroup);
}
/**
* Get the texture from the texture group for the specified render mode.
*
* @param renderMode The render mode.
* @param textureGroup The texture group.
* @return The texture.
*/
private Object getTextureHandleKeyForMode(RenderMode renderMode, TextureGroup textureGroup)
{
Object textureHandleKey;
if (renderMode == RenderMode.DRAW)
{
textureHandleKey = textureGroup.getTextureMap().get(RenderMode.DRAW);
}
else if (renderMode == RenderMode.PICK)
{
textureHandleKey = textureGroup.getTextureMap().get(RenderMode.PICK);
if (textureHandleKey == null)
{
textureHandleKey = textureGroup.getTextureMap().get(RenderMode.DRAW);
}
}
else
{
throw new UnexpectedEnumException(renderMode);
}
return textureHandleKey;
}
/**
* A factory for creating this renderer.
*/
public static class Factory extends AbstractRenderer.Factory<PolygonMeshGeometry>
{
@Override
public GeometryRenderer<PolygonMeshGeometry> createRenderer()
{
return new PolygonMeshRendererBuffered(getCache());
}
@Override
public Collection<? extends BufferDisposalHelper<?>> getDisposalHelpers()
{
return Collections.singleton(BufferDisposalHelper.create(PolygonMeshDataBuffered.class, getCache()));
}
@Override
public Class<? extends Geometry> getType()
{
return PolygonMeshGeometry.class;
}
@Override
public boolean isViable(RenderContext rc, Collection<String> warnings)
{
return rc.is11Available(getClass().getEnclosingClass().getSimpleName() + " is not viable", warnings);
}
}
/** Data used for rendering. */
private static class PolygonMeshRenderData extends RenderData
{
/** The map of geometries to data. */
private final Map<PolygonMeshGeometry, Pair<PolygonMeshDataBuffered, TextureGroup>> myData;
/**
* Constructor.
*
* @param data The map of geometries to data.
* @param projection The projection snapshot used to generate this data.
*/
public PolygonMeshRenderData(Map<PolygonMeshGeometry, Pair<PolygonMeshDataBuffered, TextureGroup>> data,
Projection projection)
{
super(projection);
myData = data;
}
/**
* Get the data.
*
* @return the data
*/
public Map<PolygonMeshGeometry, Pair<PolygonMeshDataBuffered, TextureGroup>> getData()
{
return myData;
}
}
@Override
public int compare(PolygonMeshGeometry o1, PolygonMeshGeometry o2)
{
int compare = 0;
if (o1.getTextureCoords() == null)
{
compare = -1;
}
else if (o2.getTextureCoords() == null)
{
compare = 1;
}
return compare;
}
}
|
import React from 'react';
import ReactDOM from 'react-dom';
function Clients() {
return (
<div className="bg-gray
bg-gray-900
p-20
justify-items-stretch
flex
col-2
">
<img src="img/jose-salame.svg" className="imageCeo
bg-gray-700
flex
justify-center items-center " alt=""/>
<div className="m-20 pl-20 text-6xl text-white text-mk">
Un poco de nosotros
<p className="text-xs">
Somos un equipo de gente creativa
Somos un equipo de gente creativa
Somos un equipo de gente creativa
Somos un equipo de gente creativa
Somos un equipo de gente creativa
<br/>
Somos un equipo de gente creativa
Somos un equipo de gente creativa
Somos un equipo de gente creativa
Somos un equipo de gente creativa
Somos un equipo de gente creativa
</p>
</div>
</div>
);
}
export default Clients;
if (document.getElementById('Clients')) {
ReactDOM.render(<Clients/>, document.getElementById('Clients'));
}
|
#!/bin/bash
# Tells the script to exit if a command fails instead of continuing
set -e
if [ "$1" == "backend" ]; then
echo "Starting backend..."
source .venv/bin/activate
cd backend
# Set the Django secret key and save as an environment variable
if command -v gp &> /dev/null; then
gp env SECRET_KEY=$RANDOM
eval $(gp env -e)
else
SECRET_KEY=$RANDOM
fi
echo "SECRET_KEY=$SECRET_KEY" > .env
# Run the backend in development mode
python3 manage.py migrate
python3 manage.py runserver
elif [ "$1" == "frontend" ]; then
echo "Starting frontend app..."
cd frontend
# Get the GitPod URL for the backend, for API requests
# Get the GitPod URL for the frontend, for hot module reloading
if command -v gp &> /dev/null; then
gp env VITE_BACKEND_URL=$(gp url 8000)
gp env VITE_FRONTEND_URL=$(gp url 3000)
eval $(gp env -e)
else
VITE_BACKEND_URL="http://localhost:8000"
VITE_FRONTEND_URL="http://localhost:3000"
fi
echo "VITE_BACKEND_URL=$VITE_BACKEND_URL" > .env
echo "VITE_FRONTEND_URL=$VITE_FRONTEND_URL" >> .env
# Run the frontend in development mode
npm run dev
elif [ "$1" == "install-frontend" ]; then
echo "Installing frontend dependencies..."
# Install Node dependencies within frontend directory
cd frontend
npm install
elif [ "$1" == "install-backend" ]; then
echo "Installing backend dependencies..."
python3 -m venv .venv
source .venv/bin/activate
# Install Python dependencies in workspace so that GitPod persists them
pip3 install -r requirements.txt
elif [ "$1" == "ui" ]; then
# Open the frontend in the GitPod preview window
if command -v gp &> /dev/null; then
gp preview $(gp url 3000)
else
open "http://localhost:3000"
fi
elif [ "$1" == "api" ]; then
source .venv/bin/activate
# Open the backend in the GitPod preview window
if command -v gp &> /dev/null; then
gp preview $(gp url 8000)
else
open "http://localhost:8000"
fi
elif [ "$1" == "manage" ]; then
source .venv/bin/activate
cd backend
# Set the Django secret key and save as an environment variable
if command -v gp &> /dev/null; then
gp env SECRET_KEY=$RANDOM
eval $(gp env -e)
else
SECRET_KEY=$RANDOM
fi
echo "SECRET_KEY=$SECRET_KEY" > .env
# Run the Django management command with args
python3 manage.py "${@:2}"
else
echo "No run shortcut found for: $1"
echo "Did you pull the latest version?"
fi
|
export VISUAL=atom
export EDITOR=$VISUAL
|
<filename>egov/egov-ptis/src/main/java/org/egov/ptis/domain/service/notice/RecoveryNoticeService.java
/*
* eGov SmartCity eGovernance suite aims to improve the internal efficiency,transparency,
* accountability and the service delivery of the government organizations.
*
* Copyright (C) 2017 eGovernments Foundation
*
* The updated version of eGov suite of products as by eGovernments Foundation
* is available at http://www.egovernments.org
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see http://www.gnu.org/licenses/ or
* http://www.gnu.org/licenses/gpl.html .
*
* In addition to the terms of the GPL license to be adhered to in using this
* program, the following additional terms are to be complied with:
*
* 1) All versions of this program, verbatim or modified must carry this
* Legal Notice.
* Further, all user interfaces, including but not limited to citizen facing interfaces,
* Urban Local Bodies interfaces, dashboards, mobile applications, of the program and any
* derived works should carry eGovernments Foundation logo on the top right corner.
*
* For the logo, please refer http://egovernments.org/html/logo/egov_logo.png.
* For any further queries on attribution, including queries on brand guidelines,
* please contact <EMAIL>
*
* 2) Any misrepresentation of the origin of the material is prohibited. It
* is required that all modified versions of this material be marked in
* reasonable ways as different from the original version.
*
* 3) This license does not grant any rights to any user of the program
* with regards to rights under trademark law for use of the trade names
* or trademarks of eGovernments Foundation.
*
* In case of any queries, you can reach eGovernments Foundation at <EMAIL>.
*
*/
package org.egov.ptis.domain.service.notice;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.egov.commons.CFinancialYear;
import org.egov.commons.Installment;
import org.egov.commons.dao.FinancialYearDAO;
import org.egov.demand.model.EgBill;
import org.egov.infra.admin.master.entity.AppConfigValues;
import org.egov.infra.admin.master.entity.City;
import org.egov.infra.admin.master.service.AppConfigValueService;
import org.egov.infra.admin.master.service.ModuleService;
import org.egov.infra.config.persistence.datasource.routing.annotation.ReadOnly;
import org.egov.infra.exception.ApplicationRuntimeException;
import org.egov.infra.filestore.entity.FileStoreMapper;
import org.egov.infra.filestore.service.FileStoreService;
import org.egov.infra.persistence.entity.Address;
import org.egov.infra.reporting.engine.ReportFormat;
import org.egov.infra.reporting.engine.ReportOutput;
import org.egov.infra.reporting.engine.ReportRequest;
import org.egov.infra.reporting.engine.ReportService;
import org.egov.infra.utils.DateUtils;
import org.egov.infra.utils.NumberUtil;
import org.egov.infra.utils.PdfUtils;
import org.egov.ptis.bean.NoticeRequest;
import org.egov.ptis.client.util.PropertyTaxNumberGenerator;
import org.egov.ptis.constants.PropertyTaxConstants;
import org.egov.ptis.domain.dao.property.BasicPropertyDAO;
import org.egov.ptis.domain.entity.notice.RecoveryNoticesInfo;
import org.egov.ptis.domain.entity.property.BasicProperty;
import org.egov.ptis.domain.entity.property.Floor;
import org.egov.ptis.domain.repository.notice.RecoveryNoticesInfoRepository;
import org.egov.ptis.domain.service.property.PropertyService;
import org.egov.ptis.notice.PtNotice;
import org.egov.ptis.service.DemandBill.DemandBillService;
import org.egov.ptis.service.utils.PropertyTaxCommonUtils;
import org.hibernate.Session;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import static org.egov.ptis.constants.PropertyTaxConstants.*;
@Service
public class RecoveryNoticeService {
private static final String DEMAND_BILL_SERVICE = "demandBillService";
private static final String CONSUMER_ID = "consumerId";
private static final String ADDRESS = "address";
private static final String LOCALITY = "locality";
private static final String UPIC_NO = "upicNo";
private static final String NOTICE_NUMBER = "noticeNumber";
private static final String DOOR_NO = "doorNo";
private static final String LOCATION = "Location";
private static final String FINANCIAL_YEAR = "financialYear";
private static final String DISTRESS_NOTICE_DATE = "distressNoticeDate";
private static final String DISTRESS_NOTICE_NUMBER = "distressNoticeNumber";
private static final String FIN_HALF_STRAT_MONTH = "FinHalfStratMonth";
private static final String NOTICE_YEAR = "noticeYear";
private static final String NOTICE_MONTH = "noticeMonth";
private static final String NOTICE_DAY = "noticeDay";
private static final String TOTAL_TAX_DUE = "totalTaxDue";
private static final String SECTION_ACT = "sectionAct";
private static final String BILL_NUMBER = "billNumber";
private static final String BILL_DATE = "billDate";
private static final String ESD_NOTICE_DATE = "eSDNoticeDate";
private static final String ESD_NOTICE_NUMBER = "eSDNoticeNumber";
private static final String FUTURE_DATE = "futureDate";
private static final String FIN_YEAR = "finYear";
private static final String CITY_NAME = "cityName";
private static final String INST_MON_YEAR = "instMonYear";
private static final String INST_LAST_DATE = "instLastDate";
private static final String REPORT_MON_YEAR = "reportMonYear";
private static final String REPORT_DATE = "reportDate";
private static final String OWNER_NAME = "ownerName";
private static final String OWNERSHIP_CERTIFICATE_DATE = "ownershipCertificateDate";
private static final String OWNERSHIP_CERTIFICATE_NO = "ownershipCertificateNo";
private static final String OCCUPIER_NOTICE_NAGAR_PANCHAYET = "OccupierNotice_NagarPanchayet";
private static final String OCCUPIER_NOTICE_CORPORATION = "OccupierNotice_Corporation";
private static final String TAX_DUE_IN_WORDS = "taxDueInWords";
@PersistenceContext
private EntityManager entityManager;
@Autowired
private ModuleService moduleDao;
@Autowired
private ReportService reportService;
@Autowired
private NoticeService noticeService;
@Autowired
private PropertyTaxNumberGenerator propertyTaxNumberGenerator;
@Autowired
private AppConfigValueService appConfigValuesService;
@Autowired
private ApplicationContext beanProvider;
@Autowired
private FileStoreService fileStoreService;
@Autowired
private PropertyService propertyService;
@Autowired
private BasicPropertyDAO basicPropertyDAO;
@Autowired
private PropertyTaxCommonUtils propertyTaxCommonUtils;
@Autowired
private RecoveryNoticesInfoRepository recoveryNoticesInfoRepository;
@Autowired
private FinancialYearDAO financialYearDAO;
public Session getCurrentSession() {
return entityManager.unwrap(Session.class);
}
public boolean getDemandBillByAssessmentNo(final BasicProperty basicProperty) {
boolean billExists = false;
final AppConfigValues appConfigValues = appConfigValuesService.getAppConfigValueByDate(PTMODULENAME,
APPCONFIG_CLIENT_SPECIFIC_DMD_BILL, new Date());
final String value = appConfigValues != null ? appConfigValues.getValue() : "";
if ("Y".equalsIgnoreCase(value)) {
final DemandBillService demandBillService = (DemandBillService) beanProvider.getBean(DEMAND_BILL_SERVICE);
billExists = demandBillService.getDemandBillByAssessmentNumber(basicProperty.getUpicNo());
} else {
final EgBill egBill = getBillByAssessmentNumber(basicProperty);
if (egBill != null)
billExists = true;
}
return billExists;
}
public List<String> validateRecoveryNotices(final String assessmentNo, final String noticeType) {
final List<String> errors = new ArrayList<>();
final BasicProperty basicProperty = basicPropertyDAO.getBasicPropertyByPropertyID(assessmentNo);
if (basicProperty == null)
errors.add("property.invalid");
else if (NOTICE_TYPE_ESD.equals(noticeType))
validateDemandBill(basicProperty, errors);
else if (NOTICE_TYPE_DISTRESS.equals(noticeType))
validateDistressNotice(errors, basicProperty);
else if (NOTICE_TYPE_INVENTORY.equals(noticeType))
validateInventoryNotice(errors, basicProperty);
else if (VALUATION_CERTIFICATE.equals(noticeType))
validateCertificate(errors, basicProperty);
else if (NOTICE_TYPE_OC.equals(noticeType))
validateOwnerCertificate(errors, basicProperty);
else
validateOccupierNotice(errors, basicProperty);
return errors;
}
public EgBill getBillByAssessmentNumber(final BasicProperty basicProperty) {
final StringBuilder queryStr = new StringBuilder(200);
queryStr.append(
"FROM EgBill WHERE module =:module AND egBillType.code =:billType AND consumerId =:assessmentNo AND is_history = 'N'");
final Query qry = entityManager.createQuery(queryStr.toString());
qry.setParameter("module", moduleDao.getModuleByName(PTMODULENAME));
qry.setParameter("billType", BILLTYPE_MANUAL);
qry.setParameter("assessmentNo", basicProperty.getUpicNo());
return qry.getResultList() != null && !qry.getResultList().isEmpty() ? (EgBill) qry.getResultList().get(0)
: null;
}
public BigDecimal getTotalPropertyTaxDue(final BasicProperty basicProperty) {
return propertyService.getTotalPropertyTaxDue(basicProperty);
}
public BigDecimal getTotalPropertyTaxDueIncludingPenalty(final BasicProperty basicProperty) {
return propertyService.getTotalPropertyTaxDueIncludingPenalty(basicProperty);
}
public ResponseEntity<byte[]> generateNotice(final String assessmentNo, final String noticeType) {
ReportOutput reportOutput;
final BasicProperty basicProperty = basicPropertyDAO.getBasicPropertyByPropertyID(assessmentNo);
final PtNotice notice = noticeService.getNoticeByTypeUpicNoAndFinYear(noticeType, basicProperty.getUpicNo());
if (notice == null)
reportOutput = generateNotice(noticeType, basicProperty);
else
reportOutput = getNotice(notice, noticeType);
final HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.parseMediaType("application/pdf"));
headers.add("content-disposition", "inline;filename=" + noticeType + "_" + basicProperty.getUpicNo() + ".pdf");
return new ResponseEntity<>(reportOutput.getReportOutputData(), headers, HttpStatus.CREATED);
}
public ReportOutput generateNotice(final String noticeType, final BasicProperty basicProperty) {
ReportOutput reportOutput = null;
final Map<String, Object> reportParams = new HashMap<>();
InputStream noticePDF = null;
ReportRequest reportInput = null;
final StringBuilder queryString = new StringBuilder();
queryString.append("from City");
final Query query = entityManager.createQuery(queryString.toString());
final City city = (City) query.getSingleResult();
populateReportParams(reportParams, city, basicProperty);
final String noticeNo = propertyTaxNumberGenerator.generateNoticeNumber(noticeType);
final SimpleDateFormat formatter = new SimpleDateFormat("MMM yyyy");
if (NOTICE_TYPE_ESD.equals(noticeType))
reportInput = generateEsdNotice(basicProperty, reportParams, city, noticeNo, formatter);
else if (NOTICE_TYPE_INVENTORY.equals(noticeType))
reportInput = generateInventoryNotice(basicProperty, reportParams, city, formatter);
else if (VALUATION_CERTIFICATE.equals(noticeType))
reportInput = generateValuationCertificate(basicProperty, reportParams, city, noticeNo);
else if (NOTICE_TYPE_OC.equals(noticeType))
reportInput = generateOwnershipCertificate(basicProperty, reportParams, city, noticeNo);
else if (NOTICE_TYPE_OCCUPIER.equals(noticeType))
reportOutput = prepareOccupierNotice(basicProperty, reportParams, city, noticeNo);
else
reportInput = generateDistressNotice(basicProperty, reportParams, city, noticeNo);
if (!NOTICE_TYPE_OCCUPIER.equals(noticeType)) {
reportInput.setPrintDialogOnOpenReport(true);
reportInput.setReportFormat(ReportFormat.PDF);
reportOutput = reportService.createReport(reportInput);
}
if (reportOutput != null && reportOutput.getReportOutputData() != null)
noticePDF = new ByteArrayInputStream(reportOutput.getReportOutputData());
noticeService.saveNotice(basicProperty.getPropertyForBasicProperty().getApplicationNo(), noticeNo, noticeType,
basicProperty, noticePDF);
return reportOutput;
}
public ReportOutput prepareOccupierNotice(final BasicProperty basicProperty, final Map<String, Object> reportParams,
final City city, final String noticeNo) {
ReportRequest reportInput;
ReportOutput reportOutput = null;
final List<InputStream> pdfs = new ArrayList<>();
reportInput = generateOccupierNotice(basicProperty, reportParams, city, noticeNo);
reportInput.setPrintDialogOnOpenReport(true);
reportInput.setReportFormat(ReportFormat.PDF);
for (final Floor floor : basicProperty.getProperty().getPropertyDetail().getFloorDetails())
if (OCC_TENANT.equalsIgnoreCase(floor.getPropertyOccupation().getOccupancyCode())) {
reportOutput = reportService.createReport(reportInput);
if (reportOutput != null && reportOutput.getReportOutputData() != null)
pdfs.add(new ByteArrayInputStream(reportOutput.getReportOutputData()));
}
if (!pdfs.isEmpty()) {
byte[] mergedPdfs = PdfUtils.appendFiles(pdfs);
if (reportOutput != null)
reportOutput.setReportOutputData(mergedPdfs);
}
return reportOutput;
}
@SuppressWarnings("unchecked")
public List<String> generateRecoveryNotices(final NoticeRequest noticeRequest) {
final Query qry = getSearchQuery(noticeRequest);
final List<String> properties = qry.getResultList();
final List<RecoveryNoticesInfo> noticesInfos = new ArrayList<>();
Long jobNumber = getLatestJobNumber();
if (jobNumber == null)
jobNumber = 0l;
jobNumber = jobNumber + 1;
for (final String propertyId : properties) {
final RecoveryNoticesInfo info = new RecoveryNoticesInfo();
info.setPropertyId(propertyId);
info.setNoticeType(noticeRequest.getNoticeType());
info.setGenerated(Boolean.FALSE);
info.setJobNumber(jobNumber);
noticesInfos.add(info);
}
recoveryNoticesInfoRepository.save(noticesInfos);
return properties;
}
public Long getLatestJobNumber() {
return recoveryNoticesInfoRepository.getLatestJobNumber();
}
public RecoveryNoticesInfo getRecoveryNoticeInfoByAssessmentAndNoticeType(final String propertyId, final String noticeType) {
return recoveryNoticesInfoRepository.findByPropertyIdAndNoticeType(propertyId, noticeType);
}
public void saveRecoveryNoticeInfo(final RecoveryNoticesInfo noticeInfo) {
recoveryNoticesInfoRepository.save(noticeInfo);
}
private Map<String, Object> populateReportParams(final Map<String, Object> reportParams, final City city,
final BasicProperty basicProperty) {
reportParams.put(CITY_NAME, city.getPreferences().getMunicipalityName());
reportParams.put(OWNER_NAME, basicProperty.getFullOwnerName());
return reportParams;
}
private ReportOutput getNotice(final PtNotice notice, final String noticeType) {
final ReportOutput reportOutput = new ReportOutput();
final FileStoreMapper fsm = notice.getFileStore();
final File file = fileStoreService.fetch(fsm, FILESTORE_MODULE_NAME);
byte[] bFile;
try {
bFile = FileUtils.readFileToByteArray(file);
} catch (final IOException e) {
throw new ApplicationRuntimeException("Exception while retrieving " + noticeType + " : " + e);
}
reportOutput.setReportOutputData(bFile);
reportOutput.setReportFormat(ReportFormat.PDF);
return reportOutput;
}
private void validateInventoryNotice(final List<String> errors, final BasicProperty basicProperty) {
validateDemandBill(basicProperty, errors);
final PtNotice distressNotice = noticeService.getNoticeByTypeUpicNoAndFinYear(NOTICE_TYPE_DISTRESS,
basicProperty.getUpicNo());
if (distressNotice != null) {
final DateTime noticeDate = new DateTime(distressNotice.getNoticeDate());
final DateTime currDate = new DateTime();
if (!currDate.isAfter(noticeDate.plusDays(16)))
errors.add("invntry.distress.notice.not.exists");
} else
errors.add("invntry.distress.notice.not.exists");
}
private void validateDistressNotice(final List<String> errors, final BasicProperty basicProperty) {
final BigDecimal totalDue = getTotalPropertyTaxDueIncludingPenalty(basicProperty);
if (totalDue.compareTo(BigDecimal.ZERO) == 0)
errors.add("invalid.no.due");
else if (basicProperty.getProperty().getIsExemptedFromTax())
errors.add("invalid.exempted");
else {
final PtNotice esdNotice = noticeService.getNoticeByTypeUpicNoAndFinYear(NOTICE_TYPE_ESD,
basicProperty.getUpicNo());
if (esdNotice == null)
errors.add("invalid.esd.not.generated");
else if (DateUtils.daysBetween(esdNotice.getNoticeDate(), new Date()) < 15)
errors.add("invalid.time.not.lapsed");
}
}
private void validateCertificate(final List<String> errors, final BasicProperty basicProperty) {
final BigDecimal totalDue = getTotalPropertyTaxDue(basicProperty);
if (totalDue.compareTo(BigDecimal.ZERO) > 0)
errors.add("assessment.has.pt.due");
}
private void validateOwnerCertificate(final List<String> errors, final BasicProperty basicProperty) {
validateCertificate(errors, basicProperty);
validateDemandBillExistance(errors, basicProperty);
}
private List<String> validateDemandBill(final BasicProperty basicProperty, final List<String> errors) {
final BigDecimal totalDue = getTotalPropertyTaxDue(basicProperty);
if (totalDue.compareTo(BigDecimal.ZERO) == 0)
errors.add("common.no.property.due");
validateDemandBillExistance(errors, basicProperty);
return errors;
}
private List<String> validateOccupierNotice(final List<String> errors, final BasicProperty basicProperty) {
Boolean hasTenant = Boolean.FALSE;
for (final Floor floor : basicProperty.getProperty().getPropertyDetail().getFloorDetails())
if (OCC_TENANT.equalsIgnoreCase(floor.getPropertyOccupation().getOccupancyCode()))
hasTenant = Boolean.TRUE;
if (!hasTenant)
errors.add("error.tenant.not.exist");
validateDemandBillExistance(errors, basicProperty);
return errors;
}
private List<String> validateDemandBillExistance(final List<String> errors, final BasicProperty basicProperty) {
final boolean billExists = getDemandBillByAssessmentNo(basicProperty);
if (!billExists)
errors.add("common.demandbill.not.exists");
return errors;
}
private ReportRequest generateDistressNotice(final BasicProperty basicProperty, final Map<String, Object> reportParams,
final City city, final String noticeNo) {
ReportRequest reportInput;
final Address ownerAddress = basicProperty.getAddress();
reportParams.put(TOTAL_TAX_DUE, getTotalPropertyTaxDueIncludingPenalty(basicProperty));
final DateTime noticeDate = new DateTime();
reportParams.put(DOOR_NO, StringUtils.isNotBlank(ownerAddress.getHouseNoBldgApt())
? ownerAddress.getHouseNoBldgApt().trim() : "N/A");
reportParams.put(CONSUMER_ID, basicProperty.getUpicNo());
reportParams.put(NOTICE_DAY, propertyTaxCommonUtils.getDateWithSufix(noticeDate.getDayOfMonth()));
reportParams.put(NOTICE_MONTH, noticeDate.monthOfYear().getAsShortText());
reportParams.put(NOTICE_YEAR, noticeDate.getYear());
if (noticeDate.getMonthOfYear() >= 4 && noticeDate.getMonthOfYear() <= 10)
reportParams.put(FIN_HALF_STRAT_MONTH, "April");
else
reportParams.put(FIN_HALF_STRAT_MONTH, "October");
reportParams.put(DISTRESS_NOTICE_NUMBER, noticeNo);
reportParams.put(DISTRESS_NOTICE_DATE, DateUtils.getDefaultFormattedDate(new Date()));
final String cityGrade = city.getGrade();
if (org.apache.commons.lang.StringUtils.isNotEmpty(cityGrade)
&& cityGrade.equalsIgnoreCase(PropertyTaxConstants.CITY_GRADE_CORPORATION)) {
reportParams.put(SECTION_ACT, PropertyTaxConstants.CORPORATION_ESD_NOTICE_SECTION_ACT);
reportInput = new ReportRequest(PropertyTaxConstants.REPORT_DISTRESS_CORPORATION, reportParams,
reportParams);
} else {
reportParams.put(SECTION_ACT, PropertyTaxConstants.MUNICIPALITY_DISTRESS_NOTICE_SECTION_ACT);
reportInput = new ReportRequest(PropertyTaxConstants.REPORT_DISTRESS_MUNICIPALITY, reportParams,
reportParams);
}
return reportInput;
}
private ReportRequest generateInventoryNotice(final BasicProperty basicProperty, final Map<String, Object> reportParams,
final City city, final SimpleDateFormat formatter) {
ReportRequest reportInput;
final Installment currentInstall = propertyTaxCommonUtils.getCurrentPeriodInstallment();
final DateTime dateTime = new DateTime();
final DateTime currInstToDate = new DateTime(currentInstall.getToDate());
reportParams.put(TOTAL_TAX_DUE, String.valueOf(getTotalPropertyTaxDue(basicProperty)));
reportParams.put(REPORT_DATE, propertyTaxCommonUtils.getDateWithSufix(dateTime.getDayOfMonth()));
reportParams.put(REPORT_MON_YEAR, dateTime.monthOfYear().getAsShortText() + "," + dateTime.getYear());
final String cityGrade = city.getGrade();
if (StringUtils.isNotBlank(cityGrade)
&& cityGrade.equalsIgnoreCase(PropertyTaxConstants.CITY_GRADE_CORPORATION)) {
reportParams.put(INST_LAST_DATE,
propertyTaxCommonUtils.getDateWithSufix(currInstToDate.getDayOfMonth()));
reportParams.put(INST_MON_YEAR,
currInstToDate.monthOfYear().getAsShortText() + "," + currInstToDate.getYear());
reportInput = new ReportRequest(REPORT_INVENTORY_NOTICE_CORPORATION, reportParams, reportParams);
} else {
reportParams.put(INST_LAST_DATE, formatter.format(currentInstall.getToDate()));
reportInput = new ReportRequest(REPORT_INVENTORY_NOTICE_MUNICIPALITY, reportParams, reportParams);
}
return reportInput;
}
private ReportRequest generateEsdNotice(final BasicProperty basicProperty, final Map<String, Object> reportParams,
final City city, final String noticeNo, final SimpleDateFormat formatter) {
ReportRequest reportInput;
prepareEsdReportParams(basicProperty, reportParams, noticeNo, formatter);
final String cityGrade = city.getGrade();
if (cityGrade != null && cityGrade != ""
&& cityGrade.equalsIgnoreCase(PropertyTaxConstants.CITY_GRADE_CORPORATION)) {
reportParams.put(SECTION_ACT, PropertyTaxConstants.CORPORATION_ESD_NOTICE_SECTION_ACT);
reportInput = new ReportRequest(PropertyTaxConstants.REPORT_ESD_NOTICE_CORPORATION, reportParams,
reportParams);
} else {
reportParams.put(SECTION_ACT, PropertyTaxConstants.MUNICIPALITY_ESD_NOTICE_SECTION_ACT);
reportInput = new ReportRequest(PropertyTaxConstants.REPORT_ESD_NOTICE_MUNICIPALITY, reportParams,
reportParams);
}
return reportInput;
}
private void prepareEsdReportParams(final BasicProperty basicProperty, final Map<String, Object> reportParams,
final String noticeNo, final SimpleDateFormat formatter) {
final Address ownerAddress = basicProperty.getAddress();
final DateTime noticeDate = new DateTime(new Date());
final AppConfigValues appConfigValues = appConfigValuesService.getAppConfigValueByDate(PTMODULENAME,
APPCONFIG_CLIENT_SPECIFIC_DMD_BILL, new Date());
reportParams.put(DOOR_NO, StringUtils.isNotBlank(ownerAddress.getHouseNoBldgApt())
? ownerAddress.getHouseNoBldgApt() : "N/A");
reportParams.put(FIN_YEAR, formatter.format(new Date()));
reportParams.put(CONSUMER_ID, basicProperty.getUpicNo());
reportParams.put(TOTAL_TAX_DUE, getTotalPropertyTaxDueIncludingPenalty(basicProperty));
reportParams.put(FUTURE_DATE, DateUtils.getDefaultFormattedDate(noticeDate.plusDays(2).toDate()));
reportParams.put(ESD_NOTICE_NUMBER, noticeNo);
reportParams.put(ESD_NOTICE_DATE, DateUtils.getDefaultFormattedDate(new Date()));
final String value = appConfigValues != null ? appConfigValues.getValue() : "";
if ("Y".equalsIgnoreCase(value)) {
final DemandBillService demandBillService = (DemandBillService) beanProvider
.getBean(DEMAND_BILL_SERVICE);
reportParams.putAll(demandBillService.getDemandBillDetails(basicProperty));
} else {
final EgBill egBill = getBillByAssessmentNumber(basicProperty);
reportParams.put(BILL_DATE, DateUtils.getDefaultFormattedDate(egBill.getCreateDate()));
reportParams.put(BILL_NUMBER, egBill.getBillNo());
}
}
private ReportRequest generateOwnershipCertificate(final BasicProperty basicProperty, final Map<String, Object> reportParams,
final City city, final String noticeNo) {
ReportRequest reportInput;
prepareOwnershipCertificateParams(basicProperty, reportParams, city, noticeNo);
final String[] ownerName = basicProperty.getFullOwnerName().split(",");
if (ownerName.length > 1)
reportInput = new ReportRequest(PropertyTaxConstants.REPORT_OWNERSHIP_CERTIFICATE_MULTIPLE, reportParams,
reportParams);
else
reportInput = new ReportRequest(PropertyTaxConstants.REPORT_OWNERSHIP_CERTIFICATE_SINGLE, reportParams,
reportParams);
return reportInput;
}
private void prepareOwnershipCertificateParams(final BasicProperty basicProperty, final Map<String, Object> reportParams,
final City city, final String noticeNo) {
final Address ownerAddress = basicProperty.getAddress();
reportParams.put(DOOR_NO, StringUtils.isNotBlank(ownerAddress.getHouseNoBldgApt())
? ownerAddress.getHouseNoBldgApt() : "N/A");
reportParams.put(OWNERSHIP_CERTIFICATE_NO, noticeNo);
reportParams.put(OWNERSHIP_CERTIFICATE_DATE, DateUtils.getDefaultFormattedDate(new Date()));
reportParams.put(CONSUMER_ID, basicProperty.getUpicNo());
reportParams.put("locality", ownerAddress.getAreaLocalitySector());
reportParams.put(OWNER_NAME, basicProperty.getFullOwnerName());
reportParams.put("address", basicProperty.getAddress().toString());
final String cityGrade = city.getGrade();
if (org.apache.commons.lang.StringUtils.isNotEmpty(cityGrade)
&& cityGrade.equalsIgnoreCase(PropertyTaxConstants.CITY_GRADE_CORPORATION))
reportParams.put("cityGrade", "Municipal Corporation");
else
reportParams.put("cityGrade", "Municipality/NP");
final StringBuilder ownerList = new StringBuilder(500);
final String[] ownerName = basicProperty.getFullOwnerName().split(",");
if (ownerName.length > 1) {
for (int i = 0; i < ownerName.length; i++)
ownerList.append(i + 1 + "." + ownerName[i] + "\n");
reportParams.put("ownerNameList", ownerList.toString());
} else
reportParams.put(OWNER_NAME, basicProperty.getFullOwnerName());
prepareDemandBillDetails(reportParams, basicProperty);
}
@ReadOnly
private Query getSearchQuery(final NoticeRequest noticeRequest) {
final Map<String, Object> params = new HashMap<>();
final StringBuilder query = new StringBuilder(500);
query.append(
"select mv.propertyId from PropertyMaterlizeView mv where mv.propertyId is not null ");
appendWard(noticeRequest, params, query);
appendBlock(noticeRequest, params, query);
appendPropertyType(noticeRequest, params, query);
appendCategoryType(noticeRequest, params, query);
appendPropertyId(noticeRequest, params, query);
appendFinancialYear(noticeRequest, params, query);
return getQuery(params, query);
}
private void appendFinancialYear(final NoticeRequest noticeRequest, final Map<String, Object> params,
final StringBuilder query) {
final CFinancialYear currFinYear = financialYearDAO.getFinancialYearByDate(new Date());
query.append(
" and mv.propertyId not in (select propertyId from RecoveryNoticesInfo where noticeType = :noticeType and createdDate between :startDate and :endDate )");
params.put("noticeType", noticeRequest.getNoticeType());
params.put("startDate", currFinYear.getStartingDate());
params.put("endDate", currFinYear.getEndingDate());
}
private void appendPropertyId(final NoticeRequest noticeRequest, final Map<String, Object> params,
final StringBuilder query) {
if (StringUtils.isNotEmpty(noticeRequest.getPropertyId())) {
query.append(" and mv.propertyId = :propertyId");
params.put("propertyId", noticeRequest.getPropertyId());
}
}
private void appendCategoryType(final NoticeRequest noticeRequest, final Map<String, Object> params,
final StringBuilder query) {
if (!(noticeRequest.getCategoryType() == null || "-1".equals(noticeRequest.getCategoryType()))) {
query.append(" and mv.categoryType = :categoryType");
params.put("categoryType", noticeRequest.getCategoryType());
}
}
private void appendPropertyType(final NoticeRequest noticeRequest, final Map<String, Object> params,
final StringBuilder query) {
if (!(noticeRequest.getPropertyType() == null || noticeRequest.getPropertyType().equals(-1l))) {
query.append(" and mv.propTypeMstrID.id = :propertyType");
params.put("propertyType", noticeRequest.getPropertyType());
}
}
private void appendBlock(final NoticeRequest noticeRequest, final Map<String, Object> params, final StringBuilder query) {
if (!(noticeRequest.getBlock() == null || noticeRequest.getBlock().equals(-1l))) {
query.append(" and mv.block.id = :blockId");
params.put("blockId", noticeRequest.getBlock());
}
}
private void appendWard(final NoticeRequest noticeRequest, final Map<String, Object> params, final StringBuilder query) {
if (!(noticeRequest.getWard() == null || noticeRequest.getWard().equals(-1l))) {
query.append(" and mv.ward.id = :wardId");
params.put("wardId", noticeRequest.getWard());
}
}
private Query getQuery(final Map<String, Object> params, final StringBuilder query) {
final Query qry = entityManager.createQuery(query.toString());
for (final Entry<String, Object> param : params.entrySet())
qry.setParameter(param.getKey(), param.getValue());
return qry;
}
private ReportRequest generateValuationCertificate(final BasicProperty basicProperty, final Map<String, Object> reportParams,
final City city, final String noticeNo) {
ReportRequest reportInput;
final SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
final Address ownerAddress = basicProperty.getAddress();
reportParams.put(NOTICE_NUMBER, noticeNo);
reportParams.put(REPORT_DATE, formatter.format(new Date()));
reportParams.put(DOOR_NO, StringUtils.isNotBlank(ownerAddress.getHouseNoBldgApt())
? ownerAddress.getHouseNoBldgApt() : "N/A");
reportParams.put(UPIC_NO, basicProperty.getUpicNo());
reportParams.put(LOCALITY, ownerAddress.getAreaLocalitySector());
reportParams.put(ADDRESS, ownerAddress.toString());
final String cityGrade = city.getGrade();
if (StringUtils.isNotBlank(cityGrade)
&& cityGrade.equalsIgnoreCase(PropertyTaxConstants.CITY_GRADE_CORPORATION))
reportInput = new ReportRequest(VALUATION_CERTIFICATE_CORPORATION, reportParams, reportParams);
else
reportInput = new ReportRequest(VALUATION_CERTIFICATE_MUNICIPALITY, reportParams, reportParams);
return reportInput;
}
private ReportRequest generateOccupierNotice(final BasicProperty basicProperty, final Map<String, Object> reportParams,
final City city, final String noticeNo) {
ReportRequest reportInput;
final Date asOnDate = new Date();
final CFinancialYear currFinYear = financialYearDAO.getFinancialYearByDate(asOnDate);
reportParams.put(DOOR_NO, basicProperty.getAddress().getHouseNoBldgApt() == null ? NOT_AVAILABLE
: basicProperty.getAddress().getHouseNoBldgApt());
reportParams.put(LOCATION, basicProperty.getAddress().getAreaLocalitySector() == null ? NOT_AVAILABLE
: basicProperty.getAddress().getAreaLocalitySector().trim());
reportParams.put(CITY_NAME, city.getPreferences().getMunicipalityName() == null ? NOT_AVAILABLE
: city.getPreferences().getMunicipalityName());
reportParams.put(FINANCIAL_YEAR, currFinYear.getFinYearRange());
final BigDecimal totalTaxDue = getTotalPropertyTaxDueIncludingPenalty(basicProperty);
reportParams.put(TOTAL_TAX_DUE, String.valueOf(totalTaxDue));
reportParams.put(REPORT_DATE, new SimpleDateFormat("dd/MM/yyyy").format(asOnDate));
reportParams.put(NOTICE_NUMBER, noticeNo);
reportParams.put(TAX_DUE_IN_WORDS, NumberUtil.amountInWords(totalTaxDue));
reportParams.put(CONSUMER_ID, basicProperty.getUpicNo());
prepareDemandBillDetails(reportParams, basicProperty);
final String cityGrade = city.getGrade();
if (StringUtils.isNotBlank(cityGrade)
&& cityGrade.equalsIgnoreCase(PropertyTaxConstants.CITY_GRADE_CORPORATION))
reportInput = new ReportRequest(OCCUPIER_NOTICE_CORPORATION, reportParams, reportParams);
else
reportInput = new ReportRequest(OCCUPIER_NOTICE_NAGAR_PANCHAYET, reportParams, reportParams);
return reportInput;
}
public Map<String, Object> prepareDemandBillDetails(final Map<String, Object> reportParams,
final BasicProperty basicProperty) {
final AppConfigValues appConfigValues = appConfigValuesService.getAppConfigValueByDate(PTMODULENAME,
APPCONFIG_CLIENT_SPECIFIC_DMD_BILL, new Date());
final String value = appConfigValues != null ? appConfigValues.getValue() : "";
if ("Y".equalsIgnoreCase(value)) {
final DemandBillService demandBillService = (DemandBillService) beanProvider
.getBean(DEMAND_BILL_SERVICE);
reportParams.putAll(demandBillService.getDemandBillDetails(basicProperty));
} else {
final EgBill egBill = getBillByAssessmentNumber(basicProperty);
reportParams.put(BILL_DATE, DateUtils.getDefaultFormattedDate(egBill.getCreateDate()));
reportParams.put(BILL_NUMBER, egBill.getBillNo());
}
return reportParams;
}
}
|
#!/bin/bash
# chronos test
echo "Chronos test start"
dir=${ANALYTICS_ZOO_HOME}/docs/docs/colab-notebook/chronos
pytorchFiles=("chronos_nyc_taxi_tsdataset_forecaster")
index=1
set -e
for f in "${pytorchFiles[@]}"
do
filename="${dir}/${f}"
echo "#${index} start example for ${f}"
#timer
start=$(date "+%s")
# chronos_nyc_taxi_tsdataset_forecaster data download
if [ ! -f nyc_taxi.csv ]; then
wget https://raw.githubusercontent.com/numenta/NAB/v1.0/data/realKnownCause/nyc_taxi.csv
fi
${ANALYTICS_ZOO_HOME}/apps/ipynb2py.sh ${filename}
sed -i "s/get_ipython()/#/g" ${filename}.py
sed -i "s/import os/#import os/g" ${filename}.py
sed -i "s/import sys/#import sys/g" ${filename}.py
sed -i 's/^[^#].*environ*/#&/g' ${filename}.py
sed -i 's/^[^#].*__future__ */#&/g' ${filename}.py
sed -i "s/_ = (sys.path/#_ = (sys.path/g" ${filename}.py
sed -i "s/.append/#.append/g" ${filename}.py
sed -i 's/^[^#].*site-packages*/#&/g' ${filename}.py
sed -i 's/version_info/#version_info/g' ${filename}.py
sed -i 's/python_version/#python_version/g' ${filename}.py
sed -i 's/exit()/#exit()/g' ${filename}.py
python ${filename}.py
now=$(date "+%s")
time=$((now-start))
echo "Complete #${index} with time ${time} seconds"
index=$((index+1))
done
# orca test
echo "orca test start"
dir=${ANALYTICS_ZOO_HOME}/docs/docs/colab-notebook/orca/quickstart
pytorchFiles=("pytorch_lenet_mnist_data_creator_func" "pytorch_lenet_mnist" "pytorch_distributed_lenet_mnist" "autoestimator_pytorch_lenet_mnist")
index=1
set -e
for f in "${pytorchFiles[@]}"
do
filename="${dir}/${f}"
echo "#${index} start example for ${f}"
#timer
start=$(date "+%s")
${ANALYTICS_ZOO_HOME}/apps/ipynb2py.sh ${filename}
sed -i "s/get_ipython()/#/g" ${filename}.py
sed -i "s/import os/#import os/g" ${filename}.py
sed -i "s/import sys/#import sys/g" ${filename}.py
sed -i 's/^[^#].*environ*/#&/g' ${filename}.py
sed -i 's/^[^#].*__future__ */#&/g' ${filename}.py
sed -i "s/_ = (sys.path/#_ = (sys.path/g" ${filename}.py
sed -i "s/.append/#.append/g" ${filename}.py
sed -i 's/^[^#].*site-packages*/#&/g' ${filename}.py
sed -i 's/version_info/#version_info/g' ${filename}.py
sed -i 's/python_version/#python_version/g' ${filename}.py
python ${filename}.py
now=$(date "+%s")
time=$((now-start))
echo "Complete #${index} with time ${time} seconds"
index=$((index+1))
done
|
<gh_stars>1-10
var searchData=
[
['noproxy_0',['Noproxy',['../classproxen_1_1sysproxy_1_1_noproxy.html',1,'proxen::sysproxy']]]
];
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.