text stringlengths 1 1.05M |
|---|
#!/bin/bash
# predeploy_tar.sh - Made for Puppi
# Sources common header for Puppi scripts
. $(dirname $0)/header || exit 10
# Show help
showhelp () {
echo "This script unpacks (tar) file from the download dir (storedir) to the predeploydir"
echo "It has the following options:"
echo "\$1 (Required) - Name of the variable that identifies the tar to predeploy"
echo
echo "Examples:"
echo "predeploy_tar.sh tarfile"
}
# Check Arguments
if [ $1 ] ; then
deployfilevar=$1
deployfile="$(eval "echo \${$(echo ${deployfilevar})}")"
else
showhelp
exit 2
fi
# Untar file
untar () {
cd $predeploydir
# file $deployfile | grep gzip 2>&1>/dev/null
# if [ $? == "0"] ; then
tar -zxf $deployfile
# else
# tar -xvf $deployfile
# fi
}
untar
|
#!/bin/sh
set -e
set -u
set -o pipefail
function on_error {
echo "$(realpath -mq "${0}"):$1: error: Unexpected failure"
}
trap 'on_error $LINENO' ERR
if [ -z ${UNLOCALIZED_RESOURCES_FOLDER_PATH+x} ]; then
# If UNLOCALIZED_RESOURCES_FOLDER_PATH is not set, then there's nowhere for us to copy
# resources to, so exit 0 (signalling the script phase was successful).
exit 0
fi
mkdir -p "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}"
RESOURCES_TO_COPY=${PODS_ROOT}/resources-to-copy-${TARGETNAME}.txt
> "$RESOURCES_TO_COPY"
XCASSET_FILES=()
# 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 .*.??????")
case "${TARGETED_DEVICE_FAMILY:-}" in
1,2)
TARGET_DEVICE_ARGS="--target-device ipad --target-device iphone"
;;
1)
TARGET_DEVICE_ARGS="--target-device iphone"
;;
2)
TARGET_DEVICE_ARGS="--target-device ipad"
;;
3)
TARGET_DEVICE_ARGS="--target-device tv"
;;
4)
TARGET_DEVICE_ARGS="--target-device watch"
;;
*)
TARGET_DEVICE_ARGS="--target-device mac"
;;
esac
install_resource()
{
if [[ "$1" = /* ]] ; then
RESOURCE_PATH="$1"
else
RESOURCE_PATH="${PODS_ROOT}/$1"
fi
if [[ ! -e "$RESOURCE_PATH" ]] ; then
cat << EOM
error: Resource "$RESOURCE_PATH" not found. Run 'pod install' to update the copy resources script.
EOM
exit 1
fi
case $RESOURCE_PATH in
*.storyboard)
echo "ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile ${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .storyboard`.storyboardc $RESOURCE_PATH --sdk ${SDKROOT} ${TARGET_DEVICE_ARGS}" || true
ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .storyboard`.storyboardc" "$RESOURCE_PATH" --sdk "${SDKROOT}" ${TARGET_DEVICE_ARGS}
;;
*.xib)
echo "ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile ${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib $RESOURCE_PATH --sdk ${SDKROOT} ${TARGET_DEVICE_ARGS}" || true
ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib" "$RESOURCE_PATH" --sdk "${SDKROOT}" ${TARGET_DEVICE_ARGS}
;;
*.framework)
echo "mkdir -p ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" || true
mkdir -p "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}"
echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" $RESOURCE_PATH ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" || true
rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}"
;;
*.xcdatamodel)
echo "xcrun momc \"$RESOURCE_PATH\" \"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH"`.mom\"" || true
xcrun momc "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcdatamodel`.mom"
;;
*.xcdatamodeld)
echo "xcrun momc \"$RESOURCE_PATH\" \"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcdatamodeld`.momd\"" || true
xcrun momc "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcdatamodeld`.momd"
;;
*.xcmappingmodel)
echo "xcrun mapc \"$RESOURCE_PATH\" \"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcmappingmodel`.cdm\"" || true
xcrun mapc "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcmappingmodel`.cdm"
;;
*.xcassets)
ABSOLUTE_XCASSET_FILE="$RESOURCE_PATH"
XCASSET_FILES+=("$ABSOLUTE_XCASSET_FILE")
;;
*)
echo "$RESOURCE_PATH" || true
echo "$RESOURCE_PATH" >> "$RESOURCES_TO_COPY"
;;
esac
}
if [[ "$CONFIGURATION" == "Debug" ]]; then
install_resource "${PODS_CONFIGURATION_BUILD_DIR}/HomeComponent/HomeComponentLibrary.bundle"
fi
if [[ "$CONFIGURATION" == "Release" ]]; then
install_resource "${PODS_CONFIGURATION_BUILD_DIR}/HomeComponent/HomeComponentLibrary.bundle"
fi
mkdir -p "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}"
rsync -avr --copy-links --no-relative --exclude '*/.svn/*' --files-from="$RESOURCES_TO_COPY" / "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}"
if [[ "${ACTION}" == "install" ]] && [[ "${SKIP_INSTALL}" == "NO" ]]; then
mkdir -p "${INSTALL_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}"
rsync -avr --copy-links --no-relative --exclude '*/.svn/*' --files-from="$RESOURCES_TO_COPY" / "${INSTALL_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}"
fi
rm -f "$RESOURCES_TO_COPY"
if [[ -n "${WRAPPER_EXTENSION}" ]] && [ "`xcrun --find actool`" ] && [ -n "${XCASSET_FILES:-}" ]
then
# Find all other xcassets (this unfortunately includes those of path pods and other targets).
OTHER_XCASSETS=$(find -L "$PWD" -iname "*.xcassets" -type d)
while read line; do
if [[ $line != "${PODS_ROOT}*" ]]; then
XCASSET_FILES+=("$line")
fi
done <<<"$OTHER_XCASSETS"
if [ -z ${ASSETCATALOG_COMPILER_APPICON_NAME+x} ]; then
printf "%s\0" "${XCASSET_FILES[@]}" | xargs -0 xcrun actool --output-format human-readable-text --notices --warnings --platform "${PLATFORM_NAME}" --minimum-deployment-target "${!DEPLOYMENT_TARGET_SETTING_NAME}" ${TARGET_DEVICE_ARGS} --compress-pngs --compile "${BUILT_PRODUCTS_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}"
else
printf "%s\0" "${XCASSET_FILES[@]}" | xargs -0 xcrun actool --output-format human-readable-text --notices --warnings --platform "${PLATFORM_NAME}" --minimum-deployment-target "${!DEPLOYMENT_TARGET_SETTING_NAME}" ${TARGET_DEVICE_ARGS} --compress-pngs --compile "${BUILT_PRODUCTS_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" --app-icon "${ASSETCATALOG_COMPILER_APPICON_NAME}" --output-partial-info-plist "${TARGET_TEMP_DIR}/assetcatalog_generated_info_cocoapods.plist"
fi
fi
|
#!/bin/ksh -p
#
# CDDL HEADER START
#
# The contents of this file are subject to the terms of the
# Common Development and Distribution License (the "License").
# You may not use this file except in compliance with the License.
#
# You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
# or http://www.opensolaris.org/os/licensing.
# See the License for the specific language governing permissions
# and limitations under the License.
#
# When distributing Covered Code, include this CDDL HEADER in each
# file and include the License file at usr/src/OPENSOLARIS.LICENSE.
# If applicable, add the following below this CDDL HEADER, with the
# fields enclosed by brackets "[]" replaced with your own identifying
# information: Portions Copyright [yyyy] [name of copyright owner]
#
# CDDL HEADER END
#
#
# Copyright 2010 Sun Microsystems, Inc. All rights reserved.
#
#
# ID: smbmount_001
#
# DESCRIPTION:
# Verify mount smbfs can mount the public share
#
# STRATEGY:
# 1. run "mount -F smbfs /server/public /export/mnt"
# 2. mount can get the right message
#
. $STF_SUITE/include/libtest.ksh
tc_id="smbmount001"
tc_desc="Verify smbmount can mount public share"
print_test_case $tc_id - $tc_desc
if [[ $STC_CIFS_CLIENT_DEBUG == 1 ]] || \
[[ *:${STC_CIFS_CLIENT_DEBUG}:* == *:$tc_id:* ]]; then
set -x
fi
server=$(server_name) || return
testdir_init $TDIR
smbmount_clean $TMNT
smbmount_init $TMNT
cmd="mount -F smbfs -o noprompt //$TUSER:$TPASS@$server/public $TMNT"
cti_execute -i '' FAIL $cmd
if [[ $? != 0 ]]; then
cti_fail "FAIL: smbmount can't mount the public share"
return
else
cti_report "PASS: smbmount can mount the public share"
fi
smbmount_check $TMNT || return
cmd="umount $TMNT"
cti_execute_cmd $cmd
if [[ $? != 0 ]]; then
cti_fail "FAIL: umount the $TMNT failed"
return
else
cti_report "PASS: mount the $TMNT successfully"
fi
smbmount_clean $TMNT
cti_pass "${tc_id}: PASS"
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.smartloli.kafka.eagle.web.service.impl;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.smartloli.kafka.eagle.common.protocol.KpiInfo;
import org.smartloli.kafka.eagle.common.protocol.bscreen.BScreenBarInfo;
import org.smartloli.kafka.eagle.common.protocol.bscreen.BScreenConsumerInfo;
import org.smartloli.kafka.eagle.common.util.CalendarUtils;
import org.smartloli.kafka.eagle.common.util.KConstants.CollectorType;
import org.smartloli.kafka.eagle.common.util.KConstants.MBean;
import org.smartloli.kafka.eagle.common.util.StrUtils;
import org.smartloli.kafka.eagle.core.factory.v2.BrokerFactory;
import org.smartloli.kafka.eagle.core.factory.v2.BrokerService;
import org.smartloli.kafka.eagle.web.dao.MBeanDao;
import org.smartloli.kafka.eagle.web.dao.TopicDao;
import org.smartloli.kafka.eagle.web.service.BScreenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
/**
* Big screen get data.
*
* @author smartloli.
*
* Created by Aug 29, 2019
*/
@Service
public class BScreenServiceImpl implements BScreenService {
@Autowired
private TopicDao topicDao;
@Autowired
private MBeanDao mbeanDao;
/** Broker service interface. */
private static BrokerService brokerService = new BrokerFactory().create();
/** Get producer and consumer real rate data . */
public String getProducerAndConsumerRate(String clusterAlias) {
List<KpiInfo> byteIns = getBrokersKpi(clusterAlias, MBean.BYTEIN);
List<KpiInfo> byteOuts = getBrokersKpi(clusterAlias, MBean.BYTEOUT);
long ins = 0L;
for (KpiInfo kpi : byteIns) {
try {
ins += Long.parseLong(kpi.getValue());
} catch (Exception e) {
e.printStackTrace();
}
}
long outs = 0L;
for (KpiInfo kpi : byteOuts) {
try {
outs += Long.parseLong(kpi.getValue());
} catch (Exception e) {
e.printStackTrace();
}
}
JSONObject object = new JSONObject();
object.put("ins", StrUtils.stringify(ins));
object.put("outs", StrUtils.stringify(outs));
return object.toJSONString();
}
private List<KpiInfo> getBrokersKpi(String clusterAlias, String key) {
Map<String, Object> param = new HashMap<>();
param.put("cluster", clusterAlias);
param.put("stime", CalendarUtils.getDate());
param.put("etime", CalendarUtils.getDate());
param.put("type", CollectorType.KAFKA);
param.put("key", key);
param.put("size", brokerService.brokerNumbers(clusterAlias));
return mbeanDao.getBrokersKpi(param);
}
/** Get topic total logsize data . */
public String getTopicTotalLogSize(String clusterAlias) {
Map<String, Object> params = new HashMap<>();
params.put("cluster", clusterAlias);
params.put("topics", brokerService.topicList(clusterAlias));
params.put("size", brokerService.topicList(clusterAlias).size());
params.put("tday", CalendarUtils.getCustomDate("yyyyMMdd"));
long totalRecords = topicDao.getBScreenTotalRecords(params);
JSONObject object = new JSONObject();
object.put("total", totalRecords);
return object.toJSONString();
}
/** Get producer and consumer history data. */
public String getProducerOrConsumerHistory(String clusterAlias, String type) {
JSONArray array = new JSONArray();
Map<String, Object> params = new HashMap<String, Object>();
params.put("cluster", clusterAlias);
params.put("stime", CalendarUtils.getCustomLastDay(7));
params.put("etime", CalendarUtils.getCustomDate("yyyyMMdd"));
if ("producer".equals(type)) {
List<BScreenBarInfo> bsProducers = topicDao.queryProducerHistoryBar(params);
Map<String, Object> bsMaps = new HashMap<>();
for (BScreenBarInfo bsProducer : bsProducers) {
if (bsProducer != null) {
bsMaps.put(bsProducer.getTm(), bsProducer.getValue());
}
}
for (int i = 6; i >= 0; i--) {
String tm = CalendarUtils.getCustomLastDay(i);
if (bsMaps.containsKey(tm)) {
JSONObject object = new JSONObject();
object.put("x", CalendarUtils.getCustomLastDay("MM-dd", i));
object.put("y", bsMaps.get(tm).toString());
array.add(object);
} else {
JSONObject object = new JSONObject();
object.put("x", CalendarUtils.getCustomLastDay("MM-dd", i));
object.put("y", 0);
array.add(object);
}
}
} else {
List<BScreenBarInfo> bsConsumers = topicDao.queryConsumerHistoryBar(params);
Map<String, Object> bsMaps = new HashMap<>();
for (BScreenBarInfo bsConsumer : bsConsumers) {
if (bsConsumer != null) {
bsMaps.put(bsConsumer.getTm(), bsConsumer.getValue());
}
}
for (int i = 6; i >= 0; i--) {
String tm = CalendarUtils.getCustomLastDay(i);
if (bsMaps.containsKey(tm)) {
JSONObject object = new JSONObject();
object.put("x", CalendarUtils.getCustomLastDay("MM-dd", i));
object.put("y", bsMaps.get(tm).toString());
array.add(object);
} else {
JSONObject object = new JSONObject();
object.put("x", CalendarUtils.getCustomLastDay("MM-dd", i));
object.put("y", 0);
array.add(object);
}
}
}
return array.toJSONString();
}
@Override
public String getTodayOrHistoryConsumerProducer(String clusterAlias, String type) {
JSONObject object = new JSONObject();
if ("producers".equals(type)) {
List<Long> producers = new ArrayList<Long>();
Map<String, Object> params = new HashMap<>();
params.put("cluster", clusterAlias);
params.put("tday", CalendarUtils.getCustomDate("yyyyMMdd"));
List<BScreenConsumerInfo> bscreenConsumers = topicDao.queryTodayBScreenConsumer(params);
Map<String, List<Long>> producerKeys = new HashMap<>();
for (int i = 0; i < 24; i++) {
if (i < 10) {
producerKeys.put("0" + i, new ArrayList<>());
} else {
producerKeys.put(i + "", new ArrayList<>());
}
}
for (BScreenConsumerInfo bscreenConsumer : bscreenConsumers) {
String key = CalendarUtils.convertUnixTime(bscreenConsumer.getTimespan(), "HH");
if (producerKeys.containsKey(key)) {
producerKeys.get(key).add(bscreenConsumer.getDifflogsize());
}
}
for (Entry<String, List<Long>> entry : producerKeys.entrySet()) {
long sum = 0L;
for (Long logsize : entry.getValue()) {
sum += logsize;
}
producers.add(sum);
}
object.put("producers", producers);
} else if ("consumers".equals(type)) {
List<Long> consumers = new ArrayList<Long>();
Map<String, Object> params = new HashMap<>();
params.put("cluster", clusterAlias);
params.put("tday", CalendarUtils.getCustomDate("yyyyMMdd"));
List<BScreenConsumerInfo> bscreenConsumers = topicDao.queryTodayBScreenConsumer(params);
Map<String, List<Long>> consumerKeys = new HashMap<>();
for (int i = 0; i < 24; i++) {
if (i < 10) {
consumerKeys.put("0" + i, new ArrayList<>());
} else {
consumerKeys.put(i + "", new ArrayList<>());
}
}
for (BScreenConsumerInfo bscreenConsumer : bscreenConsumers) {
String key = CalendarUtils.convertUnixTime(bscreenConsumer.getTimespan(), "HH");
if (consumerKeys.containsKey(key)) {
consumerKeys.get(key).add(bscreenConsumer.getDiffoffsets());
}
}
for (Entry<String, List<Long>> entry : consumerKeys.entrySet()) {
long sum = 0L;
for (Long offsets : entry.getValue()) {
sum += offsets;
}
consumers.add(sum);
}
object.put("consumers", consumers);
} else if ("lag".equals(type)) {
Map<String, Object> params = new HashMap<>();
params.put("cluster", clusterAlias);
params.put("tday", CalendarUtils.getCustomDate("yyyyMMdd"));
List<BScreenConsumerInfo> bscreenConsumers = topicDao.queryTodayBScreenConsumer(params);
List<Long> lags = new ArrayList<Long>();
Map<String, List<Long>> keys = new HashMap<>();
for (int i = 0; i < 24; i++) {
if (i < 10) {
keys.put("0" + i, new ArrayList<>());
} else {
keys.put(i + "", new ArrayList<>());
}
}
for (BScreenConsumerInfo bscreenConsumer : bscreenConsumers) {
String key = CalendarUtils.convertUnixTime(bscreenConsumer.getTimespan(), "HH");
if (keys.containsKey(key)) {
keys.get(key).add(bscreenConsumer.getLag());
}
}
for (Entry<String, List<Long>> entry : keys.entrySet()) {
long sum = 0L;
for (Long lag : entry.getValue()) {
sum += lag;
}
lags.add(sum);
}
object.put("lags", lags);
}
return object.toJSONString();
}
}
|
#!/bin/bash
yum groupinstall -y "PHP Support"
yum install -y php-mysql
yum install -y nginx
yum install -y php-fpm
|
#!/usr/bin/env bash
#
# Run GNA several times: fit JUNO model with different options to estimate NMO sensitivity
#
# Estimate the number of processors, may be changed manually
nproc=$(nproc)
# Running mode
mode=${1:-echo}; shift
force=${1:-0}
echo Run mode: $mode
# Define the output directory
outputdir=output/2020.01.13_sensitivity_nmo
mkdir -p $outputdir 2>/dev/null
echo Save output data to $outputdir
# Define global variables and helper functions
iteration=00
function join_by { local IFS="$1"; shift; echo "$*"; }
# The main functions
function run(){
info=$1; shift
# Make filename
suffix=$(join_by _ $iteration $1); shift
file_output=$outputdir/$suffix".out"
file_err=$outputdir/$suffix".out"
file_result=$outputdir/$suffix".yaml"
# Get arguments
oscprob=$1; shift
energy=$1
# Update counter
iteration=$(printf "%02d" $(($iteration+1)))
# Dump stuff
echo Suffix: $suffix
echo Iteration: $iteration
echo Oscprob: $oscprob
echo Energy: $energy
echo $file_output
echo $file_err
echo $file_result
echo
covpars=""
command="
./gna \
-- exp --ns juno juno_sensitivity_v01 -vv \
--energy-model $energy \
--eres-npe 1200 \
--free osc \
--oscprob $oscprob \
--dm ee \
-- snapshot juno/AD1 juno/asimov_no \
-- ns --value juno.pmns.Alpha inverted \
-- ns -n juno.pmns --print \
-- spectrum -p juno/AD1 -l 'IO (model)' \
-p juno/asimov_no -l 'NO (Asimov)' \
--plot-type hist --scale --grid -o $outputdir/$suffix'_spectra.pdf' \
-- dataset --name juno_hier --asimov-data juno/AD1 juno/asimov_no \
-- analysis --name juno_hier --datasets juno_hier \
$covpars
-- chi2 stats-chi2 juno_hier \
-- graphviz juno/asimov_no -o $outputdir/$suffix"_graph.dot" \
-- minimizer min minuit stats-chi2 juno.pmns \
-- fit min -sp -o $file_result \
-a label '$info' \
>$file_output 2>$file_err
"
if test -f $file_result -a $force -ne 1
then
echo $command | sed 's/ -- / \\\n -- /g'
echo
echo File exists, skipping!
echo
return
fi
case $mode in
echo)
echo $command | sed 's/ -- / \\\n -- /g'
;;
run)
eval $command
;;
sem)
sem -j$nproc $command
;;
*)
echo Invalid execution mode $mode
exit
;;
esac
}
run "Default" vac_eres vacuum "eres"
run "Multieres" vac_meres vacuum "multieres --subdetectors-number 5 --multieres concat"
run "Multieres (sum)" vac_meres_sum vacuum "multieres --subdetectors-number 5 --multieres sum"
run "Multieres (sum 200)" vac_meres_sum200 vacuum "multieres --subdetectors-number 200 --multieres sum"
run "+LSNL" vac_lsnl_eres vacuum "lsnl eres"
run "Meres+LSNL" vac_lsnl_meres vacuum "lsnl multieres --subdetectors-number 5 --multieres concat"
run "Meres+LSNL, matter" mat_lsnl_meres matter "lsnl multieres --subdetectors-number 5 --multieres concat"
echo Wating to finish...
parallel --wait
echo
echo Done!
|
class GroceryList {
constructor() {
this.items = [];
}
addItem(name, quantity) {
this.items.push({name, quantity});
}
removeItem(name) {
this.items = this.items.filter(item => item.name !== name);
}
} |
package net.runelite.api.events;
import lombok.Data;
import net.runelite.api.Actor;
/**
* @author Kris | 07/01/2022
*/
@Data
public class CombatLevelChangeEvent {
private final Actor actor;
private final int oldCombatLevel;
private final int newCombatLevel;
}
|
import Login from './Login'
import { shallow } from 'enzyme'
import React from 'react'
it('renders correctly', () => {
const wrapper = shallow(<Login />)
expect(wrapper).toMatchSnapshot()
})
it('renders correctly with mobile redirect', () => {
const url = 'some.url'
const wrapper = shallow(<Login downloadAppUrl={url} location={{ search: '' }} />)
expect(wrapper).toMatchSnapshot()
})
|
import { Card, Spacer, Text } from '@nextui-org/react';
const Feature = ({ tag, title, desc }) => {
return (
<Card color="primary" css={{ padding: '.5rem' }}>
<Text h6 size={14} color="$blue200">
{tag}
</Text>
<Text h5 size={24} color="white">
{title}
</Text>
<Spacer y={1} />
<Text h6 size={18} color="$blue100" css={{ lineHeight: '120%' }}>
{desc}
</Text>
</Card>
);
};
export default Feature;
|
TERMUX_PKG_HOMEPAGE=http://www.capstone-engine.org/
TERMUX_PKG_DESCRIPTION="Lightweight multi-platform, multi-architecture disassembly framework"
TERMUX_PKG_LICENSE="BSD"
TERMUX_PKG_MAINTAINER="@termux"
TERMUX_PKG_VERSION=4.0.2
TERMUX_PKG_REVISION=1
TERMUX_PKG_SRCURL=https://github.com/aquynh/capstone/archive/$TERMUX_PKG_VERSION.tar.gz
TERMUX_PKG_SHA256=7c81d798022f81e7507f1a60d6817f63aa76e489aa4e7055255f21a22f5e526a
TERMUX_PKG_AUTO_UPDATE=true
TERMUX_PKG_BREAKS="capstone-dev"
TERMUX_PKG_REPLACES="capstone-dev"
TERMUX_PKG_EXTRA_CONFIGURE_ARGS="-DINSTALL_LIB_DIR=$TERMUX_PREFIX/lib"
|
#!/bin/bash
# The Python script accepts CONSOLE_VERSION and DEVELOPMENT env variables
TAG="${1:-master}"
if [[ -z "${DEVELOPMENT}" ]]; then
dest=../../deploy/olm-catalog/next
dest_file=${2:-$dest/ember-csi-operator.vX.Y.Z.clusterserviceversion.yaml}
mkdir -p $dest
else
dest_file=./out.yaml
fi
podman pull quay.io/embercsi/ember-csi:$TAG
echo "Getting driver config from tag $TAG and writing result to $dest_file"
podman run --rm quay.io/embercsi/ember-csi:$TAG ember-list-drivers -d | python ./yaml-options-gen.py > $dest_file
|
class PostSerializer(serializers.ModelSerializer):
class Meta:
model = Post
fields = ['title', 'content', 'author'] |
def sort_list(numbers):
return sorted(numbers) |
#!/bin/sh
CC="../../kcc -x"
if [ "$CC" = "" ]; then
exit 1
fi
do_test() {
TARGET=$1
EXPECT=`basename ${TARGET%.*}`.expect
if [ ! -f $EXPECT ]; then
gcc $TARGET -o expect.exe > /dev/null 2>&1
./expect.exe > $EXPECT
echo Result:$?>> $EXPECT
fi
echo "#include <stdio.h>" > code.c
echo "#include <stdlib.h>" >> code.c
cat $TARGET >> code.c
$CC -x code.c > result.txt
echo Result:$?>> result.txt
diff --strip-trailing-cr $EXPECT result.txt > /dev/null 2>&1
if [ $? -eq 1 ]; then
echo Error: $TARGET
# diff $EXPECT result.txt
rm -f $EXPECT
else
echo Test Passed: $TARGET
fi
}
pushd `dirname $0`
do_test abstract-declaration.c
do_test address-deref-offset.c
# do_test anonymous-members.c
do_test anonymous-struct.c
do_test array-decay.c
do_test array-nested-init.c
do_test array-param.c
do_test array-registers.c
do_test array-reverse-index.c
do_test array-zero-length.c
do_test array.c
do_test assign-deref-float.c
do_test assignment-type.c
# do_test bitfield-basic.c
# do_test bitfield-extend.c
# do_test bitfield-immediate-assign.c
# do_test bitfield-initialize-zero.c
# do_test bitfield-load.c
do_test bitfield-mask.c
# do_test bitfield-packing.c
do_test bitfield-reset-align.c
# do_test bitfield-trailing-zero.c
# do_test bitfield-types-init.c
# do_test bitfield-types.c
do_test bitfield-unsigned-promote.c
# do_test bitfield.c
do_test bitwise-complement.c
do_test bitwise-constant.c
# do_test bitwise-expression.c
do_test bitwise-sign-extend.c
do_test byte-load.c
do_test cast-float-union.c
do_test cast-float.c
do_test cast-function-args.c
do_test cast-immediate-truncate.c
do_test cast.c
do_test comma-side-effects.c
# do_test comment.c
do_test compare.c
do_test compound-assignment-basic.c
do_test conditional-basic.c
do_test conditional-constant.c
do_test conditional-void.c
do_test conditional.c
do_test constant-address-index.c
do_test constant-expression.c
do_test constant-integer-type.c
do_test convert-assign-immediate.c
do_test convert-float-double.c
# do_test convert-float-int.c
# do_test convert-float-unsigned.c
do_test convert-int-float.c
# do_test convert-unsigned-float.c
do_test copy-struct.c
do_test declaration-default-int.c
do_test declarator-complex.c
do_test declarator-parens.c
do_test declare-auto-func.c
do_test deref-address-offset.c
do_test deref-array.c
# do_test deref-compare-float.c
do_test deref-deep.c
do_test deref-store.c
do_test deref.c
do_test dereference-extern.c
do_test directive-number.c
do_test do-continue.c
do_test do-while.c
do_test duffs-device.c
do_test enum.c
do_test exit.c
do_test expression-div-mod.c
do_test expression.c
do_test fact.c
# do_test float-arithmetic.c
do_test float-branch.c
do_test float-compare-equal.c
do_test float-compare-nan.c
do_test float-compare.c
do_test float-function.c
do_test float-load-deref.c
do_test for-empty-expr.c
do_test for.c
do_test function-char-args.c
# do_test function-implicit-declare.c
do_test function-incomplete.c
do_test function-pointer-call.c
do_test function-pointer.c
# do_test function.c
do_test goto.c
do_test hello.c
do_test identifier.c
do_test immediate-branch.c
do_test immediate-expr.c
# do_test immediate-pointer.c
do_test include.c
do_test increment.c
do_test initialize-address.c
do_test initialize-array.c
do_test initialize-float.c
do_test initialize-id.c
# do_test initialize-null.c
do_test initialize-string.c
do_test initialize-union.c
# do_test initialize.c
# do_test integer-suffix.c
# do_test ldouble-load-direct.c
# do_test line-continuation.c
# do_test line-directive.c
do_test linebreak.c
do_test liveness-deref-assign.c
do_test liveness-global.c
do_test liveness-loop.c
do_test liveness-pointer.c
do_test logical-and-bitwise-false.c
do_test logical-operators-basic.c
# do_test long-double-arithmetic.c
# do_test long-double-compare.c
# do_test long-double-function.c
# do_test long-double-load.c
# do_test long-double-struct.c
# do_test long-double-union.c
do_test macro-empty-arg.c
do_test macro-function-paren.c
do_test macro-keyword-define.c
do_test macro-name-arg.c
do_test macro-param-space.c
do_test macro-paste.c
do_test macro-predefined.c
do_test macro-recursive.c
do_test macro-refill-expand.c
do_test macro-repeat-expand.c
do_test macro-skip-expand.c
# do_test macro.c
do_test main.c
do_test negate.c
do_test nested-macro.c
# do_test offsetof.c
# do_test old-param-decay.c
do_test old-style-declaration.c
do_test old-style-definition.c
do_test padded-initialization.c
do_test params-mixed.c
do_test params-system-v.c
do_test partial-initialization.c
do_test pointer-diff.c
# do_test pointer.c
do_test preprocess-expression.c
do_test preprocess.c
do_test preprocessor-expression.c
# do_test printstr.c
do_test promote-unsigned.c
do_test prototype-scope-enum.c
do_test ptrdiff.c
do_test qualifier-repeat.c
do_test register-param.c
# do_test return-bitfield.c
do_test return-compare-int.c
do_test return-float-struct.c
do_test return-partial-register.c
do_test return-point.c
do_test return-struct-basic.c
do_test return-struct-integers.c
do_test return-struct-mem.c
do_test self-referential-struct.c
do_test shift-assign.c
# do_test shift.c
do_test short-circuit-comma.c
do_test short-circuit.c
do_test shortcircuit-loop.c
do_test signed-division.c
# do_test sizeof.c
do_test string-addr.c
do_test string-concat.c
do_test string-escape.c
do_test string-index.c
do_test string-length.c
# do_test stringify.c
do_test strings.c
# do_test struct-alignment.c
do_test struct-assign.c
do_test struct-comma-call.c
do_test struct-eightbyte-write.c
do_test struct-init-swap.c
# do_test struct-padding.c
do_test struct.c
do_test switch-basic.c
do_test switch-nested.c
do_test tag.c
do_test tail-compare-jump.c
do_test token.c
do_test tokenize-partial-keyword.c
# do_test trigraph.c
# do_test typedef-function.c
do_test typedef.c
do_test unary-minus-float.c
# do_test unary-plus.c
do_test union-bitfield.c
do_test union-float-assign.c
do_test union-float-param.c
do_test union-zero-init.c
# do_test union.c
do_test unsigned-compare-ge.c
do_test unsigned-compare.c
do_test unsigned-sign-extend.c
do_test vararg-complex-1.c
# do_test vararg-complex-2.c
do_test vararg-deref-arg.c
do_test vararg-deref.c
do_test vararg-float.c
do_test vararg-param.c
do_test vararg.c
do_test void-statement.c
do_test whitespace.c
do_test zero-init.c
popd
exit 0
:ERROR_LIST
pushd `dirname $0`
do_test anonymous-members.c
do_test bitfield-basic.c
do_test bitfield-extend.c
do_test bitfield-immediate-assign.c
do_test bitfield-initialize-zero.c
do_test bitfield-load.c
do_test bitfield-packing.c
do_test bitfield-trailing-zero.c
do_test bitfield-types-init.c
do_test bitfield-types.c
do_test bitfield.c
do_test bitwise-expression.c
do_test comment.c
do_test convert-float-int.c
do_test convert-float-unsigned.c
do_test convert-unsigned-float.c
do_test deref-compare-float.c
do_test float-arithmetic.c
do_test function-implicit-declare.c
do_test function.c
do_test immediate-pointer.c
do_test initialize-null.c
do_test initialize.c
do_test integer-suffix.c
do_test ldouble-load-direct.c
do_test line-continuation.c
do_test line-directive.c
do_test long-double-arithmetic.c
do_test long-double-compare.c
do_test long-double-function.c
do_test long-double-load.c
do_test long-double-struct.c
do_test long-double-union.c
do_test macro.c
do_test offsetof.c
do_test old-param-decay.c
do_test pointer.c
do_test printstr.c
do_test return-bitfield.c
do_test shift.c
do_test sizeof.c
do_test stringify.c
do_test struct-alignment.c
do_test struct-padding.c
do_test trigraph.c
do_test typedef-function.c
do_test unary-plus.c
do_test union.c
do_test vararg-complex-2.c
popd
exit 0
|
#!/bin/sh
# Copyright (c) 2014-2015 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
set -e
ROOTDIR=dist
BUNDLE="${ROOTDIR}/Qcoin-Qt.app"
CODESIGN=codesign
TEMPDIR=sign.temp
TEMPLIST=${TEMPDIR}/signatures.txt
OUT=signature-osx.tar.gz
OUTROOT=osx
if [ ! -n "$1" ]; then
echo "usage: $0 <codesign args>"
echo "example: $0 -s MyIdentity"
exit 1
fi
rm -rf ${TEMPDIR} ${TEMPLIST}
mkdir -p ${TEMPDIR}
${CODESIGN} -f --file-list ${TEMPLIST} "$@" "${BUNDLE}"
grep -v CodeResources < "${TEMPLIST}" | while read i; do
TARGETFILE="${BUNDLE}/`echo "${i}" | sed "s|.*${BUNDLE}/||"`"
SIZE=`pagestuff "$i" -p | tail -2 | grep size | sed 's/[^0-9]*//g'`
OFFSET=`pagestuff "$i" -p | tail -2 | grep offset | sed 's/[^0-9]*//g'`
SIGNFILE="${TEMPDIR}/${OUTROOT}/${TARGETFILE}.sign"
DIRNAME="`dirname "${SIGNFILE}"`"
mkdir -p "${DIRNAME}"
echo "Adding detached signature for: ${TARGETFILE}. Size: ${SIZE}. Offset: ${OFFSET}"
dd if="$i" of="${SIGNFILE}" bs=1 skip=${OFFSET} count=${SIZE} 2>/dev/null
done
grep CodeResources < "${TEMPLIST}" | while read i; do
TARGETFILE="${BUNDLE}/`echo "${i}" | sed "s|.*${BUNDLE}/||"`"
RESOURCE="${TEMPDIR}/${OUTROOT}/${TARGETFILE}"
DIRNAME="`dirname "${RESOURCE}"`"
mkdir -p "${DIRNAME}"
echo "Adding resource for: \"${TARGETFILE}\""
cp "${i}" "${RESOURCE}"
done
rm ${TEMPLIST}
tar -C "${TEMPDIR}" -czf "${OUT}" .
rm -rf "${TEMPDIR}"
echo "Created ${OUT}"
|
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
// THIS IS A GENERATED FILE. DO NOT MODIFY MANUALLY. @see scripts/compile-icons.js
import * as React from 'react';
interface SVGRProps {
title?: string;
titleId?: string;
}
const EuiIconAppWatches = ({
title,
titleId,
...props
}: React.SVGProps<SVGSVGElement> & SVGRProps) => (
<svg
xmlns="http://www.w3.org/2000/svg"
width={32}
height={32}
viewBox="0 0 32 32"
aria-labelledby={titleId}
{...props}
>
{title ? <title id={titleId}>{title}</title> : null}
<path d="M9.74 7.73l-1.5-1.32a13 13 0 000 17.19l1.5-1.32a11 11 0 010-14.54v-.01z" />
<path d="M6.51 3.66L5 2.34c-6.377 7.24-6.377 18.09 0 25.33l1.5-1.32C.792 19.867.792 10.153 6.5 3.67l.01-.01zm17.25 2.75l-1.5 1.32a11 11 0 010 14.54l1.5 1.32a13 13 0 000-17.19v.01z" />
<path d="M27 2.34l-1.5 1.32c5.708 6.483 5.708 16.197 0 22.68l1.5 1.33c6.377-7.24 6.377-18.09 0-25.33z" />
<path
className="euiIcon__fillSecondary"
d="M21 15a5 5 0 10-6 4.9V31h2V19.9a5 5 0 004-4.9zm-5 3a3 3 0 110-6 3 3 0 010 6z"
/>
</svg>
);
export const icon = EuiIconAppWatches;
|
package com.alibaba.sreworks.cmdb.common;
import com.alibaba.sreworks.cmdb.common.exception.*;
import com.alibaba.tesla.common.base.TeslaBaseResult;
import com.alibaba.tesla.common.base.TeslaResultFactory;
import com.alibaba.tesla.common.base.constant.TeslaStatusCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import static com.alibaba.sreworks.cmdb.common.CmdbCodeEnum.*;
@Slf4j
@ControllerAdvice
public class CmdbExceptionHandler {
@ExceptionHandler(HttpMessageNotReadableException.class)
@ResponseBody
public TeslaBaseResult httpMessageNotReadableException(HttpMessageNotReadableException e) {
return TeslaResultFactory.buildResult(TeslaStatusCode.USER_ARG_ERROR, e.getMessage(), "");
}
@ExceptionHandler(IllegalArgumentException.class)
@ResponseBody
public TeslaBaseResult illegalArgumentException(IllegalArgumentException e) {
log.error("Cmdb Illegal Argument Exception Occurred:", e);
return TeslaResultFactory.buildResult(TeslaStatusCode.USER_ARG_ERROR, e.getMessage(), "");
}
@ExceptionHandler(DomainException.class)
@ResponseBody
public TeslaBaseResult domainException(DomainException e) {
log.error("Cmdb Sw Domain Exception Occurred:", e);
return TeslaResultFactory.buildResult(DomainErr.code, e.getMessage(), "");
}
@ExceptionHandler(DomainRefException.class)
@ResponseBody
public TeslaBaseResult domainRefException(DomainRefException e) {
log.error("Cmdb Sw Domain Ref Exception Occurred:", e);
return TeslaResultFactory.buildResult(DomainRefErr.code, e.getMessage(), "");
}
@ExceptionHandler(DomainExistException.class)
@ResponseBody
public TeslaBaseResult domainExistException(DomainExistException e) {
log.error("Cmdb Sw Domain Exist Exception Occurred:", e);
return TeslaResultFactory.buildResult(DomainExistErr.code, e.getMessage(), "");
}
@ExceptionHandler(DomainNotExistException.class)
@ResponseBody
public TeslaBaseResult domainNotExistException(DomainNotExistException e) {
log.error("Cmdb Sw Domain Not Exist Exception Occurred:", e);
return TeslaResultFactory.buildResult(DomainNotExistErr.code, e.getMessage(), "");
}
@ExceptionHandler(EntityException.class)
@ResponseBody
public TeslaBaseResult entityException(EntityException e) {
log.error("Cmdb Entity Exception Occurred:", e);
return TeslaResultFactory.buildResult(EntityErr.code, e.getMessage(), "");
}
@ExceptionHandler(EntityExistException.class)
@ResponseBody
public TeslaBaseResult entityExistException(EntityExistException e) {
log.error("Cmdb Entity Exist Exception Occurred:", e);
return TeslaResultFactory.buildResult(EntityExistErr.code, e.getMessage(), "");
}
@ExceptionHandler(EntityNotExistException.class)
@ResponseBody
public TeslaBaseResult entityNotExistException(EntityNotExistException e) {
log.error("Cmdb Entity Not Exist Exception Occurred:", e);
return TeslaResultFactory.buildResult(EntityNotExistErr.code, e.getMessage(), "");
}
@ExceptionHandler(EntityFieldException.class)
@ResponseBody
public TeslaBaseResult entityFieldException(EntityFieldException e) {
log.error("Cmdb Entity Field Exception Occurred:", e);
return TeslaResultFactory.buildResult(EntityFieldErr.code, e.getMessage(), "");
}
@ExceptionHandler(EntityFieldExistException.class)
@ResponseBody
public TeslaBaseResult entityFieldExistException(EntityFieldExistException e) {
log.error("Cmdb Entity Field Exist Exception Occurred:", e);
return TeslaResultFactory.buildResult(EntityFieldExistErr.code, e.getMessage(), "");
}
@ExceptionHandler(EntityFieldNotExistException.class)
@ResponseBody
public TeslaBaseResult entityFieldNotExistException(EntityFieldNotExistException e) {
log.error("Cmdb Entity Field Not Exist Exception Occurred:", e);
return TeslaResultFactory.buildResult(EntityFieldNotExistErr.code, e.getMessage(), "");
}
@ExceptionHandler(ParamException.class)
@ResponseBody
public TeslaBaseResult paramException(ParamException e) {
log.error("Cmdb Param Exception Occurred:", e);
return TeslaResultFactory.buildResult(ParamErr.code, e.getMessage(), "");
}
@ExceptionHandler(Exception.class)
@ResponseBody
public TeslaBaseResult exception(Exception e) {
log.error("Cmdb Server Exception Occurred:", e);
return TeslaResultFactory.buildResult(TeslaStatusCode.SERVER_ERROR, e.getMessage(), "");
}
}
|
def sort_input(input):
'''Given the input, sort it and store it in an output array.'''
if len(input) == 0:
return []
else:
pivot = input[0]
less = [i for i in input[1:] if i <= pivot]
more = [i for i in input[1:] if i > pivot]
return sort_input(less) + [pivot] + sort_input(more) |
import { UserEntity } from '../model/user.entity';
export class UserPaginateQueryType {
data:UserEntity[]
limit:number
page:number
total:number
} |
const WINNING_SCORES = [7, 56, 73, 84, 146, 273, 292, 448];
const MINIMUM_SCORE = -10;
const MAXIMUM_SCORE = 10;
const isGameOver = (board) => {
for (let i = 0; i < WINNING_SCORES.length; i++) {
if ((board & WINNING_SCORES[i]) === WINNING_SCORES[i]) {
return true;
}
}
return false;
};
const minimax = (board, isAI) => {
if (isGameOver(board)) {
if (isAI) {
return {score: MAXIMUM_SCORE};
} else {
return {score: MINIMUM_SCORE};
}
}
let moves = [];
for (let i = 0; i < 9; i++) {
if ((board & (1 << i)) === 0) {
moves.push({
score: null,
index: i,
});
}
}
if (isAI) {
let bestScore = MINIMUM_SCORE;
for (let i = 0; i < moves.length; i++) {
let tempBoard = board | (1 << moves[i].index);
let score = minimax(tempBoard, false).score;
if (score > bestScore) {
bestScore = score;
moves[i].score = bestScore;
}
}
return bestScore;
} else {
let bestScore = MAXIMUM_SCORE;
for (let i = 0; i < moves.length; i++) {
let tempBoard = board | (1 << moves[i].index);
let score = minimax(tempBoard, true).score;
if (score < bestScore) {
bestScore = score;
moves[i].score = bestScore;
}
}
return bestScore;
}
}; |
class Node:
def __init__(self, role, action, args=[]):
self.role = role
self.action = action
self.args = args
def create_node(role, action, args=[]):
return Node(role, action, args) |
import React from "react";
import { Col } from "react-bootstrap";
import { Bill } from "../../interfaces/interfaces";
import Content from "./Content";
interface IProps {
bill: Bill;
}
const BillComponent: React.FC<IProps> = ({ bill }) => {
return (
<>
<Col className='d-flex justify-content-between mt-3 mb-3'>
<Content content={bill.name} />
<Content content={`R$ ${bill.value}`} />
</Col>
</>
);
};
export default BillComponent;
|
<filename>main.py
import request_mod as reqmod
import os.path
from os import path
print("thank you for ussing rectify if you have any sugestion head to https://github.com/Human-bio/Rectify") |
<filename>sql/derived_tables/feesfines_accounts_actions.sql
DROP TABLE IF EXISTS folio_reporting.feesfines_accounts_actions;
-- Create a derived table that takes feesfines_accounts as the main table
-- join all transaction data from the feesfines_actions table
-- add patron group information from user_group table
CREATE TABLE folio_reporting.feesfines_accounts_actions AS
SELECT
fa.id AS fine_account_id,
json_extract_path_text(fa.data, 'amount')::numeric(12,2) AS fine_account_amount,
json_extract_path_text(fa.data, 'dateCreated') AS fine_date,
json_extract_path_text(fa.data, 'dateUpdated') AS fine_updated_date,
json_extract_path_text(fa.data, 'feeFineId') AS fee_fine_id,
json_extract_path_text(fa.data, 'ownerId') AS owner_id,
json_extract_path_text(fa.data, 'feeFineOwner') AS fee_fine_owner,
json_extract_path_text(fa.data, 'feeFineType') AS fee_fine_type,
json_extract_path_text(fa.data, 'materialTypeId') AS material_type_id,
json_extract_path_text(fa.data, 'materialType') AS material_type,
json_extract_path_text(fa.data, 'payment_status') AS payment_status,
json_extract_path_text(fa.data, 'status') AS fine_status, -- open or closed
json_extract_path_text(fa.data, 'userId') AS account_user_id,
ff.id AS transaction_id,
json_extract_path_text(ff.data, 'accountId') AS account_id,
json_extract_path_text(ff.data, 'amountAction')::numeric(12,2) AS transaction_amount,
json_extract_path_text(ff.data, 'balance')::numeric(12,2) AS account_balance,
json_extract_path_text(ff.data, 'typeAction') AS type_action,
json_extract_path_text(ff.data, 'dateAction') AS transaction_date,
json_extract_path_text(ff.data, 'createdAt') AS transaction_location,
json_extract_path_text(ff.data, 'transactionInformation') AS transaction_information,
json_extract_path_text(ff.data, 'source') AS operator_id,
json_extract_path_text(ff.data, 'paymentMethod') AS payment_method,
uu.id AS user_id,
uu.patron_group AS user_patron_group_id,
ug.id AS patron_group_id,
ug.group AS patron_group_name
FROM
feesfines_accounts AS fa
LEFT JOIN feesfines_feefineactions AS ff ON fa.id = json_extract_path_text(ff.data, 'accountId')
LEFT JOIN user_users AS uu ON json_extract_path_text(fa.data, 'userId') = uu.id
LEFT JOIN user_groups AS ug ON uu.patron_group = ug.id;
CREATE INDEX ON folio_reporting.feesfines_accounts_actions (fine_account_id);
CREATE INDEX ON folio_reporting.feesfines_accounts_actions (fine_account_amount);
CREATE INDEX ON folio_reporting.feesfines_accounts_actions (fine_date);
CREATE INDEX ON folio_reporting.feesfines_accounts_actions (fine_updated_date);
CREATE INDEX ON folio_reporting.feesfines_accounts_actions (fee_fine_id);
CREATE INDEX ON folio_reporting.feesfines_accounts_actions (owner_id);
CREATE INDEX ON folio_reporting.feesfines_accounts_actions (fee_fine_owner);
CREATE INDEX ON folio_reporting.feesfines_accounts_actions (fee_fine_type);
CREATE INDEX ON folio_reporting.feesfines_accounts_actions (material_type_id);
CREATE INDEX ON folio_reporting.feesfines_accounts_actions (material_type);
CREATE INDEX ON folio_reporting.feesfines_accounts_actions (payment_status);
CREATE INDEX ON folio_reporting.feesfines_accounts_actions (fine_status);
CREATE INDEX ON folio_reporting.feesfines_accounts_actions (account_user_id);
CREATE INDEX ON folio_reporting.feesfines_accounts_actions (transaction_id);
CREATE INDEX ON folio_reporting.feesfines_accounts_actions (account_id);
CREATE INDEX ON folio_reporting.feesfines_accounts_actions (transaction_id);
CREATE INDEX ON folio_reporting.feesfines_accounts_actions (account_balance);
CREATE INDEX ON folio_reporting.feesfines_accounts_actions (type_action);
CREATE INDEX ON folio_reporting.feesfines_accounts_actions (transaction_date);
CREATE INDEX ON folio_reporting.feesfines_accounts_actions (transaction_location);
CREATE INDEX ON folio_reporting.feesfines_accounts_actions (transaction_information);
CREATE INDEX ON folio_reporting.feesfines_accounts_actions (operator_id);
CREATE INDEX ON folio_reporting.feesfines_accounts_actions (payment_method);
CREATE INDEX ON folio_reporting.feesfines_accounts_actions (user_id);
CREATE INDEX ON folio_reporting.feesfines_accounts_actions (user_patron_group_id);
CREATE INDEX ON folio_reporting.feesfines_accounts_actions (patron_group_id);
CREATE INDEX ON folio_reporting.feesfines_accounts_actions (patron_group_name);
|
package main
import (
"fmt"
"os"
"strings"
"github.com/urfave/cli/v2"
"syreclabs.com/go/faker"
"syreclabs.com/go/faker/locales"
)
func main() {
app := cli.App{
Name: "gnrate",
Description: "Genrate fake data",
Authors: []*cli.Author{
{
Name: "<NAME>",
},
},
Usage: "Generates fake data",
UsageText: "gnrate [count] [language] subject",
Action: func(c *cli.Context) error {
configuration, err := parse(c.Args().Slice())
if err != nil {
fmt.Println(err.Error())
}
generate(configuration)
return nil
},
}
app.Run(os.Args)
}
func setLocale(language string) {
language = strings.ToLower(language)
languagesMap := map[string]map[string]interface{}{
"en": locales.En,
"english": locales.En,
"en_us": locales.En_US,
"british": locales.En_GB,
"de": locales.De,
"german": locales.De,
"austrian": locales.De_AT,
"ru": locales.Ru,
"russian": locales.Ru,
"es": locales.Es,
"spanish": locales.Es,
"fr": locales.Fr,
"french": locales.Fr,
"it": locales.It,
"italian": locales.It,
"jp": locales.Ja,
"japanese": locales.Ja,
"ko": locales.Ko,
"korean": locales.Ko,
}
if value, ok := languagesMap[language]; ok {
faker.Locale = value
}
}
func generate(c *Configuration) {
setLocale(c.language)
subject := strings.ToLower(c.subject)
for i := 0; i < c.count; i += 1 {
switch subject {
case "name", "names":
fmt.Println(faker.Name())
case "firstname", "firstnames":
fmt.Println(faker.Name().FirstName())
case "address", "addresses":
fmt.Println(faker.Address())
case "email", "emails":
fmt.Println(faker.Internet().FreeEmail())
case "url", "urls":
fmt.Println(faker.Internet().Url())
case "phone", "phones":
fmt.Println(faker.PhoneNumber())
case "company", "companies":
fmt.Println(faker.Company().Name() + " " + faker.Company().Suffix())
case "sentence", "sentences", "lorem":
fmt.Println(faker.Lorem().Paragraph(1))
}
}
}
|
class ChargingStation:
def __init__(self, id, description, max_charge):
self.id = id
self.description = description
self.max_charge = max_charge
def check_status(self):
if self.max_charge > 0:
return "Charging station is available"
else:
return "Charging station is not available" |
/*
* Copyright (c) 2021 <NAME>
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0
* which is available at https://www.apache.org/licenses/LICENSE-2.0.
*
* SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
*/
package io.vertx.ext.auth.otp.totp;
import io.vertx.codegen.annotations.DataObject;
import io.vertx.codegen.annotations.GenIgnore;
import io.vertx.core.json.JsonObject;
/**
* Options configuring TOTP authentication.
*
* @author <NAME>
*/
@DataObject(generateConverter = true)
public class TotpAuthOptions {
private int passwordLength = 6;
private int authAttemptsLimit;
private long period = 30;
public TotpAuthOptions(JsonObject jsonObject) {
TotpAuthOptionsConverter.fromJson(jsonObject, this);
}
public TotpAuthOptions() {
}
public TotpAuthOptions(int passwordLength, int authAttemptsLimit, long period) {
setPasswordLength(passwordLength);
setAuthAttemptsLimit(authAttemptsLimit);
setPeriod(period);
}
public int getPasswordLength() {
return passwordLength;
}
public int getAuthAttemptsLimit() {
return authAttemptsLimit;
}
public long getPeriod() {
return period;
}
public TotpAuthOptions setPasswordLength(int passwordLength) {
if (passwordLength < 6 || passwordLength > 8) {
throw new IllegalArgumentException("password length must be between 6 and 8 digits");
}
this.passwordLength = passwordLength;
return this;
}
public TotpAuthOptions setAuthAttemptsLimit(int authAttemptsLimit) {
if (authAttemptsLimit < 0) {
throw new IllegalArgumentException("Auth attempts limit must above 0");
}
this.authAttemptsLimit = authAttemptsLimit;
return this;
}
public TotpAuthOptions setPeriod(long period) {
if (period < 0) {
throw new IllegalArgumentException("Period must above 0");
}
this.period = period;
return this;
}
@GenIgnore
public boolean isUsingAttemptsLimit() {
return authAttemptsLimit > 0;
}
}
|
#!/usr/bin/env bash
git submodule update --recursive --init && ./scripts/applyPatches.sh
if [ "$1" == "--jar" ]; then
pushd Trove-Proxy
mvn clean package
fi
|
/**
* Copyright 2005 Sakai Foundation Licensed under the
* Educational Community License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may
* obtain a copy of the License at
*
* http://www.osedu.org/licenses/ECL-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an "AS IS"
* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.sakaiproject.evaluation.tool;
import org.sakaiproject.evaluation.constant.EvalConstants;
/**
* This class holds the tool constants only, application data constants come from
* the EvalConstants class in the model<br/>
* NOTE: Make sure the constants are not already in the EvalConstants class
* before adding them here
*
* @author <NAME> (<EMAIL>)
*/
public class EvalToolConstants {
/**
* This is the key which represents an unknown item
*/
public static String UNKNOWN_KEY = "unknown.caps";
/**
* The values for all sharing menus
*/
public static String[] SHARING_VALUES = new String[] {
EvalConstants.SHARING_PRIVATE,
EvalConstants.SHARING_PUBLIC
// EvalConstants.SHARING_VISIBLE,
// EvalConstants.SHARING_SHARED
};
// should match with SHARING_VALUES
public static String[] SHARING_LABELS_PROPS = new String[] {
"sharing.private",
"sharing.public"
// "sharing.visible",
// "sharing.shared"
};
//For template_modify and preview_item.html
public static String[] STEPPED_IMAGE_URLS = new String[] {
"$context/content/images/corner.gif",
"$context/content/images/down-line.gif",
"$context/content/images/down-arrow.gif"
};
//For preview_item.html
public static String[] COLORED_IMAGE_URLS = new String[] {
"$context/content/images/ideal-none.gif",
"$context/content/images/ideal-low.jpg",
"$context/content/images/ideal-mid.jpg",
"$context/content/images/ideal-high.jpg",
"$context/content/images/ideal-outside.jpg"
};
// should match the images
public static String BLUE_COLOR = "#d7ebf6";
public static String GREEN_COLOR = "#8be8a2";
public static String RED_COLOR = "#ff8ba0";
public static String LIGHT_BLUE_COLOR = "#CCCCFF";
public static String LIGHT_GRAY_COLOR = "#E1E1E1";
// For pulldowns which show the scale display settings
public static String[] SCALE_DISPLAY_SETTING_VALUES = new String[]{
EvalConstants.ITEM_SCALE_DISPLAY_COMPACT,
EvalConstants.ITEM_SCALE_DISPLAY_COMPACT_COLORED,
EvalConstants.ITEM_SCALE_DISPLAY_FULL,
EvalConstants.ITEM_SCALE_DISPLAY_FULL_COLORED,
EvalConstants.ITEM_SCALE_DISPLAY_MATRIX,
EvalConstants.ITEM_SCALE_DISPLAY_STEPPED,
EvalConstants.ITEM_SCALE_DISPLAY_STEPPED_COLORED,
EvalConstants.ITEM_SCALE_DISPLAY_VERTICAL
};
// should match the order of the array above, should include the properties strings only (no real labels)
public static String[] SCALE_DISPLAY_SETTING_LABELS_PROPS = new String[] {
"templateitem.scale.select.compact",
"templateitem.scale.select.compactc",
"templateitem.scale.select.full",
"templateitem.scale.select.fullc",
"templateitem.scale.select.matrix",
"templateitem.scale.select.stepped",
"templateitem.scale.select.steppedc",
"templateitem.scale.select.vertical"
};
public static String[] SCALE_DISPLAY_GROUP_SETTING_VALUES = new String[] {
EvalConstants.ITEM_SCALE_DISPLAY_MATRIX,
EvalConstants.ITEM_SCALE_DISPLAY_STEPPED,
EvalConstants.ITEM_SCALE_DISPLAY_STEPPED_COLORED
};
public static String[] SCALE_DISPLAY_GROUP_SETTING_LABELS_PROPS = new String[] {
"templateitem.scale.select.matrix",
"templateitem.scale.select.stepped",
"templateitem.scale.select.steppedc"
};
// For pulldowns which show the multiple choices display settings
public static String[] CHOICES_DISPLAY_SETTING_VALUES = new String[]{
EvalConstants.ITEM_SCALE_DISPLAY_VERTICAL,
EvalConstants.ITEM_SCALE_DISPLAY_FULL
};
// should match the order of the array above, should include the properties strings only (no real labels)
public static String[] CHOICES_DISPLAY_SETTING_LABELS_PROPS = new String[] {
"templateitem.scale.select.vertical",
"templateitem.scale.select.full"
};
// used for the default category choices
public static String[] ITEM_CATEGORY_VALUES = new String[] {
EvalConstants.ITEM_CATEGORY_COURSE,
EvalConstants.ITEM_CATEGORY_INSTRUCTOR
};
// should match ITEM_CATEGORY_VALUES
public static String[] ITEM_CATEGORY_LABELS_PROPS = {
"modifyitem.course.category",
"modifyitem.instructor.category"
};
public static String ITEM_CATEGORY_ASSISTANT = EvalConstants.ITEM_CATEGORY_ASSISTANT;
public static String ITEM_CATEGORY_ASSISTANT_LABEL = "modifyitem.ta.category";
/**
* Email Settings: Page pulldown constants for email processing type
* <ol>
* <li>Multiple emails per student - one email per evaluation response outstanding.</li>
* <li>Single email per student - one email if any of a student's responses are outstanding.</li>
* </ol>
*/
public static String[] EMAIL_TYPE_VALUES = new String[] {
"multiple", "single"};
public static String[] EMAIL_TYPE_LABELS = new String[] {
"Multiple emails per student - one email per response outstanding.",
"Single email per student - one email if any of a student's responses are outstanding."
};
public static final String SINGLE_EMAIL = "single";
public static final String MULTIPLE_EMAILS = "multiple";
/**
* Email Settings: Page pulldown constants for email delivery options
* <ol>
* <li>Send email. This mode should be used in production, when you do want to send email to real users.</li>
* <li>Log email to the server log. This mode may be used in development to check the content of email messages.</li>
* <li>Do not send email. This mode may be used for safer testing, when you don't want to accidentally send email to real users.</li>
* </ol>
*/
public static String[] EMAIL_DELIVERY_VALUES = new String[] {
"send", "log", "none"};
// FIXME this should not be done this way, UM should put this in the messages file -AZ
public static String[] EMAIL_DELIVERY_LABELS = new String[] {
"Send email. This mode should be used in production, when you do want to send email to real users.",
"Log email to the server log. This mode may be used in development to check the content of email messages.",
"Do not send email. This mode may be used for safer testing, when you don't want to accidentally send email to real users."};
public static final String[] PULLDOWN_HOUR_VALUES = new String[] {
"0","1","2","3","4","5","6","7",
"8","9","10","11","12","13","14","15",
"16","17","18","19","20","21","22","23"
};
public static final String[] PULLDOWN_HOUR_LABELS = new String[] {
"controlemail.start.hour.0","controlemail.start.hour.1","controlemail.start.hour.2","controlemail.start.hour.3",
"controlemail.start.hour.4","controlemail.start.hour.5","controlemail.start.hour.6","controlemail.start.hour.7",
"controlemail.start.hour.8","controlemail.start.hour.9","controlemail.start.hour.10","controlemail.start.hour.11",
"controlemail.start.hour.12","controlemail.start.hour.13","controlemail.start.hour.14","controlemail.start.hour.15",
"controlemail.start.hour.16","controlemail.start.hour.17","controlemail.start.hour.18","controlemail.start.hour.19",
"controlemail.start.hour.20","controlemail.start.hour.21","controlemail.start.hour.22","controlemail.start.hour.23"
};
public static final String[] PULLDOWN_MINUTE_VALUES = new String[] {
"0", "5", "10", "15", "20", "25", "30", "35", "40", "45", "50", "55"
};
public static final String[] PULLDOWN_MINUTE_LABELS = new String[] {
"controlemail.start.minutes.0", "controlemail.start.minutes.5", "controlemail.start.minutes.10",
"controlemail.start.minutes.15", "controlemail.start.minutes.20", "controlemail.start.minutes.25",
"controlemail.start.minutes.30", "controlemail.start.minutes.35", "controlemail.start.minutes.40",
"controlemail.start.minutes.45", "controlemail.start.minutes.50", "controlemail.start.minutes.55"
};
/**
* Evaluation/Email Settings: Page pulldown constants for reminder interval
*/
public static final String[] REMINDER_EMAIL_DAYS_VALUES = new String[] {
"0", "1", "2", "3", "4", "5", "6", "7", "-1" };
public static final String[] REMINDER_EMAIL_DAYS_LABELS = {
"evalsettings.reminder.days.0",
"evalsettings.reminder.days.1",
"evalsettings.reminder.days.2",
"evalsettings.reminder.days.3",
"evalsettings.reminder.days.4",
"evalsettings.reminder.days.5",
"evalsettings.reminder.days.6",
"evalsettings.reminder.days.7",
"evalsettings.reminder.days.-1"
};
/**
* Defines the allowed values for the Integer constants in batch-related pulldowns
*/
public static final String[] PULLDOWN_BATCH_VALUES = new String[] {
"0", "10", "25", "50", "100", "250", "500", "750", "1000"};
/**
* Evaluation settings: Values for instructor options for using evaluationSetupService from above
*/
public static final String[] INSTRUCTOR_OPT_VALUES = new String[] {
EvalConstants.INSTRUCTOR_OPT_OUT,
EvalConstants.INSTRUCTOR_OPT_IN,
EvalConstants.INSTRUCTOR_REQUIRED
};
public static final String[] INSTRUCTOR_OPT_LABELS = {
"evalsettings.instructors.label.opt.out",
"evalsettings.instructors.label.opt.in",
"evalsettings.instructors.label.required"
};
/**
* Modify Essay: Page pulldown constants for response size
*/
public static final String[] RESPONSE_SIZE_VALUES = new String[] {
"2",
"3",
"4",
"5"
};
public static final String[] RESPONSE_SIZE_LABELS_PROPS = new String[] {
"templateitem.response.select.size.2",
"templateitem.response.select.size.3",
"templateitem.response.select.size.4",
"templateitem.response.select.size.5"
};
/**
* The default number of rows to use when displaying a textarea type input box
*/
public static final Integer DEFAULT_ROWS = new Integer(2);
// For main administrative page
/**
* Defines the allowed values for the Integer constants in pulldowns
*/
public static final String[] PULLDOWN_INTEGER_VALUES = new String[] {
"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "12", "14", "15", "18", "20", "21", "25", "28", "30", "50", "60", "90"};
/**
* Defines the allowed values for minimum time difference (in hours)
* between start and due date of an evaluation.
*/
public static final String[] MINIMUM_TIME_DIFFERENCE = new String[] {
"0", "1", "2", "4", "8", "12", "16", "20", "24", "36", "48", "96"};
/**
* Defines the allowed values for the auth control pulldown in the evaluation settings
*/
public static final String[] AUTHCONTROL_VALUES = new String[] {
EvalConstants.EVALUATION_AUTHCONTROL_AUTH_REQ,
//EvalConstants.EVALUATION_AUTHCONTROL_KEY, // CTL-563
EvalConstants.EVALUATION_AUTHCONTROL_NONE
};
public static final String[] AUTHCONTROL_LABELS = {
"evalsettings.auth.control.label.required",
//"evalsettings.auth.control.label.key", // CTL-563
"evalsettings.auth.control.label.none"
};
/**
* Administrative (system settings) page,
* values corresponding to "Yes", "No", "Configurable"
*/
public static final String ADMIN_BOOLEAN_YES = "1";
public static final String ADMIN_BOOLEAN_NO = "0";
public static final String ADMIN_BOOLEAN_CONFIGURABLE = "-1";
// TODO - this is needed to pretend to be null until RSF is fixed up in 0.7.3 (related change below)
/**
* This fills in for the real null since real null cannot be passed around
*/
public static final String NULL = "*NULL*";
/**
* Ideal scale values radio buttons (scale add/modify)
*/
public static final String[] scaleIdealValues = {
NULL, // EvalConstants.SCALE_IDEAL_NONE, TODO - undo this when RSF 0.7.3
EvalConstants.SCALE_IDEAL_LOW,
EvalConstants.SCALE_IDEAL_HIGH,
EvalConstants.SCALE_IDEAL_MID,
EvalConstants.SCALE_IDEAL_OUTSIDE
};
/**
* Ideal scale values radio button labels (scale add/modify)
*/
public static final String[] scaleIdealLabels = {
"controlscales.ideal.scale.option.label.none",
"controlscales.ideal.scale.option.label.low",
"controlscales.ideal.scale.option.label.high",
"controlscales.ideal.scale.option.label.mid",
"controlscales.ideal.scale.option.label.outside"
};
/**
* The initial values for the options of a scale which is being created
*/
public static final String[] defaultInitialScaleValues = new String[] {"",""};
/**
* Used for translating the types into I18n strings
*/
public static final String[] ITEM_CLASSIFICATION_VALUES = new String[] {
EvalConstants.ITEM_TYPE_BLOCK_CHILD,
EvalConstants.ITEM_TYPE_BLOCK_PARENT,
EvalConstants.ITEM_TYPE_SCALED,
EvalConstants.ITEM_TYPE_MULTIPLECHOICE,
EvalConstants.ITEM_TYPE_MULTIPLEANSWER,
EvalConstants.ITEM_TYPE_TEXT,
EvalConstants.ITEM_TYPE_HEADER,
};
public static final String[] ITEM_CLASSIFICATION_LABELS_PROPS = new String[] {
"item.classification.scaled",
"item.classification.block",
"item.classification.scaled",
"item.classification.multichoice",
"item.classification.multianswer",
"item.classification.text",
"item.classification.header"
};
/**
* Values for rendering the items types for creating new items
*/
public static final String[] ITEM_SELECT_CLASSIFICATION_VALUES = new String[] {
EvalConstants.ITEM_TYPE_SCALED,
EvalConstants.ITEM_TYPE_MULTIPLECHOICE,
EvalConstants.ITEM_TYPE_MULTIPLEANSWER,
EvalConstants.ITEM_TYPE_TEXT,
EvalConstants.ITEM_TYPE_HEADER
};
public static final String[] ITEM_SELECT_CLASSIFICATION_LABELS = new String[] {
"item.classification.scaled",
"item.classification.multichoice",
"item.classification.multianswer",
"item.classification.text",
"item.classification.header"
};
/**
* UMD Specific
* values for item results sharing.
* updated from public/private to Administrative/Student EVALSYS-850
*/
public static String[] ITEM_RESULTS_SHARING_VALUES = new String[] {
EvalConstants.SHARING_ADMIN,
EvalConstants.SHARING_STUDENT
};
// should match ITEM_RESULTS_SHARING_VALUES
public static String[] ITEM_RESULTS_SHARING_LABELS_PROPS = {
"modifyitem.results.sharing.admin",
"modifyitem.results.sharing.student"
//"general.public",
//"general.private"
};
/**
* values for evaluation results sharing.
*/
public static String[] EVAL_RESULTS_SHARING_VALUES = new String[] {
EvalConstants.SHARING_PRIVATE,
EvalConstants.SHARING_VISIBLE,
EvalConstants.SHARING_PUBLIC
};
// should match EVAL_RESULTS_SHARING_VALUES
public static String[] EVAL_RESULTS_SHARING_LABELS_PROPS = {
"general.private",
"general.configurable",
"general.public"
};
// The downloadable results reporting files have a maximum length, before they are chopped off.
public static int EVAL_REPORTING_MAX_NAME_LENGTH = 40;
/**
* values for eval mail notification choices
*/
public static String[] EVAL_NOTIFICATION_VALUES = new String[] {
EvalConstants.EVAL_INCLUDE_NONTAKERS,
EvalConstants.EVAL_INCLUDE_RESPONDENTS,
EvalConstants.EVAL_INCLUDE_ALL
};
/**
* values for eval mail notification choices
*/
public static String[] EVAL_NOTIFICATION_LABELS_PROPS = {
"evalnotify.send.to.non-respond",
"evalnotify.send.to.responded",
"evalnotify.send.to.all"
};
/**
* This defines the set of all hierarchy permissions. Only the permissions in this
* array will be displayed on the modify hierarchy node users screen.
*/
public static final String[] HIERARCHY_PERM_VALUES = {
EvalConstants.HIERARCHY_PERM_VIEW_NODE_DATA,
EvalConstants.HIERARCHY_PERM_VIEW_TREE_DATA,
EvalConstants.HIERARCHY_PERM_CONTROL_NODE_DATA,
EvalConstants.HIERARCHY_PERM_CONTROL_TREE_DATA,
EvalConstants.HIERARCHY_PERM_ASSIGN_EVALUATION
};
public static final String[] HIERARCHY_PERM_LABELS = {
"modifynodeperms.perm.view.node",
"modifynodeperms.perm.view.tree",
"modifynodeperms.perm.control.node",
"modifynodeperms.perm.control.tree",
"modifynodeperms.perm.assign.eval",
};
}
|
def transform_ascii_art(ascii_art):
# Split the input ASCII art into individual lines
lines = ascii_art.strip().split('\n')
# Rotate the ASCII art 90 degrees clockwise
rotated_art = [''.join([lines[j][i] for j in range(len(lines)-1, -1, -1)]) for i in range(len(lines[0]))]
# Flip the rotated ASCII art horizontally
flipped_art = '\n'.join(rotated_art)
return flipped_art |
<filename>cometchat/plugins/avchat/js/opentok.js<gh_stars>0
<?php
/*
CometChat
Copyright (c) 2014 Inscripts
CometChat ('the Software') is a copyrighted work of authorship. Inscripts
retains ownership of the Software and any copies of it, regardless of the
form in which the copies may exist. This license is not a sale of the
original Software or any copies.
By installing and using CometChat on your server, you agree to the following
terms and conditions. Such agreement is either on your own behalf or on behalf
of any corporate entity which employs you or which you represent
('Corporate Licensee'). In this Agreement, 'you' includes both the reader
and any Corporate Licensee and 'Inscripts' means Inscripts (I) Private Limited:
CometChat license grants you the right to run one instance (a single installation)
of the Software on one web server and one web site for each license purchased.
Each license may power one instance of the Software on one domain. For each
installed instance of the Software, a separate license is required.
The Software is licensed only to you. You may not rent, lease, sublicense, sell,
assign, pledge, transfer or otherwise dispose of the Software in any form, on
a temporary or permanent basis, without the prior written consent of Inscripts.
The license is effective until terminated. You may terminate it
at any time by uninstalling the Software and destroying any copies in any form.
The Software source code may be altered (at your risk)
All Software copyright notices within the scripts must remain unchanged (and visible).
The Software may not be used for anything that would represent or is associated
with an Intellectual Property violation, including, but not limited to,
engaging in any activity that infringes or misappropriates the intellectual property
rights of others, including copyrights, trademarks, service marks, trade secrets,
software piracy, and patents held by individuals, corporations, or other entities.
If any of the terms of this Agreement are violated, Inscripts reserves the right
to revoke the Software license at any time.
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
include_once(dirname(dirname(__FILE__)).DIRECTORY_SEPARATOR."config.php");
include_once(dirname(dirname(__FILE__)).DIRECTORY_SEPARATOR."lang".DIRECTORY_SEPARATOR."en.php");
if (file_exists(dirname(dirname(__FILE__)).DIRECTORY_SEPARATOR."lang".DIRECTORY_SEPARATOR.$lang.".php")) {
include_once(dirname(dirname(__FILE__)).DIRECTORY_SEPARATOR."lang".DIRECTORY_SEPARATOR.$lang.".php");
}
foreach ($avchat_language as $i => $l) {
$avchat_language[$i] = str_replace("'", "\'", $l);
}
?>
var vidWidth = <?php echo $vidWidth;?>; var vidHeight = <?php echo $vidHeight;?>; var baseUrl = "<?php echo BASE_URL;?>"; var session; var publisher; var subscribers = {}; var totalStreams = 0;var camWidth = <?php echo $camWidth;?>; var camHeight = <?php echo $camHeight;?>; var newheight = 0;
function disconnect() {
unpublish();
session.disconnect();
hide('navigation');
show('endcall');
var div = document.getElementById('canvas');
div.parentNode.removeChild(div);
eval(resize +'300,330);');
}
function publish() {
if (!publisher) {
var canvas = document.getElementById("canvas");
var div = document.createElement('div');
div.setAttribute('id', 'opentok_publisher');
canvas.appendChild(div);
var params = {width: vidWidth, height: vidHeight , name: name};
publisher = session.publish('opentok_publisher', params);
resizeWindow();
show('unpublishLink');
hide('publishLink');
}
}
function resizeWindow() {
var rows, cols;
if(totalStreams == 0) {
var marginOffset = (window.innerWidth - vidWidth)/2;
} else {
document.getElementById('canvas').style.margin = "";
}
rows = Math.round(Math.sqrt(totalStreams+1));
cols = Math.ceil(Math.sqrt(totalStreams+1));
width = (cols)*(vidWidth+2);
height = (rows)*(vidHeight+30);
if (width < vidWidth + 30) {
width = vidWidth+30;
}
if(width < 400)
width = 400;
if(height < 300)
height = 300;
eval(resize +'width,'+height + ');');
var h = vidHeight;
if( typeof( window.innerWidth ) == 'number' ) {
h = window.innerHeight;
} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
h = document.documentElement.clientHeight;
} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
h = document.body.clientHeight;
}
if (document.getElementById('canvas') && document.getElementById('canvas').style.display != 'none') {
if (h > vidHeight){
if(totalStreams == 1) {
offset = (h-30-vidHeight)/2;
document.getElementById('canvas').style.marginTop = '12%';
} else {
document.getElementById('canvas').style.marginTop = '0px';
}
} else {
document.getElementById('canvas').style.marginTop = '0px';
}
}
if(totalStreams > 1) {
document.getElementById('canvas').style.marginTop = '0px';
}
resizeVideo();
}
function resizeVideo() {
rows = Math.round(Math.sqrt(totalStreams+1));
cols = Math.ceil(Math.sqrt(totalStreams+1));
width = parseInt(window.innerWidth/cols)-3;
height = 0.75 * width;
var canvas = document.getElementById("canvas");
if (typeof( document.getElementById("canvas").childNodes ) != "undefined" && document.getElementById("canvas").childNodes != null) {
var nodes = document.getElementById("canvas").childNodes;
}
newheight = height * rows;
if(window.innerHeight < newheight){
height = parseInt(window.innerHeight/rows)-3;
width = 1.33 * height;
}
for(var i=0; i<nodes.length; i++) {
if (nodes[i].nodeName.toLowerCase() == 'object') {
nodes[i].style.width = width +'px';
nodes[i].style.height = (height-28) +'px';
}
}
newwidth = width * cols;
if(window.innerWidth > newwidth ){
document.getElementById('canvas').style.marginLeft = '0px';
var margin = parseInt((window.innerWidth - newwidth)/2) - 1;
document.getElementById('canvas').style.marginLeft = margin+'px';
}
}
function addStream(stream) {
if (stream.connection.connectionId == session.connection.connectionId) {
return;
}
var div = document.createElement('div');
var divId = stream.streamId;
div.setAttribute('id', divId);
div.setAttribute('class', 'camera');
document.getElementById('canvas').appendChild(div);
var params = {width: vidWidth, height: vidHeight};
subscribers[stream.streamId] = session.subscribe(stream, divId, params);
}
function inviteUser() {
eval(invitefunction + '("' + baseUrl + 'plugins/avchat/invite.php?action=invite&roomid='+ sessionId +'&basedata='+ basedata +'","invite","status=0,toolbar=0,menubar=0,directories=0,resizable=0,location=0,status=0,scrollbars=1, width=400,height=190",400,190,"<?php echo $avchat_language[16];?>");');
}
function connect() {
session.connect(apiKey, token);
}
function unpublish() {
if (publisher) {
session.unpublish(publisher);
}
publisher = null;
show('publishLink');
hide('unpublishLink');
resizeWindow();
}
function sessionConnectedHandler(event) {
hide('loading');
show('canvas');
publish();
for (var i = 0; i < event.streams.length; i++) {
if (event.streams[i].connection.connectionId != session.connection.connectionId) {
totalStreams++;
}
addStream(event.streams[i]);
}
resizeWindow();
show('navigation');
show('unpublishLink');
show('disconnectLink');
hide('publishLink');
}
function streamCreatedHandler(event) {
for (var i = 0; i < event.streams.length; i++) {
if (event.streams[i].connection.connectionId != session.connection.connectionId) {
totalStreams++;
}
addStream(event.streams[i]);
}
resizeWindow();
}
function streamDestroyedHandler(event) {
for (var i = 0; i < event.streams.length; i++) {
if (event.streams[i].connection.connectionId != session.connection.connectionId) {
totalStreams--;
}
}
resizeWindow();
}
function sessionDisconnectedHandler(event) {
publisher = null;
}
function connectionDestroyedHandler(event) {
}
function connectionCreatedHandler(event) {
}
function exceptionHandler(event) {
}
function show(id) {
document.getElementById(id).style.display = 'block';
}
function hide(id) {
document.getElementById(id).style.display = 'none';
}
|
#!/bin/bash
set -euo pipefail
IFS=$'\n\t'
# Swarm mode using Docker Machine (Taken from https://github.com/docker/labs)
managers=1
workers=3
# create manager machines
echo "======> Creating $managers manager machines ...";
for node in $(seq 1 $managers);
do
echo "======> Creating manager$node machine ...";
docker-machine create -d virtualbox manager$node;
done
# create worker machines
echo "======> Creating $workers worker machines ...";
for node in $(seq 1 $workers);
do
echo "======> Creating worker$node machine ...";
docker-machine create -d virtualbox worker$node;
done
# list all machines
docker-machine ls
# initialize swarm mode and create a manager
echo "======> Initializing first swarm manager ..."
docker-machine ssh manager1 "docker swarm init --listen-addr $(docker-machine ip manager1) --advertise-addr $(docker-machine ip manager1)"
docker-machine ssh manager1 "tce-load -wi make"
# get manager and worker tokens
export manager_token=`docker-machine ssh manager1 "docker swarm join-token manager -q"`
export worker_token=`docker-machine ssh manager1 "docker swarm join-token worker -q"`
echo "manager_token: $manager_token"
echo "worker_token: $worker_token"
# other masters join swarm
for node in $(seq 2 $managers);
do
echo "======> manager$node joining swarm as manager ..."
docker-machine ssh manager$node \
"docker swarm join \
--token $manager_token \
--listen-addr $(docker-machine ip manager$node) \
--advertise-addr $(docker-machine ip manager$node) \
$(docker-machine ip manager1)"
done
# show members of swarm
docker-machine ssh manager1 "docker node ls"
# workers join swarm
for node in $(seq 1 $workers);
do
echo "======> worker$node joining swarm as worker ..."
docker-machine ssh worker$node \
"docker swarm join \
--token $worker_token \
--listen-addr $(docker-machine ip worker$node) \
--advertise-addr $(docker-machine ip worker$node) \
$(docker-machine ip manager1)"
done
# show members of swarm
docker-machine ssh manager1 "docker node ls"
|
<filename>tests/test_api.py
# Copyright Contributors to the Packit project.
# SPDX-License-Identifier: MIT
from datetime import timedelta, datetime
from flexmock import flexmock
from tokman import app
from tokman.app import AppNotInstalledError
def test_api_health(client):
response = client.get("/api/health")
assert "ok" in response.data.decode()
def test_get_access_token_existing(client, init_db):
flexmock(app).should_call("get_token").never()
response = client.get("/api/packit/ogr")
assert "Token123" in response.data.decode()
def test_get_access_token_expired(client, init_db):
flexmock(app).should_receive("get_token").and_return(
"Token<PASSWORD>", datetime.utcnow() + timedelta(hours=1)
).once()
response = client.get("/api/packit/packit")
assert "Token<PASSWORD>" in response.data.decode()
def test_get_access_token_app_not_installed(client, init_db):
flexmock(app).should_receive("get_token").and_raise(AppNotInstalledError)
response = client.get("/api/packit/packit")
assert response.status_code == 400
|
import {mxEnv} from 'Resources/helpers';
export default {
profile: false,
loaded: false,
messageStatus: false,
isPartner: false,
bgShown: false,
adminDetails: {},
env: mxEnv()
};
|
import { get, post } from './http'
const api = {
getArticles(page, limit) {
const params = {
page,
limit: limit || 5
}
return get('/article', params)
},
getArticle(id) {
return get('/article/' + id)
},
getCategories() {
return get('/category')
},
getTags() {
return get('/tag')
},
getPageMenu() {
return get('/page')
},
getPage(id) {
return get('/page/' + id)
},
getArchives() {
return get('/archive')
},
getComment(articleId, page, limit) {
const params = {
articleId,
page,
limit: limit || 5
}
return get('comment', params)
},
postComment(articleId, pId, content, name, email, website) {
const params = {
articleId,
pId,
content,
name,
email,
website
}
return post('/comment', params)
},
assessComment(commentId, assess) {
const params = {
assess
}
return post('/comment/' + commentId + '/assess', params)
},
getOptions() {
return get('/option')
}
}
export default api
|
<reponame>leongaban/redux-saga-exchange
import * as React from 'react';
import { bind } from 'decko';
import { connect } from 'react-redux';
import { bindActionCreators, Dispatch } from 'redux';
import block from 'bem-cn';
import { createSelector } from 'reselect';
import * as R from 'ramda';
import { Input, Icon } from 'shared/view/elements/';
import { Table } from 'shared/view/components';
import { floorFloatToFixed } from 'shared/helpers/number';
import {
IExchangeRate,
IExchangeRateColumns,
IExchangeRateColumnData,
ICurrencyPair,
IExchangeRatesVisibleColumns,
} from 'shared/types/models';
import { ISortInfo } from 'shared/types/ui';
import { getTableRowHoverColor, getSelectedTableRowHoverColor } from 'shared/view/styles/themes';
import { transformAssetName } from 'shared/helpers/converters';
import { IStateProps, mapState } from './shared';
import { actions } from '../../../redux';
import { RateCell } from '../../components';
import { CounterCurrencyFilters } from '..';
import './ExchangeRates.scss';
interface IDispatchProps {
loadFavorites: typeof actions.loadFavorites;
toggleMarketFavoriteStatus: typeof actions.toggleMarketFavoriteStatus;
setSearchValue: typeof actions.setSearchValue;
resetUI: typeof actions.resetUI;
}
interface IOwnProps {
currentCurrencyPair?: ICurrencyPair;
columnsToDisplay: IExchangeRatesVisibleColumns;
sortInfo?: ISortInfo<IExchangeRate>;
onSortInfoChange?(sort: ISortInfo<IExchangeRate>): void;
onSelect?(record: IExchangeRate): void;
}
type IProps = IStateProps & IDispatchProps & IOwnProps;
function mapDispatch(dispatch: Dispatch<any>): IDispatchProps {
return bindActionCreators({
loadFavorites: actions.loadFavorites,
toggleMarketFavoriteStatus: actions.toggleMarketFavoriteStatus,
setSearchValue: actions.setSearchValue,
resetUI: actions.resetUI,
}, dispatch);
}
const b = block('exchange-rates');
const ExchangeRatesTable = Table as new () => Table<IExchangeRateColumnData, {}, ''>;
class ExchangeRates extends React.PureComponent<IProps> {
private columns: IExchangeRateColumns = {
market: {
title: () => 'Market',
renderCell: (record: IExchangeRate, selected: boolean) => {
return (
<div className={b('market', { selected })()}>
{transformAssetName(record.market.replace('_', '/'))}
</div>
);
},
},
current: {
title: () => 'Current',
renderCell: ({ current, market }: IExchangeRate, selected: boolean) => {
return (
<div className={b('current', { selected })()}>
{this.props.formatPrice(market, current)}
</div>
);
},
},
changeAbsolute: {
title: () => 'Change',
renderCell: ({ changeAbsolute, market }: IExchangeRate, selected: boolean) => {
return <RateCell value={this.props.formatPrice(market, changeAbsolute)} selected={selected} />;
},
},
changePercent: {
title: () => 'Change, %',
renderCell: (record: IExchangeRate, selected: boolean) => {
return (
<RateCell value={floorFloatToFixed(record.changePercent, 2)} selected={selected} postfix="%" withArrow />
);
},
},
};
private selectFilteredColumns = createSelector(
() => this.columns,
(props: IProps) => props.columnsToDisplay,
(columns, columnsToDisplay): Partial<IExchangeRateColumns> =>
R.pickBy((_, key: keyof typeof columns) => key === 'market'
? true
: columnsToDisplay[key], columns),
);
public componentDidMount() {
const { loadFavorites, currentCurrencyPair, filteredExchangeRates, onSelect } = this.props;
if (currentCurrencyPair && currentCurrencyPair.hidden) {
if (filteredExchangeRates.length) {
onSelect && onSelect(filteredExchangeRates[0]);
}
}
loadFavorites();
}
public componentWillUnmount() {
this.props.resetUI();
}
public render() {
const { currentCurrencyPair, sortInfo, onSelect, onSortInfoChange, filteredExchangeRates } = this.props;
const currentExchangeRate = (() => {
if (currentCurrencyPair) {
return filteredExchangeRates.find(exchangeRate => exchangeRate.market === currentCurrencyPair.id);
}
})();
return (
<div className={b()}>
<div className={b('controls')()}>
<div className={b('search')()}>
<Input
search
onChange={this.handleSearchInputChange}
placeholder="Search"
/>
</div>
<div className={b('controls-gap')()} />
<div className={b('tabs')()}>
<CounterCurrencyFilters size="small" />
</div>
</div>
<div className={b('table')()}>
<ExchangeRatesTable
columns={this.selectFilteredColumns(this.props)}
records={filteredExchangeRates}
selectedRecord={currentExchangeRate}
areRecordsEqual={this.areRecordsEqual}
renderHeaderRow={this.renderRowHeader}
onRecordSelect={onSelect}
sortInfo={sortInfo}
onSortInfoChange={onSortInfoChange}
recordIDColumn="market"
minWidth={23}
getRowHoverColor={getTableRowHoverColor}
getSelectedRowHoverColor={getSelectedTableRowHoverColor}
/>
</div>
</div>
);
}
private makeToggleMarketFavoriteStatus(market: string) {
const { toggleMarketFavoriteStatus } = this.props;
return (event: React.SyntheticEvent<HTMLElement>) => {
toggleMarketFavoriteStatus(market);
event.stopPropagation();
};
}
@bind
private renderRowHeader(record: IExchangeRate) {
return (
<div
className={b('toggle-favorites-checkbox', { favorite: this.isMarketInFavorites(record) })()}
onClick={this.makeToggleMarketFavoriteStatus(record.market)}
>
<Icon src={require('../../img/fav-inline.svg')} className={b('fav-icon')()} />
</div>
);
}
@bind
private isMarketInFavorites(record: IExchangeRate) {
const { favorites } = this.props;
return R.contains(record.market, favorites);
}
@bind
private handleSearchInputChange(event: React.ChangeEvent<HTMLInputElement>) {
const { setSearchValue } = this.props;
setSearchValue(event.target.value);
}
private areRecordsEqual(record: IExchangeRate, selectedRecord: IExchangeRate): boolean {
return record.market === selectedRecord.market;
}
}
export { IProps };
export default connect<IStateProps, IDispatchProps>(mapState, mapDispatch)(ExchangeRates);
|
<gh_stars>1-10
import React from 'react';
import { Link } from 'gatsby';
import { Result, Button, Layout } from 'antd';
import Helmet from '@/components/Helmet';
import UFooter from '@/components/Footer';
import styles from './404.module.less';
const Content = Layout.Content;
const Footer = Layout.Footer;
class NotFoundPage extends React.Component {
render() {
return (
<Layout className={styles.main}>
<Content>
<Helmet title="404" />
<Result
status="404"
title="404"
subTitle="抱歉,你访问的页面不存在。"
extra={
<Link to="/">
<Button type="primary">返回首页</Button>
</Link>
}
/>
</Content>
<Footer>
<UFooter />
</Footer>
</Layout>
)
}
}
export default NotFoundPage
|
<filename>activitytree/views.py<gh_stars>1-10
# -*- coding: utf-8 -*-
# Create your views here.
from django.http import HttpResponse, HttpResponseRedirect, HttpResponseNotFound
from django.http import JsonResponse
from django.template.response import TemplateResponse
from django.db.models import Avg, Count
from django.db import IntegrityError
from django.db import transaction
from django.contrib.sites.shortcuts import get_current_site
from django.core.exceptions import ObjectDoesNotExist
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.conf import settings
from django.urls import reverse
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth import models as auth_models
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.shortcuts import get_object_or_404
from django.shortcuts import render
from django.template import RequestContext
from django.views.decorators.csrf import csrf_protect
from django.views.decorators.csrf import csrf_exempt
from django.utils import timezone
#from retest import re_test
import logging
import xml.etree.ElementTree as ET
import uuid
import urllib
from urllib.parse import urlparse
import json
from activitytree.retest import re_test
import pymongo
from pymongo import errors
from pymongo import MongoClient
import redis
import bleach
from activitytree.bleach_whitelist import all_tags, attrs
from activitytree.mongo_activities import Activity
from eval_code.RedisCola import Cola, Task
from activitytree.models import Course, ActivityTree, UserLearningActivity, LearningActivity, ULA_Event, \
LearningActivityRating, LearningStyleInventory
from activitytree.interaction_handler import SimpleSequencing
from activitytree.models import UserProfile
from activitytree.courses import get_activity_tree, update_course_from_json, create_empty_course, upload_course_from_json
from django.contrib.auth.forms import UserCreationForm
from django.contrib import messages
logger = logging.getLogger(__name__)
def welcome(request):
courses = Course.objects.all()
print(request)
if request.user.is_authenticated and request.user != 'AnonymousUser':
return render(request,
'activitytree/welcome.html',
{ 'courses': courses
# , 'plus_scope':plus_scope,'plus_id':plus_id
} )
else:
return render(request,'activitytree/welcome.html',
{'user_name': None, 'courses': courses
# ,'plus_scope':plus_scope,'plus_id':plus_id
} )
def course_list(request):
courses = Course.objects.all()
if request.user.is_authenticated and request.user != 'AnonymousUser':
return render(request,'activitytree/course_list.html',
{'courses': courses
# , 'plus_scope':plus_scope,'plus_id':plus_id
})
else:
return render(request,'activitytree/course_list.html',
{'user_name': None, 'courses': courses
# ,'plus_scope':plus_scope,'plus_id':plus_id
})
def instructor(request):
if request.user.is_authenticated and request.user != 'AnonymousUser':
courses = LearningActivity.objects.filter(authorlearningactivity__user=request.user, root=None)
return render(request, 'activitytree/instructor_home.html',
{'courses': courses
# , 'plus_scope':plus_scope,'plus_id':plus_id
})
else:
return HttpResponseRedirect('/accounts/login/?next=%s' % request.path)
def student(request):
if request.user.is_authenticated and request.user != 'AnonymousUser':
courses = LearningActivity.objects.filter(authorlearningactivity__user=request.user, root=None)
return render(request,'activitytree/student_home.html',
{'courses': courses
# , 'plus_scope':plus_scope,'plus_id':plus_id
})
else:
return HttpResponseRedirect('/login/?next=%s' % request.path)
def my_courses(request):
if request.user.is_authenticated and request.user != 'AnonymousUser':
courses = LearningActivity.objects.filter(authorlearningactivity__user=request.user, root=None)
return render(request,'activitytree/instructor_home.html',
{'courses': courses
# , 'plus_scope':plus_scope,'plus_id':plus_id
})
else:
return HttpResponseRedirect('/login/?next=%s' % request.path)
def my_enrolled_courses(request):
"""view that determines if user has unfinished courses, and returns the courses"""
if request.user.is_authenticated and request.user != 'AnonymousUser':
RootULAs = UserLearningActivity.objects.filter(learning_activity__root=None, user=request.user)
return render(request,'activitytree/my_enrolled_courses.html',
{'courses': RootULAs})
else:
return HttpResponseRedirect('/login/?next=%s' % request.path)
def course_info(request, course_id):
# Must have credentials
if request.method == 'GET':
mycourse = get_object_or_404(Course, root_id=course_id)
return render(request,'activitytree/course_info.html',
{'course_id': course_id, 'course': mycourse
})
else:
return HttpResponseNotFound('<h1>HTTP METHOD IS NOT VALID</h1>')
def course(request, course_id=None):
# Must have credentials
if request.user.is_authenticated and request.user != 'AnonymousUser':
# POST:
# Add or Delete a New Course
if request.method == 'POST':
# IF course_id then a DELETE
if course_id:
# Get course and delete only if the user or staff
mycourse = None
if not request.user.is_superuser:
mycourse = get_object_or_404(LearningActivity, pk=course_id,
authorlearningactivity__user=request.user)
if (mycourse or request.user.is_superuser):
LearningActivity.objects.filter(root=course_id).delete()
LearningActivity.objects.get(id=course_id).delete()
return HttpResponseRedirect(reverse('my_courses'))
# IF course_uri IS a CREATE or UPDATE
if 'course_uri' in request.POST and 'action' in request.POST:
is_private = 'private' in request.POST
if request.POST['action'] == 'create':
course_id, course_uri = create_empty_course(request.POST['course_uri'], request.user,
request.POST['course_name'],
request.POST['course_short_description'],
is_private)
return HttpResponseRedirect(reverse('course', args=[course_id]))
elif request.POST['action'] == 'update' and 'course_id' in request.POST:
mycourse = get_object_or_404(Course, root_id=request.POST['course_id'],
root__authorlearningactivity__user=request.user)
mycourse.short_description = request.POST['course_short_description']
mycourse.html_description = bleach.clean(request.POST['html_description'], tags=all_tags,
attributes=attrs)
mycourse.save()
mycourse.root.image = request.POST['image_url']
mycourse.root.name = request.POST['course_name']
mycourse.root.save()
return HttpResponseRedirect(reverse('course', args=[request.POST['course_id']]))
return HttpResponseRedirect(reverse('course', args=[course_id]))
else:
return HttpResponseNotFound(u'<h1>Falta información para enviarse a la petición</h1>')
# GET:
# Edit course
elif request.method == 'GET':
if course_id:
# Is yours or you are staff?
mycourse = None
if not request.user.is_superuser:
mycourse = get_object_or_404(Course, root_id=course_id,
root__authorlearningactivity__user=request.user)
if (mycourse or request.user.is_superuser):
return render(request,'activitytree/course_builder.html',
{'course_id': course_id, 'course': mycourse
})
else:
return HttpResponseNotFound('<h1>Course ID not Found</h1>')
else:
# please log in
return HttpResponseRedirect('/login/?next=%s' % request.path)
@login_required()
def profile_tz(request):
if request.is_ajax():
if request.method == 'POST':
data = json.loads(request.body)
if data['method'] == 'upsert':
if hasattr(request.user, 'userprofile'):
request.user.userprofile.timezone = data['tz']
request.user.userprofile.save()
request.user.save()
else:
user_profile = UserProfile(timezone=data['tz'],user=request.user)
user_profile.save()
return HttpResponse(json.dumps({"result": "success", "tz":data['tz'], "error": None}), content_type='application/json')
elif data['method'] == 'delete':
if hasattr(request.user, 'userprofile'):
request.user.userprofile.timezone = None
request.user.userprofile.save()
request.user.save()
# Else dont bother
return HttpResponse(json.dumps({"result": "success", "error": None}),
content_type='application/json')
elif request.method == 'GET':
try:
request.user.userprofile
return HttpResponse(json.dumps({"result": "found",
"tz":request.user.userprofile.timezone,
"experience":request.user.userprofile.experience,
"reputation":request.user.userprofile.reputation
}), content_type='application/json')
except ObjectDoesNotExist:
return HttpResponse(json.dumps( {"result": "not_found", "error": None}), content_type='application/json')
@login_required()
def profile_experience(request):
if request.is_ajax():
if request.method == 'POST':
data = json.loads(request.body)
if data['method'] == 'upsert':
if hasattr(request.user, 'userprofile'):
request.user.userprofile.experience = data['experience']
request.user.userprofile.save()
request.user.save()
else:
user_profile = UserProfile(experience=data['experience'], user=request.user)
user_profile.save()
return HttpResponse(json.dumps({"result": "success", "experience": data['experience'], "error": None}),
content_type='application/json')
elif data['method'] == 'delete':
if hasattr(request.user, 'userprofile'):
request.user.userprofile.experience = None
request.user.userprofile.save()
request.user.save()
# Else dont bother
return HttpResponse(json.dumps({"result": "success", "error": None}),
content_type='application/json')
elif request.method == 'GET':
try:
request.user.userprofile
return HttpResponse(json.dumps({"result": "found",
"experience": request.user.userprofile.experience,
"reputation": request.user.userprofile.reputation
}), content_type='application/json')
except ObjectDoesNotExist:
return HttpResponse(json.dumps({"result": "not_found", "error": None}),
content_type='application/json')
@login_required()
def profile_learning_style(request):
if request.is_ajax():
if request.method == 'POST':
data = json.loads(request.body)
if data['method'] == 'upsert':
if hasattr(request.user, 'learningstyleinventory'):
request.user.learningstyleinventory.visual = data['visual']
request.user.learningstyleinventory.verbal = data['verbal']
request.user.learningstyleinventory.aural = data['aural']
request.user.learningstyleinventory.physical = data['physical']
request.user.learningstyleinventory.logical = data['logical']
request.user.learningstyleinventory.social = data['social']
request.user.learningstyleinventory.solitary = data['solitary']
request.user.learningstyleinventory.save()
request.user.save()
else:
user_learningstyleinventory = LearningStyleInventory(visual=data['visual'],
verbal=data['verbal'],
aural = data['aural'],
physical=data['physical'],
logical=data['logical'],
social=data['social'],
solitary=data['solitary'],
user=request.user)
user_learningstyleinventory.save()
return HttpResponse(
json.dumps({"result": "success", "error": None}),
content_type='application/json')
elif data['method'] == 'delete':
if hasattr(request.user, 'learningstyleinventory'):
# Delete record
# Else dont bother
request.user.learningstyleinventory.delete()
pass
return HttpResponse(json.dumps({"result": "success", "error": None}),
content_type='application/json')
elif request.method == 'GET':
try:
request.user.learningstyleinventory
return HttpResponse(json.dumps({"result": "found",
"visual":request.user.learningstyleinventory.visual,
"verbal" : request.user.learningstyleinventory.verbal,
"aural" : request.user.learningstyleinventory.aural,
"physical" : request.user.learningstyleinventory.physical,
"logical" :request.user.learningstyleinventory.logical,
"social" : request.user.learningstyleinventory.social,
"solitary" : request.user.learningstyleinventory.solitary
}), content_type='application/json')
except ObjectDoesNotExist:
return HttpResponse(json.dumps({"result": "not_found", "error": None}),
content_type='application/json')
# @csrf_exempt
@login_required()
def upload_activity(request): # view that receives activity data and saves it to database
if request.is_ajax():
if request.method == 'POST':
actividad = json.loads(request.body)
client = MongoClient(settings.MONGO_DB)
db = client.protoboard_database
activities_collection = db.activities_collection
if actividad['type'] == 'video':
try:
if not actividad['_id']:
## Is a new activity Generate a Global ID
actividad['_id'] = '/activity/video/' + str(uuid.uuid1())
actividad['content'] = actividad['description']
message = activities_collection.update({'_id': actividad['_id'], 'author': actividad['author']},
actividad, upsert=True)
return HttpResponse(json.dumps(message))
except pymongo.errors.DuplicateKeyError as e:
if e.code == 11000:
return HttpResponse(json.dumps({'message': 'Duplicated'}))
elif actividad['type'] == 'text':
try:
if not actividad['_id']:
## Is a new activity Generate a Global ID
actividad['_id'] = '/activity/' + str(uuid.uuid1())
message = activities_collection.update({'_id': actividad['_id'], 'author': actividad['author']},
actividad, upsert=True)
return HttpResponse(json.dumps(message))
except pymongo.errors.DuplicateKeyError as e:
if e.code == 11000:
return HttpResponse(json.dumps({'message': 'Duplicated'}))
elif actividad['type'] == 'quiz':
try:
if not actividad['_id']:
## Is a new activity Generate a Global ID
actividad['_id'] = '/test/' + str(uuid.uuid1())
message = activities_collection.update({'_id': actividad['_id'], 'author': actividad['author']},
actividad, upsert=True)
return HttpResponse(json.dumps(message))
except pymongo.errors.DuplicateKeyError as e:
if e.code == 11000:
return HttpResponse(json.dumps({'message': 'Duplicated'}))
elif actividad['type'] == 'prog':
try:
if not actividad['_id']:
## Is a new activity Generate a Global ID
actividad['_id'] = '/program/' + str(uuid.uuid1())
## We need to clean the HTML to be rendered to users
actividad['instructions'] = bleach.clean(actividad['instructions'], tags=all_tags, attributes=attrs)
actividad['HTML_code'] = bleach.clean(actividad['HTML_code'], tags=all_tags, attributes=attrs)
message = activities_collection.update({'_id': actividad['_id'], 'author': actividad['author']},
actividad, upsert=True)
return HttpResponse(json.dumps(message))
except pymongo.errors.DuplicateKeyError as e:
if e.code == 11000:
return HttpResponse(json.dumps({'message': 'Duplicated'}))
else:
"Tipo de actividad no existe"
elif request.method == 'GET':
return HttpResponse("Error")
return HttpResponse("Error")
@login_required()
def build_quiz(request):
if request.method == 'POST':
return HttpResponse('Error')
# GET:
# Edit course
elif request.method == 'GET':
return render(request,'activitytree/quiz_builder.html')
else:
return HttpResponseNotFound('<h1>Course ID not Found</h1>')
def search(request):
if request.method == 'GET':
return render(request,'activitytree/search.html')
else:
return HttpResponseNotFound('not found')
def build_program(request):
if request.is_ajax():
if request.method == 'POST':
return HttpResponseRedirect('/build_program')
elif request.method == 'GET':
return render(request,'activitytree/program_builder.html')
else:
if request.method == 'POST':
if request.POST.get('id'):
return HttpResponse('id')
return HttpResponseRedirect('/build_program')
elif request.method == 'GET':
return render(request,'activitytree/program_builder.html')
@login_required()
def activity_builder(request):
if request.method == 'POST':
return HttpResponse('Error')
elif request.method == 'GET':
return render(request,'activitytree/activity_builder.html')
else:
return HttpResponseNotFound('<h1>Course ID not Found</h1>')
def dashboard(request, path_id):
if request.user.is_authenticated:
if request.method == 'GET':
s = SimpleSequencing()
# First, the requested_activity exists??
# Gets the Learning Activity object from uri
requested_activity = None
try:
requested_activity = UserLearningActivity.objects.get(learning_activity__id=path_id, user=request.user)
except (ObjectDoesNotExist, IndexError) as e:
requested_activity = None
if not requested_activity:
return HttpResponseNotFound('<h1>Activity not found</h1>')
# Gets the root of the User Learning Activity
root = UserLearningActivity.objects.get(learning_activity_id=path_id, user=request.user)
# Exits last activity, and sets requested activity as current
# if choice_exit consider complete
_XML = s.get_nav(root)
# Escape for javascript
XML = ET.tostring(_XML, encoding='unicode').replace('"', r'\"') # navegation_tree = s.nav_to_html(nav)
return render(request,'activitytree/dashboard.html', {'XML_NAV': XML,
'children': requested_activity.get_children(),
'uri': root.learning_activity.uri,
'root': root.learning_activity.uri,
'root_id': '/%s' % (root.learning_activity.id,)
})
@csrf_protect
def course_view(request):
if request.user.is_authenticated and request.user != 'AnonymousUser' and request.method == 'POST':
rpc = json.loads(request.body)
if rpc["method"] == 'post_course':
update_course_from_json(json_tree=rpc['params'][0], user=request.user)
result = {"result": "added", "error": None, "id": 1}
return HttpResponse(json.dumps(result), content_type='application/javascript')
elif rpc["method"] == 'get_course':
rpc = json.loads(request.body)
course = get_activity_tree(rpc['params'][0])
return HttpResponse(json.dumps(course), content_type='application/javascript')
else:
result = {"result": "added", "error": "Error", "id": 1}
return HttpResponse(json.dumps(result), content_type='application/javascript')
def get_context(request):
context = {}
if hasattr(request.user, "userprofile"):
context['time_zone'] = request.user.userprofile.timezone
return context
def path_activity(request, path_id, uri):
learning_activity = None
try:
learning_activity = LearningActivity.objects.get(pk=path_id)
except ObjectDoesNotExist:
return HttpResponseNotFound('<h1>Learning Activity not found</h1>')
if request.user.is_authenticated:
root = None
s = SimpleSequencing(context=get_context(request))
requested_activity = None
if request.method == 'GET':
try:
requested_activity = UserLearningActivity.objects.get(learning_activity__id=path_id, user=request.user)
except (ObjectDoesNotExist, IndexError) as e:
requested_activity = None
# The requested_activity was NOT FOUND
if not requested_activity: # The requested_activity was not found
# Maybe a
# 'start' REQUEST?
# if 'nav' in request.GET and request.GET['nav'] == 'start':
if learning_activity and learning_activity.root is None:
s.assignActivityTree(request.user, learning_activity)
requested_activity = UserLearningActivity.objects.get(learning_activity__id=path_id,
user=request.user)
_set_current(request, requested_activity, requested_activity, s)
return HttpResponseRedirect('/%s%s' % (path_id, uri))
# If is not a root learning activity then sorry, not found
else:
return HttpResponseNotFound('<h1>Activity not found</h1>')
# Else NOT FOUND
# else:
# return HttpResponseNotFound('<h1>Activity not found</h1>')
# We have a valid requested_activity, lets handle OTHER NAVIGATION REQUEST
# Get root of activity tree
root = \
UserLearningActivity.objects.filter(learning_activity=requested_activity.learning_activity.get_root(),
user=request.user)[0]
# 'continue' REQUEST?
if requested_activity.is_root() and 'nav' in request.GET and request.GET['nav'] == 'continue':
current_activity = s.get_current(requested_activity)
if current_activity:
requested_activity = current_activity
return HttpResponseRedirect(
'/%s%s' % (requested_activity.learning_activity.id, requested_activity.learning_activity.uri))
else:
_set_current(request, requested_activity, root, s, progress_status=None)
# Else is a
# 'choice' REQUEST
else:
_set_current(request, requested_activity, root, s)
if request.method == 'POST' and 'nav_event' in request.POST:
# Get root of activity tree
root = None
try:
root = UserLearningActivity.objects.get(learning_activity__id=path_id, user=request.user)
except (ObjectDoesNotExist, IndexError) as e:
root = None
if not root or not root.is_root():
return HttpResponseNotFound('<h1>Activity not found</h1>')
current_activity = s.get_current(root)
if current_activity.learning_activity.choice_exit:
progress_status = 'completed'
else:
progress_status = None
next_uri = None
# 'next' REQUEST
if request.POST['nav_event'] == 'next':
# Go TO NEXT ACTIVITY
s.exit(current_activity, progress_status=progress_status)
next_uri = s.get_next(root, current_activity)
# 'prev' REQUEST
elif request.POST['nav_event'] == 'prev':
# Go TO PREV ACTIVITY
s.exit(current_activity, progress_status=progress_status)
next_uri = s.get_prev(root, current_activity)
# No more activities ?
if next_uri is None:
return HttpResponseRedirect('/%s%s' % (root.learning_activity.id, root.learning_activity.uri))
else:
next_activity = UserLearningActivity.objects.get(learning_activity__id=next_uri, user=request.user)
return HttpResponseRedirect(
'/%s%s' % (next_activity.learning_activity.id, next_activity.learning_activity.uri))
_XML = s.get_nav(root)
# Escape for javascript
XML = ET.tostring(_XML, encoding='unicode').replace('"', r'\"')
print('XML:', XML)
breadcrumbs = s.get_current_path(requested_activity)
rating_totals = LearningActivityRating.objects.filter(
learning_activity__uri=requested_activity.learning_activity.uri).aggregate(Count('rating'), Avg('rating'))
activity_content = Activity.get(requested_activity.learning_activity.uri)
if activity_content and 'content' in activity_content:
content = activity_content['content']
else:
content = ""
if (requested_activity.learning_activity.uri).split('/')[2] == 'video':
return render(request, 'activitytree/video.html',
{'XML_NAV': XML,
'uri': requested_activity.learning_activity.uri,
'uri_id': requested_activity.learning_activity.id,
'video': activity_content,
'current_site': get_current_site(request),
'breadcrumbs': breadcrumbs,
'root': requested_activity.learning_activity.get_root().uri,
'root_id': '/%s' % requested_activity.learning_activity.get_root().id,
'rating_totals': rating_totals})
elif requested_activity.learning_activity.is_container:
return render(request,'activitytree/container_list.html',
{
'XML_NAV': XML,
'children': requested_activity.get_children(),
'uri_id': '/%s' % requested_activity.learning_activity.id,
'uri': requested_activity.learning_activity.uri,
'current_site': get_current_site(request),
'content': content,
'root': requested_activity.learning_activity.get_root().uri,
'root_id': '/%s' % requested_activity.learning_activity.get_root().id,
'breadcrumbs': breadcrumbs})
else:
return render(request,'activitytree/activity.html',
{'XML_NAV': XML,
'uri': requested_activity.learning_activity.uri,
'current_site': get_current_site(request),
'uri_id': '/%s' % requested_activity.learning_activity.id,
'content': content,
'root': requested_activity.learning_activity.get_root().uri,
'root_id': '/%s' % requested_activity.learning_activity.get_root().id,
'breadcrumbs': breadcrumbs,
'rating_totals': rating_totals})
else:
print(request.path)
return HttpResponseRedirect('/accounts/login/?next=%s' % request.path)
def activity(request, uri=None):
if request.method == 'GET':
# Check if public, all public for now
if False:
return HttpResponseRedirect('/accounts/login/?next=%s' % request.path)
activity_content = Activity.get('/%s' % uri)
if activity_content and 'content' in activity_content:
content = activity_content['content']
else:
content = ""
if (uri).split('/')[1] == 'video':
return render(request,'activitytree/video.html',
{'XML_NAV': None,
'uri': uri,
'video': activity_content,
'current_site': get_current_site(request),
'breadcrumbs': None})
else:
return render(request,'activitytree/activity.html',
{'XML_NAV': None,
'uri': uri,
'content': content,
'breadcrumbs': None,
'current_site': get_current_site(request)
})
# Do something for anonymous users.
def path_test(request, path_id, uri):
if request.user.is_authenticated:
s = SimpleSequencing(context=get_context(request))
try:
requested_activity = UserLearningActivity.objects.get(learning_activity__id=path_id, user=request.user)
except ObjectDoesNotExist as e:
return HttpResponseNotFound('<h1>Learning Activity not found</h1>')
root = None
try:
root = UserLearningActivity.objects.get(learning_activity=requested_activity.learning_activity.get_root(),
user=request.user)
except (ObjectDoesNotExist, IndexError) as e:
return HttpResponseNotFound('<h1>Path not found</h1>')
feedback = None
# IF 100 attempts there is really no limit
if requested_activity.learning_activity.attempt_limit < 100:
attempts_left = requested_activity.learning_activity.attempt_limit - requested_activity.num_attempts
else:
attempts_left = 100
if request.method == 'GET':
# Exits last activity, and sets requested activity as current
# if choice_exit consider complete
_set_current(request, requested_activity, root, s, progress_status=None)
elif request.method == 'POST':
if 'check' in request.POST and attempts_left:
quiz = Activity.get(requested_activity.learning_activity.uri)
feedback = _check_quiz(request.POST, quiz)
print('feedback',feedback)
# Updates the current Learning Activity
objective_measure = float(feedback['total_correct']) / len(quiz['questions']) * 100
if feedback['total_correct'] >= int(quiz['satisfied_at_least']):
progress_status = 'completed'
else:
progress_status = 'incomplete'
s.update(requested_activity, progress_status=progress_status, attempt=True,
objective_measure=objective_measure)
# IF 100 attempts there is really no limit
if requested_activity.learning_activity.attempt_limit < 100:
attempts_left -= 1
# Gets the current navegation tree as HTML
_XML = s.get_nav(root)
# Escape for javascript
XML = ET.tostring(_XML, encoding='unicode').replace('"', r'\"') # navegation_tree = s.nav_to_html(nav)
rating_totals = LearningActivityRating.objects.filter(
learning_activity__uri=requested_activity.learning_activity.uri).aggregate(Count('rating'), Avg('rating'))
breadcrumbs = s.get_current_path(requested_activity)
test = Activity.get(requested_activity.learning_activity.uri)
if feedback:
for q in test['questions']:
q_id = str(q['id'])
if q_id in feedback:
q['feedback'] = feedback[q_id]
if q['interaction'] in ['choiceInteraction', 'simpleChoice']:
q['feedback_options'] = zip(q['options'], feedback[q_id]['user_answer'],
feedback[q_id]['checked'])
return render(request,'activitytree/' + (requested_activity.learning_activity.uri).split('/')[1] + '.html',
{'XML_NAV': XML,
'uri': requested_activity.learning_activity.uri,
'content': test,
'feedback': feedback,
'breadcrumbs': breadcrumbs,
'uri_id': '/%s' % requested_activity.learning_activity.id,
'attempt_limit': requested_activity.learning_activity.attempt_limit,
'num_attempts': requested_activity.num_attempts,
'attempts_left': attempts_left,
'root_id': '/%s' % requested_activity.learning_activity.get_root().id,
'root': requested_activity.learning_activity.get_root().uri})
else:
return HttpResponseRedirect('/accounts/login/?next=%s' % request.path)
# Do something for anonymous users.
def path_program(request, path_id, uri):
if request.user.is_authenticated:
s = SimpleSequencing(context=get_context(request))
try:
requested_activity = UserLearningActivity.objects.get(learning_activity__id=path_id, user=request.user)
except ObjectDoesNotExist as e:
return HttpResponseNotFound('<h1>Learning Activity not found</h1>')
root = None
try:
root = UserLearningActivity.objects.get(learning_activity=requested_activity.learning_activity.get_root(),
user=request.user)
except (ObjectDoesNotExist, IndexError) as e:
return HttpResponseNotFound('<h1>Path not found</h1>')
if request.method == 'GET':
# Exits last activity, and sets requested activity as current
# if choice_exit consider complete
_set_current(request, requested_activity, root, s)
# Gets the current navegation tree as XML
_XML = s.get_nav(root)
# Escape for javascript
XML = ET.tostring(_XML, encoding='unicode').replace('"', r'\"')
breadcrumbs = s.get_current_path(requested_activity)
program_quiz = Activity.get(requested_activity.learning_activity.uri)
rating_totals = LearningActivityRating.objects.filter(
learning_activity__uri=requested_activity.learning_activity.uri).aggregate(Count('rating'), Avg('rating'))
## TO DO:
## The activity was not found
if program_quiz and program_quiz['lang'] == 'javascript':
template = 'activitytree/programjs.html'
else:
template = 'activitytree/program.html'
return render(request,template, {'program_quiz': program_quiz,
'activity_uri': requested_activity.learning_activity.uri,
'uri_id': '%s' % requested_activity.learning_activity.id,
'uri': requested_activity.learning_activity.uri,
'current_site': get_current_site(request),
'breadcrumbs': breadcrumbs,
'root': requested_activity.learning_activity.get_root().uri,
'root_id': '/%s' % requested_activity.learning_activity.get_root().id,
'XML_NAV': XML, 'rating_totals': rating_totals
})
else:
return HttpResponseRedirect('/accounts/login/?next=%s' % request.path)
@transaction.atomic
def program(request, uri):
program_quiz = Activity.get(request.path)
if program_quiz:
if program_quiz['lang'] == 'javascript':
template = 'activitytree/programjs.html'
else:
template = 'activitytree/program.html'
return render(request,template, {'program_quiz': program_quiz,
'activity_uri': request.path,
'current_site': get_current_site(request),
'breadcrumbs': None,
'root': None,
'XML_NAV': None
})
else:
return HttpResponseNotFound('<h1>Activity not found</h1>')
@transaction.atomic
def test(request, uri):
quiz = Activity.get(request.path)
if quiz:
template = 'activitytree/test.html'
return render(request,template, {
'content': quiz,
'activity_uri': request.path,
'breadcrumbs': None,
'root': None,
'XML_NAV': None
})
else:
return HttpResponseNotFound('<h1>Activity not found</h1>')
@csrf_protect
def test_program(request):
if request.is_ajax():
if request.method == 'POST':
import os
data = json.loads(request.body)
unit_test = data['unit_test']
correct_code = data['correct_code']
try:
logger.error("REDIS:" + os.environ['REDIS_HOST'])
server = Cola(data['lang'])
task = {"id": None, "method": "exec", "params": {"code": correct_code, "test": unit_test}}
logger.error(task)
task_id = server.enqueue(**task)
logger.error(task_id)
result = [{"result": "added", "id": task_id}]
return HttpResponse(json.dumps({"id": task_id}))
except redis.ConnectionError:
return HttpResponse("Redis Conection Error")
else:
return HttpResponse("Error")
@csrf_protect
def execute_queue(request):
# logger.error("VIEW execute_queue")
if request.method == 'POST':
# Read RPC message from client
rpc = json.loads(request.body)
# Get params
# Code to execute
code = rpc["params"][0]
# URI of Activity
activity_uri = rpc["method"]
# Get Activity from MongoDB
program_test = Activity.get(activity_uri)
print('program_test')
print(type(program_test['unit_test']))
#Get Regular Expresion Test (RET) if there is one, if not set to None
retest = ('reg_exp' in program_test and program_test['reg_exp']) or None
#If there is a RET run test
if retest:
test_errors = re_test(code,retest)
if test_errors:
# Return Error
result = {"outcome": 0, "result": { "successes": [], "failures": test_errors,
"errors": [], "result": "Failure", "stdout": ""}}
return HttpResponse(json.dumps(result), content_type='application/javascript' )
# Get Unittest
unit_test = program_test['unit_test']
server = Cola(program_test['lang'])
task = {"id": None, "method": "exec", "params": {"code": code, "test": unit_test}}
logger.debug(task)
task_id = None
try:
task_id = server.enqueue(**task)
except Exception as err:
result = {"result": "error", "error": "Server error: {0}".format(err), "id": task_id,"success": False}
return HttpResponse(json.dumps(result), content_type='application/javascript', status=503)
logger.debug(task_id)
rpc['task_id'] = task_id
if request.user.is_authenticated and 'id' in rpc:
ula = None
try:
ula = UserLearningActivity.objects.get(learning_activity__id=rpc["id"], user=request.user)
s = SimpleSequencing(context=get_context(request))
s.update(ula)
## Mouse Dynamics
event = ULA_Event.objects.create(ULA=ula, context=rpc)
event.save()
except ObjectDoesNotExist:
# Assume is a non assigned program
pass
result = {"result": "added", "error": None, "id": task_id}
return HttpResponse(json.dumps(result), content_type='application/javascript')
@csrf_protect
def javascript_result(request):
if request.method == 'POST':
rpc = json.loads(request.body)
code = rpc["params"][0]
activity_uri = rpc["method"]
program_test = Activity.get(activity_uri)
if request.user.is_authenticated and 'id' in rpc:
ula = None
try:
ula = UserLearningActivity.objects.get(learning_activity__id=rpc["id"], user=request.user)
s = SimpleSequencing(context=get_context(request))
if rpc['result'] == 'Success':
s.update(ula, progress_status='completed', objective_measure=30, attempt=True)
else:
s.update(ula, attempt=True)
# s.update(ula)
## Mouse Dynamics
event = ULA_Event.objects.create(ULA=ula, context=rpc)
event.save()
except ObjectDoesNotExist:
# Assume is a non assigned program
pass
return HttpResponse(json.dumps({}), content_type='application/javascript')
@csrf_protect
def get_result(request):
if request.method == 'POST':
rpc = json.loads(request.body)
# We only need the Task identifier
# TO DO:
task_id = rpc["id"]
# No ID, Task Not Found
if not task_id:
return HttpResponse(json.dumps({'outcome': -1}), content_type='application/javascript')
t = Task(id=task_id)
# outcome:
# -1 No result found
# 0 Sub-process Success
# 1 Sub-process Failure
if t.get_result(task_id.split(':')[0]):
if t.result:
string_json = ""
try:
string_json = json.loads(t.result[0])
except Exception as e:
print ("string_json exception", e)
if request.user.is_authenticated:
try:
ula = UserLearningActivity.objects.get(learning_activity__uri=rpc["params"][0],
user=request.user)
s = SimpleSequencing(context=get_context(request))
if string_json['result'] == 'Success':
s.update(ula, progress_status='completed', objective_measure=30, attempt=True)
else:
s.update(ula, attempt=True)
except Exception as e:
print ("update ULA", e)
result = json.dumps({'result': string_json, 'outcome': t.result[1]})
return HttpResponse(result, content_type='application/javascript')
else:
return HttpResponse(json.dumps({'outcome': -1}), content_type='application/javascript')
else:
return HttpResponse(json.dumps({'outcome': -1}), content_type='application/javascript')
def _get_learning_activity(uri):
try:
la = LearningActivity.objects.get(uri=uri)
except ObjectDoesNotExist:
return None
return la
def _get_ula(request, uri):
try:
la = _get_learning_activity(uri)
if la is None:
return None
except ObjectDoesNotExist:
return None
# Let's get the requested user learning activity
try:
requested_activity = UserLearningActivity.objects.filter(learning_activity__uri=uri, user=request.user)[0]
except (ObjectDoesNotExist, IndexError) as e:
# User does not have a tracking activity tree
# If the requested activity is the root of a tree
# register the user to it
return None
return requested_activity
def _set_current(request, requested_activity, root, s, progress_status=None):
# Sets the requested Learning Activity as current
atree = ActivityTree.objects.get(user=request.user, root_activity=root.learning_activity.get_root())
# Exits last activty
if atree.current_activity:
if request.method == 'GET' and atree.current_activity.learning_activity.choice_exit:
progress_status = 'completed'
s.exit(atree.current_activity, progress_status=progress_status)
s.set_current(requested_activity)
def _check_quiz(post_dict, quiz):
print(post_dict)
print('quiz', quiz)
#answerDict = dict(post_dict.iterlists())
answerDict = dict(post_dict)
print('answerDict',answerDict)
checked = {}
for q in quiz['questions']:
id = str(q['id'])
answer = q['answer']
interaction = q['interaction']
checked[id] = {}
print (id in answerDict)
if interaction in ['choiceInteraction', 'simpleChoice']:
if id in answerDict:
user = answerDict[id]
user_index = [int(a.split("_")[-1]) for a in user]
user_answer = [int(i in user_index) for i in range(len(answer))]
if answer == user_answer:
checked[id]['correct'] = 1
else:
checked[id]['correct'] = 0
checked[id]['checked'] = [(user_answer[i] == answer[i]) and (answer[i] == 1) for i in
range(len(answer))]
checked[id]['user_answer'] = user_answer
else:
checked[id]['correct'] = 0
checked[id]['checked'] = [False for _ in range(len(answer))]
checked[id]['user_answer'] = [0 for _ in range(len(answer))]
elif interaction in ['textEntryInteraction']:
if id in answerDict:
user_answer = answerDict[id][0]
checked[id]['user_answer'] = user_answer
if user_answer in answer:
checked[id]['correct'] = 1
else:
checked[id]['correct'] = 0
checked['total_correct'] = sum([float(checked[key]['correct']) for key in checked if key not in ['checked']])
print ('checked',checked)
return checked
def _check_survey(post_dict, quiz):
answerDict = dict(post_dict.iterlists())
checked = {}
for q in quiz['questions']:
id = q['id']
answer = q['answer']
interaction = q['interaction']
checked[id] = {}
if interaction in ['choiceInteraction', 'simpleChoice']:
if unicode(id) in answerDict:
user = answerDict[unicode(id)]
user_index = [int(a.split("_")[-1]) for a in user]
user_answer = [int(i in user_index) for i in range(len(answer))]
if 1 in user_answer:
checked[id]['correct'] = 1
else:
checked[id]['correct'] = 0
checked[id]['checked'] = [(user_answer[i] == answer[i]) and (answer[i] == 1) for i in
range(len(answer))]
checked[id]['user_answer'] = user_answer
else:
checked[id]['correct'] = 0
checked[id]['checked'] = [False for _ in range(len(answer))]
checked[id]['user_answer'] = [0 for _ in range(len(answer))]
elif interaction in ['textEntryInteraction']:
if unicode(id) in answerDict:
user_answer = answerDict[unicode(id)][0]
checked[id]['user_answer'] = user_answer
if True:
checked[id]['correct'] = 1
else:
checked[id]['correct'] = 0
checked['total_correct'] = sum([float(checked[key]['correct']) for key in checked if key not in ['checked']])
return checked
def ajax_vote(request, type, uri):
activity_uri = request.path[len('/ajax_vote'):]
if request.user.is_authenticated:
if request.method == 'POST':
activity = UserLearningActivity.objects.filter(learning_activity__uri=activity_uri, user=request.user)[0]
activity.user_rating = int(request.POST['rate'])
activity.save()
vals = UserLearningActivity.objects.filter(learning_activity__uri=activity_uri).aggregate(Avg('user_rating'),
Count('user_rating'))
response_data = {'avg': vals['user_rating__avg'], 'votes': vals['user_rating__count']}
return HttpResponse(json.dumps(response_data), content_type="application/json")
else:
return HttpResponse(content="Ya voto?")
def register(request):
if request.method == 'POST':
f = UserCreationForm(request.POST)
if f.is_valid():
f.save()
username = f.cleaned_data.get('username')
raw_password = f.cleaned_data.get('password1')
user = authenticate(username=username, password=<PASSWORD>)
login(request, user)
return HttpResponseRedirect('/welcome/')
else:
f = UserCreationForm()
return render(request, 'registration/registration_form.html', {'form': f})
def get_new_activities(request):
activities = Activity.get_new()
json_docs = [doc for doc in activities]
return HttpResponse(json.dumps(json_docs), content_type='application/javascript')
def get_front_page_activities(request):
activities = Activity.get_frontpage()
json_docs = [doc for doc in activities]
return HttpResponse(json.dumps(json_docs), content_type='application/javascript')
@login_required
def my_activities(request): # view used by activity_builder, returns all activities by user
print(request)
client = MongoClient(settings.MONGO_DB)
db = client.protoboard_database
activities_collection = db.activities_collection
user = request.GET['user']
page = int(request.GET['page'])
if request.user.is_superuser:
print("super")
activities = Activity.get_by_admin(page)
count = activities_collection.find({},
{'_id': 1, 'title': 1, 'lang': 1, 'type': 1, 'description': 1, 'icon': 1,
'level': 1, 'tags': 1}).sort("$natural", pymongo.DESCENDING).count()
else:
activities = Activity.get_by_user(user, page)
count = activities_collection.find({'author': user},
{'_id': 1, 'title': 1, 'lang': 1, 'type': 1, 'description': 1, 'icon': 1,
'level': 1, 'tags': 1}).sort("$natural", pymongo.DESCENDING).count()
count = {'count': count}
json_docs = [doc for doc in activities]
json_docs.append(count)
return HttpResponse(json.dumps(json_docs), content_type='application/javascript')
@csrf_exempt
def search_prueba(request): # view used by search, receives page and query and returns count of docs and activities
MONGO_PAGE_SIZE = 20
client = MongoClient(settings.MONGO_DB)
db = client.protoboard_database
activities_collection = db.activities_collection
actividad = json.loads(request.body)
query = []
page = 0
for k, v in actividad.items():
if k == 'page':
page = v
else:
query.append(v)
print(query)
if len(query) == 0:
message = "null"
return HttpResponse(json.dumps(message), content_type='application/javascript')
else:
print(query)
# IF Super user return all activities
if request.user.is_superuser:
query = [ e for e in query if 'author' not in e ]
activities = activities_collection.find({'$and': query},
{'_id': 1, 'title': 1, 'lang': 1, 'type': 1, 'description': 1,
'icon': 1, 'level': 1, 'tags': 1, 'image_url': 1}).sort("$natural",
pymongo.DESCENDING).limit(
MONGO_PAGE_SIZE).skip(page * MONGO_PAGE_SIZE)
count = activities_collection.find({'$and': query},
{'_id': 1, 'title': 1, 'lang': 1, 'type': 1, 'description': 1, 'icon': 1,
'level': 1, 'tags': 1, 'image_url': 1}).sort("$natural",
pymongo.DESCENDING).count()
count = {'count': count}
json_docs = [doc for doc in activities]
json_docs.append(count)
return HttpResponse(json.dumps(json_docs), content_type='application/javascript')
def check_activity(request): # view that checks if activity id already exists
actividad = Activity.get_title(request.GET['valor'])
json_docs = [doc for doc in actividad]
return HttpResponse(json.dumps(json_docs), content_type='application/javascript')
@login_required
def delActivity(request): # view that receives user and id of activity to be deleted
if request.method == 'POST':
user = request.POST['user']
_id = request.POST['_id']
if request.user.is_superuser:
try:
message = Activity.del_activity_admin(_id)
return HttpResponse(message.deleted_count)
except Exception as e:
return HttpResponse("error",e)
else:
try:
message = Activity.del_activity(_id, user)
return HttpResponse(message.deleted_count)
except Exception as e:
return HttpResponse(e)
def get_activity(request):
if request.method == 'GET':
# We first get the Activity
_id = request.GET['_id']
try:
mongo_answer = Activity.get_activity(_id)
activity = mongo_answer[0]
# Are you AnonymousUser?
if request.user == 'AnonymousUser' or not hasattr(request.user, 'email') or activity[
'author'] != request.user.email:
# Its not yours, you can have it read_only
activity['readonly'] = 'readonly'
return HttpResponse(json.dumps([activity]), content_type='application/javascript')
except Exception as e:
return HttpResponse(e)
else:
actividad = json.loads(request.body)
_id = actividad['_id']
user = actividad['author']
type = actividad['type']
try:
message = Activity.get_activity(_id, user)
json_docs = [doc for doc in message]
return HttpResponse(json.dumps(json_docs), content_type='application/javascript')
except Exception as e:
return HttpResponse(e)
@login_required
def users(request, user_id=None, course_id=None, ):
if user_id == None or user_id == "":
users = User.objects.all()
return render(request,'activitytree/users.html', {'users': users})
elif course_id == None or course_id == "":
user = User.objects.get(pk=user_id)
cursos = user.activitytree_set.all()
return render(request,'activitytree/user.html', {'user': user, 'cursos': user})
else:
user = User.objects.get(pk=user_id)
# Gets the current navegation tree as HTML
root = None
try:
root = UserLearningActivity.objects.get(learning_activity__id=course_id, user=user_id)
except (ObjectDoesNotExist, IndexError) as e:
root = None
s = SimpleSequencing(context=get_context(request))
_XML = s.get_nav(root)
# Escape for javascript
XML = ET.tostring(_XML, encoding='unicode').replace('"', r'\"')
return render(request,'activitytree/dashboard.html', {'user': user, 'XML_NAV': XML})
@login_required
def me(request):
if request.method == 'GET':
return render(request,'activitytree/me.html', {'time':timezone.now()})
if request.method == 'POST':
try:
request.user.username = request.POST["username"]
request.user.first_name = request.POST["first_name"]
request.user.last_name = request.POST["last_name"]
request.user.email = request.POST["email"]
request.user.save()
except:
return JsonResponse({"error": True})
return JsonResponse({"success": True, "error": None})
@csrf_exempt
def upload_course(request):
if request.method == 'POST':
# We need a Course ID
if request.POST and 'course_id' in request.POST:
json_course = request.FILES['fileToUpload'].read()
upload_course_from_json(json_course, request.POST['course_id'], request.user)
request.FILES['fileToUpload'].close()
result = {"result": "added", "error": None, "id": None}
return HttpResponse(json.dumps(result), content_type='application/javascript')
else:
# We can create a NEW empty course?
result = {"result": "error", "error": "No course id supplied", "id": None}
return HttpResponse(json.dumps(result), content_type='application/javascript')
else:
# We can create a NEW empty course?
result = {"result": "error", "error": "Only PUT is supported", "id": None}
return HttpResponse(json.dumps(result), content_type='application/javascript')
@csrf_protect
def rate_object(request):
if request.method == 'POST':
vote = json.loads(request.body)
la = LearningActivity.objects.get(uri=vote["uri"])
rating = LearningActivityRating(user=request.user, learning_activity=la, rating=vote["rating"], context=0)
rating.save()
result = {"result": "added", "error": None, "id": None}
return HttpResponse(json.dumps(result), content_type='application/javascript')
@login_required
def logout_view(request):
# Log a user out using Django's logout function and redirect them
# back to the homepage.
logout(request)
return HttpResponseRedirect('/')
|
<reponame>tanxujie/AKunZhuBaoZip<gh_stars>0
import { AppDetails, IApp, IClient, IPaginator, Response } from '../definitions';
export declare class App implements IApp {
token: string;
protected client: IClient;
constructor(token: string, client: IClient);
load(app_id: string): Promise<AppDetails>;
list(): IPaginator<Response<AppDetails[]>>;
create({name}: {
name: string;
}): Promise<AppDetails>;
}
|
<reponame>leodotcloud/go-zendesk
package zendesk
// Code generated by mockery v1.0.0. DO NOT EDIT.
import io "io"
import mock "github.com/stretchr/testify/mock"
// MockClient is an autogenerated mock type for the Client type
type MockClient struct {
mock.Mock
}
// AddUserTags provides a mock function with given fields: _a0, _a1
func (_m *MockClient) AddUserTags(_a0 int64, _a1 []string) ([]string, error) {
ret := _m.Called(_a0, _a1)
var r0 []string
if rf, ok := ret.Get(0).(func(int64, []string) []string); ok {
r0 = rf(_a0, _a1)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).([]string)
}
}
var r1 error
if rf, ok := ret.Get(1).(func(int64, []string) error); ok {
r1 = rf(_a0, _a1)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// AutocompleteOrganizations provides a mock function with given fields: _a0
func (_m *MockClient) AutocompleteOrganizations(_a0 string) ([]Organization, error) {
ret := _m.Called(_a0)
var r0 []Organization
if rf, ok := ret.Get(0).(func(string) []Organization); ok {
r0 = rf(_a0)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).([]Organization)
}
}
var r1 error
if rf, ok := ret.Get(1).(func(string) error); ok {
r1 = rf(_a0)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// BatchUpdateManyTickets provides a mock function with given fields: _a0
func (_m *MockClient) BatchUpdateManyTickets(_a0 []Ticket) error {
ret := _m.Called(_a0)
var r0 error
if rf, ok := ret.Get(0).(func([]Ticket) error); ok {
r0 = rf(_a0)
} else {
r0 = ret.Error(0)
}
return r0
}
// BulkUpdateManyTickets provides a mock function with given fields: _a0, _a1
func (_m *MockClient) BulkUpdateManyTickets(_a0 []int64, _a1 *Ticket) error {
ret := _m.Called(_a0, _a1)
var r0 error
if rf, ok := ret.Get(0).(func([]int64, *Ticket) error); ok {
r0 = rf(_a0, _a1)
} else {
r0 = ret.Error(0)
}
return r0
}
// CreateIdentity provides a mock function with given fields: _a0, _a1
func (_m *MockClient) CreateIdentity(_a0 int64, _a1 *UserIdentity) (*UserIdentity, error) {
ret := _m.Called(_a0, _a1)
var r0 *UserIdentity
if rf, ok := ret.Get(0).(func(int64, *UserIdentity) *UserIdentity); ok {
r0 = rf(_a0, _a1)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).(*UserIdentity)
}
}
var r1 error
if rf, ok := ret.Get(1).(func(int64, *UserIdentity) error); ok {
r1 = rf(_a0, _a1)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// CreateOrUpdateOrganization provides a mock function with given fields: _a0
func (_m *MockClient) CreateOrUpdateOrganization(_a0 *Organization) (*Organization, error) {
ret := _m.Called(_a0)
var r0 *Organization
if rf, ok := ret.Get(0).(func(*Organization) *Organization); ok {
r0 = rf(_a0)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).(*Organization)
}
}
var r1 error
if rf, ok := ret.Get(1).(func(*Organization) error); ok {
r1 = rf(_a0)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// CreateOrUpdateUser provides a mock function with given fields: _a0
func (_m *MockClient) CreateOrUpdateUser(_a0 *User) (*User, error) {
ret := _m.Called(_a0)
var r0 *User
if rf, ok := ret.Get(0).(func(*User) *User); ok {
r0 = rf(_a0)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).(*User)
}
}
var r1 error
if rf, ok := ret.Get(1).(func(*User) error); ok {
r1 = rf(_a0)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// CreateOrganization provides a mock function with given fields: _a0
func (_m *MockClient) CreateOrganization(_a0 *Organization) (*Organization, error) {
ret := _m.Called(_a0)
var r0 *Organization
if rf, ok := ret.Get(0).(func(*Organization) *Organization); ok {
r0 = rf(_a0)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).(*Organization)
}
}
var r1 error
if rf, ok := ret.Get(1).(func(*Organization) error); ok {
r1 = rf(_a0)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// CreateOrganizationMembership provides a mock function with given fields: _a0
func (_m *MockClient) CreateOrganizationMembership(_a0 *OrganizationMembership) (*OrganizationMembership, error) {
ret := _m.Called(_a0)
var r0 *OrganizationMembership
if rf, ok := ret.Get(0).(func(*OrganizationMembership) *OrganizationMembership); ok {
r0 = rf(_a0)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).(*OrganizationMembership)
}
}
var r1 error
if rf, ok := ret.Get(1).(func(*OrganizationMembership) error); ok {
r1 = rf(_a0)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// CreateTicket provides a mock function with given fields: _a0
func (_m *MockClient) CreateTicket(_a0 *Ticket) (*Ticket, error) {
ret := _m.Called(_a0)
var r0 *Ticket
if rf, ok := ret.Get(0).(func(*Ticket) *Ticket); ok {
r0 = rf(_a0)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).(*Ticket)
}
}
var r1 error
if rf, ok := ret.Get(1).(func(*Ticket) error); ok {
r1 = rf(_a0)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// CreateUser provides a mock function with given fields: _a0
func (_m *MockClient) CreateUser(_a0 *User) (*User, error) {
ret := _m.Called(_a0)
var r0 *User
if rf, ok := ret.Get(0).(func(*User) *User); ok {
r0 = rf(_a0)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).(*User)
}
}
var r1 error
if rf, ok := ret.Get(1).(func(*User) error); ok {
r1 = rf(_a0)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// DeleteIdentity provides a mock function with given fields: _a0, _a1
func (_m *MockClient) DeleteIdentity(_a0 int64, _a1 int64) error {
ret := _m.Called(_a0, _a1)
var r0 error
if rf, ok := ret.Get(0).(func(int64, int64) error); ok {
r0 = rf(_a0, _a1)
} else {
r0 = ret.Error(0)
}
return r0
}
// DeleteOrganization provides a mock function with given fields: _a0
func (_m *MockClient) DeleteOrganization(_a0 int64) error {
ret := _m.Called(_a0)
var r0 error
if rf, ok := ret.Get(0).(func(int64) error); ok {
r0 = rf(_a0)
} else {
r0 = ret.Error(0)
}
return r0
}
// DeleteOrganizationMembershipByID provides a mock function with given fields: _a0
func (_m *MockClient) DeleteOrganizationMembershipByID(_a0 int64) error {
ret := _m.Called(_a0)
var r0 error
if rf, ok := ret.Get(0).(func(int64) error); ok {
r0 = rf(_a0)
} else {
r0 = ret.Error(0)
}
return r0
}
// DeleteTicket provides a mock function with given fields: _a0
func (_m *MockClient) DeleteTicket(_a0 int64) error {
ret := _m.Called(_a0)
var r0 error
if rf, ok := ret.Get(0).(func(int64) error); ok {
r0 = rf(_a0)
} else {
r0 = ret.Error(0)
}
return r0
}
// DeleteUser provides a mock function with given fields: _a0
func (_m *MockClient) DeleteUser(_a0 int64) (*User, error) {
ret := _m.Called(_a0)
var r0 *User
if rf, ok := ret.Get(0).(func(int64) *User); ok {
r0 = rf(_a0)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).(*User)
}
}
var r1 error
if rf, ok := ret.Get(1).(func(int64) error); ok {
r1 = rf(_a0)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// ListIdentities provides a mock function with given fields: _a0
func (_m *MockClient) ListIdentities(_a0 int64) ([]UserIdentity, error) {
ret := _m.Called(_a0)
var r0 []UserIdentity
if rf, ok := ret.Get(0).(func(int64) []UserIdentity); ok {
r0 = rf(_a0)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).([]UserIdentity)
}
}
var r1 error
if rf, ok := ret.Get(1).(func(int64) error); ok {
r1 = rf(_a0)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// ListLocales provides a mock function with given fields:
func (_m *MockClient) ListLocales() ([]Locale, error) {
ret := _m.Called()
var r0 []Locale
if rf, ok := ret.Get(0).(func() []Locale); ok {
r0 = rf()
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).([]Locale)
}
}
var r1 error
if rf, ok := ret.Get(1).(func() error); ok {
r1 = rf()
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// ListOrganizationMembershipsByUserID provides a mock function with given fields: id
func (_m *MockClient) ListOrganizationMembershipsByUserID(id int64) ([]OrganizationMembership, error) {
ret := _m.Called(id)
var r0 []OrganizationMembership
if rf, ok := ret.Get(0).(func(int64) []OrganizationMembership); ok {
r0 = rf(id)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).([]OrganizationMembership)
}
}
var r1 error
if rf, ok := ret.Get(1).(func(int64) error); ok {
r1 = rf(id)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// ListOrganizationTickets provides a mock function with given fields: _a0, _a1, _a2
func (_m *MockClient) ListOrganizationTickets(_a0 int64, _a1 *ListOptions, _a2 ...SideLoad) (*ListResponse, error) {
_va := make([]interface{}, len(_a2))
for _i := range _a2 {
_va[_i] = _a2[_i]
}
var _ca []interface{}
_ca = append(_ca, _a0, _a1)
_ca = append(_ca, _va...)
ret := _m.Called(_ca...)
var r0 *ListResponse
if rf, ok := ret.Get(0).(func(int64, *ListOptions, ...SideLoad) *ListResponse); ok {
r0 = rf(_a0, _a1, _a2...)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).(*ListResponse)
}
}
var r1 error
if rf, ok := ret.Get(1).(func(int64, *ListOptions, ...SideLoad) error); ok {
r1 = rf(_a0, _a1, _a2...)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// ListOrganizationUsers provides a mock function with given fields: _a0, _a1
func (_m *MockClient) ListOrganizationUsers(_a0 int64, _a1 *ListUsersOptions) ([]User, error) {
ret := _m.Called(_a0, _a1)
var r0 []User
if rf, ok := ret.Get(0).(func(int64, *ListUsersOptions) []User); ok {
r0 = rf(_a0, _a1)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).([]User)
}
}
var r1 error
if rf, ok := ret.Get(1).(func(int64, *ListUsersOptions) error); ok {
r1 = rf(_a0, _a1)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// ListOrganizations provides a mock function with given fields: _a0
func (_m *MockClient) ListOrganizations(_a0 *ListOptions) ([]Organization, error) {
ret := _m.Called(_a0)
var r0 []Organization
if rf, ok := ret.Get(0).(func(*ListOptions) []Organization); ok {
r0 = rf(_a0)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).([]Organization)
}
}
var r1 error
if rf, ok := ret.Get(1).(func(*ListOptions) error); ok {
r1 = rf(_a0)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// ListRequestedTickets provides a mock function with given fields: _a0
func (_m *MockClient) ListRequestedTickets(_a0 int64) ([]Ticket, error) {
ret := _m.Called(_a0)
var r0 []Ticket
if rf, ok := ret.Get(0).(func(int64) []Ticket); ok {
r0 = rf(_a0)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).([]Ticket)
}
}
var r1 error
if rf, ok := ret.Get(1).(func(int64) error); ok {
r1 = rf(_a0)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// ListTicketComments provides a mock function with given fields: _a0
func (_m *MockClient) ListTicketComments(_a0 int64) ([]TicketComment, error) {
ret := _m.Called(_a0)
var r0 []TicketComment
if rf, ok := ret.Get(0).(func(int64) []TicketComment); ok {
r0 = rf(_a0)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).([]TicketComment)
}
}
var r1 error
if rf, ok := ret.Get(1).(func(int64) error); ok {
r1 = rf(_a0)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// ListTicketFields provides a mock function with given fields:
func (_m *MockClient) ListTicketFields() ([]TicketField, error) {
ret := _m.Called()
var r0 []TicketField
if rf, ok := ret.Get(0).(func() []TicketField); ok {
r0 = rf()
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).([]TicketField)
}
}
var r1 error
if rf, ok := ret.Get(1).(func() error); ok {
r1 = rf()
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// ListTicketIncidents provides a mock function with given fields: _a0
func (_m *MockClient) ListTicketIncidents(_a0 int64) ([]Ticket, error) {
ret := _m.Called(_a0)
var r0 []Ticket
if rf, ok := ret.Get(0).(func(int64) []Ticket); ok {
r0 = rf(_a0)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).([]Ticket)
}
}
var r1 error
if rf, ok := ret.Get(1).(func(int64) error); ok {
r1 = rf(_a0)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// ListUsers provides a mock function with given fields: _a0
func (_m *MockClient) ListUsers(_a0 *ListUsersOptions) ([]User, error) {
ret := _m.Called(_a0)
var r0 []User
if rf, ok := ret.Get(0).(func(*ListUsersOptions) []User); ok {
r0 = rf(_a0)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).([]User)
}
}
var r1 error
if rf, ok := ret.Get(1).(func(*ListUsersOptions) error); ok {
r1 = rf(_a0)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// PermanentlyDeleteTicket provides a mock function with given fields: _a0
func (_m *MockClient) PermanentlyDeleteTicket(_a0 int64) (*JobStatus, error) {
ret := _m.Called(_a0)
var r0 *JobStatus
if rf, ok := ret.Get(0).(func(int64) *JobStatus); ok {
r0 = rf(_a0)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).(*JobStatus)
}
}
var r1 error
if rf, ok := ret.Get(1).(func(int64) error); ok {
r1 = rf(_a0)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// PermanentlyDeleteUser provides a mock function with given fields: _a0
func (_m *MockClient) PermanentlyDeleteUser(_a0 int64) (*User, error) {
ret := _m.Called(_a0)
var r0 *User
if rf, ok := ret.Get(0).(func(int64) *User); ok {
r0 = rf(_a0)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).(*User)
}
}
var r1 error
if rf, ok := ret.Get(1).(func(int64) error); ok {
r1 = rf(_a0)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// RedactCommentString provides a mock function with given fields: _a0, _a1, _a2
func (_m *MockClient) RedactCommentString(_a0 int64, _a1 int64, _a2 string) (*TicketComment, error) {
ret := _m.Called(_a0, _a1, _a2)
var r0 *TicketComment
if rf, ok := ret.Get(0).(func(int64, int64, string) *TicketComment); ok {
r0 = rf(_a0, _a1, _a2)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).(*TicketComment)
}
}
var r1 error
if rf, ok := ret.Get(1).(func(int64, int64, string) error); ok {
r1 = rf(_a0, _a1, _a2)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// SearchOrganizationsByExternalID provides a mock function with given fields: _a0
func (_m *MockClient) SearchOrganizationsByExternalID(_a0 string) ([]Organization, error) {
ret := _m.Called(_a0)
var r0 []Organization
if rf, ok := ret.Get(0).(func(string) []Organization); ok {
r0 = rf(_a0)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).([]Organization)
}
}
var r1 error
if rf, ok := ret.Get(1).(func(string) error); ok {
r1 = rf(_a0)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// SearchTickets provides a mock function with given fields: _a0, _a1, _a2
func (_m *MockClient) SearchTickets(_a0 string, _a1 *ListOptions, _a2 ...Filters) (*TicketSearchResults, error) {
_va := make([]interface{}, len(_a2))
for _i := range _a2 {
_va[_i] = _a2[_i]
}
var _ca []interface{}
_ca = append(_ca, _a0, _a1)
_ca = append(_ca, _va...)
ret := _m.Called(_ca...)
var r0 *TicketSearchResults
if rf, ok := ret.Get(0).(func(string, *ListOptions, ...Filters) *TicketSearchResults); ok {
r0 = rf(_a0, _a1, _a2...)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).(*TicketSearchResults)
}
}
var r1 error
if rf, ok := ret.Get(1).(func(string, *ListOptions, ...Filters) error); ok {
r1 = rf(_a0, _a1, _a2...)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// SearchUserByExternalID provides a mock function with given fields: _a0
func (_m *MockClient) SearchUserByExternalID(_a0 string) (*User, error) {
ret := _m.Called(_a0)
var r0 *User
if rf, ok := ret.Get(0).(func(string) *User); ok {
r0 = rf(_a0)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).(*User)
}
}
var r1 error
if rf, ok := ret.Get(1).(func(string) error); ok {
r1 = rf(_a0)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// SearchUsers provides a mock function with given fields: _a0
func (_m *MockClient) SearchUsers(_a0 string) ([]User, error) {
ret := _m.Called(_a0)
var r0 []User
if rf, ok := ret.Get(0).(func(string) []User); ok {
r0 = rf(_a0)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).([]User)
}
}
var r1 error
if rf, ok := ret.Get(1).(func(string) error); ok {
r1 = rf(_a0)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// ShowComplianceDeletionStatuses provides a mock function with given fields: _a0
func (_m *MockClient) ShowComplianceDeletionStatuses(_a0 int64) ([]ComplianceDeletionStatus, error) {
ret := _m.Called(_a0)
var r0 []ComplianceDeletionStatus
if rf, ok := ret.Get(0).(func(int64) []ComplianceDeletionStatus); ok {
r0 = rf(_a0)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).([]ComplianceDeletionStatus)
}
}
var r1 error
if rf, ok := ret.Get(1).(func(int64) error); ok {
r1 = rf(_a0)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// ShowIdentity provides a mock function with given fields: _a0, _a1
func (_m *MockClient) ShowIdentity(_a0 int64, _a1 int64) (*UserIdentity, error) {
ret := _m.Called(_a0, _a1)
var r0 *UserIdentity
if rf, ok := ret.Get(0).(func(int64, int64) *UserIdentity); ok {
r0 = rf(_a0, _a1)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).(*UserIdentity)
}
}
var r1 error
if rf, ok := ret.Get(1).(func(int64, int64) error); ok {
r1 = rf(_a0, _a1)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// ShowJobStatus provides a mock function with given fields: _a0
func (_m *MockClient) ShowJobStatus(_a0 string) (*JobStatus, error) {
ret := _m.Called(_a0)
var r0 *JobStatus
if rf, ok := ret.Get(0).(func(string) *JobStatus); ok {
r0 = rf(_a0)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).(*JobStatus)
}
}
var r1 error
if rf, ok := ret.Get(1).(func(string) error); ok {
r1 = rf(_a0)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// ShowLocale provides a mock function with given fields: _a0
func (_m *MockClient) ShowLocale(_a0 int64) (*Locale, error) {
ret := _m.Called(_a0)
var r0 *Locale
if rf, ok := ret.Get(0).(func(int64) *Locale); ok {
r0 = rf(_a0)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).(*Locale)
}
}
var r1 error
if rf, ok := ret.Get(1).(func(int64) error); ok {
r1 = rf(_a0)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// ShowLocaleByCode provides a mock function with given fields: _a0
func (_m *MockClient) ShowLocaleByCode(_a0 string) (*Locale, error) {
ret := _m.Called(_a0)
var r0 *Locale
if rf, ok := ret.Get(0).(func(string) *Locale); ok {
r0 = rf(_a0)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).(*Locale)
}
}
var r1 error
if rf, ok := ret.Get(1).(func(string) error); ok {
r1 = rf(_a0)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// ShowManyUsers provides a mock function with given fields: _a0
func (_m *MockClient) ShowManyUsers(_a0 []int64) ([]User, error) {
ret := _m.Called(_a0)
var r0 []User
if rf, ok := ret.Get(0).(func([]int64) []User); ok {
r0 = rf(_a0)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).([]User)
}
}
var r1 error
if rf, ok := ret.Get(1).(func([]int64) error); ok {
r1 = rf(_a0)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// ShowOrganization provides a mock function with given fields: _a0
func (_m *MockClient) ShowOrganization(_a0 int64) (*Organization, error) {
ret := _m.Called(_a0)
var r0 *Organization
if rf, ok := ret.Get(0).(func(int64) *Organization); ok {
r0 = rf(_a0)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).(*Organization)
}
}
var r1 error
if rf, ok := ret.Get(1).(func(int64) error); ok {
r1 = rf(_a0)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// ShowTicket provides a mock function with given fields: _a0
func (_m *MockClient) ShowTicket(_a0 int64) (*Ticket, error) {
ret := _m.Called(_a0)
var r0 *Ticket
if rf, ok := ret.Get(0).(func(int64) *Ticket); ok {
r0 = rf(_a0)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).(*Ticket)
}
}
var r1 error
if rf, ok := ret.Get(1).(func(int64) error); ok {
r1 = rf(_a0)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// ShowUser provides a mock function with given fields: _a0
func (_m *MockClient) ShowUser(_a0 int64) (*User, error) {
ret := _m.Called(_a0)
var r0 *User
if rf, ok := ret.Get(0).(func(int64) *User); ok {
r0 = rf(_a0)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).(*User)
}
}
var r1 error
if rf, ok := ret.Get(1).(func(int64) error); ok {
r1 = rf(_a0)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// UpdateIdentity provides a mock function with given fields: _a0, _a1, _a2
func (_m *MockClient) UpdateIdentity(_a0 int64, _a1 int64, _a2 *UserIdentity) (*UserIdentity, error) {
ret := _m.Called(_a0, _a1, _a2)
var r0 *UserIdentity
if rf, ok := ret.Get(0).(func(int64, int64, *UserIdentity) *UserIdentity); ok {
r0 = rf(_a0, _a1, _a2)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).(*UserIdentity)
}
}
var r1 error
if rf, ok := ret.Get(1).(func(int64, int64, *UserIdentity) error); ok {
r1 = rf(_a0, _a1, _a2)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// UpdateOrganization provides a mock function with given fields: _a0, _a1
func (_m *MockClient) UpdateOrganization(_a0 int64, _a1 *Organization) (*Organization, error) {
ret := _m.Called(_a0, _a1)
var r0 *Organization
if rf, ok := ret.Get(0).(func(int64, *Organization) *Organization); ok {
r0 = rf(_a0, _a1)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).(*Organization)
}
}
var r1 error
if rf, ok := ret.Get(1).(func(int64, *Organization) error); ok {
r1 = rf(_a0, _a1)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// UpdateTicket provides a mock function with given fields: _a0, _a1
func (_m *MockClient) UpdateTicket(_a0 int64, _a1 *Ticket) (*Ticket, error) {
ret := _m.Called(_a0, _a1)
var r0 *Ticket
if rf, ok := ret.Get(0).(func(int64, *Ticket) *Ticket); ok {
r0 = rf(_a0, _a1)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).(*Ticket)
}
}
var r1 error
if rf, ok := ret.Get(1).(func(int64, *Ticket) error); ok {
r1 = rf(_a0, _a1)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// UpdateUser provides a mock function with given fields: _a0, _a1
func (_m *MockClient) UpdateUser(_a0 int64, _a1 *User) (*User, error) {
ret := _m.Called(_a0, _a1)
var r0 *User
if rf, ok := ret.Get(0).(func(int64, *User) *User); ok {
r0 = rf(_a0, _a1)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).(*User)
}
}
var r1 error
if rf, ok := ret.Get(1).(func(int64, *User) error); ok {
r1 = rf(_a0, _a1)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// UploadFile provides a mock function with given fields: _a0, _a1, _a2
func (_m *MockClient) UploadFile(_a0 string, _a1 *string, _a2 io.Reader) (*Upload, error) {
ret := _m.Called(_a0, _a1, _a2)
var r0 *Upload
if rf, ok := ret.Get(0).(func(string, *string, io.Reader) *Upload); ok {
r0 = rf(_a0, _a1, _a2)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).(*Upload)
}
}
var r1 error
if rf, ok := ret.Get(1).(func(string, *string, io.Reader) error); ok {
r1 = rf(_a0, _a1, _a2)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// WithHeader provides a mock function with given fields: name, value
func (_m *MockClient) WithHeader(name string, value string) Client {
ret := _m.Called(name, value)
var r0 Client
if rf, ok := ret.Get(0).(func(string, string) Client); ok {
r0 = rf(name, value)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).(Client)
}
}
return r0
}
|
/*
* Copyright (C) 2015 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.cloud.dataflow.sdk.runners.worker.logging;
import static com.google.cloud.dataflow.sdk.runners.worker.logging.DataflowWorkerLoggingInitializer.LEVELS;
import com.google.common.base.MoreObjects;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.ISODateTimeFormat;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.logging.Formatter;
import java.util.logging.LogRecord;
/**
* Formats {@link LogRecord} into the following format:
* ISO8601Date LogLevel JobId WorkerId WorkId ThreadId LoggerName LogMessage
* with one or more additional lines for any {@link Throwable} associated with
* the {@link LogRecord}. The exception is output using
* {@link Throwable#printStackTrace()}.
*/
public class DataflowWorkerLoggingFormatter extends Formatter {
private static final DateTimeFormatter DATE_FORMATTER =
ISODateTimeFormat.dateTime().withZoneUTC();
private static final InheritableThreadLocal<String> jobId = new InheritableThreadLocal<>();
private static final InheritableThreadLocal<String> workerId = new InheritableThreadLocal<>();
private static final InheritableThreadLocal<String> workId = new InheritableThreadLocal<>();
/**
* Sets the Job ID of the current thread, which will be inherited by child threads.
*/
public static void setJobId(String newJobId) {
jobId.set(newJobId);
}
/**
* Sets the Worker ID of the current thread, which will be inherited by child threads.
*/
public static void setWorkerId(String newWorkerId) {
workerId.set(newWorkerId);
}
/**
* Sets the Work ID of the current thread, which will be inherited by child threads.
*/
public static void setWorkId(String newWorkId) {
workId.set(newWorkId);
}
/**
* Gets the Job ID of the current thread.
*/
public static String getJobId() {
return jobId.get();
}
/**
* Gets the Worker ID of the current thread.
*/
public static String getWorkerId() {
return workerId.get();
}
/**
* Gets the Work ID of the current thread.
*/
public static String getWorkId() {
return workId.get();
}
@Override
public String format(LogRecord record) {
String exception = formatException(record.getThrown());
return DATE_FORMATTER.print(record.getMillis())
+ " " + MoreObjects.firstNonNull(LEVELS.get(record.getLevel()),
record.getLevel().getName())
+ " " + record.getMessage()
+ " [" + MoreObjects.firstNonNull(jobId.get(), "unknown")
+ " " + MoreObjects.firstNonNull(workerId.get(), "unknown")
+ " " + MoreObjects.firstNonNull(workId.get(), "unknown")
+ " " + record.getThreadID()
+ "] " + record.getLoggerName() + System.lineSeparator()
+ (exception != null ? exception : "");
}
/**
* Formats the throwable as per {@link Throwable#printStackTrace()}.
*
* @param thrown The throwable to format.
* @return A string containing the contents of {@link Throwable#printStackTrace()}.
*/
public static String formatException(Throwable thrown) {
if (thrown == null) {
return null;
}
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
thrown.printStackTrace(pw);
pw.close();
return sw.toString();
}
}
|
#!/bin/bash
set -exu
for idx in 0 1 2 3 4 5 6 7 8 9; do
# # generate the training & test data
python multiple_domains.py $idx 1500
# # generate the adaptation data
for data_size in 15; do
python multiple_domains.py $idx $data_size
cd ./1500_data_fixed_${idx}/
# # combine dialog log
cat restaurant-MixSpec-1500.json weather-MixSpec-1500.json bus-MixSpec-1500.json > r_w_b.json
sed -i 's/\]\[/,/g' r_w_b.json
cat r_w_b.json movie-MixSpec-${data_size}.json > r_w_b_${data_size}m.json
sed -i 's/\]\[/,/g' r_w_b_${data_size}m.json
# # combine database
cat restaurant-MixSpec-1500-DB.json weather-MixSpec-1500-DB.json bus-MixSpec-1500-DB.json >r_w_b-DB.json
sed -i 's/\]\[/,/g' r_w_b-DB.json
cat r_w_b-DB.json movie-MixSpec-${data_size}-DB.json > r_w_b_${data_size}m-DB.json
sed -i 's/\]\[/,/g' r_w_b_${data_size}m-DB.json
# # combine OTGY(slot values) file
if [ -f "../1500_data_fixed_0/r_w_b-OTGY.json"]; then
cp ../1500_data_fixed_0/r_w_b-OTGY.json ./
else
python3 ../combine_domain.py -data_path ./ -target_domain ''
fi
if [ -f "../1500_data_fixed_0/r_w_b_${data_size}m-OTGY.json"]; then
cp ../1500_data_fixed_0/r_w_b_${data_size}m-OTGY.json ./r_w_b_${data_size}m-OTGY.json
else
python3 ../combine_domain.py -data_path ./
fi
cd ../
done
done
|
/**
* 主程序, 不包含手势,
* 主要用来适配Mouse/Touch事件
* ==================== 参考 ====================
* https://segmentfault.com/a/1190000010511484#articleHeader0
* https://segmentfault.com/a/1190000007448808#articleHeader1
* hammer.js http://hammerjs.github.io/
* ==================== 流程 ====================
* Event(Mouse|Touch) => BaseInput => Input => Computed => AnyTouchEvent
*/
import AnyEvent from 'any-event';
import type { Listener } from 'any-event';
import type { RecognizerConstruct, AnyTouchEvent, SupportEvent, ComputeFunction, ComputeWrapFunction, InputCreatorFunctionMap, InputCreatorFunction, Computed } from '@any-touch/shared';
import {
Recognizer,
TOUCH_START, TOUCH_MOVE, TOUCH_END, TOUCH_CANCEL, MOUSE_DOWN, MOUSE_MOVE, MOUSE_UP,
STATUS_POSSIBLE, STATUS_START, STATUS_MOVE, STATUS_END, STATUS_CANCELLED, STATUS_FAILED, STATUS_RECOGNIZED
} from '@any-touch/shared';
import { mouse, touch } from './createInput';
import dispatchDomEvent from './dispatchDomEvent';
import canPreventDefault from './canPreventDefault';
import bindElement from './bindElement';
import { use, removeUse } from './use';
import emit2 from './emit2';
// type TouchAction = 'auto' | 'none' | 'pan-x' | 'pan-left' | 'pan-right' | 'pan-y' | 'pan-up' | 'pan-down' | 'pinch-zoom' | 'manipulation';
type BeforeEachHook = (recognizer: Recognizer, next: () => void) => void;
/**
* 默认设置
*/
export interface Options {
domEvents?: false | EventInit;
isPreventDefault?: boolean;
// 不阻止默认行为的白名单
preventDefaultExclude?: RegExp | ((ev: SupportEvent) => boolean);
}
/**
* 默认设置
*/
const DEFAULT_OPTIONS: Options = {
domEvents: { bubbles: true, cancelable: true },
isPreventDefault: true,
preventDefaultExclude: /^(?:INPUT|TEXTAREA|BUTTON|SELECT)$/
};
export default class AnyTouch extends AnyEvent<AnyTouchEvent> {
static Tap: RecognizerConstruct;
static Pan: RecognizerConstruct;
static Swipe: RecognizerConstruct;
static Press: RecognizerConstruct;
static Pinch: RecognizerConstruct;
static Rotate: RecognizerConstruct;
static STATUS_POSSIBLE: typeof STATUS_POSSIBLE;
static STATUS_START: typeof STATUS_START;
static STATUS_MOVE: typeof STATUS_MOVE;
static STATUS_END: typeof STATUS_END;
static STATUS_CANCELLED: typeof STATUS_CANCELLED;
static STATUS_FAILED: typeof STATUS_FAILED;
static STATUS_RECOGNIZED: typeof STATUS_RECOGNIZED;
static version = '__VERSION__';
// 识别器集合
static recognizers: Recognizer[] = [];
static recognizerMap: Record<string, Recognizer> = {};
// 计算函数外壳函数集合
static computeFunctionMap: Record<string, ComputeWrapFunction> = {};
/**
* 安装插件
* @param {AnyTouchPlugin} 插件
* @param {any[]} 插件参数
*/
static use = (Recognizer: new (...args: any) => Recognizer, options?: Record<string, any>): void => {
use(AnyTouch, Recognizer, options);
};
/**
* 卸载插件[不建议]
*/
static removeUse = (recognizerName?: string): void => {
removeUse(AnyTouch, recognizerName);
};
computeFunctionMap: Record<string, ComputeFunction> = {};
// 目标元素
el?: HTMLElement;
// 选项
options: Options;
inputCreatorMap: InputCreatorFunctionMap;
recognizerMap: Record<string, Recognizer> = {};
recognizers: Recognizer[] = [];
beforeEachHook?: BeforeEachHook;
cacheComputedFunctionGroup = Object.create(null);
/**
* @param {Element} 目标元素, 微信下没有el
* @param {Object} 选项
*/
constructor(el?: HTMLElement, options?: Options) {
super();
this.el = el;
this.options = { ...DEFAULT_OPTIONS, ...options };
// 同步通过静态方法use引入的手势附带的"计算函数"
for (const k in AnyTouch.computeFunctionMap) {
this.computeFunctionMap[k] = AnyTouch.computeFunctionMap[k]();
}
// 同步插件到实例
this.recognizerMap = AnyTouch.recognizerMap;
this.recognizers = AnyTouch.recognizers;
// 之所以强制是InputCreatorFunction<SupportEvent>,
// 是因为调用this.inputCreatorMap[event.type]的时候还要判断类型,
// 因为都是固定(touch&mouse)事件绑定好的, 没必要判断
const createInputFromTouch = touch(this.el) as InputCreatorFunction<SupportEvent>;
const createInputFromMouse = mouse() as InputCreatorFunction<SupportEvent>;
this.inputCreatorMap = {
[TOUCH_START]: createInputFromTouch,
[TOUCH_MOVE]: createInputFromTouch,
[TOUCH_END]: createInputFromTouch,
[TOUCH_CANCEL]: createInputFromTouch,
[MOUSE_DOWN]: createInputFromMouse,
[MOUSE_MOVE]: createInputFromMouse,
[MOUSE_UP]: createInputFromMouse
};
// 绑定事件
if (void 0 !== el) {
// 观察了几个移动端组件, 作者都会加webkitTapHighlightColor
// 比如vant ui
// 所以在此作为默认值
// 使用者也可通过at.el改回去
el.style.webkitTapHighlightColor = 'rgba(0,0,0,0)';
// 校验是否支持passive
let supportsPassive = false;
try {
const opts = {};
Object.defineProperty(opts, 'passive', ({
get() {
// 不想为测试暴露, 会增加体积, 暂时忽略
/* istanbul ignore next */
supportsPassive = true;
}
}));
window.addEventListener('_', () => void 0, opts);
} catch { }
// 绑定元素
this.on(
'unbind',
bindElement(
el,
this.catchEvent.bind(this),
!this.options.isPreventDefault && supportsPassive ? { passive: true } : false
)
);
}
}
target(el: HTMLElement) {
return {
on: (eventName: string, listener: Listener<AnyTouchEvent>): void => {
this.on(eventName, listener, event => {
const { targets } = event;
// 检查当前触发事件的元素是否是其子元素
return event.target === el &&
targets.every((target) => el.contains(target as HTMLElement))
});
}
};
};
/**
* 监听input变化s
* @param event Touch / Mouse事件对象
*/
catchEvent(event: SupportEvent): void {
if (canPreventDefault(event, this.options)) {
event.preventDefault();
}
// if (!event.cancelable) {
// this.eventEmitter.emit('error', { code: 0, message: '页面滚动的时候, 请暂时不要操作元素!' });
// }
const input = this.inputCreatorMap[event.type](event);
// 跳过无效输入
// 比如没有按住鼠标左键的移动会返回undefined
if (void 0 !== input) {
const AT = `at`;
const AT_WITH_STATUS = AT + ':' + input.stage;
this.emit(AT, input as AnyTouchEvent);
this.emit(AT_WITH_STATUS, input as AnyTouchEvent);
const { domEvents } = this.options;
if (false !== domEvents) {
const { target } = event;
if (null !== target) {
dispatchDomEvent(target, { ...input, type: AT }, domEvents);
dispatchDomEvent(target, { ...input, type: AT_WITH_STATUS }, domEvents);
}
}
// input -> computed
const computed = input as Computed;
for (const k in this.computeFunctionMap) {
const f = this.computeFunctionMap[k];
Object.assign(computed, f(computed));
}
// 缓存每次计算的结果
// 以函数名为键值
for (const recognizer of this.recognizers) {
if (recognizer.disabled) continue;
// 恢复上次的缓存
recognizer.recognize(computed, type => {
// 此时的e就是this.computed
const payload = { ...computed, type, baseType: recognizer.name };
// 防止数据被vue类框架拦截
Object?.freeze(payload);
if (void 0 === this.beforeEachHook) {
emit2(this, payload);
} else {
this.beforeEachHook(recognizer, () => {
emit2(this, payload);
});
}
});
}
}
};
/**
* 使用插件
* @param {AnyTouchPlugin} 插件
* @param {Object} 选项
*/
use(Recognizer: new (...args: any) => Recognizer, options?: Record<string, any>): void {
use(this, Recognizer, options);
};
/**
* 移除插件
* @param {String} 识别器name
*/
removeUse(name?: string): void {
removeUse(this, name);
};
/**
* 事件拦截器
* @param hook 钩子函数
*/
beforeEach(hook: (recognizer: Recognizer, next: () => void) => void): void {
this.beforeEachHook = hook;
};
/**
* 获取识别器通过名字
* @param name 识别器的名字
* @return 返回识别器
*/
get(name: string): Recognizer | void {
return this.recognizerMap[name];
};
/**
* 设置
* @param options 选项
*/
set(options: Options): void {
this.options = { ...this.options, ...options };
};
/**
* 销毁
*/
destroy() {
// 解绑事件
this.emit('unbind');
this.listenersMap = {};
};
} |
key: a
key: b
key: c
|
from PyQt5 import QtWidgets
PLOT_STEP = 1
PLOT_YMIN = -100
PLOT_YMAX = 0
PLOT_BOTTOM = -80
class SignalProcessingSettings:
def __init__(self):
self._ref_level = QtWidgets.QSpinBox()
self._ref_level.setSingleStep(PLOT_STEP)
self._ref_level.valueChanged.connect(self._update_plot_y_axis)
self._ref_label = QtWidgets.QLabel('Reflevel: ')
self._min_level = QtWidgets.QSpinBox()
self._min_level.setRange(PLOT_YMIN, PLOT_YMAX)
self._min_level.setValue(PLOT_BOTTOM)
self._min_level.setSuffix(" dBm")
self._min_level.setSingleStep(PLOT_STEP)
def _update_plot_y_axis(self, value):
# Update the plot's y-axis based on the input value
pass # Placeholder for actual implementation
def set_reference_level(self, level):
self._ref_level.setValue(level)
def set_minimum_level(self, level):
self._min_level.setValue(level) |
#!/bin/bash
data=$(curl -L https://curl.se/ca/cacert.pem)
if [ ! -e cabundle ]; then
mkdir cabundle
fi
cat << _EOT_ > cabundle/cabundle.go
package cabundle
import (
"unsafe"
"reflect"
"net/http"
"crypto/x509"
"crypto/tls"
)
var strData = \`$data\`
func pemData() []byte {
var empty [0]byte
sx := (*reflect.StringHeader)(unsafe.Pointer(&strData))
b := empty[:]
bx := (*reflect.SliceHeader)(unsafe.Pointer(&b))
bx.Data = sx.Data
bx.Len = len(strData)
bx.Cap = bx.Len
return b
}
func GetCertPool() *x509.CertPool {
certs := x509.NewCertPool()
certs.AppendCertsFromPEM(pemData())
return certs
}
func GetTlsConfig() *tls.Config {
return &tls.Config {
RootCAs: GetCertPool(),
}
}
func GetTransport() *http.Transport {
return &http.Transport {
TLSClientConfig: GetTlsConfig(),
}
}
func GetClient() *http.Client {
return &http.Client {
Transport: GetTransport(),
}
}
_EOT_
|
#!/bin/bash -e
set -o pipefail
# set -x (bash debug) if log level is trace
# https://github.com/osixia/docker-light-baseimage/blob/stable/image/tool/log-helper
log-helper level eq trace && set -x
# Reduce maximum number of number of open file descriptors to 1024
# otherwise slapd consumes two orders of magnitude more of RAM
# see https://github.com/docker/docker/issues/8231
ulimit -n $LDAP_NOFILE
# create dir if they not already exists
[ -d /var/lib/ldap ] || mkdir -p /var/lib/ldap
[ -d /etc/ldap/slapd.d ] || mkdir -p /etc/ldap/slapd.d
# fix file permissions
chown -R openldap:openldap /var/lib/ldap
chown -R openldap:openldap /etc/ldap
chown -R openldap:openldap ${CONTAINER_SERVICE_DIR}/slapd
FIRST_START_DONE="${CONTAINER_STATE_DIR}/slapd-first-start-done"
WAS_STARTED_WITH_TLS="/etc/ldap/slapd.d/docker-openldap-was-started-with-tls"
WAS_STARTED_WITH_TLS_ENFORCE="/etc/ldap/slapd.d/docker-openldap-was-started-with-tls-enforce"
WAS_STARTED_WITH_REPLICATION="/etc/ldap/slapd.d/docker-openldap-was-started-with-replication"
WAS_ADMIN_PASSWORD_SET="/etc/ldap/slapd.d/docker-openldap-was-admin-password-set"
LDAP_TLS_CA_CRT_PATH="${CONTAINER_SERVICE_DIR}/slapd/assets/certs/$LDAP_TLS_CA_CRT_FILENAME"
LDAP_TLS_CRT_PATH="${CONTAINER_SERVICE_DIR}/slapd/assets/certs/$LDAP_TLS_CRT_FILENAME"
LDAP_TLS_KEY_PATH="${CONTAINER_SERVICE_DIR}/slapd/assets/certs/$LDAP_TLS_KEY_FILENAME"
LDAP_TLS_DH_PARAM_PATH="${CONTAINER_SERVICE_DIR}/slapd/assets/certs/$LDAP_TLS_DH_PARAM_FILENAME"
# CONTAINER_SERVICE_DIR and CONTAINER_STATE_DIR variables are set by
# the baseimage run tool more info : https://github.com/osixia/docker-light-baseimage
# container first start
if [ ! -e "$FIRST_START_DONE" ]; then
#
# Helpers
#
function get_ldap_base_dn() {
# if LDAP_BASE_DN is empty set value from LDAP_DOMAIN
if [ -z "$LDAP_BASE_DN" ]; then
IFS='.' read -ra LDAP_BASE_DN_TABLE <<< "$LDAP_DOMAIN"
for i in "${LDAP_BASE_DN_TABLE[@]}"; do
EXT="dc=$i,"
LDAP_BASE_DN=$LDAP_BASE_DN$EXT
done
LDAP_BASE_DN=${LDAP_BASE_DN::-1}
fi
}
function is_new_schema() {
local COUNT=$(ldapsearch -Q -Y EXTERNAL -H ldapi:/// -b cn=schema,cn=config cn | grep -c "}$1,")
if [ "$COUNT" -eq 0 ]; then
echo 1
else
echo 0
fi
}
function ldap_add_or_modify (){
local LDIF_FILE=$1
log-helper debug "Processing file ${LDIF_FILE}"
sed -i "s|{{ LDAP_BASE_DN }}|${LDAP_BASE_DN}|g" $LDIF_FILE
sed -i "s|{{ LDAP_BACKEND }}|${LDAP_BACKEND}|g" $LDIF_FILE
sed -i "s|{{ LDAP_DOMAIN }}|${LDAP_DOMAIN}|g" $LDIF_FILE
if [ "${LDAP_READONLY_USER,,}" == "true" ]; then
sed -i "s|{{ LDAP_READONLY_USER_USERNAME }}|${LDAP_READONLY_USER_USERNAME}|g" $LDIF_FILE
sed -i "s|{{ LDAP_READONLY_USER_PASSWORD_ENCRYPTED }}|${LDAP_READONLY_USER_PASSWORD_ENCRYPTED}|g" $LDIF_FILE
fi
if grep -iq changetype $LDIF_FILE ; then
( ldapmodify -Y EXTERNAL -Q -H ldapi:/// -f $LDIF_FILE 2>&1 || ldapmodify -h localhost -p 389 -D cn=admin,$LDAP_BASE_DN -w "$LDAP_ADMIN_PASSWORD" -f $LDIF_FILE 2>&1 ) | log-helper debug
else
( ldapadd -Y EXTERNAL -Q -H ldapi:/// -f $LDIF_FILE 2>&1 || ldapadd -h localhost -p 389 -D cn=admin,$LDAP_BASE_DN -w "$LDAP_ADMIN_PASSWORD" -f $LDIF_FILE 2>&1 ) | log-helper debug
fi
}
#
# Global variables
#
BOOTSTRAP=false
#
# database and config directory are empty
# setup bootstrap config - Part 1
#
if [ -z "$(ls -A -I lost+found --ignore=.* /var/lib/ldap)" ] && \
[ -z "$(ls -A -I lost+found --ignore=.* /etc/ldap/slapd.d)" ]; then
BOOTSTRAP=true
log-helper info "Database and config directory are empty..."
log-helper info "Init new ldap server..."
cat <<EOF | debconf-set-selections
slapd slapd/internal/generated_adminpw password ${LDAP_ADMIN_PASSWORD}
slapd slapd/internal/adminpw password ${LDAP_ADMIN_PASSWORD}
slapd slapd/password2 password ${LDAP_ADMIN_PASSWORD}
slapd slapd/password1 password ${LDAP_ADMIN_PASSWORD}
slapd slapd/dump_database_destdir string /var/backups/slapd-VERSION
slapd slapd/domain string ${LDAP_DOMAIN}
slapd shared/organization string ${LDAP_ORGANISATION}
slapd slapd/backend string ${LDAP_BACKEND^^}
slapd slapd/purge_database boolean true
slapd slapd/move_old_database boolean true
slapd slapd/allow_ldap_v2 boolean false
slapd slapd/no_configuration boolean false
slapd slapd/dump_database select when needed
EOF
dpkg-reconfigure -f noninteractive slapd
# RFC2307bis schema
if [ "${LDAP_RFC2307BIS_SCHEMA,,}" == "true" ]; then
log-helper info "Switching schema to RFC2307bis..."
cp ${CONTAINER_SERVICE_DIR}/slapd/assets/config/bootstrap/schema/rfc2307bis.* /etc/ldap/schema/
rm -f /etc/ldap/slapd.d/cn=config/cn=schema/*
mkdir -p /tmp/schema
slaptest -f ${CONTAINER_SERVICE_DIR}/slapd/assets/config/bootstrap/schema/rfc2307bis.conf -F /tmp/schema
mv /tmp/schema/cn=config/cn=schema/* /etc/ldap/slapd.d/cn=config/cn=schema
rm -r /tmp/schema
chown -R openldap:openldap /etc/ldap/slapd.d/cn=config/cn=schema
fi
rm ${CONTAINER_SERVICE_DIR}/slapd/assets/config/bootstrap/schema/rfc2307bis.*
#
# Error: the database directory (/var/lib/ldap) is empty but not the config directory (/etc/ldap/slapd.d)
#
elif [ -z "$(ls -A -I lost+found --ignore=.* /var/lib/ldap)" ] && [ ! -z "$(ls -A -I lost+found --ignore=.* /etc/ldap/slapd.d)" ]; then
log-helper error "Error: the database directory (/var/lib/ldap) is empty but not the config directory (/etc/ldap/slapd.d)"
exit 1
#
# Error: the config directory (/etc/ldap/slapd.d) is empty but not the database directory (/var/lib/ldap)
#
elif [ ! -z "$(ls -A -I lost+found --ignore=.* /var/lib/ldap)" ] && [ -z "$(ls -A -I lost+found --ignore=.* /etc/ldap/slapd.d)" ]; then
log-helper error "Error: the config directory (/etc/ldap/slapd.d) is empty but not the database directory (/var/lib/ldap)"
exit 1
#
# We have a database and config directory
#
else
# try to detect if ldap backend is hdb but LDAP_BACKEND environment variable is mdb
# due to default switch from hdb to mdb in 1.2.x
if [ "${LDAP_BACKEND}" = "mdb" ]; then
if [ -e "/etc/ldap/slapd.d/cn=config/olcDatabase={1}hdb.ldif" ]; then
log-helper warning -e "\n\n\nWarning: LDAP_BACKEND environment variable is set to mdb but hdb backend is detected."
log-helper warning "Going to use hdb as LDAP_BACKEND. Set LDAP_BACKEND=hdb to discard this message."
log-helper warning -e "https://github.com/osixia/docker-openldap#set-your-own-environment-variables\n\n\n"
LDAP_BACKEND="hdb"
fi
fi
fi
if [ "${KEEP_EXISTING_CONFIG,,}" == "true" ]; then
log-helper info "/!\ KEEP_EXISTING_CONFIG = true configration will not be updated"
else
#
# start OpenLDAP
#
# get previous hostname if OpenLDAP was started with replication
# to avoid configuration pbs
PREVIOUS_HOSTNAME_PARAM=""
if [ -e "$WAS_STARTED_WITH_REPLICATION" ]; then
source $WAS_STARTED_WITH_REPLICATION
# if previous hostname != current hostname
# set previous hostname to a loopback ip in /etc/hosts
if [ "$PREVIOUS_HOSTNAME" != "$HOSTNAME" ]; then
echo "127.0.0.2 $PREVIOUS_HOSTNAME" >> /etc/hosts
PREVIOUS_HOSTNAME_PARAM="ldap://$PREVIOUS_HOSTNAME"
fi
fi
# if the config was bootstraped with TLS
# to avoid error (#6) (#36) and (#44)
# we create fake temporary certificates if they do not exists
if [ -e "$WAS_STARTED_WITH_TLS" ]; then
source $WAS_STARTED_WITH_TLS
log-helper debug "Check previous TLS certificates..."
# fix for #73
# image started with an existing database/config created before 1.1.5
[[ -z "$PREVIOUS_LDAP_TLS_CA_CRT_PATH" ]] && PREVIOUS_LDAP_TLS_CA_CRT_PATH="${CONTAINER_SERVICE_DIR}/slapd/assets/certs/$LDAP_TLS_CA_CRT_FILENAME"
[[ -z "$PREVIOUS_LDAP_TLS_CRT_PATH" ]] && PREVIOUS_LDAP_TLS_CRT_PATH="${CONTAINER_SERVICE_DIR}/slapd/assets/certs/$LDAP_TLS_CRT_FILENAME"
[[ -z "$PREVIOUS_LDAP_TLS_KEY_PATH" ]] && PREVIOUS_LDAP_TLS_KEY_PATH="${CONTAINER_SERVICE_DIR}/slapd/assets/certs/$LDAP_TLS_KEY_FILENAME"
[[ -z "$PREVIOUS_LDAP_TLS_DH_PARAM_PATH" ]] && PREVIOUS_LDAP_TLS_DH_PARAM_PATH="${CONTAINER_SERVICE_DIR}/slapd/assets/certs/$LDAP_TLS_DH_PARAM_FILENAME"
ssl-helper $LDAP_SSL_HELPER_PREFIX $PREVIOUS_LDAP_TLS_CRT_PATH $PREVIOUS_LDAP_TLS_KEY_PATH $PREVIOUS_LDAP_TLS_CA_CRT_PATH
[ -f ${PREVIOUS_LDAP_TLS_DH_PARAM_PATH} ] || openssl dhparam -out ${LDAP_TLS_DH_PARAM_PATH} 2048
chmod 600 ${PREVIOUS_LDAP_TLS_DH_PARAM_PATH}
chown openldap:openldap $PREVIOUS_LDAP_TLS_CRT_PATH $PREVIOUS_LDAP_TLS_KEY_PATH $PREVIOUS_LDAP_TLS_CA_CRT_PATH $PREVIOUS_LDAP_TLS_DH_PARAM_PATH
fi
# start OpenLDAP
log-helper info "Start OpenLDAP..."
if log-helper level ge debug; then
slapd -h "ldap://$HOSTNAME $PREVIOUS_HOSTNAME_PARAM ldap://localhost ldapi:///" -u openldap -g openldap -d $LDAP_LOG_LEVEL 2>&1 &
else
slapd -h "ldap://$HOSTNAME $PREVIOUS_HOSTNAME_PARAM ldap://localhost ldapi:///" -u openldap -g openldap
fi
log-helper info "Waiting for OpenLDAP to start..."
while [ ! -e /run/slapd/slapd.pid ]; do sleep 0.1; done
#
# setup bootstrap config - Part 2
#
if $BOOTSTRAP; then
log-helper info "Add bootstrap schemas..."
# add ppolicy schema
ldapadd -c -Y EXTERNAL -Q -H ldapi:/// -f /etc/ldap/schema/ppolicy.ldif 2>&1 | log-helper debug
# convert schemas to ldif
SCHEMAS=""
for f in $(find ${CONTAINER_SERVICE_DIR}/slapd/assets/config/bootstrap/schema -name \*.schema -type f|sort); do
SCHEMAS="$SCHEMAS ${f}"
done
${CONTAINER_SERVICE_DIR}/slapd/assets/schema-to-ldif.sh "$SCHEMAS"
# add converted schemas
for f in $(find ${CONTAINER_SERVICE_DIR}/slapd/assets/config/bootstrap/schema -name \*.ldif -type f|sort); do
log-helper debug "Processing file ${f}"
# add schema if not already exists
SCHEMA=$(basename "${f}" .ldif)
ADD_SCHEMA=$(is_new_schema $SCHEMA)
if [ "$ADD_SCHEMA" -eq 1 ]; then
ldapadd -c -Y EXTERNAL -Q -H ldapi:/// -f $f 2>&1 | log-helper debug
else
log-helper info "schema ${f} already exists"
fi
done
# set config password
LDAP_CONFIG_PASSWORD_ENCRYPTED=$(slappasswd -s "$LDAP_CONFIG_PASSWORD")
sed -i "s|{{ LDAP_CONFIG_PASSWORD_ENCRYPTED }}|${LDAP_CONFIG_PASSWORD_ENCRYPTED}|g" ${CONTAINER_SERVICE_DIR}/slapd/assets/config/bootstrap/ldif/01-config-password.ldif
# adapt security config file
get_ldap_base_dn
sed -i "s|{{ LDAP_BASE_DN }}|${LDAP_BASE_DN}|g" ${CONTAINER_SERVICE_DIR}/slapd/assets/config/bootstrap/ldif/02-security.ldif
# process config files (*.ldif) in bootstrap directory (do no process files in subdirectories)
log-helper info "Add image bootstrap ldif..."
for f in $(find ${CONTAINER_SERVICE_DIR}/slapd/assets/config/bootstrap/ldif -mindepth 1 -maxdepth 1 -type f -name \*.ldif | sort); do
log-helper debug "Processing file ${f}"
ldap_add_or_modify "$f"
done
# read only user
if [ "${LDAP_READONLY_USER,,}" == "true" ]; then
log-helper info "Add read only user..."
LDAP_READONLY_USER_PASSWORD_ENCRYPTED=$(slappasswd -s $LDAP_READONLY_USER_PASSWORD)
ldap_add_or_modify "${CONTAINER_SERVICE_DIR}/slapd/assets/config/bootstrap/ldif/readonly-user/readonly-user.ldif"
ldap_add_or_modify "${CONTAINER_SERVICE_DIR}/slapd/assets/config/bootstrap/ldif/readonly-user/readonly-user-acl.ldif"
fi
log-helper info "Add custom bootstrap ldif..."
for f in $(find ${CONTAINER_SERVICE_DIR}/slapd/assets/config/bootstrap/ldif/custom -type f -name \*.ldif | sort); do
ldap_add_or_modify "$f"
done
fi
#
# TLS config
#
if [ -e "$WAS_STARTED_WITH_TLS" ] && [ "${LDAP_TLS,,}" != "true" ]; then
log-helper error "/!\ WARNING: LDAP_TLS=false but the container was previously started with LDAP_TLS=true"
log-helper error "TLS can't be disabled once added. Ignoring LDAP_TLS=false."
LDAP_TLS=true
fi
if [ -e "$WAS_STARTED_WITH_TLS_ENFORCE" ] && [ "${LDAP_TLS_ENFORCE,,}" != "true" ]; then
log-helper error "/!\ WARNING: LDAP_TLS_ENFORCE=false but the container was previously started with LDAP_TLS_ENFORCE=true"
log-helper error "TLS enforcing can't be disabled once added. Ignoring LDAP_TLS_ENFORCE=false."
LDAP_TLS_ENFORCE=true
fi
if [ "${LDAP_TLS,,}" == "true" ]; then
log-helper info "Add TLS config..."
# generate a certificate and key with ssl-helper tool if LDAP_CRT and LDAP_KEY files don't exists
# https://github.com/osixia/docker-light-baseimage/blob/stable/image/service-available/:ssl-tools/assets/tool/ssl-helper
ssl-helper $LDAP_SSL_HELPER_PREFIX $LDAP_TLS_CRT_PATH $LDAP_TLS_KEY_PATH $LDAP_TLS_CA_CRT_PATH
# create DHParamFile if not found
[ -f ${LDAP_TLS_DH_PARAM_PATH} ] || openssl dhparam -out ${LDAP_TLS_DH_PARAM_PATH} 2048
chmod 600 ${LDAP_TLS_DH_PARAM_PATH}
# fix file permissions
chown -R openldap:openldap ${CONTAINER_SERVICE_DIR}/slapd
# adapt tls ldif
sed -i "s|{{ LDAP_TLS_CA_CRT_PATH }}|${LDAP_TLS_CA_CRT_PATH}|g" ${CONTAINER_SERVICE_DIR}/slapd/assets/config/tls/tls-enable.ldif
sed -i "s|{{ LDAP_TLS_CRT_PATH }}|${LDAP_TLS_CRT_PATH}|g" ${CONTAINER_SERVICE_DIR}/slapd/assets/config/tls/tls-enable.ldif
sed -i "s|{{ LDAP_TLS_KEY_PATH }}|${LDAP_TLS_KEY_PATH}|g" ${CONTAINER_SERVICE_DIR}/slapd/assets/config/tls/tls-enable.ldif
sed -i "s|{{ LDAP_TLS_DH_PARAM_PATH }}|${LDAP_TLS_DH_PARAM_PATH}|g" ${CONTAINER_SERVICE_DIR}/slapd/assets/config/tls/tls-enable.ldif
sed -i "s|{{ LDAP_TLS_CIPHER_SUITE }}|${LDAP_TLS_CIPHER_SUITE}|g" ${CONTAINER_SERVICE_DIR}/slapd/assets/config/tls/tls-enable.ldif
sed -i "s|{{ LDAP_TLS_VERIFY_CLIENT }}|${LDAP_TLS_VERIFY_CLIENT}|g" ${CONTAINER_SERVICE_DIR}/slapd/assets/config/tls/tls-enable.ldif
ldapmodify -Y EXTERNAL -Q -H ldapi:/// -f ${CONTAINER_SERVICE_DIR}/slapd/assets/config/tls/tls-enable.ldif 2>&1 | log-helper debug
[[ -f "$WAS_STARTED_WITH_TLS" ]] && rm -f "$WAS_STARTED_WITH_TLS"
echo "export PREVIOUS_LDAP_TLS_CA_CRT_PATH=${LDAP_TLS_CA_CRT_PATH}" > $WAS_STARTED_WITH_TLS
echo "export PREVIOUS_LDAP_TLS_CRT_PATH=${LDAP_TLS_CRT_PATH}" >> $WAS_STARTED_WITH_TLS
echo "export PREVIOUS_LDAP_TLS_KEY_PATH=${LDAP_TLS_KEY_PATH}" >> $WAS_STARTED_WITH_TLS
echo "export PREVIOUS_LDAP_TLS_DH_PARAM_PATH=${LDAP_TLS_DH_PARAM_PATH}" >> $WAS_STARTED_WITH_TLS
# enforce TLS
if [ "${LDAP_TLS_ENFORCE,,}" == "true" ]; then
log-helper info "Add enforce TLS..."
ldapmodify -Y EXTERNAL -Q -H ldapi:/// -f ${CONTAINER_SERVICE_DIR}/slapd/assets/config/tls/tls-enforce-enable.ldif 2>&1 | log-helper debug
touch $WAS_STARTED_WITH_TLS_ENFORCE
# disable tls enforcing (not possible for now)
#else
#log-helper info "Disable enforce TLS..."
#ldapmodify -Y EXTERNAL -Q -H ldapi:/// -f ${CONTAINER_SERVICE_DIR}/slapd/assets/config/tls/tls-enforce-disable.ldif 2>&1 | log-helper debug || true
#[[ -f "$WAS_STARTED_WITH_TLS_ENFORCE" ]] && rm -f "$WAS_STARTED_WITH_TLS_ENFORCE"
fi
# disable tls (not possible for now)
#else
#log-helper info "Disable TLS config..."
#ldapmodify -c -Y EXTERNAL -Q -H ldapi:/// -f ${CONTAINER_SERVICE_DIR}/slapd/assets/config/tls/tls-disable.ldif 2>&1 | log-helper debug || true
#[[ -f "$WAS_STARTED_WITH_TLS" ]] && rm -f "$WAS_STARTED_WITH_TLS"
fi
#
# Replication config
#
function disableReplication() {
sed -i "s|{{ LDAP_BACKEND }}|${LDAP_BACKEND}|g" ${CONTAINER_SERVICE_DIR}/slapd/assets/config/replication/replication-disable.ldif
ldapmodify -c -Y EXTERNAL -Q -H ldapi:/// -f ${CONTAINER_SERVICE_DIR}/slapd/assets/config/replication/replication-disable.ldif 2>&1 | log-helper debug || true
[[ -f "$WAS_STARTED_WITH_REPLICATION" ]] && rm -f "$WAS_STARTED_WITH_REPLICATION"
}
if [ "${LDAP_REPLICATION,,}" == "true" ]; then
log-helper info "Add replication config..."
disableReplication || true
i=1
for host in $(complex-bash-env iterate LDAP_REPLICATION_HOSTS)
do
sed -i "s|{{ LDAP_REPLICATION_HOSTS }}|olcServerID: $i ${!host}\n{{ LDAP_REPLICATION_HOSTS }}|g" ${CONTAINER_SERVICE_DIR}/slapd/assets/config/replication/replication-enable.ldif
sed -i "s|{{ LDAP_REPLICATION_HOSTS_CONFIG_SYNC_REPL }}|olcSyncRepl: rid=00$i provider=${!host} ${LDAP_REPLICATION_CONFIG_SYNCPROV}\n{{ LDAP_REPLICATION_HOSTS_CONFIG_SYNC_REPL }}|g" ${CONTAINER_SERVICE_DIR}/slapd/assets/config/replication/replication-enable.ldif
sed -i "s|{{ LDAP_REPLICATION_HOSTS_DB_SYNC_REPL }}|olcSyncRepl: rid=10$i provider=${!host} ${LDAP_REPLICATION_DB_SYNCPROV}\n{{ LDAP_REPLICATION_HOSTS_DB_SYNC_REPL }}|g" ${CONTAINER_SERVICE_DIR}/slapd/assets/config/replication/replication-enable.ldif
((i++))
done
get_ldap_base_dn
sed -i "s|\$LDAP_BASE_DN|$LDAP_BASE_DN|g" ${CONTAINER_SERVICE_DIR}/slapd/assets/config/replication/replication-enable.ldif
sed -i "s|\$LDAP_ADMIN_PASSWORD|$LDAP_ADMIN_PASSWORD|g" ${CONTAINER_SERVICE_DIR}/slapd/assets/config/replication/replication-enable.ldif
sed -i "s|\$LDAP_CONFIG_PASSWORD|$LDAP_CONFIG_PASSWORD|g" ${CONTAINER_SERVICE_DIR}/slapd/assets/config/replication/replication-enable.ldif
sed -i "/{{ LDAP_REPLICATION_HOSTS }}/d" ${CONTAINER_SERVICE_DIR}/slapd/assets/config/replication/replication-enable.ldif
sed -i "/{{ LDAP_REPLICATION_HOSTS_CONFIG_SYNC_REPL }}/d" ${CONTAINER_SERVICE_DIR}/slapd/assets/config/replication/replication-enable.ldif
sed -i "/{{ LDAP_REPLICATION_HOSTS_DB_SYNC_REPL }}/d" ${CONTAINER_SERVICE_DIR}/slapd/assets/config/replication/replication-enable.ldif
sed -i "s|{{ LDAP_BACKEND }}|${LDAP_BACKEND}|g" ${CONTAINER_SERVICE_DIR}/slapd/assets/config/replication/replication-enable.ldif
ldapmodify -c -Y EXTERNAL -Q -H ldapi:/// -f ${CONTAINER_SERVICE_DIR}/slapd/assets/config/replication/replication-enable.ldif 2>&1 | log-helper debug || true
[[ -f "$WAS_STARTED_WITH_REPLICATION" ]] && rm -f "$WAS_STARTED_WITH_REPLICATION"
echo "export PREVIOUS_HOSTNAME=${HOSTNAME}" > $WAS_STARTED_WITH_REPLICATION
else
log-helper info "Disable replication config..."
disableReplication || true
fi
if [[ -f "$WAS_ADMIN_PASSWORD_SET" ]]; then
get_ldap_base_dn
LDAP_CONFIG_PASSWORD_ENCRYPTED=$(slappasswd -s "$LDAP_CONFIG_PASSWORD")
LDAP_ADMIN_PASSWORD_ENCRYPTED=$(slappasswd -s "$LDAP_ADMIN_PASSWORD")
sed -i "s|{{ LDAP_CONFIG_PASSWORD_ENCRYPTED }}|${LDAP_CONFIG_PASSWORD_ENCRYPTED}|g" ${CONTAINER_SERVICE_DIR}/slapd/assets/config/admin-pw/ldif/06-root-pw-change.ldif
sed -i "s|{{ LDAP_ADMIN_PASSWORD_ENCRYPTED }}|${LDAP_ADMIN_PASSWORD_ENCRYPTED}|g" ${CONTAINER_SERVICE_DIR}/slapd/assets/config/admin-pw/ldif/06-root-pw-change.ldif
sed -i "s|{{ LDAP_BACKEND }}|${LDAP_BACKEND}|g" ${CONTAINER_SERVICE_DIR}/slapd/assets/config/admin-pw/ldif/06-root-pw-change.ldif
sed -i "s|{{ LDAP_ADMIN_PASSWORD_ENCRYPTED }}|${LDAP_ADMIN_PASSWORD_ENCRYPTED}|g" ${CONTAINER_SERVICE_DIR}/slapd/assets/config/admin-pw/ldif/07-admin-pw-change.ldif
sed -i "s|{{ LDAP_BASE_DN }}|${LDAP_BASE_DN}|g" ${CONTAINER_SERVICE_DIR}/slapd/assets/config/admin-pw/ldif/07-admin-pw-change.ldif
for f in $(find ${CONTAINER_SERVICE_DIR}/slapd/assets/config/admin-pw/ldif -type f -name \*.ldif | sort); do
ldap_add_or_modify "$f"
done
else
touch "$WAS_ADMIN_PASSWORD_SET"
fi
#
# stop OpenLDAP
#
log-helper info "Stop OpenLDAP..."
SLAPD_PID=$(cat /run/slapd/slapd.pid)
kill -15 $SLAPD_PID
while [ -e /proc/$SLAPD_PID ]; do sleep 0.1; done # wait until slapd is terminated
fi
#
# ldap client config
#
if [ "${LDAP_TLS,,}" == "true" ]; then
log-helper info "Configure ldap client TLS configuration..."
sed -i --follow-symlinks "s,TLS_CACERT.*,TLS_CACERT ${LDAP_TLS_CA_CRT_PATH},g" /etc/ldap/ldap.conf
echo "TLS_REQCERT ${LDAP_TLS_VERIFY_CLIENT}" >> /etc/ldap/ldap.conf
cp -f /etc/ldap/ldap.conf ${CONTAINER_SERVICE_DIR}/slapd/assets/ldap.conf
[[ -f "$HOME/.ldaprc" ]] && rm -f $HOME/.ldaprc
echo "TLS_CERT ${LDAP_TLS_CRT_PATH}" > $HOME/.ldaprc
echo "TLS_KEY ${LDAP_TLS_KEY_PATH}" >> $HOME/.ldaprc
cp -f $HOME/.ldaprc ${CONTAINER_SERVICE_DIR}/slapd/assets/.ldaprc
fi
#
# remove container config files
#
if [ "${LDAP_REMOVE_CONFIG_AFTER_SETUP,,}" == "true" ]; then
log-helper info "Remove config files..."
rm -rf ${CONTAINER_SERVICE_DIR}/slapd/assets/config
fi
#
# setup done :)
#
log-helper info "First start is done..."
touch $FIRST_START_DONE
fi
ln -sf ${CONTAINER_SERVICE_DIR}/slapd/assets/.ldaprc $HOME/.ldaprc
ln -sf ${CONTAINER_SERVICE_DIR}/slapd/assets/ldap.conf /etc/ldap/ldap.conf
# force OpenLDAP to listen on all interfaces
ETC_HOSTS=$(cat /etc/hosts | sed "/$HOSTNAME/d")
echo "0.0.0.0 $HOSTNAME" > /etc/hosts
echo "$ETC_HOSTS" >> /etc/hosts
exit 0
|
function isMAC48Address(inputString) {
const strToArr = inputString.split("-");
if (strToArr.length !== 6) {
return false;
}
return strToArr.filter(str => /^[0-9A-F][0-9A-F]$/.test(str)).length === 6;
}
|
require "spec_helper"
describe Jkf::Converter::Csa do
let(:csa_converter) { Jkf::Converter::Csa.new }
let(:csa_parser) { Jkf::Parser::Csa.new }
subject { csa_parser.parse(csa_converter.convert(jkf)) }
shared_examples(:parse_file) do |filename|
let(:str) do
if File.extname(filename) == ".csa"
File.read(filename, encoding: "Shift_JIS").toutf8
else
File.read(filename).toutf8
end
end
let(:jkf) { csa_parser.parse(str).to_json }
it "should be parse #{File.basename(filename)}" do
is_expected.to eq JSON.parse(jkf)
end
end
fixtures(:csa).each do |fixture|
it_behaves_like :parse_file, fixture
end
describe "#convert_preset(preset)" do
let(:pairs) do
{
"HIRATE" => "",
"KY" => "11KY",
"KY_R" => "91KY",
"KA" => "22KA",
"HI" => "82HI",
"HIKY" => "22HI11KY91KY",
"2" => "82HI22KA",
"3" => "82HI22KA91KY",
"4" => "82HI22KA11KY91KY",
"5" => "82HI22KA81KE11KY91KY",
"5_L" => "82HI22KA21KE11KY91KY",
"6" => "82HI22KA21KE81KE11KY91KY",
"8" => "82HI22KA31GI71GI21KE81KE11KY91KY",
"10" => "82HI22KA41KI61KI31GI71GI21KE81KE11KY91KY"
}
end
it "should convert preset to PIXXX" do
pairs.each do |preset, pi|
expect(csa_converter.send(:convert_preset, preset)).to eq "PI" + pi
end
end
context "when 8mai" do
let(:kif_parser) { Jkf::Parser::Kif.new }
let(:filename) { fixtures(:kif).detect { |file| file =~ /8mai/ } }
let(:jkf) { kif_parser.parse(File.read(filename, encoding: "Shift_JIS").toutf8) }
it { expect(csa_converter.convert(jkf)).to be_a String }
end
end
end
|
package com.ap.stephen.videodrawerplayer.content;
import android.graphics.Bitmap;
import android.media.ThumbnailUtils;
import android.provider.MediaStore;
import java.util.HashMap;
public class VideoItem {
private final String name;
private final String path;
private final static HashMap<String, Bitmap> BitmapCache = new HashMap<>();
public VideoItem(String name, String path) {
this.name = name;
this.path = path;
}
@Override
public String toString() {
return path;
}
public String getName() {
return name;
}
public String getPath() {
return path;
}
public Bitmap getBitmap() {
return buildBitmap();
}
private Bitmap buildBitmap() {
String path = getPath();
if (!BitmapCache.containsKey(path)) {
Bitmap bitmap = ThumbnailUtils.createVideoThumbnail(getPath(),
MediaStore.Video.Thumbnails.MICRO_KIND);
BitmapCache.put(path, bitmap);
}
return BitmapCache.get(path);
}
}
|
def time_to_seconds(hours, minutes, seconds):
return (hours * 3600) + (minutes * 60) + seconds
result = time_to_seconds(2, 3, 4)
print(result) |
<reponame>wang-zhuoran/software-engineering-labs<filename>LAB4/music/music.js
// pages/music/music.js
Page({
/**
* 页面的初始数据
*/
data: {},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
wx.playBackgroundAudio({
dataUrl: "http://www.ytmp3.cn/down/57642.mp3",
title: "爱拼才会赢",
loop: "true",
});
this.setData({
bgmusic: wx.getBackgroundAudioManager(),
});
//使用方式如: this.data.bgmusic.play();//播放
},
// /**
// * 生命周期函数--监听页面初次渲染完成
// */
onReady: function () {},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {},
start: function () {
this.data.bgmusic.play();
},
pause: function () {
this.data.bgmusic.pause();
},
// audioPlay: function () {
// this.audioCtx.play();
// },
// audioPause: function () {
// this.audioCtx.pause();
// },
});
|
<filename>go/send-sms/main.go
package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"strings"
)
const (
senderName string = "Bosbec"
baseUrl string = "https://api.mobileresponse.se/"
message string = "Hello from Golang!"
)
var (
recipients []string = []string{"+46705176608", "+46735090065"}
username string = os.Getenv("MOBILERESPONSE_API_USERNAME")
password string = os.Getenv("MOBILERESPONSE_API_PASSWORD")
)
func main() {
if username == "" {
log.Fatal("Missing MobileResponse API username. Did you forget to set the MOBILERESPONSE_API_USERNAME environment variable?")
}
if password == "" {
log.Fatal("Missing MobileResponse API password. Did you forget to set the MOBILERESPONSE_API_PASSWORD environment variable?")
}
fmt.Printf("Sending \"%s\" to %s\n", message, strings.Join(recipients, ", "))
sendSms(username, password, message, recipients)
fmt.Println("Authenticating")
authenticationToken := authenticate(username, password)
fmt.Printf("Authenticated and received \"%s\" authentication token\n", authenticationToken)
fmt.Println("Checking if the authentication token is still valid")
if isAuthenticated(authenticationToken) {
fmt.Printf("\"%s\" is valid\n", authenticationToken)
} else {
fmt.Printf("\"%s\" is not valid\n", authenticationToken)
}
}
func authenticate(username, password string) string {
data := &Request{
Data: &AuthenticateRequest{
username,
password,
},
}
requestJson, _ := json.Marshal(data)
client := &http.Client{}
request, err := http.NewRequest("POST", baseUrl+"authenticate", bytes.NewReader(requestJson))
if err != nil {
panic(err)
}
response, err := client.Do(request)
if err != nil {
panic(err)
}
defer response.Body.Close()
body, err := ioutil.ReadAll(response.Body)
if err != nil {
panic(err)
}
var r = AuthenticateResponse{}
err = json.Unmarshal(body, &r)
return r.Data.Id
}
func sendSms(username, password, message string, recipients []string) {
data := &Request{
Data: &SendSmsRequest{
username,
password,
message,
recipients,
senderName,
},
}
requestJson, _ := json.Marshal(data)
client := &http.Client{}
request, err := http.NewRequest("POST", baseUrl+"quickie/send-message", bytes.NewReader(requestJson))
if err != nil {
panic(err)
}
response, err := client.Do(request)
if err != nil {
panic(err)
}
response.Body.Close()
}
func isAuthenticated(authenticationToken string) bool {
data := &Request{
AuthenticationToken: authenticationToken,
}
requestJson, _ := json.Marshal(data)
client := &http.Client{}
request, err := http.NewRequest("POST", baseUrl+"is-authenticated", bytes.NewReader(requestJson))
if err != nil {
panic(err)
}
response, err := client.Do(request)
if err != nil {
panic(err)
}
defer response.Body.Close()
body, err := ioutil.ReadAll(response.Body)
if err != nil {
panic(err)
}
var r = IsAuthenticatedResponse{}
err = json.Unmarshal(body, &r)
return r.Status == "Success"
return false
}
type Request struct {
Data interface{} `json:"data"`
AuthenticationToken string `json:"authenticationToken"`
}
type AuthenticateRequest struct {
Username string `json:"username"`
Password string `json:"password"`
}
type SendSmsRequest struct {
Username string `json:"username"`
Password string `json:"password"`
Message string `json:"message"`
Recipients []string `json:"recipients"`
SenderName string `json:"senderName"`
}
type AuthenticateResponse struct {
Data struct {
Id string
}
}
type IsAuthenticatedResponse struct {
Status string
}
|
<reponame>webster6667/react-flaky-form
import 'element-closest-polyfill';
import React, {useEffect, useState} from 'react';
import axios from 'axios'
// import {useImmer} from 'use-immer'
import {DEFAULT_FORM_SETTINGS, FORM_NAME} from "@const";
import {combineValidatorsSettingsLayers} from '@add-control-props-layers/add-validators-settings-layers'
import {initFlukyForm, submitFlukyFormHandler} from '@utils/form-actions'
import {addControlExample, removeControlFromListByIndex, addFormExample, removeFormByIndex} from '@utils/dynamic-form-actions'
import {FlakyInput} from '@UI/input'
import {
FormConfigProps,
FormParamsProps,
ControlsProps,
FormProps,
UseFlakyForm,
FlakyFormComponent,
AddFormExampleComponent,
RemoveFormComponent,
AddControlComponent,
RemoveControlComponent
} from "@common-types"
/**
* @description
* Хук инициализации формы
*
* @param {ControlsProps | ControlsProps[]} controls - массив контролы формы
* @param {FormConfigProps} customFormConfig - объект с настройками поведения формы, передаваемый с наружи(хуки, тип валидации и тд)
* @returns {[FormProps, any]} контролы с нужными настройками, функцию для изменения состояния формы
*
*/
const useFlakyForm: UseFlakyForm = (controls, customFormConfig) => {
const formParams: FormParamsProps = {
loaded: false,
isFormTriedSubmit: false,
isSubmitBtnLocked: false,
errorList: [],
commonError: ''
},
formValidatorsSetting = combineValidatorsSettingsLayers(DEFAULT_FORM_SETTINGS.formValidatorsSetting, customFormConfig.formValidatorsSetting),
[flukyForm, setForm] = useState<FormProps<typeof controls>>({
controls,
formParams,
formSettings: {
...DEFAULT_FORM_SETTINGS,
formName: FORM_NAME,
...customFormConfig,
formValidatorsSetting
},
controlsExample: {}
})
useEffect(() => {
(async function asyncFunction() {
const {action = null} = customFormConfig,
initAction = action ? typeof action === 'object' && action.toInit ? action.toInit : String(action) : null,
apiResponse = initAction ? await axios.post(initAction) : null
setForm((prevForm) => {
const form = {...prevForm}
initFlukyForm(form, apiResponse, customFormConfig, formParams, setForm)
return form
})
})();
}, [])
return [flukyForm, setForm]
}
const FlakyForm:FlakyFormComponent = ({
children,
className = 'form',
id = null,
action = null,
formState,
setForm
}) => {
const {loaded} = formState.formParams,
{formName: currentFormName} = formState.formSettings,
submitHandler = (e) => {
e.preventDefault()
submitFlukyFormHandler(setForm)
}
return (<form
id={String(currentFormName)}
className={className}
onSubmit={submitHandler}
>
{children}
<input data-element={'hidden-submit-trigger'}
type={'submit'}
style={{opacity: 0, width: 0, height: 0, position: 'absolute', zIndex: -1}}
/>
</form>)
}
const AddFormExample:AddFormExampleComponent = ({setForm, value = 'Добавить форму', children}) => {
const clickHandler = (e) => addFormExample(setForm)
return <div className={'add-form-clone'} onClick={clickHandler} >
{value ? value : children}
</div>
}
const RemoveForm:RemoveFormComponent = ({setForm, formIndex, value, children}) => {
const clickHandler = (e) => removeFormByIndex(formIndex, setForm)
return <div className={'remove-form-clone'} onClick={clickHandler} >
{value ? value : children}
</div>
}
const AddControlExample:AddControlComponent = ({setForm, controlName, formIndex = null}) => {
const clickHandler = (e) => addControlExample(setForm, controlName, formIndex)
return <div className={'add-form-clone'} onClick={clickHandler} >
+ c
</div>
}
const RemoveControl:RemoveControlComponent = ({setForm, controlName, controlIndex, formIndex = null}) => {
const clickHandler = (e) => removeControlFromListByIndex(setForm, controlName, formIndex, controlIndex)
return <div className={'remove-control'} onClick={clickHandler} >
- c
</div>
}
export {FlakyForm, FlakyInput, useFlakyForm, AddFormExample, RemoveForm, AddControlExample, RemoveControl} |
#!/bin/bash
# ---- ICINGA INTEGRATION ----
#
# 1- Icinga config lines to be added to contacts.cfg
#
# define contact {
# contact_name upwork
# alias Upwork
# service_notification_period 24x7
# host_notification_period 24x7
# service_notification_options w,u,c,r
# host_notification_options d,r
# service_notification_commands notify-service-by-upwork
# host_notification_commands notify-host-by-upwork
# }
#
#
# 2- Icinga config lines to be added to commands.cfg
#
# define command {
# command_name notify-service-by-upwork
# command_line /usr/local/bin/upwork_icinga.sh notification_service_type
# }
#
# define command {
# command_name notify-host-by-upwork
# command_line /usr/local/bin/upwork_icinga.sh notification_host_type
# }
#
# define contactgroup{
# contactgroup_name admins
# alias Icinga Administrators
# members root,upwork
# }
#
# 3- Variables to be modified dependeing on your environment
#
# MY_ICINGA_HOSTNAME="icinga.yourdomain.com"
#
# 4- Script (this file) to be placed in /usr/local/bin
#
MY_ICINGA_HOSTNAME="icinga.yourdomain.com"
NOTIFICATION_TYPE=$1
function notifyUpwork {
UPWORK_WEBHOOK_URL=$1
if [ "$NOTIFICATION_TYPE" = "notification_service_type" ]
then
curl -X POST --data "payload={\"notificationType\": \"${NOTIFICATION_TYPE}\", \"notificationIssue\": \"${ICINGA_NOTIFICATIONTYPE}\", \"hostData\": \"{\"hostName\": \"${ICINGA_HOSTNAME}\", \"hostAddress\": \"${ICINGA_HOSTADDRESS}\", \"hostState\": \"${ICINGA_HOSTSTATE}\", \"hostStateType\": \"${ICINGA_HOSTSTATETYPE}\", \"hostGroupName\": \"${ICINGA_HOSTGROUPNAME}\", \"hostOutput\": \"${ICINGA_HOSTOUTPUT}\", \"lastHostState\": \"${ICINGA_LASTHOSTSTATE}\", \"lastHostOk\": \"${ICINGA_LASTHOSTOK}\", \"hostAckAuthor\": \"${ICINGA_HOSTACKAUTHOR}\", \"hostAckComment\": \"${ICINGA_HOSTACKCOMMENT}\"}\", \"serviceData\": {\"serviceName\": \"${ICINGA_SERVICEDISPLAYNAME}\", \"serviceState\": \"${ICINGA_SERVICESTATE}\", \"serviceOutput\": \"${ICINGA_SERVICEOUTPUT}\", \"serviceUrl\": \"<https://${MY_ICINGA_HOSTNAME}/cgi-bin/icinga3/status.cgi?host=${ICINGA_HOSTNAME}>\", \"lastServiceState\": \"${ICINGA_LASTSERVICESTATE}\", \"serviceGroupName\": \"${ICINGA_SERVICEGROUPNAME}\", \"lastServiceOk\": \"${ICINGA_LASTSERVICEOK}\", \"serviceAckAuthor\": \"${ICINGA_SERVICEACKAUTHOR}\", \"serviceAckComment\": \"${ICINGA_SERVICEACKCOMMENT}\"}}" ${UPWORK_WEBHOOK_URL}
else
curl -X POST --data "payload={\"notificationType\": \"${NOTIFICATION_TYPE}\", \"notificationIssue\": \"${ICINGA_NOTIFICATIONTYPE}\", \"hostData\": \"{\"hostName\": \"${ICINGA_HOSTNAME}\", \"hostAddress\": \"${ICINGA_HOSTADDRESS}\", \"hostState\": \"${ICINGA_HOSTSTATE}\", \"hostStateType\": \"${ICINGA_HOSTSTATETYPE}\", \"hostGroupName\": \"${ICINGA_HOSTGROUPNAME}\", \"hostOutput\": \"${ICINGA_HOSTOUTPUT}\", \"lastHostState\": \"${ICINGA_LASTHOSTSTATE}\", \"lastHostOk\": \"${ICINGA_LASTHOSTOK}\", \"hostAckAuthor\": \"${ICINGA_HOSTACKAUTHOR}\", \"hostAckComment\": \"${ICINGA_HOSTACKCOMMENT}\"}\"}" ${UPWORK_WEBHOOK_URL}
fi
}
# The code above was placed in a function so you can easily notify multiple webhooks:
notifyUpwork "Webhook URL provided by Upwork when the integration was added"
|
#!/usr/bin/env bash
###############
# Definitions #
###############
# Shell PID
top_pid=$$
# This script name
script_name=$(basename $0)
# Firmware file location
fw_top_dir="/tmp/fw"
########################
# Function definitions #
########################
# Trap TERM signals and exit
trap "echo 'An ERROR was found. Aborting...'; exit 1" TERM
# Usage message
usage()
{
echo "Start the SMuRF server on a specific board."
echo ""
echo "usage: ${script_name} [-S|--shelfmanager <shelfmanager_name> -N|--slot <slot_number>]"
echo " [-a|--addr <FPGA_IP>] [-D|--no-check-fw] [-g|--gui] <pyrogue_server-args>"
echo " -S|--shelfmanager <shelfmanager_name> : ATCA shelfmanager node name or IP address. Must be used with -N."
echo " -N|--slot <slot_number> : ATCA crate slot number. Must be used with -S."
echo " -a|--addr <FPGA_IP> : FPGA IP address. If defined, -S and -N are ignored."
echo " -D|--no-check-fw : Disabled FPGA version checking."
echo " -g|--gui : Start the server with a GUI."
echo " -h|--help : Show this message."
echo " <pyrogue_server_args> are passed to the SMuRF pyrogue server. "
echo ""
echo "If -a if not defined, then -S and -N must both be defined, and the FPGA IP address will be automatically calculated from the crate ID and slot number."
echo "If -a if defined, -S and -N are ignored."
echo
echo "The script will bu default check if the firmware githash read from the FPGA via IPMI is the same of the found in the MCS file name."
echo "This checking can be disabled with -D. The checking will also be disabled if -a is used instead of -S and -N."
echo
echo "By default, the SMuRF server is tarted without a GUI (server mode). Use -g to start the server with a GUI. -s|--server option is ignored as that is the default."
echo
echo "All other arguments are passed verbatim to the SMuRF server."
echo ""
exit 1
}
getGitHashFW()
{
local gh_inv
local gh
# Long githash (inverted)
#gh_inv=$(ipmitool -I lan -H $SHELFMANAGER -t $IPMB -b 0 -A NONE raw 0x34 0x04 0xd0 0x14 2> /dev/null)
# Short githash (inverted)
gh_inv=$(ipmitool -I lan -H $shelfmanager -t $ipmb -b 0 -A NONE raw 0x34 0x04 0xe0 0x04 2> /dev/null)
if [ "$?" -ne 0 ]; then
kill -s TERM ${top_pid}
fi
# Invert the string
for c in ${gh_inv} ; do gh=${c}${gh} ; done
# Return the short hash (7 bytes)
echo ${gh} | cut -c 1-7
}
getGitHashMcs()
{
local filename=$(basename $mcs_file_name)
local gh=$(echo $filename | sed -r 's/.+-+(.+).mcs.*/\1/')
# Return the short hash (7 bytes)
echo ${gh} | cut -c 1-7
}
getCrateId()
{
local crate_id_str
crate_id_str=$(ipmitool -I lan -H $shelfmanager -t $ipmb -b 0 -A NONE raw 0x34 0x04 0xFD 0x02 2> /dev/null)
if [ "$?" -ne 0 ]; then
kill -s TERM ${top_pid}
fi
local crate_id=`printf %04X $((0x$(echo $crate_id_str | awk '{ print $2$1 }')))`
if [ -z ${crate_id} ]; then
kill -s TERM ${top_pid}
fi
echo ${crate_id}
}
getFpgaIp()
{
# Calculate FPGA IP subnet from the crate ID
local subnet="10.$((0x${crate_id:0:2})).$((0x${crate_id:2:2}))"
# Calculate FPGA IP last octect from the slot number
local fpga_ip="${subnet}.$(expr 100 + $slot)"
echo ${fpga_ip}
}
#############
# Main body #
#############
# Verify inputs arguments
while [[ $# -gt 0 ]]
do
key="$1"
case ${key} in
-S|--shelfmanager)
shelfmanager="$2"
shift
;;
-N|--slot)
slot="$2"
shift
;;
-D|--no-check-fw)
no_check_fw=1
;;
-a|--addr)
fpga_ip="$2"
shift
;;
-g|--gui)
use_gui=1
;;
-s|--server)
;;
-h|--help)
usage
;;
*)
args="${args} $key"
;;
esac
shift
done
echo
# Verify mandatory parameters
# Check IP address or shelfmanager/slot number
if [ -z ${fpga_ip+x} ]; then
# If the IP address is not defined, shelfmanager and slot numebr must be defined
if [ -z ${shelfmanager+x} ]; then
echo "Shelfmanager not defined!"
usage
fi
if [ -z ${slot+x} ]; then
echo "Slot number not defined!"
usage
fi
echo "IP address was not defined. It will be calculated automatically from the crate ID and slot number..."
ipmb=$(expr 0128 + 2 \* $slot)
echo "Reading Crate ID via IPMI..."
crate_id=$(getCrateId)
echo "Create ID: ${crate_id}"
echo "Calculating FPGA IP address..."
fpga_ip=$(getFpgaIp)
echo "FPGA IP: ${fpga_ip}"
else
echo "IP address was defined. Ignoring shelfmanager and slot number. FW version checking disabled."
no_check_fw=1
fi
# Add the IP address to the SMuRF arguments
args="${args} -a ${fpga_ip}"
# Check if the server GUI was requested
if [ -z ${use_gui+x} ]; then
args="${args} -s"
else
echo "Server GUI enabled."
fi
# If the slot number is defined, add the RSSI link number argument
# which is needed if the PCIe card is used for communication
if [ ${slot+x} ]; then
# Verify that the slot number is in the range [2,7]
if [ ${slot} -ge 2 -a ${slot} -le 7 ]; then
args="${args} -l $((slot-2))"
else
echo "Invalid slot number! Must be a number between 2 and 7."
exit 1
fi
fi
# Extract the pyrogue tarball and update PYTHONPATH
echo "Looking for pyrogue tarball..."
pyrogue_file=$(find ${fw_top_dir} -maxdepth 1 -name *pyrogue.tar.gz)
if [ ! -f "$pyrogue_file" ]; then
pyrogue_file=$(find ${fw_top_dir} -maxdepth 1 -name *python.tar.gz)
if [ ! -f "$pyrogue_file" ]; then
echo "Pyrogue tarball file not found!"
exit 1
fi
fi
echo "Pyrogue file found: ${pyrogue_file}"
echo "Extracting the pyrogue tarball into ${fw_top_dir}/pyrogue..."
rm -rf ${fw_top_dir}/pyrogue
mkdir ${fw_top_dir}/pyrogue
tar -zxf ${pyrogue_file} -C ${fw_top_dir}/pyrogue
proj=$(ls ${fw_top_dir}/pyrogue)
export PYTHONPATH=${fw_top_dir}/pyrogue/${proj}/python:${PYTHONPATH}
echo "Done. Pyrogue extracted to ${fw_top_dir}/pyrogue/${proj}."
# Firmware version checking
if [ -z ${no_check_fw+x} ]; then
mcs_file=$(find ${fw_top_dir} -maxdepth 1 -name *mcs*)
if [ ! -f "${mcs_file}" ]; then
echo "MCS file not found!"
exit 1
fi
mcs_file_name=$(basename ${mcs_file})
echo ${mcs_file_name}
echo "Reading FW Git Hash via IPMI..."
fw_gh=$(getGitHashFW)
echo "Firmware githash: '$fw_gh'"
echo "Reading MCS file Git Hash..."
mcs_gh=$(getGitHashMcs)
echo "MCS file githash: '$mcs_gh'"
if [ "${fw_gh}" == "${mcs_gh}" ]; then
echo "They match..."
else
echo "They don't match. Loading image..."
ProgramFPGA.bash -s $shelfmanager -n $slot -m $mcs_file
fi
else
echo "Check firmware disabled."
fi
# MCE library location
MCE_LIB_PATH=/usr/local/src/smurf2mce/mcetransmit/lib/
export PYTHONPATH=$MCE_LIB_PATH:${PYTHONPATH}
echo "Starting server..."
cd /data/smurf2mce_config/
/usr/local/src/smurf2mce/mcetransmit/scripts/control-server/python/pyrogue_server.py ${args}
|
/**
* Copyright 2018-2020 Dynatrace LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.dynatrace.openkit.providers;
import org.junit.Test;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class FixedRandomNumberGeneratorTest {
@Test
public void nextPositiveLongReturnsAlwaysTheSameNumber() {
// given
long randomNumber = 1234567890;
RandomNumberGenerator mockRng = mock(RandomNumberGenerator.class);
when(mockRng.nextPositiveLong()).thenReturn(randomNumber, 1L, 2L, 4L, 5L);
FixedRandomNumberGenerator target = new FixedRandomNumberGenerator(mockRng);
for (int i = 0; i < 100; i++) {
// when
long obtained = target.nextPositiveLong();
// then
assertThat(obtained, is(randomNumber));
}
}
}
|
// Copyright 2019 Drone.IO Inc. All rights reserved.
// Use of this source code is governed by the Drone Non-Commercial License
// that can be found in the LICENSE file.
package acl
import (
"io/ioutil"
"net/http"
"net/http/httptest"
"testing"
"github.com/drone/drone/core"
"github.com/drone/drone/handler/api/request"
"github.com/sirupsen/logrus"
)
func init() {
logrus.SetOutput(ioutil.Discard)
}
var (
mockUser = &core.User{
ID: 1,
Login: "octocat",
Admin: false,
Active: true,
}
mockUserAdmin = &core.User{
ID: 1,
Login: "octocat",
Admin: true,
Active: true,
}
mockUserInactive = &core.User{
ID: 1,
Login: "octocat",
Admin: false,
Active: false,
}
mockRepo = &core.Repository{
ID: 1,
UID: "42",
Namespace: "octocat",
Name: "hello-world",
Slug: "octocat/hello-world",
Counter: 42,
Branch: "master",
Private: true,
Visibility: core.VisibilityPrivate,
}
)
func TestAuthorizeUser(t *testing.T) {
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "/", nil)
r = r.WithContext(
request.WithUser(r.Context(), mockUser),
)
AuthorizeUser(
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// use dummy status code to signal the next handler in
// the middleware chain was properly invoked.
w.WriteHeader(http.StatusTeapot)
}),
).ServeHTTP(w, r)
if got, want := w.Code, http.StatusTeapot; got != want {
t.Errorf("Want status code %d, got %d", want, got)
}
}
func TestAuthorizeUserErr(t *testing.T) {
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "/", nil)
AuthorizeUser(
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
t.Errorf("Must not invoke next handler in middleware chain")
}),
).ServeHTTP(w, r)
if got, want := w.Code, http.StatusUnauthorized; got != want {
t.Errorf("Want status code %d, got %d", want, got)
}
}
func TestAuthorizeAdmin(t *testing.T) {
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "/", nil)
r = r.WithContext(
request.WithUser(r.Context(), &core.User{Admin: true}),
)
AuthorizeAdmin(
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// use dummy status code to signal the next handler in
// the middleware chain was properly invoked.
w.WriteHeader(http.StatusTeapot)
}),
).ServeHTTP(w, r)
if got, want := w.Code, http.StatusTeapot; got != want {
t.Errorf("Want status code %d, got %d", want, got)
}
}
func TestAuthorizeAdminUnauthorized(t *testing.T) {
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "/", nil)
AuthorizeAdmin(
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
t.Errorf("Must not invoke next handler in middleware chain")
}),
).ServeHTTP(w, r)
if got, want := w.Code, http.StatusUnauthorized; got != want {
t.Errorf("Want status code %d, got %d", want, got)
}
}
func TestAuthorizeAdminForbidden(t *testing.T) {
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "/", nil)
r = r.WithContext(
request.WithUser(r.Context(), &core.User{Admin: false}),
)
AuthorizeAdmin(
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
t.Errorf("Must not invoke next handler in middleware chain")
}),
).ServeHTTP(w, r)
if got, want := w.Code, http.StatusForbidden; got != want {
t.Errorf("Want status code %d, got %d", want, got)
}
}
|
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'cm-studenti-container',
templateUrl: './studenti-container.component.html',
styleUrls: ['./studenti-container.component.scss']
})
export class StudentiContainerComponent implements OnInit {
students: any[] = [];
constructor(private http: HttpClient) {}
ngOnInit() {
this.fetchStudents();
}
fetchStudents() {
this.http.get<any[]>('https://api.example.com/students').subscribe(
(data) => {
this.students = data;
},
(error) => {
console.error('Error fetching student data:', error);
}
);
}
getAverageGrade() {
if (this.students.length === 0) {
return 0;
}
const totalGrade = this.students.reduce((acc, student) => acc + student.grade, 0);
return totalGrade / this.students.length;
}
} |
#!/usr/bin/env bash
set -ex
# Download and unpack Gloo
GLOO_VERSION=0.17.1
GLOO_CHART=gloo-${GLOO_VERSION}.tgz
DOWNLOAD_URL=https://storage.googleapis.com/solo-public-helm/charts/${GLOO_CHART}
wget $DOWNLOAD_URL
# Create CRDs template
helm template --namespace=gloo-system \
${GLOO_CHART} --values values.yaml \
`# Removing trailing whitespaces to make automation happy` \
| sed 's/[ \t]*$//' \
> gloo.yaml
# Clean up.
rm ${GLOO_CHART}
|
/**
* Implement Gatsby's Node APIs in this file.
*
* See: https://www.gatsbyjs.com/docs/node-apis/
*/
const createFrontPage = require( './create-pages/front-page' );
// const createAllPages = require( './create-pages/pages' );
// const createAllPosts = require( './create-pages/posts' );
// const createFrontPage = require( './create-pages/front-page' );
//const createBlogPage = require( './create-pages/blog' );
//const createArchivePage = require( './create-pages/archive' );
const path = require( 'path' );
// console.log("asdasdasdasd");
/**
*
* new create pages
*/
// Create all pages.
// console.log("create pages function start");
exports.createPages = async ( { actions, graphql } ) => {
// console.log("create pages function in process");
await createFrontPage( { actions, graphql } );
};
/**
* new create pages END
*/
/*
exports.createPages = ({ graphql, actions }) =>{
const { createPage } = actions
const blogPostTemplate = path.resolve(`src/templates/blog-post.js`)
return graphql(`
query PostsQuery{
wordPress{
posts{
nodes{
title
id
slug
uri
elementorData
}
}
}
}
`, { limit:1000 }).then(result => {
if (result.errors){
throw result.errors
}
//create blog post pages.
result.data.wordPress.posts.nodes.forEach(edge => {
createPage({
path: `${edge.uri}`,
component: blogPostTemplate,
context: edge,
})
})
})
}
*/
// exports.createPages = async ({ actions, graphql, reporter }) => {
// const result = await graphql(`
// {
// posts {
// nodes {
// uri
// title
// link
// content
// }
// }
// }
// `, { limit:1000 }).then(result => {
// if (result.errors){
// throw result.errors
// }
// //create blog post pages.
// result.data.wordPress.posts.nodes.forEach(edge => {
// createPage({
// path: `${edge.uri}`,
// component: blogPostTemplate,
// context: edge,
// })
// })
// })
// } |
<filename>src/routes/shadowBanUser.ts
import {db, privateDB} from '../databases/databases';
import {getHash} from '../utils/getHash';
import {Request, Response} from 'express';
export async function shadowBanUser(req: Request, res: Response) {
const userID = req.query.userID as string;
const hashedIP = req.query.hashedIP as string;
let adminUserIDInput = req.query.adminUserID as string;
const enabled = req.query.enabled === undefined
? false
: req.query.enabled === 'true';
//if enabled is false and the old submissions should be made visible again
const unHideOldSubmissions = req.query.unHideOldSubmissions !== "false";
if (adminUserIDInput == undefined || (userID == undefined && hashedIP == undefined)) {
//invalid request
res.sendStatus(400);
return;
}
//hash the userID
adminUserIDInput = getHash(adminUserIDInput);
const isVIP = db.prepare("get", "SELECT count(*) as userCount FROM vipUsers WHERE userID = ?", [adminUserIDInput]).userCount > 0;
if (!isVIP) {
//not authorized
res.sendStatus(403);
return;
}
if (userID) {
//check to see if this user is already shadowbanned
const row = privateDB.prepare('get', "SELECT count(*) as userCount FROM shadowBannedUsers WHERE userID = ?", [userID]);
if (enabled && row.userCount == 0) {
//add them to the shadow ban list
//add it to the table
privateDB.prepare('run', "INSERT INTO shadowBannedUsers VALUES(?)", [userID]);
//find all previous submissions and hide them
if (unHideOldSubmissions) {
db.prepare('run', "UPDATE sponsorTimes SET shadowHidden = 1 WHERE userID = ?", [userID]);
}
} else if (!enabled && row.userCount > 0) {
//remove them from the shadow ban list
privateDB.prepare('run', "DELETE FROM shadowBannedUsers WHERE userID = ?", [userID]);
//find all previous submissions and unhide them
if (unHideOldSubmissions) {
let segmentsToIgnore = db.prepare('all', "SELECT UUID FROM sponsorTimes st "
+ "JOIN noSegments ns on st.videoID = ns.videoID AND st.category = ns.category WHERE st.userID = ?"
, [userID]).map((item: {UUID: string}) => item.UUID);
let allSegments = db.prepare('all', "SELECT UUID FROM sponsorTimes st WHERE st.userID = ?", [userID])
.map((item: {UUID: string}) => item.UUID);
allSegments.filter((item: {uuid: string}) => {
return segmentsToIgnore.indexOf(item) === -1;
}).forEach((UUID: string) => {
db.prepare('run', "UPDATE sponsorTimes SET shadowHidden = 0 WHERE UUID = ?", [UUID]);
});
}
}
}
else if (hashedIP) {
//check to see if this user is already shadowbanned
// let row = privateDB.prepare('get', "SELECT count(*) as userCount FROM shadowBannedIPs WHERE hashedIP = ?", [hashedIP]);
// if (enabled && row.userCount == 0) {
if (enabled) {
//add them to the shadow ban list
//add it to the table
// privateDB.prepare('run', "INSERT INTO shadowBannedIPs VALUES(?)", [hashedIP]);
//find all previous submissions and hide them
if (unHideOldSubmissions) {
db.prepare('run', "UPDATE sponsorTimes SET shadowHidden = 1 WHERE timeSubmitted IN " +
"(SELECT privateDB.timeSubmitted FROM sponsorTimes LEFT JOIN privateDB.sponsorTimes as privateDB ON sponsorTimes.timeSubmitted=privateDB.timeSubmitted " +
"WHERE privateDB.hashedIP = ?)", [hashedIP]);
}
} /*else if (!enabled && row.userCount > 0) {
// //remove them from the shadow ban list
// privateDB.prepare('run', "DELETE FROM shadowBannedUsers WHERE userID = ?", [userID]);
// //find all previous submissions and unhide them
// if (unHideOldSubmissions) {
// db.prepare('run', "UPDATE sponsorTimes SET shadowHidden = 0 WHERE userID = ?", [userID]);
// }
}*/
}
res.sendStatus(200);
}
|
/*
* Copyright 2019 BROCKHAUS AG
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package end2ast;
import io.openvalidation.common.ast.ASTComparisonOperator;
import io.openvalidation.common.data.DataPropertyType;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
public class OfTests {
@Test
public void single_of() throws Exception {
String rule = "Berlin ALS Hauptstadt\n\nder Ort muss Hauptstadt sein";
End2AstRunner.run(
rule,
"{Name:'Satoshi',Alter:25,Ort:'Dortmund'}",
"de",
r -> {
r.sizeOfElements(2)
.rules()
.hasSizeOf(1)
.first()
.condition()
.hasOperator(ASTComparisonOperator.NOT_EQUALS)
.leftProperty()
.hasPath("Ort")
.hasType(DataPropertyType.String)
.parentCondition()
.rightVariable()
.hasName("Hauptstadt")
.parentModel()
.variables()
.hasSizeOf(1)
.first()
.hasString("Berlin")
.hasName("Hauptstadt");
});
}
@Test
public void multiple_of() throws Exception {
String rule = "der Ort des Landes muss Dortmund sein";
End2AstRunner.run(
rule,
"{Ort:''}",
"de",
r -> {
r.sizeOfElements(1)
.rules()
.hasSizeOf(1)
.first()
.condition()
.hasOperator(ASTComparisonOperator.NOT_EQUALS)
.leftProperty()
.hasPath("Ort")
.hasType(DataPropertyType.String)
.parentCondition()
.rightString("Dortmund");
});
}
@Test
public void multiple_of_in_if_then() throws Exception {
String rule = "wenn der Name des Benutzers gleich Validaria ist dann tues";
End2AstRunner.run(
rule,
"{Name:''}",
"de",
r -> {
r.sizeOfElements(1)
.rules()
.hasSizeOf(1)
.first()
.hasError("tues")
.condition()
.hasOperator(ASTComparisonOperator.EQUALS)
.leftProperty()
.hasPath("Name")
.hasType(DataPropertyType.String)
.parentCondition()
.rightString("Validaria");
});
}
//
@Test
public void as_alias_() throws Exception {
String rule = "die angegebene Berufserfahrung DARF nicht GRÖßER \n Als 20 sein";
End2AstRunner.run(
rule,
"{Berufserfahrung:0}",
"de",
r -> {
r.sizeOfElements(1)
.rules()
.hasSizeOf(1)
.first()
.condition()
.hasOperator(ASTComparisonOperator.GREATER_THAN)
.leftProperty()
.hasPath("Berufserfahrung")
.hasType(DataPropertyType.Decimal)
.parentCondition()
.rightNumber(20.0);
});
}
@Test
void simple_of_accessor_with_one_property() throws Exception {
String rule = "die größe der person muss GRÖßER Als 100 sein";
End2AstRunner.run(
rule,
"{Person: {Alter: 25, Größe: 180}}",
"de",
r -> {
r.sizeOfElements(1)
.rules()
.hasSizeOf(1)
.first()
.condition()
.hasOperator(ASTComparisonOperator.LESS_OR_EQUALS)
.leftProperty()
.hasPath("Person.Größe")
.hasType(DataPropertyType.Decimal)
.parentCondition()
.rightNumber(100.0);
});
}
@Test
void simple_of_accessor_with_two_properties() throws Exception {
String rule = "die größe der person muss GRÖßER Als das Alter der Person sein";
End2AstRunner.run(
rule,
"{Person: {Alter: 25, Größe: 180}}",
"de",
r -> {
r.sizeOfElements(1)
.rules()
.hasSizeOf(1)
.first()
.condition()
.hasOperator(ASTComparisonOperator.LESS_OR_EQUALS)
.leftProperty()
.hasPath("Person.Größe")
.hasType(DataPropertyType.Decimal)
.parentCondition()
.rightProperty()
.hasPath("Person.Alter")
.hasType(DataPropertyType.Decimal);
});
}
@Test
void simple_of_accessor_with_one_deep_property() throws Exception {
String rule = "die breite von person.maße muss GRÖßER Als 0 sein";
End2AstRunner.run(
rule,
"{Person: {Maße: {Breite: 55, Größe: 180}}}",
"de",
r -> {
r.sizeOfElements(1)
.rules()
.hasSizeOf(1)
.first()
.condition()
.hasOperator(ASTComparisonOperator.LESS_OR_EQUALS)
.leftProperty()
.hasPath("Person.Maße.Breite")
.hasType(DataPropertyType.Decimal)
.parentCondition()
.rightNumber(0.0);
});
}
@Test
void simple_of_accessor_with_multiple_deep_properties() throws Exception {
String rule = "0 als null\n\n1 als eins\n\ndie alter von person.infos muss GRÖßER Als 0 sein";
End2AstRunner.run(
rule,
"{Person: {Infos: {Name: Peter, Alter: 20}, Maße: {Breite: 55, Größe: 180}}}",
"de",
r -> {
r.sizeOfElements(3)
.rules()
.hasSizeOf(1)
.first()
.condition()
.hasOperator(ASTComparisonOperator.LESS_OR_EQUALS)
.leftProperty()
.hasPath("Person.Infos.Alter")
.hasType(DataPropertyType.Decimal)
.parentCondition()
.rightNumber(0.0);
});
}
@ParameterizedTest
@CsvSource({
"Height of Metrics BIGGER THAN 180 AS over-average",
"The Height of Metrics BIGGER THAN 180 AS over-average",
"The Height measurement of Metrics BIGGER THAN 180 AS over-average",
"Height of the Metrics BIGGER THAN 180 AS over-average",
"The Height of the Metrics BIGGER THAN 180 AS over-average",
"The Height measurement of the Metrics BIGGER THAN 180 AS over-average",
"Height of the Metrics given BIGGER THAN 180 AS over-average",
"The Height of the Metrics given BIGGER THAN 180 AS over-average",
"The Height measurement of the Metrics given BIGGER THAN 180 AS over-average",
"Height of the Metrics given is BIGGER THAN 180 AS over-average",
"The Height of the Metrics given is BIGGER THAN 180 AS over-average",
"The Height measurement of the Metrics given is BIGGER THAN 180 AS over-average"
})
void simple_of_accessor_on_unique_property_in_comparison(String variable) throws Exception {
End2AstRunner.run(
variable,
"{Person: {Info: {Name: Peter, Age: 20}, Metrics: {Breadth: 55, Height: 180}}}",
r -> {
r.sizeOfElements(1)
.variables()
.hasSizeOf(1)
.first()
.condition()
.hasOperator(ASTComparisonOperator.GREATER_THAN)
.leftProperty()
.hasPath("Person.Metrics.Height")
.hasType(DataPropertyType.Decimal)
.parentCondition()
.rightNumber(180.0);
});
}
@ParameterizedTest
@CsvSource({
"adult of person is true as var1",
"the property adult of person is true as var1",
"the property adult here of person is true as var1",
"adult of person is indeed true as var1",
"the property adult of person is indeed true as var1",
"the property adult here of person is indeed true as var1",
"adult of person is indeed true as fact as var1",
"the property adult of person is indeed true as fact as var1",
"the property adult here of person is indeed true as fact as var1",
})
void simple_of_accessor_on_unique_property_with_bool_comparison(String variable)
throws Exception {
End2AstRunner.run(
variable,
"{Protocol: {Person: {Name: Peter, Age: 20, Adult: true}}}",
r -> {
r.sizeOfElements(1)
.variables()
.hasSizeOf(1)
.first()
.condition()
.hasOperator(ASTComparisonOperator.EQUALS)
.leftProperty()
.hasPath("Protocol.Person.Adult")
.hasType(DataPropertyType.Boolean)
.parentCondition()
.rightBoolean(true);
});
}
@ParameterizedTest
@CsvSource({
"If adult of person then error",
"If the property adult of person then error",
"If the property adult here of person then error"
})
void simple_of_accessor_on_unique_property_with_bool_comparison_implicit(String variable)
throws Exception {
End2AstRunner.run(
variable,
"{Protocol: {Person: {Name: Peter, Age: 20, Adult: true}}}",
r -> {
r.sizeOfElements(1)
.rules()
.hasSizeOf(1)
.first()
.condition()
.hasOperator(ASTComparisonOperator.EQUALS)
.leftProperty()
.hasPath("Protocol.Person.Adult")
.hasType(DataPropertyType.Boolean)
.parentCondition()
.rightBoolean(true);
});
}
@ParameterizedTest
@CsvSource({
"name of random person AS var1",
"the property name of random person AS var1",
"the property name here of random person AS var1"
})
void simple_of_accessor_on_unique_property_with_underscore_by_using_space_entity(String variable)
throws Exception {
End2AstRunner.run(
variable,
"{Protocol: {Random_Person: {Name: Peter, Age: 20, Adult: true}}}",
r -> {
r.sizeOfElements(1)
.variables()
.hasSizeOf(1)
.first()
.operandProperty()
.hasPath("Protocol.Random_Person.Name")
.hasType(DataPropertyType.String);
});
}
@ParameterizedTest
@CsvSource({
"first name of person AS var1",
"the property first name of person AS var1",
"the property first name here of person AS var1",
"the first name of the person in question AS var1"
})
void simple_of_accessor_on_unique_property_with_underscore_by_using_space_property(
String variable) throws Exception {
End2AstRunner.run(
variable,
"{Protocol: {Person: {First_Name: Peter, Age: 20, Adult: true}}}",
r -> {
r.sizeOfElements(1)
.variables()
.hasSizeOf(1)
.first()
.operandProperty()
.hasPath("Protocol.Person.First_Name")
.hasType(DataPropertyType.String);
});
}
}
|
#!/bin/bash
# Module specific variables go here
# Files: file=/path/to/file
# Arrays: declare -a array_name
# Strings: foo="bar"
# Integers: x=9
###############################################
# Bootstrapping environment setup
###############################################
# Get our working directory
cwd="$(pwd)"
# Define our bootstrapper location
bootstrap="${cwd}/tools/bootstrap.sh"
# Bail if it cannot be found
if [ ! -f ${bootstrap} ]; then
echo "Unable to locate bootstrap; ${bootstrap}" && exit 1
fi
# Load our bootstrap
source ${bootstrap}
###############################################
# Metrics start
###############################################
# Get EPOCH
s_epoch="$(gen_epoch)"
# Create a timestamp
timestamp="$(gen_date)"
# Whos is calling? 0 = singular, 1 is as group
caller=$(ps $PPID | grep -c stigadm)
###############################################
# Perform restoration
###############################################
# If ${restore} = 1 go to restoration mode
if [ ${restore} -eq 1 ]; then
report "Not yet implemented" && exit 1
fi
###############################################
# STIG validation/remediation
###############################################
# Module specific validation code should go here
# Errors should go in ${errors[@]} array (which on remediation get handled)
# All inspected items should go in ${inspected[@]} array
errors=("${stigid}")
# If ${change} = 1
#if [ ${change} -eq 1 ]; then
# Create the backup env
#backup_setup_env "${backup_path}"
# Create a backup (configuration output, file/folde permissions output etc
#bu_configuration "${backup_path}" "${author}" "${stigid}" "$(echo "${array_values[@]}" | tr ' ' '\n')"
#bu_file "${backup_path}" "${author}" "${stigid}" "${file}"
#if [ $? -ne 0 ]; then
# Stop, we require a backup
#report "Unable to create backup" && exit 1
#fi
# Iterate ${errors[@]}
#for error in ${errors[@]}; do
# Work to remediate ${error} should go here
#done
#fi
# Remove dupes
#inspected=( $(remove_duplicates "${inspected[@]}") )
###############################################
# Results for printable report
###############################################
# If ${#errors[@]} > 0
if [ ${#errors[@]} -gt 0 ]; then
# Set ${results} error message
#results="Failed validation" UNCOMMENT ONCE WORK COMPLETE!
results="Not yet implemented!"
fi
# Set ${results} passed message
[ ${#errors[@]} -eq 0 ] && results="Passed validation"
###############################################
# Report generation specifics
###############################################
# Apply some values expected for report footer
[ ${#errors[@]} -eq 0 ] && passed=1 || passed=0
[ ${#errors[@]} -gt 0 ] && failed=1 || failed=0
# Calculate a percentage from applied modules & errors incurred
percentage=$(percent ${passed} ${failed})
# If the caller was only independant
if [ ${caller} -eq 0 ]; then
# Show failures
[ ${#errors[@]} -gt 0 ] && print_array ${log} "errors" "${errors[@]}"
# Provide detailed results to ${log}
if [ ${verbose} -eq 1 ]; then
# Print array of failed & validated items
[ ${#inspected[@]} -gt 0 ] && print_array ${log} "validated" "${inspected[@]}"
fi
# Generate the report
report "${results}"
# Display the report
cat ${log}
else
# Since we were called from stigadm
module_header "${results}"
# Show failures
[ ${#errors[@]} -gt 0 ] && print_array ${log} "errors" "${errors[@]}"
# Provide detailed results to ${log}
if [ ${verbose} -eq 1 ]; then
# Print array of failed & validated items
[ ${#inspected[@]} -gt 0 ] && print_array ${log} "validated" "${inspected[@]}"
fi
# Finish up the module specific report
module_footer
fi
###############################################
# Return code for larger report
###############################################
# Return an error/success code (0/1)
exit ${#errors[@]}
# Date: 2018-09-19
#
# Severity: CAT-III
# Classification: UNCLASSIFIED
# STIG_ID: V0050707
# STIG_Version: SV-64913r1
# Rule_ID: OL6-00-000342
#
# OS: Oracle_Linux
# Version: 6
# Architecture:
#
# Title: The system default umask for the bash shell must be 077.
# Description: The umask value influences the permissions assigned to files when they are created. A misconfigured umask value could result in files with excessive permissions that can be read and/or written to by unauthorized users.
|
/**
* 游戏触屏事件
*/
H7.Events = (function() {
return {
nodeList: [],
/**
* 注册事件
*/
on: function(eventName, fn) {
var t = this;
if (window.addEventListener) {
this.gamecanvas.addEventListener(eventName, function() {
fn && fn.apply(t, arguments);
}, false);
} else {
this.gamecanvas.attachEvent("on" + eventName, function() {
fn && fn.apply(t, arguments);
});
}
},
/**
* 注销事件
*/
off: function(obj, eventName, fn) {
if (obj.removeEventListener) {
obj.removeEventListener(eventName, fn, false);
} else {
obj.detachEvent("on" + eventName, fn);
}
},
/**
* 获取相对位置
*/
getPos: function(e) {
e.stopPropagation && e.stopPropagation();
e.preventDefault && e.preventDefault();
if (e.changedTouches) {
var lx = e.changedTouches[0].pageX,
ly = e.changedTouches[0].pageY;
} else {
var lx = e.x,
ly = e.y;
}
var topOffset = 0;
var leftOffset = 0;
if (!this.offset) {
var obj = this.gamecanvas;
while (obj && obj.tagName != 'BODY') {
topOffset += (obj.offsetTop || 0);
leftOffset += (obj.offsetLeft || 0);
obj = obj.offsetParent;
}
lx -= leftOffset;
ly -= topOffset;
this.offset = {
top: topOffset,
left: leftOffset
};
} else {
topOffset = this.offset.top;
leftOffset = this.offset.left;
}
var wSize = H7.Game.getSize(),
clientSize = H7.Game.getClientSize();
var bitX = 1,
bitY = 1;
if (H7.Game.sizeType == 1) {
bitX = bitY = wSize.width / clientSize.width;
} else if (H7.Game.sizeType == 2) {
bitX = bitY = wSize.height / clientSize.height;
} else if (H7.Game.sizeType == 3) {
bitX = wSize.width / clientSize.width;
bitY = wSize.height / clientSize.height;
}
return {
x: lx * bitX,
y: ly * bitY
};
},
// 监测点是否在节点上
checkPointInNode: function(x, y, node) {
var pos = node.getAbsolutePos();
var size = node.getAbsoluteSize();
// x轴是否包涵在内
if (x < pos.x || x > pos.x + size.width) {
return false;
}
// y轴是否包含在内
if (y < pos.y || y > pos.y + size.height) {
return false;
}
return true;
},
_execEvent: function(e, name) {
var t = this;
var pos = this.getPos(e);
var scene = H7.Game.currentScene();
var eNs = (function(parent, eventNodes) {
if (parent._childrenList) {
var len = parent._childrenList.length;
for (var i = 0; i < len; i++) {
var node = parent._childrenList[i].node;
if (node.visible && (t.checkPointInNode(pos.x, pos.y, node) || node instanceof H7.Layer)) {
var isHad = false;
for (var ii = eventNodes.length - 1; ii >= 0; ii--) {
if (eventNodes[ii] == node) {
isHad = true;
break;
}
}
if (!isHad) {
eventNodes.push(node);
}
arguments.callee.call(this, node, eventNodes);
}
}
}
return eventNodes;
})(scene, []);
var len = eNs.length;
for (var i = len - 1; i >= 0; i--) {
var swallow = (function(eNode) {
if (eNode && eNode._events && eNode._events[name]) {
var ret = eNode._events[name].call(eNode, pos);
if (ret == false) {
return true;
}
}
if (eNode && !eNode.swallow) {
var ret = arguments.callee.call(eNode.target, eNode.target);
if (ret != undefined) {
return ret;
}
}
if (eNode) {
return eNode.swallow
}
})(eNs[i]);
if (swallow) {
break;
}
}
},
_touchStart: function(e) {
this._execEvent(e, "touchStart");
},
_touchMove: function(e) {
this._execEvent(e, "touchMove");
},
_touchEnd: function(e) {
this._execEvent(e, "touchEnd");
},
_touchCancel: function(e) {
this._execEvent(e, "touchCancel");
},
/**
* 初始化事件
*/
init: function() {
this.gamecanvas = H7.Game.ctx.canvas;
this.on("touchstart", this._touchStart);
this.on("touchmove", this._touchMove);
this.on("touchend", this._touchEnd);
this.on("touchcancel", this._touchCancel);
this.on("mousedown", this._touchStart);
this.on("mousemove", this._touchMove);
this.on("mouseup", this._touchEnd);
this.on("mouseover", this._touchCancel);
},
/**
* 加入需要事件处理的Node
*/
set: function(node, index) {
this.nodeList.push(node);
},
/**
* 场景事件清除
*/
clear: function() {
this.nodeList = [];
},
/**
* 新建事件
*/
newEvent: function(name, x, y, w, h, fn) {
var n = {
_events: {},
x: x,
y: y,
width: w,
height: h
};
n._events[name] = fn;
this.set(n, 10000);
},
touchStart: function(x, y, w, h, fn) {
this.newEvent("touchStart", x, y, w, h, fn);
},
touchMove: function(x, y, w, h, fn) {
this.newEvent("touchMove", x, y, w, h, fn);
},
touchEnd: function(x, y, w, h, fn) {
this.newEvent("touchEnd", x, y, w, h, fn);
},
touchCancel: function(x, y, w, h, fn) {
this.newEvent("touchCancel", x, y, w, h, fn);
}
};
})(); |
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
export function getInternalDevToolsModule<TModule>(): TModule {
throw new Error(
"Can't require internal version of React DevTools from public version of Flipper.",
);
}
|
<filename>src/code_katas/proper_parenthetics.py
"""Check if a string of parens is balanced, open or brokend."""
from src.stack import Stack
def proper_parens(str):
"""Return 0 if string of parens is balanced, 1 if open and -1 if broken."""
stack = Stack()
for i in str:
if i is '(':
stack.push(i)
print('data', stack._container.head.data)
elif i is ')':
try:
stack.pop()
except IndexError:
return -1
if stack._container.head:
return 1
return 0
|
#!/bin/sh
java -cp lib/*:indexer/target/classes com.gitee.kooder.indexer.PathImporter $* |
package Shop_Skins;
import java.io.BufferedReader;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.json.HTTP;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Servlet implementation class Points
*/
@WebServlet("/Points")
public class Points extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public Points() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//ShopBean anlegen
Shop_Bean shopBean = (Shop_Bean) request.getAttribute("shopBean");
//Testen ob leer wenn nicht neu anlegen
if (shopBean == null) {
shopBean = new Shop_Bean();
request.setAttribute("registerBean", shopBean);
}
StringBuffer jb = new StringBuffer();
String line = null;
try {
BufferedReader reader = request.getReader();
while ((line = reader.readLine()) != null)
jb.append(line);
} catch (Exception e) { /*report an error*/ }
try {
JSONObject jsonObject = HTTP.toJSONObject(jb.toString());
} catch (JSONException e) {
// crash and burn
throw new IOException("Error parsing JSON request string");
}
int points=Integer.parseInt(jb.substring(jb.indexOf(":")+1,jb.indexOf("}")));
HttpSession session = request.getSession(true);
String user=((String)session.getAttribute("email"));
if(user!=null) {
shopBean.addPoints(user, points);
}
}
}
|
<gh_stars>0
require 'sinatra/base'
require 'twilio-ruby'
require 'dotenv/load'
require_relative 'send_sms.rb'
class Takeaway < Sinatra::Base
enable :sessions, :method_override
set :public_folder, 'public'
get '/' do
erb :index
end
get '/confirmation' do
time = Time.new
hours_time = "#{(time.hour)+1}:#{time.min}"
#Comment out following 2 lines to prevent accidental call to Twilio API
message = Message.new(hours_time)
message.send_message
erb :confirmation
end
run! if app_file == $0
end |
var dir_895bac71a5ab2f3f201ab1eda13a633d =
[
[ "TestAdd.cpp", "_test_add_8cpp.xhtml", "_test_add_8cpp" ],
[ "TestConcat.cpp", "_test_concat_8cpp.xhtml", "_test_concat_8cpp" ],
[ "TestConvolution.cpp", "_test_convolution_8cpp.xhtml", "_test_convolution_8cpp" ],
[ "TestDropout.cpp", "_test_dropout_8cpp.xhtml", "_test_dropout_8cpp" ],
[ "TestInPlace.cpp", "_test_in_place_8cpp.xhtml", "_test_in_place_8cpp" ],
[ "TestInputs.cpp", "_test_inputs_8cpp.xhtml", "_test_inputs_8cpp" ],
[ "TestMul.cpp", "_test_mul_8cpp.xhtml", "_test_mul_8cpp" ],
[ "TestMultiInputsOutputs.cpp", "armnn_caffe_parser_2test_2_test_multi_inputs_outputs_8cpp.xhtml", "armnn_caffe_parser_2test_2_test_multi_inputs_outputs_8cpp" ],
[ "TestPooling2d.cpp", "_test_pooling2d_8cpp.xhtml", "_test_pooling2d_8cpp" ],
[ "TestSplit.cpp", "_test_split_8cpp.xhtml", "_test_split_8cpp" ]
]; |
#!/bin/bash
rm timings
rm wallclock
echo 'Linearising'
echo 'Wallclock time for generating and solving PBES:' > wallclock
echo 'mcrl22lps:' >> wallclock
{ time mcrl22lps -nf --timings=timings minepump.mcrl2 | lpssumelm > minepump.lps ; } 2>> wallclock
echo 'lps2pbes:' >> wallclock
echo 'Converting to PBES'
{ time lps2pbes --timings=timings -mf prop2.mcf minepump.lps | pbesconstelm --timings=timings | pbesparelm --timings=timings > minepump.pbes ; } 2>> wallclock
echo 'Solving PBES'
echo 'pbespgsolve:' >> wallclock
{ time pbespgsolve --timings=timings -rjittyc -srecursive minepump.pbes ; } 2>> wallclock
rm -rf *.pbes
rm -rf *.lps
|
<gh_stars>1-10
package view
///////////////////////////////////////////////////////////////////////////////
// Paragraph
type Paragraph struct {
ViewBaseWithId
Class string
Content View
}
func (self *Paragraph) IterateChildren(callback IterateChildrenCallback) {
if self.Content != nil {
callback(self, self.Content)
}
}
func (self *Paragraph) Render(ctx *Context) (err error) {
ctx.Response.XML.OpenTag("p")
ctx.Response.XML.AttribIfNotDefault("id", self.id)
ctx.Response.XML.AttribIfNotDefault("class", self.Class)
if self.Content != nil {
err = self.Content.Render(ctx)
}
ctx.Response.XML.CloseTagAlways()
return err
}
|
<gh_stars>1-10
package com.example.blockchainapp.HelpRequest;
public class HelpRequest {
private String campaignName;
private String username;
private Long amount;
private String message;
public HelpRequest(String campaignName, String username, Long amount, String message) {
this.campaignName = campaignName;
this.username = username;
this.amount = amount;
this.message = message;
}
public String getCampaignName() {
return campaignName;
}
public void setCampaignName(String campaignName) {
this.campaignName = campaignName;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Long getAmount() {
return amount;
}
public void setAmount(Long amount) {
this.amount = amount;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
|
#!/bin/bash
java -jar lib/papaya-builder.jar $* |
<filename>internal/ps/ps.go<gh_stars>0
package ps
import (
"os/exec"
"strconv"
"strings"
)
// Exec invokes ps -o keywords -p pid and returns its output
func Exec(pid int, keywords string) (string, error) {
out, err := exec.Command("ps", "-o", keywords, "-p", strconv.Itoa(pid)).Output()
if err != nil {
return "", err
}
return strings.TrimSpace(string(out)), nil
}
// Comm invokes ps -o comm= -p pid and returns its output
func Comm(pid int) (string, error) {
return Exec(pid, "comm=")
}
|
import React, {Component} from 'react';
class AudioPlayer extends Component{
static defaultProps = {
fastForwardStep: 10,
volumeStep: 0.05,
minVolume: 0,
maxVolume: 1,
maxProgress: 100
}
state = {
progress: 0,
volume: 0.5
}
componentDidMount() {
this._audio.volume = this.state.volume;
this._range.value = this.state.volume;
this._audio.addEventListener('loadedmetadata', this.loadedmetadata.bind(this));
}
loadedmetadata(e) {
const au = e.target;
const duration = au.duration;
this._progress.max = duration;
}
componentWillUnmount() {
this._audio.removeEventListener('loadedmetadata', this.loadedmetadata);
}
render() {
const {minVolume, maxVolume, volumeStep, maxProgress} = this.props;
return <div>
<ul>
<li>Gson & Abley,Amasi - Heaven (Radio Edit).mp3</li>
</ul>
<audio src="http://7xp9vw.com1.z0.glb.clouddn.com/Gson%20&%20Abley,Amasi%20-%20Heaven%20%28Radio%20Edit%29.mp3"
preload="metadata" ref={ref => this._audio = ref} onTimeUpdate={(e) => this.onTimeUpdate(e)}>
<p>Your browser does not support the <code>audio</code> element </p>
</audio>
<div>
<progress onClick={e => this.handleProgress(e)} value={this.state.progress || 0.1} max={maxProgress}
ref={ref => this._progress = ref}></progress>
</div>
<div>
<button type="button" onClick={() => this.play()}>play</button>
<button type="button" onClick={() => this.pause()}>pause</button>
<button type="button" onClick={() => this.stop()}>stop</button>
<button type="button" onClick={() => this.fastForward()}>FastForward</button>
<button type="button" onClick={() => this.rewind()}>Rewind</button>
</div>
<div>
<label>
<input type="range" name="volume" min={minVolume} max={maxVolume} step={volumeStep}
onChange={() => this.handleVolume()}
ref={ref => this._range = ref}/>
volume: <span>{new Number(this.state.volume * 100).toFixed(2) + '%'}</span>
</label>
</div>
</div>
}
handleProgress(e) {
e.persist();
// console.log(e);
const prg = e.target;
const percent = e.clientX / e.target.clientWidth;
// console.log(percent);
this._audio.currentTime = percent * this._progress.max;
}
play() {
if(this._audio.ended || this._audio.paused) {
this._audio.play();
}
}
pause() {
this._audio.pause();
}
stop() {
this.pause();
this._audio.currentTime = 0;
}
handleVolume() {
const value = this._range.value;
console.log('volume: %s', value);
this._audio.volume = value;
this.setState({volume: value});
}
fastForward() {
this._audio.currentTime += this.props.fastForwardStep;
}
rewind() {
this._audio.currentTime -= this.props.fastForwardStep;
}
onTimeUpdate(e) {
const {currentTime, duration} = this._audio;
// console.log('currentTime: %s', currentTime);
// console.log('duration: %s', duration);
this.setState({progress: currentTime});
}
}
export default AudioPlayer;
|
#!/bin/bash
function bootloader() {
# Install grub
if [ $EFI -eq 1 ]; then
grub-install --target=x86_64-efi --efi-directory=/boot --bootloader-id=grub_uefi --recheck
elif [ $EFI -eq 0 ]; then
grub-install /dev/$INSTALLDISK
fi
grub-mkconfig -o /boot/grub/grub.cfg
} |
<reponame>NBNARADHYA/cl-judge
const { pool } = require('../database')
/**
*
* @param {*} param0
* @param {Object} param0.params
* @param {Object} param0.body
* @param {Object} param0.username
* @return {Promise}
*
*/
function addBranch({ params, body, username }) {
return new Promise((resolve, reject) => {
const { group_id: groupId } = params
const { department, course, admission_year: admissionYear } = body
pool.getConnection((error, connection) => {
if (error) {
return reject(error)
}
connection.beginTransaction((error) => {
if (error) {
connection.release()
return reject(error)
}
connection.query(
`INSERT INTO user_groups (username, group_id, is_group_moderator)
SELECT username,?,0 FROM users WHERE department=? AND course=? AND admission_year=?
AND EXISTS(SELECT 1 FROM user_groups WHERE username=? AND group_id=? AND is_group_moderator=1)
ON DUPLICATE KEY UPDATE group_id=group_id`,
[groupId, department, course, admissionYear, username, groupId],
(error, results) => {
if (error) {
return connection.rollback(() => {
connection.release()
return reject(error)
})
}
const { affectedRows } = results
if (!affectedRows) {
return connection.rollback(() => {
connection.release()
return reject(
'Either you do not have moderator access of the group or there is no user with this branch'
)
})
}
connection.query(
`UPDATE \`groups\` SET member_count = (SELECT COUNT(username) FROM user_groups WHERE group_id=?) WHERE id=?`,
[groupId, groupId],
(error) => {
if (error) {
return connection.rollback(() => {
connection.release()
return reject(error)
})
}
connection.commit((error) => {
if (error) {
return connection.rollback(() => {
connection.release()
return reject(error)
})
}
connection.release()
return resolve({
message: 'Branch added successfully!',
branchMembersCount: affectedRows,
})
})
}
)
}
)
})
})
})
}
module.exports = addBranch
|
SELECT COUNT(*)
FROM Employee
WHERE Salary > (
SELECT AVG(Salary)
FROM Employee
); |
import { Column } from "./column.model";
/**
* This class represents as boards of square
*/
export class Board {
/**
* this params for create a new board
* @param name
* @param columns
*/
constructor(public name: string, public columns: Column[]) {}
} |
package dev.webfx.kit.mapper.peers.javafxgraphics.gwt.html;
import dev.webfx.kit.mapper.peers.javafxgraphics.SceneRequester;
import dev.webfx.kit.mapper.peers.javafxgraphics.base.TextPeerBase;
import dev.webfx.kit.mapper.peers.javafxgraphics.base.TextPeerMixin;
import dev.webfx.kit.mapper.peers.javafxgraphics.gwt.html.layoutmeasurable.HtmlLayoutMeasurableNoHGrow;
import dev.webfx.kit.mapper.peers.javafxgraphics.gwt.shared.SvgRoot;
import dev.webfx.kit.mapper.peers.javafxgraphics.gwt.shared.SvgRootBase;
import dev.webfx.kit.mapper.peers.javafxgraphics.gwt.svg.SvgTextPeer;
import dev.webfx.kit.mapper.peers.javafxgraphics.gwt.util.HtmlUtil;
import dev.webfx.kit.mapper.peers.javafxgraphics.gwt.util.SvgUtil;
import elemental2.dom.*;
import elemental2.svg.SVGRect;
import javafx.geometry.VPos;
import javafx.scene.effect.Effect;
import javafx.scene.paint.Paint;
import javafx.scene.shape.StrokeLineCap;
import javafx.scene.shape.StrokeLineJoin;
import javafx.scene.shape.StrokeType;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.scene.text.TextAlignment;
import java.util.List;
/**
* @author <NAME>
*/
public final class HtmlSvgTextPeer
<N extends Text, NB extends TextPeerBase<N, NB, NM>, NM extends TextPeerMixin<N, NB, NM>>
extends HtmlShapePeer<N, NB, NM>
implements TextPeerMixin<N, NB, NM>, HtmlLayoutMeasurableNoHGrow {
private final Element svgElement = SvgUtil.createSvgElement("svg");
private SvgTextPeer svgTextPeer = new SvgTextPeer();
public HtmlSvgTextPeer() {
this((NB) new TextPeerBase(), HtmlUtil.createElement("div"));
}
public HtmlSvgTextPeer(NB base, HTMLElement element) {
super(base, element);
}
@Override
public void bind(N node, SceneRequester sceneRequester) {
svgTextPeer.getNodePeerBase().setNode(node);
SvgRoot svgRoot = new SvgRootBase();
node.getProperties().put("svgRoot", svgRoot);
HtmlUtil.setChildren(svgElement, svgRoot.getDefsElement(), svgTextPeer.getElement());
HtmlUtil.appendChild(DomGlobal.document.body, svgElement);
super.bind(node, sceneRequester);
HtmlUtil.setChild(getElement(), svgElement);
}
private SVGRect bBox;
private SVGRect getBBox() {
//if (bBox == null)
bBox = svgTextPeer.getBBox();
return bBox;
}
@Override
public void updateEffect(Effect effect) {
svgTextPeer.updateEffect(effect);
updateViewBox();
}
@Override
public void updateFill(Paint fill) {
svgTextPeer.updateFill(fill);
}
@Override
public void updateStroke(Paint stroke) {
svgTextPeer.updateStroke(stroke);
}
@Override
public void updateStrokeWidth(Double strokeWidth) {
svgTextPeer.updateStrokeWidth(strokeWidth);
}
@Override
public void updateStrokeType(StrokeType strokeType) {
svgTextPeer.updateStrokeType(strokeType);
}
@Override
public void updateStrokeLineCap(StrokeLineCap strokeLineCap) {
svgTextPeer.updateStrokeLineCap(strokeLineCap);
}
@Override
public void updateStrokeLineJoin(StrokeLineJoin strokeLineJoin) {
svgTextPeer.updateStrokeLineJoin(strokeLineJoin);
}
@Override
public void updateStrokeMiterLimit(Double strokeMiterLimit) {
svgTextPeer.updateStrokeMiterLimit(strokeMiterLimit);
}
@Override
public void updateStrokeDashOffset(Double strokeDashOffset) {
svgTextPeer.updateStrokeDashOffset(strokeDashOffset);
}
@Override
public void updateStrokeDashArray(List<Double> dashArray) {
svgTextPeer.updateStrokeDashArray(dashArray);
}
@Override
public double measure(HTMLElement e, boolean width) {
return width ? getBBox().width : getBBox().height;
}
/*
private final HtmlLayoutCache cache = new HtmlLayoutCache();
@Override
public HtmlLayoutCache getCache() {
return cache;
}
*/
private void updateViewBox() {
SVGRect bb = getBBox(); // Note: bBox doesn't include strokes, nor effect (drop shadow, etc...)
double width = bb.width, height = bb.height, x = bb.x, y = bb.y;
// Adding extra space if there is an effect to prevent it to be clipped
if (getNode().getEffect() != null) {
// Assuming 20px will be enough - TODO: Make an accurate computation
width += 20;
height += 20;
}
svgElement.setAttribute("width", width);
svgElement.setAttribute("height", height);
svgElement.setAttribute("viewBox", x + " " + y + " " + width + " " + height);
svgElement.setAttribute("overflow", "visible"); // To avoid clipping the strokes (but may clip shadow, that's why we added margin in the viewBox)
}
@Override
public void updateText(String text) {
svgTextPeer.updateText(text);
updateViewBox();
}
@Override
public void updateTextOrigin(VPos textOrigin) {
svgTextPeer.updateTextOrigin(textOrigin);
}
@Override
public void updateX(Double x) {
svgTextPeer.updateX(x);
}
@Override
public void updateY(Double y) {
svgTextPeer.updateY(y);
}
@Override
public void updateWrappingWidth(Double wrappingWidth) {
svgTextPeer.updateWrappingWidth(wrappingWidth);
}
@Override
public void updateTextAlignment(TextAlignment textAlignment) {
svgTextPeer.updateTextAlignment(textAlignment);
}
@Override
public void updateFont(Font font) {
svgTextPeer.updateFont(font);
updateViewBox();
}
}
|
// @flow
import { Trans } from '@lingui/macro';
import React, { Component } from 'react';
import Timer from '@material-ui/icons/Timer';
import FlatButton from '../../../UI/FlatButton';
import Checkbox from '../../../UI/Checkbox';
import Brush from '@material-ui/icons/Brush';
import PlayArrow from '@material-ui/icons/PlayArrow';
import TextField from '../../../UI/TextField';
import Dialog from '../../../UI/Dialog';
import AnimationPreview from './AnimationPreview';
import ResourcesLoader from '../../../ResourcesLoader';
import { type ResourceExternalEditor } from '../../../ResourcesList/ResourceExternalEditor.flow';
import { ResponsiveWindowMeasurer } from '../../../UI/Reponsive/ResponsiveWindowMeasurer';
const styles = {
container: {
paddingLeft: 12,
paddingRight: 12,
display: 'flex',
alignItems: 'center',
},
timeField: {
width: 75,
},
timeIcon: {
paddingLeft: 6,
paddingRight: 6,
},
repeatContainer: {
width: 130,
},
spacer: {
width: 16,
},
};
const formatTime = (time: number) => Number(time.toFixed(6));
type Props = {|
direction: gdDirection,
resourcesLoader: typeof ResourcesLoader,
project: gdProject,
resourceExternalEditors: Array<ResourceExternalEditor>,
onEditWith: ResourceExternalEditor => void,
|};
type State = {|
timeBetweenFrames: number,
timeError: boolean,
previewOpen: boolean,
|};
export default class DirectionTools extends Component<Props, State> {
state = {
timeBetweenFrames: formatTime(this.props.direction.getTimeBetweenFrames()),
timeError: false,
previewOpen: false,
};
componentWillReceiveProps(newProps: Props) {
this.setState({
timeBetweenFrames: formatTime(
this.props.direction.getTimeBetweenFrames()
),
timeError: false,
});
}
saveTimeBetweenFrames = () => {
const { direction } = this.props;
const newTime = Math.max(parseFloat(this.state.timeBetweenFrames), 0.00001);
const newTimeIsValid = !isNaN(newTime);
if (newTimeIsValid) direction.setTimeBetweenFrames(newTime);
this.setState({
timeBetweenFrames: formatTime(
this.props.direction.getTimeBetweenFrames()
),
timeError: newTimeIsValid,
});
};
setLooping = (check: boolean) => {
const { direction } = this.props;
direction.setLoop(!!check);
this.forceUpdate();
};
openPreview = (open: boolean) => {
this.setState({
previewOpen: open,
});
if (!open) {
this.saveTimeBetweenFrames();
}
};
render() {
const {
direction,
resourcesLoader,
project,
resourceExternalEditors,
onEditWith,
} = this.props;
const imageResourceExternalEditors = resourceExternalEditors.filter(
({ kind }) => kind === 'image'
);
return (
<div style={styles.container}>
<ResponsiveWindowMeasurer>
{windowWidth =>
windowWidth !== 'small' &&
!!imageResourceExternalEditors.length && (
<FlatButton
label={imageResourceExternalEditors[0].displayName}
icon={<Brush />}
onClick={() => onEditWith(imageResourceExternalEditors[0])}
/>
)
}
</ResponsiveWindowMeasurer>
<FlatButton
label={<Trans>Preview</Trans>}
icon={<PlayArrow />}
onClick={() => this.openPreview(true)}
/>
<Timer style={styles.timeIcon} />
<TextField
value={this.state.timeBetweenFrames}
onChange={(e, text) =>
this.setState({ timeBetweenFrames: parseFloat(text) || 0 })
}
onBlur={() => this.saveTimeBetweenFrames()}
id="direction-time-between-frames"
margin="none"
style={styles.timeField}
type="number"
step={0.005}
precision={2}
min={0.01}
max={5}
/>
<span style={styles.spacer} />
<div style={styles.repeatContainer}>
<Checkbox
checked={direction.isLooping()}
label={<Trans>Loop</Trans>}
onCheck={(e, check) => this.setLooping(check)}
/>
</div>
{this.state.previewOpen && (
<Dialog
actions={
<FlatButton
label={<Trans>OK</Trans>}
primary
onClick={() => this.openPreview(false)}
key="ok"
/>
}
noMargin
modal
onRequestClose={() => this.openPreview(false)}
open={this.state.previewOpen}
>
<AnimationPreview
spritesContainer={direction}
resourcesLoader={resourcesLoader}
project={project}
timeBetweenFrames={this.state.timeBetweenFrames}
onChangeTimeBetweenFrames={text =>
this.setState({ timeBetweenFrames: text })
}
/>
</Dialog>
)}
</div>
);
}
}
|
<gh_stars>10-100
import { createLocalVue, mount } from '@vue/test-utils'
import Vuex from 'vuex'
import { DruxtRouter, DruxtRouterStore } from 'druxt-router'
import { DruxtEntityComponentSuggestionMixin } from '../../src/mixins/componentSuggestion'
const baseURL = 'https://demo-api.druxtjs.org'
// Setup local vue instance.
const localVue = createLocalVue()
localVue.use(Vuex)
let store
const component = {
name: 'DruxtEntityTest',
mixins: [DruxtEntityComponentSuggestionMixin],
render: () => ({})
}
describe('DruxtEntityComponentSuggestionMixin', () => {
beforeEach(() => {
// Setup vuex store.
store = new Vuex.Store()
store.$druxtRouter = new DruxtRouter(baseURL, {})
DruxtRouterStore({ store })
})
test('defaults', () => {
const wrapper = mount(component, { localVue, store })
expect(wrapper.vm.component).toBe('div')
expect(wrapper.vm.suggestions).toStrictEqual([])
expect(wrapper.vm.suggestionRules).toStrictEqual([])
expect(wrapper.vm.tokenContext).toHaveProperty('route', {})
expect(wrapper.vm.tokenContext).toHaveProperty('tokens')
expect(wrapper.vm.tokenType).toBe(false)
})
test('suggestion rules', () => {
const mocks = {
$druxtEntity: { options: { entity: { suggestions: [
{ type: false, value: ctx => 'DruxtEntityOptionsFunction' },
{ type: false, value: ctx => false },
{ value: 'DruxtEntityOptionsNoMatch' }
] } } },
suggestionDefaults: [{
value: 'SuggestionDefaultsString'
}]
}
const wrapper = mount(component, { localVue, mocks, store })
expect(wrapper.vm.suggestionRules.length).toBe(3)
expect(wrapper.vm.suggestionRules[2].value).toBe('SuggestionDefaultsString')
expect(wrapper.vm.suggestions.length).toBe(2)
expect(wrapper.vm.suggestions).toStrictEqual([
'DruxtEntityOptionsFunction',
'SuggestionDefaultsString'
])
})
test('suggest', () => {
const wrapper = mount(component, { localVue, store })
expect(wrapper.vm.suggest('field')).toBe('Field')
expect(wrapper.vm.suggest('field_name')).toBe('FieldName')
expect(wrapper.vm.suggest('node--page')).toBe('NodePage')
expect(wrapper.vm.suggest('node--page--field_name')).toBe('NodePageFieldName')
expect(wrapper.vm.suggest('views_block:recipe_collections-block')).toBe('ViewsBlockRecipeCollectionsBlock')
expect(wrapper.vm.suggest('block_content:924ab293-8f5f-45a1-9c7f-2423ae61a241')).toBe('BlockContent924ab2938f5f45a19c7f2423ae61a241')
})
})
|
#!/bin/bash
# Script to run ShellCheck (a static analysis tool for shell scripts) over a
# script directory
if [ -z "$1" ]; then
echo "usage: $0 <directory>"
echo ""
echo " <directory> Directory to search for scripts"
exit -1
fi
search_directory="$1"
command -v shellcheck >/dev/null 2>&1 || { echo -e >&2 \
"Error: shellcheck required but it's not installed. On Ubuntu use:\n sudo apt-get install shellcheck\n\nAborting."; exit 1; }
scripts="$(find "$search_directory" -type f ! -name '*.txt' ! -name '*.mix' ! -name '*.bin')"
echo "Running shellcheck in '$search_directory'."
# Disabled rules:
# SC2121: allow 'set' as assignment (NuttX-style)
# SC1008: unrecognized shebang
# SC2086: double quote to prevent globbing and word splitting
# SC2166: allow the form [ $OUTPUT_MODE == fmu -o $OUTPUT_MODE == io ]
# SC2148: allow files w/o shebang
# SC2039: In POSIX sh, array references are undefined. TODO: fix this
shellcheck -x \
-e SC1008 \
-e SC2086 \
-e SC2121 \
-e SC2148 \
-e SC2166 \
-e SC2039 \
--shell=dash \
$scripts
ret=$?
if [ $ret -ne 0 ]; then
echo "Please fix the above script problems."
echo "If an error is raised that should be ignored, \
add the following right before the offending line:"
echo "# shellcheck disable=SCxxxx"
echo ""
echo "Re-run the script with '$0 $@'"
exit $ret
fi
echo "No problems found."
exit 0
|
package flow
import (
"errors"
"github.com/JointFaaS/Client-go/client"
)
type input struct {
lastIndex int32
argsName string
}
type fcInvocation struct {
inputFrom []*input
funcName string
args []byte
ret []byte
}
type layer struct {
fcs []*fcInvocation
}
type FcFlow struct {
layers []layer
}
func NewFlow() (*FcFlow){
fcf := &FcFlow{
}
return fcf
}
func (fcf *FcFlow) AddSource(funcName string, args []byte) (error){
return nil
}
func (fcf *FcFlow) AddNode(funcName string, args []byte, inputs []*input) (error){
fcf.layers[]
return nil
}
func (fcf *FcFlow) NextLayer() (error){
return nil
}
func (fcf *FcFlow) End() (error){
return nil
}
type ExecFlowOutput struct {
}
func (fcf *FcFlow) Exec(client *client.Client) (*ExecFlowOutput, error) {
if client == nil {
return nil, errors.New("null pointer")
}
return nil, nil
} |
/*
* GreatestLeast.sql
* Chapter 4, Oracle10g PL/SQL Programming
* by <NAME>, <NAME>, <NAME>
*
* This script demonstrates the Greatest and Least functions
*/
SET SERVEROUTPUT ON
DECLARE
v_char VARCHAR2(10);
v_number NUMBER(10);
BEGIN
v_char := GREATEST('A', 'B', 'C');
v_number := GREATEST(1,2,3);
DBMS_OUTPUT.PUT_LINE('Greatest Character: '||v_char);
DBMS_OUTPUT.PUT_LINE('Greatest Number: '||v_number);
v_char := LEAST('A', 'B', 'C');
v_number := LEAST(1,2,3);
DBMS_OUTPUT.PUT_LINE('Least Character: '||v_char);
DBMS_OUTPUT.PUT_LINE('Least Number: '||v_number);
END;
/
|
# -*- coding: utf-8 -*-
"""
Created on Sat Feb 22 21:47:18 2020
@author: bejin
"""
def load_res_data(filename):
data_list = []
with open(filename, "r") as f:
for line in f.readlines():
line = line.rstrip()
if len(line) == 0:
continue
#data = np.array([float(s) for s in line.split(" ")])
data_list.append( np.fromstring(line, dtype=float, sep=' ') )
return np.stack(data_list, axis = 0)
def get_car_pts():
pts_res = load_res_data('res_03.txt')
choice = np.where(pts_res[:,3]>0)
pts_car = pts_res[choice, :].squeeze()
pts_car_xy = pts_car[:, 0:2]
return pts_car_xy
from sklearn.cluster import MeanShift
import numpy as np
X = get_car_pts()
clustering = MeanShift(bandwidth=2).fit(X) # too slow
clustering.labels_
clustering.predict([[0, 0], [5, 5]])
clustering |
<gh_stars>10-100
// Copyright (c) 2012-2019 The Elastos Open Source Project
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef __ELASTOS_SDK_PRVNET_H__
#define __ELASTOS_SDK_PRVNET_H__
namespace Elastos {
namespace ElaWallet {
const nlohmann::json DefaultPrvNetConfig = R"(
{
"NetType": "PrvNet",
"ELA": {
"Index": 0,
"MinFee": 10000,
"FeePerKB": 10000,
"DisconnectionTime": 300,
"ChainParameters": {
"Services": 0,
"MagicNumber": 2018201,
"StandardPort": 10018,
"TargetTimeSpan": 86400,
"TargetTimePerBlock": 120,
"DNSSeeds": [
"172.26.0.207"
],
"CheckPoints": [
[0, "8df798783097be3a8f382f6537e47c7168d4bf4d741fa3fa8c48c607a06352cf", 1513936800, 486801407]
]
}
},
"IDChain": {
"Index": 1,
"MinFee": 10000,
"FeePerKB": 10000,
"DisconnectionTime": 300,
"ChainParameters": {
"Services": 0,
"MagicNumber": 2018202,
"StandardPort": 10138,
"TargetTimeSpan": 86400,
"TargetTimePerBlock": 120,
"DNSSeeds": [
"172.26.0.207"
],
"CheckPoints": [
[0, "56be936978c261b2e649d58dbfaf3f23d4a868274f5522cd2adb4308a955c4a3", 1513936800, 486801407]
]
}
},
"TokenChain": {
"Index": 2,
"MinFee": 10000,
"FeePerKB": 10000,
"DisconnectionTime": 300,
"ChainParameters": {
"Services": 0,
"MagicNumber": 2019004,
"StandardPort": 30618,
"TargetTimeSpan": 86400,
"TargetTimePerBlock": 120,
"DNSSeeds": [
"172.26.0.165"
],
"CheckPoints": [
[0, "b569111dfb5e12d40be5cf09e42f7301128e9ac7ab3c6a26f24e77872b9a730e", 1551744000, 486801407]
]
}
},
"ETHSC": {
"Index": 3,
"MinFee": 0,
"FeePerKB": 0,
"DisconnectionTime": 0,
"ChainParameters": {
"Services": 0,
"MagicNumber": 0,
"StandardPort": 0,
"TargetTimeSpan": 0,
"TargetTimePerBlock": 0,
"DNSSeeds": [
"127.0.0.1"
],
"CheckPoints": [
[0, "0000000000000000000000000000000000000000000000000000000000000000", 1, 1]
]
}
}
}
)"_json;
}
}
#endif
|
#include <iostream>
using namespace std;
int main()
{
int array[3][3] = {{1,2,3},{4,5,6},{7,8,9}};
int sum = 0;
//Calculate sum
for(int i=0; i<3; i++){
for(int j=0; j<3; j++){
sum += array[i][j];
}
}
//Print result
cout << "Sum of elements is " << sum;
return 0;
} |
import React from 'react'
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs'
import Icon from 'react-native-vector-icons/FontAwesome5'
import { Image } from 'react-native'
import FavoriteNavigation from '../navigation/FavoriteNavigation'
import PokedexNavigation from '../navigation/PokedexNavigation'
import AccountNavigation from '../navigation/AccountNavigation'
// Tab navigation
const Tab = createBottomTabNavigator()
export default function Navigation() {
return (
<Tab.Navigator>
<Tab.Screen name="Favorite" component={FavoriteNavigation} options={{
tabBarLabel: 'Favoritos',
tabBarIcon: ({color, size}) => (
<Icon name="heart" size={size} color={color} />
)
}}/>
<Tab.Screen name="Pokedex" component={PokedexNavigation} options={{
tabBarLabel: '',
tabBarIcon: () => renderPokeball()
}}/>
<Tab.Screen name="Account" component={AccountNavigation} options={{
tabBarLabel: 'Perfil',
tabBarIcon: ({color, size}) => (
<Icon name="user" size={size} color={color} />
)
}}/>
</Tab.Navigator>
)
}
// Funcion para retornar la imagen de pokedex de src/assets
function renderPokeball() {
return (
<Image source={require('../assets/pokeball.png')} style={{width: 50, height: 50, top: -15}} />
)
} |
#/bin/bash
# Jupyter-build doesn't have an option to automatically show the
# saved reports, which makes it difficult to debug the reasons for
# build failures in CI. This is a simple wrapper to handle that.
# Use package from parent directory.
export PYTHONPATH=$(realpath ..):$PYTHONPATH
REPORTDIR=_build/html/reports
jupyter-book build -W --keep-going .
RETVAL=$?
if [ $RETVAL -ne 0 ]; then
if [ -e $REPORTDIR ]; then
echo "Error occured; showing saved reports"
cat $REPORTDIR/*
fi
else
# Clear out any old reports
rm -f $REPORTDIR/*
fi
exit $RETVAL
|
#
# Copyright (c) 2015, 2016, 2017, 2018, Intel Corporation
#
# 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 of Intel Corporation nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY LOG OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
source ../tutorial_env.sh
# OMP_FLAGS: Flags for enabling OpenMP
if [ ! "$OMP_FLAGS" ]; then
OMP_FLAGS="-fopenmp"
fi
make \
CFLAGS="$GEOPM_CFLAGS $OMP_FLAGS -std=gnu11 -mavx $CFLAGS" \
CXXFLAGS="$GEOPM_CFLAGS $OMP_FLAGS -std=gnu++11 -mavx $CXXFLAGS" \
LDFLAGS="$OMP_FLAGS -lm -lrt -mavx $LDFLAGS"
|
<filename>packages/esbuild-plugin-starter/fixtures/build.ts
import { build } from 'esbuild';
import { plugin } from '../src/plugin';
import path from 'path';
(async () => {
await build({
entryPoints: [path.resolve(__dirname, './entry.ts')],
plugins: [plugin()],
outdir: './dist',
});
})();
|
/**
* Copyright (C) 2011 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.analytics.financial.interestrate.payments.market;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.Validate;
import com.opengamma.analytics.financial.interestrate.InstrumentDerivative;
import com.opengamma.analytics.financial.interestrate.market.description.CurveSensitivityMarket;
import com.opengamma.analytics.financial.interestrate.market.description.IMarketBundle;
import com.opengamma.analytics.financial.interestrate.market.description.MarketForwardSensitivity;
import com.opengamma.analytics.financial.interestrate.market.description.MultipleCurrencyCurveSensitivityMarket;
import com.opengamma.analytics.financial.interestrate.method.PricingMarketMethod;
import com.opengamma.analytics.financial.interestrate.payments.derivative.CouponOIS;
import com.opengamma.util.ArgumentChecker;
import com.opengamma.util.money.MultipleCurrencyAmount;
import com.opengamma.util.tuple.DoublesPair;
/**
* Method to compute present value and its sensitivities for OIS coupons.
*/
public final class CouponOISDiscountingMarketMethod implements PricingMarketMethod {
/**
* The method unique instance.
*/
private static final CouponOISDiscountingMarketMethod INSTANCE = new CouponOISDiscountingMarketMethod();
/**
* Return the unique instance of the class.
* @return The instance.
*/
public static CouponOISDiscountingMarketMethod getInstance() {
return INSTANCE;
}
/**
* Private constructor.
*/
private CouponOISDiscountingMarketMethod() {
}
/**
* Computes the present value.
* @param coupon The coupon.
* @param market The market curves.
* @return The present value.
*/
public MultipleCurrencyAmount presentValue(final CouponOIS coupon, final IMarketBundle market) {
ArgumentChecker.notNull(coupon, "Coupon");
ArgumentChecker.notNull(market, "Market");
final double ratio = 1.0 + coupon.getFixingPeriodAccrualFactor()
* market.getForwardRate(coupon.getIndex(), coupon.getFixingPeriodStartTime(), coupon.getFixingPeriodEndTime(), coupon.getFixingPeriodAccrualFactor());
final double df = market.getDiscountFactor(coupon.getCurrency(), coupon.getPaymentTime());
final double pv = (coupon.getNotionalAccrued() * ratio - coupon.getNotional()) * df;
return MultipleCurrencyAmount.of(coupon.getCurrency(), pv);
}
@Override
public MultipleCurrencyAmount presentValue(final InstrumentDerivative instrument, final IMarketBundle market) {
Validate.isTrue(instrument instanceof CouponOIS, "Coupon OIS");
return presentValue((CouponOIS) instrument, market);
}
/**
* Compute the present value sensitivity to rates of a OIS coupon by discounting.
* @param coupon The coupon.
* @param market The market curves.
* @return The present value curve sensitivities.
*/
public MultipleCurrencyCurveSensitivityMarket presentValueMarketSensitivity(final CouponOIS coupon, final IMarketBundle market) {
ArgumentChecker.notNull(coupon, "Coupon");
ArgumentChecker.notNull(market, "Market");
final double df = market.getDiscountFactor(coupon.getCurrency(), coupon.getPaymentTime());
final double forward = market.getForwardRate(coupon.getIndex(), coupon.getFixingPeriodStartTime(), coupon.getFixingPeriodEndTime(),
coupon.getFixingPeriodAccrualFactor());
final double ratio = 1.0 + coupon.getFixingPeriodAccrualFactor() * forward;
// Backward sweep
final double pvBar = 1.0;
final double ratioBar = coupon.getNotionalAccrued() * df * pvBar;
final double forwardBar = coupon.getFixingPeriodAccrualFactor() * ratioBar;
final double dfBar = (coupon.getNotionalAccrued() * ratio - coupon.getNotional()) * pvBar;
final Map<String, List<DoublesPair>> mapDsc = new HashMap<String, List<DoublesPair>>();
final List<DoublesPair> listDiscounting = new ArrayList<DoublesPair>();
listDiscounting.add(new DoublesPair(coupon.getPaymentTime(), -coupon.getPaymentTime() * df * dfBar));
mapDsc.put(market.getName(coupon.getCurrency()), listDiscounting);
final Map<String, List<MarketForwardSensitivity>> mapFwd = new HashMap<String, List<MarketForwardSensitivity>>();
final List<MarketForwardSensitivity> listForward = new ArrayList<MarketForwardSensitivity>();
listForward.add(new MarketForwardSensitivity(coupon.getFixingPeriodStartTime(), coupon.getFixingPeriodEndTime(), coupon.getFixingPeriodAccrualFactor(), forwardBar));
mapFwd.put(market.getName(coupon.getIndex()), listForward);
final MultipleCurrencyCurveSensitivityMarket result = MultipleCurrencyCurveSensitivityMarket.of(coupon.getCurrency(),
CurveSensitivityMarket.ofYieldDiscountingAndForward(mapDsc, mapFwd));
return result;
}
/**
* Computes the par rate, i.e. the fair rate for the remaining period.
* @param coupon The coupon.
* @param market The market curves.
* @return The par rate.
*/
public double parRate(final CouponOIS coupon, final IMarketBundle market) {
ArgumentChecker.notNull(coupon, "Coupon");
ArgumentChecker.notNull(market, "Market");
return market.getForwardRate(coupon.getIndex(), coupon.getFixingPeriodStartTime(), coupon.getFixingPeriodEndTime(), coupon.getFixingPeriodAccrualFactor());
}
/**
* Computes the par rate sensitivity to the curve rates.
* @param coupon The coupon.
* @param market The market curves.
* @return The sensitivities.
*/
public MultipleCurrencyCurveSensitivityMarket parRateCurveSensitivity(final CouponOIS coupon, final IMarketBundle market) {
ArgumentChecker.notNull(coupon, "Coupon");
ArgumentChecker.notNull(market, "Market");
// Backward sweep.
final double forwardBar = 1.0;
final Map<String, List<MarketForwardSensitivity>> mapFwd = new HashMap<String, List<MarketForwardSensitivity>>();
final List<MarketForwardSensitivity> listForward = new ArrayList<MarketForwardSensitivity>();
listForward.add(new MarketForwardSensitivity(coupon.getFixingPeriodStartTime(), coupon.getFixingPeriodEndTime(), coupon.getFixingPeriodAccrualFactor(), forwardBar));
mapFwd.put(market.getName(coupon.getIndex()), listForward);
final MultipleCurrencyCurveSensitivityMarket result = MultipleCurrencyCurveSensitivityMarket.of(coupon.getCurrency(), CurveSensitivityMarket.ofForward(mapFwd));
return result;
}
}
|
import fetch from '../fetch';
import { getURL, getNewsURL } from '../utils';
import { IOptionsDocs } from '../typings';
export interface INewsItem {
id: string;
tag?: string;
categories: string[];
placement?: string[] | null;
type: string;
date: string;
title: string;
abstract?: string;
content: string;
trackingPageValue: string;
readTime?: string;
authors?: null;
featuredThumbnail?: {
url: string | null;
description: string | null;
};
thumbnail: {
url: string | null;
description: string | null;
};
description?: string;
button: {
commonTranslationId: string;
buttonType: string;
buttonUrl: string;
trackingCategoryValue: string;
trackingValue: string;
};
index: number;
prevNode: {
buttonType: string;
trackingLocation: string;
trackingCategoryValue: string;
trackingValue: string;
buttonUrl: string;
};
nextNode: {
buttonType: string;
trackingLocation: string;
trackingCategoryValue: string;
trackingValue: string;
buttonUrl: string;
};
}
export interface IApiResponse {
total: number;
tags: string[];
items?: INewsItem[];
message?: string;
}
export interface IOptions {
raw?: boolean;
locale?: string;
fallbackLocale?: string;
}
export const optionsDocs: IOptionsDocs = [
['raw', '`boolean`', false, '`false`', 'Include raw API response'],
['locale', '`string`', false, '`\'en-gb\'`', ''],
['fallbackLocale', '`string`', false, '`\'en-us\'`', '']
];
export default async (id: string, options?: IOptions) => {
const raw = options && options.raw || false;
const locale = options && options.locale || 'en-gb';
const fallbackLocale = options && options.fallbackLocale || 'en-us';
const res = await fetch<IApiResponse>(
getURL.NEWSBYID(id, locale, fallbackLocale),
{ headers: { 'Authorization': '3u0FfSBUaTSew-2NVfAOSYWevVQHWtY9q3VM8Xx9Lto' } }
)();
return ({
...raw && { raw: res },
total: res.total,
tags: res.tags,
...res.items && {
item: res.items.map(item => ({
id: item.id,
title: item.title,
abstract: item.abstract,
thumbnail: {
url: item.thumbnail.url, description: item.thumbnail.description
},
content: item.content,
description: item.description,
categories: item.categories,
tag: item.tag,
placement: item.placement,
type: item.type,
readTime: item.readTime,
url: getNewsURL(locale, item.type, item.button.buttonUrl),
date: item.date
}))
},
...res.message && { message: res.message }
});
};
|
import 'reflect-metadata';
import { MFDeleteMode } from '../enums/mf-delete-mode.enum';
/**
* Sets default deletion mode of the targetted DAO
*
* @param mode hard or soft mode (default: hard)
*/
export function DeletionMode(mode: MFDeleteMode): any {
// eslint-disable-next-line @typescript-eslint/ban-types
return (target: Object) => {
Reflect.defineMetadata('deletionMode', mode, target);
};
}
|
/*
* 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.
*/
#include "utils/string_helpers.h"
#include <cerrno>
#include <cstdarg>
#include <sstream>
#include <gtest/gtest.h>
namespace panda::helpers::string::test {
TEST(StringHelpers, Format)
{
EXPECT_EQ(Format("abc"), "abc");
EXPECT_EQ(Format("%s %d %c", "a", 10, 0x31), "a 10 1");
std::stringstream ss;
for (size_t i = 0; i < 10000; i++) {
ss << " ";
}
ss << "abc";
EXPECT_EQ(Format("%10003s", "abc"), ss.str());
}
TEST(StringHelpers, ParseInt)
{
errno = 0;
int i = 0;
// check format
ASSERT_FALSE(ParseInt("x", &i));
ASSERT_EQ(EINVAL, errno);
errno = 0;
ASSERT_FALSE(ParseInt("123x", &i));
ASSERT_EQ(EINVAL, errno);
ASSERT_TRUE(ParseInt("123", &i));
ASSERT_EQ(123, i);
ASSERT_EQ(0, errno);
i = 0;
EXPECT_TRUE(ParseInt(" 123", &i));
EXPECT_EQ(123, i);
ASSERT_TRUE(ParseInt("-123", &i));
ASSERT_EQ(-123, i);
i = 0;
EXPECT_TRUE(ParseInt(" -123", &i));
EXPECT_EQ(-123, i);
short s = 0;
ASSERT_TRUE(ParseInt("1234", &s));
ASSERT_EQ(1234, s);
// check range
ASSERT_TRUE(ParseInt("12", &i, 0, 15));
ASSERT_EQ(12, i);
errno = 0;
ASSERT_FALSE(ParseInt("-12", &i, 0, 15));
ASSERT_EQ(ERANGE, errno);
errno = 0;
ASSERT_FALSE(ParseInt("16", &i, 0, 15));
ASSERT_EQ(ERANGE, errno);
errno = 0;
ASSERT_FALSE(ParseInt<int>("x", nullptr));
ASSERT_EQ(EINVAL, errno);
errno = 0;
ASSERT_FALSE(ParseInt<int>("123x", nullptr));
ASSERT_EQ(EINVAL, errno);
ASSERT_TRUE(ParseInt<int>("1234", nullptr));
i = 0;
ASSERT_TRUE(ParseInt("0123", &i));
ASSERT_EQ(123, i);
i = 0;
ASSERT_TRUE(ParseInt("0x123", &i));
ASSERT_EQ(0x123, i);
i = 0;
EXPECT_TRUE(ParseInt(" 0x123", &i));
EXPECT_EQ(0x123, i);
i = 0;
ASSERT_TRUE(ParseInt(std::string("123"), &i));
ASSERT_EQ(123, i);
i = 123;
ASSERT_FALSE(ParseInt("456x", &i));
ASSERT_EQ(123, i);
}
} // namespace panda::helpers::string::test
|
#!/bin/sh
FIXED_IMAGE=$1
MOVING_IMAGE_DIR=$2
ELASTIX_RESULT_FOLDER=$3
ELASTIX_PARAMETER_FOLDER=/elastix/out_parameters
TMP_FOLDER = /elastix/tmp_out
mkdir -p $ELASTIX_RESULT_FOLDER
mkdir -p $ELASTIX_PARAMETER_FOLDER
mkdir -p $TMP_FOLDER
MOVING_IMAGE=$(ls $MOVING_IMAGE_DIR/*.nii.gz | head -1)
echo elastix -f $FIXED_IMAGE -m $MOVING_IMAGE -p parameter_map_0.txt -p parameter_map_1.txt -out $ELASTIX_PARAMETER_FOLDER
elastix -f $FIXED_IMAGE -m $MOVING_IMAGE -p parameter_map_0.txt -p parameter_map_1.txt -out $ELASTIX_PARAMETER_FOLDER
transformix -in $MOVING_IMAGE -out $TMP_FOLDER -tp $ELASTIX_PARAMETER_FOLDER/TransformParameters.1.txt
mv $TMP_FOLDER/*.nii.gz $ELASTIX_RESULT_FOLDER
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.