text
stringlengths 1
1.05M
|
|---|
#!/bin/bash
. ./defaults.sh
. ../../include/common.sh
. .envrc
DOMAIN=$(kubectl get configmap -n kube-system cap-values -o json | jq -r '.data["domain"]')
export DOMAIN
DEPLOYED_CHART=$(kubectl get configmap -n kube-system cap-values -o json | jq -r '.data["chart"]')
info
info "@@@@@@@@@"
info "Running CATs on deployed chart $DEPLOYED_CHART"
info "@@@@@@@@@"
info
kubectl create namespace catapult || true
kubectl delete pod cats -n catapult || true
if [ "${DEFAULT_STACK}" = "from_chart" ]; then
DEFAULT_STACK=$(helm inspect helm/cf/ | grep DEFAULT_STACK | sed 's~DEFAULT_STACK:~~g' | sed 's~"~~g' | sed 's~\s~~g')
export DEFAULT_STACK
fi
export CATS_REPO=$CATS_REPO
pod_definition=$(erb "$ROOT_DIR"/kube/cats/pod.yaml.erb)
cat <<EOF
Will create this pod (if you see empty values, make sure you defined all the needed env variables):
${pod_definition}
EOF
kubectl apply -n catapult -f <(echo "${pod_definition}")
wait_ns catapult
wait_container_attached "catapult" "cats"
set +e
mkdir -p artifacts
kubectl logs -f cats -n catapult > artifacts/"$(date +'%H:%M-%Y-%m-%d')"_cats.log
status="$(container_status "catapult" "cats")"
kubectl delete pod -n catapult cats
exit "$status"
|
package com.github.peacetrue.beans.modify;
import com.github.peacetrue.beans.properties.modifiedtime.ModifiedTimeAware;
import com.github.peacetrue.beans.properties.modifierid.ModifierIdAware;
/**
* @author peace
* @since 1.0
**/
public interface ModifyAware<T, S> extends ModifierIdAware<T>, ModifiedTimeAware<S> {
}
|
#! /usr/bin/env sh
###############################################################################
# touch sources files from template
###############################################################################
readonly today=$(date +%Y-%m-%d)
readonly prefix='https://raw.githubusercontent.com/Shylock-Hg/config.linux/master/template'
while getopts 'n:h' args
do
case $args in
n) #!< name of source file
readonly suffix_cheader='h'
readonly suffix_csource='c'
readonly suffix_python='py'
readonly suffix_ccheader='hh'
readonly suffix_ccsource='cc'
readonly suffix_sh='sh'
# Makefile
if [ $OPTARG = 'Makefile' ]; then
curl $prefix/linux.mk -o $PWD/$OPTARG
# c
elif [ ${OPTARG##*.} = $suffix_cheader ]; then
uppername=${OPTARG%.*}
uppername=${uppername^^}
if curl $prefix/template.h -o $PWD/$OPTARG; then
sed -i -e "s/\\date.\+/\\date $today/g" \
-e "s/_.\+_H_/_${uppername}_H_/g" $PWD/$OPTARG
fi
elif [ ${OPTARG##*.} = $suffix_csource ]; then
if curl $prefix/template.c -o $PWD/$OPTARG; then
sed -i "s/\\date.\+/\\date $today/g" $PWD/$OPTARG
fi
# c++
elif [ ${OPTARG##*.} = $suffix_ccheader ]; then
uppername=${OPTARG%.*}
uppername=${uppername^^}
if curl $prefix/template.hh -o $PWD/$OPTARG; then
sed -i -e "s/\\date.\+/\\date $today/g" \
-e "s/_.\+_HH_/_${uppername}_HH_/g" $PWD/$OPTARG
fi
elif [ ${OPTARG##*.} = $suffix_ccsource ]; then
if curl $prefix/template.cc -o $PWD/$OPTARG; then
sed -i "s/\\date.\+/\\date $today/g" $PWD/$OPTARG
fi
# python
elif [ ${OPTARG##*.} = $suffix_python ]; then
if curl $prefix/template.py -o $PWD/$OPTARG; then
sed -i "s/\\date.\+/\\date $today/g" $PWD/$OPTARG
fi
elif [ ${OPTARG##*.} = $suffix_sh ]; then
if curl $prefix/template.sh -o $PWD/$OPTARG; then
sed -i "s/\\date.\+/\\date $today/g" $PWD/$OPTARG
fi
# shell
else
echo 'error:Unkown file type!'
fi
;;
h)
printf "usage: $0 -n <name-of-source>\neg.$0 -n example.h"
;;
?)
echo "error:Unknown argument $OPTARG!"
;;
esac
done
shift $((OPTIND - 1))
|
#!/bin/sh
set -e
echo "mkdir -p ${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}"
mkdir -p "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}"
SWIFT_STDLIB_PATH="${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}"
install_framework()
{
if [ -r "${BUILT_PRODUCTS_DIR}/$1" ]; then
local source="${BUILT_PRODUCTS_DIR}/$1"
elif [ -r "${BUILT_PRODUCTS_DIR}/$(basename "$1")" ]; then
local source="${BUILT_PRODUCTS_DIR}/$(basename "$1")"
elif [ -r "$1" ]; then
local source="$1"
fi
local destination="${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}"
if [ -L "${source}" ]; then
echo "Symlinked..."
source="$(readlink "${source}")"
fi
# use filter instead of exclude so missing patterns dont' throw errors
echo "rsync -av --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${destination}\""
rsync -av --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${destination}"
local basename
basename="$(basename -s .framework "$1")"
binary="${destination}/${basename}.framework/${basename}"
if ! [ -r "$binary" ]; then
binary="${destination}/${basename}"
fi
# Strip invalid architectures so "fat" simulator / device frameworks work on device
if [[ "$(file "$binary")" == *"dynamically linked shared library"* ]]; then
strip_invalid_archs "$binary"
fi
# Resign the code if required by the build settings to avoid unstable apps
code_sign_if_enabled "${destination}/$(basename "$1")"
# Embed linked Swift runtime libraries. No longer necessary as of Xcode 7.
if [ "${XCODE_VERSION_MAJOR}" -lt 7 ]; then
local swift_runtime_libs
swift_runtime_libs=$(xcrun otool -LX "$binary" | grep --color=never @rpath/libswift | sed -E s/@rpath\\/\(.+dylib\).*/\\1/g | uniq -u && exit ${PIPESTATUS[0]})
for lib in $swift_runtime_libs; do
echo "rsync -auv \"${SWIFT_STDLIB_PATH}/${lib}\" \"${destination}\""
rsync -auv "${SWIFT_STDLIB_PATH}/${lib}" "${destination}"
code_sign_if_enabled "${destination}/${lib}"
done
fi
}
# Signs a framework with the provided identity
code_sign_if_enabled() {
if [ -n "${EXPANDED_CODE_SIGN_IDENTITY}" -a "${CODE_SIGNING_REQUIRED}" != "NO" -a "${CODE_SIGNING_ALLOWED}" != "NO" ]; then
# Use the current code_sign_identitiy
echo "Code Signing $1 with Identity ${EXPANDED_CODE_SIGN_IDENTITY_NAME}"
echo "/usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} ${OTHER_CODE_SIGN_FLAGS} --preserve-metadata=identifier,entitlements \"$1\""
/usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} ${OTHER_CODE_SIGN_FLAGS} --preserve-metadata=identifier,entitlements "$1"
fi
}
# Strip invalid architectures
strip_invalid_archs() {
binary="$1"
# Get architectures for current file
archs="$(lipo -info "$binary" | rev | cut -d ':' -f1 | rev)"
stripped=""
for arch in $archs; do
if ! [[ "${VALID_ARCHS}" == *"$arch"* ]]; then
# Strip non-valid architectures in-place
lipo -remove "$arch" -output "$binary" "$binary" || exit 1
stripped="$stripped $arch"
fi
done
if [[ "$stripped" ]]; then
echo "Stripped $binary of architectures:$stripped"
fi
}
if [[ "$CONFIGURATION" == "Debug" ]]; then
install_framework "$BUILT_PRODUCTS_DIR/SRCoreDataStack/SRCoreDataStack.framework"
fi
if [[ "$CONFIGURATION" == "Release" ]]; then
install_framework "$BUILT_PRODUCTS_DIR/SRCoreDataStack/SRCoreDataStack.framework"
fi
|
const express = require('express');
const routes = express.Router();
const aqis = require('./aqis');
// NOTE: aqis === air quality indexes
routes.use('/aqis', aqis);
routes.get('/', (req, res) => {
res.status(200).json({ message: 'OK' });
});
module.exports = routes;
|
#!/bin/bash
rm -rf ~/work/Developer/moodle/mod/opendsa
cp -r ~/work/AthabascaUniversity/COMP689AdvancedDistributedSystems/comp689project/moodle-plugin/opendsa ~/work/Developer/moodle/mod
|
#!/bin/bash
# Copyright 2013 The Shenzhen Key Laboratory of Intelligent Media and Speech,
# PKU-HKUST Shenzhen Hong Kong Institution (Author: Wei Shi)
# 2014-2016 Johns Hopkins University (Author: Daniel Povey)
# Apache 2.0
# Combine MFCC and online-pitch features together
# Note: This file is based on make_mfcc_pitch.sh
# Begin configuration section.
nj=4
cmd=run.pl
mfcc_config=conf/mfcc.conf
online_pitch_config=conf/online_pitch.conf
paste_length_tolerance=2
compress=true
write_utt2num_frames=true # If true writes utt2num_frames.
write_utt2dur=true
# End configuration section.
echo "$0 $@" # Print the command line for logging.
if [ -f path.sh ]; then . ./path.sh; fi
. parse_options.sh || exit 1;
if [ $# -lt 1 ] || [ $# -gt 3 ]; then
cat >&2 <<EOF
Usage: $0 [options] <data-dir> [<log-dir> [<mfcc-dir>] ]
e.g.: $0 data/train
Note: <log-dir> defaults to <data-dir>/log, and
<mfcc-dir> defaults to <data-dir>/data
Options:
--mfcc-config <mfcc-config-file> # config passed to compute-mfcc-feats [conf/mfcc.conf]
--online-pitch-config <online-pitch-config-file> # config passed to compute-and-process-kaldi-pitch-feats [conf/online_pitch.conf]
--paste-length-tolerance <tolerance> # length tolerance passed to paste-feats.
--nj <nj> # number of parallel jobs.
--cmd <run.pl|queue.pl <queue opts>> # how to run jobs.
--write-utt2num-frames <true|false> # If true, write utt2num_frames file.
--write-utt2dur <true|false> # If true, write utt2dur file.
EOF
exit 1;
fi
data=$1
if [ $# -ge 2 ]; then
logdir=$2
else
logdir=$data/log
fi
if [ $# -ge 3 ]; then
mfcc_pitch_dir=$3
else
mfcc_pitch_dir=$data/data
fi
# make $mfcc_pitch_dir an absolute pathname.
mfcc_pitch_dir=`perl -e '($dir,$pwd)= @ARGV; if($dir!~m:^/:) { $dir = "$pwd/$dir"; } print $dir; ' $mfcc_pitch_dir ${PWD}`
# use "name" as part of name of the archive.
name=`basename $data`
mkdir -p $mfcc_pitch_dir || exit 1;
mkdir -p $logdir || exit 1;
if [ -f $data/feats.scp ]; then
mkdir -p $data/.backup
echo "$0: moving $data/feats.scp to $data/.backup"
mv $data/feats.scp $data/.backup
fi
scp=$data/wav.scp
required="$scp $mfcc_config $online_pitch_config"
for f in $required; do
if [ ! -f $f ]; then
echo "$0: no such file $f"
exit 1;
fi
done
utils/validate_data_dir.sh --no-text --no-feats $data || exit 1;
if [ -f $data/spk2warp ]; then
echo "$0 [info]: using VTLN warp factors from $data/spk2warp"
vtln_opts="--vtln-map=ark:$data/spk2warp --utt2spk=ark:$data/utt2spk"
elif [ -f $data/utt2warp ]; then
echo "$0 [info]: using VTLN warp factors from $data/utt2warp"
vtln_opts="--vtln-map=ark:$data/utt2warp"
fi
for n in $(seq $nj); do
# the next command does nothing unless $mfcc_pitch_dir/storage/ exists, see
# utils/create_data_link.pl for more info.
utils/create_data_link.pl $mfcc_pitch_dir/raw_mfcc_online_pitch_$name.$n.ark
done
if $write_utt2num_frames; then
write_num_frames_opt="--write-num-frames=ark,t:$logdir/utt2num_frames.JOB"
else
write_num_frames_opt=
fi
if $write_utt2dur; then
write_utt2dur_opt="--write-utt2dur=ark,t:$logdir/utt2dur.JOB"
else
write_utt2dur_opt=
fi
if [ -f $data/segments ]; then
echo "$0 [info]: segments file exists: using that."
split_segments=
for n in $(seq $nj); do
split_segments="$split_segments $logdir/segments.$n"
done
utils/split_scp.pl $data/segments $split_segments || exit 1;
rm $logdir/.error 2>/dev/null
mfcc_feats="ark:extract-segments scp,p:$scp $logdir/segments.JOB ark:- | \
compute-mfcc-feats $vtln_opts $write_utt2dur_opt --verbose=2 \
--config=$mfcc_config ark:- ark:- |"
pitch_feats="ark,s,cs:extract-segments scp,p:$scp $logdir/segments.JOB ark:- | \
compute-and-process-kaldi-pitch-feats --verbose=2 \
--config=$online_pitch_config ark:- ark:- |"
$cmd JOB=1:$nj $logdir/make_mfcc_pitch_${name}.JOB.log \
paste-feats --length-tolerance=$paste_length_tolerance \
"$mfcc_feats" "$pitch_feats" ark:- \| \
copy-feats --compress=$compress $write_num_frames_opt ark:- \
ark,scp:$mfcc_pitch_dir/raw_mfcc_online_pitch_$name.JOB.ark,$mfcc_pitch_dir/raw_mfcc_online_pitch_$name.JOB.scp \
|| exit 1;
else
echo "$0: [info]: no segments file exists: assuming wav.scp indexed by utterance."
split_scps=
for n in $(seq $nj); do
split_scps="$split_scps $logdir/wav_${name}.$n.scp"
done
utils/split_scp.pl $scp $split_scps || exit 1;
mfcc_feats="ark:compute-mfcc-feats $vtln_opts $write_utt2dur_opt --verbose=2 \
--config=$mfcc_config scp,p:$logdir/wav_${name}.JOB.scp ark:- |"
pitch_feats="ark,s,cs:compute-and-process-kaldi-pitch-feats --verbose=2 \
--config=$online_pitch_config scp,p:$logdir/wav_${name}.JOB.scp ark:- |"
$cmd JOB=1:$nj $logdir/make_mfcc_pitch_${name}.JOB.log \
paste-feats --length-tolerance=$paste_length_tolerance \
"$mfcc_feats" "$pitch_feats" ark:- \| \
copy-feats --compress=$compress $write_num_frames_opt ark:- \
ark,scp:$mfcc_pitch_dir/raw_mfcc_online_pitch_$name.JOB.ark,$mfcc_pitch_dir/raw_mfcc_online_pitch_$name.JOB.scp \
|| exit 1;
fi
if [ -f $logdir/.error.$name ]; then
echo "$0: Error producing MFCC and online-pitch features for $name:"
tail $logdir/make_mfcc_pitch_${name}.1.log
exit 1;
fi
# Concatenate the .scp files together.
for n in $(seq $nj); do
cat $mfcc_pitch_dir/raw_mfcc_online_pitch_$name.$n.scp || exit 1
done > $data/feats.scp || exit 1
if $write_utt2num_frames; then
for n in $(seq $nj); do
cat $logdir/utt2num_frames.$n || exit 1
done > $data/utt2num_frames || exit 1
fi
if $write_utt2dur; then
for n in $(seq $nj); do
cat $logdir/utt2dur.$n || exit 1
done > $data/utt2dur || exit 1
fi
# Store frame_shift, mfcc_config and pitch_config_online along with features.
frame_shift=$(perl -ne 'if (/^--frame-shift=(\d+)/) {
printf "%.3f", 0.001 * $1; exit; }' $mfcc_config)
echo ${frame_shift:-'0.01'} > $data/frame_shift
mkdir -p $data/conf &&
cp $mfcc_config $data/conf/mfcc.conf &&
cp $online_pitch_config $data/conf/online_pitch.conf || exit 1
rm $logdir/wav_${name}.*.scp $logdir/segments.* \
$logdir/utt2num_frames.* $logdir/utt2dur.* 2>/dev/null
nf=$(wc -l < $data/feats.scp)
nu=$(wc -l < $data/utt2spk)
if [ $nf -ne $nu ]; then
echo "$0: It seems not all of the feature files were successfully procesed" \
"($nf != $nu); consider using utils/fix_data_dir.sh $data"
fi
if (( nf < nu - nu/20 )); then
echo "$0: Less than 95% the features were successfully generated."\
"Probably a serious error."
exit 1
fi
echo "$0: Succeeded creating MFCC and online-pitch features for $name"
|
#!/bin/bash
cd $(dirname $0)
## For Kibana
kibana_port=$1
[ -z "$kibana_port" ] && kibana_port=5601
if [ ! -e /tmp/kibana_dashboard.$UID ]; then
curl -u elastic:changeme -k -XPOST "http://localhost:${kibana_port}/api/kibana/dashboards/import" -H 'Content-Type: application/json' -H "kbn-xsrf: true" -d @export.json
[ $? -ne 0 ] && exit -1
date > /tmp/kibana_dashboard.$UID
fi
## For Elasticsearch
elastic_url=$(grep elasticsearch.url /usr/share/kibana/config/kibana.yml | awk '{print $2}')
[ -z "$elastic_url" ] && echo "elastic_url is null" && exit -1
curl -XPUT "${elastic_url}/_template/dcache-billing" -H 'Content-Type: application/json' -d @mapping.json
[ $? -ne 0 ] && "Failed: making template in [$elastic_url]" && exit -1
echo "Success: making template in [$elastic_url]"
exit 0
|
while True:
num = int(input("Please input a number between 1 and 10: "))
if num in range(1, 11):
print(num + 1)
else:
print("Invalid number!")
|
#!/bin/bash
BATCH_DIR=`dirname $0`
. $BATCH_DIR/update_common.sh
if [ -f $BATCH_DIR/.bashrc ]; then
. $BATCH_DIR/.bashrc
$YOMOU secondrank $1 download
log $0 $1 "execute secondrank $1 download"
else
echo "$0 $1 failed to execute secondrank $1 download" 1>&2
fi
|
#include <iostream>
#include <cctype>
#include <algorithm>
#include <nx/request.hpp>
#include <nx/http_status.hpp>
#include <nx/utils.hpp>
namespace nx {
request::request()
: http_msg()
{}
request::request(const nx::method& m)
: http_msg(),
method_(m.str)
{}
request::request(const std::string& method)
: http_msg(),
method_(method)
{}
request::request(const std::string& method, const std::string& path)
: http_msg(),
method_(method),
path_(path)
{}
request::request(request&& other)
{ *this = std::move(other); }
request::~request()
{}
request&
request::operator=(request&& other)
{
http_msg::operator=(std::forward<request>(other));
method_ = std::move(other.method_);
path_ = std::move(other.path_);
attrs_ = std::move(other.attrs_);
raw_method_= other.raw_method_;
raw_method_len_= other.raw_method_len_;
raw_path_= other.raw_path_;
raw_path_len_= other.raw_path_len_;
return *this;
}
bool
request::parse(buffer& b)
{
bool parsed = false;
pre_parse();
int ret = phr_parse_request(
b.data(), b.size(),
&raw_method_, &raw_method_len_,
&raw_path_, &raw_path_len_,
&minor_version_,
raw_headers_ptr_.get(), &num_headers_,
prev_buf_len_
);
if (ret > 0) {
parsed = true;
method_.assign(raw_method_, raw_method_len_);
uri u(std::string(raw_path_, raw_path_len_));
path_ = std::move(u.path());
attrs_ = std::move(u.a());
post_parse();
b.erase(b.begin(), b.begin() + (std::size_t) ret);
} else if (ret == -1) {
throw BadRequest;
} else if (ret != -2) {
throw InternalServerError;
}
prev_buf_len_ = b.size();
return parsed;
}
std::string
request::header_data() const
{
std::ostringstream oss;
auto hdrs = headers_;
if (method_ != GET.str) {
hdrs << header(nx::Content_Length, std::to_string(data_.size()));
}
oss
<< method_ << " " << clean_path(path_) << " HTTP/1.1\r\n"
<< hdrs
<< "\r\n"
;
return oss.str();
}
const std::string&
request::method() const
{ return method_; }
const std::string&
request::path() const
{ return path_; }
bool
request::has_a(const std::string& name) const
{ return attrs_.has(name); }
std::string&
request::a(const std::string& name)
{ return attrs_[name]; }
const std::string&
request::a(const std::string& name) const
{ return attrs_[name]; }
bool
request::operator==(const nx::method& m) const
{ return method_ == m.str; }
bool
request::operator!=(const nx::method& m) const
{ return !(*this == m); }
request&
request::operator/(const std::string& path)
{
path_ += '/';
path_ += path;
return *this;
}
request&
request::operator<<(const nx::method& m)
{
method_ = m.str;
return *this;
}
request&
request::operator<<(const attribute& a)
{
attrs_ << a;
return *this;
}
request&
request::operator<<(const attributes& a)
{
attrs_ << a;
return *this;
}
bool
request::is_form() const
{
return
*this == POST
&&
h(content_type) == "application/x-www-form-urlencoded"
;
}
bool
request::is_upgrade() const
{
return
*this == GET
&&
has(upgrade_websocket)
&&
has(connection_upgrade)
&&
has(Sec_WebSocket_Key)
&&
has(Sec_WebSocket_Version)
;
}
} // namespace nx
|
#!/bin/bash
#
# mount_blobfuse.sh --- simple wrapper to mount azure blobstorage as filesystem
#
#
# Author: Arul Selvan
# Version: Apr 17, 2021
#
# PreReq: apt-get install blobfuse fuse
# Source: https://github.com/Azure/azure-storage-fuse
#
# Steps:
# ------
# create a credential file to pass to the driver as shown below or set environment variables
#
# echo accountName myaccountname > $HOME/.passwd-azblob_storage
# echo accountKey myaccountkey >> $HOME/.passwd-azblob_storage
# (OR)
# export AZURE_STORAGE_ACCOUNT=myaccountname
# export AZURE_STORAGE_ACCESS_KEY=myaccountkey
#
os_name=`uname -s`
my_name=`basename $0`
options="c:m:s:t:h"
log_file="/tmp/$(echo $my_name|cut -d. -f1).log"
missing_blobfuse_msg="missing blobfuse, install with 'apt-get install blobfuse fuse'"
container=""
config_file="$HOME/.passwd-azblob_storage"
mount_point="/mnt/azblob"
tmp_path="/mnt/tmp"
mount_options="-o attr_timeout=240 -o entry_timeout=240 -o negative_timeout=120"
usage() {
cat <<EOF
Usage: $my_name [options]
-c <containername> ==> azure blob container name [required]
-m <path> ==> mount point [default: $mount_point]
-s <connfig_file> ==> secert file path [default: $HOME/.passwd-azblob_storage]
-t <temp_path> ==> temp path, a fast drive or a ram drive is better [default: $tmp_path]
-h ==> help
example: $my_name -c mycontainer -m /media/azure_blob
EOF
exit 1
}
# ---------------- main entry --------------------
# commandline parse
while getopts $options opt; do
case $opt in
c)
container=$OPTARG
;;
m)
mount_point=$OPTARG
;;
t)
tmp_path=$OPTARG
;;
s)
config_file=$OPTARG
;;
?)
usage
;;
h)
usage
;;
esac
done
if [ $os_name = "Darwin" ] ; then
echo "[ERROR] sorry blobfuse filesystem driver is not supported under MacOS!"
exit 1
fi
which blobfuse 2>&1 >/dev/null
if [ $? -gt 0 ] ; then
echo "[ERROR] $missing_s3fs_msg ... "
exit 2
fi
echo "[INFO] $my_name starting ..." | tee $log_file
# make sure we have at least bucket defined
if [ -z $container ] ; then
echo "[ERROR] required args missing!"
usage
fi
mkdir -p $mount_point || exit 3
mkdir -p $tmp_path || exit 4
echo "[INFO] Mounting azureblob container ($container) at $mount_point ..." | tee -a $log_file
if [ -f $config_file ] ; then
echo "[INFO] Using connection/config ($config_file) for authentication..." | tee -a $log_file
blobfuse $mount_point --tmp-path=$tmp_path --config-file=$config_file --container-name=$container $mount_options
rc=$?
else
if [[ -z $AZURE_STORAGE_ACCOUNT || -z $AZURE_STORAGE_ACCESS_KEY ]] ; then
echo "[ERROR] authentication file or env variables missing!"
usage
fi
blobfuse $mount_point --tmp-path=$tmp_path --container-name=$container $mount_options
rc=$?
fi
if [ $rc -ne 0 ] ; then
echo "[ERROR] mount failed! error=$rc " |tee -a $log_file
else
echo "[INFO] Mounted ($container) at $mount_point ..." | tee -a $log_file
fi
|
package sample.sadashiv.examplerealmmvp.presenter;
import io.realm.RealmList;
import sample.sadashiv.examplerealmmvp.model.Book;
import sample.sadashiv.examplerealmmvp.model.realm.RealmService;
import sample.sadashiv.examplerealmmvp.ui.author.AuthorView;
public class AuthorPresenter extends BasePresenter<AuthorView> {
private final String mAuthor;
public AuthorPresenter(final AuthorView view, final RealmService realmService, final String author) {
super(view, realmService);
mAuthor = author;
}
public void showBooks() {
mView.showBooks(formatBooks(mRealmService.getAuthorBooks(mAuthor)));
}
private RealmList<Book> formatBooks(final RealmList<Book> publisherBooks) {
return publisherBooks;
}
}
|
<gh_stars>0
package org.tarantool.orm.internals.operations;
import org.tarantool.TarantoolClient;
import org.tarantool.orm.internals.Meta;
import java.util.List;
import java.util.concurrent.CompletionStage;
public final class DeleteOperation<T> implements Operation<T> {
private final TarantoolClient tarantoolClient;
private final Meta<T> meta;
private final String spaceName;
private final List<?> keys;
public DeleteOperation(TarantoolClient tarantoolClient, Meta<T> meta, String spaceName, List<?> keys) {
this.tarantoolClient = tarantoolClient;
this.meta = meta;
this.spaceName = spaceName;
this.keys = keys;
}
@Override
public T runSync() {
List<?> result = tarantoolClient.syncOps().delete(spaceName, keys);
return meta.resultToDataClass(result);
}
@Override
public CompletionStage<T> runAsync() {
return tarantoolClient.composableAsyncOps().delete(spaceName, keys)
.thenApply(meta::resultToDataClass);
}
}
|
<gh_stars>0
# Copyright (c) 2017 Sony Corporation. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
def get_args(max_epochs=90, learning_rate=1e-1, batch_size=256,
weight_decay=1e-4, train_dir='./', train_list="train_label",
val_dir='./', val_list="val_label", dali_num_threads=4):
"""
Get command line arguments.
Arguments set the default values of command line arguments.
"""
import argparse
import os
parser = argparse.ArgumentParser(
description='''(Tiny) ImageNet classification example.
''')
parser.add_argument("--batch-size", "-b", type=int, default=batch_size)
parser.add_argument("--learning-rate", "-l",
type=float, default=learning_rate,
help='Learning rate used when --batch-size=256. For other batch sizes, the learning rate is linearly scaled.')
def parse_tuple(x):
return tuple(map(int, x.split(',')))
parser.add_argument("--learning-rate-decay-at", "-D",
default=(30, 60, 80), type=parse_tuple,
help='Step learning rate decay multiplied by 0.1 is performed at epochs specified, e.g. `-D 30,60,80`.')
parser.add_argument("--monitor-path", "-m",
type=str, default=None,
help='Path monitoring logs saved.')
parser.add_argument("--max-epochs", "-e", type=int, default=max_epochs,
help='Max epochs of training.')
parser.add_argument("--val-interval", "-v", type=int, default=10,
help='Evaluation with validation dataset is performed at every interval epochs specified.')
parser.add_argument("--weight-decay", "-w",
type=float, default=weight_decay,
help='Weight decay factor of SGD update.')
parser.add_argument("--warmup-epochs",
type=int, default=5,
help='Warmup learning rate during a specified number of epochs.')
parser.add_argument("--device-id", "-d", type=str, default='0',
help='Device ID the training run on. This is only valid if you specify `-c cudnn`.')
parser.add_argument("--type-config", "-t", type=str, default='float',
help='Type configuration.')
parser.add_argument("--model-save-interval", "-s", type=int, default=10,
help='The epoch interval of saving model parameters.')
parser.add_argument("--model-load-path", type=str, default=None,
help='Path to the model parameters to be loaded.')
parser.add_argument('--context', '-c', type=str,
default=None, help="Extension module. 'cudnn' is highly.recommended.")
parser.add_argument("--num-layers", "-L", type=int,
choices=[18, 34, 50, 101, 152], default=50,
help='Number of layers of ResNet.')
parser.add_argument("--shortcut-type", "-S", type=str,
choices=['b', 'c', ''], default='b',
help='Skip connection type. See `resnet_imagenet()` in model_resent.py for description.')
parser.add_argument("--channel-last", action='store_true',
help='Use a model with NHWC layout.')
parser.add_argument("--train-dir", '-T', type=str, default=train_dir,
help='Directory containing training data.')
parser.add_argument("--train-list", type=str, default=train_list,
help='Training file list.')
parser.add_argument("--val-dir", '-V', type=str, default=val_dir,
help='Directory containing validation data.')
parser.add_argument("--val-list", type=str, default=val_list,
help='Validation file list.')
parser.add_argument("--dali-num-threads", type=int, default=dali_num_threads,
help="DALI's number of CPU threads.")
parser.add_argument('--dali-prefetch-queue', type=int,
default=2, help="DALI prefetch queue depth")
parser.add_argument('--dali-nvjpeg-memory-padding-mb', type=int, default=64,
help="Memory padding value for nvJPEG (in MB)")
parser.add_argument('--label-smoothing', type=float, default=0.1,
help='Ratio of label smoothing loss.')
parser.add_argument('--loss-scaling', type=float, default=256,
help='Loss scaling value. Only used in half precision (mixed precision) training.')
args = parser.parse_args()
if args.monitor_path is None:
import datetime
args.monitor_path = 'tmp.monitor.' + \
datetime.datetime.now().strftime('%Y%m%d%H%M%S')
# to bytes
args.dali_nvjpeg_memory_padding = args.dali_nvjpeg_memory_padding_mb * \
(1 << 20)
# Learning rate is linearity scaled by batch size.
args.learning_rate *= args.batch_size / 256.0
return args
|
<gh_stars>1-10
import { combineReducers } from 'redux';
import { ReducersMap } from 'shared/types/redux';
import { editReducer } from './edit';
import uiReducer from './ui';
import * as NS from '../../namespace';
export default combineReducers<NS.IReduxState>({
edit: editReducer,
ui: uiReducer,
} as ReducersMap<NS.IReduxState>);
|
#!/usr/bin/env bash
SUBDOMAIN=$1
aws cloudformation describe-stacks --stack-name $SUBDOMAIN --query 'Stacks[].Outputs[]' --output table
|
<filename>src/main/java/com/ineor/countrypopulation/web/rest/CountryResource.java
package com.ineor.countrypopulation.web.rest;
import com.ineor.countrypopulation.domain.Item;
import com.ineor.countrypopulation.services.CountryService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping(value = "/api/countries")
public class CountryResource {
private final CountryService service;
public CountryResource(CountryService service) {
this.service = service;
}
@GetMapping(value = "/highest")
public ResponseEntity<List<Item>> getHighestCountries(@RequestParam(defaultValue = "2018", required = false) Integer year,
@RequestParam(defaultValue = "50", required = false) Integer countriesPerPage) {
return ResponseEntity.ok(service.getTopThreeCountriesWithHighestPopulation(year, countriesPerPage));
}
@GetMapping(value = "/lowest")
public ResponseEntity<List<Item>> getLowestCountries(@RequestParam(defaultValue = "2018", required = false) Integer year,
@RequestParam(defaultValue = "50", required = false) Integer countriesPerPage) {
return ResponseEntity.ok(service.getTopThreeCountriesWithLowestPopulation(year, countriesPerPage));
}
}
|
/*
* Contacts Service
*
* Copyright (c) 2010 - 2012 Samsung Electronics Co., Ltd. All rights reserved.
*
* Contact: <NAME> <<EMAIL>>
*
* 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 <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/inotify.h>
#include "cts-internal.h"
typedef struct
{
int wd;
void (*cb)(void *);
void *cb_data;
}noti_info;
static int cts_inoti_fd = -1;
static guint cts_inoti_handler;
static GSList *cts_noti_list;
static inline void handle_callback(GSList *noti_list, int wd, uint32_t mask)
{
noti_info *noti;
GSList *it = NULL;
for (it = noti_list;it;it=it->next)
{
noti = (noti_info *)it->data;
if (noti->wd == wd) {
if ((mask & IN_CLOSE_WRITE) && noti->cb)
noti->cb(noti->cb_data);
}
}
}
static gboolean cts_inotify_gio_cb(GIOChannel *src, GIOCondition cond, gpointer data)
{
int fd, ret;
struct inotify_event ie;
char name[FILENAME_MAX];
fd = g_io_channel_unix_get_fd(src);
while (0 < (ret = read(fd, &ie, sizeof(ie)))) {
if (sizeof(ie) == ret) {
if (cts_noti_list)
handle_callback(cts_noti_list, ie.wd, ie.mask);
while (0 < ie.len) {
ret = read(fd, name, (ie.len<sizeof(name))?ie.len:sizeof(name));
if (-1 == ret) {
if (EINTR == errno)
continue;
else
break;
}
ie.len -= ret;
}
}else {
while (ret < sizeof(ie)) {
int read_size;
read_size = read(fd, name, sizeof(ie)-ret);
if (-1 == read_size) {
if (EINTR == errno)
continue;
else
break;
}
ret += read_size;
}
}
}
return TRUE;
}
static inline int cts_inotify_attach_handler(int fd)
{
guint ret;
GIOChannel *channel;
retvm_if(fd < 0, CTS_ERR_ARG_INVALID, "fd is invalid");
channel = g_io_channel_unix_new(fd);
retvm_if(NULL == channel, CTS_ERR_INOTIFY_FAILED, "g_io_channel_unix_new() Failed");
g_io_channel_set_flags(channel, G_IO_FLAG_NONBLOCK, NULL);
ret = g_io_add_watch(channel, G_IO_IN, cts_inotify_gio_cb, NULL);
g_io_channel_unref(channel);
return ret;
}
int cts_inotify_init(void)
{
cts_inoti_fd = inotify_init();
retvm_if(-1 == cts_inoti_fd, CTS_ERR_INOTIFY_FAILED,
"inotify_init() Failed(%d)", errno);
fcntl(cts_inoti_fd, F_SETFD, FD_CLOEXEC);
fcntl(cts_inoti_fd, F_SETFL, O_NONBLOCK);
cts_inoti_handler = cts_inotify_attach_handler(cts_inoti_fd);
if (cts_inoti_handler <= 0) {
ERR("cts_inotify_attach_handler() Failed");
close(cts_inoti_fd);
cts_inoti_fd = -1;
cts_inoti_handler = 0;
return CTS_ERR_INOTIFY_FAILED;
}
return CTS_SUCCESS;
}
static inline int cts_inotify_get_wd(int fd, const char *notipath)
{
return inotify_add_watch(fd, notipath, IN_ACCESS);
}
static inline int cts_inotify_watch(int fd, const char *notipath)
{
int ret;
ret = inotify_add_watch(fd, notipath, IN_CLOSE_WRITE);
retvm_if(-1 == ret, CTS_ERR_INOTIFY_FAILED,
"inotify_add_watch() Failed(%d)", errno);
return CTS_SUCCESS;
}
int cts_inotify_subscribe(const char *path, void (*cb)(void *), void *data)
{
int ret, wd;
noti_info *noti, *same_noti = NULL;
GSList *it;
retv_if(NULL==path, CTS_ERR_ARG_NULL);
retv_if(NULL==cb, CTS_ERR_ARG_NULL);
retvm_if(cts_inoti_fd < 0, CTS_ERR_ENV_INVALID,
"cts_inoti_fd(%d) is invalid", cts_inoti_fd);
wd = cts_inotify_get_wd(cts_inoti_fd, path);
retvm_if(-1 == wd, CTS_ERR_INOTIFY_FAILED,
"cts_inotify_get_wd() Failed(%d)", errno);
for (it=cts_noti_list;it;it=it->next)
{
if (it->data)
{
same_noti = it->data;
if (same_noti->wd == wd && same_noti->cb == cb && same_noti->cb_data == data) {
break;
}
else {
same_noti = NULL;
}
}
}
if (same_noti) {
cts_inotify_watch(cts_inoti_fd, path);
ERR("The same callback(%s) is already exist", path);
return CTS_ERR_ALREADY_EXIST;
}
ret = cts_inotify_watch(cts_inoti_fd, path);
retvm_if(CTS_SUCCESS != ret, ret, "cts_inotify_watch() Failed");
noti = calloc(1, sizeof(noti_info));
retvm_if(NULL == noti, CTS_ERR_OUT_OF_MEMORY, "calloc() Failed");
noti->wd = wd;
noti->cb_data = data;
noti->cb = cb;
cts_noti_list = g_slist_append(cts_noti_list, noti);
return CTS_SUCCESS;
}
static inline int del_noti_with_data(GSList **noti_list, int wd,
void (*cb)(void *), void *user_data)
{
int del_cnt, remain_cnt;
GSList *it, *result;
del_cnt = 0;
remain_cnt = 0;
it = result = *noti_list;
while (it)
{
noti_info *noti = it->data;
if (noti && wd == noti->wd)
{
if (cb == noti->cb && user_data == noti->cb_data) {
it = it->next;
result = g_slist_remove(result , noti);
free(noti);
del_cnt++;
continue;
}
else {
remain_cnt++;
}
}
it = it->next;
}
retvm_if(del_cnt == 0, CTS_ERR_NO_DATA, "nothing deleted");
*noti_list = result;
return remain_cnt;
}
static inline int del_noti(GSList **noti_list, int wd, void (*cb)(void *))
{
int del_cnt, remain_cnt;
GSList *it, *result;
del_cnt = 0;
remain_cnt = 0;
it = result = *noti_list;
while (it)
{
noti_info *noti = it->data;
if (noti && wd == noti->wd)
{
if (NULL == cb || noti->cb == cb) {
it = it->next;
result = g_slist_remove(result, noti);
free(noti);
del_cnt++;
continue;
}
else {
remain_cnt++;
}
}
it = it->next;
}
retvm_if(del_cnt == 0, CTS_ERR_NO_DATA, "nothing deleted");
*noti_list = result;
return remain_cnt;
}
int cts_inotify_unsubscribe(const char *path, void (*cb)(void *))
{
int ret, wd;
retv_if(NULL == path, CTS_ERR_ARG_NULL);
retvm_if(cts_inoti_fd < 0, CTS_ERR_ENV_INVALID,
"cts_inoti_fd(%d) is invalid", cts_inoti_fd);
wd = cts_inotify_get_wd(cts_inoti_fd, path);
retvm_if(-1 == wd, CTS_ERR_INOTIFY_FAILED,
"cts_inotify_get_wd() Failed(%d)", errno);
ret = del_noti(&cts_noti_list, wd, cb);
warn_if(ret < CTS_SUCCESS, "del_noti() Failed(%d)", ret);
if (0 == ret)
return inotify_rm_watch(cts_inoti_fd, wd);
return cts_inotify_watch(cts_inoti_fd, path);
}
int cts_inotify_unsubscribe_with_data(const char *path,
void (*cb)(void *), void *user_data)
{
int ret, wd;
retv_if(NULL==path, CTS_ERR_ARG_NULL);
retv_if(NULL==cb, CTS_ERR_ARG_NULL);
retvm_if(cts_inoti_fd < 0, CTS_ERR_ENV_INVALID,
"cts_inoti_fd(%d) is invalid", cts_inoti_fd);
wd = cts_inotify_get_wd(cts_inoti_fd, path);
retvm_if(-1 == wd, CTS_ERR_INOTIFY_FAILED,
"cts_inotify_get_wd() Failed(%d)", errno);
ret = del_noti_with_data(&cts_noti_list, wd, cb, user_data);
warn_if(ret < CTS_SUCCESS, "del_noti_with_data() Failed(%d)", ret);
if (0 == ret)
return inotify_rm_watch(cts_inoti_fd, wd);
return cts_inotify_watch(cts_inoti_fd, path);
}
static void clear_nslot_list(gpointer data, gpointer user_data)
{
free(data);
}
static inline gboolean cts_inotify_detach_handler(guint id)
{
return g_source_remove(id);
}
void cts_inotify_close(void)
{
if (cts_inoti_handler) {
cts_inotify_detach_handler(cts_inoti_handler);
cts_inoti_handler = 0;
}
if (cts_noti_list) {
g_slist_foreach(cts_noti_list, clear_nslot_list, NULL);
g_slist_free(cts_noti_list);
cts_noti_list = NULL;
}
if (0 <= cts_inoti_fd) {
close(cts_inoti_fd);
cts_inoti_fd = -1;
}
}
|
#!/bin/bash
VOLUME_PREFIX=${VOLUME_PREFIX:-puppetindocker}
volumes="
${VOLUME_PREFIX}_ca_data
${VOLUME_PREFIX}_ca_ssl
${VOLUME_PREFIX}_db_ssl
${VOLUME_PREFIX}_haproxy_ssl
${VOLUME_PREFIX}_nats_ssl
${VOLUME_PREFIX}_postgres
${VOLUME_PREFIX}_r10k_cache
${VOLUME_PREFIX}_r10k_env
${VOLUME_PREFIX}_r10k_ssl
${VOLUME_PREFIX}_server_data
${VOLUME_PREFIX}_server_ssl
"
case $1 in
'data' )
for v in $volumes; do
echo docker run --rm -v $v:/data busybox sh -c \"rm -rf /data/*\"
docker run --rm -v $v:/data busybox sh -c "rm -rf /data/*"
done
;;
'volumes' )
for v in $volumes; do
echo docker volume rm $v
docker volume rm $v
done
;;
esac
|
import { IWidget, IOrderHistorySettings, IOrderHistoryFormSettings } from 'shared/types/models';
import { orderHistorySettingsFormEntry } from '../../../redux/data/reduxFormEntries';
// tslint:disable-next-line:max-line-length
import ordersTableHeaderLeftPartFactory from '../../factories/OrdersTableHeaderLeftPartFactory/OrdersTableHeaderLeftPartFactory';
import Settings from '../../containers/OrderHistorySettings/OrderHistorySettings';
import Content from './Content/Content';
const widget: IWidget<IOrderHistorySettings, IOrderHistoryFormSettings> = {
Content,
headerLeftPart: {
kind: 'with-settings',
Content: ordersTableHeaderLeftPartFactory('WIDGETS:ORDER-HISTORY-WIDGET-NAME'),
},
settingsForm: {
Component: Settings,
name: orderHistorySettingsFormEntry.name,
},
removable: true,
titleI18nKey: 'WIDGETS:ORDER-HISTORY-WIDGET-NAME',
};
export default widget;
|
<filename>packages/styles/src/input-label.ts
import { InputLabelStyleObj } from "@revind/types";
export const inputLabelStyleObj: InputLabelStyleObj = {
default: {
start: "overflow-ellipsis whitespace-nowrap peer-focus:text-inherit transition-all",
},
variants: {
"material-floating":
"appearance-none transform select-none absolute cursor-text -top-2 left-2 translate-y-0 text-xs peer-focus:-top-2 peer-focus:left-2 peer-focus:translate-y-0 peer-focus:text-xs peer-placeholder-shown:left-2 peer-placeholder-shown:text-base peer-placeholder-shown:top-1/2 peer-placeholder-shown:-translate-y-1/2 peer-placeholder-shown:text-gray-500",
"material-static":
"appearance-none transform select-none absolute cursor-text -top-2 left-2 text-xs",
left: "pr-2",
},
schemes: {
primary: "text-primary dark:text-primary-dark",
secondary: "text-secondary dark:text-secondary-dark",
red: "text-red dark:text-red-dark",
green: "text-green dark:text-green-dark",
yellow: "text-yellow dark:text-yellow-dark",
orange: "text-orange dark:text-orange-dark",
teal: "text-teal dark:text-teal-dark",
blue: "text-blue dark:text-blue-dark",
cyan: "text-cyan dark:text-cyan-dark",
indigo: "text-indigo dark:text-indigo-dark",
pink: "text-pink dark:text-pink-dark",
purple: "text-purple dark:text-purple-dark",
gray: "text-gray dark:text-gray-dark",
},
sizes: {},
variantInputVariant: {
"material-floating": {
outlined:
"bg-container-primary dark:bg-container-secondary-dark peer-focus:bg-container-primary dark:peer-focus:bg-container-secondary-dark peer-placeholder-shown:bg-transparent dark:peer-placeholder-shown:bg-transparent",
filled: "-top-1 peer-focus:-top-1",
},
"material-static": {
outlined: "bg-container-primary dark:bg-container-secondary-dark",
},
left: {},
top: {},
},
variantSchemes: {},
variantSizes: {},
};
|
docker images |grep paipai |sed -n "3,+100p" |awk '{print $3}' | xargs docker rmi
|
#!/bin/bash -xe
cd `cd \`dirname $0\`;pwd`
IMAGE=opengsn/cli
#build docker image of cli tools
rm -rf ../../dist && npx tsc
perl -pi -e 's/^#.*//; s/.*(start|run).*//' ../../dist/src/cli/commands/gsn.js
rm -rf dist && npx webpack
docker build -t $IMAGE .
test -z "$VERSION" && VERSION=`jq < ../../package.json -r .version`
docker tag $IMAGE $IMAGE:$VERSION
echo "== To publish"
echo " docker push $IMAGE:latest; docker push $IMAGE:$VERSION"
|
#!/bin/bash
source .env
echo "SHUTDOWN: tetris-server"
curl -XPOST http://localhost:${X_SERVER_PORT}/shutdown
echo
|
./venv/bin/pip freeze > requirements.txt
git add .
git commit -m "some fix"
git push origin master
|
<gh_stars>1-10
/*
* Copyright (C) 2017-2019 Dremio Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { shallow } from 'enzyme';
import Immutable from 'immutable';
import ApiUtils from 'utils/apiUtils/apiUtils';
import DataFreshnessSection from 'components/Forms/DataFreshnessSection';
import { ALL_TYPES, INCREMENTAL_TYPES } from 'constants/columnTypeGroups';
import { AccelerationUpdatesController } from './AccelerationUpdatesController';
import AccelerationUpdatesForm from './AccelerationUpdatesForm';
describe('AccelerationUpdatesController', () => {
let minimalProps;
let commonProps;
beforeEach(() => {
minimalProps = {
viewState: Immutable.fromJS({
isInProgress: false
}),
updateViewState: () => {}
};
commonProps = {
...minimalProps,
accelerationSettings: Immutable.fromJS({
refreshMethod: 'FULL',
accelerationRefreshPeriod: DataFreshnessSection.defaultFormValueRefreshInterval(),
accelerationGracePeriod: DataFreshnessSection.defaultFormValueGracePeriod()
}),
entity: Immutable.fromJS({
fullPathList: ['path']
}),
loadDatasetAccelerationSettings: sinon.stub(),
updateDatasetAccelerationSettings: sinon.stub(),
onDone: sinon.stub().returns('onDone'),
state: {
fields: [
{name: 'col1', type: {name: 'INTEGER'}},
{name: 'col2', type: {name: 'TEXT'}}
]
}
};
});
it('should render with minimal props without exploding', () => {
const wrapper = shallow(<AccelerationUpdatesController {...minimalProps}/>);
expect(wrapper).to.have.length(1);
});
it('should not render acceleration updates form when settings are not available', () => {
const wrapper = shallow(<AccelerationUpdatesController {...minimalProps}/>);
expect(wrapper.find(AccelerationUpdatesForm)).to.have.length(0);
});
it('should render acceleration updates form when settings are available', () => {
const wrapper = shallow(<AccelerationUpdatesController {...commonProps}/>);
expect(wrapper.find(AccelerationUpdatesForm)).to.have.length(1);
});
describe('#componentWillMount', () => {
it('should call recieveProps to perform summaryDataset and settings loading', () => {
sinon.stub(AccelerationUpdatesController.prototype, 'receiveProps');
const wrapper = shallow(<AccelerationUpdatesController {...minimalProps}/>);
const instance = wrapper.instance();
expect(instance.receiveProps).to.be.calledWith(minimalProps, {});
AccelerationUpdatesController.prototype.receiveProps.restore();
});
});
describe('#componentWillReceiveProps', () => {
it('should call recieveProps with nextProps', () => {
sinon.stub(AccelerationUpdatesController.prototype, 'receiveProps');
const wrapper = shallow(<AccelerationUpdatesController {...minimalProps}/>);
const instance = wrapper.instance();
const nextProps = {entity: {}};
instance.componentWillReceiveProps(nextProps);
expect(instance.receiveProps).to.be.calledWith(nextProps, minimalProps);
AccelerationUpdatesController.prototype.receiveProps.restore();
});
});
describe('#recieveProps', () => {
let wrapper;
let instance;
let props;
beforeEach(() => {
sinon.stub(AccelerationUpdatesController.prototype, 'componentWillMount');
props = {
...commonProps,
loadSummaryDataset: sinon.stub().returns({then: f => f()})
};
wrapper = shallow(<AccelerationUpdatesController {...props}/>);
instance = wrapper.instance();
sinon.stub(instance, 'loadDataset').returns(Promise.resolve({
fields: [
{name: 'col1', type: {name: 'INTEGER'}},
{name: 'col2', type: {name: 'TEXT'}}
]
}));
});
afterEach(() => {
AccelerationUpdatesController.prototype.componentWillMount.restore();
});
it('should load settings when entity changed', (done) => {
const nextProps = {
...props,
entity: props.entity.set('fullPath', ['changed_path'])
};
instance.receiveProps(nextProps, props);
setTimeout(() => {
expect(props.loadDatasetAccelerationSettings).to.have.been.called;
done();
}, 50);
});
it('should not load settings when entity did not change', (done) => {
instance.receiveProps(props, props);
setTimeout(() => {
expect(props.loadDatasetAccelerationSettings).to.have.not.been.called;
done();
}, 50);
});
});
describe('#schemaToColumns', () => {
it('should return only incremental columns', () => {
const summaryDataset = {
fields: ALL_TYPES.map((type, i) => ({type: {name: type}, name: `col${i}`}))
};
const wrapper = shallow(<AccelerationUpdatesController {...minimalProps}/>);
const instance = wrapper.instance();
const columnTypes = instance.schemaToColumns(summaryDataset).toJS().map(field => field.type);
expect(columnTypes).to.have.members(INCREMENTAL_TYPES);
});
});
describe('#submit', () => {
it('should perform settings update and call onDone when saved', (done) => {
sinon.stub(ApiUtils, 'attachFormSubmitHandlers').returns(Promise.resolve());
const wrapper = shallow(<AccelerationUpdatesController {...commonProps}/>);
const instance = wrapper.instance();
const formValue = commonProps.accelerationSettings.toJS();
expect(instance.submit(formValue)).to.eventually.equal('onDone').notify(done);
expect(ApiUtils.attachFormSubmitHandlers).to.have.been.calledWith(
commonProps.updateDatasetAccelerationSettings(commonProps.entity, formValue)
);
ApiUtils.attachFormSubmitHandlers.restore();
});
});
});
|
<reponame>vchoudhari45/codingcargo
package com.vc.medium
case class DoublyLinkedList(var prev: DoublyLinkedList, var next: DoublyLinkedList, value: Int)
class MyCircularDeque(k: Int) {
/** Initialize your data structure here. Set the size of the deque to be k. */
val head = new DoublyLinkedList(null, null, -1)
val tail = new DoublyLinkedList(head, null, -1)
head.next = tail
var size = 0
/** Adds an item at the front of Deque. Return true if the operation is successful. */
def insertFront(value: Int): Boolean = {
if(size < k) {
val headNext = head.next
val e = DoublyLinkedList(head, headNext, value)
headNext.prev = e
head.next = e
size += 1
return true
}
false
}
/** Adds an item at the rear of Deque. Return true if the operation is successful. */
def insertLast(value: Int): Boolean = {
if(size < k) {
val tailPrev = tail.prev
val e = DoublyLinkedList(tailPrev, tail, value)
tailPrev.next = e
tail.prev = e
size += 1
return true
}
false
}
/** Deletes an item from the front of Deque. Return true if the operation is successful. */
def deleteFront(): Boolean = {
if(size > 0) {
head.next = head.next.next
head.next.prev = head
size -= 1
return true
}
return false
}
/** Deletes an item from the rear of Deque. Return true if the operation is successful. */
def deleteLast(): Boolean = {
if(size > 0) {
tail.prev = tail.prev.prev
tail.prev.next = tail
size -= 1
return true
}
return false
}
/** Get the front item from the deque. */
def getFront(): Int = head.next.value
/** Get the last item from the deque. */
def getRear(): Int = tail.prev.value
/** Checks whether the circular deque is empty or not. */
def isEmpty(): Boolean = size == 0
/** Checks whether the circular deque is full or not. */
def isFull(): Boolean = size == k
}
/**
* Your MyCircularDeque object will be instantiated and called as such:
* var obj = new MyCircularDeque(k)
* var param_1 = obj.insertFront(value)
* var param_2 = obj.insertLast(value)
* var param_3 = obj.deleteFront()
* var param_4 = obj.deleteLast()
* var param_5 = obj.getFront()
* var param_6 = obj.getRear()
* var param_7 = obj.isEmpty()
* var param_8 = obj.isFull()
*/
|
import React from 'react';
import { shallow, mount, render } from 'enzyme';
import { MarkdownTextBox } from "../src/index";
describe('A suite', function() {
it('should have full elements', function(){
const wrapper = shallow(<MarkdownTextBox />);
expect(wrapper.find('.description').length).toBe(1);
expect(wrapper.find('.top').length).toBe(1);
expect(wrapper.find('.text').length).toBe(1);
})
it('should have proper description', function(){
const wrapper = shallow(<MarkdownTextBox />);
wrapper.setState({markdownvalue:"foobar"});
expect(wrapper.find('.description').text()).toBe("foobar");
})
it('should renders h1 properly', function(){
const wrapper = shallow(<MarkdownTextBox />);
wrapper.setState({markdownvalue:"h1.foobar"});
expect(wrapper.find('.description').text()).toBe("foobar");
})
it('should renders h2 properly', function(){
const wrapper = shallow(<MarkdownTextBox />);
wrapper.setState({markdownvalue:"h2.foobar"});
expect(wrapper.find('.description').text()).toBe("foobar");
})
it('should renders h3 properly', function(){
const wrapper = shallow(<MarkdownTextBox />);
wrapper.setState({markdownvalue:"h3.foobar"});
expect(wrapper.find('.description').text()).toBe("foobar");
})
it('should renders h4 properly', function(){
const wrapper = shallow(<MarkdownTextBox />);
wrapper.setState({markdownvalue:"h4.foobar"});
expect(wrapper.find('.description').text()).toBe("foobar");
})
it('should renders h5 properly', function(){
const wrapper = shallow(<MarkdownTextBox />);
wrapper.setState({markdownvalue:"h5.foobar"});
expect(wrapper.find('.description').text()).toBe("foobar");
})
it('should renders h6 properly', function(){
const wrapper = shallow(<MarkdownTextBox />);
wrapper.setState({markdownvalue:"h6.foobar"});
expect(wrapper.find('.description').text()).toBe("foobar");
})
it('should renders bold properly', function(){
const wrapper = shallow(<MarkdownTextBox />);
wrapper.setState({markdownvalue:"*foobar*"});
expect(wrapper.find('.description').text()).toBe("foobar");
})
it('should renders codeline properly', function(){
let test ="Among other public buildings in a certain town, which for many reasons it will be prudent to refrain from mentioning, and to which I will assign no fictitious name, there is one anciently common to most towns, great or small: to wit, a workhouse; and in this workhouse was born; on a day and date which I need not trouble myself to repeat, inasmuch as it can be of no possible consequence to the reader, in this stage of the business at all events; the item of mortality whose name is prefixed to the head of this chapter.\n" +
"For a long time after it was ushered into this world of sorrow and trouble, by the parish surgeon, it remained a matter of considerable doubt whether the child would survive to bear any name at all; in which case it is somewhat more than probable that these memoirs would never have appeared; or, if they had, that being comprised within a couple of pages, they would have possessed the inestimable merit of being the most concise and faithful specimen of biography, extant in the literature of any age or country."
const wrapper = mount(<MarkdownTextBox value={`\`\`\`${test}\`\`\` next sentence`}/>);
let fs = require("fs");
fs.writeFileSync("./test/__html__/index.test.codeline_longtext.html", wrapper.html());
const wrapper2 = mount(<MarkdownTextBox value={`\`\`\`${test}\`\`\` next sentence`}/>);
expect(wrapper2.find('.description').at(0).text()).toEqual(expect.stringContaining("Among other public buildings"));
})
it('should renders codeline properly', function(){
let test ="foo\nbar\nbaz"
const wrapper = mount(<MarkdownTextBox value={`\`\`\`${test}\`\`\` next sentence`}/>);
let fs = require("fs");
fs.writeFileSync("./test/__html__/index.test.codeline_shorttext.html", wrapper.html());
const wrapper2 = mount(<MarkdownTextBox value={`\`\`\`${test}\`\`\` next sentence`}/>);
expect(wrapper2.find('.description').at(0).text()).toEqual(expect.stringContaining("foo"));
})
it('should renders codeline properly', function(){
let tmp ="foo bar baz"
let test="";
for (let i = 0; i < 30; i++) {
test = test + "\n"+ " ".repeat(i) + tmp;
}
const wrapper = mount(<MarkdownTextBox value={`\`\`\`${test}\`\`\` next sentence`}/>);
let fs = require("fs");
fs.writeFileSync("./test/__html__/index.test.codeline_multilinetext.html", wrapper.html());
const wrapper2 = mount(<MarkdownTextBox value={`\`\`\`${test}\`\`\` next sentence`}/>);
expect(wrapper2.find('.description').at(0).text()).toEqual(expect.stringContaining("foo"));
})
});
|
<reponame>JayElPo/react-native
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* The examples provided by Facebook are for non-commercial testing and
* evaluation purposes only.
*
* Facebook reserves all rights not expressly granted.
*
* 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 NON INFRINGEMENT. IN NO EVENT SHALL
* FACEBOOK 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.
*
* @flow
*/
'use strict';
const NavigationExampleRow = require('./NavigationExampleRow');
const React = require('react');
const ReactNative = require('react-native');
/**
* Basic example that shows how to use <NavigationTransitioner /> and
* <Animated.View /> to build a stack of animated scenes that render the
* navigation state.
*/
import type {
NavigationSceneRendererProps,
NavigationState,
NavigationTransitionProps,
NavigationTransitionSpec,
} from 'NavigationTypeDefinition';
const {
Component,
PropTypes,
} = React;
const {
Animated,
Easing,
NavigationExperimental,
ScrollView,
StyleSheet,
} = ReactNative;
const {
PropTypes: NavigationPropTypes,
StateUtils: NavigationStateUtils,
Transitioner: NavigationTransitioner,
} = NavigationExperimental;
function reducer(state: ?NavigationState, action: any): NavigationState {
if (!state) {
return {
index: 0,
routes: [{key: 'route-1'}],
};
}
switch (action) {
case 'push':
const route = {key: 'route-' + (state.routes.length + 1)};
return NavigationStateUtils.push(state, route);
case 'pop':
return NavigationStateUtils.pop(state);
}
return state;
}
class Example extends Component {
state: NavigationState;
constructor(props: any, context: any) {
super(props, context);
this.state = reducer();
}
render(): ReactElement<any> {
return (
<ExampleNavigator
navigationState={this.state}
navigate={action => this._navigate(action)}
/>
);
}
_navigate(action: any): boolean {
if (action === 'exit') {
// Exits the example. `this.props.onExampleExit` is provided
// by the UI Explorer.
this.props.onExampleExit && this.props.onExampleExit();
return false;
}
const state = reducer(this.state, action);
if (state === this.state) {
return false;
}
this.setState(state);
return true;
}
// This public method is optional. If exists, the UI explorer will call it
// the "back button" is pressed. Normally this is the cases for Android only.
handleBackAction(): boolean {
return this._navigate('pop');
}
}
class ExampleNavigator extends Component {
props: {
navigate: Function,
navigationState: NavigationState,
};
static propTypes: {
navigationState: NavigationPropTypes.navigationState.isRequired,
navigate: PropTypes.func.isRequired,
};
render(): ReactElement<any> {
return (
<NavigationTransitioner
navigationState={this.props.navigationState}
render={(transitionProps) => this._render(transitionProps)}
configureTransition={this._configureTransition}
/>
);
}
_render(
transitionProps: NavigationTransitionProps,
): Array<ReactElement<any>> {
return transitionProps.scenes.map((scene) => {
const sceneProps = {
...transitionProps,
scene,
};
return this._renderScene(sceneProps);
});
}
_renderScene(
sceneProps: NavigationSceneRendererProps,
): ReactElement<any> {
return (
<ExampleScene
{...sceneProps}
key={sceneProps.scene.key}
navigate={this.props.navigate}
/>
);
}
_configureTransition(): NavigationTransitionSpec {
const easing: any = Easing.inOut(Easing.ease);
return {
duration: 500,
easing,
};
}
}
class ExampleScene extends Component {
props: NavigationSceneRendererProps & {
navigate: Function,
};
static propTypes = {
...NavigationPropTypes.SceneRendererProps,
navigate: PropTypes.func.isRequired,
};
render(): ReactElement<any> {
const {scene, navigate} = this.props;
return (
<Animated.View
style={[styles.scene, this._getAnimatedStyle()]}>
<ScrollView style={styles.scrollView}>
<NavigationExampleRow
text={scene.route.key}
/>
<NavigationExampleRow
text="Push Route"
onPress={() => navigate('push')}
/>
<NavigationExampleRow
text="Pop Route"
onPress={() => navigate('pop')}
/>
<NavigationExampleRow
text="Exit NavigationTransitioner Example"
onPress={() => navigate('exit')}
/>
</ScrollView>
</Animated.View>
);
}
_getAnimatedStyle(): Object {
const {
layout,
position,
scene,
} = this.props;
const {
index,
} = scene;
const inputRange = [index - 1, index, index + 1];
const width = layout.initWidth;
const translateX = position.interpolate({
inputRange,
outputRange: ([width, 0, -10]: Array<number>),
});
return {
transform: [
{ translateX },
],
};
}
}
const styles = StyleSheet.create({
scene: {
backgroundColor: '#E9E9EF',
bottom: 0,
flex: 1,
left: 0,
position: 'absolute',
right: 0,
shadowColor: 'black',
shadowOffset: {width: 0, height: 0},
shadowOpacity: 0.4,
shadowRadius: 10,
top: 0,
},
scrollView: {
flex: 1,
},
});
module.exports = Example;
|
<reponame>mcollina/torrent-docker-registry<filename>dolphin.js
#! /usr/bin/env node
'use strict';
var commist = require('commist')
var registry = require('./registry')
var pull = require('./pull')
var fs = require('fs')
var path = require('path')
function cli(args) {
var program = commist()
program.register('registry', registry)
program.register('pull', function(opts) {
pull(opts, function(err) {
if (err) {
console.log(err)
process.exit(1)
}
if (!opts.keep) {
process.exit(0)
}
})
})
return program.parse(args)
}
if (require.main === module) {
var remaining = cli(process.argv.splice(2))
if (remaining) {
fs.createReadStream(path.join(__dirname, 'docs', 'help.txt'))
.pipe(process.stdout)
}
}
module.exports = {
pull: pull
, registry: registry
, cli: cli
}
|
# Just run the following cells to scrape data from your LinkedIn profile (or anyone's, if you know their password :) ).
# Replace the content of "config.txt" file with the desired username or password to let it automatically fill duing login.
# Also remember to change the path of driver (mentioned in the cell), to your own location in Line 12.
# Change to your own LinkedIn username in line 30
# This particular wrapper scrapes the information data like name, connections, profile titile, location from the LikedIn profile and can easily be extended to other sections of profile.
# Now, you only require to have selenium and chrome driver installed in your machine and start have fun!!
import requests, time, random
from bs4 import BeautifulSoup
from selenium import webdriver
browser = webdriver.Chrome('C:/SomeLocation/chromedriver/chromedriver_win32/chromedriver.exe') # Change the location of chromedriver Here
browser.get('https://www.linkedin.com/uas/login')
file = open('config.txt')
lines = file.readlines()
username = lines[0]
password = <PASSWORD>[1]
elementID = browser.find_element_by_id('username')
elementID.send_keys(username)
elementID = browser.find_element_by_id('password')
elementID.send_keys(password)
elementID.submit()
link = 'https://www.linkedin.com/in/myusername/' #Change it to your own username
browser.get(link)
SCROLL_PAUSE_TIME = 5
# Get scroll height
last_height = browser.execute_script("return document.body.scrollHeight")
for i in range(3):
# Scroll down to bottom
browser.execute_script("window.scrollTo(0, document.body.scrollHeight);")
# Wait to load page
time.sleep(SCROLL_PAUSE_TIME)
# Calculate new scroll height and compare with last scroll height
new_height = browser.execute_script("return document.body.scrollHeight")
if new_height == last_height:
break
last_height = new_height
src = browser.page_source
soup = BeautifulSoup(src, 'lxml')
#soup
name_div = soup.find('div', {'class': 'flex-1 mr5'})
#name_div
name_loc = name_div.find_all('ul')
name = name_loc[0].find('li').get_text().strip()
#name
loc = name_loc[1].find('li').get_text().strip()
#loc
profile_title = name_div.find('h2').get_text().strip()
#profile_title
connection = name_loc[1].find_all('li')
connection = connection[1].get_text().strip()
#connection
info = []
info.append(link)
info.append(name)
info.append(profile_title)
info.append(loc)
info.append(connection)
print(info)
browser.quit()
|
$(document).ready(function(){
$(".clickable1").click(function(){
$(".img1").toggle();
$(".design1").toggle();
});
$(".clickable2").click(function(){
$(".img2").toggle();
$(".dev").toggle();
});
$(".clickable3").click(function(){
$(".img3").toggle();
$(".product").toggle();
});
});
$(document).ready(function(){
$("#port1").mouseover(function(){
$(".port1").show();
})
.mouseout(function(){
$(".port1 ").hide();
});
$("#port2").mouseover(function(){
$(".port2").show();
})
.mouseout(function(){
$(".port2").hide();
});
$("#port3").mouseover(function(){
$(".port3").show();
})
.mouseout(function(){
$(".port3").hide();
});
$("#port4").mouseover(function(){
$(".port4").show();
})
.mouseout(function(){
$(".port4").hide();
});
$("#port5").mouseover(function(){
$(".port5").show();
})
.mouseout(function(){
$(".port5").hide();
});
$("#port6").mouseover(function(){
$(".port6").show();
})
.mouseout(function(){
$(".port6").hide();
});
$("#port7").mouseover(function(){
$(".port7").show();
})
.mouseout(function(){
$(".port7").hide();
});
$("#port8").mouseover(function(){
$(".port8").show();
})
.mouseout(function(){
$(".port8").hide();
});
});
$(document).ready(function(){
$("form").submit(function(){
var name = $("#name").val();
var email = $("#email").val();
var message = $("#message").val();
alert(name+' thanks for feedback');
});
});
|
<gh_stars>1-10
#ifndef F5529_BLDC_SETTINGS_H_
#define F5529_BLDC_SETTINGS_H_
#ifdef __cplusplus
extern "C" {
#endif
// ----------------------------------------------------------------------
// info and license
// ----------------------------------------------------------------------
//
// filename: F5529_BLDC_Settings.h
//
// MIT License
//
// Copyright (c) 2019 <NAME>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// target: Texas Instruments MSP430F5529LP with BOOSTXL-DRV8323RS EVM
//
// ----------------------------------------------------------------------
// history
// ----------------------------------------------------------------------
// 17.08.2019 - initial programming
// ----------------------------------------------------------------------
// header files
// ----------------------------------------------------------------------
// ----------------------------------------------------------------------
// #defines
// ----------------------------------------------------------------------
// ----------------------------------------------------------------------
// Define the system frequencies:
// ----------------------------------------------------------------------
#define XT1_LF_CRYSTAL_FREQUENCY_IN_HZ 32768 // 32KHz
#define XT2_HF_CRYSTAL_FREQUENCY_IN_HZ 4000000 // 4MHz
#define MCLK_FREQUENCY_1MHz 1000 // Value has to be in kHz
#define MCLK_FREQUENCY_4MHz 4000 // Value has to be in kHz
#define MCLK_FREQUENCY_8MHz 8000 // Value has to be in kHz
#define MCLK_FREQUENCY_12MHz 12000 // Value has to be in kHz
#define MCLK_FREQUENCY_16MHz 16000 // Value has to be in kHz
#define MCLK_FREQUENCY_25MHz 25000 // Value has to be in kHz
#define MCLK_DESIRED_FREQUENCY_IN_KHZ MCLK_FREQUENCY_25MHz
#define MCLK_FLLREF_RATIO MCLK_DESIRED_FREQUENCY_IN_KHZ / ( UCS_REFOCLK_FREQUENCY / 1024 ) // Ratio = 250 for 8MHz clock
#define XT1_TIMEOUT 50000
#define XT2_TIMEOUT 50000
#define SYSTEM_FREQUENCY_MHz (MCLK_DESIRED_FREQUENCY_IN_KHZ / 1000)
// ----------------------------------------------------------------------
// Define the control and PWM frequencies:
// ----------------------------------------------------------------------
// 16kHz is the maximum frequency according to the calculation duration in the mode run and spin.
#define DEVICE_PWM_FREQUENCY_kHz (16.0)
#define DEVICE_ISR_FREQUENCY_kHz DEVICE_PWM_FREQUENCY_kHz
#define DEVICE_ISR_PERIDODE_Sec (0.001/DEVICE_ISR_FREQUENCY_kHz)
// ticks for the PWM module
#define DEVICE_PWM_CLOCK_FREQUENCY_MHz (MCLK_DESIRED_FREQUENCY_IN_KHZ)
#define DEVICE_PWM_TICKS ((DEVICE_PWM_CLOCK_FREQUENCY_MHz/DEVICE_PWM_FREQUENCY_kHz)*1000)
#define DEVICE_PWM_TBPRD (DEVICE_PWM_TICKS/2)
// ----------------------------------------------------------------------
// Define the ADC dependencies:
// ----------------------------------------------------------------------
// 3 phase currents are located at:
#define DRV_ISEN_A_CH ADC12_A_INPUT_A12
#define DRV_ISEN_B_CH ADC12_A_INPUT_A4
#define DRV_ISEN_C_CH ADC12_A_INPUT_A3
// 3 phase voltages are located at:
#define DRV_VSEN_A_CH ADC12_A_INPUT_A0
#define DRV_VSEN_B_CH ADC12_A_INPUT_A1
#define DRV_VSEN_C_CH ADC12_A_INPUT_A2
// bus voltage is located at:
#define DRV_VSEN_VM_CH ADC12_A_INPUT_A5
// DRV potentiometer is located at:
#define DRV_POTENTIOMETER_CH ADC12_A_INPUT_A6
// 3 phase currents memory:
#define DRV_ADC_ISEN_A ADC12_A_MEMORY_3
#define DRV_ADC_ISEN_B ADC12_A_MEMORY_4
#define DRV_ADC_ISEN_C ADC12_A_MEMORY_5
// 3 phase voltages memory:
#define DRV_ADC_VSEN_A ADC12_A_MEMORY_0
#define DRV_ADC_VSEN_B ADC12_A_MEMORY_1
#define DRV_ADC_VSEN_C ADC12_A_MEMORY_2
// bus voltage memory:
#define DRV_ADC_VSEN_VM ADC12_A_MEMORY_6
// DRV potentiometer memory:
#define DRV_ADC_POTI ADC12_A_MEMORY_7
// ----------------------------------------------------------------------
// Define motor parameter:
// ----------------------------------------------------------------------
// these values fit for an "Hetai 42BLF01" motor
#define MOTOR_POLES (8)
#define MOTOR_POLEPAIRS (MOTOR_POLES/2)
#define MOTOR_RS_OHM (0.985100389)
#define MOTOR_LD_H (0.00053623761)
#define MOTOR_LQ_H (0.00053623761)
#define MOTOR_FLUX_WB (0.0063879968)
#define MOTOR_MAX_SPD_RPM (4000.0L)
#define MOTOR_MAX_SPD_ELEC ((MOTOR_MAX_SPD_RPM/60)*MOTOR_POLEPAIRS)
#define MOTOR_MEASURINGRANGE_RPM (1.2 * MOTOR_MAX_SPD_RPM) // give 20% headroom
#define MOTOR_MAX_CURRENT_IDC_A (2.0)
// ----------------------------------------------------------------------
// Define the operating conditions for open-loop start up ramp
// ----------------------------------------------------------------------
#define TRIGGER_PER_REVOLUTION 6 // 6-step commutation
#define OPENLOOP_END_RPM 500 // [rpm]
#define OPENLOOP_RAMP_DELAY (0.4) // [sec]
#define OPENLOOP_DUTY (0.3) // 30% of DEVICE_SHUNT_CURRENT_A
// open loop ramps up from 1 rpm up to OPENLOOP_END_RPM.
// open-loop algorithm works with period input...
// don't change the following 5 lines:
#define OPENLOOP_START_TICKS ((DEVICE_ISR_FREQUENCY_kHz*1000)/(TRIGGER_PER_REVOLUTION*MOTOR_POLEPAIRS*OPENLOOP_START_PERIODE))
#define OPENLOOP_END_TICKS ((DEVICE_ISR_FREQUENCY_kHz*1000)/(TRIGGER_PER_REVOLUTION*MOTOR_POLEPAIRS*OPENLOOP_END_PERIODE))
#define OPENLOOP_DELAY_TICKS ((DEVICE_ISR_FREQUENCY_kHz*1000*OPENLOOP_RAMP_DELAY)/(OPENLOOP_START_TICKS-OPENLOOP_END_TICKS))
#define OPENLOOP_START_PERIODE 1 // [Hz]
#define OPENLOOP_END_PERIODE (OPENLOOP_END_RPM / 60) // [Hz]
// ----------------------------------------------------------------------
// Define the operating conditions for ramp control
// ----------------------------------------------------------------------
#define DEVICE_RAMP_ACC_STEPS 10 // Gradient for accelerate
#define DEVICE_RAMP_DEC_STEPS 15 // Gradient for decelerate
// ----------------------------------------------------------------------
// Define the DRV8323 quantities (gain)
// ----------------------------------------------------------------------
//#define DRV8323_GAIN_5 5
//#define DRV8323_GAIN_10 10
//#define DRV8323_GAIN_20 20
#define DRV8323_GAIN_40 40
// ----------------------------------------------------------------------
// Define the device quantities (voltage, current, speed)
// ----------------------------------------------------------------------
#define DEVICE_DC_VOLTAGE_V 56.867134 // max. ADC bus voltage(PEAK) [V]
#ifdef DRV8323_GAIN_5
#define DEVICE_SHUNT_CURRENT_A 47.0 // phase current(PEAK) [A]
#elif DRV8323_GAIN_10
#define DEVICE_SHUNT_CURRENT_A 23.5 // phase current(PEAK) [A]
#elif DRV8323_GAIN_20
#define DEVICE_SHUNT_CURRENT_A 11.75 // phase current(PEAK) [A]
#elif DRV8323_GAIN_40
#define DEVICE_SHUNT_CURRENT_A 5.875 // phase current(PEAK) [A]
#endif
// ----------------------------------------------------------------------
// Define the device quantities limits for shutdown / safety functions
// ----------------------------------------------------------------------
#define DEVICE_MAX_CURRENT_A 5.90 // limit of motor or semiconductor
#define DEVICE_MAX_DC_VOLTAGE_V 30.00 // limit of motor or semiconductor
#define DEVICE_MIN_DC_VOLTAGE_V 8.00
#define DEVICE_UNDERVOLTAGE_TIMEOUT_mSec 5.0
// scale to per-unit
#define DEVICE_MAX_CURRENT_PU (DEVICE_MAX_CURRENT_A / DEVICE_SHUNT_CURRENT_A)
#define DEVICE_MAX_DC_VOLTAGE_PU (DEVICE_MAX_DC_VOLTAGE_V / DEVICE_DC_VOLTAGE_V)
// ----------------------------------------------------------------------
// Define the device pin mappings
// ----------------------------------------------------------------------
#define GPIO_SPI_SCLK GPIO_PORT_P3, GPIO_PIN2
#define GPIO_SPI_MOSI GPIO_PORT_P3, GPIO_PIN0
#define GPIO_SPI_MISO GPIO_PORT_P3, GPIO_PIN1
#define GPIO_UART_TX GPIO_PORT_P3, GPIO_PIN3
#define GPIO_UART_RX GPIO_PORT_P3, GPIO_PIN4
#define GPIO_I2C_SCL GPIO_PORT_P4, GPIO_PIN2
#define GPIO_I2C_SDA GPIO_PORT_P4, GPIO_PIN1
#define GPIO_HALL_A GPIO_PORT_P2, GPIO_PIN0
#define GPIO_HALL_B GPIO_PORT_P2, GPIO_PIN2
#define GPIO_HALL_C GPIO_PORT_P2, GPIO_PIN6
#define GPIO_LED_RED GPIO_PORT_P1, GPIO_PIN0
#define GPIO_LED_GREEN GPIO_PORT_P4, GPIO_PIN7
#define GPIO_BUTTON_S1 GPIO_PORT_P2, GPIO_PIN1
#define GPIO_BUTTON_S2 GPIO_PORT_P1, GPIO_PIN1
#define GPIO_XOUT_XIN GPIO_PORT_P5, GPIO_PIN5 | GPIO_PIN4
#define GPIO_XT2OUT_XT2IN GPIO_PORT_P5, GPIO_PIN3 | GPIO_PIN2
#define GPIO_ACLK GPIO_PORT_P1, GPIO_PIN0
#define GPIO_SMCLK GPIO_PORT_P2, GPIO_PIN2
#define GPIO_MCLK GPIO_PORT_P7, GPIO_PIN7
#define GPIO_DRV_CS GPIO_PORT_P2, GPIO_PIN3
#define GPIO_DRV_CAL GPIO_PORT_P8, GPIO_PIN1
#define GPIO_DRV_nFAULT GPIO_PORT_P2, GPIO_PIN7
#define GPIO_DRV_ENABLE GPIO_PORT_P1, GPIO_PIN6
#define GPIO_DRV_LED GPIO_PORT_P4, GPIO_PIN0
// The DRV is going to be used in 1xPWM-Mode:
#define GPIO_DRV_INHA GPIO_PORT_P2, GPIO_PIN5
#define GPIO_DRV_INLA GPIO_PORT_P2, GPIO_PIN4
#define GPIO_DRV_INHB GPIO_PORT_P1, GPIO_PIN5
#define GPIO_DRV_INLB GPIO_PORT_P1, GPIO_PIN4
#define GPIO_DRV_INHC GPIO_PORT_P1, GPIO_PIN3
#define GPIO_DRV_INLC GPIO_PORT_P1, GPIO_PIN2
// In 1xPWM-Mode GPIO_DRV_INHC & GPIO_DRV_INLC have some special functions:
// The INHC input controls the direction through the 6-step commutation
// table which is used to change the direction of the motor when Hall
// effect sensors are directly controlling the state of the INLA, INHB,
// and INLB inputs. Tie the INHC pin low if this feature is not required.
#define GPIO_DRV_DIR GPIO_DRV_INHC
// The INLC input brakes the motor by turning off all high-side MOSFETs
// and turning on all low-side MOSFETs when the INLC pin is pulled low.
#define GPIO_DRV_BRAKE GPIO_DRV_INLC
// ----------------------------------------------------------------------
// end of file
// ----------------------------------------------------------------------
#ifdef __cplusplus
}
#endif /* extern "C" */
#endif /* F5529_BLDC_SETTINGS_H_ */
|
#!/bin/bash
# LinuxGSM install_squad_license.sh module
# Author: Daniel Gibbs
# Contributors: http://linuxgsm.com/contrib
# Website: https://linuxgsm.com
# Description: Configures the Squad server's license.
functionselfname="$(basename "$(readlink -f "${BASH_SOURCE[0]}")")"
echo -e ""
echo -e "${lightyellow}Squad Server License${default}"
echo -e "================================="
fn_sleep_time
echo -e "Server license is an optional feature for ${gamename} server"
fn_script_log_info "Server license is an optional feature for ${gamename} server"
echo -e "Get more info and a server license here:"
echo -e "http://forums.joinsquad.com/topic/16519-server-licensing-general-info/"
fn_script_log_info "Get more info and a server license here:"
fn_script_log_info "http://forums.joinsquad.com/topic/16519-server-licensing-general-info/"
echo -e ""
fn_sleep_time
echo -e "The Squad server license can be changed by editing ${servercfgdir}/License.cfg."
fn_script_log_info "The Squad server license can be changed by editing ${selfname}."
echo -e ""
|
#!/usr/bin/env bash
set -e
set -x
shopt -s dotglob
readonly name="yaml-cpp"
readonly ownership="yaml-cpp Upstream <robot@adios2>"
readonly subtree="thirdparty/yaml-cpp/yaml-cpp"
readonly repo="https://github.com/jbeder/yaml-cpp.git"
readonly tag="yaml-cpp-0.6.3"
readonly shortlog="true"
readonly paths="
"
extract_source () {
git_archive
}
. "${BASH_SOURCE%/*}/../update-common.sh"
|
// find tag values
pub fn get_values(tags: &[Tag], keys: &[String]) -> Vec<String> {
let mut result: Vec<String> = vec!["".to_string(); keys.len()];
for tag in tags {
if let Some(index) = keys.iter().position(|k| *k == tag.key) {
result[index] = tag.value.clone();
}
}
result
}
|
<reponame>lheureuxe13/oppia
# Copyright 2019 The Oppia Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Controllers for the skill mastery."""
from __future__ import absolute_import
from __future__ import unicode_literals
from core import feconf
from core import python_utils
from core import utils
from core.controllers import acl_decorators
from core.controllers import base
from core.domain import skill_domain
from core.domain import skill_fetchers
from core.domain import skill_services
from core.domain import topic_fetchers
class SkillMasteryDataHandler(base.BaseHandler):
"""A handler that handles fetching and updating the degrees of user
skill mastery.
"""
GET_HANDLER_ERROR_RETURN_TYPE = feconf.HANDLER_TYPE_JSON
@acl_decorators.can_access_learner_dashboard
def get(self):
"""Handles GET requests."""
comma_separated_skill_ids = (
self.request.get('comma_separated_skill_ids'))
if not comma_separated_skill_ids:
raise self.InvalidInputException(
'Expected request to contain parameter '
'comma_separated_skill_ids.')
skill_ids = comma_separated_skill_ids.split(',')
try:
for skill_id in skill_ids:
skill_domain.Skill.require_valid_skill_id(skill_id)
except utils.ValidationError:
raise self.InvalidInputException('Invalid skill ID %s' % skill_id)
try:
skill_fetchers.get_multi_skills(skill_ids)
except Exception as e:
raise self.PageNotFoundException(e)
degrees_of_mastery = skill_services.get_multi_user_skill_mastery(
self.user_id, skill_ids)
self.values.update({
'degrees_of_mastery': degrees_of_mastery
})
self.render_json(self.values)
@acl_decorators.can_access_learner_dashboard
def put(self):
"""Handles PUT requests."""
mastery_change_per_skill = (
self.payload.get('mastery_change_per_skill'))
if (not mastery_change_per_skill or
not isinstance(mastery_change_per_skill, dict)):
raise self.InvalidInputException(
'Expected payload to contain mastery_change_per_skill '
'as a dict.')
skill_ids = list(mastery_change_per_skill.keys())
current_degrees_of_mastery = (
skill_services.get_multi_user_skill_mastery(self.user_id, skill_ids)
)
new_degrees_of_mastery = {}
for skill_id in skill_ids:
try:
skill_domain.Skill.require_valid_skill_id(skill_id)
except utils.ValidationError:
raise self.InvalidInputException(
'Invalid skill ID %s' % skill_id)
# float(bool) will not raise an error.
if isinstance(mastery_change_per_skill[skill_id], bool):
raise self.InvalidInputException(
'Expected degree of mastery of skill %s to be a number, '
'received %s.'
% (skill_id, mastery_change_per_skill[skill_id]))
try:
mastery_change_per_skill[skill_id] = (
float(mastery_change_per_skill[skill_id]))
except (TypeError, ValueError):
raise self.InvalidInputException(
'Expected degree of mastery of skill %s to be a number, '
'received %s.'
% (skill_id, mastery_change_per_skill[skill_id]))
if current_degrees_of_mastery[skill_id] is None:
current_degrees_of_mastery[skill_id] = 0.0
new_degrees_of_mastery[skill_id] = (
current_degrees_of_mastery[skill_id] +
mastery_change_per_skill[skill_id])
if new_degrees_of_mastery[skill_id] < 0.0:
new_degrees_of_mastery[skill_id] = 0.0
elif new_degrees_of_mastery[skill_id] > 1.0:
new_degrees_of_mastery[skill_id] = 1.0
try:
skill_fetchers.get_multi_skills(skill_ids)
except Exception as e:
raise self.PageNotFoundException(e)
skill_services.create_multi_user_skill_mastery(
self.user_id, new_degrees_of_mastery)
self.render_json({})
class SubtopicMasteryDataHandler(base.BaseHandler):
"""A handler that handles fetching user subtopic mastery for a topic."""
GET_HANDLER_ERROR_RETURN_TYPE = feconf.HANDLER_TYPE_JSON
URL_PATH_ARGS_SCHEMAS = {}
HANDLER_ARGS_SCHEMAS = {
'GET': {
'comma_separated_topic_ids': {
'schema': {
'type': 'basestring'
}
}
}
}
@acl_decorators.can_access_learner_dashboard
def get(self):
"""Handles GET requests."""
comma_separated_topic_ids = (
self.request.get('comma_separated_topic_ids'))
topic_ids = comma_separated_topic_ids.split(',')
topics = topic_fetchers.get_topics_by_ids(topic_ids)
all_skill_ids = []
subtopic_mastery_dict = {}
for ind, topic in enumerate(topics):
if not topic:
raise self.InvalidInputException(
'Invalid topic ID %s' % topic_ids[ind])
all_skill_ids.extend(topic.get_all_skill_ids())
all_skill_ids = list(set(all_skill_ids))
all_skills_mastery_dict = skill_services.get_multi_user_skill_mastery(
self.user_id, all_skill_ids)
for topic in topics:
subtopic_mastery_dict[topic.id] = {}
for subtopic in topic.subtopics:
skill_mastery_dict = {
skill_id: mastery
for skill_id, mastery in all_skills_mastery_dict.items()
if mastery is not None and skill_id in subtopic.skill_ids
}
if skill_mastery_dict:
# Subtopic mastery is average of skill masteries.
subtopic_mastery_dict[topic.id][subtopic.id] = (
python_utils.divide(
sum(skill_mastery_dict.values()),
len(skill_mastery_dict)))
self.values.update({
'subtopic_mastery_dict': subtopic_mastery_dict
})
self.render_json(self.values)
|
<reponame>alexandremcp/Papyrus
package br.com.papyrus.controller;
import br.com.papyrus.model.CriarConexao;
import br.com.papyrus.view.ViewDevolucoes;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import javax.swing.JOptionPane;
/**
*
* @author <NAME>
*/
public class ControllerDevolucoesComboBoxAcervo extends javax.swing.JFrame {
public static String s = "SELECT ace.Id, ace.Titulo AS TituloAcervo FROM acervo ace WHERE ace.Disponivel='não'";
/**
* Cria um novo formulário a partir de ControllerEmprestimosComboBoxAcervo
*/
public ControllerDevolucoesComboBoxAcervo() {
initComponents();
CarregarComboBox();
}
public void CarregarComboBox() {
CriarConexao cc = new CriarConexao();
HashMap<String, Integer> mapDevolucoes = cc.CarregarComboBox(s);
if (mapDevolucoes.keySet().isEmpty()) {
JOptionPane.showMessageDialog(null, "Não existem itens disponíveis para devolução !");
}
mapDevolucoes.keySet().forEach((s) -> {
cmbDevolucoesAcervo.addItem(s);
});
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
cmbDevolucoesAcervo = new javax.swing.JComboBox<>();
btnOk = new javax.swing.JButton();
btnCancelar = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("Escolha o item do acervo");
setAlwaysOnTop(true);
setName("Idioma"); // NOI18N
btnOk.setText("OK");
btnOk.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnOkActionPerformed(evt);
}
});
btnCancelar.setText("CANCELAR");
btnCancelar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnCancelarActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(29, 29, 29)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(cmbDevolucoesAcervo, javax.swing.GroupLayout.PREFERRED_SIZE, 230, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addComponent(btnOk, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnCancelar)))
.addContainerGap(32, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(23, 23, 23)
.addComponent(cmbDevolucoesAcervo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 24, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnOk)
.addComponent(btnCancelar))
.addContainerGap())
);
getAccessibleContext().setAccessibleName("Classificação");
pack();
setLocationRelativeTo(null);
}// </editor-fold>//GEN-END:initComponents
private void btnOkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnOkActionPerformed
CriarConexao cc = new CriarConexao();
HashMap<String, Integer> mapDevolucoes = cc.CarregarComboBox(s);
if (!mapDevolucoes.keySet().isEmpty()) {
try {
ViewDevolucoes.txtAcervo_Id.setText(mapDevolucoes.get(cmbDevolucoesAcervo.getSelectedItem().toString()).toString());
ViewDevolucoes.txtTituloAcervo.setText(cmbDevolucoesAcervo.getItemAt(cmbDevolucoesAcervo.getSelectedIndex()));
setarInformacoesSobreOAcervo();
this.dispose();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Item já foi selecionado, por favor escolha outro !");
}
} else {
this.dispose();
}
}//GEN-LAST:event_btnOkActionPerformed
private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
this.dispose();
}//GEN-LAST:event_btnCancelarActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ControllerDevolucoesComboBoxAcervo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new ControllerDevolucoesComboBoxAcervo().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnCancelar;
private javax.swing.JButton btnOk;
public static javax.swing.JComboBox<String> cmbDevolucoesAcervo;
// End of variables declaration//GEN-END:variables
private void setarInformacoesSobreOAcervo() {
if (!ViewDevolucoes.txtAcervo_Id.getText().isEmpty()) {
LocalDate dataDevolucao = LocalDate.now();
DateTimeFormatter formatoBR = DateTimeFormatter.ofPattern("dd-MM-yyyy");
try {
int numeroAcervo = Integer.parseInt(ViewDevolucoes.txtAcervo_Id.getText());
Connection conn = CriarConexao.abrirConexao();
String SQL = "SELECT tip.Id, tip.Dias AS DiasDeEmprestimo, "
+ "ace.Id, ace.Tipos_Id, ace.SubTitulo, ace.Exemplar, "
+ "ace.Edicao, ace.Volume, ace.Disponivel, ace.Local, "
+ "lei.Id AS IdLeitores, lei.Nome AS NomeLeitores, "
+ "aut.Id AS Autores_Id, aut.Nome AS AutorNome "
+ "FROM tipos tip "
+ "JOIN acervo ace ON ace.Tipos_Id = tip.Id "
+ "JOIN emprestimos emp ON emp.Acervo_Id = ace.Id "
+ "JOIN leitores lei ON lei.Id = emp.Leitores_Id "
+ "JOIN autores aut ON aut.Id = ace.Autores_Id "
+ "WHERE ace.Id = '" + numeroAcervo + "'";
Statement stm = conn.createStatement();
ResultSet rs = stm.executeQuery(SQL);
if (rs.next()) {
ViewDevolucoes.txtDevolucao.setText(dataDevolucao.format(formatoBR));
ViewDevolucoes.txtSubTituloAcervo.setText(rs.getString("SubTitulo"));
ViewDevolucoes.txtExemplarAcervo.setText(rs.getString("Exemplar"));
ViewDevolucoes.txtEdicaoAcervo.setText(rs.getString("Edicao"));
ViewDevolucoes.txtVolumeAcervo.setText(rs.getString("Volume"));
ViewDevolucoes.txtDisponivelAcervo.setText(rs.getString("Disponivel"));
ViewDevolucoes.txtLocalAcervo.setText(rs.getString("Local"));
ViewDevolucoes.txtLeitores_Id.setText(rs.getString("IdLeitores"));
ViewDevolucoes.txtNomeLeitores.setText(rs.getString("NomeLeitores"));
ViewDevolucoes.txtAutores_Id.setText(rs.getString("Autores_Id"));
ViewDevolucoes.txtAutorNome.setText(rs.getString("AutorNome"));
} else {
JOptionPane.showMessageDialog(null, "Primeiro selecione um item do acervo");
}
} catch (ClassNotFoundException | SQLException ex) {
ex.printStackTrace();
}
} else {
JOptionPane.showMessageDialog(null, "Primeiro selecione um item do acervo");
}
}
}
|
<filename>src/Register.js
import React from 'react';
import {
StyleSheet,
View,
Text,
ScrollView,
ToastAndroid,
TextComponent,
Alert
} from 'react-native';
import {
widthPercentageToDP as wp,
heightPercentageToDP as hp,
} from 'react-native-responsive-screen';
import Icon from 'react-native-vector-icons/Ionicons'
import Icon2 from 'react-native-vector-icons/Feather'
import moment from 'moment';
import DateTimePicker from "react-native-modal-datetime-picker";
import {Button} from 'react-native-elements'
import { TextField } from 'react-native-material-textfield';
import api from './services/api'
import LoadingScreen from './components/LoadingScreen';
import * as yup from 'yup'
import {Formik} from 'formik'
export default class Register extends React.Component {
constructor(props) {
super(props);
this.renderPasswordAccessory = this.renderPasswordAccessory.bind(this);
this.onAccessoryPress = this.onAccessoryPress.bind(this);
this.state = {
isVisible: false,
user:'',
email: '',
cpf:'',
birhtDate: '',
password: '',
contact: '',
secureTextEntry: true ,
load: false,
trueCpf: '',
};
}
Cadastra = async (values) => {
console.log(values)
try{
this.setState({load:true})
const response = await api.post('/users',{
email: values.email,
password: <PASSWORD>,
name: values.user,
cpf: values.cpf,
birth: (moment(this.state.birhtDate, 'DD/MM/YYYY').format('YYYY-MM-DD')),
contact: values.contact
});
this.setState({load:false})
Alert.alert('Parabéns, seu cadastro foi efetuado com sucesso',
'Para efetuar login, utilize seu E-mail com a sua Senha'
)
console.log(response)
this.props.navigation.navigate('Login')
} catch (response){
console.log(response)
this.setState({load:false})
let erro = response.response.data;
if (erro === 'CPF is invalid'){
ToastAndroid.showWithGravityAndOffset(
'CPF INVALIDO',
ToastAndroid.SHORT,
ToastAndroid.BOTTOM,
0,
200,
);
} else if(error = 'User already exists'){
this.setState({load:false})
ToastAndroid.showWithGravityAndOffset(
'Email já cadastrado',
ToastAndroid.SHORT,
ToastAndroid.BOTTOM,
0,
200,
);
}else {
this.setState({load:false})
ToastAndroid.showWithGravityAndOffset(
'Cadastro não efetuado, verifique seus dados',
ToastAndroid.SHORT,
ToastAndroid.BOTTOM,
0,
200,
);
}
}
}
_addMaskContactBr(contact){
try {
contact = contact.replace(/[^\d]+/g,'');
this.setState({ contact: contact });
if(contact.length == 10){
contact = (contact.length > 1 ? "(" : "")+contact.substring(0, 2) + (contact.length > 2 ? ")" : "")+(contact.length > 2 ? " " : "") + contact.substring(2,6) + (contact.length > 3 ? "-" : "") + contact.substring(6, 10);
} else {
contact = (contact.length > 1 ? "(" : "")+contact.substring(0, 2) + (contact.length > 2 ? ")" : "")+(contact.length > 2 ? " " : "") + contact.substring(3,2) + (contact.length > 3 ? " " : "") + contact.substring(3, 7) + (contact.length > 7 ? "-" : "") + contact.substring(7, 12);
}
} catch(e){
this.setState({ contact: contact });
}
return contact;
}
cpfMask (value) {
return value
.replace(/\D/g, '') // substitui qualquer caracter que nao seja numero por nada
.replace(/(\d{3})(\d)/, '$1.$2') // captura 2 grupos de numero o primeiro de 3 e o segundo de 1, apos capturar o primeiro grupo ele adiciona um ponto antes do segundo grupo de numero
.replace(/(\d{3})(\d)/, '$1.$2')
.replace(/(\d{3})(\d{1,2})/, '$1-$2')
.replace(/(-\d{2})\d+?$/, '$1') // captura 2 numeros seguidos de um traço e não deixa ser digitado mais nada
}
renderPasswordAccessory() {
let { secureTextEntry } = this.state;
let name = secureTextEntry?
'eye':
'eye-off';
return (
<Icon2 size={24} name={name} color='#01A83E' onPress={this.onAccessoryPress}/>
);
}
onAccessoryPress() {
this.setState(({ secureTextEntry }) => ({ secureTextEntry: !secureTextEntry }));
}
handlePicker =(date)=>{
this.setState({
isVisible: false,
birhtDate: moment(date).format('DD/MM/YYYY')
})
}
hidePicker =()=>{
this.setState({
isVisible: false
})
}
showPicker =()=>{
this.setState({
isVisible: true
})
}
render() {
return (
<>
<LoadingScreen enabled = {this.state.load}/>
<View style = {{flexGrow:1, backgroundColor: '#01A83E', marginBottom: hp('1%'), alignItems: 'center', justifyContent: 'center', alignSelf: 'center'}}>
<Text style={{fontSize: wp('4%'), color:'white', marginHorizontal: wp('15%')}}> Faça seu cadastro para aproveitar os descontos dos parceiros participantes</Text>
</View>
<ScrollView style = {{ backgroundColor: "white"}}>
<Formik
initialValues = {{user: '', email:'', password: '', contact: '', cpf:''}}
validationSchema ={
yup.object().shape({
user: yup.string()
.required('Insira um usuário'),
email: yup.string()
.required('Inisra um email')
.email('Insira um email válido'),
password: <PASSWORD>()
.required('Inisra uma senha')
.min(5, 'Senha muito curta'),
contact: yup.string()
.required('Inisra um telefone')
.min(11),
cpf: yup.string()
.required('Insira um CPF')
})
}
onSubmit={(values)=>{
console.log(values)
this.Cadastra(values)
}}
>
{({values, handleChange,errors, handleSubmit})=>(
<View style = {styles.field}>
<TextField
style={styles.input}
label = 'Nome'
tintColor = 'rgba(1, 168, 62, 1)'
baseColor = 'rgba(1, 168, 62, 1)'
textColor = 'rgba(1, 168, 62, 1)'
lineWidth = {2}
fontSize = {17}
value = {values.user}
onChangeText = {handleChange('user')}
onSubmitEditing={() => this.password.focus()}
error = {errors.user}
/>
<TextField
style={styles.input}
ref={(input) => { this.email= input; }}
label = 'E-mail'
tintColor = 'rgba(1, 168, 62, 1)'
baseColor = 'rgba(1, 168, 62, 1)'
textColor = 'rgba(1, 168, 62, 1)'
lineWidth = {2}
fontSize = {17}
autoCapitalize ='none'
onSubmitEditing={() => this.onSubmitEmail()}
onChangeText = {handleChange('email')}
error= {errors.email}
/>
<TextField
style={styles.input}
ref={(input) => { this.password= input; }}
label = 'Senha'
tintColor = 'rgba(1, 168, 62, 1)'
baseColor = 'rgba(1, 168, 62, 1)'
textColor = 'rgba(1, 168, 62, 1)'
secureTextEntry = {this.state.secureTextEntry}
lineWidth = {2}
autoCapitalize = 'none'
fontSize = {17}
error = {errors.password}
onSubmitEditing={() => { this.phone.focus(); }}
onChangeText = {handleChange('password')}
renderRightAccessory = {this.renderPasswordAccessory}
/>
<TextField
style={styles.input}
ref={(input) => { this.phone = input; }}
label = 'Telefone'
keyboardType = 'phone-pad'
tintColor = 'rgba(1, 168, 62, 1)'
baseColor = 'rgba(1, 168, 62, 1)'
textColor = 'rgba(1, 168, 62, 1)'
lineWidth = {2}
fontSize = {17}
error = {errors.contact}
onSubmitEditing={() => { this.cpf.focus(); }}
onChangeText = {handleChange('contact')}
formatText={value => this._addMaskContactBr(value)}
/>
<TextField
style={styles.input}
ref={(input) => { this.cpf = input; }}
label = 'CPF'
keyboardType = 'phone-pad'
tintColor = 'rgba(1, 168, 62, 1)'
baseColor = 'rgba(1, 168, 62, 1)'
textColor = 'rgba(1, 168, 62, 1)'
lineWidth = {2}
maxLength= {11}
fontSize = {17}
error = {errors.cpf}
onChangeText = {handleChange('cpf')}
onSubmitEditing={() => {this.showPicker()}}
/>
<TextField
style={styles.input}
label = 'Aniversário'
keyboardType = 'phone-pad'
baseColor = 'rgba(1, 168, 62, 1)'
textColor = 'rgba(1, 168, 62, 1)'
lineWidth = {2}
fontSize = {17}
placeholder = {this.state.birhtDate}
onChangeText = {handleChange('birth')}
onFocus = {()=>this.showPicker()}
error = {this.state.errorBirth}
/>
<DateTimePicker
isVisible={this.state.isVisible}
onConfirm={this.handlePicker}
onCancel={this.hidePicker}
mode = {'date'}
/>
<View style= {styles.divider}/>
<Button
type = 'outline'
title = 'Cadastrar'
titleStyle = {styles.btnLabel}
buttonStyle = {styles.btnLogin}
onPress = {handleSubmit}
/>
</View>
)}
</Formik>
{/*<TextField
style={styles.input}
label = 'Nome'
tintColor = 'rgba(1, 168, 62, 1)'
baseColor = 'rgba(1, 168, 62, 1)'
textColor = 'rgba(1, 168, 62, 1)'
lineWidth = {2}
fontSize = {17}
onSubmitEditing={() => this.onSubmitName()}
onChangeText = {user =>{(this.setState({user}))}}
error = {this.state.errorUser}
/>
<TextField
style={styles.input}
ref={(input) => { this.email= input; }}
label = 'E-mail'
tintColor = 'rgba(1, 168, 62, 1)'
baseColor = 'rgba(1, 168, 62, 1)'
textColor = 'rgba(1, 168, 62, 1)'
lineWidth = {2}
fontSize = {17}
autoCapitalize ='none'
onSubmitEditing={() => this.onSubmitEmail()}
onChangeText = {email =>{(this.setState({email}))}}
error= {this.state.errorEmail}
/>
<TextField
style={styles.input}
ref={(input) => { this.password= input; }}
label = 'Senha'
tintColor = 'rgba(1, 168, 62, 1)'
baseColor = 'rgba(1, 168, 62, 1)'
textColor = 'rgba(1, 168, 62, 1)'
secureTextEntry = {this.state.secureTextEntry}
lineWidth = {2}
autoCapitalize = 'none'
fontSize = {17}
onSubmitEditing={() => { this.phone.focus(); }}
onChangeText = {password =>{(this.setState({password}))}}
renderRightAccessory = {this.renderPasswordAccessory}
/>
<TextField
style={styles.input}
ref={(input) => { this.phone = input; }}
label = 'Telefone'
keyboardType = 'phone-pad'
tintColor = 'rgba(1, 168, 62, 1)'
baseColor = 'rgba(1, 168, 62, 1)'
textColor = 'rgba(1, 168, 62, 1)'
lineWidth = {2}
fontSize = {17}
onSubmitEditing={() => { this.cpf.focus(); }}
onChangeText = {contact =>{(this.setState({contact}))}}
formatText={value => this._addMaskContactBr(value)}
/>
<TextField
style={styles.input}
ref={(input) => { this.cpf = input; }}
label = 'CPF'
keyboardType = 'phone-pad'
tintColor = 'rgba(1, 168, 62, 1)'
baseColor = 'rgba(1, 168, 62, 1)'
textColor = 'rgba(1, 168, 62, 1)'
lineWidth = {2}
maxLength= {11}
fontSize = {17}
onChangeText = {trueCpf =>{this.setState({trueCpf})}}
onSubmitEditing={() => {this.showPicker()}}
//formatText = {value =>this.cpfMask(value)}
/>
<TextField
style={styles.input}
label = 'Aniversário'
keyboardType = 'phone-pad'
tintColor = 'rgba(1, 168, 62, 1)'
baseColor = 'rgba(1, 168, 62, 1)'
textColor = 'rgba(1, 168, 62, 1)'
lineWidth = {2}
fontSize = {17}
placeholder = {this.state.birhtDate}
onFocus = {()=>this.showPicker()}
/>
<DateTimePicker
isVisible={this.state.isVisible}
onConfirm={this.handlePicker}
onCancel={this.hidePicker}
mode = {'date'}
/> */}
</ScrollView>
</>
);
}
};
const styles = StyleSheet.create({
divider:{
height: hp('5%')
},
text:{
alignSelf:'center',
fontSize: wp('9%'),
fontFamily: 'roboto',
color: 'white',
},
field:{
color:'white',
width: '80%',
alignSelf: 'center',
},
btnLogin:{
marginTop: hp('4%'),
borderRadius: wp('2%'),
alignSelf: 'center',
width: '40%',
backgroundColor: '#01A83E',
},
btnLabel:{
color:'white',
fontSize: wp('5%'),
},
});
|
def max_profit(stock_prices):
max_profit = 0
for i in range(len(stock_prices) - 1):
for j in range(i + 1, len(stock_prices)):
if stock_prices[j] - stock_prices[i] > max_profit:
max_profit = stock_prices[j] - stock_prices[i]
return max_profit
if __name__ == "__main__":
stock_prices = [7, 1, 5, 3, 6, 4]
result = max_profit(stock_prices)
print(result)
|
#!/bin/sh
# Install go
curl -o go.tar https://dl.google.com/go/go1.10.3.linux-amd64.tar.gz
tar -xvf go.tar 1>/dev/null
# Install git
sudo apt-get update
#sudo apt-get upgrade
sudo apt-get -y install git
mkdir gopath 2>/dev/null
# setup our environment
. ~/setenv.sh
echo "Installing NATS components."
go get github.com/nats-io/gnatsd
go get github.com/nats-io/go-nats
go get github.com/nats-io/latency-tests
|
<gh_stars>0
#include <iostream>
#define ll long long
using namespace std;
int csb(ll n)
{
int res = 0;
while (n > 0)
{
ll rsb = n & -n;
n -= rsb;
res++;
}
return res;
}
ll ncr(ll n, ll r)
{
if (n < r)
{
return 0;
}
ll res = 1;
for (ll i = 0; i < r; i++)
{
res = res * (n - i);
res = res / (i + 1);
}
return res;
}
ll solution(ll n, int k, int i)
{
if (i == 0)
{
return 0;
}
ll mask = 1L << i;
ll res = 0;
if ((n & mask) == 0)
{
// last bit will be zero (rightmost bit)
res = solution(n, k, i - 1);
// cout << res << endl ;
}
else
{
ll res1 = solution(n, k - 1, i - 1);
ll res2 = ncr(i, k);
// cout << res1 << " " << res2 << endl;
res = res1 + res2;
}
return res;
}
int main()
{
ll n;
cin >> n;
int k = csb(n);
cout << solution(n, k, 63) << endl;
return 0;
}
|
def to_binary(n):
return bin(n).replace("0b", "")
|
#! /bin/bash
PRGNAME="perl-test-fatal"
ARCH_NAME="Test-Fatal"
### Test::Fatal (simple helpers for testing code)
# Test::Fatal Perl модуль
# Required: perl-try-tiny
# Recommended: no
# Optional: no
ROOT="/root/src/lfs"
source "${ROOT}/check_environment.sh" || exit 1
source "${ROOT}/unpack_source_archive.sh" "${ARCH_NAME}" || exit 1
TMP_DIR="${BUILD_DIR}/package-${PRGNAME}-${VERSION}"
mkdir -pv "${TMP_DIR}"
perl Makefile.PL || exit 1
make || exit 1
# make test
make install DESTDIR="${TMP_DIR}"
# исправим пути (убираем из путей временную директорию установки пакета)
PERL_MAJ_VER="$(perl -v | /bin/grep version | cut -d \( -f 2 | cut -d v -f 2 | \
cut -d . -f 1,2)"
PERL_MAIN_VER="$(echo "${PERL_MAJ_VER}" | cut -d . -f 1)"
PERL_LIB_PATH="/usr/lib/perl${PERL_MAIN_VER}/${PERL_MAJ_VER}"
sed -e "s|${TMP_DIR}||" -i \
"${TMP_DIR}${PERL_LIB_PATH}/site_perl/auto/Test/Fatal/.packlist"
source "${ROOT}/stripping.sh" || exit 1
source "${ROOT}/update-info-db.sh" || exit 1
/bin/cp -vpR "${TMP_DIR}"/* /
cat << EOF > "/var/log/packages/${PRGNAME}-${VERSION}"
# Package: ${PRGNAME} (simple helpers for testing code)
#
# The Test::Fatal module provides simple helpers for testing code which throws
# exceptions
#
# Home page: https://metacpan.org/pod/Test::Fatal
# Download: https://cpan.metacpan.org/authors/id/R/RJ/RJBS/${ARCH_NAME}-${VERSION}.tar.gz
#
EOF
source "${ROOT}/write_to_var_log_packages.sh" \
"${TMP_DIR}" "${PRGNAME}-${VERSION}"
|
<reponame>BIGCATDOG/communityBackend<filename>src/vess-service/handler.go
package main
import (
"context"
pb "github.com/vess-service/proto/vess"
)
// 定义货船服务
type service struct {
repo Repository
}
// 实现服务端
func (s *service) FindAvailable(ctx context.Context, spec *pb.Specification, resp *pb.Response) error {
// 调用内部方法查找
v, err := s.repo.FindAvailable(spec)
if err != nil {
return err
}
resp.Vessel = v
return nil
}
func (s *service) Create(ctx context.Context,vessel *pb.Vessel,resp *pb.Response)error {
return s.repo.CreatVessel(vessel)
}
|
# This file is based on part of the Dython package (https://github.com/shakedzy/dython)
# Because I only needed Cramér's V, adding a whole dependency
# did not make sense.
import warnings
from typing import Union, List
import numpy as np
import pandas as pd
import scipy.stats as ss
def cramers_v(
x: Union[pd.Series, np.ndarray, List],
y: Union[pd.Series, np.ndarray, List],
bias_correction: bool = True,
nan_strategy: str = "replace",
nan_replace_value: Union[int, float] = 0,
):
"""
Calculates Cramer's V statistic for categorical-categorical association.
This is a symmetric coefficient: V(x,y) = V(y,x)
Original function taken from: https://stackoverflow.com/a/46498792/5863503
Wikipedia: https://en.wikipedia.org/wiki/Cram%C3%A9r%27s_V
Parameters
----------
x :
A sequence of categorical measurements
y :
A sequence of categorical measurements
bias_correction :
Use bias correction from Bergsma and Wicher,
Journal of the Korean Statistical Society 42 (2013): 323-328.
nan_strategy :
How to handle missing values: can be either 'drop' to remove samples
with missing values, or 'replace' to replace all missing values with
the nan_replace_value. Missing values are None and np.nan.
nan_replace_value :
The value used to replace missing values with. Only applicable when
nan_strategy is set to 'replace'.
Returns
-------
float in the range of [0,1]
"""
if nan_strategy == "replace":
x, y = replace_nan_with_value(x, y, nan_replace_value)
elif nan_strategy == "drop":
x, y = remove_incomplete_samples(x, y)
confusion_matrix = pd.crosstab(x, y)
chi2 = ss.chi2_contingency(confusion_matrix)[0]
n = confusion_matrix.sum().sum()
phi2 = chi2 / n
r, k = confusion_matrix.shape
if bias_correction:
phi2corr = max(0, phi2 - ((k - 1) * (r - 1)) / (n - 1))
rcorr = r - ((r - 1) ** 2) / (n - 1)
kcorr = k - ((k - 1) ** 2) / (n - 1)
if min((kcorr - 1), (rcorr - 1)) == 0:
warnings.warn(
"Unable to calculate Cramer's V using bias correction. Consider using bias_correction=False",
RuntimeWarning,
)
return np.nan
else:
return np.sqrt(phi2corr / min((kcorr - 1), (rcorr - 1)))
else:
return np.sqrt(phi2 / min(k - 1, r - 1))
def replace_nan_with_value(x, y, value):
x = np.array([v if v == v and v is not None else value for v in x]) # NaN != NaN
y = np.array([v if v == v and v is not None else value for v in y])
return x, y
def remove_incomplete_samples(x, y):
x = [v if v is not None else np.nan for v in x]
y = [v if v is not None else np.nan for v in y]
arr = np.array([x, y]).transpose()
arr = arr[~np.isnan(arr).any(axis=1)].transpose()
if isinstance(x, list):
return arr[0].tolist(), arr[1].tolist()
else:
return arr[0], arr[1]
|
#!/bin/sh -e
CROSS_BASE=/opt/freescale/usr/local/gcc-4.4.4-glibc-2.11.1-multilib-1.0/arm-fsl-linux-gnueabi
CROSS_INCLUDE=${CROSS_BASE}/arm-fsl-linux-gnueabi/multi-libs/usr/include/
#/opt/freescale/usr/local/gcc-4.4.4-glibc-2.11.1-multilib-1.0/arm-fsl-linux-gnueabi
CROSS_CC=${CROSS_BASE}/bin/arm-fsl-linux-gnueabi-gcc
#@echo Using GCC toolchain for Freescale i.MX28: $(CROSS_CC)
#CC= $(CROSS_CC) -I$(CROSS_INCLUDE)
#LD_FLAGS= -L${CROSS_BASE}/multi-libs/armv5te/usr/lib
PREFIX_BIN=$CROSS_BASE/bin/arm-fsl-linux-gnueabi
#export CSTOOLS=/opt/code-sourcery/arm-2009q1
export CSTOOLS=$CROSS_BASE/bin
ROOTFS_USR_LIB=/opt2/freescale/ltib/ltib/rootfs/usr/lib
ROOTFS_USR_INC=/opt2/freescale/ltib/ltib/rootfs/usr/include
# cross library directory, should include stdc++:
export CSTOOLS_LIB=/opt/ltib/rootfs/lib
export CSTOOLS_USR_LIB=/opt/ltib/rootfs/usr/lib
# libc & system headers:
export CSTOOLS_INC=${CROSS_BASE}/arm-fsl-linux-gnueabi/multi-libs/usr/include/
#export CSTOOLS_LIB=${CROSS_BASE}/multi-libs/armv5te/usr/lib
export TARGET_ARCH="-march=armv5te"
#"-march=armv7-a" # must be at least armv5te
#export TARGET_TUNE="-mtune=cortex-a8 -mfpu=neon -mfloat-abi=softfp -mthumb-interwork -mno-thumb" # optional
export TARGET_TUNE="-mtune=arm926ej-s -mfloat-abi=soft -mno-thumb-interwork" # optional
export TOOL_PREFIX=$PREFIX_BIN
#export CXX=$TOOL_PREFIX-g++
#export AR=$TOOL_PREFIX-ar
#export RANLIB=$TOOL_PREFIX-ranlib
#export CC=$TOOL_PREFIX-gcc
#export LD=$TOOL_PREFIX-ld
export CCFLAGS="-march=armv5te -mtune=arm926ej-s -mno-thumb-interwork -lstdc++"
# -march=armv5te -mtune=arm926ej-s -mfloat-abi=softfp
export ARM_TARGET_LIB=$CTOOLS_LIB
export GYP_DEFINES="armv7=0" # if your target does not do ARM v7 instructions then =0
export CPP="${PREFIX_BIN}-gcc -E"
export STRIP="${PREFIX_BIN}-strip"
export OBJCOPY="${PREFIX_BIN}-objcopy"
export AR="${PREFIX_BIN}-ar"
export F77="${PREFIX_BIN}-g77 ${TARGET_ARCH} ${TARGET_TUNE}"
unset LIBC
export RANLIB="${PREFIX_BIN}-ranlib"
#export LD="${PREFIX_BIN}-ld" # for some reason this newer ld for arm does not have -rpath option (or at least they aren't taking) so go to g++
export LD="${PREFIX_BIN}-g++"
export LDFLAGS="-L${CSTOOLS_USR_LIB} -L${CSTOOLS_LIB} -Wl,-rpath-link,${CSTOOLS_LIB} -Wl,-O1 -Wl,--hash-style=gnu"
export MAKE="make"
export CXXFLAGS="-isystem${CSTOOLS_INC} -fexpensive-optimizations -frename-registers -fomit-frame-pointer -O0 -ggdb3 -fpermissive -fvisibility-inlines-hidden"
export LANG="en_US.UTF-8"
export HOME="/home/ed"
export CCLD="${PREFIX_BIN}-gcc ${TARGET_ARCH} ${TARGET_TUNE}"
export PATH="${CSTOOLS}/bin:/opt/code-sourcery/arm-2009q1/bin/:${HOME}/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games"
export CFLAGS="-isystem${CSTOOLS_INC} -fexpensive-optimizations -frename-registers -fomit-frame-pointer -O0 -ggdb3"
export OBJDUMP="arm-none-linux-gnueabi-objdump"
export CPPFLAGS="-isystem${CSTOOLS_INC}"
export CC="${PREFIX_BIN}-gcc ${TARGET_ARCH} ${TARGET_TUNE}"
#export TITOOLSDIR="/mnt/data/overo-oe/ti"
export TERM="screen"
export SHELL="/bin/bash"
export CXX="${PREFIX_BIN}-g++ ${TARGET_ARCH} ${TARGET_TUNE}"
export NM="${PREFIX_BIN}-nm"
export AS="${PREFIX_BIN}-as"
#export LINK.host="ld -m elf_i386"
# Configure node.js for cross-compile
./configure --debug --without-snapshot --dest-cpu=arm --gdb --shared-zlib --shared-zlib-libpath=${ROOTFS_USR_LIB} --shared-zlib-includes=${ROOTFS_USR_INC} --without-ssl --no-ssl2 # --shared-v8
bash --norc
# or run make / make -j 8 / etc...
|
<reponame>vharsh/cattle2
package io.cattle.platform.api.auth;
import java.util.Set;
public interface Policy {
String AGENT_ID = "agentId";
String LIST_ALL_ACCOUNTS = "list.all.accounts";
String AUTHORIZED_FOR_ALL_ACCOUNTS = "all.accounts";
String OVERRIDE_ACCOUNT_ID = "override.account.id";
String RESOURCE_ACCOUNT_ID = "resource.account.id";
String LIST_ALL_SETTINGS = "list.all.settings";
String PLAIN_ID = "plain.id";
String PLAIN_ID_OPTION = "plain.id.option";
String ROLE_OPTION = "role.option";
String ASSIGNED_ROLE = "assigned.role";
String CLUSTER_OWNER = "cluster.owner";
long NO_ACCOUNT = -1L;
boolean isOption(String optionName);
String getOption(String optionName);
void setOption(String optionName, String value);
Set<Identity> getIdentities();
long getAccountId();
Long getClusterId();
long getAuthenticatedAsAccountId();
String getUserName();
<T> T checkAuthorized(T obj);
<T> void grantObjectAccess(T obj);
Set<String> getRoles();
}
|
# One-time setup for the cluster and persistent volume
# System setup kubectl expose deployment hello-world --type=NodePort --name=example-service
gcloud config set compute/zone us-west1-c
gcloud config set project bike-rental-system
gcloud container clusters create brs-cluster --num-nodes 1
kubectl create -f brs-persistant-volume.yaml
|
#!/bin/sh
LIB=compiler_bg
# Builds the NPM package
wasm-pack build --release
# Run wasm-opt on binary for platforms where wasm-pack didn't do it for us automatically
# (currently M1 macs).
# We can safely run it again on a .wasm file that's already been optimized though.
which wasm-opt > /dev/null
if [ $? -eq 0 ]; then
wasm-opt -Os -o pkg/${LIB}.new.wasm pkg/${LIB}.wasm
mv pkg/${LIB}.new.wasm pkg/${LIB}.wasm
fi
# This is a hack. wasm-pack hard-codes `sideEffects` false into its generated
# package.json. Webpack 4+'s treeshaking breaks though, because it erronously
# treeshakes out files we need in this module.
cat ./pkg/package.json | jq '. + {"sideEffects": true}' > ./pkg/package.new.json
mv ./pkg/package.new.json ./pkg/package.json
|
import { Heading } from 'components/Heading'
import { Logo } from 'components/Logo'
import Link from 'next/link'
import * as S from './styles'
export const Footer = () => (
<S.Wrapper>
<Logo color="blue" />
<S.Content>
<S.Column>
<Heading color="black" size="small" lineBottom lineColor="secondary">
Contact us
</Heading>
<a href="mailto:<EMAIL>"><EMAIL></a>
<a href="tel:+550000000000">+55 00 00000000</a>
</S.Column>
<S.Column>
<Heading color="black" size="small" lineBottom lineColor="secondary">
Follow us
</Heading>
<nav aria-labelledby="social media">
<a
href="https://www.instagram.com/won-games"
target="_blank"
rel="noopenner, noreferrer"
>
Instagram
</a>
<a
href="https://www.twitter.com/won-games"
target="_blank"
rel="noopenner, noreferrer"
>
Twitter
</a>
<a
href="https://www.youtube.com/won-games"
target="_blank"
rel="noopenner, noreferrer"
>
Youtube
</a>
<a
href="https://www.facebook.com/won-games"
target="_blank"
rel="noopenner, noreferrer"
>
Facebook
</a>
</nav>
</S.Column>
<S.Column>
<Heading color="black" lineColor="secondary" lineBottom size="small">
Links
</Heading>
<nav aria-labelledby="footer resources">
<Link href="/games">
<a>Store</a>
</Link>
<Link href="/explore">
<a>Explore</a>
</Link>
<Link href="/search">
<a>Search</a>
</Link>
<Link href="/faq">
<a>FAQ</a>
</Link>
</nav>
</S.Column>
<S.Column aria-labelledby="footer-contact">
<Heading color="black" lineColor="secondary" lineBottom size="small">
Location
</Heading>
<span>Rua Lorem ipsum dolor</span>
<span>123 - 00000000</span>
<span>Lorem ipsum, Brasil</span>
</S.Column>
</S.Content>
<S.Copyright>Won Games 2021 © All rights reserved</S.Copyright>
</S.Wrapper>
)
|
#!/bin/bash
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
if [ "$#" -ne 2 ]; then
echo "Usage: $0 <paragraph-source-directory> <release_tarball_name>"
exit 1
fi
set -e
if [[ ! -f $2 ]]; then
echo "Build tarball file does not exist."
exit 1
fi
realpath() {
[[ $1 = /* ]] && echo "$1" || echo "$PWD/${1#./}"
}
SOURCE_DIR=$1
RELEASE_DIR=$(dirname $(python ${DIR}/realpath.py $2))
RELEASE_FILE=$(basename $2)
if [[ -z "${RELEASE_DIR// }" ]]; then
RELEASE_DIR=$(pwd)
fi
docker pull ilmncgrpmi/paragraph-testing-dev:master
docker run --rm \
-t \
-v ${DIR}:/opt/testing-helpers \
-v ${SOURCE_DIR}:/opt/paragraph-source \
-v ${RELEASE_DIR}:/release \
-v $(pwd):/valgrind-test \
ilmncgrpmi/paragraph-testing-dev:master \
/bin/bash /opt/testing-helpers/test-helpers/valgrind-test.sh /release/${RELEASE_FILE}
|
/**
* Created by user on 30/06/2017.
*/
//Function taken from crypto.js
export function hexToBytes(hex) {
if (hex === undefined) {
return false;
}
let bytes;
let c;
for (bytes = [], c = 0; c < hex.length; c += 2)
bytes.push(parseInt(hex.substr(c, 2), 16));
return bytes;
}
//Function taken from crypto.js
export function bytesToHex(bytes) {
let hex, i;
for (hex = [], i = 0; i < bytes.length; i++) {
hex.push((bytes[i] >>> 4).toString(16));
hex.push((bytes[i] & 0xF).toString(16));
}
return hex.join("");
}
|
# frozen_string_literal: true
require_relative './reference_note'
require_relative './utils'
# reference note that reads from
# an already existing generated reference note
class OpenedReferenceNote < ReferenceNote
attr_reader :contents
def initialize(filename, dir_path)
@dir_path = dir_path
referencing_note_lines = aggregate_filepaths("#{dir_path}/#{filename}")
filename_without_extention = File.basename(filename, '.*')
super(referencing_note_lines, dir_path, filename_without_extention)
end
private
def aggregate_filepaths(filepath)
read_ref_file(filepath)
parse_contents_for_individual_files
end
def read_ref_file(filepath)
@contents = OpenedFile.new(filepath, dir_path).contents
end
def parse_contents_for_individual_files
ref_note_filepaths = []
@contents.each do |line|
filematch = /<!-- %% (.*) (.*) -->/.match(line)
next unless filematch
absolute_path = filematch[2]
ref_note_filepaths << "#{absolute_path}:"
end
ref_note_filepaths
end
end
|
export CC_NAME="grade-book";
export CC_LANGUAGE="typescript";
export CC_CHANNEL="grade-book-channel";
export CC_PATH="$PWD/grade-book-chaincode";
cd ./test-network || exit
sudo rm -rf channel-artifacts/
sudo rm -rf organizations/fabric-ca/ordererOrg
sudo rm -rf organizations/fabric-ca/ordererOrg
sudo rm -rf organizations/fabric-ca/org1
sudo rm -rf organizations/fabric-ca/org2
sudo rm -rf organizations/ordererOrganizations
sudo rm -rf organizations/peerOrganizations
sudo rm -rf system-genesis-block
./network.sh down
./network.sh up -ca
./network.sh createChannel -c $CC_CHANNEL
./network.sh deployCC -ccn $CC_NAME -ccl $CC_LANGUAGE -ccp "$CC_PATH" -c $CC_CHANNEL -cci InitLedger -cccg "$CC_PATH"/collections_config.json
cp organizations/peerOrganizations/org1.example.com/connection-org1.json ../grade-book-application/assets/connection-config.json
|
#!/usr/bin/env bash
#================================================
# install ide vscode on debian family
#================================================
echo 'install ide vscode start'
# install aria2
if [ -z $(apt list aria2|awk '{print $4}') ]
then
sudo apt-get update
sudo apt-get install -y aria2
sudo apt-get purge
sudo apt-get autoremove -y
sudo apt-get autoclean
fi
# install libgconf2-4
if [ -z $(apt list libgconf2-4|awk '{print $4}') ]
then
sudo apt-get update
sudo apt-get install -y libgconf2-4
sudo apt-get purge
sudo apt-get autoremove -y
sudo apt-get autoclean
fi
# environment variables
devtools_dir=$HOME/devtools
download_dir=$HOME/Downloads
ide_dir=$devtools_dir/ide/
ide_vscode_url='https://vscode.cdn.azure.cn/stable/7f3ce96ff4729c91352ae6def877e59c561f4850/code-stable-1539735949.tar.gz'
ide_vscode_filename=$(echo $ide_vscode_url|awk -F/ '{print $6}')
# mkdir
mkdir -p $download_dir
mkdir -p $devtools_dir
mkdir -p $ide_dir
# download and tar
rm -rf $download_dir/$ide_vscode_filename
aria2c -s 10 -x 10 -d $download_dir $ide_vscode_url
rm -rf $ide_dir/*vscode*
tar -xf $download_dir/$ide_vscode_filename -C $ide_dir
ide_vscode_dir=$(find $ide_dir -maxdepth 1 -type d -iname 'vscode*')
# configure alias
echo >> $HOME/.bash_aliases
echo "alias vscode='nohup $ide_vscode_dir/code 1>/dev/null 2>&1 &'" >> $HOME/.bash_aliases
source $HOME/.bash_aliases
# add vscode desktop
echo "[Desktop Entry]
Version=1.0
Type=Application
Name=Visual Studio Code
Icon=$ide_vscode_dir/resources/app/resources/linux/code.png
Exec=$ide_vscode_dir/code
Comment=IDE for Text Editor
Categories=Development;IDE;
Terminal=false" > $HOME/Desktop/visual-studio-code.desktop
chmod 755 $HOME/Desktop/visual-studio-code.desktop
echo 'install ide vscode done'
|
{{- define "shoot-cloud-config.execution-script" -}}
#!/bin/bash -eu
DIR_KUBELET="/var/lib/kubelet"
DIR_CLOUDCONFIG_DOWNLOADER="/var/lib/cloud-config-downloader"
DIR_CLOUDCONFIG="$DIR_CLOUDCONFIG_DOWNLOADER/downloads"
PATH_CLOUDCONFIG_DOWNLOADER_SERVER="$DIR_CLOUDCONFIG_DOWNLOADER/credentials/server"
PATH_CLOUDCONFIG_DOWNLOADER_CA_CERT="$DIR_CLOUDCONFIG_DOWNLOADER/credentials/ca.crt"
PATH_CLOUDCONFIG="{{ .configFilePath }}"
PATH_CLOUDCONFIG_OLD="${PATH_CLOUDCONFIG}.old"
PATH_CHECKSUM="$DIR_CLOUDCONFIG_DOWNLOADER/downloaded_checksum"
mkdir -p "$DIR_CLOUDCONFIG" "$DIR_KUBELET"
function docker-preload() {
name="$1"
image="$2"
echo "Checking whether to preload $name from $image"
if [ -z $(docker images -q "$image") ]; then
echo "Preloading $name from $image"
docker pull "$image"
else
echo "No need to preload $name from $image"
fi
}
{{- if .worker.kubeletDataVolume }}
function format-data-device() {
LABEL=KUBEDEV
if ! blkid --label $LABEL >/dev/null; then
DEVICES=$(lsblk -dbsnP -o NAME,PARTTYPE,FSTYPE,SIZE)
MATCHING_DEVICES=$(echo "$DEVICES" | grep 'PARTTYPE="".*FSTYPE="".*SIZE="{{.worker.kubeletDataVolume.size}}"')
echo "Matching kubelet data device by size : {{.worker.kubeletDataVolume.size}}"
TARGET_DEVICE_NAME=$(echo "$MATCHING_DEVICES" | head -n1 | cut -f2 -d\")
echo "detected kubelet data device $TARGET_DEVICE_NAME"
mkfs.ext4 -L $LABEL -O quota -E lazy_itable_init=0,lazy_journal_init=0,quotatype=usrquota:grpquota:prjquota /dev/$TARGET_DEVICE_NAME
echo "formatted and labeled data device $TARGET_DEVICE_NAME"
mkdir /tmp/varlibcp
mount LABEL=$LABEL /tmp/varlibcp
echo "mounted temp copy dir on data device $TARGET_DEVICE_NAME"
cp -a /var/lib/* /tmp/varlibcp/
umount /tmp/varlibcp
echo "copied /var/lib to data device $TARGET_DEVICE_NAME"
mount LABEL=$LABEL /var/lib -o defaults,prjquota,errors=remount-ro
echo "mounted /var/lib on data device $TARGET_DEVICE_NAME"
fi
}
format-data-device
{{- end}}
{{ range $name, $image := (required ".images is required" .images) -}}
docker-preload "{{ $name }}" "{{ $image }}"
{{ end }}
cat << 'EOF' | base64 -d > "$PATH_CLOUDCONFIG"
{{ .worker.cloudConfig | b64enc }}
EOF
if [ ! -f "$PATH_CLOUDCONFIG_OLD" ]; then
touch "$PATH_CLOUDCONFIG_OLD"
fi
if [[ ! -f "$DIR_KUBELET/kubeconfig-real" ]] || [[ ! -f "$DIR_KUBELET/pki/kubelet-client-current.pem" ]]; then
cat <<EOF > "$DIR_KUBELET/kubeconfig-bootstrap"
---
apiVersion: v1
kind: Config
current-context: kubelet-bootstrap@default
clusters:
- cluster:
certificate-authority-data: $(cat "$PATH_CLOUDCONFIG_DOWNLOADER_CA_CERT" | base64 | tr -d '\n')
server: $(cat "$PATH_CLOUDCONFIG_DOWNLOADER_SERVER")
name: default
contexts:
- context:
cluster: default
user: kubelet-bootstrap
name: kubelet-bootstrap@default
users:
- name: kubelet-bootstrap
user:
as-user-extra: {}
token: {{ required ".bootstrapToken is required" .bootstrapToken }}
EOF
else
rm -f "$DIR_KUBELET/kubeconfig-bootstrap"
fi
if ! diff "$PATH_CLOUDCONFIG" "$PATH_CLOUDCONFIG_OLD" >/dev/null; then
echo "Seen newer cloud config version"
if {{ .worker.command }}; then
echo "Successfully applied new cloud config version"
systemctl daemon-reload
{{- range $name := (required ".worker.units is required" .worker.units) }}
{{- if and (ne $name "docker.service") (ne $name "var-lib.mount") }}
systemctl enable {{ $name }} && systemctl restart --no-block {{ $name }}
{{- end }}
{{- end }}
echo "Successfully restarted all units referenced in the cloud config."
cp "$PATH_CLOUDCONFIG" "$PATH_CLOUDCONFIG_OLD"
fi
fi
rm "$PATH_CLOUDCONFIG"
ANNOTATION_RESTART_SYSTEMD_SERVICES="worker.gardener.cloud/restart-systemd-services"
# Try to find Node object for this machine
if [[ -f "$DIR_KUBELET/kubeconfig-real" ]]; then
{{`NODE="$(/opt/bin/kubectl --kubeconfig="$DIR_KUBELET/kubeconfig-real" get node -l "kubernetes.io/hostname=$(hostname)" -o go-template="{{ if .items }}{{ (index .items 0).metadata.name }}{{ if (index (index .items 0).metadata.annotations \"$ANNOTATION_RESTART_SYSTEMD_SERVICES\") }} {{ index (index .items 0).metadata.annotations \"$ANNOTATION_RESTART_SYSTEMD_SERVICES\" }}{{ end }}{{ end }}")"`}}
if [[ ! -z "$NODE" ]]; then
NODENAME="$(echo "$NODE" | awk '{print $1}')"
SYSTEMD_SERVICES_TO_RESTART="$(echo "$NODE" | awk '{print $2}')"
fi
# Update checksum/cloud-config-data annotation on Node object if possible
if [[ ! -z "$NODENAME" ]] && [[ -f "$PATH_CHECKSUM" ]]; then
/opt/bin/kubectl --kubeconfig="$DIR_KUBELET/kubeconfig-real" annotate node "$NODENAME" "checksum/cloud-config-data=$(cat "$PATH_CHECKSUM")" --overwrite
fi
# Restart systemd services if requested
for service in $(echo "$SYSTEMD_SERVICES_TO_RESTART" | sed "s/,/ /g"); do
echo "Restarting systemd service $service due to $ANNOTATION_RESTART_SYSTEMD_SERVICES annotation"
systemctl restart "$service" || true
done
/opt/bin/kubectl --kubeconfig="$DIR_KUBELET/kubeconfig-real" annotate node "$NODENAME" "${ANNOTATION_RESTART_SYSTEMD_SERVICES}-"
fi
{{- end}}
|
package sql
import (
"fmt"
"strings"
)
type DependecyNode struct {
Name string
Edges []*DependecyNode
}
func (d *DependecyNode) String() string {
depNames := []string{}
for _, e := range d.Edges {
depNames = append(depNames, e.Name)
}
return fmt.Sprintf("%v -> (%v)", d.Name, strings.Join(depNames, ","))
}
func (d *DependecyNode) AddEdge(node *DependecyNode) {
d.Edges = append(d.Edges, node)
}
type DependecyGraph []DependecyNode
func (g *DependecyGraph) Add(node *DependecyNode) *DependecyGraph {
*g = append(*g, *node)
return g
}
func (g *DependecyGraph) Remove(node *DependecyNode) *DependecyGraph {
graph := DependecyGraph{}
for _, n := range *g {
if n.String() == node.String() {
continue
}
graph = append(graph, n)
}
return &graph
}
func (g *DependecyGraph) Has(node *DependecyNode) bool {
for _, n := range *g {
if n.String() == node.String() {
return true
}
}
return false
}
func (g *DependecyGraph) resolveNode(node *DependecyNode, resolved, unresolved *DependecyGraph) (bool, error) {
unresolved = unresolved.Add(node)
for _, edge := range node.Edges {
if !resolved.Has(edge) {
if unresolved.Has(edge) {
return true, fmt.Errorf("circular reference detected: %v -> %s", node.Name, edge.Name)
}
cycle, err := g.resolveNode(edge, resolved, unresolved)
if cycle {
return true, err
}
}
}
// prevent from being added multiple times
if !resolved.Has(node) {
resolved = resolved.Add(node)
}
unresolved = unresolved.Remove(node)
return false, nil
}
func (g *DependecyGraph) Items() []DependecyNode {
return *g
}
func (g *DependecyGraph) TopSort(resolved *DependecyGraph) (bool, error) {
unresolved := &DependecyGraph{}
for i := range *g {
cycle, err := g.resolveNode(&(*g)[i], resolved, unresolved)
if cycle {
return true, err
}
}
return false, nil
}
func (g *DependecyGraph) CreateNode(name string) {
for _, n := range *g {
if n.Name == name {
return
}
}
*g = append(*g, DependecyNode{Name: name})
}
func (g DependecyGraph) Node(name string) *DependecyNode {
for i, n := range g {
if n.Name == name {
return &g[i]
}
}
return nil
}
func (g DependecyGraph) PrintNames() {
for _, node := range g {
fmt.Printf("%v\n", node.Name)
}
}
func (g DependecyGraph) Print() {
for _, node := range g {
fmt.Printf("%v\n", node.String())
}
}
|
#!/bin/bash
echo `git show --format="%h" HEAD | head -1` > build_info.txt
echo `git rev-parse --abbrev-ref HEAD` >> build_info.txt
docker build -t $USER_NAME/post .
|
<gh_stars>0
import Element from "./Element.js"
export default class Social extends Element{
constructor(title,list){
super()
var t = document.createElement("div");
t.innerHTML = title;
t.style.textAlign= "right";
t.style.fontWeight = "bold";
t.style.paddingTop = "5px"
for (let node of list){
if(!node.href || !node.innerHTML) continue;
this._el.appendChild(this.socialIcon(node.innerHTML,node.href))
}
this._el.appendChild(t); //title appended last because we're in float:right
}
socialIcon(name,target){
var d = document.createElement("DIV");
var l = document.createElement("A");
var c = document.createElement("DIV");
d.className = "rs";
l.target = "_blank"
l.href = target;
l.title = name;
c.style.backgroundImage = 'url("/data/sprites/'+name.toLowerCase()+'.png")';
c.id=encodeURIComponent(name);
l.appendChild(c);
d.appendChild(l);
return d
}
}
|
<reponame>InsideZhou/southern-quiet
package me.insidezhou.southernquiet.filesystem;
public class PathAlreadyExistsException extends FileSystemException {
private final static long serialVersionUID = -3641435326452253077L;
public PathAlreadyExistsException(String message) {
super(message);
}
public PathAlreadyExistsException(String message, Throwable cause) {
super(message, cause);
}
}
|
#! /bin/bash
echo -e "Enter a characters = \c"
read char
case $char in
[a-z] )
echo "You entered lower case character.";;
[A-Z] )
echo "You entered upper case character.";;
[0-9] )
echo "You entered digits";;
? )
echo "You entered special character";;
* )
echo "You entered unknown characters";;
esac
|
<gh_stars>0
package com.udacity.jdnd.course3.critter.pet;
import com.udacity.jdnd.course3.critter.common.Creature;
import com.udacity.jdnd.course3.critter.common.IEntity;
import com.udacity.jdnd.course3.critter.user.Customer;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.time.LocalDate;
import java.util.Objects;
@Entity
public class Pet extends Creature implements IEntity {
public static final String TYPE_COL = "type";
public static final String OWNER_COL = "owner";
public static final String BIRTH_DATE_COL = "birthDate";
public static final String NOTES_COL = "notes";
@NotNull
@Enumerated(EnumType.STRING)
private PetType type;
@ManyToOne
@JoinColumn(name ="owner_id")
private Customer owner;
@NotNull
private LocalDate birthDate;
@NotNull
private String notes;
public Pet() {
super();
}
public Pet(long id, String name, PetType type, Customer owner, LocalDate birthDate, String notes) {
super(id, name);
init(type, owner, birthDate, notes);
}
private void init(PetType type, Customer owner, LocalDate birthDate, String notes) {
this.type = type;
this.owner = owner;
this.birthDate = birthDate;
this.notes = notes;
}
public static Pet of() {
return new Pet();
}
public static Pet proxy(long id) {
Pet pet = new Pet();
pet.proxy = true;
pet.setId(id);
return pet;
}
public static Pet of(long id, String name, PetType type, Customer owner, LocalDate birthDate, String notes) {
return new Pet(id, name, type, owner, birthDate, notes);
}
public PetType getType() {
return type;
}
public void setType(PetType type) {
this.type = type;
}
public Customer getOwner() {
return owner;
}
public void setOwner(Customer owner) {
if (!Objects.equals(this.owner, owner)) {
// set new owner
Customer oldOwner = this.owner;
this.owner = owner;
// remove from the old owner
if (oldOwner != null) {
oldOwner.removePet(this);
}
// add to new owner
if (owner != null)
owner.addPet(this);
}
}
public LocalDate getBirthDate() {
return birthDate;
}
public void setBirthDate(LocalDate birthDate) {
this.birthDate = birthDate;
}
public String getNotes() {
return notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
@Override
public String toString() {
return super.toString().replace('}', ',') +
" type=" + type +
", owner=" + owner +
", birthDate=" + birthDate +
", notes='" + notes + '\'' +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Pet)) return false;
if (!super.equals(o)) return false;
Pet pet = (Pet) o;
return getType() == pet.getType() && Objects.equals(getOwner(), pet.getOwner())
&& Objects.equals(getBirthDate(), pet.getBirthDate()) && Objects.equals(getNotes(), pet.getNotes());
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), getType(), getOwner(), getBirthDate(), getNotes());
}
}
|
#!/bin/bash -l
set -eu
# SUBMIT SH
THIS=$( readlink --canonicalize $( dirname $0 ) )
DIRECTORY=$THIS
OUTPUT=$THIS/output.txt
source $THIS/settings.sh
if [[ -f $OUTPUT ]]
then
mv --backup=numbered $OUTPUT $OUTPUT.bak
fi
set -x
qsub -n $WORKERS \
-t $WALLTIME \
-A $PROJECT \
-q $QUEUE \
-o $OUTPUT \
-e $OUTPUT \
--env THIS=$THIS \
--cwd $DIRECTORY \
--jobname $JOBNAME \
$THIS/job.sh
|
import {
ComponentAnnotation,
DirectiveAnnotation,
ComponentArgs,
DirectiveArgs
} from './annotations';
import {ViewAnnotation, ViewArgs} from './view';
import {
SelfAnnotation,
ParentAnnotation,
AncestorAnnotation,
UnboundedAnnotation
} from './visibility';
import {AttributeAnnotation, QueryAnnotation} from './di';
import {makeDecorator, makeParamDecorator, TypeDecorator, Class} from '../../util/decorators';
import {Type} from 'angular2/src/facade/lang';
export interface DirectiveTypeDecorator extends TypeDecorator {}
export interface ComponentTypeDecorator extends TypeDecorator {
View(obj: ViewArgs): ViewTypeDecorator;
}
export interface ViewTypeDecorator extends TypeDecorator { View(obj: ViewArgs): ViewTypeDecorator }
export interface Directive {
(obj: any): DirectiveTypeDecorator;
new (obj: DirectiveAnnotation): DirectiveAnnotation;
}
export interface Component {
(obj: any): ComponentTypeDecorator;
new (obj: ComponentAnnotation): ComponentAnnotation;
}
export interface View {
(obj: ViewArgs): ViewTypeDecorator;
new (obj: ViewArgs): ViewAnnotation;
}
/* from annotations */
export var Component = <Component>makeDecorator(ComponentAnnotation, (fn: any) => fn.View = View);
export var Directive = <Directive>makeDecorator(DirectiveAnnotation);
/* from view */
export var View = <View>makeDecorator(ViewAnnotation, (fn: any) => fn.View = View);
/* from visibility */
export var Self = makeParamDecorator(SelfAnnotation);
export var Parent = makeParamDecorator(ParentAnnotation);
export var Ancestor = makeParamDecorator(AncestorAnnotation);
export var Unbounded = makeParamDecorator(UnboundedAnnotation);
/* from di */
export var Attribute = makeParamDecorator(AttributeAnnotation);
export var Query = makeParamDecorator(QueryAnnotation);
|
<filename>src/test/java/org/apache/sling/scriptingbundle/plugin/capability/CapabilityTest.java<gh_stars>1-10
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~ Licensed to the Apache Software Foundation (ASF) under one
~ or more contributor license agreements. See the NOTICE file
~ distributed with this work for additional information
~ regarding copyright ownership. The ASF licenses this file
~ to you under the Apache License, Version 2.0 (the
~ "License"); you may not use this file except in compliance
~ with the License. You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
package org.apache.sling.scriptingbundle.plugin.capability;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Set;
import org.junit.Assert;
import org.junit.Test;
import org.osgi.framework.Version;
import org.osgi.framework.VersionRange;
public class CapabilityTest {
@Test
public void testGetProvidedCapabilitiesString() {
Set<ProvidedResourceTypeCapability> resourceTypeCaps = new LinkedHashSet<>();
resourceTypeCaps.add(ProvidedResourceTypeCapability.builder()
.withResourceTypes("my/type", "/libs/my/type")
.withVersion(new Version("2.1.0"))
.withRequestExtension("json")
.withRequestMethod("POST")
.withSelectors("selector1", "selector,2")
.build());
// TODO: add script capabilities
Capabilities caps = new Capabilities(resourceTypeCaps, Collections.emptySet(), Collections.emptySet());
String expectedHeaderValue = "sling.servlet;sling.servlet.resourceTypes:List<String>=\"my/type,/libs/my/type\";version:Version=\"2.1.0\";sling.servlet.methods=POST;sling.servlet.extensions=json;sling.servlet.selectors:List<String>=\"selector1,selector\\,2\"";
Assert.assertEquals(expectedHeaderValue, caps.getProvidedCapabilitiesString());
}
@Test
public void testGetRequiredCapabilitiesString() {
Set<RequiredResourceTypeCapability> resourceTypeCaps = new LinkedHashSet<>();
resourceTypeCaps.add(RequiredResourceTypeCapability.builder()
.withResourceType("my/type")
.withVersionRange(new VersionRange("(1.0,3.0)"))
.withIsOptional()
.build());
resourceTypeCaps.add(RequiredResourceTypeCapability.builder()
.withResourceType("/other/type")
.build());
Capabilities caps = new Capabilities(Collections.emptySet(), Collections.emptySet(), resourceTypeCaps);
String expectedHeaderValue = "sling.servlet;filter:=\"(&(!(sling.servlet.selectors=*))(&(&(version=*)(!(version<=1.0.0))(!(version>=3.0.0)))(sling.servlet.resourceTypes=my/type)))\";resolution:=optional" +
",sling.servlet;filter:=\"(&(!(sling.servlet.selectors=*))(sling.servlet.resourceTypes=/other/type))\"";
Assert.assertEquals(expectedHeaderValue, caps.getRequiredCapabilitiesString());
}
}
|
<gh_stars>1-10
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import {
Row,
Col,
Button,
ButtonDropdown,
DropdownToggle,
DropdownMenu,
DropdownItem,
Card,
CardHeader,
CardFooter,
CardBody,
Collapse,
Form,
FormGroup,
FormText,
Label,
Input,
InputGroup,
InputGroupAddon,
InputGroupText
} from 'reactstrap';
import renderField from '../Utils/renderFields';
import { Field, reduxForm } from 'redux-form';
class CourseForm extends Component {
constructor(props) {
super(props);
this.toggle = this.toggle.bind(this);
this.state = { collapse: true };
}
toggle() {
this.setState({ collapse: !this.state.collapse });
}
componentDidMount(){
alertify.success('success loading')
}
render() {
return (
<div>
<Row>
<Col xs="12">
<Card>
<CardHeader>
<i className="fa fa-edit"></i>Form Elements
<div className="card-actions">
<a href="#" className="btn-setting"><i className="icon-settings"></i></a>
<Button className="btn btn-minimize" data-target="#collapseExample" onClick={this.toggle}><i className="icon-arrow-up"></i></Button>
<a href="#" className="btn-close"><i className="icon-close"></i></a>
</div>
</CardHeader>
<Collapse isOpen={this.state.collapse} id="collapseExample">
<CardBody>
<Form className="form-horizontal">
<FormGroup>
<Field name="Course_name" component={renderField} type="text" label="ชื่อ" autoFocus />
</FormGroup>
<FormGroup>
<Field name="first_name" component={renderField} type="text" label="ชื่อ" autoFocus />
</FormGroup>
<FormGroup>
<Label htmlFor="appendedPrependedInput">Append and prepend</Label>
<div className="controls">
<InputGroup className="input-prepend">
<InputGroupAddon addonType="prepend">
<InputGroupText>$</InputGroupText>
</InputGroupAddon>
<Input id="appendedPrependedInput" size="16" type="text"/>
<InputGroupAddon addonType="append">
<InputGroupText>.00</InputGroupText>
</InputGroupAddon>
</InputGroup>
</div>
</FormGroup>
<FormGroup>
<Label htmlFor="appendedInputButton">Append with button</Label>
<div className="controls">
<InputGroup>
<Input id="appendedInputButton" size="16" type="text"/>
<InputGroupAddon addonType="append">
<Button color="secondary">Go!</Button>
</InputGroupAddon>
</InputGroup>
</div>
</FormGroup>
<FormGroup>
<Label htmlFor="appendedInputButtons">Two-button append</Label>
<div className="controls">
<InputGroup>
<Input id="appendedInputButtons" size="16" type="text"/>
<InputGroupAddon addonType="append">
<Button color="secondary">Search</Button>
<Button color="secondary">Options</Button>
</InputGroupAddon>
</InputGroup>
</div>
</FormGroup>
<div className="form-actions">
<Button type="submit" color="primary">Save changes</Button>
<Button color="secondary">Cancel</Button>
</div>
</Form>
</CardBody>
</Collapse>
</Card>
</Col>
</Row>
</div>
);
}
}
function validate(values){
errors ={};
return errors;
}
const form = reduxForm({
form: 'CourseForm',
validate
})
export default form(CourseForm);
|
package br.indie.fiscal4j.mdfe3.classes.def;
/**
* @Author <NAME> on 30/05/17.
*/
public enum MDFTipoProprietario {
/**
* 0-TAC – Agregado;
* 1-TAC Independente; ou
* 2 – Outros.
*/
TAC_AGREGADO("0", "TAC – Agregado"),
TAC_INDEPENDENTE("1", "TAC – Independente"),
OUTROS("2", "Outros");
private final String codigo;
private final String descricao;
MDFTipoProprietario(final String codigo, final String descricao) {
this.codigo = codigo;
this.descricao = descricao;
}
public String getCodigo() {
return this.codigo;
}
public static MDFTipoProprietario valueOfCodigo(final String codigo) {
for (MDFTipoProprietario tipoUnidadeCarga : MDFTipoProprietario.values()) {
if (tipoUnidadeCarga.getCodigo().equalsIgnoreCase(codigo)) {
return tipoUnidadeCarga;
}
}
return null;
}
@Override
public String toString() {
return codigo + " - " + descricao;
}
}
|
<filename>src/components/profile/profile.tsx
import React, { useState, useEffect } from "react";
import { useObserver } from "mobx-react-lite";
import { useStores, useTheme } from "../../store";
import {
View,
Text,
StyleSheet,
TouchableOpacity,
Image,
ToastAndroid,
ScrollView,
Dimensions,
} from "react-native";
import { useNavigation, DrawerActions } from "@react-navigation/native";
import {
Appbar,
Portal,
ActivityIndicator,
TextInput,
} from "react-native-paper";
import { Title } from "react-native-paper";
import Icon from "react-native-vector-icons/AntDesign";
import { me } from "../form/schemas";
import Form from "../form";
import Cam from "../utils/cam";
import ImgSrcDialog from "../utils/imgSrcDialog";
import { usePicSrc } from "../utils/picSrc";
import RNFetchBlob from "rn-fetch-blob";
import * as rsa from "../../crypto/rsa";
import * as e2e from "../../crypto/e2e";
import { encode as btoa } from "base-64";
import PIN, { userPinCode } from "../utils/pin";
import Clipboard from "@react-native-community/clipboard";
import Toggler from "./toggler";
import { useDarkMode } from "react-native-dynamic";
import { getPinTimeout, updatePinTimeout } from "../utils/pin";
import Slider from "@react-native-community/slider";
export default function Profile() {
const { details, user, contacts, meme, ui } = useStores();
const theme = useTheme();
const [uploading, setUploading] = useState(false);
const [dialogOpen, setDialogOpen] = useState(false);
const [takingPhoto, setTakingPhoto] = useState(false);
const [saving, setSaving] = useState(false);
const [photo_url, setPhotoUrl] = useState("");
const [_, setTapCount] = useState(0);
const [sharing, setSharing] = useState(false);
const [showPIN, setShowPIN] = useState(false);
const [exporting, setExporting] = useState(false);
const [advanced, setAdvanced] = useState(false);
const [pinTimeout, setPinTimeout] = useState(12);
const [initialPinTimeout, setInitialPinTimeout] = useState(12);
const [serverURL, setServerURL] = useState("");
const [tipAmount, setTipAmount] = useState(user.tipAmount + "");
async function loadPinTimeout() {
const pt = await getPinTimeout();
setInitialPinTimeout(pt);
setPinTimeout(pt);
}
useEffect(() => {
loadPinTimeout();
setServerURL(user.currentIP);
}, []);
function pinTimeoutValueUpdated(v) {
console.log("UPDATE NOW");
updatePinTimeout(String(v));
}
function pinTimeoutValueChange(v) {
setPinTimeout(v);
}
function serverURLchange(URL) {
setServerURL(URL);
}
function serverURLDoneChanging() {
user.setCurrentIP(serverURL);
}
function tipAmountChange(ta) {
const int = parseInt(ta);
setTipAmount(int ? int + "" : "");
}
function tipAmountDoneChanging() {
user.setTipAmount(parseInt(tipAmount));
}
const isDark = useDarkMode();
function selectAppearance(a) {
if (a === "System") theme.setDark(isDark);
if (a === "Dark") theme.setDark(true);
if (a === "Light") theme.setDark(false);
theme.setMode(a);
}
async function shareContactKey() {
const me = contacts.contacts.find((c) => c.id === user.myid);
const contact_key = me.contact_key;
if (!contact_key) return;
setSharing(true);
await contacts.updateContact(user.myid, { contact_key });
setSharing(false);
}
async function tookPic(img) {
setDialogOpen(false);
setTakingPhoto(false);
setUploading(true);
try {
await upload(img.uri);
} catch (e) {
console.log(e);
setUploading(false);
}
}
async function upload(uri) {
const type = "image/jpg";
const name = "Image.jpg";
const server = meme.getDefaultServer();
if (!server) return;
RNFetchBlob.fetch(
"POST",
`https://${server.host}/public`,
{
Authorization: `Bearer ${server.token}`,
"Content-Type": "multipart/form-data",
},
[
{
name: "file",
filename: name,
type: type,
data: RNFetchBlob.wrap(uri),
},
{ name: "name", data: name },
]
)
.uploadProgress({ interval: 250 }, (written, total) => {
// console.log('uploaded', written / total)
})
.then(async (resp) => {
let json = resp.json();
if (json.muid) {
console.log("UPLOADED!!", json.muid);
setPhotoUrl(`https://${server.host}/public/${json.muid}`);
}
setUploading(false);
})
.catch((err) => {
console.log(err);
setUploading(false);
});
}
return useObserver(() => {
const myid = user.myid;
const myContactKey = user.contactKey
const meContact = contacts.contacts.find((c) => c.id === myid) || {
contact_key:myContactKey,
private_photo:false,
route_hint:'',
};
function showError(err) {
ToastAndroid.showWithGravityAndOffset(
err,
ToastAndroid.SHORT,
ToastAndroid.TOP,
0,
125
);
}
async function exportKeys(pin) {
try {
setShowPIN(false);
if (!pin) return showError('NO PIN');
const thePIN = await userPinCode();
if (pin !== thePIN) return showError('NO USER PIN');
setExporting(true);
const priv = await rsa.getPrivateKey();
if(!priv) return showError('CANT READ PRIVATE KEY');
let pub = myContactKey
if(!pub) {
// showError('myContactKey is not found');
pub = meContact && meContact.contact_key;
}
if(!pub) return showError('CANT FIND CONTACT KEY');;
const ip = user.currentIP;
if(!ip) return showError('CANT FIND IP');
const token = user.authToken;
if(!token) return showError('CANT FIND TOKEN');
if (!priv || !pub || !ip || !token) return showError('MISSING A VAR');
const str = `${priv}::${pub}::${ip}::${token}`;
const enc = await e2e.encrypt(str, pin);
const final = btoa(`keys::${enc}`);
Clipboard.setString(final);
ToastAndroid.showWithGravityAndOffset(
"Export Keys Copied",
ToastAndroid.SHORT,
ToastAndroid.TOP,
0,
125
);
setExporting(false);
} catch(e) {
showError(e.message || e)
}
}
let imgURI = usePicSrc(meContact);
if (photo_url) imgURI = photo_url;
if (showPIN) {
return <PIN forceEnterMode={true} onFinish={(pin) => exportKeys(pin)} />;
}
const cardStyles = {
backgroundColor: theme.main,
borderBottomColor: theme.dark ? "#181818" : "#ddd",
borderTopColor: theme.dark ? "#181818" : "#ddd",
};
const width = Math.round(Dimensions.get("window").width);
return (
<View style={{ ...styles.wrap, backgroundColor: theme.bg }}>
<Header />
<View style={styles.userInfoSection}>
<View>
<TouchableOpacity
onPress={() => setDialogOpen(true)}
style={styles.userPic}
>
<Image
resizeMode="cover"
source={
imgURI
? { uri: imgURI }
: require("../../../android_assets/avatar.png")
}
style={{ width: 60, height: 60, borderRadius: 30 }}
/>
{uploading && (
<ActivityIndicator
animating={true}
color="#55D1A9"
style={styles.spinner}
/>
)}
</TouchableOpacity>
</View>
<View style={styles.userInfo}>
<Title style={styles.title}>{user.alias}</Title>
<View style={styles.userBalance}>
<Text style={{ color: theme.title }}>{details.balance}</Text>
<Text
style={{ marginLeft: 10, marginRight: 10, color: "#c0c0c0" }}
>
sat
</Text>
<TouchableOpacity
onPress={() => {
setTapCount((cu) => {
if (cu >= 6) {
// seventh tap
shareContactKey();
return 0;
}
return cu + 1;
});
}}
>
{sharing ? (
<View style={{ height: 20, paddingTop: 4 }}>
<ActivityIndicator
animating={true}
color="#d0d0d0"
size={12}
style={{ marginLeft: 4 }}
/>
</View>
) : (
<Icon name="wallet" color="#d0d0d0" size={20} />
)}
</TouchableOpacity>
</View>
</View>
</View>
<Toggler
width={width}
extraStyles={{
borderRadius: 0,
borderRightWidth: 0,
borderLeftWidth: 0,
}}
onSelect={(e) => setAdvanced(e === "Advanced")}
selectedItem={advanced ? "Advanced" : "Basic"}
items={["Basic", "Advanced"]}
/>
{!advanced && (
<ScrollView style={styles.scroller}>
<View style={{ ...styles.formWrap, ...cardStyles }}>
<Form
schema={me}
loading={saving}
buttonText="Save"
readOnlyFields={["public_key", "route_hint"]}
forceEnable={photo_url}
initialValues={{
alias: user.alias,
public_key: user.publicKey,
private_photo: meContact.private_photo || false,
route_hint: meContact.route_hint || "",
}}
extraCopySuffixes={{
// so that route hint is appended when copy
public_key: meContact.route_hint ? ':' + meContact.route_hint : ""
}}
onSubmit={async (values) => {
setSaving(true);
await contacts.updateContact(user.myid, {
alias: values.alias,
private_photo: values.private_photo,
...(photo_url && { photo_url }),
});
setSaving(false);
}}
/>
</View>
<View style={{ ...styles.options, ...cardStyles }}>
<Text style={{ ...styles.label, color: theme.subtitle }}>
Appearance
</Text>
<Toggler
width={300}
extraStyles={{}}
onSelect={selectAppearance}
selectedItem={theme.mode}
items={["System", "Dark", "Light"]}
/>
</View>
<View style={{ ...styles.inputs, ...cardStyles }}>
<Text style={{ ...styles.label, color: theme.subtitle }}>
Default tip amount
</Text>
<Text style={{ paddingLeft: 12, paddingRight: 12 }}>
<TextInput
placeholder="Default Tip Amount"
value={tipAmount + ""}
onChangeText={tipAmountChange}
onBlur={tipAmountDoneChanging}
/>
</Text>
</View>
<TouchableOpacity
style={{ ...styles.export, ...cardStyles }}
onPress={() => setShowPIN(true)}
>
<Text style={styles.exportText}>
{!exporting
? "Want to switch devices? Export keys"
: "Encrypting keys with your PIN........"}
</Text>
</TouchableOpacity>
</ScrollView>
)}
{advanced && (
<ScrollView style={styles.scroller}>
<View style={{ ...cardStyles, padding: 20, marginBottom: 12 }}>
<View style={styles.pinTimeoutTextWrap}>
<Text style={{ color: theme.subtitle }}>Server URL</Text>
</View>
<TextInput
placeholder="Server URL"
value={serverURL}
onChangeText={serverURLchange}
onBlur={serverURLDoneChanging}
/>
</View>
<View style={{ ...cardStyles, padding: 20 }}>
<View style={styles.pinTimeoutTextWrap}>
<Text style={{ color: theme.subtitle }}>PIN Timeout</Text>
<Text style={{ color: theme.title }}>
{pinTimeout ? pinTimeout : "Always Require PIN"}
</Text>
</View>
<Slider
minimumValue={0}
maximumValue={24}
value={initialPinTimeout}
step={1}
minimumTrackTintColor={theme.primary}
maximumTrackTintColor={theme.primary}
thumbTintColor={theme.primary}
onSlidingComplete={pinTimeoutValueUpdated}
onValueChange={pinTimeoutValueChange}
/>
</View>
</ScrollView>
)}
<ImgSrcDialog
open={dialogOpen}
onClose={() => setDialogOpen(false)}
onPick={(res) => tookPic(res)}
onChooseCam={() => setTakingPhoto(true)}
/>
{takingPhoto && (
<Portal>
<Cam
onCancel={() => setTakingPhoto(false)}
onSnap={(pic) => tookPic(pic)}
/>
</Portal>
)}
</View>
);
});
}
function Header() {
const navigation = useNavigation();
const theme = useTheme();
return (
<Appbar.Header style={{ width: "100%", backgroundColor: theme.main }}>
<Appbar.Action
icon="menu"
onPress={() => navigation.dispatch(DrawerActions.openDrawer())}
accessibilityLabel="menu-close-profile"
/>
<Appbar.Content title="Profile" />
</Appbar.Header>
);
}
const styles = StyleSheet.create({
wrap: {
flex: 1,
},
content: {
flex: 1,
width: "100%",
marginTop: 10,
alignItems: "center",
},
userInfoSection: {
paddingLeft: 20,
marginBottom: 25,
marginTop: 25,
display: "flex",
flexDirection: "row",
},
scroller: {
display: "flex",
},
drawerSection: {
marginTop: 25,
},
userPic: {
flexDirection: "row",
alignItems: "center",
minHeight: 62,
minWidth: 62,
height: 62,
width: 62,
flexShrink: 0,
borderColor: "#ddd",
borderWidth: 1,
borderRadius: 31,
position: "relative",
},
userInfo: {
display: "flex",
flexDirection: "column",
alignItems: "flex-start",
justifyContent: "flex-start",
marginLeft: 15,
},
title: {
fontWeight: "bold",
flexDirection: "row",
alignItems: "center",
},
userBalance: {
flexDirection: "row",
alignItems: "center",
},
img: {
height: 50,
width: 50,
borderRadius: 25,
},
spinner: {
position: "absolute",
left: 19,
top: 19,
},
formWrap: {
flex: 1,
paddingBottom: 30,
maxHeight: 445,
minHeight: 445,
position: "relative",
borderBottomWidth: 1,
borderTopWidth: 1,
marginBottom: 10,
},
options: {
maxHeight: 100,
minHeight: 100,
borderBottomWidth: 1,
borderTopWidth: 1,
},
inputs: {
maxHeight: 100,
minHeight: 124,
borderBottomWidth: 1,
borderTopWidth: 1,
marginBottom: 10,
marginTop: 10,
},
export: {
width: "100%",
display: "flex",
alignItems: "center",
justifyContent: "center",
height: 50,
marginTop: 10,
borderBottomWidth: 1,
borderTopWidth: 1,
marginBottom: 45,
},
exportText: {
color: "#6289FD",
fontSize: 12,
},
label: {
fontSize: 12,
marginTop: 15,
marginLeft: 20,
marginBottom: 10,
},
pinTimeoutTextWrap: {
width: "100%",
display: "flex",
flexDirection: "row",
justifyContent: "space-between",
alignItems: "center",
paddingLeft: 16,
paddingRight: 16,
marginBottom: 15,
},
});
|
#!/bin/bash
#>>>>>>>>>> prepare
source prepare.sh
#<<<<<<<<<<
set -e
# See: latest stable version from https://nodejs.org/ja/download/ at 2018-11-19
declare -r MAJOR_VER=${1:-"10.16"}
declare -r MINOR_VER=${2:-"3"}
declare -r VER=${MAJOR_VER}.${MINOR_VER}
: "----- install ndenv"
declare -r NDENV_DIR=${HOME}/.ndenv
[ -d ${NDENV_DIR} ] && rm -fr ${NDENV_DIR}
git clone https://github.com/riywo/ndenv ~/.ndenv
declare -r NDENV_BIN=${NDENV_DIR}/bin
echo "export PATH=${NDENV_BIN}:${PATH}" >> ${ENV_RC}
echo 'eval "$(ndenv init -)"' >> ${ENV_RC}
set +u; source ${ENV_RC}; set -u
: "----- install nodebuild"
declare -r NDENV_PLUGIN_DIR=${NDENV_DIR}/plugins
[ -d ${NDENV_PLUGIN_DIR} ] || mkdir ${NDENV_PLUGIN_DIR}
git clone https://github.com/riywo/node-build.git ${NDENV_PLUGIN_DIR}/node-build
: "----- install node.js using ndenv"
${NDENV_BIN}/ndenv install v${VER}
${NDENV_BIN}/ndenv rehash
${NDENV_BIN}/ndenv global v${VER}
|
cur_path="$HOME/.config/Alfred/Alfred.alfredpreferences"
preference_path="$HOME/Library/Application Support/Alfred/Alfred.alfredpreferences"
rm "$preference_path"
ln -s "$cur_path" "$preference_path"
|
<reponame>dmitry-korolev/gfm-json<gh_stars>1-10
import { expect } from 'chai'
import { MDJ } from 'core/MDJ'
const { parse } = MDJ()
const singleQuotes = '[single quotes](http://example.com \'Title\')'
const doubleQuotes = '[double quotes](http://example.com "Title")'
const singleQuotesBlank = '[single quotes blank](http://example.com \'\')'
const doubleQuotesBlank = '[double quotes blank](http://example.com "")'
const space = '[space](http://example.com "2 Words")'
const parenthesis = '[parentheses](http://example.com/url-(parentheses) "Title")'
describe('Link titles', () => {
it('single quotes', () => {
expect(parse(singleQuotes)).to.eql([
{
type: 'paragraph',
children: [
{
type: 'link',
href: 'http://example.com',
title: 'Title',
children: [
{
type: 'text',
value: 'single quotes'
}
]
}
]
}
])
})
it('double quotes', () => {
expect(parse(doubleQuotes)).to.eql([
{
type: 'paragraph',
children: [
{
type: 'link',
href: 'http://example.com',
title: 'Title',
children: [
{
type: 'text',
value: 'double quotes'
}
]
}
]
}
])
})
it('empty single quotes', () => {
expect(parse(singleQuotesBlank)).to.eql([
{
type: 'paragraph',
children: [
{
type: 'link',
href: 'http://example.com',
children: [
{
type: 'text',
value: 'single quotes blank'
}
]
}
]
}
])
})
it('empty double quotes', () => {
expect(parse(doubleQuotesBlank)).to.eql([
{
type: 'paragraph',
children: [
{
type: 'link',
href: 'http://example.com',
children: [
{
type: 'text',
value: 'double quotes blank'
}
]
}
]
}
])
})
it('space', () => {
expect(parse(space)).to.eql([
{
type: 'paragraph',
children: [
{
type: 'link',
href: 'http://example.com',
title: '2 Words',
children: [
{
type: 'text',
value: 'space'
}
]
}
]
}
])
})
xit('parenthesis', () => {
expect(parse(parenthesis)).to.eql([
{
type: 'paragraph',
children: [
{
type: 'link',
href: 'http://example.com/url-(parentheses)',
title: 'Title',
children: [
{
type: 'text',
value: 'parentheses'
}
]
}
]
}
])
})
})
|
#!/usr/bin/env bash
function __sdkman_pre_installation_hook {
echo "Inside pre-install hook..."
cookie="$SDKMAN_DIR/var/cookie"
if [[ -f "$cookie" ]]; then rm "$cookie"; fi
echo "oraclelicense=accept-securebackup-cookie" > "$cookie"
echo "Dropped cookie..."
}
|
#!/bin/bash
# Gibs me access <3
sudo /root.sh
# turn on bash's job control
set -m
# Start the primary process and put it in the background
ROCKET_ADDRESS="0.0.0.0" \
PUBLIC_PATH="/home/steam/ark-manager-web/dist" \
/home/steam/ark-manager-web/server &
# Start the helper process
/home/steam/ark-manager-web/agent
# the my_helper_process might need to know how to wait on the
# primary process to start before it does its work and returns
# now we bring the primary process back into the foreground
# and leave it there
fg %1
|
#!/usr/bin/env bash
set -eu -o pipefail
if [[ $# -lt 1 ]]; then
echo "$0: version" >&2
exit 1
fi
VERSION=$1
declare -A SYSTEMS
SYSTEMS=(
[i686-linux]=linux-ia32
[x86_64-linux]=linux-x64
[armv7l-linux]=linux-armv7l
[aarch64-linux]=linux-arm64
[x86_64-darwin]=darwin-x64
[aarch64-darwin]=darwin-arm64
)
hashfile="$(nix-prefetch-url --print-path "https://github.com/electron/electron/releases/download/v${VERSION}/SHASUMS256.txt" 2>/dev/null | tail -n1)"
headers="$(nix-prefetch-url "https://atom.io/download/electron/v${VERSION}/node-v${VERSION}-headers.tar.gz")"
# Entry similar to the following goes in default.nix:
echo "Add the following lines to dream2nix/overrides/nodejs/default.nix:\n"
echo " \"${VERSION}\" = {"
for S in "${!SYSTEMS[@]}"; do
hash="$(grep " *electron-v${VERSION}-${SYSTEMS[$S]}.zip$" "$hashfile"|cut -f1 -d' ' || :)"
if [[ -n $hash ]]; then
echo " $S = \"$hash\";"
fi
done
echo " headers = \"$headers\";"
echo " };"
|
#! /bin/bash
BUCKET="imjacobclark-artifacts"
if [ $1 = "update" ]
then
zip -r api-crime-rate.zip ./*
aws s3 cp api-crime-rate.zip s3://$BUCKET/api-crime-rate.zip
aws lambda update-function-code --function-name api-crime-rate --s3-bucket $BUCKET --s3-key api-crime-rate.zip --publish
python troposphere/api.py > template.json
aws cloudformation update-stack --capabilities CAPABILITY_IAM --stack-name api-crime-data --template-body file://./template.json
rm template.json api-crime-rate.zip
exit $?
fi
if [ $1 = "create" ]
then
zip -r api-crime-rate.zip ./*
aws s3 cp api-crime-rate.zip s3://$BUCKET/api-crime-rate.zip
python troposphere/api.py > template.json
aws cloudformation create-stack --capabilities CAPABILITY_IAM --stack-name api-crime-data --template-body file://./template.json
rm template.json api-crime-rate.zip
exit $?
fi
echo "Unknown operation, try again with update or create"
|
<reponame>Esther-Anyona/Pass_Locker
#!/usr/bin/env python3.8
from User import User
from Credentials import Credentials
def create_useraccount(firstName, lastName, userName, password):
"""
Function to create a new user account
"""
new_user = User(firstName, lastName, userName, password)
return new_user
def save_user(User):
"""
Function to save the newly created user account
"""
User.save_user()
def delete_user(User):
"""
Function to delete existing user account
"""
User.delete_user
def find_user(userName):
"""
Function to find a user by username
"""
return User.find_by_name(userName)
def display_user():
"""
Function to display existing users
"""
return User.display_user()
def isexist_user(userName):
"""
Method to check whether a user exists
"""
return User.user_exists(userName)
def create_accountcredentials(account, username, passcode):
new_account = Credentials (account, username, passcode)
return new_account
def save_account(Credentials):
Credentials.save_account()
def delete_account(Credentials):
Credentials.delete_account()
def display_account():
"""
Function that returns all saved accounts
"""
return Credentials.display_account()
def isexist_account(account):
"""
Function for checking whether an account exists
"""
return Credentials.account_exists(account)
def generate_passcode():
"""
Function for generating a random passcode
"""
generate_passcode = Credentials.generate_passcode()
return generate_passcode
def main():
while True:
print("Hey, Welcome to Password Locker!")
print("**"*10)
print("Use: 1 - to sign up as a new user, 2 - to login, 3 - to find a user, 4 - to exit")
code = int(input())
if code == 1: #sign-up
print("Create User Account")
print("*"*10)
print("Enter your First Name")
firstName = input()
print("Enter your Last Name")
lastName = input()
print("Enter your username")
userName = input()
print("Enter your password")
password = input()
print("\n")
save_user(create_useraccount(firstName, lastName, userName, password))
print("Your user account has been successfully created!")
print("\n")
while True:
print(f"Welcome {userName}, use the following code options to proceed")
print ("**"*10)
print("1 - save new passcode, 2 - Delete passcode, 3 - Display saved passcodes, 4 - log out ")
print("\n")
option = int(input())
if option ==1:
print("New Credentials")
print("*"*10)
print("Account Name")
account = input()
print("username")
username = input()
print("Enter your password, use the following options;")
print("1 - for own passcode, 2 - for system generated passcode")
option == int(input())
if option == 1:
print("Enter your password")
passcode = input()
elif option == 2:
passcode = generate_passcode()
break
save_account(create_accountcredentials(account, username, passcode))
elif option ==2:
print("Enter the name of account to delete")
print("*"*10)
account = input()
if isexist_account(account):
remove_account(account)
delete_account(remove_account)
else:
print(f"{account} account cannot be found")
elif option ==3:
if display_account():
for account in display_account():
print(f"{account.account}:{account.passcode}")
else:
print("No passcode saved for this account")
elif option ==4:
break
if code == 2: #user login
print("Enter username")
userName = input()
print("Enter your password")
password = input()
if __name__ == '__main__':
main()
|
const express = require('express');
const indexRouter = express.Router();
indexRouter.get('/', (req, res) => {
res.render('index');
});
indexRouter.get('/login', (req, res) => {
res.render('login');
});
// This route serves your `/signup` form
indexRouter.get('/signup', (req, res) => {
res.render('signup');
});
module.exports = indexRouter;
|
// Copyright 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef WebLayerTreeViewImpl_h
#define WebLayerTreeViewImpl_h
#include "base/memory/scoped_ptr.h"
#include "cc/layer_tree_host_client.h"
#include "third_party/WebKit/Source/Platform/chromium/public/WebLayerTreeView.h"
namespace cc {
class LayerTreeHost;
}
namespace WebKit {
class WebLayer;
class WebLayerTreeViewClient;
class WebLayerTreeViewClientAdapter;
class WebLayerTreeViewImpl : public WebLayerTreeView, public cc::LayerTreeHostClient {
public:
explicit WebLayerTreeViewImpl(WebLayerTreeViewClient*);
virtual ~WebLayerTreeViewImpl();
bool initialize(const Settings&);
// WebLayerTreeView implementation.
virtual void setSurfaceReady() OVERRIDE;
virtual void setRootLayer(const WebLayer&) OVERRIDE;
virtual void clearRootLayer() OVERRIDE;
virtual void setViewportSize(const WebSize& layoutViewportSize, const WebSize& deviceViewportSize = WebSize()) OVERRIDE;
virtual WebSize layoutViewportSize() const OVERRIDE;
virtual WebSize deviceViewportSize() const OVERRIDE;
virtual WebFloatPoint adjustEventPointForPinchZoom(const WebFloatPoint& point) const OVERRIDE;
virtual void setDeviceScaleFactor(float) OVERRIDE;
virtual float deviceScaleFactor() const OVERRIDE;
virtual void setBackgroundColor(WebColor) OVERRIDE;
virtual void setHasTransparentBackground(bool) OVERRIDE;
virtual void setVisible(bool) OVERRIDE;
virtual void setPageScaleFactorAndLimits(float pageScaleFactor, float minimum, float maximum) OVERRIDE;
virtual void startPageScaleAnimation(const WebPoint& destination, bool useAnchor, float newPageScale, double durationSec) OVERRIDE;
virtual void setNeedsAnimate() OVERRIDE;
virtual void setNeedsRedraw() OVERRIDE;
virtual bool commitRequested() const OVERRIDE;
virtual void composite() OVERRIDE;
virtual void updateAnimations(double frameBeginTime) OVERRIDE;
virtual bool compositeAndReadback(void *pixels, const WebRect&) OVERRIDE;
virtual void finishAllRendering() OVERRIDE;
virtual void setDeferCommits(bool deferCommits) OVERRIDE;
virtual void renderingStats(WebRenderingStats&) const OVERRIDE;
virtual void setFontAtlas(SkBitmap, WebRect asciiToRectTable[128], int fontHeight) OVERRIDE;
virtual void loseCompositorContext(int numTimes) OVERRIDE;
// cc::LayerTreeHostClient implementation.
virtual void willBeginFrame() OVERRIDE;
virtual void didBeginFrame() OVERRIDE;
virtual void animate(double monotonicFrameBeginTime) OVERRIDE;
virtual void layout() OVERRIDE;
virtual void applyScrollAndScale(const cc::IntSize& scrollDelta, float pageScale) OVERRIDE;
virtual scoped_ptr<WebCompositorOutputSurface> createOutputSurface() OVERRIDE;
virtual void didRecreateOutputSurface(bool success) OVERRIDE;
virtual scoped_ptr<cc::InputHandler> createInputHandler() OVERRIDE;
virtual void willCommit() OVERRIDE;
virtual void didCommit() OVERRIDE;
virtual void didCommitAndDrawFrame() OVERRIDE;
virtual void didCompleteSwapBuffers() OVERRIDE;
virtual void scheduleComposite() OVERRIDE;
private:
WebLayerTreeViewClient* m_client;
scoped_ptr<cc::LayerTreeHost> m_layerTreeHost;
};
} // namespace WebKit
#endif // WebLayerTreeViewImpl_h
|
<filename>odps-data-carrier/network-measurement-tool/src/main/java/com/aliyun/odps/datacarrier/network/Endpoint.java
package com.aliyun.odps.datacarrier.network;
public class Endpoint {
private String odpsEndpoint;
private String tunnelEndpoint;
private String location;
public Endpoint(String odpsEndpoint, String tunnelEndpoint, String location) {
if (odpsEndpoint == null || tunnelEndpoint == null) {
throw new IllegalArgumentException("ODPS endpoint or tunnel endpoint cannot be null");
}
this.odpsEndpoint = odpsEndpoint;
this.tunnelEndpoint = tunnelEndpoint;
this.location = location;
}
public String getOdpsEndpoint() {
return this.odpsEndpoint;
}
public String getTunnelEndpoint() {
return this.tunnelEndpoint;
}
public String getLocation() {
return this.location;
}
}
|
//
// Created by ooooo on 2019/12/5.
//
#ifndef CPP_0231_SOLUTION1_H
#define CPP_0231_SOLUTION1_H
#include <iostream>
using namespace std;
class Solution {
public:
bool isPowerOfTwo(int n) {
return n > 0 && (n & n - 1) == 0;
}
};
#endif //CPP_0231_SOLUTION1_H
|
#!/bin/bash
WORKSPACEDIR="/workspace"
pushd .
cd $WORKSPACEDIR
echo "Installing NPM dependencies..."
npm install --silent
echo "Starting datatracker server..."
ietf/manage.py runserver 0.0.0.0:8000 --settings=settings_local > /dev/null 2>&1 &
serverPID=$!
echo "Waiting for server to come online ..."
wget -qO- https://raw.githubusercontent.com/eficode/wait-for/v2.1.3/wait-for | sh -s -- localhost:8000 -- echo "Server ready"
echo "Run dbus process to silence warnings..."
sudo mkdir -p /run/dbus
sudo dbus-daemon --system &> /dev/null
echo "Starting JS tests..."
npx cypress run
kill $serverPID
popd
|
#! /bin/bash
GPUS_PER_NODE=8
# Change for multinode config
MASTER_ADDR=127.0.0.1
MASTER_PORT=2000
NNODES=1
NODE_RANK=1
export DLWS_NUM_WORKER=${NNODES}
export DLWS_NUM_GPU_PER_WORKER=${GPUS_PER_NODE}
# DATA OPTIONS:
DATA_PATH=data/enron/enron_text_document # data/webtext/webtext_text_document
VOCAB_PATH=data/gpt2-vocab.json
MERGE_PATH=data/gpt2-merges.txt
CHECKPOINT_PATH=checkpoints/gpt2_XL_ds
script_path=$(realpath $0)
script_dir=$(dirname $script_path)
#config_json="configs/deepspeed_configs/ds_zero_stage_2_config.json"
config_json="configs/deepspeed_configs/ds_zero_stage_1_config.json"
#config_json="configs/deepspeed_configs/ds_config.json"
# Training options:
# Megatron Model Parallelism
mp_size=1
# DeepSpeed Pipeline parallelism
pp_size=2
# TOTAL BATCH SIZE = BATCHSIZE(pergpu) * GAS * N_GPUS
# ensure batch size details are consistent between here and the deepspeed config
BATCHSIZE=4
GAS=16
LOGDIR="tensorboard_data/${NLAYERS}l_${NHIDDEN}h_${NNODES}n_${GPUS_PER_NODE}g_${pp_size}pp_${mp_size}mp_${BATCHSIZE}b_ds4"
#ZeRO Configs
stage=1
reduce_scatter=true
contigious_gradients=true
rbs=50000000
agbs=5000000000
#Actication Checkpointing and Contigious Memory
chkp_layers=1
PA=true
PA_CPU=true
CC=true
SYNCHRONIZE=true
PROFILE=false
# GPT options:
NLAYERS=24
NHIDDEN=2048
NHEADS=16
SEQLEN=1024
LR="2.0e-4"
MINLR="2.0e-5"
WEIGHTDECAY=0
DROPOUT=0
SPARSITY='interspersed'
TRAIN_ITERS=320000
gpt_options=" \
--model-parallel-size ${mp_size} \
--pipe-parallel-size ${pp_size} \
--num-layers $NLAYERS \
--hidden-size $NHIDDEN \
--num-attention-heads $NHEADS \
--seq-length $SEQLEN \
--max-position-embeddings 1024 \
--batch-size $BATCHSIZE \
--gas $GAS \
--train-iters $TRAIN_ITERS \
--lr-decay-iters $TRAIN_ITERS \
--save $CHECKPOINT_PATH \
--load $CHECKPOINT_PATH \
--data-path $DATA_PATH \
--vocab-file $VOCAB_PATH \
--merge-file $MERGE_PATH \
--data-impl mmap \
--split 949,50,1 \
--distributed-backend nccl \
--lr $LR \
--lr-decay-style cosine \
--min-lr $MINLR \
--weight-decay $WEIGHTDECAY \
--attention-dropout $DROPOUT \
--hidden-dropout $DROPOUT \
--clip-grad 1.0 \
--warmup 0.01 \
--checkpoint-activations \
--log-interval 1 \
--save-interval 500 \
--eval-interval 100 \
--eval-iters 10 \
--fp16 \
--tensorboard-dir ${LOGDIR} \
--sparsity $SPARSITY
"
deepspeed_options=" \
--deepspeed \
--deepspeed_config ${config_json} \
--zero-stage ${stage} \
--zero-reduce-bucket-size ${rbs} \
--zero-allgather-bucket-size ${agbs}
"
if [ "${contigious_gradients}" = "true" ]; then
deepspeed_options="${deepspeed_options} \
--zero-contigious-gradients"
fi
if [ "${reduce_scatter}" = "true" ]; then
deepspeed_options="${deepspeed_options} \
--zero-reduce-scatter"
fi
chkp_opt=" \
--checkpoint-activations \
--checkpoint-num-layers ${chkp_layers}"
if [ "${PA}" = "true" ]; then
chkp_opt="${chkp_opt} \
--partition-activations"
fi
if [ "${PA_CPU}" = "true" ]; then
chkp_opt="${chkp_opt} \
--checkpoint-in-cpu"
fi
if [ "${SYNCHRONIZE}" = "true" ]; then
chkp_opt="${chkp_opt} \
--synchronize-each-layer"
fi
if [ "${CC}" = "true" ]; then
chkp_opt="${chkp_opt} \
--contigious-checkpointing"
fi
if [ "${PROFILE}" = "true" ]; then
chkp_opt="${chkp_opt} \
--profile-backward"
fi
full_options="${gpt_options} ${deepspeed_options} ${chkp_opt}"
run_cmd="deepspeed pretrain_gpt2.py $@ ${full_options}"
echo ${run_cmd}
eval ${run_cmd}
set +x
|
<filename>spec/fastbill_spec.rb
require 'spec_helper'
describe Fastbill do
# puts MY_CONFIG['test']
# pending
end
|
import numpy as np
def mandelbrot(x, y):
X, Y = np.meshgrid(x, y)
C = X + 1j*Y
Z = np.zeros_like(C, dtype=complex)
M = np.full(C.shape, True, dtype=bool)
for _ in range(30):
Z = Z**2 + C
M = M & (np.abs(Z) < 2)
return M
|
<gh_stars>1-10
'use strict';
const Command = require("../../structure/Command.js");
const moment = require('moment')
class Userinfo extends Command {
constructor() {
super({
name: 'userinfo',
category: 'utils',
description: 'Cette commande donne des informations sur des utilisateurs !',
usage: 'userinfo [@user]',
example: ['userinfo', 'userinfo @user'],
aliases: ['ui']
});
}
async run(client, message, args) {
const membre = message.mentions[0] || client.users.find(u => u.id === args[1]) || message.author ;
// if (!membre) { return message.channel.send('Veuillez mentionner un utilisateur !'); }
await message.channel.createMessage({
embed: {
color: client.maincolor,
title: `Statistiques du l'utilisateur **${membre.username}#${membre.discriminator}**`,
thumbnail: {
url: membre.avatarURL
},
fields: [
{
name: 'ID :',
value: membre.id
},
{
name: 'Créé le :',
value: `${moment(membre.createdAt).format('MMMM Do YYYY, h:mm:ss a')}`
},
{
name: "Pub approuvée:",
value: "En cours de calcul..."
},
{
name: "Pub rejetée",
value: "En cours de calcul..."
},
{
name: "Premium:",
value: client.userdb.get(membre.id).rank === 1 ? 'Oui' : "Non"
}
],
footer: {
text: `Informations de l'utilisateur ${membre.username}`
}
}
}).then(msg => {
let c = 0;
let y = 0;
const a = client.ads.array();
for(const x of a) {
if(x.author.id === membre.id) {
if(x.status === 1) {
c++;
} else if(x.status === 2) {
y++;
}
}
}
msg.embeds[0].fields[2].value = c;
msg.embeds[0].fields[3].value = y;
msg.edit({
embed: msg.embeds[0]
})
})
}
}
module.exports = new Userinfo();
|
package com.huatuo.activity.personal;
import org.json.JSONObject;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.huatuo.R;
import com.huatuo.activity.login.LoginActivity;
import com.huatuo.base.BaseFragment;
import com.huatuo.base.MyApplication;
import com.huatuo.custom_widget.CustomDialog;
import com.huatuo.dictionary.MsgId;
import com.huatuo.net.thread.GetUserInfo;
import com.huatuo.util.CallUtil;
import com.huatuo.util.CommonUtil;
import com.huatuo.util.Constants;
import com.huatuo.util.DialogUtils;
import com.huatuo.util.NumFormatUtil;
import com.huatuo.util.UmengEventUtil;
import com.nostra13.universalimageloader.core.ImageLoader;
public class FragmentPersonalCenter extends BaseFragment {
private Context mContext;
private Handler mHandler;
private View rootLayout;
private RelativeLayout rl_userInfo, rl_login;
private LinearLayout ll_address, ll_WoDeDingDan, ll_JinE, ll_YouHuiDuiHuan, ll_ChangJianWenTi, ll_GuanYuHuaTuo, ll_XiaoFeiMa, ll_WoDeShouCang;
private Button btn_login;
private ImageView /* iv_kefu, */iv_icon;
private TextView tv_userMobile, tv_userName, tvYuE, tv_zhuxiao, tv_youhuiduihuan_1, tv_xiaofeima_1;
private GetUserInfo getUserInfo;
private JSONObject userObj;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootLayout = inflater.inflate(R.layout.fragment_personal_center, container, false);
mContext = getActivity();
mHandler = new MyHandler();
initWidget();
bindListener();
CommonUtil.log("-----------------onCreateView--------------------------");
// initData();
return rootLayout;
}
@Override
public void onResume() {
super.onResume();
if (MyApplication.getLoginFlag()) {
getUserInfo();
rl_userInfo.setVisibility(View.VISIBLE);
tv_zhuxiao.setVisibility(View.VISIBLE);
tv_youhuiduihuan_1.setVisibility(View.VISIBLE);
tv_xiaofeima_1.setVisibility(View.VISIBLE);
rl_login.setVisibility(View.GONE);
JSONObject u = MyApplication.getUserJSON();
if (!("").equals(u) && null != u) {
String a = u.optString("mobile", "XXXXXXXXXXX");
CommonUtil.logE("usejson---------->" + u);
if (a.length() >= 11) {
tv_userMobile.setText(a.replaceFirst(a.substring(3, 7), "****"));
}
ll_JinE.setVisibility(View.VISIBLE);
}
} else {
rl_userInfo.setVisibility(View.GONE);
tv_zhuxiao.setVisibility(View.GONE);
tv_youhuiduihuan_1.setVisibility(View.GONE);
tv_xiaofeima_1.setVisibility(View.GONE);
rl_login.setVisibility(View.VISIBLE);
}
}
@Override
public void onDetach() {
// TODO Auto-generated method stub
super.onDetach();
// LogUtil.e("deesha", "HelpFragment onDetach");
}
/**
* 在这里获取到每个需要用到的控件的实例,并给它们设置好必要的点击事件。
*
*/
private void initWidget() {
rl_userInfo = (RelativeLayout) rootLayout.findViewById(R.id.rl_userInfo);
rl_login = (RelativeLayout) rootLayout.findViewById(R.id.rl_login);
ll_address = (LinearLayout) rootLayout.findViewById(R.id.ll_dizhi);
ll_WoDeDingDan = (LinearLayout) rootLayout.findViewById(R.id.ll_WoDeDingDan);
ll_YouHuiDuiHuan = (LinearLayout) rootLayout.findViewById(R.id.ll_YouHuiDuiHuan);
ll_ChangJianWenTi = (LinearLayout) rootLayout.findViewById(R.id.ll_ChangJianWenTi);
ll_GuanYuHuaTuo = (LinearLayout) rootLayout.findViewById(R.id.ll_GuanYuHuaTuo);
ll_XiaoFeiMa = (LinearLayout) rootLayout.findViewById(R.id.ll_XiaoFeiMa);
ll_WoDeShouCang = (LinearLayout) rootLayout.findViewById(R.id.ll_WoDeShouCang);
ll_JinE = (LinearLayout) rootLayout.findViewById(R.id.ll_JinE);
tv_zhuxiao = (TextView) rootLayout.findViewById(R.id.tv_zhuxiao);
// tv_zhuxiao.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);//设置下划线
tv_userName = (TextView) rl_userInfo.findViewById(R.id.tv_userName);
tv_userMobile = (TextView) rl_userInfo.findViewById(R.id.tv_userMobile);
tvYuE = (TextView) rootLayout.findViewById(R.id.tvYuE);
tv_youhuiduihuan_1 = (TextView) rootLayout.findViewById(R.id.tv_youhuiduihuan_1);
tv_xiaofeima_1 = (TextView) rootLayout.findViewById(R.id.tv_xiaofeima_1);
// tvMingXi = (TextView) rootLayout.findViewById(R.id.tvMingXi);
// tvMingXi.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
// iv_kefu = (ImageView) rootLayout.findViewById(R.id.iv_kefu);
iv_icon = (ImageView) rootLayout.findViewById(R.id.iv_icon);
btn_login = (Button) rootLayout.findViewById(R.id.btn_login);
}
private void bindListener() {
MyOnClickListener myOnClickListener = new MyOnClickListener();
btn_login.setOnClickListener(myOnClickListener);
ll_address.setOnClickListener(myOnClickListener);
ll_WoDeDingDan.setOnClickListener(myOnClickListener);
tv_zhuxiao.setOnClickListener(myOnClickListener);
// ll_ZhangHuChongZhi.setOnClickListener(myOnClickListener);
ll_ChangJianWenTi.setOnClickListener(myOnClickListener);
ll_YouHuiDuiHuan.setOnClickListener(myOnClickListener);
ll_GuanYuHuaTuo.setOnClickListener(myOnClickListener);
ll_XiaoFeiMa.setOnClickListener(myOnClickListener);
ll_WoDeShouCang.setOnClickListener(myOnClickListener);
// iv_kefu.setOnClickListener(myOnClickListener);
// tvMingXi.setOnClickListener(myOnClickListener);
ll_JinE.setOnClickListener(myOnClickListener);
}
/**
* 是否注销:自定义Dialog
*/
private void showCustomDialog() {
CustomDialog.Builder builder = new CustomDialog.Builder(getActivity());
builder.setTitle("提示");
builder.setMessage("您确定要注销该账号吗?");
builder.setPositiveButton(getActivity().getResources().getString(R.string.common_confirm), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
// 设置你的操作事项
MyApplication.setLoginFlag(false);
rl_userInfo.setVisibility(View.GONE);
tv_zhuxiao.setVisibility(View.GONE);
rl_login.setVisibility(View.VISIBLE);
tvYuE.setText("¥0");
}
});
builder.setNegativeButton(getActivity().getResources().getString(R.string.common_cancel), new android.content.DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.create().show();
}
/**
* 打电话
*/
private void call() {
CallUtil.showCallDialog(mContext, Constants.phoneNumber);
}
class MyOnClickListener implements OnClickListener {
@Override
public void onClick(View view) {
// TODO Auto-generated method stub
Intent intent = null;
switch (view.getId()) {
case R.id.ll_YouHuiDuiHuan://优惠券
if (!MyApplication.getLoginFlag()) {
DialogUtils.showToastMsg(mContext, "你尚未登录,请登录!", Toast.LENGTH_SHORT);
return;
}
UmengEventUtil.my_coupon(mContext);
intent = new Intent();
intent.setClass(mContext, ExchangeActivity.class);
startActivity(intent);
break;
case R.id.ll_GuanYuHuaTuo://关于华佗
UmengEventUtil.my_aboutus(mContext);
intent = new Intent();
intent.setClass(mContext, AboutHuatuoActivity.class);
startActivity(intent);
break;
case R.id.ll_XiaoFeiMa://消费吗
if (!MyApplication.getLoginFlag()) {
DialogUtils.showToastMsg(mContext, "你尚未登录,请登录!", Toast.LENGTH_SHORT);
return;
}
UmengEventUtil.my_code(mContext);
intent = new Intent();
intent.setClass(mContext, XiaoFeiMaActivity.class);
startActivity(intent);
break;
case R.id.btn_login:
intent = new Intent();
intent.setClass(mContext, LoginActivity.class);
startActivity(intent);
break;
case R.id.ll_dizhi://我的地址
if (!MyApplication.getLoginFlag()) {
DialogUtils.showToastMsg(mContext, "你尚未登录,请登录!", Toast.LENGTH_SHORT);
return;
}
UmengEventUtil.my_adress(mContext);
intent = new Intent();
intent.setClass(mContext, AddressListActivity.class);
startActivity(intent);
break;
case R.id.ll_WoDeDingDan://我的订单
// CommonUtil.saveBooleanOfSharedPreferences(mContext,
// "ISSTORE", false);
if (!MyApplication.getLoginFlag()) {
DialogUtils.showToastMsg(mContext, "你尚未登录,请登录!", Toast.LENGTH_SHORT);
return;
}
intent = new Intent();
intent.setAction(Constants.REFRESH_CHANGETAB);
intent.putExtra("tabIndex", 3);
mContext.sendBroadcast(intent);
// intent = new Intent();
// intent.setClass(mContext, MyOrderListActivity.class);
// startActivity(intent);
break;
case R.id.tv_zhuxiao:// 注销账号
UmengEventUtil.my_logout(mContext);
showCustomDialog();
break;
case R.id.ll_JinE:
if (!MyApplication.getLoginFlag()) {
DialogUtils.showToastMsg(mContext, "你尚未登录,请登录!", Toast.LENGTH_SHORT);
return;
}
intent = new Intent();
intent.setClass(mContext, AccountDetailActivity.class);
startActivity(intent);
break;
case R.id.ll_WoDeShouCang:
if (!MyApplication.getLoginFlag()) {
DialogUtils.showToastMsg(mContext, "你尚未登录,请登录!", Toast.LENGTH_SHORT);
return;
}
UmengEventUtil.my_collect(mContext);
intent = new Intent();
intent.setClass(mContext, Collect_ListActivity.class);
startActivity(intent);
break;
// case R.id.tvMingXi:
// if (!MyApplication.getLoginFlag()) {
// DialogUtils.showToastMsg(mContext, "你尚未登录,请登录!",
// Toast.LENGTH_SHORT);
// return;
// }
// intent = new Intent();
// intent.setClass(mContext, AccountDetailActivity.class);
// startActivity(intent);
// break;
// case R.id.ll_ZhangHuChongZhi:
// if (!MyApplication.getLoginFlag()) {
// DialogUtils.showToastMsg(mContext, "你尚未登录,请登录!",
// Toast.LENGTH_SHORT);
// return;
// }
// intent = new Intent();
// intent.setClass(mContext, ChongZhiActivity.class);
// startActivity(intent);
// break;
case R.id.ll_ChangJianWenTi://常见问题
UmengEventUtil.my_qa(mContext);
intent = new Intent();
intent.setClass(mContext, ProblemActivity.class);
startActivity(intent);
break;
// case R.id.iv_kefu:
// call();
// break;
default:
break;
}
}
}
private void getUserInfo() {
showCustomCircleProgressDialog(null, mContext.getResources().getString(R.string.common_toast_net_prompt_submit));
getUserInfo = new GetUserInfo(mContext, mHandler);
Thread thread = new Thread(getUserInfo);
thread.start();
}
class MyHandler extends Handler {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MsgId.DOWN_DATA_S:
closeCustomCircleProgressDialog();
userObj = getUserInfo.getUserJson();
if (!("").equals(userObj) && null != userObj) {
tvYuE.setText("¥" + NumFormatUtil.centFormatYuanTodouble(userObj.optString("deposit", " ")));
String couponCount = userObj.optString("couponCount", "");
String exchangeCodeCount = userObj.optString("exchangeCodeCount", "");
ImageLoader.getInstance().displayImage(userObj.optString("userIcons", ""), iv_icon);
MyApplication.setUserJSON(userObj);
String userName = userObj.optString("name", "");
if ("未知昵称".equals(userName) || ("").equals(userName)) {
tv_userName.setVisibility(View.GONE);
} else {
tv_userName.setText(userName);
}
// 是否显示优惠券
if (!TextUtils.isEmpty(couponCount) && !couponCount.equals("0")) {
tv_youhuiduihuan_1.setText("您有" + couponCount + "张优惠券");
} else {
tv_youhuiduihuan_1.setText("");
}
// 是否显示消费码个数
if (!TextUtils.isEmpty(exchangeCodeCount) && !exchangeCodeCount.equals("0")) {
tv_xiaofeima_1.setText("待消费" + exchangeCodeCount + "个");
} else {
tv_xiaofeima_1.setText("");
}
}
break;
case MsgId.DOWN_DATA_F:
closeCustomCircleProgressDialog();
DialogUtils.showToastMsg(mContext, mContext.getResources().getString(R.string.common_toast_net_down_data_fail), Toast.LENGTH_SHORT);
break;
case MsgId.NET_NOT_CONNECT:
setCustomDialog(mContext.getResources().getString(R.string.common_toast_net_not_connect), true);
break;
default:
break;
}
}
}
}
|
package com.telpoo.frame.utils;
public class Cons {
public class Defi {
public static final String SPR_GET_FALL = "get reference fall";
public static final String SPR_NAME = "TAG_FM_TEST";
}
public static final String urlCheckApp="http://vilandsoft.com/api/mobile/getsetting.php?app_id=";
public class Id{
public static final int dialogSupport_ok = 12;
public static final int dialogSupport_cancel = 13;
public static final int root_layout = 14;
public static final int dialogSupport_title = 15;
}
public interface NetConfig1 {
public static final int FILE_BUFFER_SIZE = 8192;
public static final int PAGE_SIZE = 5;
public final static int NUMBER_OF_RETRY = 3;
public static final int CONNECTION_TIMEOUT = 15000;
public static final int SO_TIMEOUT = 15000;
public static final String CONTENT_TYPE = "UTF-8";
public final String AUTHORIZATION_TYPE = null;
public static final int CODE_SUCCESS = 0;
public static final int CODE_FAIL = -1;
public static final String CODE = "ok";
public static final String MESSAGE = "message";
}
public class Spr {
public static final String KEY_PASS_SAVE = "KEY_PASS_SAVE";
public static final String KEY_USER_SAVE = "KEY_USER_SAVE";
public static final String SAVE_LOGIN = "save_login";
public static final String KEY_TICK_MENU = "KEY_TICK_MENU";
public static final String KEY_PHONE = "KEY_PHONE";
}
}
|
package uk.org.ulcompsoc.ld32.util;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import uk.org.ulcompsoc.ld32.components.EntityLink;
import uk.org.ulcompsoc.ld32.components.Position;
import uk.org.ulcompsoc.ld32.components.Renderable;
import com.badlogic.ashley.core.Engine;
import com.badlogic.ashley.core.Entity;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.utils.Disposable;
public class TextureManager implements Disposable {
public final List<Texture> textures = new ArrayList<Texture>();
public final Map<TextureName, Texture> nameMap = new HashMap<TextureName, Texture>();
public final Map<TextureName, TextureRegion[]> animationRegionMap = new HashMap<TextureName, TextureRegion[]>();
public final Map<Character, TextureRegion> mapOfChars = new HashMap<Character, TextureRegion>();
public TextureManager() {
}
public void load() {
for (final TextureName texName : TextureName.values()) {
final FileHandle handle = Gdx.files.internal(texName.assetName);
final Texture texture = new Texture(handle);
textures.add(texture);
nameMap.put(texName, texture);
if (texName.isAnimated) {
animationRegionMap.put(texName,
TextureRegion.split(texture, texName.frameWidth, texName.frameHeight)[0]);
}
}
fillCharTextures();
}
private void fillCharTextures() {
final TextureRegion[] temp = animationRegionMap.get(TextureName.FONT);
for (int i = 0; i < 25; ++i) {
mapOfChars.put((char) ('A' + i), temp[i]);
}
for (int i = 0, j = 26; i < 25; ++i, ++j) {
mapOfChars.put((char) ('a' + i), temp[j]);
}
for (int i = 0, j = 26 * 2; i < 9; ++i, ++j) {
mapOfChars.put((char) ('1' + i), temp[j]);
}
final int zeroPos = 26 * 2 + 9;
mapOfChars.put('0', temp[zeroPos + 0]);
mapOfChars.put('-', temp[zeroPos + 1]);
mapOfChars.put('+', temp[zeroPos + 2]);
mapOfChars.put('(', temp[zeroPos + 3]);
mapOfChars.put(')', temp[zeroPos + 4]);
mapOfChars.put('!', temp[zeroPos + 5]);
mapOfChars.put('?', temp[zeroPos + 6]);
mapOfChars.put('.', temp[zeroPos + 7]);
mapOfChars.put(' ', temp[0]); // will be drawn with 0 alpha
}
public Entity makeWord(Engine engine, String str, int x, int y) {
return makeWord(engine, str, Color.BLACK, x, y);
}
public Entity makeWord(Engine engine, String str, Color color, int x, int y) {
Entity head = null;
final Entity[] rest = new Entity[str.length() - 1];
for (int i = 0; i < str.length(); ++i) {
final char c = str.charAt(i);
if (!mapOfChars.containsKey(c)) {
throw new IllegalArgumentException("Can't use character \"" + c + "\" in TextureManager.makeWord");
}
final Entity e = new Entity();
final TextureRegion region = new TextureRegion(mapOfChars.get(c));
final Renderable r = new Renderable(region).setScale(0.25f);
final Color col = color.cpy();
if (c == ' ') {
col.a = 0.0f;
}
r.setColor(col);
e.add(r);
e.add(Position.fromEuclidean(x + i * r.getWidth(), y));
if (i == 0) {
head = e;
} else {
rest[i - 1] = e;
}
engine.addEntity(e);
}
return head.add(new EntityLink(rest));
}
@Override
public void dispose() {
animationRegionMap.clear();
nameMap.clear();
for (final Texture t : textures) {
t.dispose();
}
textures.clear();
}
/*
* public Entity[] generateWord(String characters, float x, float y){ float
* xValue = x; float yValue = y; Entity[] toReturn = new
* Entity[characters.length()]; while(!characters.equals("")){ char tempChar
* = characters.charAt(0); characters = characters.substring(1); Entity temp
* = new Entity(); temp.add(Position.fromEuclidean(xValue, yValue));
* temp.add(component) } }
*/
}
|
parallel --jobs 6 < ./results/exp_node/run-3/sea_mem_4n_6t_6d_1000f_617m_10i/jobs/jobs_n0.txt
|
/*
* Copyright (C) 2012 Atlassian
*
* 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.atlassian.jira.tests;
import com.atlassian.jira.pageobjects.JiraTestedProduct;
import com.atlassian.jira.testkit.client.Backdoor;
import com.atlassian.jira.tests.rules.DirtyWarningTerminatorRule;
import com.atlassian.jira.tests.rules.MaximizeWindow;
import com.atlassian.jira.tests.rules.OnboardingRule;
import com.atlassian.jira.tests.rules.WebDriverScreenshot;
import com.atlassian.pageobjects.PageBinder;
import org.junit.ClassRule;
import org.junit.Rule;
public abstract class TestBase {
@Rule
public MaximizeWindow maximizeWindow = new MaximizeWindow(jira());
@Rule
public WebDriverScreenshot $screenshot = new WebDriverScreenshot(jira());
@Rule
public DirtyWarningTerminatorRule dirtyWarning = new DirtyWarningTerminatorRule(jira());
@Rule
public OnboardingRule onboardingRule = new OnboardingRule(jira());
@ClassRule
public static FuncTestHelper funcTestHelper = new FuncTestHelper();
@ClassRule
public static JiraTestedProductHelper productHelper = new JiraTestedProductHelper();
protected static JiraTestedProduct jira() {
return productHelper.jira();
}
protected static PageBinder pageBinder() {
return jira().getPageBinder();
}
protected static Backdoor backdoor() {
return funcTestHelper.backdoor;
}
}
|
/**
* @author <NAME> / https://github.com/Leeft
*/
import MapGeometry from '../map-geometry';
import JumpPoint from '../../jump-point';
import LineSegments from './line-segments';
import config from '../../config';
import THREE from 'three';
//const MATERIALS = {
// NORMAL: new THREE.LineBasicMaterial({
// color: 0xFFFFFF,
// linewidth: 2,
// vertexColors: true,
// }),
// UNDISC: new THREE.LineDashedMaterial({
// color: 0xFFFFFF,
// dashSize: 0.75,
// gapSize: 0.75,
// linewidth: 2,
// vertexColors: true,
// }),
// UNCONF: new THREE.LineDashedMaterial({
// color: 0xFFFFFF,
// dashSize: 2,
// gapSize: 2,
// linewidth: 2,
// vertexColors: true,
// }),
//};
//
//const DEFAULT_MATERIAL = MATERIALS.UNCONF;
class JumpPoints extends MapGeometry {
get mesh () {
if ( this._mesh ) {
return this._mesh;
}
const jumpLines = new LineSegments();
this.allSystems.forEach( system => {
system.jumpPoints.forEach( jumpPoint => {
if ( ! jumpPoint.drawn )
{
// TODO: Maybe this can be done more efficiently?
const sourceVec = jumpPoint.source.position.clone().sub( jumpPoint.destination.position );
sourceVec.setLength( sourceVec.length() - ( 3 * config.renderScale * jumpPoint.source.scale ) );
sourceVec.add( jumpPoint.destination.position );
// TODO: Maybe this can be done more efficiently?
const destVec = jumpPoint.destination.position.clone().sub( jumpPoint.source.position );
destVec.setLength( destVec.length() - ( 3 * config.renderScale * jumpPoint.destination.scale ) );
destVec.add( jumpPoint.source.position );
jumpLines.addColoredLine(
sourceVec, jumpPoint.source.faction.lineColor,
destVec, jumpPoint.destination.faction.lineColor,
);
jumpPoint.setDrawn();
const oppositeJumppoint = jumpPoint.getOppositeJumppoint();
if ( oppositeJumppoint instanceof JumpPoint ) {
oppositeJumppoint.setDrawn();
}
}
});
});
this._mesh = jumpLines.mesh();
// Set the 2d/3d tween callback
this._mesh.userData.scaleY = JumpPoints.scaleY;
JumpPoints.scaleY( this._mesh, this.initialScale );
return this._mesh;
}
static scaleY ( mesh, scaleY ) {
mesh.scale.y = scaleY;
mesh.updateMatrix();
}
//getMaterial () {
// if ( this.type in MATERIALS ) {
// return MATERIALS[ this.type ];
// } else {
// return DEFAULT_MATERIAL;
// }
//}
}
export default JumpPoints;
|
/*******************************************************************************
* Copyright Searchbox - http://www.searchbox.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.searchbox.core.search.query;
import com.searchbox.core.SearchAttribute;
import com.searchbox.core.SearchComponent;
import com.searchbox.core.SearchCondition;
import com.searchbox.core.SearchConverter;
import com.searchbox.core.SearchElement;
import com.searchbox.core.search.AbstractSearchCondition;
import com.searchbox.core.search.ConditionalSearchElement;
@SearchComponent
public class MoreLikeThisQuery extends
ConditionalSearchElement<QueryCondition> {
private String query;
@SearchAttribute
private String id;
private Long hitCount = 0l;
public MoreLikeThisQuery() {
super("mlt component", SearchElement.Type.QUERY);
}
public MoreLikeThisQuery(String query) {
super("mlt component", SearchElement.Type.QUERY);
this.query = query;
}
public String getQuery() {
return query;
}
public void setQuery(String query) {
this.query = query;
}
@Override
public QueryCondition getSearchCondition() {
return new QueryCondition(query);
}
/**
* @param l
* the hitCount to set
*/
public void setHitCount(Long l) {
this.hitCount = l;
}
@Override
public void mergeSearchCondition(AbstractSearchCondition condition) {
if (QueryCondition.class.equals(condition.getClass())) {
this.query = ((QueryCondition) condition).getQuery();
}
}
@Override
public Class<?> getConditionClass() {
return QueryCondition.class;
}
}
|
#!/bin/bash
sudo cd /opt
git clone https://github.com/gohugoio/hugo.git
cd hugo
go install --tags extend
|
#!/usr/bin/env bash
pushd "$(dirname "$0")" > /dev/null || exit
cd ..
dart ./util/lib/main.dart "$@"
popd > /dev/null || exit
|
module.exports = (req, res, next) => {
const matchingToken = (req.headers || {})['x-api-key'];
const validToken = process.env.API_TOKEN;
if (!validToken) throw new Error('Internal Server Error');
if (matchingToken !== validToken) {
res.status(401).json({});
} else {
next();
}
};
|
#!/usr/bin/env bash
set -e
sbt ++${TRAVIS_SCALA_VERSION} publishM2 publishLocal
# Downloads maven schema file which will be used to validate the generated pom file
wget -c http://maven.apache.org/xsd/maven-4.0.0.xsd
# Use xmllint to validate the generated pom.xml
find . -name *.pom -exec xmllint --noout -schema maven-4.0.0.xsd {} \;
|
<gh_stars>0
/*
* Licensed to the OpenAirInterface (OAI) Software Alliance under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The OpenAirInterface Software Alliance 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.
*-------------------------------------------------------------------------------
* For more information about the OpenAirInterface (OAI) Software Alliance:
* <EMAIL>
*/
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#if HAVE_CONFIG_H
# include "config.h"
#endif
#include <freeDiameter/freeDiameter-host.h>
#include <freeDiameter/libfdcore.h>
#include "intertask_interface.h"
#include "s6a_defs.h"
#include "s6a_messages.h"
#include "common_types.h"
#include "assertions.h"
#include "msc.h"
#include "log.h"
static int gnutls_log_level = 9;
struct session_handler *ts_sess_hdl;
s6a_fd_cnf_t s6a_fd_cnf;
void *s6a_thread (void *args);
static void fd_gnutls_debug (
int level,
const char *str);
static void s6a_exit(void);
//------------------------------------------------------------------------------
static void fd_gnutls_debug (
int loglevel,
const char *str)
{
OAILOG_EXTERNAL (loglevel, LOG_S6A, "[GTLS] %s", str);
}
//------------------------------------------------------------------------------
// callback for freeDiameter logs
static void oai_fd_logger(int loglevel, const char * format, va_list args)
{
#define FD_LOG_MAX_MESSAGE_LENGTH 8192
char buffer[FD_LOG_MAX_MESSAGE_LENGTH];
int rv = 0;
rv = vsnprintf (buffer, 8192, format, args);
if ((0 > rv) || ((FD_LOG_MAX_MESSAGE_LENGTH) < rv)) {
return;
}
OAILOG_EXTERNAL (loglevel, LOG_S6A, "%s\n", buffer);
}
//------------------------------------------------------------------------------
void *s6a_thread (void *args)
{
itti_mark_task_ready (TASK_S6A);
OAILOG_START_USE ();
MSC_START_USE ();
while (1) {
MessageDef *received_message_p = NULL;
/*
* Trying to fetch a message from the message queue.
* * If the queue is empty, this function will block till a
* * message is sent to the task.
*/
itti_receive_msg (TASK_S6A, &received_message_p);
DevAssert (received_message_p );
switch (ITTI_MSG_ID (received_message_p)) {
case S6A_UPDATE_LOCATION_REQ:{
s6a_generate_update_location (&received_message_p->ittiMsg.s6a_update_location_req);
}
break;
case S6A_AUTH_INFO_REQ:{
s6a_generate_authentication_info_req (&received_message_p->ittiMsg.s6a_auth_info_req);
}
break;
case TERMINATE_MESSAGE:{
s6a_exit();
itti_exit_task ();
}
break;
default:{
OAILOG_DEBUG (LOG_S6A, "Unkwnon message ID %d: %s\n", ITTI_MSG_ID (received_message_p), ITTI_MSG_NAME (received_message_p));
}
break;
}
itti_free (ITTI_MSG_ORIGIN_ID (received_message_p), received_message_p);
received_message_p = NULL;
}
return NULL;
}
//------------------------------------------------------------------------------
int s6a_init (
const mme_config_t * mme_config_p)
{
int ret;
OAILOG_DEBUG (LOG_S6A, "Initializing S6a interface\n");
memset (&s6a_fd_cnf, 0, sizeof (s6a_fd_cnf_t));
/*
* if (strcmp(fd_core_version(), free_wrapper_DIAMETER_MINIMUM_VERSION) ) {
* S6A_ERROR("Freediameter version %s found, expecting %s\n", fd_core_version(),
* free_wrapper_DIAMETER_MINIMUM_VERSION);
* return RETURNerror;
* } else {
* S6A_DEBUG("Freediameter version %s\n", fd_core_version());
* }
*/
/*
* Initializing freeDiameter logger
*/
ret = fd_log_handler_register(oai_fd_logger);
if (ret) {
OAILOG_ERROR (LOG_S6A, "An error occurred during freeDiameter log handler registration: %d\n", ret);
return ret;
} else {
OAILOG_DEBUG (LOG_S6A, "Initializing freeDiameter log handler done\n");
}
/*
* Initializing freeDiameter core
*/
OAILOG_DEBUG (LOG_S6A, "Initializing freeDiameter core...\n");
ret = fd_core_initialize ();
if (ret) {
OAILOG_ERROR (LOG_S6A, "An error occurred during freeDiameter core library initialization: %d\n", ret);
return ret;
} else {
OAILOG_DEBUG (LOG_S6A, "Initializing freeDiameter core done\n");
}
OAILOG_DEBUG (LOG_S6A, "Default ext path: %s\n", DEFAULT_EXTENSIONS_PATH);
ret = fd_core_parseconf (bdata(mme_config_p->s6a_config.conf_file));
if (ret) {
OAILOG_ERROR (LOG_S6A, "An error occurred during fd_core_parseconf file : %s.\n", bdata(mme_config_p->s6a_config.conf_file));
return ret;
} else {
OAILOG_DEBUG (LOG_S6A, "fd_core_parseconf done\n");
}
/*
* Set gnutls debug level ?
*/
if (gnutls_log_level) {
gnutls_global_set_log_function ((gnutls_log_func) fd_gnutls_debug);
gnutls_global_set_log_level (gnutls_log_level);
OAILOG_DEBUG (LOG_S6A, "Enabled GNUTLS debug at level %d\n", gnutls_log_level);
}
/*
* Starting freeDiameter core
*/
ret = fd_core_start ();
if (ret) {
OAILOG_ERROR (LOG_S6A, "An error occurred during freeDiameter core library start\n");
return ret;
} else {
OAILOG_DEBUG (LOG_S6A, "fd_core_start done\n");
}
ret = fd_core_waitstartcomplete ();
if (ret) {
OAILOG_ERROR (LOG_S6A, "An error occurred during freeDiameter core library start\n");
return ret;
} else {
OAILOG_DEBUG (LOG_S6A, "fd_core_waitstartcomplete done\n");
}
ret = s6a_fd_init_dict_objs ();
if (ret) {
OAILOG_ERROR (LOG_S6A, "An error occurred during s6a_fd_init_dict_objs.\n");
return ret;
} else {
OAILOG_DEBUG (LOG_S6A, "s6a_fd_init_dict_objs done\n");
}
/*
* Trying to connect to peers
*/
CHECK_FCT (s6a_fd_new_peer ());
if (itti_create_task (TASK_S6A, &s6a_thread, NULL) < 0) {
OAILOG_ERROR (LOG_S6A, "s6a create task\n");
return RETURNerror;
}
OAILOG_DEBUG (LOG_S6A, "Initializing S6a interface: DONE\n");
return RETURNok;
}
//------------------------------------------------------------------------------
static void s6a_exit(void)
{
int rv = RETURNok;
/* Initialize shutdown of the framework */
rv = fd_core_shutdown();
if (rv) {
OAI_FPRINTF_ERR ("An error occurred during fd_core_shutdown().\n");
}
/* Wait for the shutdown to be complete -- this should always be called after fd_core_shutdown */
rv = fd_core_wait_shutdown_complete();
if (rv) {
OAI_FPRINTF_ERR ("An error occurred during fd_core_wait_shutdown_complete().\n");
}
}
|
package com.twitter.finatra.json.tests.internal.caseclass.validation
import com.twitter.finatra.json.FinatraObjectMapper
import com.twitter.finatra.json.internal.caseclass.exceptions.CaseClassValidationException.PropertyPath
import com.twitter.finatra.json.internal.caseclass.exceptions.{CaseClassMappingException, CaseClassValidationException}
import com.twitter.finatra.json.tests.internal.CarMake
import com.twitter.finatra.json.tests.internal.caseclass.validation.domain.{Address, Car, Person}
import com.twitter.finatra.validation.ErrorCode
import com.twitter.finatra.validation.ValidationResult.Invalid
import com.twitter.inject.Test
import org.joda.time.DateTime
class CaseClassValidationTest extends Test {
val now = new DateTime("2015-04-09T05:17:15Z")
val mapper = FinatraObjectMapper.create()
val baseCar = Car(
id = 1,
make = CarMake.Ford,
model = "Model-T",
year = 2000,
owners = Seq(),
numDoors = 2,
manual = true,
ownershipStart = now,
ownershipEnd = now.plusMinutes(1),
warrantyStart = Some(now),
warrantyEnd = Some(now.plusHours(1)))
"class and field level validations" should {
"success" in {
parseCar(baseCar)
}
"top-level failed validations" in {
val parseError = intercept[CaseClassMappingException] {
parseCar(baseCar.copy(id = 2, year = 1910))
}
parseError should equal(CaseClassMappingException(
Set(CaseClassValidationException(PropertyPath.leaf("year"), Invalid("[1910] is not greater than or equal to 2000", ErrorCode.ValueTooSmall(2000, 1910))))))
}
"nested failed validations" in {
val owners = Seq(
Person(
name = "<NAME>",
dob = Some(DateTime.now),
address = Some(Address(
street = Some(""), // invalid
city = "", // invalid
state = "FL")))
)
val car = baseCar.copy(owners = owners)
val parseError = intercept[CaseClassMappingException] {
parseCar(car)
}
parseError should equal(CaseClassMappingException(
Set(
CaseClassValidationException(PropertyPath.leaf("city").withParent("address").withParent("owners"), Invalid("cannot be empty", ErrorCode.ValueCannotBeEmpty)),
CaseClassValidationException(PropertyPath.leaf("street").withParent("address").withParent("owners"), Invalid("cannot be empty", ErrorCode.ValueCannotBeEmpty))
)))
}
"nested method validations" in {
val owners = Seq(
Person(
name = "<NAME>",
dob = Some(DateTime.now),
address = Some(Address(
city = "pyongyang",
state = "KP" /* invalid */)))
)
val car = baseCar.copy(owners = owners)
val parseError = intercept[CaseClassMappingException] {
parseCar(car)
}
parseError should equal(CaseClassMappingException(
Set(
CaseClassValidationException(PropertyPath.leaf("address").withParent("owners"), Invalid("state must be one of [CA, MD, WI]")))))
parseError.errors.map(_.getMessage) should equal(Seq("owners.address: state must be one of [CA, MD, WI]"))
}
"end before start" in {
intercept[CaseClassMappingException] {
parseCar(baseCar.copy(
ownershipStart = baseCar.ownershipEnd,
ownershipEnd = baseCar.ownershipStart))
} should equal(
CaseClassMappingException(
Set(
CaseClassValidationException(
PropertyPath.empty,
Invalid("ownershipEnd [2015-04-09T05:17:15.000Z] must be after ownershipStart [2015-04-09T05:18:15.000Z]")))))
}
"optional end before start" in {
intercept[CaseClassMappingException] {
parseCar(baseCar.copy(
warrantyStart = baseCar.warrantyEnd,
warrantyEnd = baseCar.warrantyStart))
} should equal(
CaseClassMappingException(
Set(
CaseClassValidationException(
PropertyPath.empty,
Invalid("warrantyEnd [2015-04-09T05:17:15.000Z] must be after warrantyStart [2015-04-09T06:17:15.000Z]")))))
}
"no start with end" in {
intercept[CaseClassMappingException] {
parseCar(baseCar.copy(
warrantyStart = None,
warrantyEnd = baseCar.warrantyEnd))
} should equal(
CaseClassMappingException(
Set(
CaseClassValidationException(
PropertyPath.empty,
Invalid("both warrantyStart and warrantyEnd are required for a valid range")))))
}
"start with end" in {
parseCar(baseCar)
}
"errors sorted by message" in {
val first = CaseClassValidationException(PropertyPath.empty, Invalid("123"))
val second = CaseClassValidationException(PropertyPath.empty, Invalid("aaa"))
val third = CaseClassValidationException(PropertyPath.leaf("bla"), Invalid("zzz"))
val fourth = CaseClassValidationException(PropertyPath.empty, Invalid("xxx"))
val unsorted = Set(third, second, fourth, first)
val expectedSorted = Seq(first, second, third, fourth)
CaseClassMappingException(unsorted).errors should equal(expectedSorted)
}
}
private def parseCar(car: Car): Car = {
mapper.parse[Car](
mapper.writeValueAsBytes(car))
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.