text stringlengths 1 1.05M |
|---|
<filename>index.js<gh_stars>0
'use strict';
const assert = require('assert');
assert(false, `amqplib-flow shouldn't be used at runtime`);
|
source "../yrun_template.sh"
vim -c "source ${source}.exscript"
|
@MethodsReturnNonnullByDefault
@ParametersAreNonnullByDefault
package arekkuusu.stratoprism.common.item.prism;
import mcp.MethodsReturnNonnullByDefault;
import javax.annotation.ParametersAreNonnullByDefault; |
if which swiftformat >/dev/null; then
`which swiftformat` "Sources" --config .swiftformat --quiet
`which swiftformat` "Tests" --config .swiftformat --quiet
`which swiftformat` "Examples/RxRealmDemo-iOS" --config .swiftformat --quiet
`which swiftformat` "Package.swift" --config .swiftformat --quiet
else
echo "error: swiftformat not installed, do `sh setup.sh` to install swiftformat."
exit 1
fi
if which swiftlint >/dev/null; then
`which swiftlint` autocorrect --quiet
else
echo "error: SwiftLint not installed, do `sh setup.sh` to install SwiftLint."
exit 1
fi
if which xcodegen >/dev/null; then
`which xcodegen` --spec project-carthage.yml
else
echo "error: XcodeGen not installed, do `sh setup.sh` to install XcodeGen."
exit 1
fi |
import { ContractKit, newKitFromWeb3 } from "@celo/contractkit"
import { ReadOnlyWallet } from "@celo/connect"
import Web3 from "web3"
import net from "net"
import { CFG } from '../../lib/cfg'
const networkURLKeyPrefix = "terminal/core/network-url/"
let _cfgNetworkURL: string | undefined
export const cfgNetworkURL = (): string => {
if (!_cfgNetworkURL) {
const cfg = CFG()
const networkURL: string | null = localStorage.getItem(networkURLKeyPrefix + cfg.chainId)
_cfgNetworkURL = (networkURL && networkURL !== "") ? networkURL : cfg.defaultNetworkURL
}
return _cfgNetworkURL
}
const setCFGNetworkURL = (v: string) => {
_cfgNetworkURL = v
const cfg = CFG()
const cfgValue = v === cfg.defaultNetworkURL ? "" : v
localStorage.setItem(networkURLKeyPrefix + CFG().chainId, cfgValue)
}
let _kit: ContractKit | undefined
let _kitURL: string
const kitInstance = (): ContractKit => {
const networkURL = cfgNetworkURL()
if (_kit && _kitURL !== networkURL) {
_kit.stop()
_kit = undefined
}
if (!_kit) {
_kitURL = networkURL
_kit = newKitWithTimeout(_kitURL)
}
return _kit
}
export default kitInstance
export const useNetworkURL = (): [string, (v: string) => void] => {
return [cfgNetworkURL(), setCFGNetworkURL]
}
export const newKitWithTimeout = (url: string, wallet?: ReadOnlyWallet): ContractKit => {
let web3
if (url.startsWith("http://") || url.startsWith("https://")) {
web3 = new Web3(new Web3.providers.HttpProvider(url, {timeout: 30000}))
} else if (url.startsWith("ws://") || url.startsWith("wss://")) {
web3 = new Web3(new Web3.providers.WebsocketProvider(url, {timeout: 30000}))
} else if (url.endsWith('.ipc')) {
web3 = new Web3(new Web3.providers.IpcProvider(url, net))
} else {
web3 = new Web3(url)
}
return newKitFromWeb3(web3, wallet)
} |
using Discord.WebSocket;
using System;
namespace TournamentAssistantShared.Discord.Services
{
public class MessageUpdateService
{
private DiscordSocketClient _discordClient;
public event Action<SocketReaction> ReactionAdded;
public event Action<SocketReaction> ReactionRemoved;
public void Initialize(DiscordSocketClient discordClient)
{
_discordClient = discordClient;
_discordClient.ReactionAdded += HandleReactionAdded;
_discordClient.ReactionRemoved += HandleReactionRemoved;
}
private async Task HandleReactionAdded(Cacheable<IUserMessage, ulong> message, ISocketMessageChannel channel, SocketReaction reaction)
{
// Perform logic when a reaction is added
// Example: Check the reaction and perform specific action
ReactionAdded?.Invoke(reaction);
}
private async Task HandleReactionRemoved(Cacheable<IUserMessage, ulong> message, ISocketMessageChannel channel, SocketReaction reaction)
{
// Perform logic when a reaction is removed
// Example: Check the reaction and perform specific action
ReactionRemoved?.Invoke(reaction);
}
}
} |
#!/bin/bash
# Copyright (c) 2021 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
set -e
ninja_trace()
{
if [ "${NINJA_START_TIME}x" == "x" ]; then
return
fi
#generate build.trace to TARGET_OUT_DIR dir.
if [ -f "${TARGET_OUT_DIR}"/.ninja_log ]; then
if [ -f "${BASE_HOME}"/build/scripts/ninja2trace.py ]; then
python3 ${BASE_HOME}/build/scripts/ninja2trace.py --ninja-log ${TARGET_OUT_DIR}/.ninja_log \
--trace-file ${TARGET_OUT_DIR}/build.trace --ninja-start-time $NINJA_START_TIME \
--duration-file ${TARGET_OUT_DIR}/sorted_action_duration.txt
fi
fi
}
calc_build_time()
{
END_TIME=$(date "+%s")
log "used: $(expr $END_TIME - $BEGIN_TIME) seconds"
}
get_build_warning_list()
{
if [ -f "${BASE_HOME}"/build/scripts/get_warnings.py ];then
python3 ${BASE_HOME}/build/scripts/get_warnings.py --build-log-file ${TARGET_OUT_DIR}/build.log --warning-out-file ${TARGET_OUT_DIR}/packages/WarningList.txt
fi
}
generate_opensource_package()
{
log "generate opensource package"
if [ -f "${BASE_HOME}"/build/scripts/code_release.py ];then
python3 "${BASE_HOME}"/build/scripts/code_release.py
if [ ! -d "${TARGET_OUT_DIR}"/packages/code_opensource ];then
mkdir -p "${TARGET_OUT_DIR}"/packages/code_opensource
fi
cp "${BASE_HOME}"/out/Code_Opensource.tar.gz "${TARGET_OUT_DIR}"/packages/code_opensource/Code_Opensource.tar.gz -f
fi
}
ccache_stat()
{
if [[ ! -z "${CCACHE_EXEC}" ]] && [[ ! -z "${USE_CCACHE}" ]] && [[ "${USE_CCACHE}" == 1 ]]; then
log "ccache statistics"
if [ -e "${LOG_FILE}" -a -e "${CCACHE_LOGFILE}" ]; then
python3 ${BASE_HOME}/build/scripts/summary_ccache_hitrate.py $CCACHE_LOGFILE | tee -a $LOG_FILE
fi
fi
}
pycache_stat()
{
log "pycache statistics"
python3 ${BASE_HOME}/build/scripts/util/pyd.py --stat
}
pycache_manage()
{
log "manage pycache contents"
python3 ${BASE_HOME}/build/scripts/util/pyd.py --manage
}
pycache_stop()
{
log "pycache daemon exit"
python3 ${BASE_HOME}/build/scripts/util/pyd.py --stop
}
post_process()
{
if [ "${OPEN_SOURCE}" == true ];then
generate_opensource_package
fi
calc_build_time
pycache_stat
pycache_manage
pycache_stop
ninja_trace
ccache_stat
python3 ${BASE_HOME}/build/ohos/statistics/build_overlap_statistics.py --build-out-dir ${TARGET_OUT_DIR} --subsystem-config-file ${BASE_HOME}/build/subsystem_config.json --root-source-dir ${BASE_HOME}
get_build_warning_list
echo "post_process"
}
|
<gh_stars>1-10
import fetchWrap from '@/utils/fetch';
const getSstatistics = async () =>
await fetchWrap({
url: `/api/v1/statistics`,
method: 'GET',
});
const getSstatisticsByCountyName = async countyName =>
await fetchWrap({
url: `/api/v1/statistics/county/${countyName}`,
method: 'GET',
});
export { getSstatistics, getSstatisticsByCountyName };
|
<reponame>lonelyion/TweetToBot-Docker<filename>pluginsinterface/PlugAsyncio.py
# -*- coding: UTF-8 -*-
from pluginsinterface.EventHandling import StandEven
from pluginsinterface.Plugmanagement import async_send_even
import asyncio
import traceback
import threading
from helper import getlogger
logger = getlogger(__name__)
runinfo = {
'run': False,
'threading': None,
'loop': asyncio.new_event_loop(),
'queue': None
}
async def __even_put(runinfo, even: StandEven):
return await runinfo['queue'].put(even)
def even_put(even: StandEven):
global runinfo
if runinfo['run']:
asyncio.run_coroutine_threadsafe(__even_put(runinfo, even),
runinfo['loop'])
return
async def __evendeal(queue):
while True:
even = await queue.get()
try:
await async_send_even(even)
except:
s = traceback.format_exc(limit=10)
logger.error(s)
logger.error('出现这条消息表明模块出现异常')
queue.task_done()
def __runAsyncioTask(runinfo):
#设置事件循环
asyncio.set_event_loop(runinfo['loop'])
runinfo['queue'] = asyncio.Queue(128)
runinfo['loop'].run_forever()
def RunLoop():
"""
启动插件处理循环
"""
global runinfo
runinfo['threading'] = threading.Thread(group=None,
target=__runAsyncioTask,
args=(runinfo, ),
name='PlugAsyncio_thread',
daemon=True)
runinfo['threading'].start()
logger.info('插件事件处理循环启动...')
asyncio.run_coroutine_threadsafe(__evendeal(runinfo['queue']),
runinfo['loop'])
runinfo['run'] = True
|
<reponame>dlaidig/vqf
// SPDX-FileCopyrightText: 2021 <NAME> <<EMAIL>>
//
// SPDX-License-Identifier: MIT
#include "basicvqf.hpp"
#include <algorithm>
#include <limits>
#define _USE_MATH_DEFINES
#include <math.h>
#include <assert.h>
#define EPS std::numeric_limits<vqf_real_t>::epsilon()
#define NaN std::numeric_limits<vqf_real_t>::quiet_NaN()
inline vqf_real_t square(vqf_real_t x) { return x*x; }
BasicVQFParams::BasicVQFParams()
: tauAcc(3.0)
, tauMag(9.0)
{
}
BasicVQF::BasicVQF(vqf_real_t gyrTs, vqf_real_t accTs, vqf_real_t magTs)
{
coeffs.gyrTs = gyrTs;
coeffs.accTs = accTs > 0 ? accTs : gyrTs;
coeffs.magTs = magTs > 0 ? magTs : gyrTs;
setup();
}
BasicVQF::BasicVQF(const BasicVQFParams ¶ms, vqf_real_t gyrTs, vqf_real_t accTs, vqf_real_t magTs)
{
this->params = params;
coeffs.gyrTs = gyrTs;
coeffs.accTs = accTs > 0 ? accTs : gyrTs;
coeffs.magTs = magTs > 0 ? magTs : gyrTs;
setup();
}
BasicVQF::~BasicVQF()
{
}
void BasicVQF::updateGyr(const vqf_real_t gyr[3])
{
// gyroscope prediction step
vqf_real_t gyrNorm = norm(gyr, 3);
vqf_real_t angle = gyrNorm * coeffs.gyrTs;
if (gyrNorm > EPS) {
vqf_real_t c = cos(angle/2);
vqf_real_t s = sin(angle/2)/gyrNorm;
vqf_real_t gyrStepQuat[4] = {c, s*gyr[0], s*gyr[1], s*gyr[2]};
quatMultiply(state.gyrQuat, gyrStepQuat, state.gyrQuat);
normalize(state.gyrQuat, 4);
}
}
void BasicVQF::updateAcc(const vqf_real_t acc[3])
{
// ignore [0 0 0] samples
if (acc[0] == vqf_real_t(0.0) && acc[1] == vqf_real_t(0.0) && acc[2] == vqf_real_t(0.0)) {
return;
}
vqf_real_t accEarth[3];
// filter acc in inertial frame
quatRotate(state.gyrQuat, acc, accEarth);
filterVec(accEarth, 3, params.tauAcc, coeffs.accTs, coeffs.accLpB, coeffs.accLpA, state.accLpState, state.lastAccLp);
// transform to 6D earth frame and normalize
quatRotate(state.accQuat, state.lastAccLp, accEarth);
normalize(accEarth, 3);
// inclination correction
vqf_real_t accCorrQuat[4];
vqf_real_t q_w = sqrt((accEarth[2]+1)/2);
if (q_w > 1e-6) {
accCorrQuat[0] = q_w;
accCorrQuat[1] = 0.5*accEarth[1]/q_w;
accCorrQuat[2] = -0.5*accEarth[0]/q_w;
accCorrQuat[3] = 0;
} else {
// to avoid numeric issues when acc is close to [0 0 -1], i.e. the correction step is close (<= 0.00011°) to 180°:
accCorrQuat[0] = 0;
accCorrQuat[1] = 1;
accCorrQuat[2] = 0;
accCorrQuat[3] = 0;
}
quatMultiply(accCorrQuat, state.accQuat, state.accQuat);
normalize(state.accQuat, 4);
}
void BasicVQF::updateMag(const vqf_real_t mag[3])
{
// ignore [0 0 0] samples
if (mag[0] == vqf_real_t(0.0) && mag[1] == vqf_real_t(0.0) && mag[2] == vqf_real_t(0.0)) {
return;
}
vqf_real_t magEarth[3];
// bring magnetometer measurement into 6D earth frame
vqf_real_t accGyrQuat[4];
getQuat6D(accGyrQuat);
quatRotate(accGyrQuat, mag, magEarth);
// calculate disagreement angle based on current magnetometer measurement
vqf_real_t magDisAngle = atan2(magEarth[0], magEarth[1]) - state.delta;
// make sure the disagreement angle is in the range [-pi, pi]
if (magDisAngle > vqf_real_t(M_PI)) {
magDisAngle -= vqf_real_t(2*M_PI);
} else if (magDisAngle < vqf_real_t(-M_PI)) {
magDisAngle += vqf_real_t(2*M_PI);
}
vqf_real_t k = coeffs.kMag;
// ensure fast initial convergence
if (state.kMagInit != vqf_real_t(0.0)) {
// make sure that the gain k is at least 1/N, N=1,2,3,... in the first few samples
if (k < state.kMagInit) {
k = state.kMagInit;
}
// iterative expression to calculate 1/N
state.kMagInit = state.kMagInit/(state.kMagInit+1);
// disable if t > tauMag
if (state.kMagInit*params.tauMag < coeffs.magTs) {
state.kMagInit = 0.0;
}
}
// first-order filter step
state.delta += k*magDisAngle;
// make sure delta is in the range [-pi, pi]
if (state.delta > vqf_real_t(M_PI)) {
state.delta -= vqf_real_t(2*M_PI);
} else if (state.delta < vqf_real_t(-M_PI)) {
state.delta += vqf_real_t(2*M_PI);
}
}
void BasicVQF::update(const vqf_real_t gyr[3], const vqf_real_t acc[3])
{
updateGyr(gyr);
updateAcc(acc);
}
void BasicVQF::update(const vqf_real_t gyr[3], const vqf_real_t acc[3], const vqf_real_t mag[3])
{
updateGyr(gyr);
updateAcc(acc);
updateMag(mag);
}
void BasicVQF::updateBatch(const vqf_real_t gyr[], const vqf_real_t acc[], const vqf_real_t mag[], size_t N,
vqf_real_t out6D[], vqf_real_t out9D[], vqf_real_t outDelta[])
{
for (size_t i = 0; i < N; i++) {
if (mag) {
update(gyr+3*i, acc+3*i, mag+3*i);
} else {
update(gyr+3*i, acc+3*i);
}
if (out6D) {
getQuat6D(out6D+4*i);
}
if (out9D) {
getQuat9D(out9D+4*i);
}
if (outDelta) {
outDelta[i] = state.delta;
}
}
}
void BasicVQF::getQuat3D(vqf_real_t out[4]) const
{
std::copy(state.gyrQuat, state.gyrQuat+4, out);
}
void BasicVQF::getQuat6D(vqf_real_t out[4]) const
{
quatMultiply(state.accQuat, state.gyrQuat, out);
}
void BasicVQF::getQuat9D(vqf_real_t out[4]) const
{
quatMultiply(state.accQuat, state.gyrQuat, out);
quatApplyDelta(out, state.delta, out);
}
vqf_real_t BasicVQF::getDelta() const
{
return state.delta;
}
void BasicVQF::setTauAcc(vqf_real_t tauAcc)
{
if (params.tauAcc == tauAcc) {
return;
}
params.tauAcc = tauAcc;
double newB[3];
double newA[3];
filterCoeffs(params.tauAcc, coeffs.accTs, newB, newA);
filterAdaptStateForCoeffChange(state.lastAccLp, 3, coeffs.accLpB, coeffs.accLpA, newB, newA, state.accLpState);
std::copy(newB, newB+3, coeffs.accLpB);
std::copy(newA, newA+2, coeffs.accLpA);
}
void BasicVQF::setTauMag(vqf_real_t tauMag)
{
params.tauMag = tauMag;
coeffs.kMag = gainFromTau(params.tauMag, coeffs.magTs);
}
const BasicVQFParams& BasicVQF::getParams() const
{
return params;
}
const BasicVQFCoefficients& BasicVQF::getCoeffs() const
{
return coeffs;
}
const BasicVQFState& BasicVQF::getState() const
{
return state;
}
void BasicVQF::setState(const BasicVQFState& state)
{
this->state = state;
}
void BasicVQF::resetState()
{
quatSetToIdentity(state.gyrQuat);
quatSetToIdentity(state.accQuat);
state.delta = 0.0;
std::fill(state.lastAccLp, state.lastAccLp+3, 0);
std::fill(state.accLpState, state.accLpState + 3*2, NaN);
state.kMagInit = 1.0;
}
void BasicVQF::quatMultiply(const vqf_real_t q1[4], const vqf_real_t q2[4], vqf_real_t out[4])
{
vqf_real_t w = q1[0] * q2[0] - q1[1] * q2[1] - q1[2] * q2[2] - q1[3] * q2[3];
vqf_real_t x = q1[0] * q2[1] + q1[1] * q2[0] + q1[2] * q2[3] - q1[3] * q2[2];
vqf_real_t y = q1[0] * q2[2] - q1[1] * q2[3] + q1[2] * q2[0] + q1[3] * q2[1];
vqf_real_t z = q1[0] * q2[3] + q1[1] * q2[2] - q1[2] * q2[1] + q1[3] * q2[0];
out[0] = w; out[1] = x; out[2] = y; out[3] = z;
}
void BasicVQF::quatConj(const vqf_real_t q[4], vqf_real_t out[4])
{
vqf_real_t w = q[0];
vqf_real_t x = -q[1];
vqf_real_t y = -q[2];
vqf_real_t z = -q[3];
out[0] = w; out[1] = x; out[2] = y; out[3] = z;
}
void BasicVQF::quatSetToIdentity(vqf_real_t out[4])
{
out[0] = 1;
out[1] = 0;
out[2] = 0;
out[3] = 0;
}
void BasicVQF::quatApplyDelta(vqf_real_t q[], vqf_real_t delta, vqf_real_t out[])
{
// out = quatMultiply([cos(delta/2), 0, 0, sin(delta/2)], q)
vqf_real_t c = cos(delta/2);
vqf_real_t s = sin(delta/2);
vqf_real_t w = c * q[0] - s * q[3];
vqf_real_t x = c * q[1] - s * q[2];
vqf_real_t y = c * q[2] + s * q[1];
vqf_real_t z = c * q[3] + s * q[0];
out[0] = w; out[1] = x; out[2] = y; out[3] = z;
}
void BasicVQF::quatRotate(const vqf_real_t q[4], const vqf_real_t v[3], vqf_real_t out[3])
{
vqf_real_t x = (1 - 2*q[2]*q[2] - 2*q[3]*q[3])*v[0] + 2*v[1]*(q[2]*q[1] - q[0]*q[3]) + 2*v[2]*(q[0]*q[2] + q[3]*q[1]);
vqf_real_t y = 2*v[0]*(q[0]*q[3] + q[2]*q[1]) + v[1]*(1 - 2*q[1]*q[1] - 2*q[3]*q[3]) + 2*v[2]*(q[2]*q[3] - q[1]*q[0]);
vqf_real_t z = 2*v[0]*(q[3]*q[1] - q[0]*q[2]) + 2*v[1]*(q[0]*q[1] + q[3]*q[2]) + v[2]*(1 - 2*q[1]*q[1] - 2*q[2]*q[2]);
out[0] = x; out[1] = y; out[2] = z;
}
vqf_real_t BasicVQF::norm(const vqf_real_t vec[], size_t N)
{
vqf_real_t s = 0;
for(size_t i = 0; i < N; i++) {
s += vec[i]*vec[i];
}
return sqrt(s);
}
void BasicVQF::normalize(vqf_real_t vec[], size_t N)
{
vqf_real_t n = norm(vec, N);
if (n < EPS) {
return;
}
for(size_t i = 0; i < N; i++) {
vec[i] /= n;
}
}
void BasicVQF::clip(vqf_real_t vec[], size_t N, vqf_real_t min, vqf_real_t max)
{
for(size_t i = 0; i < N; i++) {
if (vec[i] < min) {
vec[i] = min;
} else if (vec[i] > max) {
vec[i] = max;
}
}
}
vqf_real_t BasicVQF::gainFromTau(vqf_real_t tau, vqf_real_t Ts)
{
assert(Ts > 0);
if (tau < vqf_real_t(0.0)) {
return 0; // k=0 for negative tau (disable update)
} else if (tau == vqf_real_t(0.0)) {
return 1; // k=1 for tau=0
} else {
return 1 - exp(-Ts/tau); // fc = 1/(2*pi*tau)
}
}
void BasicVQF::filterCoeffs(vqf_real_t tau, vqf_real_t Ts, double outB[], double outA[])
{
assert(tau > 0);
assert(Ts > 0);
// second order Butterworth filter based on https://stackoverflow.com/a/52764064
double fc = (M_SQRT2 / (2.0*M_PI))/double(tau); // time constant of dampened, non-oscillating part of step response
double C = tan(M_PI*fc*double(Ts));
double D = C*C + sqrt(2)*C + 1;
double b0 = C*C/D;
outB[0] = b0;
outB[1] = 2*b0;
outB[2] = b0;
// a0 = 1.0
outA[0] = 2*(C*C-1)/D; // a1
outA[1] = (1-sqrt(2)*C+C*C)/D; // a2
}
void BasicVQF::filterInitialState(vqf_real_t x0, const double b[3], const double a[2], double out[])
{
// initial state for steady state (equivalent to scipy.signal.lfilter_zi, obtained by setting y=x=x0 in the filter
// update equation)
out[0] = x0*(1 - b[0]);
out[1] = x0*(b[2] - a[1]);
}
void BasicVQF::filterAdaptStateForCoeffChange(vqf_real_t last_y[], size_t N, const double b_old[],
const double a_old[], const double b_new[],
const double a_new[], double state[])
{
if (isnan(state[0])) {
return;
}
for (size_t i = 0; i < N; i++) {
state[0+2*i] = state[0+2*i] + (b_old[0] - b_new[0])*last_y[i];
state[1+2*i] = state[1+2*i] + (b_old[1] - b_new[1] - a_old[0] + a_new[0])*last_y[i];
}
}
vqf_real_t BasicVQF::filterStep(vqf_real_t x, const double b[3], const double a[2], double state[2])
{
// difference equations based on scipy.signal.lfilter documentation
// assumes that a0 == 1.0
double y = b[0]*x + state[0];
state[0] = b[1]*x - a[0]*y + state[1];
state[1] = b[2]*x - a[1]*y;
return y;
}
void BasicVQF::filterVec(const vqf_real_t x[], size_t N, vqf_real_t tau, vqf_real_t Ts, const double b[3],
const double a[2], double state[], vqf_real_t out[])
{
assert(N>=2);
// to avoid depending on a single sample, average the first samples (for duration tau)
// and then use this average to calculate the filter initial state
if (isnan(state[0])) { // initialization phase
if (isnan(state[1])) { // first sample
state[1] = 0; // state[1] is used to store the sample count
for(size_t i = 0; i < N; i++) {
state[2+i] = 0; // state[2+i] is used to store the sum
}
}
state[1]++;
for (size_t i = 0; i < N; i++) {
state[2+i] += x[i];
out[i] = state[2+i]/state[1];
}
if (state[1]*Ts >= tau) {
for(size_t i = 0; i < N; i++) {
filterInitialState(out[i], b, a, state+2*i);
}
}
return;
}
for (size_t i = 0; i < N; i++) {
out[i] = filterStep(x[i], b, a, state+2*i);
}
}
void BasicVQF::setup()
{
assert(coeffs.gyrTs > 0);
assert(coeffs.accTs > 0);
assert(coeffs.magTs > 0);
filterCoeffs(params.tauAcc, coeffs.accTs, coeffs.accLpB, coeffs.accLpA);
coeffs.kMag = gainFromTau(params.tauMag, coeffs.magTs);
resetState();
}
|
<filename>static/js/noTableOrder.js
$('.nTOHederDownMove a').click(function(){
$(this).attr("class","nTOHederDownMoveActive").siblings().removeAttr("class","nTOHederDownMoveActive")
})
$(".nTOHederUp p").on("click",function(){
$(".nTOHederUp input").val("");
}) |
<gh_stars>1-10
package com.zhihuianxin.xyaxf.commonservice.thrift.user;
import com.zhihuianxin.xyaxf.commonservice.thrift.common.Gender;
import java.io.Serializable;
public class WXAccount implements Serializable {
public WXAccount(String open_id, String union_id, String nickname, String avatar, Gender gender, String country, String province, String city) {
this.open_id = open_id;
this.union_id = union_id;
this.nickname = nickname;
this.avatar = avatar;
this.gender = gender;
this.country = country;
this.province = province;
this.city = city;
}
public String open_id;
public String union_id;
public String nickname;
public String avatar;
public Gender gender;
public String country;
public String province;
public String city;
}
|
export default {
currentLevel: 3,
levelData: [{
briefing: `Ahoy newbie, on your first traning mission! ¶
To accelerate ship speed press and hold A button. ¶
To slow down press and hold D button. ¶
Your task will be to lure 10 police ship and don't let them catch you!
Good luck!!!`,
missionText: "Police ships lure: 0",
failText: "Ahhh newbie, you have \n\r to try harder. \n\r Again!",
successText: "Good job newbie. Lets continue your traning!"
}, {
briefing: `Ahoy newbie, your traning continue. Today you will learn how to collect valuable asteroids! ¶Brown are normal asteroid. He cost only 5$ ¶
Silver is asteroid rich on silver. He cost 10$ ¶
Gold one is asteroid rich on gold. He cost 20$ !!! ¶
Be careful with red one. They will explode if you or any ship touch them ¶
Your cargo compartment can hold only 5 asteroids for now.
So try to catch gold one!¶
It's time for a business!
Good luck!!!`,
missionText: "Asteroids collected: 0",
failText: "Ahhh newbie, you have to try harder. Try again!",
successText: `Good job crewman! You earn your first credits. For this I'll gift you with breaks. ¶
When you press S button your ship will stop for a 2 seconds. Later you can upgrade your engine. After short break you will be able to use them again ¶
`
}, {
briefing: ` Let's continue with your traning. Your next task will be to survive for 1 minute. Good luck !`,
missionText: "Time passed: 0:00",
failText: "Ahhh newbie, you have to try harder. Try again!",
successText: `Good job crewman! `
}, {
briefing: `Mission 4`,
missionText: " ",
failText: "Ahhh newbie, you have to try harder. Try again!",
successText: `Good job crewman! `
}]
}; |
#!/bin/bash
#
# @file node-exclude-ip.sh
# @brief uCodev Elastic Tools - Utilities
# Gracefully excludes a node from an Elasticsearch cluster based on it's Name
#
# Date: 29/10/2015
#
# Copyright 2015 Pedro A. Hortas (pah@ucodev.org)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
#
# uCodev Elastic Tools v0.1 - Utilities
#
# Description: Elasticsearch analysis, report and handling tools.
#
# Author: Pedro A. Hortas
# Email: pah@ucodev.org
# Date: 29/10/2015
#
if [ ${#} -ne 2 ]; then
echo "Usage: ${0} <host> <node name>"
exit 1;
fi
HOST=${1}
NNAME=${2}
curl -XPUT http://${HOST}:9200/_cluster/settings -d "{
\"transient\" :{
\"cluster.routing.allocation.exclude._name\" : \"${NNAME}\"
}
}"
echo ""
exit 0
|
<gh_stars>1-10
# -*- coding: utf-8 -*-
import csv
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
SENDER_EMAIL = '<EMAIL>'
SENDER_NAME = '<NAME> :)'
EMAIL_SUBJECT = f'Olá! Você tem um novo e-mail do {SENDER_NAME}'
# password = '@#!' # senha do email do remetente
def prepare_msg(recipient_name, recipient_email):
"""
Prepara e retorna uma mensagem de e-mail
"""
msg = MIMEMultipart('alternative')
msg['From'] = f'{SENDER_NAME} <{SENDER_EMAIL}>'
msg['To'] = recipient_email
msg['Subject'] = EMAIL_SUBJECT
text = '''
Olá ''' +recipient_name+ ''', este é um texto básico no corpo do e-mail e sem formatação,
caso o seu usuário abra esse e-mail em algum ~lugar~ sem suporte HTML.
'''
html = '''
<h1>Olá ''' +recipient_name+ ''',</h1>
<h4>este é um texto básico no corpo do e-mail e com formatação simples em HTML</h4>
<p>Esse texto irá aparecer caso o usuáriocaso o seu usuário abra esse e-mail em algum ~lugar~ COM suporte HTML.</p>
'''
msg.attach(MIMEText(text, 'plain'))
msg.attach(MIMEText(html, 'html'))
# According to RFC 2046, the last part of a multipart message, in this case
# the HTML message, is best and preferred.
return msg
def send_mail(recipient_name, recipient_email):
"""
Envia e-mail para o destinatário com email `recipient_email` e nome `recipient_name` .
"""
smtp = smtplib.SMTP('localhost', 1025)
# smtp = smtplib.SMTP('smtp.gmail.com', 587)
# smtp.starttls()
# smtp.login(send_from, password)
email_msg = prepare_msg(recipient_name, recipient_email)
smtp.sendmail(SENDER_EMAIL, recipient_email, email_msg.as_string())
smtp.close()
def process_file(filename):
"""
Abre o csv indicado por `filename` em modo leitura e para cada linha,
exeto a primeira (cabeçalho), extrai o nome e e-mail dos destinatários.
Para cada conjunto de nome e e-mail encontrado, a função de envio de e-mail
`send_mail` é executada.
"""
with open(filename, 'r') as csv_file:
users = csv.reader(csv_file, delimiter=',')
next(users, None) # pulando cabeçalho do csv
for name, email in users:
print(name,email)
send_mail(name, email)
if __name__ == '__main__':
process_file('lista.csv')
|
def generate_all_strings(char_list, n):
"""
This function will generate all possible strings of length n
using characters in the given list of characters
"""
if n == 0:
return [''] # Stopping condition
elif n == 1:
return char_list # Stopping condition
else:
# Generate all possible strings of length (n-1)
strings = generate_all_strings(char_list, n-1)
# Now for each string in the list, we add each character
# from the char_list to them and create a list of strings
current_strings = []
for string in strings:
for char in char_list:
current_strings.append(string + char)
return current_strings |
#!/bin/sh
set -e
set -u
set -o pipefail
if [ -z ${FRAMEWORKS_FOLDER_PATH+x} ]; then
# If FRAMEWORKS_FOLDER_PATH is not set, then there's nowhere for us to copy
# frameworks to, so exit 0 (signalling the script phase was successful).
exit 0
fi
echo "mkdir -p ${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}"
mkdir -p "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}"
COCOAPODS_PARALLEL_CODE_SIGN="${COCOAPODS_PARALLEL_CODE_SIGN:-false}"
SWIFT_STDLIB_PATH="${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}"
# Used as a return value for each invocation of `strip_invalid_archs` function.
STRIP_BINARY_RETVAL=0
# This protects against multiple targets copying the same framework dependency at the same time. The solution
# was originally proposed here: https://lists.samba.org/archive/rsync/2008-February/020158.html
RSYNC_PROTECT_TMP_FILES=(--filter "P .*.??????")
# Copies and strips a vendored framework
install_framework()
{
if [ -r "${BUILT_PRODUCTS_DIR}/$1" ]; then
local source="${BUILT_PRODUCTS_DIR}/$1"
elif [ -r "${BUILT_PRODUCTS_DIR}/$(basename "$1")" ]; then
local source="${BUILT_PRODUCTS_DIR}/$(basename "$1")"
elif [ -r "$1" ]; then
local source="$1"
fi
local destination="${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}"
if [ -L "${source}" ]; then
echo "Symlinked..."
source="$(readlink "${source}")"
fi
# Use filter instead of exclude so missing patterns don't throw errors.
echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${destination}\""
rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${destination}"
local basename
basename="$(basename -s .framework "$1")"
binary="${destination}/${basename}.framework/${basename}"
if ! [ -r "$binary" ]; then
binary="${destination}/${basename}"
fi
# Strip invalid architectures so "fat" simulator / device frameworks work on device
if [[ "$(file "$binary")" == *"dynamically linked shared library"* ]]; then
strip_invalid_archs "$binary"
fi
# Resign the code if required by the build settings to avoid unstable apps
code_sign_if_enabled "${destination}/$(basename "$1")"
# Embed linked Swift runtime libraries. No longer necessary as of Xcode 7.
if [ "${XCODE_VERSION_MAJOR}" -lt 7 ]; then
local swift_runtime_libs
swift_runtime_libs=$(xcrun otool -LX "$binary" | grep --color=never @rpath/libswift | sed -E s/@rpath\\/\(.+dylib\).*/\\1/g | uniq -u && exit ${PIPESTATUS[0]})
for lib in $swift_runtime_libs; do
echo "rsync -auv \"${SWIFT_STDLIB_PATH}/${lib}\" \"${destination}\""
rsync -auv "${SWIFT_STDLIB_PATH}/${lib}" "${destination}"
code_sign_if_enabled "${destination}/${lib}"
done
fi
}
# Copies and strips a vendored dSYM
install_dsym() {
local source="$1"
if [ -r "$source" ]; then
# Copy the dSYM into a the targets temp dir.
echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${DERIVED_FILES_DIR}\""
rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${DERIVED_FILES_DIR}"
local basename
basename="$(basename -s .framework.dSYM "$source")"
binary="${DERIVED_FILES_DIR}/${basename}.framework.dSYM/Contents/Resources/DWARF/${basename}"
# Strip invalid architectures so "fat" simulator / device frameworks work on device
if [[ "$(file "$binary")" == *"Mach-O dSYM companion"* ]]; then
strip_invalid_archs "$binary"
fi
if [[ $STRIP_BINARY_RETVAL == 1 ]]; then
# Move the stripped file into its final destination.
echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${DERIVED_FILES_DIR}/${basename}.framework.dSYM\" \"${DWARF_DSYM_FOLDER_PATH}\""
rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${DERIVED_FILES_DIR}/${basename}.framework.dSYM" "${DWARF_DSYM_FOLDER_PATH}"
else
# The dSYM was not stripped at all, in this case touch a fake folder so the input/output paths from Xcode do not reexecute this script because the file is missing.
touch "${DWARF_DSYM_FOLDER_PATH}/${basename}.framework.dSYM"
fi
fi
}
# Signs a framework with the provided identity
code_sign_if_enabled() {
if [ -n "${EXPANDED_CODE_SIGN_IDENTITY}" -a "${CODE_SIGNING_REQUIRED:-}" != "NO" -a "${CODE_SIGNING_ALLOWED}" != "NO" ]; then
# Use the current code_sign_identitiy
echo "Code Signing $1 with Identity ${EXPANDED_CODE_SIGN_IDENTITY_NAME}"
local code_sign_cmd="/usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} ${OTHER_CODE_SIGN_FLAGS:-} --preserve-metadata=identifier,entitlements '$1'"
if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then
code_sign_cmd="$code_sign_cmd &"
fi
echo "$code_sign_cmd"
eval "$code_sign_cmd"
fi
}
# Strip invalid architectures
strip_invalid_archs() {
binary="$1"
# Get architectures for current target binary
binary_archs="$(lipo -info "$binary" | rev | cut -d ':' -f1 | awk '{$1=$1;print}' | rev)"
# Intersect them with the architectures we are building for
intersected_archs="$(echo ${ARCHS[@]} ${binary_archs[@]} | tr ' ' '\n' | sort | uniq -d)"
# If there are no archs supported by this binary then warn the user
if [[ -z "$intersected_archs" ]]; then
echo "warning: [CP] Vendored binary '$binary' contains architectures ($binary_archs) none of which match the current build architectures ($ARCHS)."
STRIP_BINARY_RETVAL=0
return
fi
stripped=""
for arch in $binary_archs; do
if ! [[ "${ARCHS}" == *"$arch"* ]]; then
# Strip non-valid architectures in-place
lipo -remove "$arch" -output "$binary" "$binary" || exit 1
stripped="$stripped $arch"
fi
done
if [[ "$stripped" ]]; then
echo "Stripped $binary of architectures:$stripped"
fi
STRIP_BINARY_RETVAL=1
}
if [[ "$CONFIGURATION" == "Debug" ]]; then
install_framework "${BUILT_PRODUCTS_DIR}/Mockingjay/Mockingjay.framework"
install_framework "${BUILT_PRODUCTS_DIR}/Nimble/Nimble.framework"
install_framework "${BUILT_PRODUCTS_DIR}/Quick/Quick.framework"
install_framework "${BUILT_PRODUCTS_DIR}/URITemplate/URITemplate.framework"
fi
if [[ "$CONFIGURATION" == "Release" ]]; then
install_framework "${BUILT_PRODUCTS_DIR}/Mockingjay/Mockingjay.framework"
install_framework "${BUILT_PRODUCTS_DIR}/Nimble/Nimble.framework"
install_framework "${BUILT_PRODUCTS_DIR}/Quick/Quick.framework"
install_framework "${BUILT_PRODUCTS_DIR}/URITemplate/URITemplate.framework"
fi
if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then
wait
fi
|
# Copyright 2021 Curtin University
#
# 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.
# Author: <NAME>
import contextlib
import threading
from observatory.api.server.api import create_app
from observatory.api.server.orm import create_session, set_session
from sqlalchemy.pool import StaticPool
from werkzeug.serving import make_server
class ObservatoryApiEnvironment:
def __init__(self, host: str = "localhost", port: int = 5000, seed_db: bool = False):
"""Create an ObservatoryApiEnvironment instance.
:param host: the host name.
:param port: the port.
:param seed_db: whether to seed the database or not.
"""
self.host = host
self.port = port
self.seed_db = seed_db
self.db_uri = "sqlite://"
self.session = None
self.server = None
self.server_thread = None
@contextlib.contextmanager
def create(self):
"""Make and destroy an Observatory API isolated environment, which involves:
* Creating an in memory SQLite database for the API backend to connect to
* Start the Connexion / Flask app
:yield: None.
"""
try:
# Connect to in memory SQLite database with SQLAlchemy
self.session = create_session(
uri=self.db_uri, connect_args={"check_same_thread": False}, poolclass=StaticPool
)
set_session(self.session)
# Create the Connexion App and start the server
app = create_app()
self.server = make_server(self.host, self.port, app)
self.server_thread = threading.Thread(target=self.server.serve_forever)
self.server_thread.start()
yield
finally:
# Stop server and wait for server thread to join
self.server.shutdown()
self.server_thread.join()
|
SERVER_REQS_INSTALLED="FALSE"
SERVER_PID=""
DEFAULT_DB=""
PYTHON_QUERY_SCRIPT="
import os
import sys
args = sys.argv[sys.argv.index('--') + 1:]
query_results = None
expected_exception = None
working_dir, database, port_str, auto_commit, query_strs = args[0:5]
if len(args) > 5:
query_results = args[5]
if len(args) > 6:
expected_exception = args[6]
print('Query Strings: ' + query_strs)
print('Working Dir: ' + working_dir)
print('Database: ' + database)
print('Port: ' + port_str)
print('Autocommit: ' + auto_commit)
print('Expected Results: ' + str(query_results))
os.chdir(working_dir)
if auto_commit == '1':
auto_commit = True
else:
auto_commit = False
from pytest import DoltConnection, csv_to_row_maps
if not database:
dc = DoltConnection(port=int(port_str), database=None, user='dolt', auto_commit=auto_commit)
else:
dc = DoltConnection(port=int(port_str), database=database, user='dolt', auto_commit=auto_commit)
dc.connect()
queries = query_strs.split(';')
expected = [None]*len(queries)
if query_results is not None:
expected = query_results.split(';')
if len(expected) < len(queries):
expected.extend(['']*(len(queries)-len(expected)))
for i in range(len(queries)):
query_str = queries[i].strip()
print('executing:', query_str)
actual_rows, num_rows = None, None
try:
actual_rows, num_rows = dc.query(query_str, False)
except BaseException as e:
print('caught exception', str(e))
if expected_exception is not None and len(expected_exception) > 0:
if expected_exception not in str(e):
print('expected exception: ', expected_exception, '\n got: ', str(e))
sys.exit(1)
continue
else:
sys.exit(1)
if expected[i] is not None:
expected_rows = csv_to_row_maps(expected[i])
if expected_rows != actual_rows:
print('expected:', expected_rows, '\n actual:', actual_rows)
sys.exit(1)
"
set_server_reqs_installed() {
SERVER_REQS_INSTALLED=$(python3 -c "
requirements_installed = True
try:
import mysql.connector
except:
requirements_installed = False
print(str(requirements_installed).upper())
")
}
wait_for_connection() {
PYTEST_DIR="$BATS_TEST_DIRNAME/helper"
python3 -c "
import os
import sys
args = sys.argv[sys.argv.index('--') + 1:]
working_dir, database, port_str, timeout_ms = args
os.chdir(working_dir)
from pytest import wait_for_connection
wait_for_connection(port=int(port_str), timeout_ms=int(timeout_ms), database=database, user='dolt')
" -- "$PYTEST_DIR" "$DEFAULT_DB" "$1" "$2"
}
start_sql_server() {
DEFAULT_DB="$1"
let PORT="$$ % (65536-1024) + 1024"
dolt sql-server --host 0.0.0.0 --port=$PORT --user dolt &
SERVER_PID=$!
wait_for_connection $PORT 5000
}
# like start_sql_server, but the second argument is a string with all
# arguments to dolt-sql-server (excluding --port, which is defined in
# this func)
start_sql_server_with_args() {
DEFAULT_DB=""
let PORT="$$ % (65536-1024) + 1024"
dolt sql-server "$@" --port=$PORT &
SERVER_PID=$!
wait_for_connection $PORT 5000
}
start_sql_server_with_config() {
DEFAULT_DB="$1"
let PORT="$$ % (65536-1024) + 1024"
echo "
log_level: debug
user:
name: dolt
listener:
host: 0.0.0.0
port: $PORT
max_connections: 10
behavior:
autocommit: false
" > .cliconfig.yaml
cat "$2" >> .cliconfig.yaml
dolt sql-server --config .cliconfig.yaml &
SERVER_PID=$!
wait_for_connection $PORT 5000
}
start_sql_multi_user_server() {
DEFAULT_DB="$1"
let PORT="$$ % (65536-1024) + 1024"
echo "
log_level: debug
user:
name: dolt
listener:
host: 0.0.0.0
port: $PORT
max_connections: 10
behavior:
autocommit: false
" > .cliconfig.yaml
dolt sql-server --config .cliconfig.yaml &
SERVER_PID=$!
wait_for_connection $PORT 5000
}
start_multi_db_server() {
DEFAULT_DB="$1"
let PORT="$$ % (65536-1024) + 1024"
dolt sql-server --host 0.0.0.0 --port=$PORT --user dolt --multi-db-dir ./ &
SERVER_PID=$!
wait_for_connection $PORT 5000
}
# stop_sql_server stops the SQL server. For cases where it's important
# to wait for the process to exit after the kill signal (e.g. waiting
# for an async replication push), pass 1.
stop_sql_server() {
wait=$1
if [ ! -z "$SERVER_PID" ]; then
kill $SERVER_PID
fi
if [ $wait ]; then
while ps -p $SERVER_PID > /dev/null; do
sleep .1;
done
fi;
SERVER_PID=
}
# server_query connects to a running mysql server, executes a query and compares the results against what is expected.
# In the event that the results do not match expectations, the python process will exit with an exit code of 1
# * param1 is the database name for the connection string
# * param2 is 1 for autocommit = true, 0 for autocommit = false
# * param3 is the query_str
# * param4 is a csv representing the expected result set. If a query is not expected to have a result set "" should
# be passed.
# * param5 is an expected exception string. Mutually exclusive with param4
server_query() {
let PORT="$$ % (65536-1024) + 1024"
PYTEST_DIR="$BATS_TEST_DIRNAME/helper"
echo Executing server_query
python3 -u -c "$PYTHON_QUERY_SCRIPT" -- "$PYTEST_DIR" "$1" "$PORT" "$2" "$3" "$4" "$5"
}
# server_query connects to a running mysql server, executes a query and compares the results against what is expected.
# In the event that the results do not match expectations, the python process will exit with an exit code of 1
# * param1 is the database name for the connection string
# * param2 is 1 for autocommit = true, 0 for autocommit = false
# * param3 is the query_str
multi_query() {
let PORT="$$ % (65536-1024) + 1024"
PYTEST_DIR="$BATS_TEST_DIRNAME/helper"
echo Executing multi_query
python3 -c "$PYTHON_QUERY_SCRIPT" -- "$PYTEST_DIR" "$1" "$PORT" "$2" "$3"
}
# update_query runs an update query and should be called with 3 parameters
# * param1 is the database name for the connection string
# * param2 is 1 for autocommit = true, 0 for autocommit = false
# * param3 is the query string
update_query() {
server_query "$1" "$2" "$3" ""
}
# insert_query runs an insert query and should be called with 3 parameters
# * param1 is the database name for the connection string
# * param2 is 1 for autocommit = true, 0 for autocommit = false
# * param3 is the query string
insert_query() {
server_query "$1" "$2" "$3" ""
}
# unselected_server_query connects to a running mysql server, but not to a particular database, executes a query and
# compares the results against what is expected.
# In the event that the results do not match expectations, the python process will exit with an exit code of 1
# * param1 is 1 for autocommit = true, 0 for autocommit = false
# * param2 is the query_str
unselected_server_query() {
let PORT="$$ % (65536-1024) + 1024"
PYTEST_DIR="$BATS_TEST_DIRNAME/helper"
echo Executing server_query
python3 -c "$PYTHON_QUERY_SCRIPT" -- "$PYTEST_DIR" "" "$PORT" "$1" "$2" "$3"
}
# unselected_update_query runs an update query and should be called with 2 parameters
# * param1 is 1 for autocommit = true, 0 for autocommit = false
# * param2 is the query string
unselected_update_query() {
unselected_server_query $1 "$2" ""
}
# unselected_insert_query runs an insert query and should be called with 2 parameters
# * param1 is 1 for autocommit = true, 0 for autocommit = false
# * param2 is the query string
unselected_insert_query() {
unselected_server_query $1 "$2" ""
}
|
import {
isWrittenValueEmpty,
isLessThanLimit,
isGreaterThanLimit,
isShorterThanLimit,
isLongerThanLimit,
errorDataHandler,
} from 'simple-input-validators';
import getArraySum from 'get-array-sum';
import { isLiveValidatorEnable } from './../helpers/is-live-validator-enable';
import {
LiveValidator,
ValidatorErrorProps,
ValidatorsRulesListInsideValidator
} from '@common-types';
/**
* @description
* Живой валидатор кликабельных инпутов
*
* @param {HookProps} hooksData - Данные для хуков(контрол, его данные, форма)
*
* @returns {{ValidatorErrorProps}}
*
*/
export const validateClickedData: LiveValidator = hooksData => {
const { currentControl, newValue } = hooksData,
controlValidatorsRules = currentControl.validateRules as ValidatorsRulesListInsideValidator || {},
{
required: requiredRules,
minValue: minValueRules,
maxValue: maxValueRules,
minLength: minLengthRules,
maxLength: maxLengthRules,
} = controlValidatorsRules,
errorData: ValidatorErrorProps = {
hasError: false,
hasErrorLockingSubmitBtn: false,
shouldLockNotValidWrite: false,
message: null,
limit: null,
showLiveErrorAfterFirstSubmit: null,
hideErrorTimeout: null,
showErrorTimeout: null,
},
newValueArraySum = Array.isArray(newValue) ? getArraySum(newValue) : null,
shouldValidateArraySumValue = !isNaN(newValueArraySum),
hasError = true;
/**
* Обязательное поле
*/
if (
requiredRules &&
isWrittenValueEmpty(newValue) &&
isLiveValidatorEnable(requiredRules)
) {
const hasErrorLockingSubmitBtn = requiredRules.shouldLockSubmitBtnWhenControlInvalid
errorDataHandler(errorData, {
...requiredRules,
hasError,
hasErrorLockingSubmitBtn
});
}
/**
* Минимальная сумма элементов
*/
if (
minValueRules &&
shouldValidateArraySumValue &&
isLessThanLimit(newValueArraySum, minValueRules) &&
isLiveValidatorEnable(minValueRules)
) {
const hasErrorLockingSubmitBtn = minValueRules.shouldLockSubmitBtnWhenControlInvalid
errorDataHandler(errorData, {
...minValueRules,
hasError,
hasErrorLockingSubmitBtn
});
}
/**
* Максимальная сумма элементов
*/
if (
maxValueRules &&
shouldValidateArraySumValue &&
isGreaterThanLimit(newValueArraySum, maxValueRules) &&
isLiveValidatorEnable(maxValueRules)
) {
const hasErrorLockingSubmitBtn = maxValueRules.shouldLockSubmitBtnWhenControlInvalid
errorDataHandler(errorData, {
...maxValueRules,
hasError,
hasErrorLockingSubmitBtn
});
}
/**
* Минимальное кол-во элементов
*/
if (
minLengthRules &&
isShorterThanLimit(newValue, minLengthRules) &&
isLiveValidatorEnable(minLengthRules)
) {
const hasErrorLockingSubmitBtn = minLengthRules.shouldLockSubmitBtnWhenControlInvalid
errorDataHandler(errorData, {
...minLengthRules,
hasError,
hasErrorLockingSubmitBtn
});
}
/**
* Максимальное кол-во элементов
*/
if (
maxLengthRules &&
isLongerThanLimit(newValue, maxLengthRules) &&
isLiveValidatorEnable(maxLengthRules)
) {
const hasErrorLockingSubmitBtn = maxLengthRules.shouldLockSubmitBtnWhenControlInvalid
errorDataHandler(errorData, {
...maxLengthRules,
hasError,
hasErrorLockingSubmitBtn
});
}
return { errorData };
};
|
#include<bits/stdc++.h>
using namespace std;
#define n 100
class stackk{
int* ar;
int top;
public:
stackk(){
ar=new int[n];
top=-1;
}
void push(int x){
if(top==n-1){
cout<<"Stack Overflow"<<'\n';
return;
}
top++;
ar[top]=x;
}
void pop(){
if(top==-1){
cout<<"Stack is empty"<<'\n';
return;
}
top--;
}
int Top(){
if(top==-1){
cout<<"No element in stack"<<'\n';
return -1;
}
return ar[top];
}
bool empty(){
return top==-1;
}
};
int main(){
stackk st;
st.push(1);
st.push(2);
st.push(3);
st.pop();
cout<<st.Top()<<'\n';
cout<<st.empty()<<'\n';
return 0;
} |
#!/usr/bin/env bash
set -euo pipefail
ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE:-$0}")"; pwd)"
WORKSPACE_DIR="${ROOT_DIR}/../.."
if [ "${OSTYPE-}" = msys ] && [ -z "${MINGW_DIR+x}" ]; then
# On Windows MINGW_DIR (analogous to /usr) might not always be defined when we need it for some tools
if [ "${HOSTTYPE-}" = x86_64 ]; then
MINGW_DIR=/mingw64
elif [ "${HOSTTYPE-}" = i686 ]; then
MINGW_DIR=/mingw32
fi
fi
invoke_cc() {
local env_vars=() args=() env_parsed=0 result=0
if [ "${OSTYPE}" = msys ]; then
# On Windows we don't want automatic path conversion, since it can break non-path arguments
env_vars+=("MSYS2_ARG_CONV_EXCL=*")
fi
local arg; for arg in "$@"; do
if [ 0 -ne "${env_parsed}" ]; then
# Nothing to do if we've already finished converting environment variables.
args+=("${arg}")
elif [ "${arg}" == "--" ]; then
# Reached '--'? Then we're finished parsing environment variables.
env_parsed=1
else
if [ "${OSTYPE}" = msys ] && [ ! "${arg}" = "${arg#PATH=}" ]; then
# We need to split Windows-style paths and convert them to UNIX-style one-by-one.
local key="${arg%%=*}" # name of environment variable
local value="${arg#*=}" # value of environment variable
value="${value//'/'\\''}" # Escape single quotes
value="'${value//;/\' \'}'" # Replace semicolons by spaces for splitting
local paths; declare -a paths="(${value})" # Split into array
value=""
local path; for path in "${paths[@]}"; do
if [ "${OSTYPE}" = msys ]; then
path="${path//\\//}" # Convert 'C:\...' into 'C:/...'
fi
case "${path}" in
[a-zA-Z]:|[a-zA-Z]:/*)
# Convert 'C:/...' into '/c/...'
local drive; drive="${path%%:*}"
path="/${drive,,}${path#*:}"
;;
*) true;;
esac
if [ -n "${value}" ]; then
value="${value}:"
fi
value="${value}${path}" # Replace with modified PATH
done
arg="${key}=${value}" # Replace the environment variable with the modified version
fi
env_vars+=("${arg}")
fi
done
local cc; cc="${args[0]}"
case "${cc##*/}" in
clang*)
# Call iwyu with the modified arguments and environment variables (env -i starts with a blank slate)
local output
# shellcheck disable=SC2016
output="$(PATH="${PATH}:/usr/bin" env -i "${env_vars[@]}" "${SHELL-/bin/bash}" -c 'iwyu -isystem "$("$1" -print-resource-dir "${@:2}")/include" "${@:2}"' exec "${args[@]}" 3>&1 1>&2 2>&3- || true)." || result=$?
output="${output%.}"
if [ 0 -eq "${result}" ]; then
printf "%s" "${output}"
else
printf "%s" "${output}" 1>&2
fi
;;
esac
return "${result}"
}
_fix_include() {
"$(command -v python2 || echo python)" "$(command -v fix_include)" "$@"
}
process() {
# TODO(mehrdadn): Install later versions of iwyu that avoid suggesting <bits/...> headers
case "${OSTYPE}" in
linux*)
sudo apt-get install -qq -o=Dpkg::Use-Pty=0 clang iwyu
;;
esac
local target
target="$1"
CC=clang bazel build -k --config=iwyu "${target}"
CC=clang bazel aquery -k --config=iwyu --output=textproto "${target}" |
"$(command -v python3 || echo python)" "${ROOT_DIR}"/bazel.py textproto2json |
jq -s -r '{
"artifacts": map(select(.[0] == "artifacts") | (.[1] | map({(.[0]): .[1]}) | add) | {(.id): .exec_path}) | add,
"outputs": map(select(.[0] == "actions") | (.[1] | map({(.[0]): .[1]}) | add | select(.mnemonic == "iwyu_action") | .output_ids))
} | (. as $parent | .outputs | map($parent.artifacts[.])) | .[]' |
sed "s|^|$(bazel info | sed -n "s/execution_root: //p")/|" |
xargs -r -I {} -- sed -e "/^clang: /d" -e "s|[^ ]*_virtual_includes/[^/]*/||g" {} |
(
# Checkout & modify a clean copy of the repo to affecting the current one
local data new_worktree args=(--nocomments)
data="$(cat)"
new_worktree="$(TMPDIR="${WORKSPACE_DIR}/.." mktemp -d)"
git worktree add -q "${new_worktree}"
pushd "${new_worktree}"
echo "${data}" | _fix_include "${args[@]}" || true # HACK: For files are only accessible from the workspace root
echo "${data}" | { cd src && _fix_include "${args[@]}"; } || true # For files accessible from src/
git diff
popd # this is required so we can remove the worktree when we're done
git worktree remove --force "${new_worktree}"
)
}
postbuild() {
# Parsing might fail due to various things like aspects (e.g. BazelCcProtoAspect), but we don't want to check generated files anyway
local data="" # initialize in case next line fails
data="$(exec "$1" --decode=blaze.CppCompileInfo "$2" < "${3#*=}" 2>&-)" || true
if [ -n "${data}" ]; then
# Convert output to JSON-like format so we can parse it
data="$(exec sed -e "/^[a-zA-Z]/d" -e "s/^\(\s*\)\([0-9]\+\):\s*\(.*\)/\1[\2, \3],/g" -e "s/^\(\s*\)\([0-9]\+\)\s*{/\1[\2, /g" -e "s/^\(\s*\)}/\1],/g" <<< "${data}")"
# Turn everything into a single line by replacing newlines with a special character that should never appear in the actual stream
data="$(exec tr "\n" "\a" <<< "${data}")"
# Remove some fields that we don't want, and put back newlines we removed
data="$(exec sed -e "s/\(0x[0-9a-fA-F]*\)]\(,\a\)/\"\1\"]\2/g" -e "s/,\(\a\s*\(]\|\$\)\)/\1/g" -e "s/\a/\n/g" <<< "${data}")"
# Parse the resulting JSON and select the actual fields we're interested in.
# We put the environment variables first, separating them from the command-line arguments via '--'.
# shellcheck disable=SC1003
data="$(PATH="${PATH}:${MINGW_DIR-/usr}/bin" && exec jq -r '(
[]
+ [.[1:][] | select (.[0] == 6) | "\(.[1][1])=\(.[2][1])" | gsub("'\''"; "'\''\\'\'''\''") | "'\''\(.)'\''"]
+ ["--"]
+ [.[1:][] | select (.[0] == 1) | .[1] | gsub("'\''"; "'\''\\'\'''\''") | "'\''\(.)'\''"]
+ [.[1:][] | select (.[0] == 2 and (.[1] | type) == "string") | .[1] ]
) | .[]' <<< "${data}")"
# On Windows, jq can insert carriage returns; remove them
data="$(exec tr -d "\r" <<< "${data}")"
# Wrap everything into a single line for passing as argument array
data="$(exec tr "\n" " " <<< "${data}")"
eval invoke_cc "${data}"
fi
}
"$@"
|
<gh_stars>1-10
/*
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.floody.model;
import com.google.api.services.dfareporting.model.FloodlightActivityGroup;
import com.google.auto.value.AutoValue;
import org.checkerframework.checker.nullness.qual.Nullable;
@AutoValue
public abstract class FloodyGroup {
@Nullable
public abstract Long id();
public abstract String name();
public abstract String tagString();
public abstract GroupType type();
public abstract Long floodlightConfigurationId();
@Nullable
public abstract String creationRemarks();
public enum GroupType {
COUNTER,
SALE
}
public static FloodyGroup fromFloodlightActivity(FloodlightActivityGroup activityGroup) {
return builder()
.type(FloodyGroup.GroupType.valueOf(activityGroup.getType()))
.tagString(activityGroup.getTagString())
.name(activityGroup.getName())
.floodlightConfigurationId(activityGroup.getFloodlightConfigurationId())
.id(activityGroup.getId())
.build();
}
public abstract Builder toBuilder();
public static Builder builder() {
return new AutoValue_FloodyGroup.Builder();
}
@AutoValue.Builder
public abstract static class Builder {
public abstract Builder id(@Nullable Long id);
public abstract Builder name(String name);
public abstract Builder tagString(String tagString);
public abstract Builder type(GroupType type);
public abstract Builder floodlightConfigurationId(Long floodlightConfigurationId);
public abstract Builder creationRemarks(@Nullable String remarks);
public abstract FloodyGroup build();
}
}
|
import React from 'react';
import classNames from 'classnames';
import styles from './BigList.module.scss';
const BigList = ({ className, children }) => {
const cls = classNames(
styles.list,
className
);
return <ul className={cls}>{ children }</ul>
};
export default BigList;
|
<filename>logstash-core/lib/logstash/api/commands/stats.rb
# encoding: utf-8
require "logstash/api/commands/base"
require 'logstash/util/thread_dump'
require_relative "hot_threads_reporter"
java_import java.nio.file.Files
java_import java.nio.file.Paths
module LogStash
module Api
module Commands
class Stats < Commands::Base
def jvm
{
:threads => extract_metrics(
[:jvm, :threads],
:count,
:peak_count
),
:mem => memory,
:gc => gc,
:uptime_in_millis => service.get_shallow(:jvm, :uptime_in_millis),
}
end
def reloads
service.get_shallow(:stats, :reloads)
end
def process
extract_metrics(
[:jvm, :process],
:open_file_descriptors,
:peak_open_file_descriptors,
:max_file_descriptors,
[:mem, [:total_virtual_in_bytes]],
[:cpu, [:total_in_millis, :percent, :load_average]]
)
end
def events
extract_metrics(
[:stats, :events],
:in, :filtered, :out, :duration_in_millis, :queue_push_duration_in_millis
)
end
def pipeline(pipeline_id = nil)
if pipeline_id.nil?
pipeline_ids = service.get_shallow(:stats, :pipelines).keys
pipeline_ids.each_with_object({}) do |pipeline_id, result|
result[pipeline_id] = plugins_stats_report(pipeline_id)
end
else
{ pipeline_id => plugins_stats_report(pipeline_id) }
end
rescue # failed to find pipeline
{}
end
def memory
memory = service.get_shallow(:jvm, :memory)
{
:heap_used_percent => memory[:heap][:used_percent],
:heap_committed_in_bytes => memory[:heap][:committed_in_bytes],
:heap_max_in_bytes => memory[:heap][:max_in_bytes],
:heap_used_in_bytes => memory[:heap][:used_in_bytes],
:non_heap_used_in_bytes => memory[:non_heap][:used_in_bytes],
:non_heap_committed_in_bytes => memory[:non_heap][:committed_in_bytes],
:pools => memory[:pools].inject({}) do |acc, (type, hash)|
hash.delete("committed_in_bytes")
acc[type] = hash
acc
end
}
end
def os
service.get_shallow(:os)
rescue
# The only currently fetch OS information is about the linux
# containers.
{}
end
def gc
service.get_shallow(:jvm, :gc)
end
def hot_threads(options={})
HotThreadsReport.new(self, options)
end
private
def plugins_stats_report(pipeline_id)
stats = service.get_shallow(:stats, :pipelines, pipeline_id.to_sym)
PluginsStats.report(stats)
end
module PluginsStats
module_function
def plugin_stats(stats, plugin_type)
# Turn the `plugins` stats hash into an array of [ {}, {}, ... ]
# This is to produce an array of data points, one point for each
# plugin instance.
return [] unless stats[:plugins] && stats[:plugins].include?(plugin_type)
stats[:plugins][plugin_type].collect do |id, data|
{ :id => id }.merge(data)
end
end
def report(stats)
{
:events => stats[:events],
:plugins => {
:inputs => plugin_stats(stats, :inputs),
:filters => plugin_stats(stats, :filters),
:outputs => plugin_stats(stats, :outputs)
},
:reloads => stats[:reloads],
:queue => stats[:queue]
}.merge(stats[:dlq] ? {:dead_letter_queue => stats[:dlq]} : {})
end
end # module PluginsStats
end
end
end
end
|
<gh_stars>1-10
'use strict';
angular.module('erp', [
'ngCookies',
'ngResource',
'ngSanitize',
'ngRoute',
'http-auth-interceptor',
'ui.bootstrap',
'ui.utils',
'datatables'
])
.config(function ($routeProvider, $locationProvider) {
$routeProvider
.when('/', {
templateUrl: '/partials/home/index',
controller: 'MainCtrl'
})
.when('/auth/logout',{
templateUrl: '/partials/home/index',
controller: 'MainCtrl'
})
.when('/user/index', {
templateUrl: '/partials/user/index',
controller: 'UserCtrl'
})
.when('/user/:action', {
templateUrl: '/partials/user/add',
controller: 'UserCtrl'
})
.when('/user/:action/:id', {
templateUrl: '/partials/user/add',
controller: 'UserCtrl'
})
.when('/customer/index', {
templateUrl: '/partials/customer/index',
controller: 'CustomerCtrl'
})
.when('/customer/:action', {
templateUrl: '/partials/customer/add',
controller: 'CustomerCtrl'
})
.when('/customer/:action/:id', {
templateUrl: '/partials/customer/add',
controller: 'CustomerCtrl'
})
.when('/product/index', {
templateUrl: '/partials/product/index',
controller: 'ProductCtrl'
})
.when('/product/:action', {
templateUrl: '/partials/product/add',
controller: 'ProductCtrl'
})
.when('/product/:action/:id', {
templateUrl: '/partials/product/add',
controller: 'ProductCtrl'
})
.when('/monitor/inventory', {
templateUrl: '/partials/monitor/inventory',
controller: 'InventoryMonitorCtrl'
})
.when('/monitor/products', {
templateUrl: '/partials/monitor/products',
controller: 'MonitorCtrl'
})
.when('/monitor/customers', {
templateUrl: '/partials/monitor/customers',
controller: 'MonitorCtrl'
})
.when('/monitor/duplicate', {
templateUrl: '/partials/monitor/duplicate',
controller: 'MonitorCtrl'
})
.when('/packing/index', {
templateUrl: '/partials/packing/index',
controller: 'PackingCtrl'
})
.when('/packing/:action', {
templateUrl: '/partials/packing/add',
controller: 'PackingCtrl'
})
.when('/packing/:action/:id', {
templateUrl: '/partials/packing/add',
controller: 'PackingCtrl'
})
.when('/trips/index', {
templateUrl: '/partials/trips/index',
controller: 'TripsCtrl'
})
.when('/trips/:action', {
templateUrl: '/partials/trips/add',
controller: 'TripsCtrl'
})
.when('/trips/:action/:id', {
templateUrl: '/partials/trips/add',
controller: 'TripsCtrl'
})
.when('/sales/index/:type', {
templateUrl: '/partials/sales/index',
controller: 'SalesCtrl'
})
.when('/sales/order/:action', {
templateUrl: '/partials/sales/order',
controller: 'SalesOrderCtrl'
})
.when('/sales/order/:action/:id', {
templateUrl: '/partials/sales/order',
controller: 'SalesOrderCtrl'
})
.when('/sales/delivery/:action/:id', {
templateUrl: '/partials/sales/delivery',
controller: 'DeliveryReceiptCtrl'
})
.when('/sales/delivery/:action', {
templateUrl: '/partials/sales/delivery',
controller: 'DeliveryReceiptCtrl'
})
.when('/sales/invoice/:action/:id', {
templateUrl: '/partials/sales/invoice',
controller: 'SalesInvoiceCtrl'
})
.when('/sales/proforma/:action', {
templateUrl: '/partials/sales/proforma',
controller: 'SalesProformaCtrl'
})
.when('/sales/proforma/:action/:id', {
templateUrl: '/partials/sales/proforma',
controller: 'SalesProformaCtrl'
})
.when('/sales/promo/:action', {
templateUrl: '/partials/sales/promo',
controller: 'SalesPromoCtrl'
})
.when('/sales/promo/:action/:id', {
templateUrl: '/partials/sales/promo',
controller: 'SalesPromoCtrl'
})
.when('/sales/return/:action/:id', {
templateUrl: '/partials/sales/return',
controller: 'SalesReturnCtrl'
})
.when('/sales/memo/:action/:id', {
templateUrl: '/partials/sales/memo',
controller: 'SalesMemoCtrl'
})
.when('/sales/payment/:action', {
templateUrl: '/partials/sales/payment',
controller: 'SalesPaymentCtrl'
})
.when('/sales/payment/:action/:id', {
templateUrl: '/partials/sales/payment',
controller: 'SalesPaymentCtrl'
})
.when('/sales/monitor/:action/:id', {
templateUrl: '/partials/sales/monitor',
controller: 'SalesMonitorCtrl'
})
.when('/consignment/index/:type', {
templateUrl: '/partials/consignment/index',
controller: 'ConsignCtrl'
})
.when('/consignment/order/:action', {
templateUrl: '/partials/consignment/order',
controller: 'ConsignOrderCtrl'
})
.when('/consignment/order/:action/:id', {
templateUrl: '/partials/consignment/order',
controller: 'ConsignOrderCtrl'
})
.when('/consignment/delivery/:action', {
templateUrl: '/partials/consignment/delivery',
controller: 'ConsignDeliveryCtrl'
})
.when('/consignment/delivery/:action/:id', {
templateUrl: '/partials/consignment/delivery',
controller: 'ConsignDeliveryCtrl'
})
.when('/consignment/approval/:action', {
templateUrl: '/partials/consignment/approval',
controller: 'ConsignApprovalCtrl'
})
.when('/consignment/approval/:action/:id', {
templateUrl: '/partials/consignment/approval',
controller: 'ConsignApprovalCtrl'
})
.when('/consignment/packing/:action', {
templateUrl: '/partials/consignment/packing',
controller: 'ConsignPackingCtrl'
})
.when('/consignment/packing/:action/:id', {
templateUrl: '/partials/consignment/packing',
controller: 'ConsignPackingCtrl'
})
.when('/cds/index', {
templateUrl: '/partials/cds/index',
controller: 'CDSCtrl'
})
.when('/cds/:action', {
templateUrl: '/partials/cds/add',
controller: 'CDSCtrl'
})
.when('/cds/:action/:id', {
templateUrl: '/partials/cds/add',
controller: 'CDSCtrl'
})
.when('/memo/index', {
templateUrl: '/partials/memo/index',
controller: 'MemoCtrl'
})
.when('/memo/:action', {
templateUrl: '/partials/memo/add',
controller: 'MemoCtrl'
})
.when('/memo/:action/:id', {
templateUrl: '/partials/memo/add',
controller: 'MemoCtrl'
})
.when('/shipment/index/:type', {
templateUrl: '/partials/shipment/index',
controller: 'ShipmentCtrl'
})
.when('/shipment/:action', {
templateUrl: '/partials/shipment/add',
controller: 'ShipmentCtrl'
})
.when('/shipment/:action/:id', {
templateUrl: '/partials/shipment/add',
controller: 'ShipmentCtrl'
})
.when('/purchase/index', {
templateUrl: '/partials/purchase/index',
controller: 'PurchaseCtrl'
})
.when('/purchase/:action', {
templateUrl: '/partials/purchase/add',
controller: 'PurchaseCtrl'
})
.when('/purchase/:action/:id', {
templateUrl: '/partials/purchase/add',
controller: 'PurchaseCtrl'
})
.when('/adjustment/index', {
templateUrl: '/partials/adjustment/index',
controller: 'AdjustmentCtrl'
})
.when('/adjustment/:action', {
templateUrl: '/partials/adjustment/add',
controller: 'AdjustmentCtrl'
})
.when('/adjustment/:action/:id', {
templateUrl: '/partials/adjustment/add',
controller: 'AdjustmentCtrl'
})
.when('/calendar/index', {
templateUrl: '/partials/calendar/index',
controller: 'CalendarCtrl'
})
.when('/calendar/:action', {
templateUrl: '/partials/calendar/add',
controller: 'CalendarCtrl'
})
.when('/cycle/index', {
templateUrl: '/partials/cycle/index',
controller: 'CycleCtrl'
})
.when('/cycle/:action', {
templateUrl: '/partials/cycle/add',
controller: 'CycleCtrl'
})
.when('/cycle/:action/:id', {
templateUrl: '/partials/cycle/add',
controller: 'CycleCtrl'
})
.when('/promo/index', {
templateUrl: '/partials/promo/index',
controller: 'PromoCtrl'
})
.when('/promo/:action', {
templateUrl: '/partials/promo/add',
controller: 'PromoCtrl'
})
.when('/promo/:action/:id', {
templateUrl: '/partials/promo/add',
controller: 'PromoCtrl'
})
.when('/print/sales/:type/:id', {
templateUrl: '/partials/sales/index',
controller: 'PrintCtrl'
})
.when('/reports/:module/:type', {
templateUrl: '/partials/sales/reports',
controller: 'ReportCtrl'
})
.when('/reports/:module/:type/:id', {
templateUrl: '/partials/sales/record',
controller: 'ReportCtrl'
})
.when('/schedule/index', {
templateUrl: '/partials/schedule/index',
controller: 'ScheduleCtrl'
})
.when('/schedule/:action', {
templateUrl: '/partials/schedule/add',
controller: 'ScheduleCtrl'
})
.when('/schedule/:action/:id', {
templateUrl: '/partials/schedule/add',
controller: 'ScheduleCtrl'
})
.when('/merge/index', {
templateUrl: '/partials/merge/index',
controller: 'MergeCtrl'
})
.when('/merge/:action', {
templateUrl: '/partials/merge/add',
controller: 'MergeCtrl'
})
.when('/merge/:action/:id', {
templateUrl: '/partials/merge/add',
controller: 'MergeCtrl'
})
.when('/upload/inventories', {
templateUrl: '/partials/upload/inventories',
controller: 'UploadInventoriesCtrl'
})
.when('/upload/prices', {
templateUrl: '/partials/upload/prices',
controller: 'UploadPricesCtrl'
})
.when('/upload/contacts', {
templateUrl: '/partials/upload/contacts',
controller: 'UploadContactsCtrl'
})
.when('/auth/unauthorized', {
templateUrl: '/partials/home/unauthorized',
controller: 'MainCtrl'
})
.otherwise({
redirectTo: '/'
});
$locationProvider.html5Mode(true);
})
.run(function ($window,$rootScope, $location, Auth) {
//watching the value of the currentUser variable.
$rootScope.$watch('currentUser', function(currentUser) {
// if no currentUser and on a page that requires authorization then try to update it
// will trigger 401s if user does not have a valid session
if (!currentUser && (['/auth/login', '/auth/logout'].indexOf($location.path()) == -1 )) {
Auth.currentUser();
}
});
// On catching 401 errors, redirect to the login page.
$rootScope.$on('event:auth-loginRequired', function() {
$window.location.href = '/auth/login';
});
});
|
<reponame>Byndyusoft/node-casc
export * from "./cascSettingsDtoValidator";
export * from "./jsonSchemaValidator";
export * from "./keyPathsDtoValidator";
export * from "./valuesDtoValidator";
|
<gh_stars>1-10
import Enzyme, { shallow } from 'enzyme'
import Adapter from 'enzyme-adapter-react-16'
import {} from 'jest'
import React from 'react'
import CuneiformChar from '../CuneiformChar'
Enzyme.configure({ adapter: new Adapter() })
jest.mock('aphrodite/lib/inject')
test('<CuneiformChar /> contains the given character', () => {
const wrapper = shallow(<CuneiformChar value={'a'} translated={false} />)
expect(wrapper.text()).toBe('a')
})
|
import axios from 'axios'
import defaultsDeep from 'lodash/defaultsDeep'
const config = {
baseURL: 'https://randomuser.me/',
}
const baseApi = axios.create(config)
baseApi.request = (path, options) => baseApi(path, defaultsDeep(config, options))
export default baseApi
|
declare module 'react-flip-toolkit' {
export interface Spring {
stiffness?: number
damping?: number
overshootClamping?: boolean
}
export type SpringConfig = 'noWobble' | 'veryGentle' | 'gentle' | 'wobbly' | 'stiff' | Spring
export type FlippedComponentIdFilter = string | any[]
export interface FlippedWithContextProps {
children: React.ReactNode
inverseFlipId?: string
flipId?: string
opacity?: boolean
translate?: boolean
scale?: boolean
transformOrigin?: string
stagger?: string | boolean
spring?: SpringConfig
onStart?: (element: HTMLElement) => any
onComplete?: (element: HTMLElement) => any
onAppear?: (element: HTMLElement, index: number) => any
onDelayedAppear?: (element: HTMLElement, index: number) => any
onExit?: (element: HTMLElement, index: number, removeElement: () => any) => any
componentIdFilter?: FlippedComponentIdFilter
componentId?: string
portalKey?: string
}
export const FlippedWithContext: React.FunctionComponent<FlippedWithContextProps>
export const Flipped: React.FunctionComponent<FlippedWithContextProps>
export interface FlipperProps {
flipKey: any
children: React.ReactNode
spring?: SpringConfig
applyTransformOrigin?: boolean
debug?: boolean
element?: string
className?: string
portalKey?: string
jitterFix?: boolean
}
export class Flipper extends React.Component<FlipperProps, any> {
render(): JSX.Element
}
}
|
<reponame>warlock2207/warlock<filename>src/main/java/com/company/warlock/modular/wx/service/WxFriendService.java
package com.company.warlock.modular.wx.service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.company.warlock.core.common.page.LayuiPageFactory;
import com.company.warlock.modular.wx.entity.WxAccount;
import com.company.warlock.modular.wx.mapper.WxAccountMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
/**
* <p>
* 微信账号数据 服务实现类
* </p>
*
* @author ycw
* @since 2019-05-29
*/
@Service
public class WxFriendService extends ServiceImpl<WxAccountMapper, WxAccount> {
@Resource
private WxAccountMapper wxAccountMapper;
/**
* 获取任务信息表
*
* @author fengshuonan
* @Date 2018/12/23 6:05 PM
*/
public Page<Map<String, Object>> list(String beginTime) {
Page page = LayuiPageFactory.defaultPage();
return this.baseMapper.list(page, beginTime);
}
/**
* 查询列表时更新已经超过时间未完成的任务状态
*
* @author fengshuonan
* @Date 2018/12/23 5:00 PM
*/
@Transactional(rollbackFor = Exception.class)
public void updateAccountStatue(WxAccount wxAccount) {
this.baseMapper.updateAccountStatue(wxAccount);
}
/**
* 更新账号是否可以添加用户
*
* @author fengshuonan
* @Date 2018/12/23 5:00 PM
*/
@Transactional(rollbackFor = Exception.class)
public void updateAccountAdd(Long userID,String isAdd,List idList) {
this.baseMapper.updateAccountAdd(userID,isAdd,idList);
}
}
|
class Remake:
pass # Placeholder class for task rules
class TaskRule:
def __init__(self):
self.inputs = {}
self.outputs = {}
def rule_run(self):
raise NotImplementedError("Subclasses must implement rule_run method")
# Example usage:
ex8 = Remake()
class CannotRun(TaskRule):
rule_inputs = {'in1': 'data/inputs/input_not_there.txt'}
rule_outputs = {'out': 'data/inputs/ex8_in1.txt'}
def rule_run(self):
input_text = self.inputs['in1'].read_text()
self.outputs['out'].write_text(input_text + '\n')
# Additional task rule class
class CanRun1(TaskRule):
rule_inputs = {'in1': 'data/inputs/input1.txt'}
rule_outputs = {'out': 'data/outputs/output1.txt'}
def rule_run(self):
input_text = self.inputs['in1'].read_text()
processed_text = input_text.upper()
self.outputs['out'].write_text(processed_text) |
import {LoginResponse} from './login-response';
export class Token {
public accessToken: string;
public refreshToken: string;
public tokenType: string;
public tokenCreated: Date;
static fromAuthorization(loginResponse: LoginResponse): Token {
return new Token(loginResponse.accessToken, loginResponse.refreshToken, loginResponse.tokenType);
}
static fromRefresh(json: any): Token {
return new Token(json.access_token, json.refresh_token, json.token_type);
}
static fromSerialization(serialized: string): Token {
const json = JSON.parse(serialized);
return Token.fromJson(json);
}
static fromJson({accessToken, refreshToken, tokenType, tokenCreated}): Token {
return new Token(accessToken, refreshToken, tokenType, new Date(tokenCreated));
}
constructor(accessToken: string, refreshToken: string, tokenType: string, tokenExpires: Date = new Date()) {
this.accessToken = accessToken;
this.refreshToken = refreshToken;
this.tokenType = tokenType;
this.tokenCreated = tokenExpires;
}
public serialize(): string {
return JSON.stringify(this);
}
}
|
# Generated by Django 1.10.7 on 2017-06-30 10:54
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('prison', '0014_prisonercreditnoticeemail'),
]
operations = [
migrations.AlterModelOptions(
name='prisonerlocation',
options={'get_latest_by': 'created', 'ordering': ('prisoner_number',)},
),
migrations.AddField(
model_name='prisonerlocation',
name='single_offender_id',
field=models.UUIDField(blank=True, null=True),
),
migrations.AlterField(
model_name='prisonerlocation',
name='created_by',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to=settings.AUTH_USER_MODEL),
),
]
|
<reponame>levibostian/Trent
# frozen_string_literal: true
require 'travis'
require 'travis/pro' # For private repos
require_relative '../log'
# Functions to run on Travis
class TravisCI
def initialize(params = {})
Log.fatal('Cannot run commands against Travis when not running on a Travis server') unless TravisCI.running_on_travis?
@private = params.fetch(:private_repo, false)
@travis_token = params.fetch(:api_key)
authenticate
end
# If currently running on a Travis CI machine
def self.running_on_travis?
ENV['HAS_JOSH_K_SEAL_OF_APPROVAL']
end
# If CI job running on a pull request
def self.pull_request?
ENV['TRAVIS_PULL_REQUEST'].to_s == 'true'
end
# If the current job is a pull request, this will determine if the previous build for the current branch was successful or not.
# Note: An exception will be thrown if not in a pull request.
def branch_build_successful?
Log.fatal('Cannot determine if branch build was successful if not running on a pull request') unless TravisCI.pull_request?
travis_repo = repo
original_branch = ENV['TRAVIS_PULL_REQUEST_BRANCH']
travis_repo.branch(original_branch).green?
end
# Get repository from Travis
def repo
if @private
Travis::Pro::Repository.find(ENV['TRAVIS_REPO_SLUG'])
else
Travis::Repository.find(ENV['TRAVIS_REPO_SLUG'])
end
end
# If the previous build on current branch failed on Travis, skip this build too.
def fail_if_pr_branch_build_failed
return unless TravisCI.pull_request?
Log.warning('Checking if previous build for this branch was successful on Travis...')
Log.fatal('Skipping running command because previous build for branch failed.') unless branch_build_successful?
end
private
def authenticate
if @private
Travis::Pro.access_token = @travis_token
else
Travis.access_token = @travis_token
end
end
end
|
# Copyright (c) 2016, 2022, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
module OCI
module Jms::Models
OS_FAMILY_ENUM = [
OS_FAMILY_LINUX = 'LINUX'.freeze,
OS_FAMILY_WINDOWS = 'WINDOWS'.freeze,
OS_FAMILY_MACOS = 'MACOS'.freeze,
OS_FAMILY_UNKNOWN = 'UNKNOWN'.freeze
].freeze
end
end
|
"""
Generate a program to construct a histogram from input data.
"""
# Input data
data = [1, 2, 5, 4, 6, 8, 5, 3, 1, 9, 5, 3, 3, 3, 5, 3, 3, 1, 5]
# Initialize the empty histogram
hist = {}
# Count the occurrences of each value
for val in data:
if val not in hist:
hist[val] = 1
else:
hist[val] += 1
# Print the histogram
for val, count in hist.items():
print("(" + str(val) + ", " + str(count) + ")") |
<filename>src/swganh_core/object/intangible/intangible_factory.h
// This file is part of SWGANH which is released under the MIT license.
// See file LICENSE or go to http://swganh.com/LICENSE
#pragma once
#include "swganh_core/object/object_factory.h"
#include <unordered_map>
namespace swganh {
namespace database {
class DatabaseManagerInterface;
}} // swganh::database
namespace swganh {
namespace object {
class Intangible;
class IntangibleFactory : public swganh::object::ObjectFactory
{
public:
IntangibleFactory(swganh::app::SwganhKernel* kernel);
virtual ~IntangibleFactory() {}
virtual void LoadFromStorage(const std::shared_ptr<sql::Connection>& connection, const std::shared_ptr<Object>& object, boost::unique_lock<boost::mutex>& lock);
virtual uint32_t PersistObject(const std::shared_ptr<swganh::object::Object>& object, boost::unique_lock<boost::mutex>& lock, bool persist_inherited = false);
void DeleteObjectFromStorage(const std::shared_ptr<swganh::object::Object>& object);
virtual void PersistChangedObjects(){}
std::shared_ptr<swganh::object::Object> CreateObject();
virtual void RegisterEventHandlers(){}
private:
};
}} // namespace swganh::object
|
#!/usr/bin/env bash
python3 main.py --beta_UB=4.66 --delta=23.53 --no_gpu --domain riverswim --num_layers 1 --layer_size 16 --n_estimators 10 |
# Gemfile
gem 'rails'
gem 'bcrypt', '~> 3.1.7'
# routes.rb
Rails.application.routes.draw do
get '/login', to: 'sessions#new', as: 'login'
post '/login', to: 'sessions#create'
delete '/logout', to: 'sessions#destroy', as: 'logout'
get '/register', to: 'registrations#new', as: 'register'
post '/register', to: 'registrations#create'
get '/protected_route_1', to: 'protected#event_page', as: 'protected_1'
get '/protected_route_2', to: 'protected#view_data', as: 'protected_2'
get '/protected_route_3', to: 'protected#edit_data', as: 'protected_3'
end
# sessions_controller.rb
class SessionsController < ApplicationController
def new
end
def create
user = User.find_by(username: params[:username])
if user && user.authenticate(params[:password])
session[:user_id] = user.id
redirect_to root_path
else
render :new
end
end
def destroy
session.delete(:user_id)
redirect_to login_path
end
end
# registrations_controller.rb
class RegistrationsController < ApplicationController
def new
@user = User.new
end
def create
@user = User.new(user_params)
if @user.save
session[:user_id] = @user.id
redirect_to root_path
else
render :new
end
end
private
def user_params
params.require(:user).permit(:username, :password)
end
end
# application_controller.rb
class ApplicationController < ActionController::Base
before_action :require_login
private
def require_login
unless current_user
flash[:error] = "You must be logged in to access this section"
redirect_to login_path
end
end
def current_user
@current_user ||= User.find(session[:user_id]) if session[:user_id]
end
end |
#!/bin/bash
start=$(date +"%T")
for f in *.afa; do kalign "$f" Res"$f"; done
echo "============================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================"
finTime=$(date +"%T")
echo "Current time : $start"
echo "Current time : $finTime"
|
export const strToBool = s => {
return s == "0" ? false : true;
}
export const dateTransform = d_ => {
const [y, m, d, hh, mm] = getDateParts(d_)
if (!y) {
return ''
}
return `${d}.${m}.${y} ${hh}:${mm}`;
};
export const dateTransformYearFirst = d_ => {
const [y, m, d, hh, mm] = getDateParts(d_)
if (!y) {
return ''
}
return `${y}-${m}-${d} ${hh}:${mm}`;
}
export const getDateParts = d_ => {
const dateObj = new Date(Date.parse(d_) + new Date().getTimezoneOffset() * 60000);
const y = dateObj.getFullYear();
if (Number.isNaN(y)) {
return ''
}
let m = dateObj.getMonth() + 1;
if (Number.isNaN(m)) {
return ''
}
if (m < 10) {
m = `0${m}`;
} else {
m = `${m}`;
}
let d = dateObj.getDate();
if (Number.isNaN(d)) {
return ''
}
if (d < 10) {
d = `0${d}`;
} else {
d = `${d}`;
}
let hh = dateObj.getHours()
if (Number.isNaN(hh)) {
return ''
}
if (hh < 10) {
hh = `0${hh}`
} else {
hh = `${hh}`
}
let mm = dateObj.getMinutes()
if (Number.isNaN(mm)) {
return ''
}
if (mm < 10) {
mm = `0${mm}`
} else {
mm = `${mm}`
}
return [y, m, d, hh, mm]
}
export const dateTransform_rev = (d_) => {
const dateObj = new Date(Date.parse(`${d_}Z`));
return dateObj.toISOString();
};
|
// Create a data structure to store employee information
class Employee {
// Define properties
public String name;
public double salary;
public int age;
// Constructor
public Employee(String name, double salary, int age) {
// Initialize the properties
this.name = name;
this.salary = salary;
this.age = age;
}
} |
<filename>open-sphere-base/core/src/main/java/io/opensphere/core/event/ServerRequestEvent.java
package io.opensphere.core.event;
/**
* An event indicating the state of a server request.
*/
public class ServerRequestEvent extends AbstractMultiStateEvent
{
@Override
public String getDescription()
{
return "Event indicating the state of a server request.";
}
}
|
#!/bin/sh
#BSUB -q gpua100
#BSUB -J Laplace_A100
#BSUB -n 1
#BSUB -gpu "num=1:mode=exclusive_process"
#BSUB -W 24:00
#BSUB -R "rusage[mem=40GB]"
#BSUB -u oliversvaneolsen@gmail.com
#BSUB -B
#BSUB -N
#BSUB -o log.out_oliver
#BSUB -e log.err_oliver
# Load the cuda module
module load python3/3.8.11
module load cuda/11.3
module load cudnn/v8.2.0.53-prod-cuda-11.3
python3 main.py
|
#!/bin/bash
find . \( -name "bracket*" -o -name "postseason*" \) -not -path "./vp/*" | xargs -n1 -I% gsed -i -e 's/World Series/Hellmouth Cup/g' %
|
/*
* Copyright (c) 2015 The Regents of the University of California.
* All rights reserved.
*
* '$Author: crawl $'
* '$Date: 2017-09-04 12:59:35 -0700 (Mon, 04 Sep 2017) $'
* '$Revision: 1407 $'
*
* Permission is hereby granted, without written agreement and without
* license or royalty fees, to use, copy, modify, and distribute this
* software and its documentation for any purpose, provided that the above
* copyright notice and the following two paragraphs appear in all copies
* of this software.
*
* IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY
* FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
* ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF
* THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE
* PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF
* CALIFORNIA HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES,
* ENHANCEMENTS, OR MODIFICATIONS.
*
*/
package org.kepler.webview.server;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.stream.Collectors;
import org.apache.commons.io.FilenameUtils;
import org.kepler.build.modules.Module;
import org.kepler.build.modules.ModuleTree;
import org.kepler.gui.KeplerGraphFrame;
import org.kepler.gui.KeplerGraphFrame.Components;
import org.kepler.gui.KeplerGraphFrameUpdater;
import org.kepler.loader.util.ParseWorkflow;
import org.kepler.module.webview.Shutdown;
import org.kepler.objectmanager.lsid.KeplerLSID;
import org.kepler.provenance.ProvenanceRecorder;
import org.kepler.provenance.Queryable;
import org.kepler.provenance.Recording;
import org.kepler.util.ParseWorkflowUtil;
import org.kepler.webview.actor.ControlAttribute;
import org.kepler.webview.actor.ParametersAttribute;
import org.kepler.webview.server.app.App;
import org.kepler.webview.server.auth.AuthUtilities;
import org.kepler.webview.server.auth.WebViewAuthHandlerImpl;
import org.kepler.webview.server.handler.ActorHandler;
import org.kepler.webview.server.handler.AuthenticatedProxyHandler;
import org.kepler.webview.server.handler.LoginHandler;
import org.kepler.webview.server.handler.NoMatchHandler;
import org.kepler.webview.server.handler.RunIdHandler;
import org.kepler.webview.server.handler.RunWorkflowHandler;
import org.kepler.webview.server.handler.RunsHandler;
import org.kepler.webview.server.handler.TableOfContentsHandler;
import org.kepler.webview.server.handler.WorkflowHandler;
import com.hazelcast.config.Config;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.AsyncResult;
import io.vertx.core.DeploymentOptions;
import io.vertx.core.Future;
import io.vertx.core.Handler;
import io.vertx.core.Vertx;
import io.vertx.core.VertxOptions;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.http.HttpMethod;
import io.vertx.core.http.HttpServer;
import io.vertx.core.http.HttpServerOptions;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.http.ServerWebSocket;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.core.net.PemKeyCertOptions;
import io.vertx.core.net.SocketAddress;
import io.vertx.core.spi.cluster.ClusterManager;
import io.vertx.ext.auth.AuthProvider;
import io.vertx.ext.auth.User;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.client.HttpResponse;
import io.vertx.ext.web.client.WebClient;
import io.vertx.ext.web.handler.AuthHandler;
import io.vertx.ext.web.handler.BodyHandler;
import io.vertx.ext.web.handler.CookieHandler;
import io.vertx.ext.web.handler.CorsHandler;
import io.vertx.ext.web.handler.SessionHandler;
import io.vertx.ext.web.handler.UserSessionHandler;
import io.vertx.ext.web.sstore.ClusteredSessionStore;
import io.vertx.ext.web.sstore.LocalSessionStore;
import io.vertx.ext.web.sstore.SessionStore;
import io.vertx.spi.cluster.hazelcast.HazelcastClusterManager;
import ptolemy.actor.CompositeActor;
import ptolemy.actor.ExecutionListener;
import ptolemy.actor.Manager;
import ptolemy.actor.gui.ConfigurationApplication;
import ptolemy.kernel.util.Attribute;
import ptolemy.kernel.util.IllegalActionException;
import ptolemy.kernel.util.NamedObj;
import ptolemy.kernel.util.Settable;
import ptolemy.kernel.util.Workspace;
import ptolemy.moml.MoMLParser;
import ptolemy.moml.filter.BackwardCompatibility;
import ptolemy.util.MessageHandler;
public class WebViewServer extends AbstractVerticle {
/** Execute an app.
* @param json The JSON object with the workflow name and any parameters.
* @param handler Asynchronous handler to receive the a JSON object with any results.
*/
public void executeApp(JsonObject json, User user,
Handler<AsyncResult<JsonObject>> handler) {
String appName = json.getString("app_name");
//System.out.println("execute workflow " + wfName);
if(appName == null || appName.trim().isEmpty()) {
handler.handle(Future.failedFuture("No app_name specified."));
return;
}
if(user == null) {
handler.handle(Future.failedFuture("User is not authenticated"));
return;
}
for(String key: json.fieldNames()) {
if(!key.equals("app_name") &&
!key.equals("app_param") &&
!key.equals("prov") &&
!key.equals("reqid") &&
!key.equals("sync")) {
System.err.println("WARNING: unknown property in request: " + key);
}
}
// the following will block, e.g., waiting on the workspace lock,
// so execute in blocking threads.
_vertx.<JsonObject>executeBlocking(future -> {
//System.out.println("executeBlocking " + wfName);
boolean runSynchronously = false;
App app = null;
boolean running = false;
// see if app is already loaded
try {
app = _getApp(appName);
if(app == null) {
throw new Exception("App not found.");
}
JsonObject appParams;
if(json.containsKey("app_param")) {
try {
appParams = json.getJsonObject("app_param");
} catch(ClassCastException e) {
throw new Exception("app_param must be a json object.");
}
} else {
appParams = new JsonObject();
}
runSynchronously = json.getBoolean("sync", false);
if(!runSynchronously) {
throw new Exception("Asynchronous execution not supported for apps.");
}
if(runSynchronously) {
// execute the application
running = true;
final App appCopy = app;
app.exec(user, appParams, appHandler -> {
if(appHandler.failed()) {
future.fail(appHandler.cause());
} else {
future.complete(new JsonObject().put("responses", appHandler.result()));
}
appCopy.close();
});
}
} catch (Exception e) {
e.printStackTrace();
future.fail("Error executing app: " + e.getMessage());
return;
} finally {
if(!running) {
app.close();
}
}
// set ordered to false to allow parallel executions,
// and use handler for result.
}, false, handler);
}
/** Execute a workflow.
* @param requestJson The JSON object with the workflow name and any parameters.
* @param handler Asynchronous handler to receive the a JSON object with any results.
*/
public void executeWorkflow(JsonObject requestJson, User user,
Handler<AsyncResult<JsonObject>> handler) {
// TODO check for unknown arguments in the request json
String wfName = requestJson.getString("wf_name");
//System.out.println("execute workflow " + wfName);
if(wfName == null || wfName.trim().isEmpty()) {
handler.handle(Future.failedFuture("No wf_name specified."));
return;
}
if(user == null) {
handler.handle(Future.failedFuture("User is not authenticated"));
return;
}
user.isAuthorized("executeWorkflow:" + wfName, resExec -> {
if(resExec.failed()) {
handler.handle(Future.failedFuture("User is not allowed to execute " + wfName));
return;
}
// TODO correct way to convert Buffer to JSON?
//System.out.println("recvd: " + json);
boolean useWebHook = requestJson.containsKey("webhook");
boolean runSynchronously = requestJson.getBoolean("sync", false);
boolean recordProvenance = requestJson.getBoolean("prov", true);
// cannot run async without provenance or webhook
if(!runSynchronously && !recordProvenance && !useWebHook) {
handler.handle(Future.failedFuture("Cannot execute workflow asynchronously " +
"without recording provenance or using webhook."));
return;
}
// cannot run synchronously and use webhook
if(runSynchronously && useWebHook) {
handler.handle(Future.failedFuture("Cannot execute workflow synchronously " +
"and use webhook."));
return;
}
if(useWebHook) {
JsonObject webHookJson = requestJson.getJsonObject("webhook");
if(!webHookJson.containsKey("url")) {
handler.handle(Future.failedFuture("Webhook object must contain url."));
return;
}
}
// the following will block, e.g., waiting on the workspace lock,
// so execute in blocking threads.
_vertx.<JsonObject>executeBlocking(future -> {
//System.out.println("executeBlocking " + wfName);
ProvenanceRecorder recorder = null;
CompositeActor model = null;
// see if workflow is already loaded
try {
model = _getModel(wfName);
if(model == null) {
throw new Exception("Workflow not found.");
}
try {
_setModelParameters(wfName, model, requestJson, user);
} catch (IllegalActionException e) {
future.fail(e.getMessage());
return;
}
recorder = ProvenanceRecorder.getDefaultProvenanceRecorder(model);
if(recordProvenance) {
if(recorder == null) {
if(!ProvenanceRecorder.addProvenanceRecorder(model, null, null)) {
throw new Exception("Error adding provenance recorder to workflow.");
}
recorder = ProvenanceRecorder.getDefaultProvenanceRecorder(model);
if(recorder == null) {
throw new Exception("Cannot find provenance recorder in workflow after adding one.");
}
}
//System.out.println("setting provenance username = " + user.principal().getString("username"));
recorder.username.setToken(user.principal().getString("username"));
} else if (recorder != null) {
recorder.setContainer(null);
}
// create manager and add model
final Manager manager = new Manager(model.workspace(), "Manager");
try {
model.setManager(manager);
} catch(IllegalActionException e) {
throw new Exception("Error setting Manager for sub-workflow: " + e.getMessage());
}
String[] errorMessage = new String[1];
ExecutionListener managerListener = new ExecutionListener() {
@Override
public void executionError(Manager m, Throwable throwable) {
System.err.println("Workflow execution error: " + throwable.getMessage());
throwable.printStackTrace();
errorMessage[0] = throwable.getMessage();
}
@Override
public void executionFinished(Manager m) {
//System.out.println("finished");
}
@Override
public void managerStateChanged(Manager m) {
//System.out.println("manager state changed " + m.getState().getDescription());
}
};
manager.addExecutionListener(managerListener);
if(runSynchronously || useWebHook) {
final String[] runLSIDStr = new String[1];
if(recordProvenance) {
recorder.addPiggyback(new Recording() {
@Override
public void executionStart(KeplerLSID lsid) {
runLSIDStr[0] = lsid.toString();
}
});
}
final boolean[] timeout = new boolean[1];
timeout[0] = false;
long timerId = vertx.setTimer(_workflowTimeout, id -> {
timeout[0] = true;
manager.stop();
if(useWebHook) {
_postToWebHook(requestJson,
new JsonObject().put("error", "Execution timeout."));
} else {
future.fail("Execution timeout.");
}
});
// if using webhook, send response to client now that
// workflow execution has started
if(useWebHook) {
handler.handle(Future.succeededFuture(new JsonObject()));
}
// call execute() instead of run, otherwise exceptions
// go to execution listener asynchronously.
try {
manager.execute();
} catch(Exception e) {
if(!vertx.cancelTimer(timerId)) {
System.err.println("Workflow timeout Timer does not exist.");
}
else if(useWebHook) {
_postToWebHook(requestJson,
new JsonObject().put("error", "Execution error:" + e.getMessage()));
return;
}
throw e;
}
// see if we timed-out. if so, we already sent the response,
// so exit.
if(timeout[0]) {
return;
} else if(!vertx.cancelTimer(timerId)) {
System.err.println("Workflow timeout Timer does not exist.");
}/* else {
System.out.println("cancelled timer.");
}*/
// see if there is a workflow exception
if(errorMessage[0] != null) {
if(useWebHook) {
_postToWebHook(requestJson,
new JsonObject().put("error", "Execution error: " + errorMessage[0]));
return;
}
System.err.println("errorMessage = " + errorMessage);
future.fail(errorMessage[0]);
return;
}
JsonObject responseJson = new JsonObject();
if(recordProvenance) {
responseJson.put("id", runLSIDStr[0]);
}
// build the response JSON object from the client buffers
// for this workflow.
JsonArray arrayJson = new JsonArray();
List<JsonObject> outputs = getClientBuffer(model);
if(outputs != null) {
for(JsonObject outputJson : outputs) {
if(outputJson.containsKey("actor")) {
JsonObject actorObject = outputJson.getJsonObject("actor");
for(String idStr : actorObject.fieldNames()) {
JsonObject idObject = actorObject.getJsonObject(idStr);
if(idObject.containsKey("data")) {
arrayJson.add(idObject.getJsonObject("data"));
}
}
}
}
}
// send the successful response
//System.out.println(arrayJson.encodePrettily());
responseJson.put("responses", arrayJson);
if(useWebHook) {
_postToWebHook(requestJson, responseJson);
} else {
future.complete(responseJson);
}
} else { // asynchronous and no webhook
final CompositeActor finalModel = model;
recorder.addPiggyback(new Recording() {
@Override
public void executionStart(KeplerLSID lsid) {
//System.out.println("execution lsid is " + lsid);
future.complete(new JsonObject().put("id", lsid.toString()));
}
@Override
public void executionStop() {
removeModel(finalModel);
}
});
manager.startRun();
}
} catch (Exception e) {
future.fail("Error executing workflow: " + e.getMessage());
// e.printStackTrace();
return;
} finally {
if(model != null && (runSynchronously || useWebHook)) {
removeModel(model);
model = null;
}
}
// set ordered to false to allow parallel executions,
// and use handler for result.
}, false, handler);
});
}
private void _postToWebHook(JsonObject requestJson, JsonObject responseJson) {
JsonObject webHookJson = requestJson.getJsonObject("webhook");
String webHookURLStr = webHookJson.getString("url");
Object reqId = requestJson.getValue("reqid");
if(reqId != null) {
responseJson.put("reqid", reqId);
}
if(webHookJson.containsKey("secret")) {
responseJson.put("secret", webHookJson.getString("secret"));
}
WebClient client = WebClient.create(WebViewServer.vertx());
client.postAbs(webHookURLStr)
.sendJsonObject(responseJson, ar -> {
if(ar.failed()) {
System.err.println("WARNING: webhook post failed " +
webHookURLStr + ": " + ar.cause());
} else {
HttpResponse<Buffer> response = ar.result();
if(response.statusCode() != HttpURLConnection.HTTP_OK) {
System.err.println("WARNING: webhook post failed (" +
response.statusCode() +
") " + webHookURLStr + ":");
System.err.println(response.bodyAsString());
}
}
});
}
/** Search for a file. The directories searched are the root directory (if specified),
* and <module>/resources/html/.
* @param name The name of the file to search for.
* @return If the path is found, the absolute path of the file.
* Otherwise, returns null.
*/
public static String findFile(String name) {
//System.out.println("findFile: " + name);
if(_appendIndexHtml && name.endsWith("/")) {
name = name.concat("index.html");
}
// search root dir first if specified
if(_rootDir != null) {
String fsPath = new StringBuilder(_rootDir)
.append(File.separator)
.append(name)
.toString();
// TODO check path is not outside _rootDir
if(_vertx.fileSystem().existsBlocking(fsPath)) {
return fsPath;
}
}
// not found in root dir, so search module tree.
for(Module module : _moduleTree) {
String fsPath = new StringBuilder(module.getResourcesDir().getAbsolutePath())
.append(File.separator)
.append("html")
.append(File.separator)
.append(name).toString();
// TODO check path is not outside of resources/html dir
//System.out.println("checking " + fsPath);
if(_vertx.fileSystem().existsBlocking(fsPath)) {
return fsPath;
}
}
// not found anywhere
return null;
}
/** Get the client buffers for a workflow. */
public static List<JsonObject> getClientBuffer(NamedObj model) {
return _clientBuffers.get(model);
}
/** Called during initialization. */
public static void initialize() {
int workerPoolSize = WebViewConfiguration.getHttpServerWorkerThreads();
VertxOptions options = new VertxOptions()
.setWorkerPoolSize(workerPoolSize)
.setMaxWorkerExecuteTime(Long.MAX_VALUE);
if(WebViewConfiguration.shouldStartClusterHazelcast()) {
Config hazelcastConfig = new Config();
ClusterManager mgr = new HazelcastClusterManager(hazelcastConfig);
if (WebViewConfiguration.deployInKubernetes()) {
hazelcastConfig.getNetworkConfig().getJoin().getMulticastConfig().setEnabled(false);
hazelcastConfig.getNetworkConfig().getJoin().getKubernetesConfig().setEnabled(true)
.setProperty("service-dns", WebViewConfiguration.getHazelcastDiscoveryDnsServiceName());
}
options.setClusterManager(mgr);
Vertx.clusteredVertx(options, result -> {
if(result.failed()) {
MessageHandler.error("Failed to get vertx context.", result.cause());
// TODO shutdown?
} else {
_vertx = result.result();
_initializeAfterCreatingVertx();
}
});
} else if(!WebViewConfiguration.shouldStartCluster()) {
_vertx = Vertx.vertx(options);
_initializeAfterCreatingVertx();
} else {
MessageHandler.error("Unknown value for cluster type in configuration.xml.");
Shutdown.shutdownLatch.countDown();
}
}
private static void _initializeAfterCreatingVertx() {
String rootDir = WebViewConfiguration.getHttpServerRootDir();
if(rootDir != null &&
!rootDir.equals(WebViewConfiguration.DEFAULT_WEBVIEW_SERVER_ROOT_DIR)) {
_rootDir = rootDir;
System.out.println("Web view root dir is " + _rootDir);
}
_appendIndexHtml = WebViewConfiguration.getHttpServerAppendIndexHtml();
_workflowTimeout = WebViewConfiguration.getHttpServerWorkflowTimeout();
// register as an updater to get window open and close events
KeplerGraphFrame.addUpdater(_updater);
// start logging thread
_loggingThread = new Thread(new Runnable() {
@Override
public void run() {
String logPath = WebViewConfiguration.getHttpServerLogPath();
System.out.println("Web-view logging to " + logPath);
try(FileWriter writer = new FileWriter(logPath, true)) {
String message;
try {
while((message = _loggingQueue.take()) != STOP_LOGGING_THREAD_MESSAGE) {
writer.write(message);
writer.write('\n');
writer.flush();
}
} catch (InterruptedException e) {
MessageHandler.error("Interrupted while waiting in logging thread.", e);
}
} catch (IOException e) {
MessageHandler.error("Error trying to write to web-view server log " +
logPath, e);
}
}
});
_loggingThread.start();
boolean daemon = WebViewConfiguration.shouldStartHttpServerAsDaemon();
if(daemon) {
System.out.println("Loading MoML filters.");
// We set the list of MoMLFilters to handle Backward Compatibility.
MoMLParser.setMoMLFilters(BackwardCompatibility.allFilters());
// load the gui and cache configuration since we need the CacheManager
// to load the KAREntryHandlers for exporting provenance kars.
try {
ConfigurationApplication.readConfiguration(
ConfigurationApplication.specToURL("ptolemy/configs/kepler/ConfigGUIAndCache.xml"));
} catch (Exception e) {
MessageHandler.error("Error creating Configuration.", e);
}
}
if(WebViewConfiguration.shouldStartHttpServer() || daemon) {
/* TODO still necessary?
List<URL> list = new LinkedList<URL>();
for(String path : System.getProperty("java.class.path").split(File.pathSeparator)) {
try {
list.add(new File(path).toURI().toURL());
} catch (MalformedURLException e) {
MessageHandler.error("Bad URL.", e);
}
}
*/
// list.toArray(new URL[list.size()]),
DeploymentOptions deploymentOptions = new DeploymentOptions()
.setInstances(WebViewConfiguration.getHttpServerInstances());
WebViewServer.vertx().deployVerticle(
WebViewServer.class.getName(),
deploymentOptions,
deployResult -> {
if(deployResult.failed()) {
MessageHandler.error("Failed to deploy web view server.", deployResult.cause());
// TODO shut down kepler.
}
}
);
for(String model: WebViewConfiguration.getPreloadModels()) {
System.out.println("Preloading " + model);
try {
if(_getModel(model) == null) {
System.err.println("ERROR: Unable to find model for preload: " + model);
}
} catch (Exception e) {
System.err.println("ERROR: Unable to preload " + model + ": " + e.getMessage());
}
}
// TODO preload apps
} else {
// not starting server, so set latch to 0
Shutdown.shutdownLatch.countDown();
}
}
/** Log an http server request.
* @param request The request
* @param user The user
* @param status The status
* @param timestamp The timestamp when the request occurred.
*/
public void log(HttpServerRequest request, User user, int status, long timestamp) {
log(request, user, status, timestamp, -1);
}
/** Log an http server request.
* @param request The request
* @param user The user
* @param status The status
* @param timestamp The timestamp when the request occurred.
* @param length The length of the file successfully sent to the client.
*/
public void log(HttpServerRequest request, User user, int status, long timestamp, long length) {
String versionStr;
switch(request.version()) {
case HTTP_1_1:
versionStr = "HTTP/1.1";
break;
case HTTP_1_0:
versionStr = "HTTP/1.0";
break;
default:
versionStr = "-";
break;
}
String hostString;
SocketAddress address = request.remoteAddress();
if(address == null) {
hostString = "-";
} else {
hostString = address.host();
}
String referrer = request.headers().get("referrer");
if(referrer == null) {
referrer = "-";
}
String userAgent = request.headers().get("user-agent");
if(userAgent == null) {
userAgent = "-";
}
String userNameStr = "-";
if(user != null) {
//System.out.println(user);
userNameStr = user.principal().getString("username");
}
// TODO how to get user-identifier and userid?
String message = String.format("%s - %s [%s] \"%s %s %s\" %d %s \"%s\" \"%s\"",
hostString,
userNameStr,
_logTimeFormat.format(new Date(timestamp)),
request.method(),
request.uri(),
versionStr,
status,
length < 0 ? "-" : String.valueOf(length),
referrer,
userAgent);
try {
_loggingQueue.put(message);
} catch (InterruptedException e) {
MessageHandler.error("Interuppted adding to logging thread.", e);
}
}
public void log(ServerWebSocket socket, String command, String path) {
log(socket, command, path, null);
}
public void log(ServerWebSocket socket, String command, String path, Buffer buffer) {
final long timestamp = System.currentTimeMillis();
String hostString;
SocketAddress address = socket.remoteAddress();
if(address == null) {
hostString = "-";
} else {
hostString = address.host();
}
String referrer = socket.headers().get("referrer");
if(referrer == null) {
referrer = "-";
}
String userAgent = socket.headers().get("user-agent");
if(userAgent == null) {
userAgent = "-";
}
String message = String.format("%s - - [%s] \"%s %s %s %s\" %s %s \"%s\" \"%s\"",
hostString,
_logTimeFormat.format(new Date(timestamp)),
command,
path,
buffer == null ? "-" : buffer.toString(),
"websocket",
"-", // status
"-", // length
referrer,
userAgent);
try {
_loggingQueue.put(message);
} catch (InterruptedException e) {
MessageHandler.error("Interuppted adding to logging thread.", e);
}
}
/** Start the server. */
@Override
public void start() throws Exception {
super.start();
_auth = WebViewConfiguration.getAuthProvider();
_queryable = ProvenanceRecorder.getDefaultQueryable(null);
if(_queryable == null) {
throw new Exception("Unable to get provenance queryable.");
}
Router router = Router.router(vertx);
if(WebViewConfiguration.getHttpServerCorsEnabled()) {
String allowOriginPatternStr = WebViewConfiguration.getHttpServerCorsAllowOriginPattern();
if(allowOriginPatternStr == null || allowOriginPatternStr.trim().isEmpty()) {
throw new Exception("Must specify allow origini pattern for CORS.");
}
router.route().handler(CorsHandler.create(allowOriginPatternStr)
.allowedMethod(HttpMethod.GET)
.allowedMethod(HttpMethod.POST)
.allowedMethod(HttpMethod.OPTIONS)
.allowCredentials(true)
.allowedHeader("Access-Control-Allow-Credentials")
.allowedHeader("X-PINGARUNER")
.allowedHeader("Content-Type")
.allowedHeader("authorization"));
System.out.println("CORS enabled for " + allowOriginPatternStr);
}
// create cookie and session handlers
// authenticated users are cached in the session so authentication
// does not need to be performed for each request.
router.route().handler(CookieHandler.create());
BodyHandler bodyHandler = BodyHandler.create();
if(_rootDir != null) {
File uploadsDir = new File(_rootDir, "file-uploads");
if(!uploadsDir.exists()) {
if(!uploadsDir.mkdirs()) {
throw new Exception("Unable to create file uploads directory " + uploadsDir);
}
}
bodyHandler.setUploadsDirectory(uploadsDir.getAbsolutePath());
}
// NOTE: need to install the BodyHandler before any handlers that
// make asynchronous calls such as BasicAuthHandler.
router.route().handler(bodyHandler);
SessionStore sessionStore;
if(WebViewConfiguration.shouldStartCluster()) {
sessionStore = ClusteredSessionStore.create(_vertx);
} else {
sessionStore = LocalSessionStore.create(_vertx);
}
SessionHandler sessionHandler = SessionHandler.create(sessionStore)
.setSessionCookieName("WebViewSession")
.setSessionTimeout(WebViewConfiguration.getHttpServerSessionTimeout());
router.route().handler(sessionHandler);
router.route().handler(UserSessionHandler.create(_auth));
//System.out.println("session timeout = " + WebViewConfiguration.getHttpServerSessionTimeout());
// use custom auth handler with custom auth scheme to prevent
// browsers (e.g., chrome) from opening auth dialog.
// FIXME read realm from conf file.
AuthHandler authenticationHandler = new WebViewAuthHandlerImpl(_auth, "WebView");
Handler<RoutingContext> authorizationHandler = new Handler<RoutingContext>() {
@Override
public void handle(RoutingContext c) {
if(c.user() == null) {
c.next();
} else {
c.user().isAuthorized("login", result -> {
if(result.failed()) {
c.response()
.putHeader("Content-type", "text/plain")
.setStatusCode(HttpURLConnection.HTTP_FORBIDDEN)
.end(result.cause().getMessage());
} else {
c.next();
}
});
}
}
};
// everything under /kepler and /app needs to be
// authenticated and authorized.
router.route("/kepler/*")
.handler(authenticationHandler)
.handler(authorizationHandler);
router.route("/app")
.handler(authenticationHandler)
.handler(authorizationHandler);
// TODO should these be under /kepler?
router.getWithRegex("^/wf/(\\d+)$").handler(new WorkflowHandler(this));
router.getWithRegex("^/wf/(\\d+(?:\\-\\d+)+)$").handler(new ActorHandler(this));
RunWorkflowHandler runWorkflowHandler = new RunWorkflowHandler(this);
router.post("/kepler/runwf").handler(runWorkflowHandler::handleRunWorkflow);
router.post("/app").handler(runWorkflowHandler::handleRunApp);
router.post("/kepler/runs").handler(new RunsHandler(this));
RunIdHandler runIdHandler = new RunIdHandler(this);
String runIdRegexStr = "(urn:lsid:[^:]+:[^:]+:[^:]+(?::\\d+)?)";
router.getWithRegex("/kepler/runs/" + runIdRegexStr + "/(\\w+)").blockingHandler(runIdHandler::handleBinary);
router.getWithRegex("/kepler/runs/" + runIdRegexStr).handler(runIdHandler);
if(WebViewConfiguration.getHttpServerMetadataFileName() != null) {
System.out.println("Metadata file set; requests at /login");
router.route("/login")
.handler(authenticationHandler)
.handler(authorizationHandler);
LoginHandler loginHandler = new LoginHandler(this);
router.route("/login").handler(loginHandler);
// login session handler to check if session cookie is valid.
/*
router.route("/loginSession")
.handler(authorizationHandler)
.handler(loginSessionContext -> {
System.out.println("session " + loginSessionContext.session().id());
// if not valid, return 400
if(loginSessionContext.user() == null) {
System.out.println("user is null");
loginSessionContext.response()
.putHeader("Content-Type", "text/plain")
.setStatusCode(HttpURLConnection.HTTP_BAD_REQUEST)
.end();
} else {
// otherwise call login handler to return metadata.
loginSessionContext.next();
}
});
router.route("/loginSession").handler(loginHandler);
*/
// logout handler to remove session and user.
router.route("/logout").handler(authenticationHandler);
// FIXME what about authorization handler?
router.route("/logout").handler(logoutContext -> {
//System.out.println("destroying session " + logoutContext.session().id());
logoutContext.session().destroy();
logoutContext.clearUser();
logoutContext.response()
.putHeader("Content-Type", "text/plain")
.end();
});
}
if(WebViewConfiguration.enableHttpServerTableOfContents()) {
String path = WebViewConfiguration.getHttpServerTableOfContentsPath();
if(path == null) {
path = "^(?:/kepler/toc){0,1}/*$";
}
System.out.println("Enabling http server table of contents at " + path);
router.getWithRegex(path).handler(new TableOfContentsHandler(this));
}
// add any authenticated proxies
for(String path: WebViewConfiguration.getHttpServerAuthenticatedProxyPaths()) {
router.route(path)
.handler(authenticationHandler)
.handler(authorizationHandler)
.handler(new AuthenticatedProxyHandler(path));
}
// add route that handles anything unmatched
router.route().handler(new NoMatchHandler(this));
if(WebViewConfiguration.enableHttps()) {
sessionHandler.setCookieSecureFlag(true);
String pemKeyStr = WebViewConfiguration.getHttpsPEMKeyPath();
if(pemKeyStr == null) {
throw new Exception("Must specify PEM key file for HTTPS server.");
}
if(!new File(pemKeyStr).canRead()) {
throw new Exception("Cannot read PEM key file for HTTPS server: " + pemKeyStr);
}
String pemCertStr = WebViewConfiguration.getHttpsPEMCertPath();
if(pemCertStr == null) {
throw new Exception("Must specify PEM certificate file for HTTPS server.");
}
if(!new File(pemCertStr).canRead()) {
throw new Exception("Cannot read PEM certificate file for HTTPS server: " + pemCertStr);
}
int securePort = WebViewConfiguration.getHttpsServerPort();
// FIXME what if pemCert or pemKey do not exist?
HttpServerOptions options = new HttpServerOptions()
.setSsl(true)
.setPemKeyCertOptions(new PemKeyCertOptions()
.setCertPath(pemCertStr)
.setKeyPath(pemKeyStr))
.setPort(securePort);
System.out.println("Starting secure web server on port " + securePort);
_secureServer = vertx.createHttpServer(options)
// TODO had to comment out for AuthenticatedProxyHandler
//.websocketHandler(new WorkflowWebSocketHandler(this))
.requestHandler(router::accept)
.listen();
if(WebViewConfiguration.shouldHttpServerRedirect()) {
int status = WebViewConfiguration.getHttpServerRedirectStatus();
String hostname = WebViewConfiguration.getHttpServerRedirectHostname();
int redirectFromPort = WebViewConfiguration.getHttpServerPort();
int redirectToPort = WebViewConfiguration.getHttpServerRedirectPort();
String redirectUrl = "https://" + hostname + ":" + redirectToPort;
System.out.println("Redirecting web view server port " + redirectFromPort +
" to " + redirectUrl + " with status " + status);
_server = vertx.createHttpServer()
.requestHandler(req -> {
req.response().headers().set("Location", redirectUrl + req.path());
req.response()
.setStatusCode(status)
.end();
})
.listen(redirectFromPort);
}
} else {
int port = WebViewConfiguration.getHttpServerPort();
System.out.println("Starting web view server on port " + port);
_server = vertx.createHttpServer()
// TODO had to comment out for AuthenticatedProxyHandler
//.websocketHandler(new WorkflowWebSocketHandler(this))
.requestHandler(router::accept)
.listen(port);
}
}
public static void removeModel(NamedObj model) {
// notify any clients that the workflow was closed.
try {
WebViewableUtilities.sendEvent(
WebViewableUtilities.Event.WorkflowClosed, model);
} catch (IllegalActionException e) {
MessageHandler.error("Error notifying clients that workflow closed.", e);
}
WebViewId.removeWorkflow(model);
//System.gc();
_clientBuffers.remove(model);
//System.out.println("removing " + model + " " + model.hashCode());
/*
for(CompositeActor master : _models.values()) {
System.out.println("master " + master + " " + master.hashCode());
}
*/
//System.out.println("remove " + model.hashCode());
//_models.remove(model);
//System.out.println("removed workflow " + model.getName());
}
/** Called during shutdown. */
public static void shutdown() {
KeplerGraphFrame.removeUpdater(_updater);
for(CompositeActor model : _models.values()) {
removeModel(model);
}
_models.clear();
for(App app : _apps.values()) {
app.close();
}
_apps.clear();
// stop the logging thread
_loggingQueue.add(STOP_LOGGING_THREAD_MESSAGE);
try {
_loggingThread.join(5000);
} catch (InterruptedException e) {
MessageHandler.error("Interrupted while waiting for logging thread to stop.", e);
}
_loggingThread = null;
}
/** Stop the server. */
@Override
public void stop() throws Exception {
super.stop();
if(_server != null) {
//System.out.println("Stopping vertx web server.");
_server.close();
_server = null;
}
if(_secureServer != null) {
_secureServer.close();
_secureServer = null;
}
}
public static Vertx vertx() {
return _vertx;
}
private static class ModelUpdater implements KeplerGraphFrameUpdater {
@Override
public int compareTo(KeplerGraphFrameUpdater o) {
return 1;
}
@Override
public void updateFrameComponents(Components components) {
try {
CompositeActor model = (CompositeActor) components.getFrame().getModel();
_addModel(model);
_models.put(model.getName(), model);
} catch (Exception e) {
MessageHandler.error("Error adding model from UI.", e);
}
}
/** Remove the model associated with the frame from the web server. */
@Override
public void dispose(KeplerGraphFrame frame) {
CompositeActor model = (CompositeActor) frame.getModel();
removeModel(model);
_models.remove(model.getName());
}
}
///////////////////////////////////////////////////////////////////
//// public variables ////
public final static String WS_PATH = "/ws/";
public final static String WS_RUNWF_PATH = "/ws-runwf";
///////////////////////////////////////////////////////////////////
//// package-protected variables ////
///////////////////////////////////////////////////////////////////
//// private methods ////
/** Add a model to the set managed by the server. */
public static void _addModel(CompositeActor model) throws Exception {
//System.out.println("adding model " + model.getFullName());
//_models.add(model);
//System.out.println("put " + model.hashCode());
_clientBuffers.put(model, new LinkedList<JsonObject>());
/*
ProvenanceRecorder recorder = ProvenanceRecorder.getDefaultProvenanceRecorder(model);
if(recorder != null) {
recorder.addPiggyback(new WebViewRecording());
}
*/
if(model.attributeList(ControlAttribute.class).isEmpty()) {
ControlAttribute control = new ControlAttribute(model, "_wvControl");
control.setPersistent(false);
}
if(model.attributeList(ParametersAttribute.class).isEmpty()) {
ParametersAttribute parameters = new ParametersAttribute(model, "_wvParameters");
parameters.setPersistent(false);
}
/*
WebViewAttribute timeline = (WebViewAttribute) model.getAttribute("_wfTimeline");
if(timeline == null) {
timeline = new WebViewAttribute(model, "_wfTimeline");
timeline.htmlFile.setExpression("web-view/visjs/wf-timeline.html");
timeline.title.setExpression("Workflow Execution Timeline");
}
timeline.setPersistent(false);
*/
}
/** Get a clone of a model. */
private static CompositeActor _cloneModel(CompositeActor masterModel) throws CloneNotSupportedException {
CompositeActor model = (CompositeActor)masterModel.clone(new Workspace());
_clientBuffers.put(model, new LinkedList<JsonObject>());
//System.out.println("put " + model.hashCode());
return model;
}
/** Convert from a JSON object value to a string representation of a Ptolemy token. */
private static String _convertJSONToTokenString(Object value) {
if(value instanceof JsonArray) {
StringBuilder buf = new StringBuilder("{");
Iterator<Object> iter = ((JsonArray)value).iterator();
while(iter.hasNext()) {
Object item = iter.next();
// strings need to be surrounded by quotes in arrays
if(item instanceof String) {
buf.append("\"")
.append(item)
.append("\"");
} else {
// item may be a complex type (e.g., record token)
buf.append(_convertJSONToTokenString(item));
}
if(iter.hasNext()) {
buf.append(",");
}
}
return buf.append("}").toString();
} else if(value instanceof JsonObject) {
// convert json objects to ptolemy record strings.
StringBuilder buf = new StringBuilder("{");
Iterator<Entry<String, Object>> iter = ((JsonObject)value).iterator();
while(iter.hasNext()) {
Entry<String,Object> entry = iter.next();
buf.append(entry.getKey())
.append("=")
.append(_convertJSONToTokenString(entry.getValue()));
if(iter.hasNext()) {
buf.append(",");
}
};
return buf.append("}").toString();
} else {
// FIXME if value is a string and parameter is not in string mode,
// will this work?
return value.toString();
}
}
@SuppressWarnings("resource")
private App _getApp(String name) throws Exception {
App masterApp = null;
synchronized(_apps) {
// see if we've already instantiated this app
masterApp = _apps.get(name);
if(masterApp == null) {
String className = WebViewConfiguration.getAppClassName(name);
if(className == null || className.trim().isEmpty()) {
throw new Exception("Missing class name for app " + name);
}
try {
Class<?> appClass = Class.forName(className);
masterApp = (App) appClass.newInstance();
_apps.put(name, masterApp);
} catch(ClassNotFoundException | InstantiationException
| IllegalAccessException e) {
throw new Exception("Error instantiating app " + name + ": " + e.getMessage());
}
}
}
return (App) masterApp.clone();
}
/** Get the model for a specific name. If the model is not already
* loaded, then use findFile() to find the model file with the
* given name, name.kar and name.xml. Otherwise, return a copy
* of the already-loaded model.
* @return If a model with the specified name is loaded or can be
* found and parsed, returns the model. Otherwise, null.
*/
private static CompositeActor _getModel(String name) throws Exception {
//System.out.println("size = " + _models.size());
synchronized(_models) {
// see if the model is already loaded.
CompositeActor masterModel = _models.get(name);
if(masterModel != null) {
//System.out.println("found master model.");
return _cloneModel(masterModel);
}
// if not, find workflow file and load
String wfFileStr = findFile(name);
if(wfFileStr == null) {
wfFileStr = findFile(name + ".kar");
if(wfFileStr == null) {
wfFileStr = findFile(name + ".xml");
if(wfFileStr == null) {
return null;
}
}
}
masterModel = (CompositeActor) ParseWorkflow.parseKAR(new File(wfFileStr), true);
_addModel(masterModel);
_models.put(name, masterModel);
//System.out.println("adding master model " + name);
// see if there is a configuration file for parameters
File wfFile = new File(wfFileStr);
File wfDir = wfFile.getParentFile();
File wfConfFile = new File(wfDir,
FilenameUtils.getBaseName(wfFileStr) + ".conf");
if(wfConfFile.exists()) {
ParseWorkflowUtil.setParametersFromFile(masterModel, wfConfFile.getAbsolutePath());
}
return _cloneModel(masterModel);
}
}
/** Set model parameters from json key-values.
* @param model the model
* @param params a set of parameters to set in the model
* @param jsonValueObjectsAreRanges if true, any value in params that
* is an JSONObject is checked for "min" and "max" keys, which are then
* used to validate the corresponding value in alreadySetParams.
* @param alreadySetParams a set of parameters already set in the model
*
*/
private static void _setModelParametersFromJson(NamedObj model,
JsonObject params, boolean jsonValueObjectsAreRanges,
JsonObject alreadySetParams)
throws IllegalActionException {
for(Map.Entry<String, Object> entry: params) {
final String paramName = entry.getKey();
//System.out.println("attempting to set parameter " + paramName);
Attribute attribute = model.getAttribute(paramName);
if(attribute == null || !(attribute instanceof Settable)) {
throw new IllegalActionException("Workflow does not have settable parameter " + paramName);
}
Object paramValue = entry.getValue();
if(jsonValueObjectsAreRanges && (paramValue instanceof JsonObject)) {
JsonObject paramValueJsonObject = ((JsonObject)paramValue);
if(alreadySetParams != null && alreadySetParams.containsKey(paramName)) {
Double alreadySetValue = alreadySetParams.getDouble(paramName);
// check min/max range
if(paramValueJsonObject.containsKey("max") &&
paramValueJsonObject.getDouble("max") < alreadySetValue) {
throw new IllegalActionException("Maximum value for " +
paramName + " is " + paramValueJsonObject.getValue("max"));
} else if(paramValueJsonObject.containsKey("min") &&
paramValueJsonObject.getDouble("min") > alreadySetValue) {
throw new IllegalActionException("Minimum value for " +
paramName + " is " + paramValueJsonObject.getValue("min"));
} else {
// don't need to set the value again
continue;
}
} else if(!paramValueJsonObject.containsKey("default")) {
throw new IllegalActionException("No default value for " + paramName);
} else {
paramValue = paramValueJsonObject.getValue("default");
}
}
try {
String valueStr = _convertJSONToTokenString(paramValue);
((Settable)attribute).setExpression(valueStr);
//System.out.println("set " + paramName + " = " + valueStr);
} catch (IllegalActionException e) {
throw new IllegalActionException("Error settings parameter " +
paramName + ": " + e.getMessage());
}
}
}
/** Set model parameters from a paramset
* @param model the model
* @param type the type of the paramset
* @param value the value of the paramset
* @param alreadySetParams the set of parameters specified by the user
* already set in the model.
*/
private static void _setModelParametersFromMetadataParamSet(NamedObj model,
String type, String value, JsonObject alreadySetParams)
throws IllegalActionException {
// make sure user paramset type is in metadata configuration
CompletableFuture<AsyncResult<JsonObject>> metadataFuture =
new CompletableFuture<>();
Map<String,String> map = new HashMap<>();
map.put("paramset_type", type);
MetadataUtilities.getMetadataItem(value, "paramset", map)
.setHandler(res -> metadataFuture.complete(res));
AsyncResult<JsonObject> metadataResult = null;
try {
metadataResult = metadataFuture.get();
if(metadataResult.failed()) {
throw new IllegalActionException("Error getting metadata: " +
metadataResult.cause());
}
} catch (InterruptedException | ExecutionException e) {
throw new IllegalActionException("Error getting metadata: " +
e.getMessage());
}
JsonObject metadata = metadataResult.result();
if(!metadata.containsKey("private")) {
throw new IllegalActionException("paramset " + type +
" is missing private field");
}
if(!metadata.getJsonObject("private").containsKey("parameters")) {
throw new IllegalActionException("paramset " + type +
" is missing private.parameters field");
}
// first set public parameters, then private ones
// check any parameters specified by the user that have a range
// in the paramset.
if(metadata.containsKey("range")) {
_setModelParametersFromJson(model, metadata.getJsonObject("range"),
true, alreadySetParams);
}
// set private parameters in the paramset. this will override any
// parameters with the same name specified by the user.
JsonObject parameters = metadata.getJsonObject("private")
.getJsonObject("parameters");
// set the parameters in the model for this paramset
_setModelParametersFromJson(model, parameters, false, null);
}
/** Set any parameters for a model from a JSON object. */
private static void _setModelParameters(String wfName, NamedObj model, JsonObject json,
User user) throws IllegalActionException {
// get any parameters specified by the user
JsonObject userParams = null;
if(json.containsKey("wf_param")) {
try {
userParams = json.getJsonObject("wf_param");
} catch(ClassCastException e) {
throw new IllegalActionException("wf_param must be a json object.");
}
// set user-specified parameters in the model
_setModelParametersFromJson(model, userParams, false, null);
}
// set any paramset parameters
// get any default paramsets for this model
Map<String,String> paramSetsDefault =
WebViewConfiguration.getParamSetsForModel(wfName);
// get any paramsets from user request
JsonObject paramSetsUser = null;
if(json.containsKey("wf_paramset")) {
try {
paramSetsUser = json.getJsonObject("wf_paramset");
} catch(ClassCastException e) {
throw new IllegalActionException("wf_paramset must be a json object.");
}
//System.out.println("setting user-specified paramsets");
// check all user-specified paramsets
for(String paramSetType : paramSetsUser.fieldNames()) {
// make sure user paramset type is in the default configuration
if(!paramSetsDefault.containsKey(paramSetType)) {
throw new IllegalActionException("wf_paramset " +
paramSetType + " not defined for model " + wfName);
}
String paramSetValue = paramSetsUser.getString(paramSetType);
// check user has permission to set this value for paramset
CompletableFuture<AsyncResult<Boolean>> authFuture =
new CompletableFuture<>();
user.isAuthorized("paramset:" + paramSetType + ":" + paramSetValue,
res -> authFuture.complete(res));
try {
AsyncResult<Boolean> authResult = authFuture.get();
if(authResult.failed() || !authResult.result().booleanValue()) {
throw new IllegalActionException("Permission denied setting paramset " +
paramSetType + " to " + paramSetValue);
}
} catch (InterruptedException | ExecutionException e) {
throw new IllegalActionException("Error checking authorization: " +
e.getMessage());
}
// set parameters in model from this parameter set
_setModelParametersFromMetadataParamSet(model, paramSetType,
paramSetValue, userParams);
// delete this type from the default paramsets
paramSetsDefault.remove(paramSetType);
}
}
// set the parameters in the model for any remaining default paramsets
//System.out.println("setting default paramsets for " + wfName);
for(Map.Entry<String, String> entry: paramSetsDefault.entrySet()) {
_setModelParametersFromMetadataParamSet(model, entry.getKey(),
entry.getValue(), userParams);
}
// set user full name if present
Attribute attribute = model.getAttribute("WebView_FullName");
if(attribute != null) {
if(!(attribute instanceof Settable)) {
System.err.println("WARNING: WebView_FullName parameter is not settable.");
} else {
((Settable)attribute).setExpression(user.principal().getString("fullname"));
}
attribute = null;
}
// set the authorization groups parameter if present
attribute = model.getAttribute("WebView_groups");
if(attribute != null) {
if(!(attribute instanceof Settable)) {
System.err.println("WARNING: WebView_group parameter is not settable.");
} else {
// add quotes around each string since we use this to set the
// WebView_groups parameter in the workflow.
String authGroupsStr = AuthUtilities.getGroups(user).stream()
.map(s -> "\"" + s + "\"").collect(Collectors.joining(","));
//System.out.println(authGroupsStr);
((Settable)attribute).setExpression("{" + authGroupsStr + "}");
}
}
}
///////////////////////////////////////////////////////////////////
//// private variables ////
private Queryable _queryable;
/** Authentication provider. */
private AuthProvider _auth;
/** HTTP server listening for HTTP and WS requests. */
private HttpServer _server;
/** HTTPS server listening for HTTPS and WSS requests. */
private HttpServer _secureServer;
/** ModelUpdater used to add/remove workflows when KeplerGraphFrames
* are opened/closed.
*/
private final static ModelUpdater _updater = new ModelUpdater();
/** The module tree. */
private final static ModuleTree _moduleTree = ModuleTree.instance();
/** The root directory to search for files. If not set, the value is null. */
private static String _rootDir;
// TODO need better name
private final static Map<NamedObj,List<JsonObject>> _clientBuffers =
Collections.synchronizedMap(new HashMap<NamedObj,List<JsonObject>>());
public final static Map<String,CompositeActor> _models
= Collections.synchronizedMap(new HashMap<String,CompositeActor>());
public final static Map<String,App> _apps
= Collections.synchronizedMap(new HashMap<String,App>());
/* Timestamp format for logging. */
private final DateFormat _logTimeFormat = new SimpleDateFormat("dd/MMM/yyyy:HH:mm:ss Z");
private static Thread _loggingThread;
private final static String STOP_LOGGING_THREAD_MESSAGE = "STOP";
private final static LinkedBlockingQueue<String> _loggingQueue = new LinkedBlockingQueue<String>();
/** If true, append index.html to all (unmatched) GETs ending with "/". */
private static boolean _appendIndexHtml;
private static Vertx _vertx;
private static long _workflowTimeout;
}
|
<filename>server/index.js
var express = require('express');
var app = express();
var path = require('path');
var cors = require('cors');
var morgan = require('morgan');
var restaurantsRouter = require('./routers/restaurants.js');
var restaurantsApiRouter = require('./routers/restaurants_api.js');
var axios = require('axios');
var getRestaurantById = require('../db/controllers/getRestaurantById.js');
import React from 'react';
import ReactDOM from 'react-dom/server';
import { App } from '../client/src/app.jsx';
app.use(cors());
//app.use(morgan('tiny'));
app.options((req, res) => {
res.send('OK');
});
app.get('/bundle.js', (req, res) => {
res.sendFile(path.resolve('client/dist/bundle.js'));
});
//app.use('/restaurants', restaurantsRouter);
app.use('/api/restaurants', restaurantsApiRouter);
app.get('/api/restaurants/:id/string', (req, res) => {
console.log('Service req id: ', req.params.id);
getRestaurantById(req.params.id).then((result) => {
res.send(ReactDOM.renderToString(<App restaurant={result} />) + '%$%$^^%$%$' + JSON.stringify(result));
}).catch((err) => {
console.error('Failed to fetch restaurant data from server:', err);
});
});
var port = process.env.PORT || 3003;
app.listen(port, () => { console.log('Listening on http://localhost:' + port); });
|
import random
# define a list of operators
ops = ['+', '-', '*', '/']
# generate a random expression
expr = str(random.randint(1,1000))
for i in range(4):
expr += random.choice(ops) + str(random.randint(1,1000))
# evaluate the expression
result = eval(expr)
# print the expression and the result
print(f'Expression: {expr}')
print(f'Result: {result}') |
<gh_stars>1-10
import * as localStorage from '../common/storage.js';
import todoController from '../../controllers/todoController.js';
import todoInput from '../todos/todoInput.js';
import editimage from '../../assets/edit.png';
import deleteimage from '../../assets/delete.png';
const todolistDisplay = (() => {
const changeCurrentRowView = (targetId, currentStatus) => {
const todoRows = document.querySelector(`#todolistrow-${targetId}`);
if (currentStatus === true) {
todoRows.classList.remove('bg-primary');
todoRows.classList.add('bg-success');
} else {
todoRows.classList.remove('bg-success');
todoRows.classList.add('bg-primary');
}
};
const createTableRow = (todo) => {
const tableRow = document.createElement('tr');
tableRow.setAttribute('id', `todolistrow-${todo.id}`);
if (todo.status) {
tableRow.classList.add('bg-success');
} else {
tableRow.classList.add('bg-primary');
}
return tableRow;
};
const createCheckbox = (todo) => {
const statusCheckboxContainer = document.createElement('td');
const statusCheckbox = document.createElement('input');
statusCheckbox.setAttribute('type', 'checkbox');
if (todo.status) {
statusCheckbox.checked = true;
statusCheckbox.setAttribute('value', todo.status);
} else {
statusCheckbox.checked = false;
statusCheckbox.setAttribute('value', todo.status);
}
statusCheckbox.addEventListener('change', () => {
todo.status = !todo.status;
changeCurrentRowView(todo.id, todo.status);
todoController.updateTodo(todo);
});
statusCheckboxContainer.appendChild(statusCheckbox);
return statusCheckboxContainer;
};
const createTodoTitleContainer = (todo) => {
const todoTitleContainer = document.createElement('th');
todoTitleContainer.setAttribute('scope', 'row');
todoTitleContainer.innerText = todo.title;
return todoTitleContainer;
};
const createTodoDescriptionContainer = (todo) => {
const todoDescriptionContainer = document.createElement('td');
todoDescriptionContainer.innerText = todo.description;
return todoDescriptionContainer;
};
const createTodoDate = (todo) => {
const todoDateContainer = document.createElement('td');
todoDateContainer.innerText = todo.date;
return todoDateContainer;
};
const createTodoPriority = (todo) => {
const todoPriorityContainer = document.createElement('td');
todoPriorityContainer.innerText = todo.priority;
return todoPriorityContainer;
};
const removeFromTodoList = (id) => {
const todoList = document.querySelector(`#todolistrow-${id}`);
todoList.parentNode.removeChild(todoList);
};
const createDeleteImage = (targetID) => {
const editImageContainer = document.createElement('img');
editImageContainer.setAttribute('src', deleteimage);
editImageContainer.setAttribute('alt', 'delete image');
editImageContainer.classList.add('todo-delete-img');
editImageContainer.addEventListener('click', () => {
todoController.deleteTodo(targetID);
removeFromTodoList(targetID);
});
return editImageContainer;
};
const updateCurrentRowValue = (target) => {
const todoRows = document.querySelector(`#todolistrow-${target.id}`).childNodes;
todoRows[1].innerText = target.title;
todoRows[2].innerText = target.description;
todoRows[3].innerText = target.time;
todoRows[4].innerText = target.priority;
};
const enableEditButton = (target) => {
const editButton = document.querySelector('#edit-todo');
editButton.addEventListener('click', () => {
const {
title, description, date, priority,
} = todoInput.getEditData();
target.title = title;
target.description = description;
target.time = date;
target.priority = priority;
todoController.updateTodo(target);
updateCurrentRowValue(target);
});
};
const createEditImage = (target) => {
const editImageContainer = document.createElement('img');
editImageContainer.setAttribute('src', editimage);
editImageContainer.setAttribute('alt', 'edit image');
editImageContainer.classList.add('todo-edit-img');
editImageContainer.setAttribute('data-toggle', 'modal');
editImageContainer.setAttribute('data-target', '#exampleModal3');
editImageContainer.addEventListener('click', () => {
todoInput.loadtodoeditform(target);
enableEditButton(target);
});
return editImageContainer;
};
const creteTodoAction = (todo) => {
const todoActionContainer = document.createElement('td');
const deleteImage = createDeleteImage(todo.id);
const editImage = createEditImage(todo);
todoActionContainer.appendChild(deleteImage);
todoActionContainer.appendChild(editImage);
return todoActionContainer;
};
const createTodoListItem = (todo) => {
const tableRow = createTableRow(todo);
const checkboxElement = createCheckbox(todo);
const todoTitle = createTodoTitleContainer(todo);
const todoDescription = createTodoDescriptionContainer(todo);
const todoDate = createTodoDate(todo);
const todoPriority = createTodoPriority(todo);
const todoAction = creteTodoAction(todo);
tableRow.appendChild(checkboxElement);
tableRow.appendChild(todoTitle);
tableRow.appendChild(todoDescription);
tableRow.appendChild(todoDate);
tableRow.appendChild(todoPriority);
tableRow.appendChild(todoAction);
return tableRow;
};
const appendTodoList = (newTodo) => {
const newRow = createTodoListItem(newTodo);
document.querySelector('#todo-container').appendChild(newRow);
};
const disableTodolist = () => {
const emptyDialogue = document.querySelector('#emptyselector');
emptyDialogue.classList.remove('d-none');
const todolistsection = document.querySelector('#todolistsection');
todolistsection.classList.add('d-none');
};
const renderTodo = () => {
const emptyDialogue = document.querySelector('#emptyselector');
emptyDialogue.classList.add('d-none');
const todolistsection = document.querySelector('#todolistsection');
todolistsection.classList.remove('d-none');
const projectHeader = document.querySelector('#project-name-enable');
const currentProject = localStorage.getDataFromLocalStorage('currentProject');
projectHeader.innerHTML = currentProject.name;
const currentTodolist = currentProject.todolist;
document.querySelector('#todo-container').innerHTML = '';
if (currentTodolist.length > 0) {
const todoListContainer = document.querySelector('#todo-container');
currentTodolist.forEach((element) => {
todoListContainer.appendChild(createTodoListItem(element));
});
}
};
return {
renderTodo,
disableTodolist,
appendTodoList,
};
})();
export default todolistDisplay;
|
fn process_rules(rules: Vec<Rule>, condition: bool) -> Vec<Rule> {
let mut processed_rules = Vec::new();
let mut i_pos_skip = None;
for (i, rule) in rules.iter().enumerate() {
if i_pos_skip.is_some() && i == i_pos_skip.unwrap() {
continue;
}
if condition {
// Apply the condition based on the specific requirement
if rule.meets_condition() {
// Skip the current rule and set the value of i_pos_skip
i_pos_skip = Some(i);
continue;
}
}
processed_rules.push(rule.clone());
}
processed_rules
} |
Rails.application.routes.draw do
resources :scores
resources :users
get '/topten', to: 'scores#topten'
root to: 'users#home'
end |
<gh_stars>0
module.exports = {
"count": 20,
"start": 0,
"total": 23,
"subjects": [
{
"rating": {
"max": 10,
"average": 7.8,
"stars": "40",
"min": 0
},
"genres": [
"剧情",
"科幻"
],
"title": "降临",
"casts": [
{
"alt": "https://movie.douban.com/celebrity/1022563/",
"avatars": {
"small": "https://img3.doubanio.com/img/celebrity/small/23782.jpg",
"large": "https://img3.doubanio.com/img/celebrity/large/23782.jpg",
"medium": "https://img3.doubanio.com/img/celebrity/medium/23782.jpg"
},
"name": "艾米·亚当斯",
"id": "1022563"
},
{
"alt": "https://movie.douban.com/celebrity/1013770/",
"avatars": {
"small": "https://img3.doubanio.com/img/celebrity/small/15184.jpg",
"large": "https://img3.doubanio.com/img/celebrity/large/15184.jpg",
"medium": "https://img3.doubanio.com/img/celebrity/medium/15184.jpg"
},
"name": "杰瑞米·雷纳",
"id": "1013770"
},
{
"alt": "https://movie.douban.com/celebrity/1053567/",
"avatars": {
"small": "https://img1.doubanio.com/img/celebrity/small/40097.jpg",
"large": "https://img1.doubanio.com/img/celebrity/large/40097.jpg",
"medium": "https://img1.doubanio.com/img/celebrity/medium/40097.jpg"
},
"name": "福里斯特·惠特克",
"id": "1053567"
}
],
"collect_count": 34996,
"original_title": "Arrival",
"subtype": "movie",
"directors": [
{
"alt": "https://movie.douban.com/celebrity/1028333/",
"avatars": {
"small": "https://img3.doubanio.com/img/celebrity/small/1451296171.85.jpg",
"large": "https://img3.doubanio.com/img/celebrity/large/1451296171.85.jpg",
"medium": "https://img3.doubanio.com/img/celebrity/medium/1451296171.85.jpg"
},
"name": "丹尼斯·维伦纽瓦",
"id": "1028333"
}
],
"year": "2016",
"images": {
"small": "https://img3.doubanio.com/view/movie_poster_cover/ipst/public/p2411622421.jpg",
"large": "https://img3.doubanio.com/view/movie_poster_cover/lpst/public/p2411622421.jpg",
"medium": "https://img3.doubanio.com/view/movie_poster_cover/spst/public/p2411622421.jpg"
},
"alt": "https://movie.douban.com/subject/21324900/",
"id": "21324900"
},
{
"rating": {
"max": 10,
"average": 6.9,
"stars": "35",
"min": 0
},
"genres": [
"冒险",
"科幻"
],
"title": "太空旅客",
"casts": [
{
"alt": "https://movie.douban.com/celebrity/1022616/",
"avatars": {
"small": "https://img3.doubanio.com/img/celebrity/small/1358747052.41.jpg",
"large": "https://img3.doubanio.com/img/celebrity/large/1358747052.41.jpg",
"medium": "https://img3.doubanio.com/img/celebrity/medium/1358747052.41.jpg"
},
"name": "詹妮弗·劳伦斯",
"id": "1022616"
},
{
"alt": "https://movie.douban.com/celebrity/1017967/",
"avatars": {
"small": "https://img3.doubanio.com/img/celebrity/small/1408271589.94.jpg",
"large": "https://img3.doubanio.com/img/celebrity/large/1408271589.94.jpg",
"medium": "https://img3.doubanio.com/img/celebrity/medium/1408271589.94.jpg"
},
"name": "克里斯·普拉特",
"id": "1017967"
},
{
"alt": "https://movie.douban.com/celebrity/1004566/",
"avatars": {
"small": "https://img3.doubanio.com/img/celebrity/small/21073.jpg",
"large": "https://img3.doubanio.com/img/celebrity/large/21073.jpg",
"medium": "https://img3.doubanio.com/img/celebrity/medium/21073.jpg"
},
"name": "麦克·辛",
"id": "1004566"
}
],
"collect_count": 43280,
"original_title": "Passengers",
"subtype": "movie",
"directors": [
{
"alt": "https://movie.douban.com/celebrity/1299674/",
"avatars": {
"small": "https://img3.doubanio.com/img/celebrity/small/1422983107.34.jpg",
"large": "https://img3.doubanio.com/img/celebrity/large/1422983107.34.jpg",
"medium": "https://img3.doubanio.com/img/celebrity/medium/1422983107.34.jpg"
},
"name": "莫滕·泰杜姆",
"id": "1299674"
}
],
"year": "2016",
"images": {
"small": "https://img5.doubanio.com/view/movie_poster_cover/ipst/public/p2410576676.jpg",
"large": "https://img5.doubanio.com/view/movie_poster_cover/lpst/public/p2410576676.jpg",
"medium": "https://img5.doubanio.com/view/movie_poster_cover/spst/public/p2410576676.jpg"
},
"alt": "https://movie.douban.com/subject/3434070/",
"id": "3434070"
},
{
"rating": {
"max": 10,
"average": 6.3,
"stars": "35",
"min": 0
},
"genres": [
"喜剧"
],
"title": "情圣",
"casts": [
{
"alt": "https://movie.douban.com/celebrity/1274979/",
"avatars": {
"small": "https://img1.doubanio.com/img/celebrity/small/9489.jpg",
"large": "https://img1.doubanio.com/img/celebrity/large/9489.jpg",
"medium": "https://img1.doubanio.com/img/celebrity/medium/9489.jpg"
},
"name": "肖央",
"id": "1274979"
},
{
"alt": "https://movie.douban.com/celebrity/1274496/",
"avatars": {
"small": "https://img3.doubanio.com/img/celebrity/small/37681.jpg",
"large": "https://img3.doubanio.com/img/celebrity/large/37681.jpg",
"medium": "https://img3.doubanio.com/img/celebrity/medium/37681.jpg"
},
"name": "闫妮",
"id": "1274496"
},
{
"alt": "https://movie.douban.com/celebrity/1274081/",
"avatars": {
"small": "https://img1.doubanio.com/img/celebrity/small/6398.jpg",
"large": "https://img1.doubanio.com/img/celebrity/large/6398.jpg",
"medium": "https://img1.doubanio.com/img/celebrity/medium/6398.jpg"
},
"name": "小沈阳",
"id": "1274081"
}
],
"collect_count": 40053,
"original_title": "情圣",
"subtype": "movie",
"directors": [
{
"alt": "https://movie.douban.com/celebrity/1325035/",
"avatars": {
"small": "https://img3.doubanio.com/img/celebrity/small/1353401566.43.jpg",
"large": "https://img3.doubanio.com/img/celebrity/large/1353401566.43.jpg",
"medium": "https://img3.doubanio.com/img/celebrity/medium/1353401566.43.jpg"
},
"name": "宋晓飞 ",
"id": "1325035"
},
{
"alt": "https://movie.douban.com/celebrity/1364417/",
"avatars": {
"small": "https://img5.doubanio.com/img/celebrity/small/1480566101.36.jpg",
"large": "https://img5.doubanio.com/img/celebrity/large/1480566101.36.jpg",
"medium": "https://img5.doubanio.com/img/celebrity/medium/1480566101.36.jpg"
},
"name": "董旭",
"id": "1364417"
}
],
"year": "2016",
"images": {
"small": "https://img3.doubanio.com/view/movie_poster_cover/ipst/public/p2409022364.jpg",
"large": "https://img3.doubanio.com/view/movie_poster_cover/lpst/public/p2409022364.jpg",
"medium": "https://img3.doubanio.com/view/movie_poster_cover/spst/public/p2409022364.jpg"
},
"alt": "https://movie.douban.com/subject/26879060/",
"id": "26879060"
},
{
"rating": {
"max": 10,
"average": 4.3,
"stars": "25",
"min": 0
},
"genres": [
"喜剧",
"动画",
"冒险"
],
"title": "大卫贝肯之倒霉特工熊",
"casts": [
{
"alt": "https://movie.douban.com/celebrity/1360207/",
"avatars": {
"small": "https://img1.doubanio.com/f/movie/ca527386eb8c4e325611e22dfcb04cc116d6b423/pics/movie/celebrity-default-small.png",
"large": "https://img3.doubanio.com/f/movie/63acc16ca6309ef191f0378faf793d1096a3e606/pics/movie/celebrity-default-large.png",
"medium": "https://img1.doubanio.com/f/movie/8dd0c794499fe925ae2ae89ee30cd225750457b4/pics/movie/celebrity-default-medium.png"
},
"name": "汤水雨",
"id": "1360207"
},
{
"alt": "https://movie.douban.com/celebrity/1366856/",
"avatars": {
"small": "https://img1.doubanio.com/f/movie/ca527386eb8c4e325611e22dfcb04cc116d6b423/pics/movie/celebrity-default-small.png",
"large": "https://img3.doubanio.com/f/movie/63acc16ca6309ef191f0378faf793d1096a3e606/pics/movie/celebrity-default-large.png",
"medium": "https://img1.doubanio.com/f/movie/8dd0c794499fe925ae2ae89ee30cd225750457b4/pics/movie/celebrity-default-medium.png"
},
"name": "徐佳琪",
"id": "1366856"
},
{
"alt": "https://movie.douban.com/celebrity/1339447/",
"avatars": {
"small": "https://img3.doubanio.com/img/celebrity/small/UDVCMvDBxTMcel_avatar_uploaded1396190489.1.jpg",
"large": "https://img3.doubanio.com/img/celebrity/large/UDVCMvDBxTMcel_avatar_uploaded1396190489.1.jpg",
"medium": "https://img3.doubanio.com/img/celebrity/medium/UDVCMvDBxTMcel_avatar_uploaded1396190489.1.jpg"
},
"name": "杨默",
"id": "1339447"
}
],
"collect_count": 913,
"original_title": "大卫贝肯之倒霉特工熊",
"subtype": "movie",
"directors": [
{
"alt": "https://movie.douban.com/celebrity/1366855/",
"avatars": {
"small": "https://img1.doubanio.com/f/movie/ca527386eb8c4e325611e22dfcb04cc116d6b423/pics/movie/celebrity-default-small.png",
"large": "https://img3.doubanio.com/f/movie/63acc16ca6309ef191f0378faf793d1096a3e606/pics/movie/celebrity-default-large.png",
"medium": "https://img1.doubanio.com/f/movie/8dd0c794499fe925ae2ae89ee30cd225750457b4/pics/movie/celebrity-default-medium.png"
},
"name": "李清舫",
"id": "1366855"
}
],
"year": "2017",
"images": {
"small": "https://img3.doubanio.com/view/movie_poster_cover/ipst/public/p2408893200.jpg",
"large": "https://img3.doubanio.com/view/movie_poster_cover/lpst/public/p2408893200.jpg",
"medium": "https://img3.doubanio.com/view/movie_poster_cover/spst/public/p2408893200.jpg"
},
"alt": "https://movie.douban.com/subject/26921827/",
"id": "26921827"
},
{
"rating": {
"max": 10,
"average": 7.4,
"stars": "40",
"min": 0
},
"genres": [
"动作",
"科幻",
"冒险"
],
"title": "星球大战外传:侠盗一号",
"casts": [
{
"alt": "https://movie.douban.com/celebrity/1013981/",
"avatars": {
"small": "https://img3.doubanio.com/img/celebrity/small/42373.jpg",
"large": "https://img3.doubanio.com/img/celebrity/large/42373.jpg",
"medium": "https://img3.doubanio.com/img/celebrity/medium/42373.jpg"
},
"name": "菲丽希缇·琼斯",
"id": "1013981"
},
{
"alt": "https://movie.douban.com/celebrity/1013867/",
"avatars": {
"small": "https://img3.doubanio.com/img/celebrity/small/36123.jpg",
"large": "https://img3.doubanio.com/img/celebrity/large/36123.jpg",
"medium": "https://img3.doubanio.com/img/celebrity/medium/36123.jpg"
},
"name": "迭戈·鲁纳",
"id": "1013867"
},
{
"alt": "https://movie.douban.com/celebrity/1025194/",
"avatars": {
"small": "https://img3.doubanio.com/img/celebrity/small/10695.jpg",
"large": "https://img3.doubanio.com/img/celebrity/large/10695.jpg",
"medium": "https://img3.doubanio.com/img/celebrity/medium/10695.jpg"
},
"name": "甄子丹",
"id": "1025194"
}
],
"collect_count": 76047,
"original_title": "Rogue One: A Star Wars Story",
"subtype": "movie",
"directors": [
{
"alt": "https://movie.douban.com/celebrity/1310557/",
"avatars": {
"small": "https://img5.doubanio.com/img/celebrity/small/1351661374.56.jpg",
"large": "https://img5.doubanio.com/img/celebrity/large/1351661374.56.jpg",
"medium": "https://img5.doubanio.com/img/celebrity/medium/1351661374.56.jpg"
},
"name": "加里斯·爱德华斯",
"id": "1310557"
}
],
"year": "2016",
"images": {
"small": "https://img5.doubanio.com/view/movie_poster_cover/ipst/public/p2403049086.jpg",
"large": "https://img5.doubanio.com/view/movie_poster_cover/lpst/public/p2403049086.jpg",
"medium": "https://img5.doubanio.com/view/movie_poster_cover/spst/public/p2403049086.jpg"
},
"alt": "https://movie.douban.com/subject/25894431/",
"id": "25894431"
},
{
"rating": {
"max": 10,
"average": 5.1,
"stars": "25",
"min": 0
},
"genres": [
"喜剧",
"动作"
],
"title": "铁道飞虎",
"casts": [
{
"alt": "https://movie.douban.com/celebrity/1054531/",
"avatars": {
"small": "https://img3.doubanio.com/img/celebrity/small/694.jpg",
"large": "https://img3.doubanio.com/img/celebrity/large/694.jpg",
"medium": "https://img3.doubanio.com/img/celebrity/medium/694.jpg"
},
"name": "成龙",
"id": "1054531"
},
{
"alt": "https://movie.douban.com/celebrity/1337445/",
"avatars": {
"small": "https://img1.doubanio.com/img/celebrity/small/1405266144.28.jpg",
"large": "https://img1.doubanio.com/img/celebrity/large/1405266144.28.jpg",
"medium": "https://img1.doubanio.com/img/celebrity/medium/1405266144.28.jpg"
},
"name": "黄子韬",
"id": "1337445"
},
{
"alt": "https://movie.douban.com/celebrity/1314544/",
"avatars": {
"small": "https://img3.doubanio.com/img/celebrity/small/1444998211.72.jpg",
"large": "https://img3.doubanio.com/img/celebrity/large/1444998211.72.jpg",
"medium": "https://img3.doubanio.com/img/celebrity/medium/1444998211.72.jpg"
},
"name": "王凯",
"id": "1314544"
}
],
"collect_count": 39949,
"original_title": "铁道飞虎",
"subtype": "movie",
"directors": [
{
"alt": "https://movie.douban.com/celebrity/1274856/",
"avatars": {
"small": "https://img3.doubanio.com/img/celebrity/small/20143.jpg",
"large": "https://img3.doubanio.com/img/celebrity/large/20143.jpg",
"medium": "https://img3.doubanio.com/img/celebrity/medium/20143.jpg"
},
"name": "丁晟",
"id": "1274856"
}
],
"year": "2016",
"images": {
"small": "https://img5.doubanio.com/view/movie_poster_cover/ipst/public/p2404720316.jpg",
"large": "https://img5.doubanio.com/view/movie_poster_cover/lpst/public/p2404720316.jpg",
"medium": "https://img5.doubanio.com/view/movie_poster_cover/spst/public/p2404720316.jpg"
},
"alt": "https://movie.douban.com/subject/26389069/",
"id": "26389069"
},
{
"rating": {
"max": 10,
"average": 7.5,
"stars": "40",
"min": 0
},
"genres": [
"动画",
"奇幻",
"冒险"
],
"title": "魔弦传说",
"casts": [
{
"alt": "https://movie.douban.com/celebrity/1018991/",
"avatars": {
"small": "https://img3.doubanio.com/img/celebrity/small/44470.jpg",
"large": "https://img3.doubanio.com/img/celebrity/large/44470.jpg",
"medium": "https://img3.doubanio.com/img/celebrity/medium/44470.jpg"
},
"name": "查理兹·塞隆",
"id": "1018991"
},
{
"alt": "https://movie.douban.com/celebrity/1040511/",
"avatars": {
"small": "https://img3.doubanio.com/img/celebrity/small/1392653727.04.jpg",
"large": "https://img3.doubanio.com/img/celebrity/large/1392653727.04.jpg",
"medium": "https://img3.doubanio.com/img/celebrity/medium/1392653727.04.jpg"
},
"name": "马修·麦康纳",
"id": "1040511"
},
{
"alt": "https://movie.douban.com/celebrity/1006956/",
"avatars": {
"small": "https://img3.doubanio.com/img/celebrity/small/28941.jpg",
"large": "https://img3.doubanio.com/img/celebrity/large/28941.jpg",
"medium": "https://img3.doubanio.com/img/celebrity/medium/28941.jpg"
},
"name": "拉尔夫·费因斯",
"id": "1006956"
}
],
"collect_count": 37996,
"original_title": "Kubo and the Two Strings",
"subtype": "movie",
"directors": [
{
"alt": "https://movie.douban.com/celebrity/1305796/",
"avatars": {
"small": "https://img3.doubanio.com/img/celebrity/small/1471358307.31.jpg",
"large": "https://img3.doubanio.com/img/celebrity/large/1471358307.31.jpg",
"medium": "https://img3.doubanio.com/img/celebrity/medium/1471358307.31.jpg"
},
"name": "特拉维斯·奈特",
"id": "1305796"
}
],
"year": "2016",
"images": {
"small": "https://img5.doubanio.com/view/movie_poster_cover/ipst/public/p2411608656.jpg",
"large": "https://img5.doubanio.com/view/movie_poster_cover/lpst/public/p2411608656.jpg",
"medium": "https://img5.doubanio.com/view/movie_poster_cover/spst/public/p2411608656.jpg"
},
"alt": "https://movie.douban.com/subject/26287884/",
"id": "26287884"
},
{
"rating": {
"max": 10,
"average": 5,
"stars": "25",
"min": 0
},
"genres": [
"喜剧",
"动画",
"奇幻"
],
"title": "猪猪侠之英雄猪少年",
"casts": [
{
"alt": "https://movie.douban.com/celebrity/1340022/",
"avatars": {
"small": "https://img1.doubanio.com/img/celebrity/small/1415645996.57.jpg",
"large": "https://img1.doubanio.com/img/celebrity/large/1415645996.57.jpg",
"medium": "https://img1.doubanio.com/img/celebrity/medium/1415645996.57.jpg"
},
"name": "易烊千玺",
"id": "1340022"
},
{
"alt": "https://movie.douban.com/celebrity/1322063/",
"avatars": {
"small": "https://img1.doubanio.com/f/movie/ca527386eb8c4e325611e22dfcb04cc116d6b423/pics/movie/celebrity-default-small.png",
"large": "https://img3.doubanio.com/f/movie/63acc16ca6309ef191f0378faf793d1096a3e606/pics/movie/celebrity-default-large.png",
"medium": "https://img1.doubanio.com/f/movie/8dd0c794499fe925ae2ae89ee30cd225750457b4/pics/movie/celebrity-default-medium.png"
},
"name": "陈轶",
"id": "1322063"
},
{
"alt": "https://movie.douban.com/celebrity/1366599/",
"avatars": {
"small": "https://img1.doubanio.com/f/movie/ca527386eb8c4e325611e22dfcb04cc116d6b423/pics/movie/celebrity-default-small.png",
"large": "https://img3.doubanio.com/f/movie/63acc16ca6309ef191f0378faf793d1096a3e606/pics/movie/celebrity-default-large.png",
"medium": "https://img1.doubanio.com/f/movie/8dd0c794499fe925ae2ae89ee30cd225750457b4/pics/movie/celebrity-default-medium.png"
},
"name": "张子琨",
"id": "1366599"
}
],
"collect_count": 664,
"original_title": "猪猪侠之英雄猪少年",
"subtype": "movie",
"directors": [
{
"alt": "https://movie.douban.com/celebrity/1340248/",
"avatars": {
"small": "https://img1.doubanio.com/f/movie/ca527386eb8c4e325611e22dfcb04cc116d6b423/pics/movie/celebrity-default-small.png",
"large": "https://img3.doubanio.com/f/movie/63acc16ca6309ef191f0378faf793d1096a3e606/pics/movie/celebrity-default-large.png",
"medium": "https://img1.doubanio.com/f/movie/8dd0c794499fe925ae2ae89ee30cd225750457b4/pics/movie/celebrity-default-medium.png"
},
"name": "陆锦明",
"id": "1340248"
},
{
"alt": "https://movie.douban.com/celebrity/1366597/",
"avatars": {
"small": "https://img1.doubanio.com/f/movie/ca527386eb8c4e325611e22dfcb04cc116d6b423/pics/movie/celebrity-default-small.png",
"large": "https://img3.doubanio.com/f/movie/63acc16ca6309ef191f0378faf793d1096a3e606/pics/movie/celebrity-default-large.png",
"medium": "https://img1.doubanio.com/f/movie/8dd0c794499fe925ae2ae89ee30cd225750457b4/pics/movie/celebrity-default-medium.png"
},
"name": "钟裕",
"id": "1366597"
}
],
"year": "2017",
"images": {
"small": "https://img3.doubanio.com/view/movie_poster_cover/ipst/public/p2410095594.jpg",
"large": "https://img3.doubanio.com/view/movie_poster_cover/lpst/public/p2410095594.jpg",
"medium": "https://img3.doubanio.com/view/movie_poster_cover/spst/public/p2410095594.jpg"
},
"alt": "https://movie.douban.com/subject/26912427/",
"id": "26912427"
},
{
"rating": {
"max": 10,
"average": 8.8,
"stars": "45",
"min": 0
},
"genres": [
"剧情",
"传记",
"动作"
],
"title": "血战钢锯岭",
"casts": [
{
"alt": "https://movie.douban.com/celebrity/1022620/",
"avatars": {
"small": "https://img3.doubanio.com/img/celebrity/small/13151.jpg",
"large": "https://img3.doubanio.com/img/celebrity/large/13151.jpg",
"medium": "https://img3.doubanio.com/img/celebrity/medium/13151.jpg"
},
"name": "安德鲁·加菲尔德",
"id": "1022620"
},
{
"alt": "https://movie.douban.com/celebrity/1000147/",
"avatars": {
"small": "https://img3.doubanio.com/img/celebrity/small/35783.jpg",
"large": "https://img3.doubanio.com/img/celebrity/large/35783.jpg",
"medium": "https://img3.doubanio.com/img/celebrity/medium/35783.jpg"
},
"name": "萨姆·沃辛顿",
"id": "1000147"
},
{
"alt": "https://movie.douban.com/celebrity/1002673/",
"avatars": {
"small": "https://img5.doubanio.com/img/celebrity/small/6056.jpg",
"large": "https://img5.doubanio.com/img/celebrity/large/6056.jpg",
"medium": "https://img5.doubanio.com/img/celebrity/medium/6056.jpg"
},
"name": "文斯·沃恩",
"id": "1002673"
}
],
"collect_count": 174226,
"original_title": "Hacksaw Ridge",
"subtype": "movie",
"directors": [
{
"alt": "https://movie.douban.com/celebrity/1054530/",
"avatars": {
"small": "https://img3.doubanio.com/img/celebrity/small/680.jpg",
"large": "https://img3.doubanio.com/img/celebrity/large/680.jpg",
"medium": "https://img3.doubanio.com/img/celebrity/medium/680.jpg"
},
"name": "梅尔·吉布森",
"id": "1054530"
}
],
"year": "2016",
"images": {
"small": "https://img1.doubanio.com/view/movie_poster_cover/ipst/public/p2397337958.jpg",
"large": "https://img1.doubanio.com/view/movie_poster_cover/lpst/public/p2397337958.jpg",
"medium": "https://img1.doubanio.com/view/movie_poster_cover/spst/public/p2397337958.jpg"
},
"alt": "https://movie.douban.com/subject/26325320/",
"id": "26325320"
},
{
"rating": {
"max": 10,
"average": 0,
"stars": "00",
"min": 0
},
"genres": [
"动画",
"奇幻",
"冒险"
],
"title": "超能龙骑侠",
"casts": [
{
"alt": "https://movie.douban.com/celebrity/1334349/",
"avatars": {
"small": "https://img3.doubanio.com/img/celebrity/small/1398540567.14.jpg",
"large": "https://img3.doubanio.com/img/celebrity/large/1398540567.14.jpg",
"medium": "https://img3.doubanio.com/img/celebrity/medium/1398540567.14.jpg"
},
"name": "山新",
"id": "1334349"
},
{
"alt": "https://movie.douban.com/celebrity/1320629/",
"avatars": {
"small": "https://img1.doubanio.com/f/movie/ca527386eb8c4e325611e22dfcb04cc116d6b423/pics/movie/celebrity-default-small.png",
"large": "https://img3.doubanio.com/f/movie/63acc16ca6309ef191f0378faf793d1096a3e606/pics/movie/celebrity-default-large.png",
"medium": "https://img1.doubanio.com/f/movie/8dd0c794499fe925ae2ae89ee30cd225750457b4/pics/movie/celebrity-default-medium.png"
},
"name": "乔诗语",
"id": "1320629"
},
{
"alt": "https://movie.douban.com/celebrity/1035359/",
"avatars": {
"small": "https://img1.doubanio.com/img/celebrity/small/12037.jpg",
"large": "https://img1.doubanio.com/img/celebrity/large/12037.jpg",
"medium": "https://img1.doubanio.com/img/celebrity/medium/12037.jpg"
},
"name": "李珊珊",
"id": "1035359"
}
],
"collect_count": 115,
"original_title": "超能龙骑侠",
"subtype": "movie",
"directors": [
{
"alt": "https://movie.douban.com/celebrity/1320626/",
"avatars": {
"small": "https://img1.doubanio.com/img/celebrity/small/1375588383.38.jpg",
"large": "https://img1.doubanio.com/img/celebrity/large/1375588383.38.jpg",
"medium": "https://img1.doubanio.com/img/celebrity/medium/1375588383.38.jpg"
},
"name": "刘可欣",
"id": "1320626"
}
],
"year": "2017",
"images": {
"small": "https://img3.doubanio.com/view/movie_poster_cover/ipst/public/p2410306344.jpg",
"large": "https://img3.doubanio.com/view/movie_poster_cover/lpst/public/p2410306344.jpg",
"medium": "https://img3.doubanio.com/view/movie_poster_cover/spst/public/p2410306344.jpg"
},
"alt": "https://movie.douban.com/subject/26818364/",
"id": "26818364"
},
{
"rating": {
"max": 10,
"average": 0,
"stars": "00",
"min": 0
},
"genres": [
"儿童",
"喜剧",
"动画"
],
"title": "蛋计划",
"casts": [
{
"alt": "https://movie.douban.com/celebrity/1362506/",
"avatars": {
"small": "https://img1.doubanio.com/f/movie/ca527386eb8c4e325611e22dfcb04cc116d6b423/pics/movie/celebrity-default-small.png",
"large": "https://img3.doubanio.com/f/movie/63acc16ca6309ef191f0378faf793d1096a3e606/pics/movie/celebrity-default-large.png",
"medium": "https://img1.doubanio.com/f/movie/8dd0c794499fe925ae2ae89ee30cd225750457b4/pics/movie/celebrity-default-medium.png"
},
"name": "胡婷",
"id": "1362506"
},
{
"alt": "https://movie.douban.com/celebrity/1367159/",
"avatars": {
"small": "https://img1.doubanio.com/f/movie/ca527386eb8c4e325611e22dfcb04cc116d6b423/pics/movie/celebrity-default-small.png",
"large": "https://img3.doubanio.com/f/movie/63acc16ca6309ef191f0378faf793d1096a3e606/pics/movie/celebrity-default-large.png",
"medium": "https://img1.doubanio.com/f/movie/8dd0c794499fe925ae2ae89ee30cd225750457b4/pics/movie/celebrity-default-medium.png"
},
"name": "周微",
"id": "1367159"
},
{
"alt": "https://movie.douban.com/celebrity/1345978/",
"avatars": {
"small": "https://img1.doubanio.com/f/movie/ca527386eb8c4e325611e22dfcb04cc116d6b423/pics/movie/celebrity-default-small.png",
"large": "https://img3.doubanio.com/f/movie/63acc16ca6309ef191f0378faf793d1096a3e606/pics/movie/celebrity-default-large.png",
"medium": "https://img1.doubanio.com/f/movie/8dd0c794499fe925ae2ae89ee30cd225750457b4/pics/movie/celebrity-default-medium.png"
},
"name": "孟雨田",
"id": "1345978"
}
],
"collect_count": 37,
"original_title": "蛋计划",
"subtype": "movie",
"directors": [
{
"alt": "https://movie.douban.com/celebrity/1367158/",
"avatars": {
"small": "https://img1.doubanio.com/f/movie/ca527386eb8c4e325611e22dfcb04cc116d6b423/pics/movie/celebrity-default-small.png",
"large": "https://img3.doubanio.com/f/movie/63acc16ca6309ef191f0378faf793d1096a3e606/pics/movie/celebrity-default-large.png",
"medium": "https://img1.doubanio.com/f/movie/8dd0c794499fe925ae2ae89ee30cd225750457b4/pics/movie/celebrity-default-medium.png"
},
"name": "李扬武",
"id": "1367158"
}
],
"year": "2017",
"images": {
"small": "https://img1.doubanio.com/view/movie_poster_cover/ipst/public/p2401055708.jpg",
"large": "https://img1.doubanio.com/view/movie_poster_cover/lpst/public/p2401055708.jpg",
"medium": "https://img1.doubanio.com/view/movie_poster_cover/spst/public/p2401055708.jpg"
},
"alt": "https://movie.douban.com/subject/26920899/",
"id": "26920899"
},
{
"rating": {
"max": 10,
"average": 5,
"stars": "25",
"min": 0
},
"genres": [
"剧情",
"动作",
"奇幻"
],
"title": "长城",
"casts": [
{
"alt": "https://movie.douban.com/celebrity/1054443/",
"avatars": {
"small": "https://img3.doubanio.com/img/celebrity/small/620.jpg",
"large": "https://img3.doubanio.com/img/celebrity/large/620.jpg",
"medium": "https://img3.doubanio.com/img/celebrity/medium/620.jpg"
},
"name": "马特·达蒙",
"id": "1054443"
},
{
"alt": "https://movie.douban.com/celebrity/1275432/",
"avatars": {
"small": "https://img3.doubanio.com/img/celebrity/small/1407683852.1.jpg",
"large": "https://img3.doubanio.com/img/celebrity/large/1407683852.1.jpg",
"medium": "https://img3.doubanio.com/img/celebrity/medium/1407683852.1.jpg"
},
"name": "景甜",
"id": "1275432"
},
{
"alt": "https://movie.douban.com/celebrity/1329628/",
"avatars": {
"small": "https://img3.doubanio.com/img/celebrity/small/1397806328.94.jpg",
"large": "https://img3.doubanio.com/img/celebrity/large/1397806328.94.jpg",
"medium": "https://img3.doubanio.com/img/celebrity/medium/1397806328.94.jpg"
},
"name": "佩德罗·帕斯卡",
"id": "1329628"
}
],
"collect_count": 185923,
"original_title": "The Great Wall",
"subtype": "movie",
"directors": [
{
"alt": "https://movie.douban.com/celebrity/1054398/",
"avatars": {
"small": "https://img1.doubanio.com/img/celebrity/small/568.jpg",
"large": "https://img1.doubanio.com/img/celebrity/large/568.jpg",
"medium": "https://img1.doubanio.com/img/celebrity/medium/568.jpg"
},
"name": "张艺谋",
"id": "1054398"
}
],
"year": "2016",
"images": {
"small": "https://img3.doubanio.com/view/movie_poster_cover/ipst/public/p2394573821.jpg",
"large": "https://img3.doubanio.com/view/movie_poster_cover/lpst/public/p2394573821.jpg",
"medium": "https://img3.doubanio.com/view/movie_poster_cover/spst/public/p2394573821.jpg"
},
"alt": "https://movie.douban.com/subject/6982558/",
"id": "6982558"
},
{
"rating": {
"max": 10,
"average": 4.2,
"stars": "25",
"min": 0
},
"genres": [
"惊悚"
],
"title": "心惊胆战",
"casts": [
{
"alt": "https://movie.douban.com/celebrity/1016847/",
"avatars": {
"small": "https://img5.doubanio.com/img/celebrity/small/1352363438.56.jpg",
"large": "https://img5.doubanio.com/img/celebrity/large/1352363438.56.jpg",
"medium": "https://img5.doubanio.com/img/celebrity/medium/1352363438.56.jpg"
},
"name": "惠英红",
"id": "1016847"
},
{
"alt": "https://movie.douban.com/celebrity/1274442/",
"avatars": {
"small": "https://img5.doubanio.com/img/celebrity/small/4406.jpg",
"large": "https://img5.doubanio.com/img/celebrity/large/4406.jpg",
"medium": "https://img5.doubanio.com/img/celebrity/medium/4406.jpg"
},
"name": "黄德斌",
"id": "1274442"
},
{
"alt": "https://movie.douban.com/celebrity/1315532/",
"avatars": {
"small": "https://img5.doubanio.com/img/celebrity/small/32416.jpg",
"large": "https://img5.doubanio.com/img/celebrity/large/32416.jpg",
"medium": "https://img5.doubanio.com/img/celebrity/medium/32416.jpg"
},
"name": "余淼",
"id": "1315532"
}
],
"collect_count": 1577,
"original_title": "上身",
"subtype": "movie",
"directors": [
{
"alt": "https://movie.douban.com/celebrity/1346245/",
"avatars": {
"small": "https://img1.doubanio.com/f/movie/ca527386eb8c4e325611e22dfcb04cc116d6b423/pics/movie/celebrity-default-small.png",
"large": "https://img3.doubanio.com/f/movie/63acc16ca6309ef191f0378faf793d1096a3e606/pics/movie/celebrity-default-large.png",
"medium": "https://img1.doubanio.com/f/movie/8dd0c794499fe925ae2ae89ee30cd225750457b4/pics/movie/celebrity-default-medium.png"
},
"name": "陈鹏振",
"id": "1346245"
}
],
"year": "2015",
"images": {
"small": "https://img3.doubanio.com/view/movie_poster_cover/ipst/public/p2409828702.jpg",
"large": "https://img3.doubanio.com/view/movie_poster_cover/lpst/public/p2409828702.jpg",
"medium": "https://img3.doubanio.com/view/movie_poster_cover/spst/public/p2409828702.jpg"
},
"alt": "https://movie.douban.com/subject/26617291/",
"id": "26617291"
},
{
"rating": {
"max": 10,
"average": 8.5,
"stars": "45",
"min": 0
},
"genres": [
"剧情",
"爱情",
"动画"
],
"title": "你的名字。",
"casts": [
{
"alt": "https://movie.douban.com/celebrity/1185637/",
"avatars": {
"small": "https://img1.doubanio.com/img/celebrity/small/13768.jpg",
"large": "https://img1.doubanio.com/img/celebrity/large/13768.jpg",
"medium": "https://img1.doubanio.com/img/celebrity/medium/13768.jpg"
},
"name": "神木隆之介",
"id": "1185637"
},
{
"alt": "https://movie.douban.com/celebrity/1316660/",
"avatars": {
"small": "https://img1.doubanio.com/img/celebrity/small/1445093052.07.jpg",
"large": "https://img1.doubanio.com/img/celebrity/large/1445093052.07.jpg",
"medium": "https://img1.doubanio.com/img/celebrity/medium/1445093052.07.jpg"
},
"name": "上白石萌音",
"id": "1316660"
},
{
"alt": "https://movie.douban.com/celebrity/1018667/",
"avatars": {
"small": "https://img3.doubanio.com/img/celebrity/small/183.jpg",
"large": "https://img3.doubanio.com/img/celebrity/large/183.jpg",
"medium": "https://img3.doubanio.com/img/celebrity/medium/183.jpg"
},
"name": "长泽雅美",
"id": "1018667"
}
],
"collect_count": 327567,
"original_title": "君の名は。",
"subtype": "movie",
"directors": [
{
"alt": "https://movie.douban.com/celebrity/1005177/",
"avatars": {
"small": "https://img1.doubanio.com/img/celebrity/small/39258.jpg",
"large": "https://img1.doubanio.com/img/celebrity/large/39258.jpg",
"medium": "https://img1.doubanio.com/img/celebrity/medium/39258.jpg"
},
"name": "新海诚",
"id": "1005177"
}
],
"year": "2016",
"images": {
"small": "https://img1.doubanio.com/view/movie_poster_cover/ipst/public/p2395733377.jpg",
"large": "https://img1.doubanio.com/view/movie_poster_cover/lpst/public/p2395733377.jpg",
"medium": "https://img1.doubanio.com/view/movie_poster_cover/spst/public/p2395733377.jpg"
},
"alt": "https://movie.douban.com/subject/26683290/",
"id": "26683290"
},
{
"rating": {
"max": 10,
"average": 4.8,
"stars": "25",
"min": 0
},
"genres": [
"动画",
"家庭"
],
"title": "冰雪女皇之冬日魔咒",
"casts": [
{
"alt": "https://movie.douban.com/celebrity/1013784/",
"avatars": {
"small": "https://img3.doubanio.com/img/celebrity/small/34284.jpg",
"large": "https://img3.doubanio.com/img/celebrity/large/34284.jpg",
"medium": "https://img3.doubanio.com/img/celebrity/medium/34284.jpg"
},
"name": "伊莎贝拉·弗尔曼",
"id": "1013784"
},
{
"alt": "https://movie.douban.com/celebrity/1036300/",
"avatars": {
"small": "https://img5.doubanio.com/img/celebrity/small/1393386887.76.jpg",
"large": "https://img5.doubanio.com/img/celebrity/large/1393386887.76.jpg",
"medium": "https://img5.doubanio.com/img/celebrity/medium/1393386887.76.jpg"
},
"name": "沙尔托·科普雷",
"id": "1036300"
},
{
"alt": "https://movie.douban.com/celebrity/1002683/",
"avatars": {
"small": "https://img3.doubanio.com/img/celebrity/small/53.jpg",
"large": "https://img3.doubanio.com/img/celebrity/large/53.jpg",
"medium": "https://img3.doubanio.com/img/celebrity/medium/53.jpg"
},
"name": "肖恩·宾",
"id": "1002683"
}
],
"collect_count": 726,
"original_title": "Снежная королева 2: Перезаморозка",
"subtype": "movie",
"directors": [
{
"alt": "https://movie.douban.com/celebrity/1362482/",
"avatars": {
"small": "https://img1.doubanio.com/f/movie/ca527386eb8c4e325611e22dfcb04cc116d6b423/pics/movie/celebrity-default-small.png",
"large": "https://img3.doubanio.com/f/movie/63acc16ca6309ef191f0378faf793d1096a3e606/pics/movie/celebrity-default-large.png",
"medium": "https://img1.doubanio.com/f/movie/8dd0c794499fe925ae2ae89ee30cd225750457b4/pics/movie/celebrity-default-medium.png"
},
"name": "阿列克谢·特斯蒂斯林",
"id": "1362482"
}
],
"year": "2014",
"images": {
"small": "https://img1.doubanio.com/view/movie_poster_cover/ipst/public/p2381915097.jpg",
"large": "https://img1.doubanio.com/view/movie_poster_cover/lpst/public/p2381915097.jpg",
"medium": "https://img1.doubanio.com/view/movie_poster_cover/spst/public/p2381915097.jpg"
},
"alt": "https://movie.douban.com/subject/26108086/",
"id": "26108086"
},
{
"rating": {
"max": 10,
"average": 7.9,
"stars": "40",
"min": 0
},
"genres": [
"剧情",
"战争"
],
"title": "天空之眼",
"casts": [
{
"alt": "https://movie.douban.com/celebrity/1054390/",
"avatars": {
"small": "https://img1.doubanio.com/img/celebrity/small/21169.jpg",
"large": "https://img1.doubanio.com/img/celebrity/large/21169.jpg",
"medium": "https://img1.doubanio.com/img/celebrity/medium/21169.jpg"
},
"name": "海伦·米伦",
"id": "1054390"
},
{
"alt": "https://movie.douban.com/celebrity/1049498/",
"avatars": {
"small": "https://img1.doubanio.com/img/celebrity/small/1307.jpg",
"large": "https://img1.doubanio.com/img/celebrity/large/1307.jpg",
"medium": "https://img1.doubanio.com/img/celebrity/medium/1307.jpg"
},
"name": "亚伦·保尔",
"id": "1049498"
},
{
"alt": "https://movie.douban.com/celebrity/1025153/",
"avatars": {
"small": "https://img3.doubanio.com/img/celebrity/small/10644.jpg",
"large": "https://img3.doubanio.com/img/celebrity/large/10644.jpg",
"medium": "https://img3.doubanio.com/img/celebrity/medium/10644.jpg"
},
"name": "艾伦·瑞克曼",
"id": "1025153"
}
],
"collect_count": 46106,
"original_title": "Eye in the Sky",
"subtype": "movie",
"directors": [
{
"alt": "https://movie.douban.com/celebrity/1045060/",
"avatars": {
"small": "https://img3.doubanio.com/img/celebrity/small/1353058554.65.jpg",
"large": "https://img3.doubanio.com/img/celebrity/large/1353058554.65.jpg",
"medium": "https://img3.doubanio.com/img/celebrity/medium/1353058554.65.jpg"
},
"name": "加文·胡德",
"id": "1045060"
}
],
"year": "2015",
"images": {
"small": "https://img3.doubanio.com/view/movie_poster_cover/ipst/public/p2411665175.jpg",
"large": "https://img3.doubanio.com/view/movie_poster_cover/lpst/public/p2411665175.jpg",
"medium": "https://img3.doubanio.com/view/movie_poster_cover/spst/public/p2411665175.jpg"
},
"alt": "https://movie.douban.com/subject/10484117/",
"id": "10484117"
},
{
"rating": {
"max": 10,
"average": 7.7,
"stars": "40",
"min": 0
},
"genres": [
"喜剧",
"动画",
"奇幻"
],
"title": "海洋奇缘",
"casts": [
{
"alt": "https://movie.douban.com/celebrity/1364824/",
"avatars": {
"small": "https://img3.doubanio.com/img/celebrity/small/1479447814.43.jpg",
"large": "https://img3.doubanio.com/img/celebrity/large/1479447814.43.jpg",
"medium": "https://img3.doubanio.com/img/celebrity/medium/1479447814.43.jpg"
},
"name": "奥丽伊·卡瓦洛",
"id": "1364824"
},
{
"alt": "https://movie.douban.com/celebrity/1044707/",
"avatars": {
"small": "https://img5.doubanio.com/img/celebrity/small/196.jpg",
"large": "https://img5.doubanio.com/img/celebrity/large/196.jpg",
"medium": "https://img5.doubanio.com/img/celebrity/medium/196.jpg"
},
"name": "道恩·强森",
"id": "1044707"
},
{
"alt": "https://movie.douban.com/celebrity/1031855/",
"avatars": {
"small": "https://img3.doubanio.com/img/celebrity/small/13834.jpg",
"large": "https://img3.doubanio.com/img/celebrity/large/13834.jpg",
"medium": "https://img3.doubanio.com/img/celebrity/medium/13834.jpg"
},
"name": "艾伦·图代克",
"id": "1031855"
}
],
"collect_count": 34314,
"original_title": "Moana",
"subtype": "movie",
"directors": [
{
"alt": "https://movie.douban.com/celebrity/1045252/",
"avatars": {
"small": "https://img3.doubanio.com/img/celebrity/small/48764.jpg",
"large": "https://img3.doubanio.com/img/celebrity/large/48764.jpg",
"medium": "https://img3.doubanio.com/img/celebrity/medium/48764.jpg"
},
"name": "罗恩·克莱蒙兹",
"id": "1045252"
},
{
"alt": "https://movie.douban.com/celebrity/1041456/",
"avatars": {
"small": "https://img1.doubanio.com/img/celebrity/small/1359182726.97.jpg",
"large": "https://img1.doubanio.com/img/celebrity/large/1359182726.97.jpg",
"medium": "https://img1.doubanio.com/img/celebrity/medium/1359182726.97.jpg"
},
"name": "约翰·马斯克",
"id": "1041456"
}
],
"year": "2016",
"images": {
"small": "https://img1.doubanio.com/view/movie_poster_cover/ipst/public/p2397960879.jpg",
"large": "https://img1.doubanio.com/view/movie_poster_cover/lpst/public/p2397960879.jpg",
"medium": "https://img1.doubanio.com/view/movie_poster_cover/spst/public/p2397960879.jpg"
},
"alt": "https://movie.douban.com/subject/25793398/",
"id": "25793398"
},
{
"rating": {
"max": 10,
"average": 0,
"stars": "00",
"min": 0
},
"genres": [
"喜剧",
"动画",
"奇幻"
],
"title": "大魔法师孟兜兜",
"casts": [
{
"alt": "https://movie.douban.com/celebrity/1366254/",
"avatars": {
"small": "https://img1.doubanio.com/img/celebrity/small/1482726880.38.jpg",
"large": "https://img1.doubanio.com/img/celebrity/large/1482726880.38.jpg",
"medium": "https://img1.doubanio.com/img/celebrity/medium/1482726880.38.jpg"
},
"name": "郭太旭",
"id": "1366254"
},
{
"alt": "https://movie.douban.com/celebrity/1366255/",
"avatars": {
"small": "https://img3.doubanio.com/img/celebrity/small/1482726989.71.jpg",
"large": "https://img3.doubanio.com/img/celebrity/large/1482726989.71.jpg",
"medium": "https://img3.doubanio.com/img/celebrity/medium/1482726989.71.jpg"
},
"name": "石梁一骁",
"id": "1366255"
},
{
"alt": "https://movie.douban.com/celebrity/1327833/",
"avatars": {
"small": "https://img3.doubanio.com/img/celebrity/small/1365318316.3.jpg",
"large": "https://img3.doubanio.com/img/celebrity/large/1365318316.3.jpg",
"medium": "https://img3.doubanio.com/img/celebrity/medium/1365318316.3.jpg"
},
"name": "吴冰",
"id": "1327833"
}
],
"collect_count": 46,
"original_title": "大魔法师孟兜兜",
"subtype": "movie",
"directors": [
{
"alt": "https://movie.douban.com/celebrity/1366246/",
"avatars": {
"small": "https://img3.doubanio.com/img/celebrity/small/1482728962.83.jpg",
"large": "https://img3.doubanio.com/img/celebrity/large/1482728962.83.jpg",
"medium": "https://img3.doubanio.com/img/celebrity/medium/1482728962.83.jpg"
},
"name": "孟晖",
"id": "1366246"
}
],
"year": "2017",
"images": {
"small": "https://img1.doubanio.com/view/movie_poster_cover/ipst/public/p2413609578.jpg",
"large": "https://img1.doubanio.com/view/movie_poster_cover/lpst/public/p2413609578.jpg",
"medium": "https://img1.doubanio.com/view/movie_poster_cover/spst/public/p2413609578.jpg"
},
"alt": "https://movie.douban.com/subject/26941206/",
"id": "26941206"
},
{
"rating": {
"max": 10,
"average": 2.5,
"stars": "15",
"min": 0
},
"genres": [
"爱情",
"悬疑",
"惊悚"
],
"title": "恐怖理发店",
"casts": [
{
"alt": "https://movie.douban.com/celebrity/1340984/",
"avatars": {
"small": "https://img1.doubanio.com/img/celebrity/small/1403756298.69.jpg",
"large": "https://img1.doubanio.com/img/celebrity/large/1403756298.69.jpg",
"medium": "https://img1.doubanio.com/img/celebrity/medium/1403756298.69.jpg"
},
"name": "殷果儿",
"id": "1340984"
},
{
"alt": "https://movie.douban.com/celebrity/1359164/",
"avatars": {
"small": "https://img1.doubanio.com/f/movie/ca527386eb8c4e325611e22dfcb04cc116d6b423/pics/movie/celebrity-default-small.png",
"large": "https://img3.doubanio.com/f/movie/63acc16ca6309ef191f0378faf793d1096a3e606/pics/movie/celebrity-default-large.png",
"medium": "https://img1.doubanio.com/f/movie/8dd0c794499fe925ae2ae89ee30cd225750457b4/pics/movie/celebrity-default-medium.png"
},
"name": "任青安",
"id": "1359164"
},
{
"alt": "https://movie.douban.com/celebrity/1353667/",
"avatars": {
"small": "https://img3.doubanio.com/img/celebrity/small/1451209491.55.jpg",
"large": "https://img3.doubanio.com/img/celebrity/large/1451209491.55.jpg",
"medium": "https://img3.doubanio.com/img/celebrity/medium/1451209491.55.jpg"
},
"name": "姜星丘",
"id": "1353667"
}
],
"collect_count": 252,
"original_title": "恐怖理发店",
"subtype": "movie",
"directors": [
{
"alt": "https://movie.douban.com/celebrity/1360707/",
"avatars": {
"small": "https://img1.doubanio.com/f/movie/ca527386eb8c4e325611e22dfcb04cc116d6b423/pics/movie/celebrity-default-small.png",
"large": "https://img3.doubanio.com/f/movie/63acc16ca6309ef191f0378faf793d1096a3e606/pics/movie/celebrity-default-large.png",
"medium": "https://img1.doubanio.com/f/movie/8dd0c794499fe925ae2ae89ee30cd225750457b4/pics/movie/celebrity-default-medium.png"
},
"name": "陆诗雷",
"id": "1360707"
}
],
"year": "2017",
"images": {
"small": "https://img3.doubanio.com/view/movie_poster_cover/ipst/public/p2406903891.jpg",
"large": "https://img3.doubanio.com/view/movie_poster_cover/lpst/public/p2406903891.jpg",
"medium": "https://img3.doubanio.com/view/movie_poster_cover/spst/public/p2406903891.jpg"
},
"alt": "https://movie.douban.com/subject/26865690/",
"id": "26865690"
},
{
"rating": {
"max": 10,
"average": 6.8,
"stars": "35",
"min": 0
},
"genres": [
"剧情",
"喜剧"
],
"title": "少年巴比伦",
"casts": [
{
"alt": "https://movie.douban.com/celebrity/1330472/",
"avatars": {
"small": "https://img3.doubanio.com/img/celebrity/small/1385100761.5.jpg",
"large": "https://img3.doubanio.com/img/celebrity/large/1385100761.5.jpg",
"medium": "https://img3.doubanio.com/img/celebrity/medium/1385100761.5.jpg"
},
"name": "董子健",
"id": "1330472"
},
{
"alt": "https://movie.douban.com/celebrity/1317539/",
"avatars": {
"small": "https://img3.doubanio.com/img/celebrity/small/1402198542.62.jpg",
"large": "https://img3.doubanio.com/img/celebrity/large/1402198542.62.jpg",
"medium": "https://img3.doubanio.com/img/celebrity/medium/1402198542.62.jpg"
},
"name": "李梦",
"id": "1317539"
},
{
"alt": "https://movie.douban.com/celebrity/1326042/",
"avatars": {
"small": "https://img3.doubanio.com/img/celebrity/small/1357696338.94.jpg",
"large": "https://img3.doubanio.com/img/celebrity/large/1357696338.94.jpg",
"medium": "https://img3.doubanio.com/img/celebrity/medium/1357696338.94.jpg"
},
"name": "尚铁龙",
"id": "1326042"
}
],
"collect_count": 4098,
"original_title": "少年巴比伦",
"subtype": "movie",
"directors": [
{
"alt": "https://movie.douban.com/celebrity/1349688/",
"avatars": {
"small": "https://img5.doubanio.com/img/celebrity/small/1477215027.26.jpg",
"large": "https://img5.doubanio.com/img/celebrity/large/1477215027.26.jpg",
"medium": "https://img5.doubanio.com/img/celebrity/medium/1477215027.26.jpg"
},
"name": "相国强",
"id": "1349688"
}
],
"year": "2015",
"images": {
"small": "https://img3.doubanio.com/view/movie_poster_cover/ipst/public/p2410887742.jpg",
"large": "https://img3.doubanio.com/view/movie_poster_cover/lpst/public/p2410887742.jpg",
"medium": "https://img3.doubanio.com/view/movie_poster_cover/spst/public/p2410887742.jpg"
},
"alt": "https://movie.douban.com/subject/25876760/",
"id": "25876760"
}
],
"title": "正在上映的电影-南京"
} |
int towerOfHanoi(int n, char from_rod, char to_rod, char aux_rod)
{
if (n == 1)
{
cout << "Move disk 1 from rod " << from_rod << " to rod " << to_rod<<endl;
return 1;
}
int moves = towerOfHanoi(n - 1, from_rod, aux_rod, to_rod);
cout << "Move disk " << n << " from rod " << from_rod << " to rod " << to_rod << endl;
moves += towerOfHanoi(n - 1, aux_rod, to_rod, from_rod);
return moves + 1;
} |
def count_substring(main_string, substring):
count = 0
start = 0
while True:
start = main_string.find(substring, start) # Find the next occurrence of the substring
if start == -1: # If no more occurrences are found, break the loop
break
count += 1
start += 1 # Move the starting index for the next search
return count
# Test cases
print(count_substring('arfyslowy', 'low')) # Output: 1
print(count_substring('kloter2surga', '2')) # Output: 1
print(count_substring('ababababab', 'aba')) # Output: 4 |
function areAnagrams(stringA, stringB) {
// check if both strings have the same length
if (stringA.length !== stringB.length) {
return false;
}
// sort the strings alphabetically
const a = stringA.split('').sort().join('');
const b = stringB.split('').sort().join('');
return a === b;
} |
/*
Copyright (c) 2017, UPMC Enterprises
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 UPMC Enterprises 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 UPMC ENTERPRISES 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
*/
package kong
import (
"crypto/tls"
"fmt"
"net/http"
"time"
"github.com/Sirupsen/logrus"
)
// Kong struct
type Kong struct {
client *http.Client
KongAdminURL string
}
// New creates an instance of Kong
func New(namespace string) (*Kong, error) {
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
client := &http.Client{Transport: tr, Timeout: time.Second * 10}
k := &Kong{
client: client,
KongAdminURL: GetKongAdminURL(namespace),
}
return k, nil
}
// Ready creates a new Kong api
func (k *Kong) Ready(timeout chan bool, ready chan bool) {
logrus.Infof("Using [%s] as kong-admin url", k.KongAdminURL)
for i := 0; i < 20; i++ {
resp, err := k.client.Get(k.KongAdminURL)
if err != nil {
logrus.Error("Error getting kong admin status: ", err)
} else {
if resp.StatusCode == 200 {
logrus.Info("Kong API is ready!")
ready <- true
return
}
}
time.Sleep(2 * time.Second)
}
timeout <- true
}
func GetKongAdminURL(namespace string) string {
return fmt.Sprintf("https://kong-admin.%s:8444", namespace)
}
|
#!/bin/bash
source /etc/profile
BASE=/opt/ericsson/nfvo/fcaps/bin/fm_spark
if [ "$(whoami)" != "fcaps" ]; then
echo "using the account:fcaps to execute."
su - fcaps -c "${BASE}/stop_fm_spark.sh all"
sleep 2
su - fcaps -c "${BASE}/start_fm_spark.sh all"
echo "Complete the execution."
else
${BASE}/stop_fm_spark.sh "all"
sleep 2
${BASE}/start_fm_spark.sh "all"
fi
|
package org.hisp.dhis.vn.chr.hibernate;
/**
* @author <NAME>
*
*/
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.hisp.dhis.vn.chr.Egroup;
import org.hisp.dhis.vn.chr.EgroupStore;
import org.hisp.dhis.vn.chr.Form;
import org.hisp.dhis.vn.chr.comparator.EgroupNameComparator;
import org.springframework.transaction.annotation.Transactional;
@Transactional
public class HibernateEgroupStore
implements EgroupStore
{
// -----------------------------------------------------------------------------------------------
// Dependencies
// -----------------------------------------------------------------------------------------------
private SessionFactory sessionFactory;
public void setSessionFactory( SessionFactory sessionFactory )
{
this.sessionFactory = sessionFactory;
}
// -----------------------------------------------------------------------------------------------
// Implements
// -----------------------------------------------------------------------------------------------
public int addEgroup( Egroup egroup )
{
Session session = sessionFactory.getCurrentSession();
String name = egroup.getName().toLowerCase();
egroup.setName( name );
return (Integer) session.save( egroup );
}
public void deleteEgroup( int id )
{
Session session = sessionFactory.getCurrentSession();
session.delete( getEgroup( id ) );
}
@SuppressWarnings( "unchecked" )
public Collection<Egroup> getAllEgroups()
{
Session session = sessionFactory.getCurrentSession();
Criteria criteria = session.createCriteria( Egroup.class );
List<Egroup> list = criteria.list();
Collections.sort( list, new EgroupNameComparator() );
return list;
}
public Egroup getEgroup( int id )
{
Session session = sessionFactory.getCurrentSession();
return (Egroup) session.get( Egroup.class, id );
}
@SuppressWarnings( "unchecked" )
public Collection<Egroup> getEgroupsByForm( Form form )
{
Session session = sessionFactory.getCurrentSession();
Criteria criteria = session.createCriteria( Egroup.class );
criteria.add( Restrictions.eq( "form", form ) );
return criteria.list();
}
public void updateEgroup( Egroup egroup )
{
Session session = sessionFactory.getCurrentSession();
session.update( egroup );
}
}
|
import React from 'react';
import { Switch, Route, Link } from 'react-router-dom';
import {Nav,Navbar,Form,FormControl,Button} from 'react-bootstrap';
const NavigationBar=(props)=><Navbar bg="dark" variant="dark">
<Navbar.Brand as={Link} to="/home"><img src={props.logo} style={{height:25,width:'auto '}}/></Navbar.Brand>
<Nav className="mr-auto">
{props.routes.map(route=><Link to={route.path} className="nav-link">{route.name}</Link>)}
{/* <Nav.Link href="#home">Home</Nav.Link>
<Nav.Link href="#features">Features</Nav.Link>
<Nav.Link href="#pricing">Pricing</Nav.Link> */}
</Nav>
{/* <Form inline>
<FormControl type="text" placeholder="Search" className="mr-sm-2" />
<Button variant="outline-info">Search</Button>
</Form> */}
</Navbar>
export default NavigationBar; |
<filename>src/main.js
import 'sanitize.css/sanitize.css'
import React from 'react'
import ReactDOM from 'react-dom'
const rootEl = document.getElementById('root')
let render = () => {
const Root = require('./components/Root').default
ReactDOM.render(<Root />, rootEl)
}
if (module.hot) {
const renderApp = render
const renderError = err => {
const RedBox = require('redbox-react')
ReactDOM.render(<RedBox error={err} />, rootEl)
}
render = () => {
try {
renderApp()
} catch (err) {
renderError(err)
}
}
module.hot.accept('./components/Root', render)
}
render()
|
import React, { useState } from "react";
const App = () => {
const [ names, setNames ] = useState([]);
const [ inputName, setInputName ] = useState("");
const handleSubmit = e => {
e.preventDefault();
setNames([...names, inputName]);
setInputName("");
};
return (
<div>
<form onSubmit={handleSubmit}>
<label>
Name:
<input
value={inputName}
onChange={e => setInputName(e.target.value)}
/>
</label>
<input type="submit" value="Submit" />
</form>
<ul>
{names.map(name => (
<li>{name}</li>
))}
</ul>
</div>
);
}; |
package nsm
// States
var CREATING = "CREATING"
var WAIT_FOR_GATEWAY_CONFIG = "WAIT_FOR_GATEWAY_CONFIGURATION"
var CREATED = "CREATED"
var RUNNING = "RUNNING"
var READY = "READY"
// Intermediate states
var DELETING_RESOURCES = "DELETING_RESOURCES"
var CONFIGURING = "CONFIGURING"
var DELETING_CONFIGURATION = "DELETING_CONFIGURATION"
// Error states
var CREATION_ERROR = "CREATION_ERROR"
var CONFIGURATION_ERROR = "CONFIGURATION_ERROR"
var ERROR = "ERROR"
var DELETE_ERROR = "DELETE_ERROR"
|
def find_common_types(telecom_cable, telecom_building):
communication_types = set()
building_types = set()
# Extract communication types from telecom_cable
if "communication" in telecom_cable[1]:
communication_types.update(telecom_cable[1]["communication"])
if "construction:communication" in telecom_cable[1]:
communication_types.update(telecom_cable[1]["construction:communication"])
# Extract building types from telecom_building
for key, value in telecom_building[1].items():
building_types.update(value)
# Find common elements between communication and building types
common_types = list(communication_types.intersection(building_types))
return common_types
# Example usage
telecom_cable = (
"telecom_cable",
{
"communication": ["line", "cable"],
"construction:communication": ["line", "cable"],
},
"linestring",
)
telecom_building = (
"telecom_building",
{
"building": ["data_center", "data_centre", "telephone_exchange"],
"telecom": ["data_center", "data_centre", "central_office", "exchange"],
"office": ["telecommunication"],
"man_made": ["telephone_office"],
}
)
common_types = find_common_types(telecom_cable, telecom_building)
print(common_types) # Output: ["data_center", "data_centre", "telephone_exchange"] |
<reponame>RaafaGarcia/AdminPro
require('./bootstrap');
import { createApp } from 'vue'
import App from '@/Components/App.vue'
import store from './../store'
import router from './../router'
const app = createApp(App)
.use(store)
.use(router)
// app.component('App', App)
router.beforeEach((to, from, next) => {
document.title = `${to.meta.title} - Admin`
if(to.meta.middleware=="guest"){
if(store.state.auth.authenticated){
next({name:"dashboard"})
}
next()
}else{
if(store.state.auth.authenticated){
next()
}else{
next({name:"login"})
}
}
})
app.mount('#app')
|
int sumOfThirdDigits(int num) {
int sum = 0;
while (num != 0) {
if ((num % 10) % 3 == 0)
sum += num % 10;
num /= 10;
}
return sum;
} |
#!/bin/sh
CURRENT_DIR=$(pwd)
cd ${CURRENT_DIR}/bin
# /bin/pidof -s ./gameworld | xargs kill
killall -9 gameworld |
exports.names = ['catfact', 'catfacts'];
exports.hidden = true;
exports.enabled = true;
exports.cdAll = 10;
exports.cdUser = 30;
exports.cdStaff = 10;
exports.minRole = PERMISSIONS.NONE;
exports.handler = function (data) {
request('http://catfacts-api.appspot.com/api/facts', function (error, response, body) {
if(body != null) {
bot.sendChat(JSON.parse(body).facts[0]);
}
});
}; |
#!/bin/bash
cd /tmp
#Clone or pull if exist (auto update on restart container)
if [ -d "Front_Docker_Angular" ]; then
cd Front_Docker_Angular
git pull;
else
git clone https://github.com/EtienneTr/Front_Docker_Angular
cd Front_Docker_Angular;
fi
npm install
npm start
wait |
{
"spikes":{
"size":{"x": 300,"y": 110},
"position":{"x":5, "y":5}
},
"accele":{
"size":{"x": 101,"y": 115},
"position":{"x":315, "y":5}
},
"anti":{
"size":{"x": 99,"y": 96},
"position":{"x":426, "y":5}
},
"atra":{
"size":{"x": 99,"y": 96},
"position":{"x":535, "y":5}
},
"in":{
"size":{"x": 396,"y": 406},
"position":{"x":5, "y":130}
},
"in-open":{
"size":{"x": 396,"y": 406},
"position":{"x":644, "y":5}
}
}
|
Minimize z = -3x - 2y
Subject to
2x + y <= 10
-x - 4y <= -8
x ≥ 0, y ≥ 0 |
<filename>fluentlenium-core/src/test/java/org/fluentlenium/unit/initialization/ConstructorInitialization.java
package org.fluentlenium.unit.initialization;
import org.fluentlenium.adapter.FluentTest;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
import static org.assertj.core.api.Assertions.assertThat;
public class ConstructorInitialization extends FluentTest {
public WebDriver webDriver = new HtmlUnitDriver();
@Test
public void do_not_use_overridable_methods_in_a_constructor() {
assertThat(webDriver).isEqualTo(this.getDriver());
}
@Override
public WebDriver getDefaultDriver() {
return webDriver;
}
}
|
package io.github.marcelbraghetto.dailydeviations.features.home.logic;
import android.content.Intent;
import android.support.v4.app.Fragment;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.robolectric.RobolectricGradleTestRunner;
import org.robolectric.annotation.Config;
import io.github.marcelbraghetto.dailydeviations.BuildConfig;
import io.github.marcelbraghetto.dailydeviations.R;
import io.github.marcelbraghetto.dailydeviations.features.about.ui.AboutFragment;
import io.github.marcelbraghetto.dailydeviations.features.application.MainApp;
import io.github.marcelbraghetto.dailydeviations.features.collection.logic.CollectionArguments;
import io.github.marcelbraghetto.dailydeviations.features.collection.logic.providers.contracts.CollectionProvider;
import io.github.marcelbraghetto.dailydeviations.features.collection.ui.CollectionFragment;
import io.github.marcelbraghetto.dailydeviations.features.settings.ui.SettingsFragment;
import io.github.marcelbraghetto.dailydeviations.framework.artworks.contracts.ArtworksProvider;
import io.github.marcelbraghetto.dailydeviations.framework.artworks.models.Artwork;
import io.github.marcelbraghetto.dailydeviations.framework.artworks.models.CollectionFilterMode;
import io.github.marcelbraghetto.dailydeviations.framework.foundation.analytics.contracts.AnalyticsProvider;
import io.github.marcelbraghetto.dailydeviations.framework.foundation.eventbus.contracts.EventBusProvider;
import io.github.marcelbraghetto.dailydeviations.framework.foundation.eventbus.events.CollectionFilterModeToggleEvent;
import io.github.marcelbraghetto.dailydeviations.testconfig.RobolectricProperties;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
/**
* Created by <NAME> on 13/06/16.
*/
@Config(constants = BuildConfig.class, sdk = RobolectricProperties.EMULATE_SDK)
@RunWith(RobolectricGradleTestRunner.class)
public class HomeViewModelTest {
@Mock ArtworksProvider mArtworksProvider;
@Mock EventBusProvider mEventBusProvider;
@Mock CollectionProvider mCollectionProvider;
@Mock AnalyticsProvider mAnalyticsProvider;
@Mock HomeViewModel.Actions mDelegate;
private HomeViewModel mViewModel;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
mViewModel = new HomeViewModel(
MainApp.getDagger().getApplicationContext(),
mArtworksProvider,
mEventBusProvider,
MainApp.getDagger().getAppStringsProvider(),
mCollectionProvider,
mAnalyticsProvider);
}
private void resetAll() {
reset(mArtworksProvider, mEventBusProvider, mCollectionProvider, mAnalyticsProvider, mDelegate);
}
@Test
public void verifyDefaultDataBindings() {
// Verify
assertThat(mViewModel.glue.navigationTitle.get(), is(""));
assertThat(mViewModel.glue.selectedMenuId.get(), is(R.id.nav_menu_browse));
}
@Test
public void beginFilterModeFavourites() {
// Setup
ArgumentCaptor<Fragment> fragmentCaptor = new ArgumentCaptor<>();
when(mCollectionProvider.getCollectionFilterMode()).thenReturn(CollectionFilterMode.Favourites);
// Run
mViewModel.begin(mDelegate);
// Verify
assertThat(mViewModel.glue.navigationTitle.get(), is("My Deviations"));
assertThat(mViewModel.glue.selectedMenuId.get(), is(R.id.nav_menu_browse));
verify(mDelegate).showToggleButtons();
verify(mDelegate).replaceContent(fragmentCaptor.capture(), eq(false));
Fragment fragment = fragmentCaptor.getValue();
CollectionArguments arguments = new CollectionArguments(fragment.getArguments());
assertThat(fragment, instanceOf(CollectionFragment.class));
assertThat(arguments.getFilterMode(), is(CollectionFilterMode.Favourites));
}
@Test
public void beginFilterModeAll() {
// Setup
ArgumentCaptor<Fragment> fragmentCaptor = new ArgumentCaptor<>();
when(mCollectionProvider.getCollectionFilterMode()).thenReturn(CollectionFilterMode.All);
// Run
mViewModel.begin(mDelegate);
// Verify
assertThat(mViewModel.glue.navigationTitle.get(), is("Browse"));
assertThat(mViewModel.glue.selectedMenuId.get(), is(R.id.nav_menu_browse));
verify(mDelegate).showToggleButtons();
verify(mDelegate).replaceContent(fragmentCaptor.capture(), eq(false));
Fragment fragment = fragmentCaptor.getValue();
CollectionArguments arguments = new CollectionArguments(fragment.getArguments());
assertThat(fragment, instanceOf(CollectionFragment.class));
assertThat(arguments.getFilterMode(), is(CollectionFilterMode.All));
}
@Test
public void menuItemSelectedUnknownId() {
// Setup
when(mCollectionProvider.getCollectionFilterMode()).thenReturn(CollectionFilterMode.All);
mViewModel.begin(mDelegate);
resetAll();
// Run
mViewModel.menuItemSelected(-1);
// Verify
verify(mDelegate).closeNavigationMenu();
verifyNoMoreInteractions(mDelegate);
verifyZeroInteractions(mAnalyticsProvider);
}
@Test
public void menuItemSelectedBrowse() {
// Setup
when(mCollectionProvider.getCollectionFilterMode()).thenReturn(CollectionFilterMode.Favourites);
mViewModel.begin(mDelegate);
reset(mDelegate, mAnalyticsProvider);
// Run
mViewModel.menuItemSelected(R.id.nav_menu_browse);
// Verify
verify(mDelegate).closeNavigationMenu();
assertThat(mViewModel.glue.selectedMenuId.get(), is(R.id.nav_menu_browse));
verify(mAnalyticsProvider).trackEvent("MenuItemSelected", "HomeScreen", "Browse");
verify(mDelegate).replaceContent(any(Fragment.class), eq(true));
verify(mDelegate).showToggleButtons();
verifyNoMoreInteractions(mDelegate);
}
@Test
public void menuItemSelectedTellFriends() {
// Setup
ArgumentCaptor<Intent> intentCaptor = new ArgumentCaptor<>();
when(mCollectionProvider.getCollectionFilterMode()).thenReturn(CollectionFilterMode.Favourites);
mViewModel.begin(mDelegate);
reset(mDelegate, mAnalyticsProvider);
// Run
mViewModel.menuItemSelected(R.id.nav_menu_tell_friends);
// Verify
verify(mDelegate).closeNavigationMenu();
assertThat(mViewModel.glue.selectedMenuId.get(), is(R.id.nav_menu_browse));
verify(mAnalyticsProvider).trackEvent("MenuItemSelected", "HomeScreen", "TellFriends");
verify(mDelegate).startActivityForResult(intentCaptor.capture(), eq(666));
Intent intent = intentCaptor.getValue();
assertThat(intent.getAction(), is("com.google.android.gms.appinvite.ACTION_APP_INVITE"));
assertThat(intent.getStringExtra("com.google.android.gms.appinvite.TITLE"), is("Daily Deviations App!"));
assertThat(intent.getStringExtra("com.google.android.gms.appinvite.MESSAGE"), is("Keep up to date with the Daily Deviations app."));
assertThat(intent.getStringExtra("com.google.android.gms.appinvite.BUTTON_TEXT"), is("Get the app!"));
verifyNoMoreInteractions(mDelegate);
}
@Test
public void menuItemSelectedRateApp() {
// Setup
ArgumentCaptor<Intent> intentCaptor = new ArgumentCaptor<>();
when(mCollectionProvider.getCollectionFilterMode()).thenReturn(CollectionFilterMode.Favourites);
mViewModel.begin(mDelegate);
reset(mDelegate, mAnalyticsProvider);
// Run
mViewModel.menuItemSelected(R.id.nav_menu_rate_app);
// Verify
verify(mDelegate).closeNavigationMenu();
assertThat(mViewModel.glue.selectedMenuId.get(), is(R.id.nav_menu_browse));
verify(mAnalyticsProvider).trackEvent("MenuItemSelected", "HomeScreen", "RateApp");
verify(mDelegate).startActivity(intentCaptor.capture());
Intent intent = intentCaptor.getValue();
assertThat(intent.getAction(), is(Intent.ACTION_VIEW));
assertThat(intent.getData().toString(), is("https://play.google.com/store/apps/details?id=io.github.marcelbraghetto.dailydeviations"));
verifyNoMoreInteractions(mDelegate);
}
@Test
public void menuItemSelectedSettings() {
// Setup
ArgumentCaptor<Fragment> fragmentCaptor = new ArgumentCaptor<>();
when(mCollectionProvider.getCollectionFilterMode()).thenReturn(CollectionFilterMode.Favourites);
mViewModel.begin(mDelegate);
reset(mDelegate, mAnalyticsProvider);
// Run
mViewModel.menuItemSelected(R.id.nav_menu_settings);
// Verify
verify(mDelegate).closeNavigationMenu();
assertThat(mViewModel.glue.selectedMenuId.get(), is(R.id.nav_menu_settings));
verify(mAnalyticsProvider).trackEvent("MenuItemSelected", "HomeScreen", "Settings");
assertThat(mViewModel.glue.navigationTitle.get(), is("Settings"));
verify(mDelegate).hideToggleButtons();
verify(mDelegate).replaceContent(fragmentCaptor.capture(), eq(true));
assertThat(fragmentCaptor.getValue(), instanceOf(SettingsFragment.class));
verifyNoMoreInteractions(mDelegate);
}
@Test
public void menuItemSelectedAbout() {
// Setup
ArgumentCaptor<Fragment> fragmentCaptor = new ArgumentCaptor<>();
when(mCollectionProvider.getCollectionFilterMode()).thenReturn(CollectionFilterMode.Favourites);
mViewModel.begin(mDelegate);
reset(mDelegate, mAnalyticsProvider);
// Run
mViewModel.menuItemSelected(R.id.nav_menu_about);
// Verify
verify(mDelegate).closeNavigationMenu();
assertThat(mViewModel.glue.selectedMenuId.get(), is(R.id.nav_menu_about));
verify(mAnalyticsProvider).trackEvent("MenuItemSelected", "HomeScreen", "About");
assertThat(mViewModel.glue.navigationTitle.get(), is("About"));
verify(mDelegate).hideToggleButtons();
verify(mDelegate).replaceContent(fragmentCaptor.capture(), eq(true));
assertThat(fragmentCaptor.getValue(), instanceOf(AboutFragment.class));
verifyNoMoreInteractions(mDelegate);
}
@Test
public void backPressedOnBrowseScreen() {
// Setup
when(mCollectionProvider.getCollectionFilterMode()).thenReturn(CollectionFilterMode.Favourites);
mViewModel.begin(mDelegate);
resetAll();
// Run
mViewModel.backPressed();
// Verify
verify(mDelegate).finishActivity();
verifyNoMoreInteractions(mDelegate);
}
@Test
public void backPressedNotOnBrowseScreen() {
// Setup
when(mCollectionProvider.getCollectionFilterMode()).thenReturn(CollectionFilterMode.Favourites);
mViewModel.begin(mDelegate);
mViewModel.menuItemSelected(R.id.nav_menu_about);
reset(mDelegate);
// Run
mViewModel.backPressed();
// Verify
verify(mDelegate, never()).finishActivity();
verify(mCollectionProvider, times(2)).getCollectionFilterMode();
verify(mDelegate).replaceContent(any(Fragment.class), eq(true));
verify(mDelegate).showToggleButtons();
}
@Test
public void screenStartedNoSavedArtworks() {
// Setup
when(mArtworksProvider.hasSavedArtworks()).thenReturn(false);
// Run
mViewModel.screenStarted();
// Verify
verify(mAnalyticsProvider).trackScreenView("HomeScreen");
verify(mEventBusProvider).subscribe(mViewModel);
verify(mArtworksProvider).hasSavedArtworks();
verify(mArtworksProvider).refreshData();
}
@Test
public void screenStartedWithSavedArtworks() {
// Setup
when(mArtworksProvider.hasSavedArtworks()).thenReturn(true);
// Run
mViewModel.screenStarted();
// Verify
verify(mAnalyticsProvider).trackScreenView("HomeScreen");
verify(mEventBusProvider).subscribe(mViewModel);
verify(mArtworksProvider).hasSavedArtworks();
verify(mArtworksProvider, never()).refreshData();
}
@Test
public void screenStopped() {
// Run
mViewModel.screenStopped();
// Verify
verify(mEventBusProvider).unsubscribe(mViewModel);
}
@Test
public void onCollectionFilterModeToggleEvent() {
// Setup
when(mCollectionProvider.getCollectionFilterMode()).thenReturn(CollectionFilterMode.Favourites);
mViewModel.begin(mDelegate);
reset(mDelegate);
// Run
mViewModel.onEvent(new CollectionFilterModeToggleEvent());
// Verify
verify(mCollectionProvider, times(2)).getCollectionFilterMode();
verify(mDelegate).replaceContent(any(Fragment.class), eq(true));
}
@Test
public void onHomeNavHeaderDetailsEvent() {
// Setup
ArgumentCaptor<Intent> intentCaptor = ArgumentCaptor.forClass(Intent.class);
Artwork artworkIn = new Artwork();
artworkIn.setTitle("test artwork");
HomeNavHeaderDetailsEvent event = new HomeNavHeaderDetailsEvent(artworkIn);
when(mCollectionProvider.getCollectionFilterMode()).thenReturn(CollectionFilterMode.Favourites);
mViewModel.begin(mDelegate);
reset(mDelegate);
// Run
mViewModel.onEvent(event);
// Verify
verify(mDelegate).closeNavigationMenu();
verify(mDelegate).startActivity(intentCaptor.capture());
Intent intent = intentCaptor.getValue();
assertThat(intent.getComponent().getClassName(), is("io.github.marcelbraghetto.dailydeviations.features.detail.ui.DetailActivity"));
Artwork artworkOut = Artwork.getFrom(intent);
assertThat(artworkOut.getTitle(), is("test artwork"));
}
} |
<reponame>ardianbagus7/eepisat-react<gh_stars>0
import React from 'react';
import { HighlightedTextIcon } from 'components/molecules';
import { AboutSectionContentProps } from 'components/organisms/About/types';
const Text = () => (
<>
EEPISAT is a part of PENS Aerospace Team which under the {' '}
<span className="font-bold text-gray-800">Dirgantara PENS</span>.
It has the ambition to continue the goals to the <span className="font-bold text-gray-800">International Competition</span>.
After the previous winning for the National Competition at <span className="font-bold text-gray-800">Komurindo Kombat</span>.
held by LAPAN RI.{' '}
</>
);
const about: AboutSectionContentProps = {
text: <Text />,
};
export default about;
|
#!/bin/bash
# Testing the validations
./ldap-cli -addMembers
./ldap-cli -addMembers -cn group1
./ldap-cli -addMembers -cn group1 -ou nexus
./ldap-cli -addMembers -cn group0 -ou nexus -memberIds C00000
./ldap-cli -addMembers -cn group1 -ou nex -memberIds C00001
./ldap-cli -addMembers -cn group1 -ou nexus -memberIds C00000
# Testing the functionality
./ldap-cli -addMembers -cn group1 -ou nexus -memberIds C00001
./ldap-cli -addMembers -cn group1 -ou nexus -memberIds C00002
./ldap-cli -addMembers -cn group1 -ou nexus -memberIds C00002,C00003
./ldap-cli -addMembers -cn group1 -ou nexus -memberIds C00004,C00005
./ldap-cli -addMembers -cn group1 -ou nexus -memberIds C00006,C00007,C00008,C00009,C00010 |
#!/bin/bash
set -eo pipefail
VERSION=1
brew update
brew install git cmake python libtool libusb graphviz automake wget gmp llvm@7 pkgconfig doxygen openssl@1.1 jq || :
# install clang from source
git clone --single-branch --branch release_80 https://git.llvm.org/git/llvm.git clang8
cd clang8
git checkout 18e41dc
cd tools
git clone --single-branch --branch release_80 https://git.llvm.org/git/lld.git
cd lld
git checkout d60a035
cd ../
git clone --single-branch --branch release_80 https://git.llvm.org/git/polly.git
cd polly
git checkout 1bc06e5
cd ../
git clone --single-branch --branch release_80 https://git.llvm.org/git/clang.git clang
cd clang
git checkout a03da8b
cd tools
mkdir extra
cd extra
git clone --single-branch --branch release_80 https://git.llvm.org/git/clang-tools-extra.git
cd clang-tools-extra
git checkout 6b34834
cd ../../../../../projects/
git clone --single-branch --branch release_80 https://git.llvm.org/git/libcxx.git
cd libcxx
git checkout 1853712
cd ../
git clone --single-branch --branch release_80 https://git.llvm.org/git/libcxxabi.git
cd libcxxabi
git checkout d7338a4
cd ../
git clone --single-branch --branch release_80 https://git.llvm.org/git/libunwind.git
cd libunwind
git checkout 57f6739
cd ../
git clone --single-branch --branch release_80 https://git.llvm.org/git/compiler-rt.git
cd compiler-rt
git checkout 5bc7979
mkdir ../../build
cd ../../build
cmake -G 'Unix Makefiles' -DCMAKE_INSTALL_PREFIX='/usr/local' -DLLVM_BUILD_EXTERNAL_COMPILER_RT=ON -DLLVM_BUILD_LLVM_DYLIB=ON -DLLVM_ENABLE_LIBCXX=ON -DLLVM_ENABLE_RTTI=ON -DLLVM_INCLUDE_DOCS=OFF -DLLVM_OPTIMIZED_TABLEGEN=ON -DLLVM_TARGETS_TO_BUILD=X86 -DCMAKE_BUILD_TYPE=Release ..
make -j $(getconf _NPROCESSORS_ONLN)
sudo make install
cd ../..
rm -rf clang8
# install boost from source
# Boost Fix: lcscs/install/bin/../include/c++/v1/stdlib.h:94:15: fatal error: 'stdlib.h' file not found
export SDKROOT="$(xcrun --sdk macosx --show-sdk-path)"
curl -LO https://dl.bintray.com/boostorg/release/1.71.0/source/boost_1_71_0.tar.bz2
tar -xjf boost_1_71_0.tar.bz2
cd boost_1_71_0
./bootstrap.sh --prefix=/usr/local
sudo SDKROOT="$SDKROOT" ./b2 --with-iostreams --with-date_time --with-filesystem --with-system --with-program_options --with-chrono --with-test -q -j$(getconf _NPROCESSORS_ONLN) install
cd ..
sudo rm -rf boost_1_71_0.tar.bz2 boost_1_71_0
# install mongoDB
cd ~
curl -OL https://fastdl.mongodb.org/osx/mongodb-osx-ssl-x86_64-3.6.3.tgz
tar -xzf mongodb-osx-ssl-x86_64-3.6.3.tgz
rm -f mongodb-osx-ssl-x86_64-3.6.3.tgz
ln -s ~/mongodb-osx-x86_64-3.6.3 ~/mongodb
# install mongo-c-driver from source
cd /tmp
curl -LO https://github.com/mongodb/mongo-c-driver/releases/download/1.13.0/mongo-c-driver-1.13.0.tar.gz
tar -xzf mongo-c-driver-1.13.0.tar.gz
cd mongo-c-driver-1.13.0
mkdir -p cmake-build
cd cmake-build
cmake -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX='/usr/local' -DENABLE_BSON=ON -DENABLE_SSL=DARWIN -DENABLE_AUTOMATIC_INIT_AND_CLEANUP=OFF -DENABLE_STATIC=ON -DENABLE_ICU=OFF -DENABLE_SASL=OFF -DENABLE_SNAPPY=OFF ..
make -j $(getconf _NPROCESSORS_ONLN)
sudo make install
cd ../..
rm mongo-c-driver-1.13.0.tar.gz
# install mongo-cxx-driver from source
cd /tmp
curl -L https://github.com/mongodb/mongo-cxx-driver/archive/r3.4.0.tar.gz -o mongo-cxx-driver-r3.4.0.tar.gz
tar -xzf mongo-cxx-driver-r3.4.0.tar.gz
cd mongo-cxx-driver-r3.4.0/build
cmake -DBUILD_SHARED_LIBS=OFF -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX='/usr/local' ..
make -j $(getconf _NPROCESSORS_ONLN) VERBOSE=1
sudo make install
cd ../..
rm -f mongo-cxx-driver-r3.4.0.tar.gz |
<gh_stars>0
//////////////////////////////////////////////////////////////////////////////80
// Project Init
//////////////////////////////////////////////////////////////////////////////80
// Copyright (c) Atheos & <NAME> (Atheos.io), distributed as-is and without
// warranty under the MIT License. See [root]/LICENSE.md for more.
// This information must remain intact.
//////////////////////////////////////////////////////////////////////////////80
// Authors: Codiad Team, @Fluidbyte, Atheos Team, @hlsiira
//////////////////////////////////////////////////////////////////////////////80
(function(global) {
var atheos = global.atheos;
var self = null;
amplify.subscribe('system.loadMinor', () => atheos.project.init());
atheos.project = {
//projectmanager
sideExpanded: true,
openTrigger: 'click',
current: {
name: '',
path: ''
},
init: function() {
self = this;
self.load();
self.dock.load();
oX('#project-atheos', true).on('click', function() {
self.open('Atheos IDE', '@TH305');
});
oX('#projects-create', true).on('click', self.create);
oX('#projects-manage', true).on('click', self.list);
oX('#projects-collapse', true).on('click', function() {
if (self.sideExpanded) {
self.dock.collapse();
} else {
self.dock.expand();
}
});
amplify.subscribe('chrono.mega', function() {
self.getCurrent();
});
amplify.subscribe('settings.loaded', function() {
var local = atheos.storage('project.openTrigger');
if (local === 'click' || local === 'dblclick') {
self.openTrigger = local;
}
});
oX('#project_list .content li', true).on('click, dblclick', function(e) {
if (self.openTrigger === e.type) {
var node = oX(e.target);
if (node.tagName === 'UL') {
return false;
} else if (node.tagName !== 'LI') {
node = node.parent();
}
self.open(node.text(), node.attr('data-project'));
}
});
},
//////////////////////////////////////////////////////////////////
// Get Current Project
//////////////////////////////////////////////////////////////////
load: function() {
echo({
url: atheos.controller,
data: {
target: 'project',
action: 'load'
},
success: function(reply) {
atheos.toast.show(reply);
if (reply.status === 'error') {
return;
}
var logSpan = oX('#last_login');
if (reply.lastLogin && logSpan) {
// logSpan.find('span').text(i18n('login_last', reply.lastLogin));
logSpan.find('span').text(reply.lastLogin);
}
self.setRoot(reply.name, reply.path);
}
});
},
//////////////////////////////////////////////////////////////////
// Open Project
//////////////////////////////////////////////////////////////////
open: function(projectName, projectPath) {
log(projectPath);
atheos.scout.hideFilter();
echo({
url: atheos.controller,
data: {
target: 'project',
action: 'open',
projectName,
projectPath
},
success: function(reply) {
atheos.toast.show(reply);
if (reply.status === 'error') {
return;
}
self.setRoot(reply.name, reply.path);
if (atheos.modal.modalVisible) {
atheos.modal.unload();
}
atheos.user.saveActiveProject(reply.name, reply.path);
localStorage.removeItem('lastSearched');
/* Notify listeners. */
amplify.publish('project.open', reply.path);
}
});
},
//////////////////////////////////////////////////////////////////
// Set project root in file manager
//////////////////////////////////////////////////////////////////
setRoot: function(name, path) {
self.current = {
name,
path
};
oX('#file-manager').empty();
oX('#file-manager').html(`<ul><li>
<a id="project-root" data-type="root" data-path="${path}">
<i class="root fa fa-folder blue"></i>
<span>${name}</span>
</a>
</li></ul>`);
atheos.filemanager.openDir(path);
},
//////////////////////////////////////////////////////////////////
// Open the project manager dialog
//////////////////////////////////////////////////////////////////
list: function() {
atheos.modal.load(500, {
target: 'project',
action: 'list'
});
},
//////////////////////////////////////////////////////////////////
// Load and list projects in the sidebar.
//////////////////////////////////////////////////////////////////
dock: {
load: function() {
echo({
url: atheos.dialog,
data: {
target: 'project',
action: 'projectDock'
},
success: function(reply) {
oX('#project_list .content').html(reply);
}
});
},
expand: function() {
self.sideExpanded = true;
oX('#sb_left #project_list').css('height', '');
oX('#sb_left>.content').css('bottom', '');
oX('#projects-collapse').replaceClass('fa-chevron-circle-up', 'fa-chevron-circle-down');
},
collapse: function() {
self.sideExpanded = false;
var height = oX('#sb_left #project_list .title').height();
oX('#sb_left #project_list').css('height', height + 'px');
oX('#sb_left>.content').css('bottom', height + 'px');
oX('#projects-collapse').replaceClass('fa-chevron-circle-down', 'fa-chevron-circle-up');
}
},
//////////////////////////////////////////////////////////////////
// Create Project
//////////////////////////////////////////////////////////////////
create: function() {
var projectName, projectPath, gitRepo, gitBranch;
var createProject = function() {
var data = {
target: 'project',
action: 'create',
projectName,
projectPath,
gitRepo,
gitBranch
};
echo({
url: atheos.controller,
data,
success: function(reply) {
if (reply.status !== 'error') {
self.open(reply.name, reply.path);
self.dock.load();
/* Notify listeners. */
delete data.action;
amplify.publish('project.create', data);
}
}
});
};
var listener = function(e) {
e.preventDefault();
projectName = oX('#modal_content form input[name="projectName"]').value();
projectPath = oX('#modal_content form input[name="projectPath"]').value();
gitRepo = oX('#modal_content form input[name="gitRepo"]').value();
gitBranch = oX('#modal_content form input[name="gitBranch"]').value();
if (projectPath.indexOf('/') === 0) {
atheos.alert.show({
banner: 'Do you really want to create a project with an absolute path?',
data: projectPath,
actions: {
'Yes': function() {
createProject();
},
'No': function() {}
}
});
} else {
createProject();
}
};
atheos.modal.load(400, {
target: 'project',
action: 'create',
listener,
callback: function() {
// More Selector
oX('#show_git_options').on('click', function(e) {
e.preventDefault();
oX(e.target).hide();
atheos.flow.slide('open', oX('#git_options').el);
});
}
});
},
//////////////////////////////////////////////////////////////////
// Rename Project
//////////////////////////////////////////////////////////////////
rename: function(projectName, projectPath) {
var listener = function(e) {
e.preventDefault();
projectName = oX('#modal_content form input[name="projectName"]').value();
var data = {
target: 'project',
action: 'rename',
projectPath,
projectName
};
echo({
url: atheos.controller,
data,
success: function(reply) {
if (reply.status !== 'error') {
atheos.toast.show('success', 'Project renamed');
self.dock.load();
atheos.modal.unload();
/* Notify listeners. */
delete data.action;
amplify.publish('project.rename', data);
}
}
});
};
atheos.modal.load(400, {
target: 'project',
action: 'rename',
name: projectName,
listener
});
},
//////////////////////////////////////////////////////////////////
// Delete Project
//////////////////////////////////////////////////////////////////
delete: function(projectName, projectPath) {
log(projectName, projectPath);
var listener = function(e) {
e.preventDefault();
var scope = oX('input[name="scope"]:checked').value();
echo({
url: atheos.controller,
data: {
target: 'project',
action: 'delete',
scope,
projectPath,
projectName
},
settled: function(status, reply) {
if (status === 'success') {
atheos.toast.show('success', reply.text);
self.list();
self.dock.load();
for (var path in atheos.active.sessions) {
if (path.indexOf(projectPath) === 0) {
atheos.active.remove(path);
}
}
amplify.publish('project.delete', {
'path': projectPath,
'name': projectName
});
}
}
});
};
atheos.modal.load(400, {
target: 'project',
action: 'delete',
name: projectName,
path: projectPath,
listener
});
},
//////////////////////////////////////////////////////////////////
// Get Current (Path)
//////////////////////////////////////////////////////////////////
getCurrent: function() {
echo({
url: atheos.controller,
data: {
target: 'project',
action: 'current'
},
success: function(data) {
if (data.status === 'success') {
self.current.path = data.path;
}
}
});
return self.current.path;
}
};
})(this); |
var Version = "1.2.2";
// Here, we're using one 'pageInit' event handler for all pages and selecting one
// that might need extra initialization. This is a special case in that the home
// page isn't reached from the Framework7 navigation handler so it won't be fired
// off in the standard version as seen below for other page initializers.
var globalArrayPrinterProfiles = [];
var globalCurrentPrinterName = "";
var isWebcamON = false;
document.addEventListener('pageInit', function (e) {
// Get page data from event data
var page = e.detail.page;
if (page.name === 'index') {
// First, retrieve the existing jsonString of the printer profiles array
// from local storage
var jsonStringExistingArray = localStorage.getItem('arrayPrinterProfiles');
// Then, convert it back into a json object (array)
var objArrayExistingPrinterProfiles = JSON.parse(jsonStringExistingArray);
// Create an ordinal-based counter for use in determining landing page
var ordinalLandingPage = 1;
// And store these to our global array for later use
// console.log('Iterating printer profiles...');
objArrayExistingPrinterProfiles.PrinterProfiles.forEach(function (item) {
var itemKey;
for (var prop in item) {
itemKey = prop; // Should be 'charming-pascal' on mine
break;
}
// console.log('Printer profile: ' + itemKey);
var landingPage = 'printer0' + ordinalLandingPage++;
var objPrinterState = new PrinterState(itemKey,
item[itemKey].hostName,
item[itemKey].apiKey,
item[itemKey].webcamUrl,
item[itemKey].selectedFilament,
landingPage);
globalArrayPrinterProfiles.push(objPrinterState);
});
// console.log(globalArrayPrinterProfiles[0].getConnectionInfo().hostName);
// console.log(document.getElementById('idIndexPagePrinters'));
// console.log('Length of globalArrayPrinterProfiles: ' + globalArrayPrinterProfiles.length);
/* --------------------------------------------------------------------
So now, we want to add one of these dynamically per printer profile
that's in the globalArrayPrinterProfiles array of PrinterState
(class-based) objects.
--------------------------------------------------------------------
<li class="background-gray">
<a href="#" class="item-content item-link">
<div class="item-inner">
<div class="item-title printer01">• charming-pascal</div>
</div>
</a>
</li>
*/
var htmlContent = "<ul>";
//console.log(globalArrayPrinterProfiles);
if (globalArrayPrinterProfiles.length) {
globalArrayPrinterProfiles.forEach(function (objItem) {
//console.log(objItem.name);
// TODO (make this work for more than one printer by determining the page ordinal)
// Query the printer and determine if it is in an operational state
var url = "http://" + objItem.hostName + "/api/printer?apikey=" + objItem.apiKey;
//console.log(url);
var printerRequest = new XMLHttpRequest();
printerRequest.open("get", url, true);
printerRequest.timeout = 5000; // Set timeout to 5 seconds
printerRequest.setRequestHeader('X-Api-Key', objItem.apiKey);
printerRequest.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var jsonData = JSON.parse(this.responseText);
//console.log(jsonData);
if (jsonData.state.flags) {
// console.log('jsonData.state.flags');
if (jsonData.state.flags.operational) {
//console.log(objItem.appLandingPage);
htmlContent += '<li class="background-gray">' +
'<a href="' + objItem.appLandingPage + '.html" class="item-content item-link">' +
'<div class="item-inner">' +
'• ' + objItem.name +
'</div></a></li>';
htmlContent += "</ul>";
document.getElementById('idIndexPagePrinters').innerHTML = htmlContent;
return;
} else {
// It responded but isn't operational
htmlContent += '<li class="background-gray" style="color:red">' +
'<a href="printeroffline.html" class="item-content item-link">' +
'<div class="item-inner">' +
'• ' + objItem.name +
'</div></a></li>';
htmlContent += "</ul>";
document.getElementById('idIndexPagePrinters').innerHTML = htmlContent;
return;
}
} else {
// It did not respond at all
htmlContent += '<li class="background-gray" style="color:red">' +
'<a href="printeroffline.html" class="item-content item-link">' +
'<div class="item-inner">' +
'• ' + objItem.name +
'</div></a></li>';
htmlContent += "</ul>";
document.getElementById('idIndexPagePrinters').innerHTML = htmlContent;
return;
}
} else {
// Else from if (this.readystate...
if (this.readyState == 4 && this.status == 409) {
console.log('Printer returned a 409 error ["' + this.responseText + '"] (potentially okay for a test rig)');
if (this.responseText == 'Printer is not operational') {
htmlContent += '<li class="background-gray">' +
'<a href="' + objItem.appLandingPage + '.html" class="item-content item-link">' +
'<div class="item-inner">' +
'• ' + objItem.name +
'</div></a></li>';
htmlContent += "</ul>";
document.getElementById('idIndexPagePrinters').innerHTML = htmlContent;
}
return;
}
//myApp.alert('Could not find printer');
// htmlContent += '<li class="background-gray" style="color:red">' +
// '<a href="printeroffline.html" class="item-content item-link">' +
// '<div class="item-inner">' +
// '• ' + objItem.name +
// '</div></a></li>';
// htmlContent += "</ul>";
// document.getElementById('idIndexPagePrinters').innerHTML = htmlContent;
// return;
} // End of if (this.readystate...
}; // End of xmlhttp.onreadystatechange...
printerRequest.send();
}); // End of globalArrayPrinterProfiles.forEach()
} else {
// Else from if (globalArrayPrinterProfiles.length) {
htmlContent += '<li class="background-gray">' +
'<a href="addprinter.html" class="item-content item-link">' +
'<div class="item-inner">' +
'<div class="item-title addprinter.html">' +
'Add a printer</div>' +
'</div></a></li>';
htmlContent += "</ul>";
document.getElementById('idIndexPagePrinters').innerHTML = htmlContent;
return;
} // End of if (globalArrayPrinterProfiles.length) {
}
});
// Initialize app and if we need to use custom DOM library, let's save it to $$ variable:
var myApp = new Framework7();
var $$ = Dom7;
// Add view and because we want to use dynamic navbar, we need to enable it:
var mainView = myApp.addView('.view-main', {
dynamicNavbar: true,
domCache: true
});
// Handle Cordova Device Ready Event since smartphones take a while to load up.
// Set the version text in the left panel's footer while we're initializing things.
$$(document).on('deviceready', function () {
$$('.panel-footer-version').html('Ver. ' + Version);
// ------------------------------------------------------------------------
// Here, we do some initialization if there are no saved printer profiles
// in local storage.
// First, retrieve the existing jsonString of the array from local storage
var jsonStringExistingArray = localStorage.getItem('arrayPrinterProfiles');
if (!jsonStringExistingArray) {
//myApp.alert('Initializing local storage');
// Looks like the user hasn't save any printers yet, let's save an
// empty array
var objEmptyArrayPrinterProfiles = { 'PrinterProfiles': [] };
// Now convert this into a json string
var jsonStringEmptyArrayPrinterProfiles = JSON.stringify(objEmptyArrayPrinterProfiles);
// Finally, save it to local storage
localStorage.setItem('arrayPrinterProfiles', jsonStringEmptyArrayPrinterProfiles);
} //else myApp.alert('Found initial local storage: ' + jsonStringExistingArray);
// ------------------------------------------------------------------------
});
/* ----------------------------------------------------------
Local storage (stored as json strings)
----------------------------------------------------------
{
'PrinterProfiles':
[
{
charming-pascal': {
'hostName': 'charming-pascal.local',
'apiKey': 'hexstring',
'webcamUrl': 'http://charming-pascal.local:8080/?actin=stream',
'selectedFilament': 'PLA'}
}
]
}
*/
/**
* Add a new printer profile object in the local storage array if it doesn't
* already exist; overwrite it otherwise (TODO).
*
* @param {object} - The incoming JSON printer profile information
*/
function addPrinterProfile(objIncomingPrinterProfile) {
// First, retrieve the existing jsonString of the array from local storage
var jsonStringExistingArray = localStorage.getItem('arrayPrinterProfiles');
// Then, convert it back into a json object (array)
var objArrayExistingPrinterProfiles = JSON.parse(jsonStringExistingArray);
// Look up the incoming printer to see if it's already there
var incomingKey;
for (var prop in objIncomingPrinterProfile) {
incomingKey = prop; // Should be 'charming-pascal' on mine
break;
}
// Does it already exist?
if (objArrayExistingPrinterProfiles[incomingKey]) {
// TODO (ignores at the moment)
} else {
// Okay, let's add it then
// objIncomingPrinterProfile should look like:
// { 'charming-pascal':
// { 'hostName': 'charming-pascal.local',
// 'apiKey': 'hexstring',
// 'webcamUrl': 'http://charming-pascal.local:8080/?action=stream'
// 'selectedFilament': 'PLA' }}
objArrayExistingPrinterProfiles.PrinterProfiles.push(objIncomingPrinterProfile);
//myApp.alert(JSON.stringify(objArrayExistingPrinterProfiles));
// Now convert the object into a json string for saving back to storage
var jsonStringNewPrinterProfiles = JSON.stringify(objArrayExistingPrinterProfiles);
// Finally, save it back to local storage
localStorage.setItem('arrayPrinterProfiles', jsonStringNewPrinterProfiles);
}
}
/**
* Return an array of printer profiles, as stored in local storage.
*
*/
function getPrinterProfiles() {
var jsonString = localStorage.getItem('arrayPrinterProfiles');
var objArrayPrinterProfiles = JSON.parse(jsonString);
return objArrayPrinterProfiles;
}
/**
* Pad the single-digit integer minutes, for example, to two digits as a string
*
* @param {Number} - The (probably) one or two-digit number
*/
function pad(num) {
return ('00' + num).substr(-2);
}
/**
* Send the specified command to the indicated printer.
*
* @param {Number} - The printer ordinal from the global array
* @param {String} - The API endpoint
* @param {object} - The JSON printer command to send
*/
function sendToPrinter(iPrinterOrdinal, endPoint, objPrinterCommand, callback) {
var response = "";
var objPrinter = globalArrayPrinterProfiles[iPrinterOrdinal];
var apiKey = objPrinter.apiKey;
var url = "http://" + objPrinter.hostName + endPoint;
//console.log(objPrinterCommand);
$$.ajaxSetup({ headers: { 'X-Api-Key': apiKey }});
$$.ajax({
url: url,
method: 'POST',
contentType: 'application/json',
data: JSON.stringify(objPrinterCommand),
success: function(response){
if (typeof callback === "function") {
callback('Status 204');
}
},
error: function(xhr, status){
if (typeof callback === "function") {
callback(JSON.stringify(status));
}
}
});
};
// Upon clicking the left panel's video link, toggle visibility... and then back
$$('.gettingStartedVideos').on('click', function () {
document.getElementById('videosLeft').style.display = 'block';
document.getElementById('mainLeft').style.display = 'none';
});
$$('.gettingStartedVideosClose').on('click', function () {
document.getElementById('videosLeft').style.display = 'none';
document.getElementById('mainLeft').style.display = 'block';
});
// Here, we're using a page callback for the reportissue page:
myApp.onPageInit('reportissue', function (page) {
$$('#idReportIssueSendLink').on('click', function () {
// First, retrieve the existing jsonString of the array from local storage
var jsonStringReportIssue = localStorage.getItem('f7form-idReportIssue');
// Then, convert it back into a json object (array)
var objReportIssue = JSON.parse(jsonStringReportIssue);
var args = {
subject: 'subject',
body: 'message',
toRecipients: '<EMAIL>'
};
$$('#idDivReportIssue').html(
'Body:<br/>' +
' Name: ' +
objReportIssue.name + '<br/>' +
' Email: ' + objReportIssue.email + '<br/>' +
' Phone: ' + objReportIssue.phone + '<br/><br/>' +
' ' + objReportIssue.body + '<br/><br/>' +
'<a class="external link" href="mailto:' +
objReportIssue.recipient +
'?subject=' +
objReportIssue.subject +
'&body=' +
'Name: ' +
objReportIssue.name + '%0D%0A' +
'Email: ' + objReportIssue.email + '%0D%0A' +
'Phone: ' + objReportIssue.phone + '%0D%0A%0D%0A' +
objReportIssue.body + '%0D%0A' +
'"><div class="button-send button-blue">Click here to send this info to us</div>' +
'</a>');
setTimeout(function(){mainView.router.loadPage("/");}, 10000);
});
});
// Here, we're using a page callback for the deleteprinter page:
myApp.onPageInit('deleteprinter', function (page) {
$$('#idDeletePrinterBackLink').on('click', function () {
localStorage.clear();
// Let's save an empty array in its place
var objEmptyArrayPrinterProfiles = { 'PrinterProfiles': [] };
// Now convert this into a json string
var jsonStringEmptyArrayPrinterProfiles = JSON.stringify(objEmptyArrayPrinterProfiles);
// Finally, save it to local storage
localStorage.setItem('arrayPrinterProfiles', jsonStringEmptyArrayPrinterProfiles);
mainView.router.loadPage("/");
});
});
// Here, we're using a page callback for the addprinter page:
myApp.onPageInit('addprinter', function (page) {
//console.log('Initializing addprinter...');
$$('#idSaveButtonAddPrinter').on('click', function () {
//console.log('Save Button clicked');
// First, retrieve the existing jsonString of the array from local storage
var jsonStringAddPrinter = localStorage.getItem('f7form-idAddPrinterForm');
// Then, convert it back into a json object (array)
var objAddPrinter = JSON.parse(jsonStringAddPrinter);
// Push the data sideways into a json string
/*
{ "charming-pascal":
{ "hostName": "charming-pascal.local",
"apiKey": "hexstring",
"webcamUrl": "http://charming-pascal.local:8080/?action=stream",
"selectedFilament": "PLA" }}
*/
var jsonStringNewPrinter = '{ "' +
objAddPrinter.addPrinterDisplayName +
'": { "hostName": "' +
objAddPrinter.addPrinterHostName +
'", "apiKey": "' +
objAddPrinter.addPrinterApiKey +
'", "webcamUrl": "' +
objAddPrinter.addPrinterWebcamUrl +
'", "selectedFilament": "PLA" }}';
// Then, convert it into a json object
var objNewPrinter = JSON.parse(jsonStringNewPrinter);
// And add it to the local storage
addPrinterProfile(objNewPrinter);
});
});
// Here, we're using a page callback for the appsettings page:
myApp.onPageInit('appsettings', function (page) {
var htmlContent = "";
if (globalArrayPrinterProfiles.length) {
globalArrayPrinterProfiles.forEach(function (objItem) {
// console.log(objItem.name);
// TODO (make this work for more than one printer by determining the page ordinal)
htmlContent += '<div class="button-app-settings button-blue">' +
objItem.name +
'</div>' +
'<a href="deleteprinter.html" class="item-content item-link a-button-delete">' +
'<div class="button-delete">Delete</div>' +
'</a>';
});
} else {
htmlContent += '<a href="addprinter.html" class="item-content item-link a-button-addprinter">' +
'<div class="button-addprinter button-blue">Add a Printer</div>' +
'</a>';
}
document.getElementById('idAppSettingsDetail').innerHTML = htmlContent;
});
// Page loader for the printerProfile[0] click
$$('.printer01').on('click', function () {
mainView.router.loadPage('printer01.html');
});
// Here, we're using a page callback for the printerProfile[0] page:
myApp.onPageInit('printer01', function (page) {
var printerName = "";
var printerHostName = "";
var printerApiKey = "";
var printerSelectedFilament = "";
var selectedJogAmount = "";
var selectedMotor = "";
var selectedHeatingElement = "tool0";
// Also, we need to push the printer's name to the top of each landing page
globalArrayPrinterProfiles.forEach(function (objItem) {
if (objItem.appLandingPage === page.name) {
printerName = objItem.name;
printerHostName = objItem.hostName;
printerApiKey = objItem.apiKey;
printerSelectedFilament = objItem.selectedFilament;
$$("#idPrinterTitle").html(objItem.name);
}
});
const apiKeyAddon = "apikey=" + printerApiKey;
var url = "";
var htmlContent = "";
var operationalPrinter01 = false;
var printingPrinter01 = false;
var pausedPrinter01 = false;
var printerOrdinal = (parseInt(page.name[page.name.length - 1])) - 1;
/* ----------------------------------------------------------------------
Motors
-------------------------------------------------------------------------*/
{
// To-do: Need to query the current jog amount and colorize one of these
htmlContent = '<p></p>';
/* ------------------------------------------------------------------
Jog amounts
---------------------------------------------------------------------*/
if (selectedJogAmount == "") selectedJogAmount = "1mm";
var amounts = [
{ 'name': '0.1mm', 'color': 'button-gray' },
{ 'name': '1mm', 'color': 'button-blue' },
{ 'name': '10mm', 'color': 'button-gray' },
{ 'name': '100mm', 'color': 'button-gray' }
];
amounts.forEach(function (item) {
htmlContent += '<div id="idMotorControlJog' + item.name.replace(/\./g, '') + '" class="button-jog ' + item.color + '">' +
item.name + '</div>';
});
/* ------------------------------------------------------------------
Motor selection
---------------------------------------------------------------------*/
if (selectedMotor == "") selectedMotor = "X-Axis";
var motors = [
{ 'name': 'X-Axis', 'color': 'button-blue', 'isSelected': true },
{ 'name': 'Y-Axis', 'color': 'button-gray', 'isSelected': false },
{ 'name': 'Z-Axis', 'color': 'button-gray', 'isSelected': false },
{ 'name': 'Extruder', 'color': 'button-gray', 'isSelected': false }
];
motors.forEach(function (item) {
htmlContent += '<div id="idMotorControl' + item.name + '" class="button-motors ' + item.color + '">' +
item.name + '</div>';
});
htmlContent += '<hr width="95%"/>';
/* ------------------------------------------------------------------
Actions
---------------------------------------------------------------------*/
var directions = [
{ 'name': 'Left', 'display': 'inline-block' },
{ 'name': 'Back', 'display': 'none' },
{ 'name': 'Up', 'display': 'none' },
{ 'name': 'Extrude', 'display': 'none' },
{ 'name': 'Home', 'display': 'inline-block' },
{ 'name': 'Right', 'display': 'inline-block' },
{ 'name': 'Front', 'display': 'none' },
{ 'name': 'Down', 'display': 'none' },
{ 'name': 'Retract', 'display': 'none' }
];
directions.forEach(function (item) {
htmlContent += '<div id="idMotorControl' + item.name + '" class="button-action button-blue" ' +
'style="display:' + item.display + '"' +
'>' +
item.name + '</div>';
});
$$("#idMotorsDetail").html(htmlContent);
$$('#idMotorControlHome').on('click', function () {
// myApp.alert('You pressed the Home button');
// /api/printer/printhead
// { "command": "home", "axes": ["x", "y", "z"] }
var endPoint = "/api/printer/printhead";
var objPrinterCommand = { "command": "home", "axes": ["x","y","z"] };
sendToPrinter(printerOrdinal, endPoint, objPrinterCommand, function(data){
//console.log('Home command sent to printer: ' + data);
});
});
$$('#idMotorControlLeft').on('click', function () {
//myApp.alert('You pressed the Left button');
// api/printer/printhead
// { "command": "jog", "x": jogAmount }
var jogAmount = -1 * parseFloat(selectedJogAmount.replace(/m/g, ''));
//myApp.alert(jogAmount);
var endPoint = "/api/printer/printhead";
var objPrinterCommand = { "command": "jog", "x": jogAmount };
sendToPrinter(printerOrdinal, endPoint, objPrinterCommand, function(data){
//console.log('Left command sent to printer: ' + data);
});
});
$$('#idMotorControlRight').on('click', function () {
//myApp.alert('You pressed the Right button');
// api/printer/printhead
// { "command": "jog", "x": jogAmount }
var jogAmount = parseFloat(selectedJogAmount.replace(/m/g, ''));
//myApp.alert(jogAmount);
var endPoint = "/api/printer/printhead";
var objPrinterCommand = { "command": "jog", "x": jogAmount };
sendToPrinter(printerOrdinal, endPoint, objPrinterCommand, function(data){
//console.log('Right command sent to printer: ' + data);
});
});
$$('#idMotorControlBack').on('click', function () {
//myApp.alert('You pressed the Back button');
// api/printer/printhead
// { "command": "jog", "y": jogAmount }
var jogAmount = parseFloat(selectedJogAmount.replace(/m/g, ''));
//myApp.alert(jogAmount);
var endPoint = "/api/printer/printhead";
var objPrinterCommand = { "command": "jog", "y": jogAmount };
sendToPrinter(printerOrdinal, endPoint, objPrinterCommand, function(data){
//console.log('Back command sent to printer: ' + data);
});
});
$$('#idMotorControlFront').on('click', function () {
//myApp.alert('You pressed the Front button');
// api/printer/printhead
// { "command": "jog", "y": jogAmount }
var jogAmount = -1 * parseFloat(selectedJogAmount.replace(/m/g, ''));
//myApp.alert(jogAmount);
var endPoint = "/api/printer/printhead";
var objPrinterCommand = { "command": "jog", "y": jogAmount };
sendToPrinter(printerOrdinal, endPoint, objPrinterCommand, function(data){
//console.log('Front command sent to printer: ' + data);
});
});
$$('#idMotorControlUp').on('click', function () {
//myApp.alert('You pressed the Up button');
// api/printer/printhead
// { "command": "jog", "z": jogAmount }
var jogAmount = -1 * parseFloat(selectedJogAmount.replace(/m/g, ''));
//myApp.alert(jogAmount);
var endPoint = "/api/printer/printhead";
var objPrinterCommand = { "command": "jog", "z": jogAmount };
sendToPrinter(printerOrdinal, endPoint, objPrinterCommand, function(data){
//console.log('Up command sent to printer: ' + data);
});
});
$$('#idMotorControlDown').on('click', function () {
//myApp.alert('You pressed the Down button');
// api/printer/printhead
// { "command": "jog", "z": jogAmount }
var jogAmount = parseFloat(selectedJogAmount.replace(/m/g, ''));
//myApp.alert(jogAmount);
var endPoint = "/api/printer/printhead";
var objPrinterCommand = { "command": "jog", "z": jogAmount };
sendToPrinter(printerOrdinal, endPoint, objPrinterCommand, function(data){
//console.log('Down command sent to printer: ' + data);
});
});
$$('#idMotorControlExtrude').on('click', function () {
//myApp.alert('You pressed the Extrude button');
// api/printer/tool
// { "command": "select", "tool": "tool0" }
// { "command": "extrude", "amount": jogAmount }
var jogAmount = parseFloat(selectedJogAmount.replace(/m/g, ''));
//myApp.alert(jogAmount);
var endPoint = "/api/printer/tool";
var objPrinterCommand = { "command": "select", "tool": "tool0" };
sendToPrinter(printerOrdinal, endPoint, objPrinterCommand, function(data){
objPrinterCommand = { "command": "extrude", "amount": jogAmount };
sendToPrinter(printerOrdinal, endPoint, objPrinterCommand, function(data){
//console.log('Extrude command sent to printer: ' + data);
});
});
});
$$('#idMotorControlRetract').on('click', function () {
//myApp.alert('You pressed the Retract button');
// api/printer/tool
// { "command": "select", "tool": "tool0" }
// { "command": "extrude", "amount": jogAmount }
var jogAmount = -1 * parseFloat(selectedJogAmount.replace(/m/g, ''));
//myApp.alert(jogAmount);
var endPoint = "/api/printer/tool";
var objPrinterCommand = { "command": "select", "tool": "tool0" };
sendToPrinter(printerOrdinal, endPoint, objPrinterCommand, function(data){
objPrinterCommand = { "command": "extrude", "amount": jogAmount };
sendToPrinter(printerOrdinal, endPoint, objPrinterCommand, function(data){
//console.log('Retract command sent to printer: ' + data);
});
});
});
$$('#idMotorControlX-Axis').on('click', function () {
//myApp.alert('You pressed the X-Axis button');
selectedMotor = "X-Axis";
// Toggle motor-select colors
document.getElementById('idMotorControlX-Axis').className = "button-motors button-blue";
document.getElementById('idMotorControlY-Axis').className = "button-motors button-gray";
document.getElementById('idMotorControlZ-Axis').className = "button-motors button-gray";
document.getElementById('idMotorControlExtruder').className = "button-motors button-gray";
// Change motor-direction buttons
document.getElementById('idMotorControlBack').style.display = "none";
document.getElementById('idMotorControlUp').style.display = "none";
document.getElementById('idMotorControlExtrude').style.display = "none";
document.getElementById('idMotorControlLeft').style.display = "inline-block";
document.getElementById('idMotorControlFront').style.display = "none";
document.getElementById('idMotorControlDown').style.display = "none";
document.getElementById('idMotorControlRetract').style.display = "none";
document.getElementById('idMotorControlRight').style.display = "inline-block";
});
$$('#idMotorControlY-Axis').on('click', function () {
//myApp.alert('You pressed the Y-Axis button');
selectedMotor = "Y-Axis";
// Toggle motor-select colors
document.getElementById('idMotorControlX-Axis').className = "button-motors button-gray";
document.getElementById('idMotorControlY-Axis').className = "button-motors button-blue";
document.getElementById('idMotorControlZ-Axis').className = "button-motors button-gray";
document.getElementById('idMotorControlExtruder').className = "button-motors button-gray";
// Change motor-direction buttons
document.getElementById('idMotorControlLeft').style.display = "none";
document.getElementById('idMotorControlUp').style.display = "none";
document.getElementById('idMotorControlExtrude').style.display = "none";
document.getElementById('idMotorControlBack').style.display = "inline-block";
document.getElementById('idMotorControlRight').style.display = "none";
document.getElementById('idMotorControlDown').style.display = "none";
document.getElementById('idMotorControlRetract').style.display = "none";
document.getElementById('idMotorControlFront').style.display = "inline-block";
});
$$('#idMotorControlZ-Axis').on('click', function () {
//myApp.alert('You pressed the Z-Axis button');
selectedMotor = "Z-Axis";
// Toggle motor-select colors
document.getElementById('idMotorControlX-Axis').className = "button-motors button-gray";
document.getElementById('idMotorControlY-Axis').className = "button-motors button-gray";
document.getElementById('idMotorControlZ-Axis').className = "button-motors button-blue";
document.getElementById('idMotorControlExtruder').className = "button-motors button-gray";
// Change motor-direction buttons
document.getElementById('idMotorControlLeft').style.display = "none";
document.getElementById('idMotorControlBack').style.display = "none";
document.getElementById('idMotorControlExtrude').style.display = "none";
document.getElementById('idMotorControlUp').style.display = "inline-block";
document.getElementById('idMotorControlRight').style.display = "none";
document.getElementById('idMotorControlFront').style.display = "none";
document.getElementById('idMotorControlRetract').style.display = "none";
document.getElementById('idMotorControlDown').style.display = "inline-block";
});
$$('#idMotorControlExtruder').on('click', function () {
// TODO prevent this until the temperature is right
//myApp.alert('You pressed the Extruder button');
selectedMotor = "Extruder";
// Toggle motor-select colors
document.getElementById('idMotorControlX-Axis').className = "button-motors button-gray";
document.getElementById('idMotorControlY-Axis').className = "button-motors button-gray";
document.getElementById('idMotorControlZ-Axis').className = "button-motors button-gray";
document.getElementById('idMotorControlExtruder').className = "button-motors button-blue";
// Change motor-direction buttons
document.getElementById('idMotorControlLeft').style.display = "none";
document.getElementById('idMotorControlBack').style.display = "none";
document.getElementById('idMotorControlUp').style.display = "none";
document.getElementById('idMotorControlExtrude').style.display = "inline-block";
document.getElementById('idMotorControlRight').style.display = "none";
document.getElementById('idMotorControlFront').style.display = "none";
document.getElementById('idMotorControlDown').style.display = "none";
document.getElementById('idMotorControlRetract').style.display = "inline-block";
});
$$('#idMotorControlJog01mm').on('click', function () {
//myApp.alert('You pressed the Jog 0.1mm button');
selectedJogAmount = "0.1mm";
document.getElementById('idMotorControlJog01mm').className = "button-jog button-blue";
document.getElementById('idMotorControlJog1mm').className = "button-jog button-gray";
document.getElementById('idMotorControlJog10mm').className = "button-jog button-gray";
document.getElementById('idMotorControlJog100mm').className = "button-jog button-gray";
});
$$('#idMotorControlJog1mm').on('click', function () {
//myApp.alert('You pressed the Jog 1mm button');
selectedJogAmount = "1mm";
document.getElementById('idMotorControlJog01mm').className = "button-jog button-gray";
document.getElementById('idMotorControlJog1mm').className = "button-jog button-blue";
document.getElementById('idMotorControlJog10mm').className = "button-jog button-gray";
document.getElementById('idMotorControlJog100mm').className = "button-jog button-gray";
});
$$('#idMotorControlJog10mm').on('click', function () {
//myApp.alert('You pressed the Jog 10mm button');
selectedJogAmount = "10mm";
document.getElementById('idMotorControlJog01mm').className = "button-jog button-gray";
document.getElementById('idMotorControlJog1mm').className = "button-jog button-gray";
document.getElementById('idMotorControlJog10mm').className = "button-jog button-blue";
document.getElementById('idMotorControlJog100mm').className = "button-jog button-gray";
});
$$('#idMotorControlJog100mm').on('click', function () {
//myApp.alert('You pressed the Jog 100mm button');
selectedJogAmount = "100mm";
document.getElementById('idMotorControlJog01mm').className = "button-jog button-gray";
document.getElementById('idMotorControlJog1mm').className = "button-jog button-gray";
document.getElementById('idMotorControlJog10mm').className = "button-jog button-gray";
document.getElementById('idMotorControlJog100mm').className = "button-jog button-blue";
});
}
/* ----------------------------------------------------------------------
End of Motors
-------------------------------------------------------------------------*/
/* ----------------------------------------------------------------------
Temperature
-------------------------------------------------------------------------*/
url = "http://" + printerHostName + "/api/printer?" + apiKeyAddon;
var aTools = [];
$$.getJSON(url, function (jsonData) {
// TODO Set selectedHeatingElement if button is clicked for Tool0, for example,
// and use this when doing later extrude/extract commands. It's probably a
// good idea to use the tool ID that OctoPrint expects for this variable's
// value.
htmlContent = '<p></p>';
var temps = [];
if (jsonData.state.flags) {
operationalPrinter01 = jsonData.state.flags.operational;
printingPrinter01 = jsonData.state.flags.printing;
pausedPrinter01 = jsonData.state.flags.paused;
}
if (jsonData.temperature.tool0) {
temps.push({
'tool': 'tool0',
'name': 'Extruder1',
'actual': jsonData.temperature.tool0.actual,
'target': jsonData.temperature.tool0.target,
'color': 'button-blue'
});
aTools.push('tool0');
}
if (jsonData.temperature.tool1) {
temps.push({
'tool': 'tool1',
'name': 'Extruder2',
'actual': jsonData.temperature.tool1.actual,
'target': jsonData.temperature.tool1.target,
'color': 'button-gray'
});
aTools.push('tool1');
}
if (jsonData.temperature.bed) {
temps.push({
'tool': 'bed',
'name': 'Bed',
'actual': jsonData.temperature.bed.actual,
'target': jsonData.temperature.bed.target,
'color': 'button-gray'
});
aTools.push('bed');
}
temps.forEach(function (item) {
htmlContent += '<div id="idButton-' + item.tool + '" ' +
'style="color:white;font-size:14pt;font-family: Arial, Helvetica, sans-serif;border-radius:5px;padding:5px;margin-bottom:5px;' +
'" class="button-file ' + item.color + '">' +
'<span>' + item.name + ' (' + printerSelectedFilament + ')</span><span style="position:relative;float:right">Actual: ' + item.actual + '°C / Target: ' + item.target + '°C</span></div>';
});
// Add a button for preheating the selected tool
htmlContent += '<hr width="95%"/>';
htmlContent += '<div id="idToolPreheat" ' +
'" class="button-preheat button-blue">' +
'Preheat Selected Tool</div>';
htmlContent += '<p></p>';
htmlContent += '<div id="idToolCooldown" ' +
'style="display:none" ' +
'" class="button-preheat button-blue">' +
'Turn Off Heat For Selected Tool</div>';
htmlContent += '<p></p>';
$$("#idTemperatureDetail").html(htmlContent);
// TODO add buttons based on aTools[] for selecting different tools
$$('#idToolPreheat').on('click', function () {
// myApp.alert('You pressed the Tool Preheat button with ' + printerSelectedFilament + ' and ' + selectedHeatingElement);
document.getElementById('idToolPreheat').style.display = "none";
document.getElementById('idToolCooldown').style.display = "inline-block";
// api/printer/tool
// { "command": "target", "targets": ["tool0": tempTarget] }
var tempTarget = 90.0; // 190
//myApp.alert(tempTarget);
var endPoint = "/api/printer/tool";
var objPrinterCommand = JSON.parse('{ "command": "target", "targets": {"' +
selectedHeatingElement + '": ' + tempTarget + '}}');
// console.log(objPrinterCommand);
sendToPrinter(printerOrdinal, endPoint, objPrinterCommand, function(data){
//console.log('Preheat command sent to printer: ' + data);
});
});
$$('#idToolCooldown').on('click', function () {
// myApp.alert('You pressed the Tool Cooldown button with ' + printerSelectedFilament + ' and ' + selectedHeatingElement);
document.getElementById('idToolCooldown').style.display = "none";
document.getElementById('idToolPreheat').style.display = "inline-block";
// api/printer/tool
// { "command": "target", "targets": ["tool0": tempTarget] }
var tempTarget = 0;
//myApp.alert(tempTarget);
var endPoint = "/api/printer/tool";
var objPrinterCommand = JSON.parse('{ "command": "target", "targets": {"' +
selectedHeatingElement + '": ' + tempTarget + '}}');
// console.log(objPrinterCommand);
sendToPrinter(printerOrdinal, endPoint, objPrinterCommand, function(data){
//console.log('Cooldown command sent to printer: ' + data);
});
});
});
/* ----------------------------------------------------------------------
End of Temperature
-------------------------------------------------------------------------*/
/* ----------------------------------------------------------------------
Settings
-------------------------------------------------------------------------*/
url = "http://" + printerHostName + "/api/settings?" + apiKeyAddon;
$$.getJSON(url, function (jsonData) {
var buttonColor = 'button-blue';
/*
Honestly, there's not much usefulness in showing the user the COM
settings to the Robo board so even though the original app had it,
I'm removing it.
*/
/*htmlContent = '<p></p>';
var settings = [
{ 'name': 'Baud rate', 'value': jsonData.serial.baudrate },
{ 'name': 'Autoconnect', 'value': jsonData.serial.autoconnect },
{ 'name': 'Device', 'value': jsonData.serial.port }
];
settings.forEach(function (item) {
htmlContent += '<div ' +
'style="color:white;font-size:14pt;font-family: Arial, Helvetica, sans-serif;border-radius:5px;padding:5px;margin-bottom:5px;' +
'" class="button-file ' + buttonColor + '">' +
'<span>' + item.name + '</span><span style="position:relative;float:right">' + item.value + '</span></div>';
});
htmlContent += '<p></p>';
$$("#idSettingsDetail").html(htmlContent);*/
/* ------------------------------------------------------------------
Filament
---------------------------------------------------------------------*/
buttonColor = "button-gray";
htmlContent = '<p></p>';
var filaments = [
{ 'name': jsonData.temperature.profiles[0].name, 'extruder': jsonData.temperature.profiles[0].extruder, 'bed': jsonData.temperature.profiles[0].bed },
{ 'name': jsonData.temperature.profiles[1].name, 'extruder': jsonData.temperature.profiles[1].extruder, 'bed': jsonData.temperature.profiles[1].bed }
];
filaments.forEach(function (item) {
buttonColor = (printerSelectedFilament === item.name) ? 'button-blue' : 'button-gray';
htmlContent += '<div ' +
'style="color:white;font-size:14pt;font-family: Arial, Helvetica, sans-serif;border-radius:5px;padding:5px;margin-bottom:5px;' +
'" id="idFilament' + item.name + '" ' +
'class="button-file ' + buttonColor + '">' +
'<span>' + item.name + '</span><span style="position:relative;float:right">Extruder: ' + item.extruder + '°C, Bed: ' + item.bed + '°C</span></div>';
});
htmlContent += '<p></p>';
$$("#idFilamentDetail").html(htmlContent);
// Upon clicking the filament button, change filament stored in local storage
$$('#idFilamentABS').on('click', function () {
document.getElementById('idFilamentABS').className = 'button-file button-blue';
document.getElementById('idFilamentPLA').className = 'button-file button-gray';
// First, retrieve the existing jsonString of the array from local storage
var jsonStringExistingArray = localStorage.getItem('arrayPrinterProfiles');
// Then, convert it back into a json object (array)
var objArrayExistingPrinterProfiles = JSON.parse(jsonStringExistingArray);
objArrayExistingPrinterProfiles.PrinterProfiles[0][printerName].selectedFilament = 'ABS';
// Now convert the object into a json string for saving back to storage
var jsonStringNewPrinterProfiles = JSON.stringify(objArrayExistingPrinterProfiles);
// Finally, save it back to local storage
localStorage.setItem('arrayPrinterProfiles', jsonStringNewPrinterProfiles);
// Don't forget to save it into the global array
globalArrayPrinterProfiles[0].selectedFilament = 'ABS';
});
$$('#idFilamentPLA').on('click', function () {
document.getElementById('idFilamentPLA').className = 'button-file button-blue';
document.getElementById('idFilamentABS').className = 'button-file button-gray';
// First, retrieve the existing jsonString of the array from local storage
var jsonStringExistingArray = localStorage.getItem('arrayPrinterProfiles');
// Then, convert it back into a json object (array)
var objArrayExistingPrinterProfiles = JSON.parse(jsonStringExistingArray);
objArrayExistingPrinterProfiles.PrinterProfiles[0][printerName].selectedFilament = 'PLA';
// Now convert the object into a json string for saving back to storage
var jsonStringNewPrinterProfiles = JSON.stringify(objArrayExistingPrinterProfiles);
// Finally, save it back to local storage
localStorage.setItem('arrayPrinterProfiles', jsonStringNewPrinterProfiles);
// Don't forget to save it into the global array
globalArrayPrinterProfiles[0].selectedFilament = 'PLA';
});
});
/* ----------------------------------------------------------------------
End of Settings
-------------------------------------------------------------------------*/
/* ----------------------------------------------------------------------
Webcam
-------------------------------------------------------------------------*/
{
htmlContent = '<p></p>';
// console.log(isWebcamON);
htmlContent += '<div ' +
'style="display:' + ((isWebcamON) ? 'none' : 'inline-block') + '" ' +
' id="idWebcamOn" ' +
'class="button-webcam button-blue">' +
'Turn On Webcam</div>';
htmlContent += '<div ' +
'style="display:' + ((isWebcamON) ? 'inline-block' : 'none') + '" ' +
' id="idWebcamOff" ' +
'class="button-webcam button-red">' +
'Turn Off Webcam</div>';
htmlContent += '<p></p>';
$$("#idWebcamDetail").html(htmlContent);
$$('#idWebcamOn').on('click', function () {
document.getElementById('idWebcamOff').style.display = 'block';
document.getElementById('idWebcamOn').style.display = 'none';
// POST /api/system/commands/(string: source)/(string: action)
// POST /api/system/commands/custom/streamon
var endPoint = "/api/system/commands/custom/streamon";
var objPrinterCommand = {};
sendToPrinter(printerOrdinal, endPoint, objPrinterCommand, function(data){
//console.log('Stream ON command sent to printer: ' + data);
isWebcamON = true;
document.getElementById('idBackgroundImg').style.display = 'none';
document.getElementById('idWebcamImg').style.display = 'block';
document.getElementById('idWebcamImg').style.backgroundImage = "url('http://charming-pascal.local:8080/?action=stream')";
document.getElementById('idIndexPagePrinterContainer').className = 'page-content after-webcam';
// This doesn't seem to want to work
// setTimeout(function() {
// mainView.router.loadPage("/")},
// 15000);
});
});
$$('#idWebcamOff').on('click', function () {
document.getElementById('idWebcamOn').style.display = 'block';
document.getElementById('idWebcamOff').style.display = 'none';
// POST /api/system/commands/custom/streamoff
var endPoint = "/api/system/commands/custom/streamoff";
var objPrinterCommand = {};
sendToPrinter(printerOrdinal, endPoint, objPrinterCommand, function(data){
//console.log('Stream OFF command sent to printer: ' + data);
isWebcamON = false;
document.getElementById('idBackgroundImg').style.display = 'block';
document.getElementById('idWebcamImg').style.display = 'none';
document.getElementById('idWebcamImg').style.backgroundImage = "url('../img/c2-r2-header.jpg')";
document.getElementById('idIndexPagePrinterContainer').className = 'page-content after-background';
});
});
}
/* ----------------------------------------------------------------------
End of Webcam
-------------------------------------------------------------------------*/
/* ----------------------------------------------------------------------
Files
-------------------------------------------------------------------------*/
url = "http://" + printerHostName + "/api/files?recursive=true&" + apiKeyAddon;
var aFiles = [];
$$.getJSON(url, function (jsonData) {
// At this point, we have a jsonData object which includes jsonData.files[]
// as an array of objects:
// We're probably only really interested in 1) name, 2) date,
// 3) robo_data.time.hours, robo_data.time.minutes,
htmlContent = '<p></p>';
// Walk the array first, looking for folders
// for (var i = 0, len = jsonData.files.length; i < len; i++) {
// var iconType = 'folder';
// var buttonColor = 'button-green';
// if (jsonData.files[i].type_path) {
// htmlContent += '<div ' +
// 'style="color:white;font-weight:bolder;font-size:12pt;font-family: Arial, Helvetica, sans-serif;border-radius:5px;padding:5px;margin-bottom:5px;' +
// '" class="button-file ' + buttonColor + '">' +
// '<img class="img-file ' + buttonColor + '" src="/img/' + iconType + '_48x48.png" width="48" height="48"/>' +
// '<span style="position:relative;top:3px;">' + jsonData.files[i].name + '</span></div>';
// }
// }
// Walk the array a second time, looking for just files
for (var i = 0, len = jsonData.files.length; i < len; i++) {
//console.log('Files section inside getJSON inside second for loop with: ' + i);
var iconType = (operationalPrinter01) ? 'images' : 'spacer';
var buttonColor = (operationalPrinter01) ? 'button-blue' : 'button-gray';
var hours = 0;
var minutes = 0;
var nameWithoutExtension = jsonData.files[i].name.replace(/\./g, '').replace(/gcode/g, '');
if (!jsonData.files[i].type_path) {
aFiles.push(nameWithoutExtension);
if (jsonData.files[i].robo_data) {
hours = jsonData.files[i].robo_data.time.hours;
minutes = pad(jsonData.files[i].robo_data.time.minutes);
}
htmlContent += '<div ' +
'id="idFileButton' + i + '" ' +
'style="color:white;font-weight:bolder;font-size:12pt;font-family: Arial, Helvetica, sans-serif;border-radius:5px;padding:5px;margin-bottom:5px;' +
'" class="button-file ' + buttonColor + '">' +
'<img class="img-file ' + buttonColor + '" src="/img/' + iconType + '_48x48.png" width="48" height="48"/>' +
'<span style="position:relative;top:3px;">' + jsonData.files[i].name +
// Ignore if it's never been printed
((hours == 0 && minutes == 0) ? '' : ' (' + hours + ':' + minutes + ')') +
'</span></div>';
}
}
htmlContent += '<p></p>';
$$("#idFilesDetail").html(htmlContent);
if (operationalPrinter01) {
// Create the button handler events on a per-file-button basis
for (var i = 0, len = aFiles.length; i < len; i++) {
$$('#idFileButton'+i).on('click', function (e) {
var fileName = e.target.textContent;
// Remove the optional ' (hours:minutes)' at the end
if (fileName[fileName.length - 1] == ')') {
fileName = fileName.substring(0, fileName.indexOf(' ('));
}
// /api/files/(string: location)/(path: path)
// /api/files/local/whistle_v2.gcode
// { "command": "select", "print": true }
var endPoint = "/api/files/local/" + fileName;
var objPrinterCommand = { "command": "select", "print": true };
sendToPrinter(printerOrdinal, endPoint, objPrinterCommand, function(data){
//console.log('Select/print command sent to printer for ' + fileName + ': ' + data);
});
});
};
}
});
/* ----------------------------------------------------------------------
End of Files
-------------------------------------------------------------------------*/
});
|
<reponame>DrItanium/durandal
#ifndef _rampancy_compiler_h
#define _rampancy_compiler_h
/*
* The rampancy library is a standard way to access compilers and interpreters
* from within CLIPS. It assumes that you're going to generate a pass
*
* This class is abstract
*/
#include "llvm/Pass.h"
#include "llvm/Module.h"
#include "ExpertSystem/CLIPSEnvironment.h"
#include "llvm/LLVMContext.h"
#include "llvm/ADT/StringRef.h"
namespace rampancy {
class Compiler {
private:
llvm::LLVMContext* context;
CLIPSEnvironment* env;
public:
Compiler();
~Compiler();
//this one gets arguments straight from CLIPS
virtual llvm::Module* compile() = 0;
virtual llvm::Module* compile(int argc, char** argv) = 0;
virtual llvm::Module* interpret() = 0;
virtual llvm::Module* interpret(llvm::StringRef input) = 0;
llvm::LLVMContext* getContext();
void setContext(llvm::LLVMContext* context);
void setEnvironment(CLIPSEnvironment* tEnv);
CLIPSEnvironment* getEnvironment();
};
}
#endif
|
package com.cwl.service;
import javax.xml.stream.events.Namespace;
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args ) throws ClassNotFoundException {
}
}
|
#!/bin/bash
# Sample script to set environment variables for running unit tests
# This setup matches the setup in the test/resources/create-stairwaylib-db.sql
export STAIRWAY_USERNAME='stairwayuser'
export STAIRWAY_PASSWORD='stairwaypw'
export STAIRWAY_URI='jdbc:postgresql://127.0.0.1:5432/stairwaylib'
|
const encryptPassword = require('./encryptPassword');
const generateChecksum = require('./generateChecksum');
function generateUserDocument(data, checksumSecret) {
return new Promise(async (resolve, reject) => {
try {
const { salt, hash } = await encryptPassword(data.password);
const checksum = generateChecksum(data, checksumSecret);
resolve({
_id: data.userID,
organizationID: data.organizationID,
name: data.userName,
email: data.email,
passwordSalt: salt,
passwordSHash: hash,
phone: data.phone,
role: data.role,
checksum
});
} catch (err) {
reject(errr);
}
});
}
module.exports = generateUserDocument; |
def predict_rating(reviews):
num_positive_words = 0
num_negative_words = 0
num_ambiguous_words = 0
positive_words = ["amazing", "great", "love", "like"]
negative_words = ["bad", "boring", "uninteresting"]
for review in reviews:
words = review.split()
for word in words:
if word in positive_words:
num_positive_words += 1
else if word in negative_words:
num_negative_words += 1
else:
num_ambiguous_words += 1
rating = 0.8 * (num_positive_words / (num_positive_words + num_negative_words + num_ambiguous_words)) + 0.2 * (num_positive_words / len(reviews))
return rating
print(predict_rating(["This is a great movie", "I loved it", "It was amazing"])) # 0.9 |
<filename>spec/index-spec.js
jasmine.getFixtures().fixturesPath = "spec/javascripts/fixtures";
describe("index", function() {
var ESC = 27,
$toggle_nav,
$toggle_menu;
function triggerKeydown(key) {
var e = jQuery.Event("keydown");
e.keyCode = key;
$(document).trigger(e);
}
function callFunction(func, num_times) {
for (var i = 0; i < num_times; i++) {
func.call();
}
}
beforeEach(function(){
loadFixtures("index.html");
demo.init();
$toggle_menu = $("#toggle-menu");
$toggle_nav = $("#toggle-nav");
});
describe("main navigation", function() {
it("is initially hidden", function() {
expect($toggle_nav).toHaveAttr("aria-hidden", "true");
});
it("is shown on toggle", function() {
demo.toggleMenu();
expect($toggle_nav).toHaveAttr("aria-hidden", "false");
});
it("is hidden on toggle", function() {
callFunction(demo.toggleMenu, 2);
expect($toggle_nav).toHaveAttr("aria-hidden", "true");
});
it("is hidden when escape key is pressed", function() {
demo.toggleMenu();
triggerKeydown(ESC);
expect($toggle_nav).toHaveAttr("aria-hidden", "true");
});
});
});
|
<gh_stars>1-10
from rofl.functions.const import *
from rofl.functions.torch import *
from rofl.functions.functions import isBatch, no_grad, Tmul, nprnd, F
from rofl.functions.exploratory import EpsilonGreedy
from .base import Policy
def dqnTarget(onlineNet, targetNet, s2, r, t, gamma, double:bool = True):
with no_grad():
model_out = targetNet.forward(s2)
if double:
On_model_out = onlineNet.forward(s2)
a_greedy = On_model_out.max(1)[1]
Qs2_max = model_out.gather(1, a_greedy.unsqueeze(1))
else:
Qs2_max = model_out.max(1)[0].unsqueeze(1)
t = t.bitwise_not()
target = r + Tmul(t, Qs2_max).mul(gamma).reshape(r.shape)
return target
def importanceNorm(IS):
IS = IS.unsqueeze(1)
maxIS = IS.max()
return IS / maxIS
class dqnPolicy(Policy):
discrete = True
name = "dqnPolicy"
def initPolicy(self, **kwargs):
config = self.config
self.dqnOnline = self.actor
self.dqnTarget = cloneNet(self.actor)
self.keysForUpdate = DEFT_KEYS
self.epsilon = EpsilonGreedy(config)
self.prioritized = config["agent"]["memory_prioritized"]
self.updateTarget = config["policy"]["freq_update_target"]
self.double = config['policy'].get("double", False)
self.optimizer = getOptimizer(config, self.dqnOnline)
def getAction(self, state):
throw = nprnd.uniform()
eps = self.epsilon.test(state) if self.test else self.epsilon.train(state)
self.lastNetOutput = self.actor(state) if self.prioritized else None
if throw <= eps:
return self.getRndAction()
else:
output = self.lastNetOutput if self.prioritized else self.actor(state)
return self.actor.processAction(output.argmax(1))
def update(self, infoDict):
st1, st2, rewards = infoDict['observation'], infoDict['next_observation'], infoDict['reward']
actions, dones = infoDict['action'], infoDict['done']
IS = None # TODO: add this part for sampling importance
actions = self.actor.unprocessAction(actions, isBatch(st1))
qValues = self.dqnOnline(st1).gather(1, actions)
qTargets = dqnTarget(self.dqnOnline, self.dqnTarget,
st2, rewards, dones, self.gamma, self.double)
loss = F.smooth_l1_loss(qValues, qTargets, reduction="none")
if self.prioritized:
IS = importanceNorm(IS)
loss = Tmul(IS, loss)
loss = Tmean(loss)
self.optimizer.zero_grad()
loss.backward()
self.optimizer.step()
if (self.tbw != None) and (self.epoch % self.tbwFreq == 0):
self.tbw.add_scalar('train/Loss', loss.item(), self.epoch)
self.tbw.add_scalar('train/Mean TD Error', torch.mean(qTargets - qValues).item(), self.epoch)
self._evalTBWActor_()
if self.epoch % self.updateTarget == 0:
updateNet(self.dqnTarget, self.dqnOnline.state_dict())
self.epoch += 1
del infoDict
|
<filename>src/utils/misc.ts
export const getNumberId = (data: any[], idField: string) => {
return Math.max(...data.map(item => item[idField])) + 1;
}
export const delay = (ms: number) => {
return new Promise(resolve => setTimeout(resolve, ms));
}
|
<gh_stars>100-1000
import config from '@config/config'
type objectWithNameProperty = {
name: string,
[key: string]: any
}
const exclusionPrefix = (exclusionPrefixStrings: string[]): string[] => {
return [
...config.exclusionPrefixDefault,
...exclusionPrefixStrings
]
}
const filterByPropertyName = (object: objectWithNameProperty, exclusionPrefixStrings: string[]) => !exclusionPrefix(exclusionPrefixStrings).includes(object.name.trim().substr(0, 1))
export default filterByPropertyName
|
<filename>google/cloud/dialogflow/cx/v3beta1/google-cloud-dialogflow-cx-v3beta1-ruby/lib/google/cloud/dialogflow/cx/v3beta1/fulfillment_pb.rb
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/cloud/dialogflow/cx/v3beta1/fulfillment.proto
require 'google/api/resource_pb'
require 'google/cloud/dialogflow/cx/v3beta1/advanced_settings_pb'
require 'google/cloud/dialogflow/cx/v3beta1/response_message_pb'
require 'google/protobuf/struct_pb'
require 'google/api/annotations_pb'
require 'google/protobuf'
Google::Protobuf::DescriptorPool.generated_pool.build do
add_file("google/cloud/dialogflow/cx/v3beta1/fulfillment.proto", :syntax => :proto3) do
add_message "google.cloud.dialogflow.cx.v3beta1.Fulfillment" do
repeated :messages, :message, 1, "google.cloud.dialogflow.cx.v3beta1.ResponseMessage"
optional :webhook, :string, 2
optional :return_partial_responses, :bool, 8
optional :tag, :string, 3
repeated :set_parameter_actions, :message, 4, "google.cloud.dialogflow.cx.v3beta1.Fulfillment.SetParameterAction"
repeated :conditional_cases, :message, 5, "google.cloud.dialogflow.cx.v3beta1.Fulfillment.ConditionalCases"
end
add_message "google.cloud.dialogflow.cx.v3beta1.Fulfillment.SetParameterAction" do
optional :parameter, :string, 1
optional :value, :message, 2, "google.protobuf.Value"
end
add_message "google.cloud.dialogflow.cx.v3beta1.Fulfillment.ConditionalCases" do
repeated :cases, :message, 1, "google.cloud.dialogflow.cx.v3beta1.Fulfillment.ConditionalCases.Case"
end
add_message "google.cloud.dialogflow.cx.v3beta1.Fulfillment.ConditionalCases.Case" do
optional :condition, :string, 1
repeated :case_content, :message, 2, "google.cloud.dialogflow.cx.v3beta1.Fulfillment.ConditionalCases.Case.CaseContent"
end
add_message "google.cloud.dialogflow.cx.v3beta1.Fulfillment.ConditionalCases.Case.CaseContent" do
oneof :cases_or_message do
optional :message, :message, 1, "google.cloud.dialogflow.cx.v3beta1.ResponseMessage"
optional :additional_cases, :message, 2, "google.cloud.dialogflow.cx.v3beta1.Fulfillment.ConditionalCases"
end
end
end
end
module Google
module Cloud
module Dialogflow
module CX
module V3beta1
Fulfillment = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.dialogflow.cx.v3beta1.Fulfillment").msgclass
Fulfillment::SetParameterAction = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.dialogflow.cx.v3beta1.Fulfillment.SetParameterAction").msgclass
Fulfillment::ConditionalCases = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.dialogflow.cx.v3beta1.Fulfillment.ConditionalCases").msgclass
Fulfillment::ConditionalCases::Case = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.dialogflow.cx.v3beta1.Fulfillment.ConditionalCases.Case").msgclass
Fulfillment::ConditionalCases::Case::CaseContent = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.dialogflow.cx.v3beta1.Fulfillment.ConditionalCases.Case.CaseContent").msgclass
end
end
end
end
end
|
<reponame>TimPietrusky/fivetwelve-enttec-dmx-usb-pro-mk2-test<filename>src/index.js
'use strict';
let fivetwelve = require('fivetwelve/es5');
let fivetwelve_driver_usbpro = require('fivetwelve-driver-usbpro/es5');
import randomColor from 'random-color';
let Serialport = require('serialport');
if (process.env.NODE_ENV == 'development') {
Serialport = require('virtual-serialport');
}
// Load devices
import CameoFlat1RGBW from './device/CameoFlat1RGBW';
import CameoPixBar600PRO from './device/CameoPixBar600PRO';
import CameoWookie200Rgy from './device/CameoWookie200Rgy';
import AdjStarburst from './device/AdjStarburst';
// Serial connection (USB) to Enttec DMX USB PRO Mk2
const usbProSerialport = new Serialport('/dev/cu.usbserial-EN193448');
// Initialize the driver using the serial connection
const driver = new fivetwelve_driver_usbpro(usbProSerialport);
// Create the output using the driver and initialize 2 universes
const output = fivetwelve.default(driver, 2);
// // Create the DMX devices and set the basic configuration
const device1 = new CameoFlat1RGBW({ universe : 1, address: 100 });
const pixbar = new CameoPixBar600PRO({ universe: 1, address: 13 });
const device2 = new CameoFlat1RGBW({ universe : 2, address: 1 });
const scanner = new CameoWookie200Rgy({ universe: 2, address: 10 });
const discoBall = new AdjStarburst({ universe: 2, address: 20 });
// Connect the devices to the DMX output
device1.setOutput(output);
device2.setOutput(output);
pixbar.setOutput(output);
scanner.setOutput(output);
discoBall.setOutput(output);
let dimmer = 255;
let fps = 1;
// Set initial values for the devices
device1.dimmer = dimmer;
device1.strobe = 0;
device1.color = 'rgb(0, 0, 0)';
device1.white = 0;
device2.dimmer = dimmer;
device2.strobe = 0;
device2.color = 'rgb(0, 0, 0)';
device2.white = 0;
pixbar.dimmer = dimmer;
pixbar.strobe = 0;
scanner.mode = 'dmx';
scanner.colors = 'red';
scanner.pattern = 8;
scanner.zoom = 'manual(50)';
scanner.xAxisRolling = 'manual(0)';
scanner.yAxisRolling = 'manual(0)';
scanner.zAxisRolling = 'manual(0)';
scanner.xAxisMoving = 'manual(150)';
scanner.yAxisMoving = 'manual(0)';
discoBall.color = 'rgb(255, 0, 0)';
discoBall.white = 0;
discoBall.yellow = 0;
discoBall.uv = 255;
discoBall.strobe = 'on';
discoBall.dimmer = dimmer;
discoBall.rotate = 'off';
let pixbar_active = 1;
let pixbar_animation_color = [255, 0, 0];
// Animation loop
output.requestDmxFrame(function loop(time) {
// Set a random color for each device
device1.color = randomColor().rgbString();
device2.color = randomColor().rgbString();
for (var i = 1; i <= 12; i++) {
pixbar['led' + i].rgbwauv = [0, 0, 0, 0, 0, 255];
if (i === pixbar_active) {
pixbar['led' + i].rgbwauv = [pixbar_animation_color[0], pixbar_animation_color[1], pixbar_animation_color[2], 0, 0, 0];
}
}
if (pixbar_active >= 12) {
pixbar_active = 0;
}
pixbar_active++;
output.requestDmxFrame(loop);
});
// Start the DMX output with the specified fps
output.start(1000 / fps);
console.log("Started in", process.env.NODE_ENV, "mode with", fps, "fps");
|
//#include "io2d.h"
//#include "xio2dhelpers.h"
//#include "xcairoenumhelpers.h"
//
//using namespace std;
//using namespace std::experimental::io2d;
//
//mesh_brush_factory::mesh_brush_factory() noexcept
// : _Has_current_patch()
// , _Current_patch_index()
// , _Current_patch_side_count()
// , _Current_patch_initial_point()
// , _Has_current_point()
// , _Patches() {
//}
//
//mesh_brush_factory::mesh_brush_factory(mesh_brush_factory&& other) noexcept
// : _Has_current_patch()
// , _Current_patch_index()
// , _Current_patch_side_count()
// , _Current_patch_initial_point()
// , _Has_current_point()
// , _Patches() {
// _Has_current_patch = move(other._Has_current_patch);
// _Has_current_point = move(other._Has_current_point);
// _Current_patch_index = move(other._Current_patch_index);
// _Current_patch_side_count = move(other._Current_patch_side_count);
// _Current_patch_initial_point = move(other._Current_patch_initial_point);
// _Patches = move(other._Patches);
//}
//
//mesh_brush_factory& mesh_brush_factory::operator=(mesh_brush_factory&& other) noexcept {
// if (this != &other) {
// _Has_current_patch = move(other._Has_current_patch);
// _Has_current_point = move(other._Has_current_point);
// _Current_patch_index = move(other._Current_patch_index);
// _Current_patch_side_count = move(other._Current_patch_side_count);
// _Current_patch_initial_point = move(other._Current_patch_initial_point);
// _Patches = move(other._Patches);
// }
// return *this;
//}
//
//void mesh_brush_factory::begin_patch() {
// if (_Has_current_patch) {
// _Throw_if_failed_cairo_status_t(CAIRO_STATUS_INVALID_MESH_CONSTRUCTION);
// }
// _Patches.push_back(_Patch());
// _Has_current_patch = true;
// _Has_current_point = false;
// _Current_patch_side_count = 0;
// _Current_patch_initial_point = { };
// _Current_patch_index = static_cast<unsigned int>(_Patches.size()) - 1U;
//}
//
//void mesh_brush_factory::begin_patch(error_code& ec) noexcept {
// if (_Has_current_patch) {
// ec = _Cairo_status_t_to_std_error_code(CAIRO_STATUS_INVALID_MESH_CONSTRUCTION);
// return;
// }
// try {
// _Patches.push_back(_Patch());
// }
// catch (const bad_alloc&) {
// ec = make_error_code(errc::not_enough_memory);
// return;
// }
// _Has_current_patch = true;
// _Has_current_point = false;
// _Current_patch_side_count = 0;
// _Current_patch_initial_point = { };
// _Current_patch_index = static_cast<unsigned int>(_Patches.size()) - 1U;
// ec.clear();
//}
//
//void mesh_brush_factory::begin_replace_patch(unsigned int patch_num) {
// if (_Has_current_patch) {
// _Throw_if_failed_cairo_status_t(CAIRO_STATUS_INVALID_MESH_CONSTRUCTION);
// }
//
// if (patch_num >= _Patches.size()) {
// _Throw_if_failed_cairo_status_t(CAIRO_STATUS_INVALID_INDEX);
// }
//
// _Has_current_patch = true;
// _Has_current_point = false;
// _Current_patch_side_count = 0;
// _Current_patch_initial_point = { };
// _Patch p;
// _Patches[patch_num] = p;
// _Current_patch_index = patch_num;
//}
//
//void mesh_brush_factory::begin_replace_patch(unsigned int patch_num, error_code& ec) noexcept {
// if (_Has_current_patch) {
// ec = _Cairo_status_t_to_std_error_code(CAIRO_STATUS_INVALID_MESH_CONSTRUCTION);
// return;
// }
//
// if (patch_num >= _Patches.size()) {
// ec = _Cairo_status_t_to_std_error_code(CAIRO_STATUS_INVALID_INDEX);
// return;
// }
// _Patch p;
// _Patches[patch_num] = p;
// _Has_current_patch = true;
// _Has_current_point = false;
// _Current_patch_side_count = 0;
// _Current_patch_initial_point = { };
// _Current_patch_index = patch_num;
// ec.clear();
//}
//
//void mesh_brush_factory::end_patch() {
// if (!_Has_current_patch) {
// _Throw_if_failed_cairo_status_t(CAIRO_STATUS_INVALID_MESH_CONSTRUCTION);
// }
// if (_Current_patch_side_count < 4) {
// line_to(_Current_patch_initial_point);
// }
// _Has_current_patch = false;
// _Has_current_point = false;
//}
//
//void mesh_brush_factory::end_patch(error_code& ec) noexcept {
// if (!_Has_current_patch) {
// ec = _Cairo_status_t_to_std_error_code(CAIRO_STATUS_INVALID_MESH_CONSTRUCTION);
// return;
// }
// if (_Current_patch_side_count < 4) {
// line_to(_Current_patch_initial_point, ec);
// if (static_cast<bool>(ec)) {
// return;
// }
// }
// _Has_current_patch = false;
// _Has_current_point = false;
// ec.clear();
//}
//
//void mesh_brush_factory::move_to(const vector_2d& pt) {
// if (!_Has_current_patch || _Current_patch_side_count > 0) {
// _Throw_if_failed_cairo_status_t(CAIRO_STATUS_INVALID_MESH_CONSTRUCTION);
// }
// auto& patch = _Patches.at(_Current_patch_index);
// _Current_patch_initial_point = pt;
// get<0>(patch).move_to(pt);
// _Has_current_point = true;
//}
//
//void mesh_brush_factory::move_to(const vector_2d& pt, error_code& ec) noexcept {
// if (!_Has_current_patch || _Current_patch_side_count > 0) {
// ec = _Cairo_status_t_to_std_error_code(CAIRO_STATUS_INVALID_MESH_CONSTRUCTION);
// return;
// }
// try {
// auto& patch = _Patches.at(_Current_patch_index);
// _Current_patch_initial_point = pt;
// get<0>(patch).move_to(pt);
// _Has_current_point = true;
// }
// catch (const out_of_range&) {
// ec = _Cairo_status_t_to_std_error_code(CAIRO_STATUS_INVALID_MESH_CONSTRUCTION);
// return;
// }
// ec.clear();
//}
//
//void mesh_brush_factory::line_to(const vector_2d& pt) {
// if (!_Has_current_patch || _Current_patch_side_count >= 4) {
// _Throw_if_failed_cairo_status_t(CAIRO_STATUS_INVALID_MESH_CONSTRUCTION);
// }
//
// if (!_Has_current_point) {
// move_to(pt);
// }
// else {
// auto& patch = _Patches.at(_Current_patch_index);
// get<0>(patch).line_to(pt);
// _Current_patch_side_count++;
// }
//}
//
//void mesh_brush_factory::line_to(const vector_2d& pt, error_code& ec) noexcept {
// if (!_Has_current_patch || _Current_patch_side_count >= 4) {
// ec = _Cairo_status_t_to_std_error_code(CAIRO_STATUS_INVALID_MESH_CONSTRUCTION);
// return;
// }
//
// if (!_Has_current_point) {
// move_to(pt, ec);
// if (static_cast<bool>(ec)) {
// return;
// }
// }
// else {
// try {
// auto& patch = _Patches.at(_Current_patch_index);
// get<0>(patch).line_to(pt);
// _Current_patch_side_count++;
// }
// catch (const out_of_range&) {
// ec = _Cairo_status_t_to_std_error_code(CAIRO_STATUS_INVALID_MESH_CONSTRUCTION);
// return;
// }
// }
// ec.clear();
//}
//
//void mesh_brush_factory::curve_to(const vector_2d& pt0, const vector_2d& pt1, const vector_2d& pt2) {
// if (!_Has_current_patch || _Current_patch_side_count >= 4) {
// _Throw_if_failed_cairo_status_t(CAIRO_STATUS_INVALID_MESH_CONSTRUCTION);
// }
//
// if (!_Has_current_point) {
// move_to(pt0);
// }
//
// _Current_patch_side_count++;
// auto& patch = _Patches.at(_Current_patch_index);
// get<0>(patch).curve_to(pt0, pt1, pt2);
//}
//
//void mesh_brush_factory::curve_to(const vector_2d& pt0, const vector_2d& pt1, const vector_2d& pt2, error_code& ec) noexcept {
// if (!_Has_current_patch || _Current_patch_side_count >= 4) {
// ec = _Cairo_status_t_to_std_error_code(CAIRO_STATUS_INVALID_MESH_CONSTRUCTION);
// return;
// }
//
// if (!_Has_current_point) {
// move_to(pt0, ec);
// if (static_cast<bool>(ec)) {
// return;
// }
// }
//
// try {
// auto& patch = _Patches.at(_Current_patch_index);
// _Current_patch_side_count++;
// get<0>(patch).curve_to(pt0, pt1, pt2);
// }
// catch (const out_of_range&) {
// ec = _Cairo_status_t_to_std_error_code(CAIRO_STATUS_INVALID_MESH_CONSTRUCTION);
// return;
// }
// ec.clear();
//}
//
//void mesh_brush_factory::control_point(unsigned int point_num, const vector_2d& pt) {
// if (!_Has_current_patch) {
// _Throw_if_failed_cairo_status_t(CAIRO_STATUS_INVALID_MESH_CONSTRUCTION);
// }
// if (point_num > 3) {
// _Throw_if_failed_cairo_status_t(CAIRO_STATUS_INVALID_INDEX);
// }
// auto& patch = _Patches.at(_Current_patch_index);
// get<1>(patch)[point_num] = make_tuple(true, pt);
//}
//
//void mesh_brush_factory::control_point(unsigned int point_num, const vector_2d& pt, error_code& ec) noexcept {
// if (!_Has_current_patch) {
// ec = _Cairo_status_t_to_std_error_code(CAIRO_STATUS_INVALID_MESH_CONSTRUCTION);
// return;
// }
// if (point_num > 3) {
// ec = _Cairo_status_t_to_std_error_code(CAIRO_STATUS_INVALID_INDEX);
// return;
// }
//
// try {
// auto& patch = _Patches.at(_Current_patch_index);
// get<1>(patch)[point_num] = make_tuple(true, pt);
// }
// catch (const out_of_range&) {
// ec = _Cairo_status_t_to_std_error_code(CAIRO_STATUS_INVALID_MESH_CONSTRUCTION);
// return;
// }
// ec.clear();
//}
//
//void mesh_brush_factory::corner_color(unsigned int corner_num, const rgba_color& color) {
// if (!_Has_current_patch) {
// _Throw_if_failed_cairo_status_t(CAIRO_STATUS_INVALID_MESH_CONSTRUCTION);
// }
// if (corner_num > 3) {
// _Throw_if_failed_cairo_status_t(CAIRO_STATUS_INVALID_INDEX);
// }
// auto& patch = _Patches.at(_Current_patch_index);
// get<2>(patch)[corner_num] = make_tuple(true, color);
//}
//
//void mesh_brush_factory::corner_color(unsigned int corner_num, const rgba_color& color, error_code& ec) noexcept {
// if (!_Has_current_patch) {
// ec = _Cairo_status_t_to_std_error_code(CAIRO_STATUS_INVALID_MESH_CONSTRUCTION);
// return;
// }
// if (corner_num > 3) {
// ec = _Cairo_status_t_to_std_error_code(CAIRO_STATUS_INVALID_INDEX);
// return;
// }
//
// try {
// auto& patch = _Patches.at(_Current_patch_index);
// get<2>(patch)[corner_num] = make_tuple(true, color);
// }
// catch (const out_of_range&) {
// ec = _Cairo_status_t_to_std_error_code(CAIRO_STATUS_INVALID_MESH_CONSTRUCTION);
// return;
// }
// ec.clear();
//}
//
//unsigned int mesh_brush_factory::patch_count() const noexcept {
// return static_cast<unsigned int>(_Patches.size());
//}
//
//path_factory mesh_brush_factory::path_factory(unsigned int patch_num) const {
// if (patch_num >= _Patches.size()) {
// _Throw_if_failed_cairo_status_t(CAIRO_STATUS_INVALID_INDEX);
// }
// const auto& patch = _Patches[patch_num];
// return get<0>(patch);
//}
//
//// Relies on C++17 noexcept guarantee for vector default ctor (N4258, adopted 2014-11).
//path_factory mesh_brush_factory::path_factory(unsigned int patch_num, error_code& ec) const noexcept {
// if (patch_num >= _Patches.size()) {
// ec = _Cairo_status_t_to_std_error_code(CAIRO_STATUS_INVALID_INDEX);
// return ::std::experimental::io2d::path_factory{};
// }
// try {
// const auto& patch = _Patches[patch_num];
// auto factory = get<0>(patch);
// ec.clear();
// return factory;
// }
// catch (const out_of_range&) {
// ec = _Cairo_status_t_to_std_error_code(CAIRO_STATUS_INVALID_MESH_CONSTRUCTION);
// return ::std::experimental::io2d::path_factory{};
// }
// catch (const bad_alloc&) {
// ec = make_error_code(errc::not_enough_memory);
// return ::std::experimental::io2d::path_factory{};
// }
//}
//
//// Note: This returns a bool and uses an out parameter because it's valid to have a control point which has not been assigned a value.
//bool mesh_brush_factory::control_point(unsigned int patch_num, unsigned int point_num, vector_2d& controlPoint) const {
// if (patch_num >= _Patches.size() || point_num > 3) {
// _Throw_if_failed_cairo_status_t(CAIRO_STATUS_INVALID_INDEX);
// }
// const auto& patch = _Patches[patch_num];
// const auto& controlPoints = get<1>(patch);
// const auto& controlPointTuple = controlPoints[point_num];
// if (!get<0>(controlPointTuple)) {
// return false;
// }
// controlPoint = get<1>(controlPointTuple);
// return true;
//}
//
//// Note: This returns a bool and uses an out parameter because it's valid to have a control point which has not been assigned a value.
//bool mesh_brush_factory::control_point(unsigned int patch_num, unsigned int point_num, vector_2d& controlPoint, error_code& ec) const noexcept {
// if (patch_num >= _Patches.size() || point_num > 3) {
// ec = _Cairo_status_t_to_std_error_code(CAIRO_STATUS_INVALID_INDEX);
// return false;
// }
// try {
// const auto& patch = _Patches[patch_num];
// const auto& controlPoints = get<1>(patch);
// const auto& controlPointTuple = controlPoints[point_num];
// if (!get<0>(controlPointTuple)) {
// ec.clear();
// return false;
// }
// controlPoint = get<1>(controlPointTuple);
// ec.clear();
// return true;
// }
// catch (const out_of_range&) {
// ec = _Cairo_status_t_to_std_error_code(CAIRO_STATUS_INVALID_MESH_CONSTRUCTION);
// return false;
// }
//}
//
//// Note: This returns a bool and uses an out parameter because it's valid to have a corner which has not been assigned a color.
//bool mesh_brush_factory::corner_color(unsigned int patch_num, unsigned int corner_num, rgba_color& color) const {
// if (patch_num >= _Patches.size() || corner_num > 3) {
// _Throw_if_failed_cairo_status_t(CAIRO_STATUS_INVALID_INDEX);
// }
// const auto& patch = _Patches[patch_num];
// const auto& cornerColors = get<2>(patch);
// const auto& cornerColorTuple = cornerColors[corner_num];
// if (!get<0>(cornerColorTuple)) {
// return false;
// }
// color = get<1>(cornerColorTuple);
// return true;
//}
//
//// Note: This returns a bool and uses an out parameter because it's valid to have a corner which has not been assigned a color.
//bool mesh_brush_factory::corner_color(unsigned int patch_num, unsigned int corner_num, rgba_color& color, error_code& ec) const noexcept {
// if (patch_num >= _Patches.size() || corner_num > 3) {
// ec = _Cairo_status_t_to_std_error_code(CAIRO_STATUS_INVALID_INDEX);
// return false;
// }
// try {
// const auto& patch = _Patches[patch_num];
// const auto& cornerColors = get<2>(patch);
// const auto& cornerColorTuple = cornerColors[corner_num];
// if (!get<0>(cornerColorTuple)) {
// ec.clear();
// return false;
// }
// color = get<1>(cornerColorTuple);
// ec.clear();
// return true;
// }
// catch (const out_of_range&) {
// ec = _Cairo_status_t_to_std_error_code(CAIRO_STATUS_INVALID_MESH_CONSTRUCTION);
// return false;
// }
//}
|
package com.github.passerr.idea.plugins.spring.web;
import com.github.passerr.idea.plugins.spring.web.po.ApiDocSettingPo;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.options.Configurable;
import com.intellij.openapi.options.SearchableConfigurable;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.Pair;
import com.intellij.ui.TabbedPaneWrapper;
import com.intellij.ui.tabs.JBTabs;
import com.intellij.ui.tabs.TabInfo;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.annotation.Generated;
import javax.swing.JComponent;
import javax.swing.JPanel;
import java.util.List;
import java.util.Objects;
/**
* api文档配置组件
* @author xiehai
* @date 2021/06/30 19:37
* @Copyright(c) tellyes tech. inc. co.,ltd
*/
public class ApiDocConfigurable implements SearchableConfigurable, Configurable.NoScroll {
Disposable disposable;
ApiDocSettingPo source;
ApiDocSettingPo copy;
ApiDocConfigurable() {
this.source = ApiDocStateComponent.getInstance().getState();
assert this.source != null;
this.copy = this.source.deepCopy();
}
@Override
public String getDisplayName() {
return "Api Doc Setting";
}
@Override
public String getHelpTopic() {
return "doc";
}
@Override
public JComponent createComponent() {
this.disposable = Disposer.newDisposable();
TabbedPaneWrapper tabbedPanel = new TabbedPaneWrapper(disposable);
List<Pair<String, JPanel>> panels = ApiDocConfigViews.panels(this.copy);
panels.forEach(it -> tabbedPanel.addTab(it.getFirst(), it.getSecond()));
tabbedPanel.addChangeListener(e -> {
TabInfo selectedInfo = ((JBTabs) e.getSource()).getSelectedInfo();
if (Objects.isNull(selectedInfo)) {
return;
}
// 切换tab自动保存
if (this.isModified()) {
this.apply();
}
String tab = selectedInfo.getText();
panels.stream()
.filter(it -> Objects.equals(it.getFirst(), tab))
.findFirst()
.ifPresent(it -> {
it.getSecond().validate();
it.getSecond().repaint();
});
});
tabbedPanel.setSelectedIndex(0);
return tabbedPanel.getComponent();
}
@Override
public boolean isModified() {
return !Objects.equals(this.source, this.copy);
}
@Override
public void apply() {
this.source.shallowCopy(this.copy);
}
@Override
public void reset() {
this.copy.shallowCopy(this.source);
}
@Generated({})
@Override
public void disposeUIResources() {
if (this.disposable != null) {
Disposer.dispose(this.disposable);
this.disposable = null;
}
}
@NotNull
@Override
public String getId() {
return Objects.requireNonNull(this.getHelpTopic());
}
@Nullable
@Override
public Runnable enableSearch(String option) {
return null;
}
}
|
class Oid:
def __init__(self):
# Constructor for Oid class
pass
def build_config(self, config_path):
# Method to build configuration
pass
def build_bbox(self, dataset_type):
# Method to build bounding boxes for the given dataset type
pass
def build_image(self, dataset_type):
# Method to build images for the given dataset type
pass
def convert_dataset_images(self, dataset_type):
# Method to convert dataset images using OidConv class
conv = OidConv()
conv.convert_images(dataset_type)
# Additional logic for image conversion
pass
class OidConv:
def __init__(self):
# Constructor for OidConv class
pass
def convert_images(self, dataset_type):
# Method to convert images for the given dataset type
pass |
import updatelib
project_dbupgrade = updatelib.dbupgrade.DBUpgradeTools('projectdata', drop=True)
if __name__ == "__main__":
project_dbupgrade.perform_upgrade() |
// Code generated by MockGen. DO NOT EDIT.
// Source: service.go
// Package eth is a generated GoMock package.
package eth
import (
reflect "reflect"
gomock "github.com/golang/mock/gomock"
)
// MockTxGetter is a mock of TxGetter interface.
type MockTxGetter struct {
ctrl *gomock.Controller
recorder *MockTxGetterMockRecorder
}
// MockTxGetterMockRecorder is the mock recorder for MockTxGetter.
type MockTxGetterMockRecorder struct {
mock *MockTxGetter
}
// NewMockTxGetter creates a new mock instance.
func NewMockTxGetter(ctrl *gomock.Controller) *MockTxGetter {
mock := &MockTxGetter{ctrl: ctrl}
mock.recorder = &MockTxGetterMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockTxGetter) EXPECT() *MockTxGetterMockRecorder {
return m.recorder
}
// GetAccountTransactions mocks base method.
func (m *MockTxGetter) GetAccountTransactions(account string) ([]Transaction, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetAccountTransactions", account)
ret0, _ := ret[0].([]Transaction)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// GetAccountTransactions indicates an expected call of GetAccountTransactions.
func (mr *MockTxGetterMockRecorder) GetAccountTransactions(account interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetAccountTransactions", reflect.TypeOf((*MockTxGetter)(nil).GetAccountTransactions), account)
}
|
$(function () {
$("svg").draggable();
});
function make_number(min, max) {
var result = "";
result = Math.round(Math.random() * (max - min) + min);
return result;
}
$("#shape_01").html(
'<path d="M' +
make_number(6, 9) +
" " +
make_number(5, 10) +
" L" +
make_number(5, 10) +
" " +
make_number(15, 25) +
" L" +
make_number(10, 20) +
" " +
make_number(40, 50) +
" L" +
make_number(16, 16) +
" " +
make_number(60, 70) +
" L" +
make_number(16, 16) +
" " +
make_number(85, 95) +
'" />'
);
$("#shape_02").html(
'<path d="M' +
make_number(45, 55) +
" " +
make_number(5, 10) +
" L" +
make_number(75, 85) +
" " +
make_number(10, 20) +
" L" +
make_number(90, 95) +
" " +
make_number(40, 50) +
" L" +
make_number(80, 90) +
" " +
make_number(70, 80) +
" L" +
make_number(60, 70) +
" " +
make_number(85, 95) +
" L" +
make_number(30, 40) +
" " +
make_number(85, 95) +
" L" +
make_number(5, 15) +
" " +
make_number(70, 80) +
" L" +
make_number(5, 15) +
" " +
make_number(40, 50) +
" L" +
make_number(15, 25) +
" " +
make_number(10, 20) +
" Z" +
'" />'
);
$("#shape_03").html(
'<path d="M' +
make_number(6, 16) +
" " +
make_number(5, 10) +
" L" +
make_number(6, 16) +
" " +
make_number(30, 35) +
" L" +
make_number(5, 20) +
" " +
make_number(40, 45) +
" L" +
make_number(5, 20) +
" " +
make_number(50, 60) +
" L" +
make_number(5, 20) +
" " +
make_number(70, 80) +
" L" +
make_number(5, 20) +
" " +
make_number(100, 105) +
" L" +
make_number(5, 20) +
" " +
make_number(115, 120) +
" L" +
make_number(6, 18) +
" " +
make_number(135, 145) +
" L" +
make_number(8, 13) +
" " +
make_number(160, 175) +
" L" +
make_number(9, 11) +
" " +
make_number(180, 220) +
" L" +
make_number(5, 20) +
" " +
make_number(235, 245) +
'" />'
);
$("#shape_04").html(
'<path d="M' +
make_number(5, 10) +
" " +
make_number(5, 10) +
" L" +
make_number(15, 25) +
" " +
make_number(10, 20) +
" L" +
make_number(40, 50) +
" " +
make_number(1, 15) +
" L" +
make_number(60, 70) +
" " +
make_number(10, 20) +
" L" +
make_number(85, 95) +
" " +
make_number(5, 15) +
'" />'
);
$("#shape_05").html(
'<path d="M' +
make_number(90, 95) +
" " +
make_number(5, 10) +
" L" +
make_number(55, 70) +
" " +
make_number(5, 10) +
" L" +
make_number(30, 40) +
" " +
make_number(5, 10) +
" L" +
make_number(5, 10) +
" " +
make_number(15, 30) +
" L" +
make_number(5, 10) +
" " +
make_number(55, 70) +
" L" +
make_number(10, 20) +
" " +
make_number(80, 95) +
" L" +
make_number(40, 50) +
" " +
make_number(85, 95) +
" L" +
make_number(55, 65) +
" " +
make_number(85, 95) +
'" />'
);
$("#shape_06").html(
'<path d="M' +
make_number(60, 70) +
" " +
make_number(5, 10) +
" L" +
make_number(80, 90) +
" " +
make_number(10, 15) +
" L" +
make_number(90, 95) +
" " +
make_number(30, 40) +
" L" +
make_number(90, 95) +
" " +
make_number(60, 65) +
" L" +
make_number(80, 90) +
" " +
make_number(80, 90) +
" L" +
make_number(60, 70) +
" " +
make_number(90, 95) +
" L" +
make_number(15, 25) +
" " +
make_number(85, 95) +
" L" +
make_number(5, 10) +
" " +
make_number(60, 65) +
" L" +
make_number(10, 15) +
" " +
make_number(20, 30) +
'" />'
);
$("#shape_07").html(
'<path d="M' +
make_number(5, 10) +
" " +
make_number(5, 10) +
" L" +
make_number(20, 30) +
" " +
make_number(5, 10) +
" L" +
make_number(40, 50) +
" " +
make_number(7, 13) +
" L" +
make_number(57, 65) +
" " +
make_number(10, 20) +
" L" +
make_number(65, 70) +
" " +
make_number(30, 40) +
" L" +
make_number(65, 70) +
" " +
make_number(60, 70) +
" L" +
make_number(65, 70) +
" " +
make_number(85, 95) +
'" />'
);
$("#shape_01").css({
"-webkit-transform": "rotate(" + make_number(-20, 20) + "deg)",
"transform": "rotate(" + make_number(-20, 20) + "deg)",
});
$("#shape_02").css({
"-webkit-transform": "rotate(" + make_number(0, 360) + "deg)",
"transform": "rotate(" + make_number(0, 360) + "deg)",
});
$("#shape_03").css({
"-webkit-transform": "rotate(" + make_number(-10, 10) + "deg)",
"transform": "rotate(" + make_number(-10, 10) + "deg)",
});
$("#shape_04").css({
"-webkit-transform": "rotate(" + make_number(-30, 30) + "deg)",
"transform": "rotate(" + make_number(-30, 30) + "deg)",
});
$("#shape_05").css({
"-webkit-transform": "rotate(" + make_number(-60, 60) + "deg)",
"transform": "rotate(" + make_number(-60, 60) + "deg)",
});
$("#shape_06").css({
"-webkit-transform": "rotate(" + make_number(-45, 30) + "deg)",
"transform": "rotate(" + make_number(-45, 30) + "deg)",
});
$("#shape_07").css({
"-webkit-transform": "rotate(" + make_number(-30, 30) + "deg)",
"transform": "rotate(" + make_number(-30, 30) + "deg)",
});
/*$("path").css("stroke-width", +make_number(9, 9) + "px");*/
|
<filename>bugzillarest/mocks/es_client_provider.go
// Code generated by mockery v0.0.0-dev. DO NOT EDIT.
package mocks
import (
elastic "github.com/LF-Engineering/dev-analytics-libraries/elastic"
mock "github.com/stretchr/testify/mock"
time "time"
)
// ESClientProvider is an autogenerated mock type for the ESClientProvider type
type ESClientProvider struct {
mock.Mock
}
// Add provides a mock function with given fields: index, documentID, body
func (_m *ESClientProvider) Add(index string, documentID string, body []byte) ([]byte, error) {
ret := _m.Called(index, documentID, body)
var r0 []byte
if rf, ok := ret.Get(0).(func(string, string, []byte) []byte); ok {
r0 = rf(index, documentID, body)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).([]byte)
}
}
var r1 error
if rf, ok := ret.Get(1).(func(string, string, []byte) error); ok {
r1 = rf(index, documentID, body)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// Bulk provides a mock function with given fields: body
func (_m *ESClientProvider) Bulk(body []byte) ([]byte, error) {
ret := _m.Called(body)
var r0 []byte
if rf, ok := ret.Get(0).(func([]byte) []byte); ok {
r0 = rf(body)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).([]byte)
}
}
var r1 error
if rf, ok := ret.Get(1).(func([]byte) error); ok {
r1 = rf(body)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// BulkInsert provides a mock function with given fields: data
func (_m *ESClientProvider) BulkInsert(data []elastic.BulkData) ([]byte, error) {
ret := _m.Called(data)
var r0 []byte
if rf, ok := ret.Get(0).(func([]elastic.BulkData) []byte); ok {
r0 = rf(data)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).([]byte)
}
}
var r1 error
if rf, ok := ret.Get(1).(func([]elastic.BulkData) error); ok {
r1 = rf(data)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// CreateIndex provides a mock function with given fields: index, body
func (_m *ESClientProvider) CreateIndex(index string, body []byte) ([]byte, error) {
ret := _m.Called(index, body)
var r0 []byte
if rf, ok := ret.Get(0).(func(string, []byte) []byte); ok {
r0 = rf(index, body)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).([]byte)
}
}
var r1 error
if rf, ok := ret.Get(1).(func(string, []byte) error); ok {
r1 = rf(index, body)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// DelayOfCreateIndex provides a mock function with given fields: ex, uin, du, index, data
func (_m *ESClientProvider) DelayOfCreateIndex(ex func(string, []byte) ([]byte, error), uin uint, du time.Duration, index string, data []byte) error {
ret := _m.Called(ex, uin, du, index, data)
var r0 error
if rf, ok := ret.Get(0).(func(func(string, []byte) ([]byte, error), uint, time.Duration, string, []byte) error); ok {
r0 = rf(ex, uin, du, index, data)
} else {
r0 = ret.Error(0)
}
return r0
}
// Get provides a mock function with given fields: index, query, result
func (_m *ESClientProvider) Get(index string, query map[string]interface{}, result interface{}) error {
ret := _m.Called(index, query, result)
var r0 error
if rf, ok := ret.Get(0).(func(string, map[string]interface{}, interface{}) error); ok {
r0 = rf(index, query, result)
} else {
r0 = ret.Error(0)
}
return r0
}
// GetStat provides a mock function with given fields: index, field, aggType, mustConditions, mustNotConditions
func (_m *ESClientProvider) GetStat(index string, field string, aggType string, mustConditions []map[string]interface{}, mustNotConditions []map[string]interface{}) (time.Time, error) {
ret := _m.Called(index, field, aggType, mustConditions, mustNotConditions)
var r0 time.Time
if rf, ok := ret.Get(0).(func(string, string, string, []map[string]interface{}, []map[string]interface{}) time.Time); ok {
r0 = rf(index, field, aggType, mustConditions, mustNotConditions)
} else {
r0 = ret.Get(0).(time.Time)
}
var r1 error
if rf, ok := ret.Get(1).(func(string, string, string, []map[string]interface{}, []map[string]interface{}) error); ok {
r1 = rf(index, field, aggType, mustConditions, mustNotConditions)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
|
#!/bin/sh -
#
# Copyright (c) 1991, 1993
# The Regents of the University of California. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. 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.
# 4. Neither the name of the University 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 REGENTS 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 REGENTS 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.
#
# @(#)mkdep.gcc.sh 8.1 (Berkeley) 6/6/93
# $FreeBSD$
D=.depend # default dependency file is .depend
append=0
pflag=
while :
do case "$1" in
# -a appends to the depend file
-a)
append=1
shift ;;
# -f allows you to select a makefile name
-f)
D=$2
shift; shift ;;
# the -p flag produces "program: program.c" style dependencies
# so .o's don't get produced
-p)
pflag=p
shift ;;
*)
break ;;
esac
done
case $# in 0)
echo 'usage: mkdep [-ap] [-f file] [flags] file ...' >&2
exit 1;;
esac
TMP=_mkdep$$
trap 'rm -f $TMP ; trap 2 ; kill -2 $$' 1 2 3 13 15
trap 'rm -f $TMP' 0
# For C sources, mkdep must use exactly the same cpp and predefined flags
# as the compiler would. This is easily arranged by letting the compiler
# pick the cpp. mkdep must be told the cpp to use for exceptional cases.
CC=${CC-"cc"}
MKDEP_CPP=${MKDEP_CPP-"${CC} -E"}
MKDEP_CPP_OPTS=${MKDEP_CPP_OPTS-"-M"};
echo "# $@" > $TMP # store arguments for debugging
if $MKDEP_CPP $MKDEP_CPP_OPTS "$@" >> $TMP; then :
else
echo 'mkdep: compile failed' >&2
exit 1
fi
case x$pflag in
x) case $append in
0) sed -e 's; \./; ;g' < $TMP > $D;;
*) sed -e 's; \./; ;g' < $TMP >> $D;;
esac
;;
*) case $append in
0) sed -e 's;\.o:;:;' -e 's; \./; ;g' < $TMP > $D;;
*) sed -e 's;\.o:;:;' -e 's; \./; ;g' < $TMP >> $D;;
esac
;;
esac
exit $?
|
<gh_stars>0
var namespaceCatch_1_1Matchers_1_1Exception =
[
[ "ExceptionMessageMatcher", "classCatch_1_1Matchers_1_1Exception_1_1ExceptionMessageMatcher.html", "classCatch_1_1Matchers_1_1Exception_1_1ExceptionMessageMatcher" ]
]; |
<reponame>Legend1991/monobanksnake
#ifndef MAPRECOGNIZERTEST_H
#define MAPRECOGNIZERTEST_H
#include <QObject>
#include "pos.h"
#include "map.h"
#include "snake.h"
#include "customsolver.h"
class MapRecognizerTest : public QObject
{
Q_OBJECT
public:
MapRecognizerTest();
void setUp(DirecType init_direc, QList<Pos> init_bodies, QList<PointType> init_types = {
PointType::HEAD_R,
PointType::BODY_HOR,
PointType::BODY_HOR,
PointType::BODY_HOR
});
void clean();
void move();
void compareHead(int headX, int headY);
void compareAfterMove(DirecType targetDirec, int headX, int headY);
DirecType next_direc;
Map *map;
Snake *snake;
CustomSolver *solver;
private slots:
void simpleMovingFromBottomRightCorner();
void movingWithObstaclesFromBottomRightCorner();
void movingWithObstaclesFromBottomRightCorner2();
void movingWithObstaclesFromBottomRightCorner3();
void movingWithObstaclesFromLeftBottomCorner();
void movingWithObstaclesFromLeftBottomCorner1();
void movingWithObstaclesTopRight();
void movingWithObstaclesTopRight1();
void movingWithObstaclesTopRight2();
void movingWithObstaclesTopRight3();
void movingWithObstaclesCenterRight();
void movingWithObstaclesCenterRight2();
void movingWithObstaclesCenterLeft();
void movingWithObstaclesCenterLeft2();
void movingWithObstaclesTopLeft();
void movingWithObstaclesCenter();
// void obstacleRecognition();
// void obstacleRecognition2();
};
#endif // MAPRECOGNIZERTEST_H
|
--- checking the desequilibrate batch ---
select * FROM actb_daily_log lo where lo.batch_no = '1026'
SELECT * FROM getm_liab WHERE id = '91822';
--- --- checking the validated desequilibrate batch --- ---
select*from fbtb_txnlog_master ff where ff.txnactdet='0231720101560102' and ff.txnamtdet='8785000.' --for update
select * from actb_daily_log dd where dd.auth_stat = 'U' and dd.module = 'CG'
select * from actb_history hi where hi.batch_no = '0646'
select * from actb_history where external_ref_no ='FJB1334001918728'and trn_dt ='&date'
select * from actb_history where txn_init_date = '17-july-2012' and lcy_amount = '100000'
acvw_all_ac_entries_fin
--- petite requete perso ---
select ac.brancmh_code,ac.cust_ac_no,ac.ac_desc,ac.ac_open_date,ac.maker_id from sttm_cust_account ac
where ac.date_last_cr not between to_date('&start_date','DD/MM/YYYY') and to_date('&end_date','DD/MM/YYYY')
and ac.account_type in ('U','S') and ac.auth_stat = 'A'
select ac.branch_code, ac.cust_no, ac.cust_ac_no, ac.ac_desc, ac.ac_open_date, ac.alt_ac_no from sttm_cust_account ac
where ac.branch_code='023' order by cust_no, cust_ac_no
select * from sttm_cust_account ac
--- VOIR TOUTES LES SIGNATURES non autorisées
SELECT * FROM svtm_acc_sig_master cc where cc.auth_stat = 'U'
SELECT * FROM svtm_acc_sig_master cc where cc.MAKER_DT_STAMP='&DATE'
SELECT * FROM svtm_acc_sig_det cc where cc.SIG_MSG <> 'A'
select * from svtm_cif_sig_master dd where dd.auth_stat = 'X'
--
select * from sttb_record_log where auth_stat = 'U' order by KEY_ID for update;
----------------------------------------------------------------------------------------------------
-------------------------------------- EOD Checks --------------------------------------------------
select * from aetb_eoc_branches_history where branch_code='042';
--- users release ---
select * from smtb_current_users c where c.current_branch = '031' order by HOME_BRANCH for update
select * from smtb_current_users where user_id ='%JCHOU%'
select * from smtb_user where user_id like 'MC%'
select * from smtb_user
select * from smtb_current_users--for update --where user_id = 'MCA'
--- Branches which are NOT YET completed with EODM ---
SELECT * FROM STTM_BRANCH WHERE BRANCH_CODE NOT IN
( select BRANCH_CODE from sttb_brn_eodm where RUN_DATE='&DATE' ) order by BRANCH_CODE
SELECT * FROM sttm_trncode
-- Host Pending items
select * from eivw_pending_items XA where xa.id = 'SYSTAC'
---- Vérifier si un debug est activé ------
SELECT * FROM cstb_debug_users xa where xa.debug = 'Y'
--- To clear all the login user ---
delete SMTB_CURRENT_USERS where user_id='&user_id'
commit;
CREATE TABLE DAILY_log_01_07_2015 as select * from actb_daily_log a where a.ac_branch='023' and AUTH_STAT='U';
select * from actb_daily_log a where a.ac_branch='024' and AUTH_STAT='U' ---for update;
---------------------------------------------
select * from sttm_trn_code where trn_code='EFB'
select * from gltm_glmaster where gl_code like '37%'
--- ff / VAULT CHECKS --- ---
SELECT * FROM FBTB_TILL_MASTER WHERE BALANCED_IND<>'Y' ORDer by branch_code
SELECT * FROM FBTB_TILL_MASTER WHERE BALANCED_IND<>'Y' AND BRANCH_CODE='021' ORDer by branch_code
SELECT * FROM FBTB_TILL_MASTER WHERE BALANCED_IND='N'
--- Txn Log pending
SELECT * FROM FBTB_TXNLOG_MASTER where TXNSTATUS NOT IN ('COM','DIS','REV','FAL') -- AND BRANCHCODE='002'
AND FUNCTIONID NOT IN ('TVCL','TVQR','EODM','LOCH')
ORDER BY BRANCHCODE --for update
--UPDATE FBTB_TXNLOG_MASTER SET TXNSTATUS='DIS',STAGESTATUS='DIS' WHERE TXNSTATUS NOT IN ('COM','DIS','REV','FAL')
select * from eivw_pending_items cd where cd.MD <> 'MA'
select * from sttb_record_log where auth_stat = 'U'
--- To view Pending WB Teller Transactions ---
select branchcode, FUNCTIONID, b.sub_menu_2, count(*)
from fbtb_txnlog_master f, smtb_function_description b
where f.txnstatus = 'IPR'
and f.functionid not in ('TVCL', 'TVQR', 'EODM')
and b.function_id = F.functionid
and F.POSTINGDATE='&Date'
group by branchcode, FUNCTIONID, b.sub_menu_2
order by BRANCHCODE, F.FUNCTIONID
--- peding trnsaction for user ---
select F.branchcode, C.BRANCH_NAME, FUNCTIONID, b.sub_menu_2, Makerid, ASSIGNEDTO,count(*)
from fbtb_txnlog_master f, smtb_function_description b, STTM_BRANCH C
where f.txnstatus = 'IPR'
and C.BRANCH_CODE = F.branchcode
and f.functionid not in ('TVCL', 'TVQR', 'EODM')
and b.function_id = F.functionid
and F.POSTINGDATE IN ('&DATE')
group by F.branchcode, C.BRANCH_NAME, FUNCTIONID, b.sub_menu_2, Makerid, ASSIGNEDTO
order by F.branchcode, C.BRANCH_NAME, F.FUNCTIONID, Makerid, ASSIGNEDTO
select * from fbtb_txnlog_master where POSTINGDATE in ('30/05/2014') and txnstatus='IPR' and makerid ='QMBAKU'
--- Branches which are NOT YET completed with EODM ---
SELECT * FROM STTM_BRANCH WHERE BRANCH_CODE NOT IN
( select BRANCH_CODE from sttb_brn_eodm where RUN_DATE='&DATE' ) order by BRANCH_CODE
select * from sttb_brn_eodm where RUN_DATE='17-dec-2013' order by BRANCH_CODE
--- Branches which are completed with EODM
select branch_code,currentpostingdate,nextpostingdate from fbtm_branch_info
where currentpostingdate='&DATE'
select * from fbtm_branch_info where branch_code='082' for update
select * from sttm_lcl_holiday where year='2012' /*and branch_code='001'*/ and month=8--082
select * from sttm_dates
select * from sttm_aeod_dates
--- To view Branches ready for EODM run
select branch_code from
(
select branch_code
from sttm_branch
where branch_code not in (SELECT D.BRANCH_CODE
FROM FBTB_TILL_MASTER d
WHERE D.BALANCED_IND = 'N'
GROUP BY D.BRANCH_CODE)
MINUS
select branch_code from sttb_brn_eodm where run_date = '31/05/2012'
)
-- EOD Completed for below
select * from sttb_brn_eodm where run_date = '28-may-2013'
-- Host Pending items
select * from eivw_pending_items XA where xa.id = 'CSUNYIN'
select * from eivw_pending_items XA
-- Branches EOD Stage //run this when some package is Aborted
SELECT * FROM AETB_EOC_BRANCHES WHERE EOC_STATUS<>'C' ORDER BY BRANCH_CODE
SELECT * FROM AETB_EOC_BRANCHES WHERE EOC_STATUS='C' ORDER BY BRANCH_CODE
SELECT * FROM AETB_EOC_BRANCHES WHERE EOC_STATUS<>'C' and TARGET_STAGE='POSTEOFI' ORDER BY BRANCH_CODE
select * from Fbtb_Txnlog_Details where xrefid = 'FJB1334001918728'
select * from FBTB_TXNLOG_MASTER xx
where xx.branchcode='043'
and xx.postingdate='29/05/2012' AND xx.xrefid = 'FJB1214400900751' for update xx.TXNSTATUS='IPR'
select * from FBTB_TILL_MASTER
WHERE BRANCH_CODE='023'
SELECT * FROM FBTM_FUNCT
--- Branches EOD Batches Stage //run this when some package is Aborted
SELECT * FROM AETB_EOC_PROGRAMS WHERE EOC_BATCH_STATUS NOT IN ('C','N') ORDER BY BRANCH_CODE
SELECT * FROM AETB_EOC_PROGRAMS WHERE EOC_BATCH_STATUS IN ('C','N') ORDER BY BRANCH_CODE--cndbatch
select * from ictb_acc_pr where brn='020' and last_calc_dt<>'08/05/2012'
SELECT * FROM AETB_EOC_PROGRAMS where EOC_batch='ICEOD' and eod_date='30-APR-2012' and eoc_batch_status<>'C'
select * from smtb_role_detail
-- EITB
SELECT * FROM EITB_PENDING_PROGRAMS WHERE BRANCH_CODE='010'
-- Branches Status & Date
SELECT A.BRANCH_CODE,A.TODAY,
DECODE(B.End_Of_Input,'N','Txn Input','T','End of Input','F','End of Fin Input','E','EOD Mark','B','BOD',B.End_Of_Input) Status
FROM STTM_DATES A, STTM_BRANCH B
WHERE A.BRANCH_CODE = B.BRANCH_CODE
ORDER BY STATUS, TODAY, A.BRANCH_CODE
-- EOC Run Chart //run this when some package is Aborted
select * FROM AETB_EOC_RUNCHART where EOC_STAGE_STATUS='A';
select * from actb_daily_log dd where dd.external_ref_no = 'FJB1403802037597'
-- SWITCH ON DEBUG
--1 run this first
UPDATE CSTB_PARAM SET PARAM_VAL='Y' WHERE PARAM_NAME='REAL_DEBUG'
--2 run this second
UPDATE CSTB_DEBUG_USERS SET DEBUG='Y' WHERE USER_ID='&User_ID'
--3 run if number of updated rows is 0 on script 2
INSERT INTO CSTB_DEBUG_USERS (SELECT MODULE_ID,'Y','&User_ID' FROM SMTB_MODULES )
-- Verify if Debug is active for any user
SELECT * FROM cstb_debug_users xa where xa.debug = 'Y'
-- SWITCH OFF DEBUG check this every times before start the EOD ---
UPDATE CSTB_DEBUG_USERS SET DEBUG='N' WHERE USER_ID='&User_ID'
UPDATE CSTB_DEBUG_USERS SET DEBUG='N' WHERE debug='Y'
UPDATE CSTB_PARAM SET PARAM_VAL='N' WHERE PARAM_NAME='REAL_DEBUG'
-- After Eod check below tables for date befor go to restart ---
select branch_code,end_of_input from sttm_branch ---end_of_input should be 'N' for all the branch---
select dd.branch_code,dd.currentpostingdate,nextpostingdate from fbtm_branch_info dd -- currentpostingdate should be next bussiness day
select branch_code,today,prev_working_day,next_working_day from sttm_dates order by branch_code
select * from acvw_all_ac_entries ac where ac.LCY_AMOUNT = 74500 and ac.TRN_DT = '02-AUG-2013' and ac.USER_ID = 'INKWAIN'
SELECT * FROM actb_daily_log where user
select * from fbtb_txnlog_details ma where ma.
--- extractions mouvement d'un compte
select ac_branch,ac_no,module,user_id,batch_no,ac_entry_sr_no,period_code,trn_dt,value_dt,lcy_amount,trn_code from ACTB_HISTORY where ac_no='0202820100721430' and module='DE'
SELECT count(*) FROM actb_daily_log;
---- tyraitement ATM ------
-- Update date de generation des fichiers GIMAC---
select * from gitm_interface_definition where external_system ='FLEXSWITCH' for update;
select * from aetb
select * from fbtb_txnlog_master f,
-------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------
------ Adding Account and CIF in payway-------
select * from Custacc_Temp_09oct2015 for UPDATE ---- Account
select * from Cust_Temp for UPDATE ------ CIF
---------------------------------------------------------------------------------------------------------------
SELECT * FROM ACVW_ALL_AC_ENTRIES WHERE TRN_DT BETWEEN '01-JUL-2015' AND '31-DEC-2015' AND MODULE='DE' AND TRN_CODE<>'SAL'
select * from acvw_all_ac_entries WHERE TRN_DT BETWEEN '01-JUL-2015' AND '31-DEC-2015' AND MODULE='DE' AND TRN_CODE<>'SAL'
alter system kill session '2724,30305' ;
ALTER SYSTEM KILL SESSION '2184,3';
select * from dba_objects where status='INVALID';
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.