text stringlengths 1 1.05M |
|---|
/*
LedMatrixInfo.java
Firefly Luciferin, very fast Java Screen Capture software designed
for Glow Worm Luciferin firmware.
Copyright (C) 2020 - 2022 <NAME> (https://github.com/sblantipodi)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package org.dpsoftware.managers.dto;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
/**
* Information used to create LED Matrixes
*/
@Getter
@Setter
@NoArgsConstructor
public class LedMatrixInfo implements Cloneable {
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
int bottomRightLedOriginal;
int rightLedOriginal;
int topLedOriginal;
int leftLedOriginal;
int bottomLeftLedOriginal;
int bottomRowLedOriginal;
int screenWidth;
int screenHeight;
int bottomRightLed;
int rightLed;
int topLed;
int leftLed;
int bottomLeftLed;
int bottomRowLed;
String splitBottomRow;
String grabberTopBottom;
String grabberSide;
String gapTypeTopBottom;
String gapTypeSide;
int topBottomAreaHeight;
int sideAreaWidth;
int splitBottomMargin;
int cornerGapTopBottom;
int cornerGapSide;
int bottomLedDistance;
int groupBy;
int letterboxBorder;
int pillarboxBorder;
int minimumNumberOfLedsInARow;
int totaleNumOfLeds;
public LedMatrixInfo(int screenWidth, int screenHeight, int bottomRightLed, int rightLed, int topLed, int leftLed, int bottomLeftLed,
int bottomRowLed, String splitBottomRow, String grabberTopBottom, String grabberSide,
String gapTypeTopBottom, String gapTypeSide, int groupBy) {
this.screenWidth = screenWidth;
this.screenHeight = screenHeight;
this.bottomRightLed = bottomRightLed;
this.rightLed = rightLed;
this.topLed = topLed;
this.leftLed = leftLed;
this.bottomLeftLed = bottomLeftLed;
this.bottomRowLed = bottomRowLed;
this.splitBottomRow = splitBottomRow;
this.grabberTopBottom = grabberTopBottom;
this.grabberSide = grabberSide;
this.gapTypeTopBottom = gapTypeTopBottom;
this.gapTypeSide = gapTypeSide;
this.groupBy = groupBy;
}
}
|
import sys
class LibraryCatalog:
def __init__(self, file_path):
self.catalog = {}
try:
with open(file_path, 'r') as file:
for line in file:
key, value = line.strip().split(':')
self.catalog[key] = value
except FileNotFoundError:
print("Library catalog file not found")
except Exception:
print("Error occurred while reading the library catalog")
def get_library_entry(self, key):
if key in self.catalog:
return self.catalog[key]
else:
return "Library entry not found"
if __name__ == "__main__":
if len(sys.argv) < 3:
print("Usage: python library_catalog.py <file_path> <library_key>")
else:
file_path = sys.argv[1]
libKey = sys.argv[2]
catalog = LibraryCatalog(file_path)
print(catalog.get_library_entry(libKey)) |
#!/usr/bin/env bash
archive=$1
#create temp directory
temp=$(mktemp -d)
#extract file and put it in it's temp directory
tar -xzf "$archive" -C "$temp"
#capturing current directory
here=$(pwd)
#navigate to temp directory
#|| exit gives the option to exit if cd doesn't work
cd "$temp" || exit
#keeping the base name of the file
base=$(basename -s .tgz "$archive")
#searching through the extracted file to see which ones to delete
grep "DELETE ME!" -rl "$base" | xargs rm
#creating a new tar file
tar -zcf cleaned_"$archive" "$base"
#move new archive to cleaning directory
mv cleaned_"$archive" "$here"
#navigate to another directory and delete scratch directory since it's unneeded
cd "$here" || exit
rm -rf "$temp"
|
#!/bin/bash
#####################################################
# This script is used for Continuous Integration
#
# Run locally to verify before committing your code.
#
# Options:
# -z to run Flutter Analysis
# -a to run Android CI tasks.
# -i to run iOS CI tasks.
#####################################################
set -o pipefail
set -e
# get platforms
ANDROID=true
ANALYZE=true
IOS=true
# Parse arguments
OPTS=`getopt haiz $*`
if [ $? != 0 ] ; then echo "Failed parsing options." >&2 ; exit 1 ; fi
eval set -- "$OPTS"
while true; do
case "$1" in
-h ) echo -ne "-a to run Android CI tasks.\n-i to run iOS CI tasks.\n -z to run Flutter analysis tasks.\n Defaults to all. \n"; exit 0;;
-z ) ANALYZE=true;ANDROID=false;IOS=false;;
-a ) ANDROID=true;IOS=false;ANALYZE=false;;
-i ) IOS=true;ANDROID=false;ANALYZE=false;;
* ) break ;;
esac
shift
done
flutter packages get
# Flutter Analysis
if $ANALYZE; then
flutter analyze
# Perform publish dry run to ensure the package can be published
flutter pub pub publish --dry-run
fi
# Android
if $ANDROID ; then
cd example
# Build sample using flutter tool
flutter build apk --release
cd ..
fi
# iOS
if $IOS; then
cd example
if [ ! -f ios/AirshipConfig.plist ]; then
cp ios/AirshipConfig.plist.sample ios/AirshipConfig.plist
fi
flutter build ios --release --no-codesign
cd ..
fi |
#!/bin/bash
#
# 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.
#
# Copyright Clairvoyant 2017
PATH=/usr/bin:/usr/sbin:/bin:/sbin:/usr/local/bin
# Function to discover basic OS details.
discover_os() {
if command -v lsb_release >/dev/null; then
# CentOS, Ubuntu, RedHatEnterpriseServer, Debian, SUSE LINUX
# shellcheck disable=SC2034
OS=$(lsb_release -is)
# CentOS= 6.10, 7.2.1511, Ubuntu= 14.04, RHEL= 6.10, 7.5, SLES= 11
# shellcheck disable=SC2034
OSVER=$(lsb_release -rs)
# 7, 14
# shellcheck disable=SC2034
OSREL=$(echo "$OSVER" | awk -F. '{print $1}')
# Ubuntu= trusty, wheezy, CentOS= Final, RHEL= Santiago, Maipo, SLES= n/a
# shellcheck disable=SC2034
OSNAME=$(lsb_release -cs)
else
if [ -f /etc/redhat-release ]; then
if [ -f /etc/centos-release ]; then
# shellcheck disable=SC2034
OS=CentOS
# 7.5.1804.4.el7.centos, 6.10.el6.centos.12.3
# shellcheck disable=SC2034
OSVER=$(rpm -qf /etc/centos-release --qf='%{VERSION}.%{RELEASE}\n' | awk -F. '{print $1"."$2}')
# shellcheck disable=SC2034
OSREL=$(rpm -qf /etc/centos-release --qf='%{VERSION}\n')
else
# shellcheck disable=SC2034
OS=RedHatEnterpriseServer
# 7.5, 6Server
# shellcheck disable=SC2034
OSVER=$(rpm -qf /etc/redhat-release --qf='%{VERSION}\n')
if [ "$OSVER" == "6Server" ]; then
# shellcheck disable=SC2034
OSVER=$(rpm -qf /etc/redhat-release --qf='%{RELEASE}\n' | awk -F. '{print $1"."$2}')
# shellcheck disable=SC2034
OSNAME=Santiago
else
# shellcheck disable=SC2034
OSNAME=Maipo
fi
# shellcheck disable=SC2034
OSREL=$(echo "$OSVER" | awk -F. '{print $1}')
fi
elif [ -f /etc/SuSE-release ]; then
if grep -q "^SUSE Linux Enterprise Server" /etc/SuSE-release; then
# shellcheck disable=SC2034
OS="SUSE LINUX"
fi
# shellcheck disable=SC2034
OSVER=$(rpm -qf /etc/SuSE-release --qf='%{VERSION}\n' | awk -F. '{print $1}')
# shellcheck disable=SC2034
OSREL=$(rpm -qf /etc/SuSE-release --qf='%{VERSION}\n' | awk -F. '{print $1}')
# shellcheck disable=SC2034
OSNAME="n/a"
fi
fi
}
echo "********************************************************************************"
echo "*** $(basename "$0")"
echo "********************************************************************************"
# Check to see if we are on a supported OS.
discover_os
if [ "$OS" != RedHatEnterpriseServer ] && [ "$OS" != CentOS ] && [ "$OS" != Debian ] && [ "$OS" != Ubuntu ]; then
echo "ERROR: Unsupported OS."
exit 3
fi
echo "Installing BIND..."
if [ "$OS" == RedHatEnterpriseServer ] || [ "$OS" == CentOS ]; then
yum -y -e1 -d1 install bind
service named start
chkconfig named on
elif [ "$OS" == Debian ] || [ "$OS" == Ubuntu ]; then
export DEBIAN_FRONTEND=noninteractive
apt-get -y -q install bind9
service bind9 start
update-rc.d bind9 defaults
fi
|
package prepared
import (
"bytes"
"testing"
"github.com/modern-go/parse"
"github.com/stretchr/testify/require"
)
func TestDecodeStmtExecutePacket(t *testing.T) {
var testCase = []struct {
raw []byte
expect *StmtExecuteBody
}{
{
raw: []byte{
0x2c, 0x00, 0x00, 0x00, 0x17, 0x02, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00,
0x00, 0x00, 0x00, 0x01, 0xfe, 0x00, 0x08, 0x00, 0x08, 0x00, 0x09, 0x72,
0x6f, 0x6e, 0x61, 0x6c, 0x64, 0x6f, 0x31, 0x32, 0x17, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x32, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
},
expect: &StmtExecuteBody{
StatementID: 2,
Flag: 0,
ExtraBytes: []byte{0x00, 0x01, 0xfe, 0x00, 0x08, 0x00, 0x08, 0x00, 0x09, 0x72,
0x6f, 0x6e, 0x61, 0x6c, 0x64, 0x6f, 0x31, 0x32, 0x17, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x32, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
},
},
},
}
should := require.New(t)
for idx, tc := range testCase {
src, err := parse.NewSource(bytes.NewReader(tc.raw), 10)
should.NoError(err)
actual, err := DecodeStmtExecutePacket(src)
should.NoError(err, "case #%d fail", idx)
should.Equal(tc.expect, actual, "case #%d fail", idx)
}
}
|
export class ValidationError extends Error {
}
export class UserCanNotBetError extends ValidationError {
}
|
package org.quifft.params;
/**
* Generates coefficients for various windowing functions based on
* <a href="https://www.mathworks.com/help/dsp/ref/windowfunction.html">MATLAB implementations</a>
*/
public class WindowFunctionGenerator {
/**
* Generates coefficients for a window of specified length and type
* @param N length of window (should be equal to number of samples taken from waveform)
* @param windowType type of windowing function desired (i.e. Hanning, Blackman, etc)
* @return coefficients for window of specified length and type
* @see WindowFunction
*/
public static double[] generateWindow(int N, WindowFunction windowType) {
switch(windowType) {
case TRIANGULAR:
return triang(N);
case BARTLETT:
return bartlett(N);
case HANNING:
return hann(N);
case HAMMING:
return hamming(N);
case BLACKMAN:
default:
return blackman(N);
}
}
/**
* Triangular window of size N
* @see <a href="https://www.mathworks.com/help/signal/ref/triang.html">MATLAB reference</a>
*/
private static double[] triang(int N) {
double[] w = new double[N];
int n = 0;
if(N % 2 == 1) {
for(; n < (N + 1) / 2; n++) {
w[n] = (2.0 * (n + 1)) / (N + 1);
}
for(; n < N; n++) {
w[n] = 2 - ((2.0 * (n + 1)) / (N + 1));
}
} else {
for(; n < (N / 2); n++) {
w[n] = (2.0 * (n + 1) - 1) / N;
}
for(; n < N; n++) {
w[n] = 2 - ((2.0 * (n + 1) - 1) / N);
}
}
return w;
}
/**
* Bartlett window of size N
* @see <a href="https://www.mathworks.com/help/signal/ref/bartlett.html">MATLAB reference</a>
*/
private static double[] bartlett(int N) {
double[] w = new double[N];
int n = 0;
for(; n <= (N - 1) / 2; n++) {
w[n] = (2.0 * n) / (N - 1);
}
for(; n < N; n++) {
w[n] = 2 - (2.0 * n) / (N - 1);
}
return w;
}
/**
* Hanning window of size N
* @see <a href="https://www.mathworks.com/help/signal/ref/hann.html">MATLAB reference</a>
*/
private static double[] hann(int N) {
double[] w = new double[N];
for(int n = 0; n < N; n++) {
w[n] = 0.5 * (1 - Math.cos(2 * Math.PI * (n / (N - 1.0))));
}
return w;
}
/**
* Hamming window of size N
* @see <a href="https://www.mathworks.com/help/signal/ref/hamming.html">MATLAB reference</a>
*/
private static double[] hamming(int N) {
double[] w = new double[N];
for(int n = 0; n < N; n++) {
w[n] = 0.54 - 0.46 * Math.cos(2 * Math.PI * (n / (N - 1.0)));
}
return w;
}
/**
* Blackman window of size N
* @see <a href="https://www.mathworks.com/help/signal/ref/blackman.html">MATLAB reference</a>
*/
private static double[] blackman(int N) {
double[] w = new double[N];
for(int n = 0; n < N; n++) {
w[n] = 0.42 - 0.5 * Math.cos((2 * Math.PI * n) / (N - 1)) + 0.08 * Math.cos((4 * Math.PI * n) / (N - 1));
}
return w;
}
}
|
#!/bin/bash
# Copyright 2017 The Forseti Security Authors. All rights reserved.
#
# Licensed under the Apache License, Versisn 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.
trap 'return_code=$?' ERR
# Check to see that the docker command is available to us.
if [ -x "$(command -v docker)" ]; then
# Docker command does exist.
# Check to see if we're on Travis.
if [ ${TRAVIS+x} ]; then
# We are on Travis.
# Required for codecov.io to export coverage within a Docker container.
echo "We're on Travis, setting our CI_ENV... "
CI_ENV=`bash <(curl -s https://codecov.io/env) || echo ''`
# Start the container for testing and code verification.
echo "Starting our container for testing and code verification... "
docker run ${CI_ENV} -it -d --name build forseti/build /bin/bash
else
# We're not on Travis, run without the CI_ENV environment variable.
echo "Starting our container for testing and code verification... "
docker run -it -d --name build forseti/build /bin/bash
fi
else
echo "Can\'t run docker, exiting."
exit 1
fi
# Test to see Forseti Security was installed, these should match the entry
# points in setup.py
echo "Testing the container for a successfull Forseti Security installation... "
docker exec -it build /bin/bash -c "hash forseti" || exit 1
docker exec -it build /bin/bash -c "hash forseti_enforcer" || exit 1
docker exec -it build /bin/bash -c "hash forseti_server" || exit 1
exit ${return_code}
|
import tensorflow as tf
# Define the model
model = tf.keras.Sequential([
tf.keras.layers.Dense(64, activation='relu'),
tf.keras.layers.Dense(64, activation='relu'),
tf.keras.layers.Dense(1)
])
# Compile the model
model.compile(optimizer='adam',
loss=tf.keras.losses.MeanSquaredError())
# Train the model
model.fit(x_train, y_train, epochs=100)
# Evaluate the model
model.evaluate(x_test, y_test) |
<filename>src/main/java/com/google/enterprise/secmgr/matcher/State.java
// Copyright 2011 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.enterprise.secmgr.matcher;
import com.google.common.base.Preconditions;
import javax.annotation.Nonnull;
import javax.annotation.ParametersAreNonnullByDefault;
import javax.annotation.concurrent.Immutable;
/**
* A simple object that holds a matcher's state.
*
*/
@Immutable
@ParametersAreNonnullByDefault
public final class State {
// Our position in the input sequence.
@Nonnull private final Position position;
// A stack of values created by the matching process. This could be used to
// match two instances of the same character in a row, for example, by pushing
// the first matched character, and popping it to match the second.
@Nonnull private final ValueStack stack;
// A collection of named values created by the matching process. This could
// be used to hold something like a named regexp group, for example.
@Nonnull private final Dict dict;
private State(Position position, ValueStack stack, Dict dict) {
this.position = position;
this.stack = stack;
this.dict = dict;
}
/**
* Makes a state object.
*
* @param position A position.
* @param stack A value stack.
* @param dict A dictionary.
* @return The corresponding state object.
*/
@Nonnull
public static State make(Position position, ValueStack stack, Dict dict) {
Preconditions.checkNotNull(position);
Preconditions.checkNotNull(stack);
Preconditions.checkNotNull(dict);
return new State(position, stack, dict);
}
/**
* Gets the position.
*/
@Nonnull
public Position getPosition() {
return position;
}
/**
* Gets a new state in which the position has been changed.
*
* @param position The new position.
* @return A new state with the given position.
*/
@Nonnull
public State newPosition(Position position) {
Preconditions.checkNotNull(position);
return new State(position, stack, dict);
}
/**
* Gets the value stack.
*/
@Nonnull
public ValueStack getStack() {
return stack;
}
/**
* Gets a new state in which the stack has been changed.
*
* @param stack The new stack.
* @return A new state with the given stack.
*/
@Nonnull
public State newStack(ValueStack stack) {
Preconditions.checkNotNull(stack);
return new State(position, stack, dict);
}
/**
* Gets the dictionary.
*/
@Nonnull
public Dict getDict() {
return dict;
}
/**
* Gets a new state in which the dictionary has been changed.
*
* @param dict The new dictionary.
* @return A new state with the given dict.
*/
@Nonnull
public State newDict(Dict dict) {
Preconditions.checkNotNull(dict);
return new State(position, stack, dict);
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("{position: ");
builder.append(position.toString());
builder.append(", stack: ");
builder.append(stack.toString());
builder.append(", dict: ");
builder.append(dict.toString());
builder.append("}");
return builder.toString();
}
}
|
<?php
$host = 'localhost';
$user = 'my_username';
$pass = 'my_password';
$db = 'my_database';
$conn = new mysqli($host, $user, $pass, $db);
$sql = "DELETE FROM student WHERE id=?";
$stmt = $conn->prepare($sql);
$stmt->bind_param('i', $id);
$stmt->execute();
// Close statement and connection
$stmt->close();
$conn->close();
?> |
#!/bin/sh
# 配置文件根目录,固定是spring-microservice-exam
DOCKERHOME=/spring-microservice-exam
# 镜像名称前缀、标签
BASE_IMAGE_NAME=registry.cn-hangzhou.aliyuncs.com/spring-microservice-exam
BSEE_IMAGE_TAG=latest
# 各服务的镜像名称
CONFIG_SERVICE=$BASE_IMAGE_NAME/config-service:$BSEE_IMAGE_TAG
AUTH_SERVICE=$BASE_IMAGE_NAME/auth-service:$BSEE_IMAGE_TAG
USER_SERVICE=$BASE_IMAGE_NAME/user-service:$BSEE_IMAGE_TAG
EXAM_SERVICE=$BASE_IMAGE_NAME/exam-service:$BSEE_IMAGE_TAG
GATEWAY_SERVICE=$BASE_IMAGE_NAME/gateway-service:$BSEE_IMAGE_TAG
MSC_SERVICE=$BASE_IMAGE_NAME/msc-service:$BSEE_IMAGE_TAG
MONITOR_SERVICE=$BASE_IMAGE_NAME/monitor-service:$BSEE_IMAGE_TAG
UI_SERVICE=$BASE_IMAGE_NAME/spring-microservice-exam-ui:$BSEE_IMAGE_TAG
WEB_SERVICE=$BASE_IMAGE_NAME/spring-microservice-exam-web:$BSEE_IMAGE_TAG
WEB_SERVICE_EXAMPLE=$BASE_IMAGE_NAME/exam-web-example:$BSEE_IMAGE_TAG
case "$1" in
# 删除容器
removeAll)
echo "* 正在删除容器..."
time docker rm $(docker ps -aq) -f
echo "* 删除容器成功..."
;;
# 拉取镜像
pull)
echo "* 正在拉取后端镜像..."
time docker pull $CONFIG_SERVICE
time docker pull $AUTH_SERVICE
time docker pull $USER_SERVICE
time docker pull $EXAM_SERVICE
time docker pull $GATEWAY_SERVICE
time docker pull $MSC_SERVICE
time docker pull $MONITOR_SERVICE
echo "* 开始拉取前端镜像..."
time docker pull $UI_SERVICE
time docker pull $WEB_SERVICE
echo "* 拉取镜像成功..."
;;
# 运行镜像
run)
echo "* 开始运行基础镜像..."
time docker-compose -f $DOCKERHOME/docker-compose-base.yml up -d
echo "* 等待10s..."
sleep 10
echo "* 开始运行后端服务镜像..."
time docker-compose -f $DOCKERHOME/docker-compose-services.yml up -d
echo "* 等待10s..."
sleep 10
echo "* 开始运行前端服务镜像..."
time docker-compose -f $DOCKERHOME/docker-compose-nginx.yml up -d
echo "* 运行成功..."
;;
# 拉取镜像并运行
pullrun)
echo "* 正在拉取后端镜像..."
time docker pull $CONFIG_SERVICE
time docker pull $AUTH_SERVICE
time docker pull $USER_SERVICE
time docker pull $EXAM_SERVICE
time docker pull $GATEWAY_SERVICE
time docker pull $MSC_SERVICE
time docker pull $MONITOR_SERVICE
echo "* 开始拉取前端镜像..."
time docker pull $UI_SERVICE
time docker pull $WEB_SERVICE
echo "* 拉取镜像成功..."
echo "* 开始运行基础镜像..."
time docker-compose -f $DOCKERHOME/docker-compose-base.yml up -d
echo "* 等待10s..."
sleep 10
echo "* 开始运行后端服务镜像..."
time docker-compose -f $DOCKERHOME/docker-compose-services.yml up -d
echo "* 等待10s..."
sleep 10
echo "* 开始运行前端服务镜像..."
time docker-compose -f $DOCKERHOME/docker-compose-nginx.yml up -d
echo "* 运行成功..."
;;
# 停止容器
stop)
echo "* 正在停止容器..."
time docker-compose -f $DOCKERHOME/docker-compose-nginx.yml stop
time docker-compose -f $DOCKERHOME/docker-compose-services.yml stop
time docker-compose -f $DOCKERHOME/docker-compose-base.yml stop
echo "* 停止容器成功..."
;;
# 重启容器
restart)
echo "* 正在停止镜像..."
time docker-compose -f $DOCKERHOME/docker-compose-nginx.yml restart
time docker-compose -f $DOCKERHOME/docker-compose-services.yml restart
time docker-compose -f $DOCKERHOME/docker-compose-base.yml restart
;;
# 其它
*)
echo "* ..."
;;
esac
exit 0 |
# make_model.py COPYRIGHT Fujitsu Limited 2021
import torch
import torchvision.transforms as transforms
import torchvision.datasets as datasets
from tqdm import tqdm
from vgg import VGG11
# model filepath
MODEL_PATH = './vgg11.pt'
def main():
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
print('device: ', device)
print('===== load data ===================')
train_transform = transforms.Compose([
transforms.RandomCrop(32, padding=4),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize((0.4914, 0.4822, 0.4465),
(0.2023, 0.1994, 0.2010)),
])
val_transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.4914, 0.4822, 0.4465),
(0.2023, 0.1994, 0.2010)),
])
# get cifar10 datasets
dataset_path = './data'
batch_size = 256
train_dataset = datasets.CIFAR10(root=dataset_path, train=True,
download=True, transform=train_transform)
val_dataset = datasets.CIFAR10(root=dataset_path, train=False,
download=True, transform=val_transform)
# make DataLoader
train_loader = torch.utils.data.DataLoader(train_dataset,
batch_size=batch_size,
shuffle=True,)
val_loader = torch.utils.data.DataLoader(val_dataset,
batch_size=batch_size,
shuffle=False)
# initialize model
model = VGG11()
if torch.cuda.device_count() > 1:
print('use {} GPUs.'.format(torch.cuda.device_count()))
model = torch.nn.DataParallel(model)
model.to(device)
criterion = torch.nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(model.parameters(), lr=0.01,
momentum=0.9, weight_decay=1e-4)
# optimizer = torch.optim.SGD(model.parameters(), lr=0.1,
# momentum=0.9, weight_decay=5e-4)
# train and valitate model
print('===== start train ===============')
epochs = 50
for epoch in range(epochs):
train(train_loader, model, device, criterion, optimizer, epoch+1)
acc = validate(val_loader, model, device, epoch+1, 100)
print('Epoch: {}/{}, Acc: {}'.format(epoch+1, epochs, acc))
# save model
if torch.cuda.device_count() > 1:
torch.save(model.module.state_dict(), MODEL_PATH)
else:
torch.save(model.state_dict(), MODEL_PATH)
print('===== finish train ==============')
def train(train_loader, model, device, criterion, optimizer, epoch):
model.train()
hit = 0
total = 0
with tqdm(train_loader, leave=False) as pbar:
for _, (images, targets) in enumerate(pbar):
pbar.set_description('Epoch {} Training'.format(epoch))
images = images.to(device)
targets = targets.to(device)
outputs = model(images)
loss = criterion(outputs, targets)
optimizer.zero_grad()
loss.backward()
optimizer.step()
outClass = outputs.cpu().detach().numpy().argmax(axis=1)
hit += (outClass == targets.cpu().numpy()).sum()
total += len(targets)
pbar.set_postfix({'train Acc': hit / total * 100})
def validate(val_loader, model, device, epoch, valid_iter):
model.eval()
with torch.no_grad():
with tqdm(val_loader, leave=False) as pbar:
pbar.set_description('Epoch {} Validation'.format(epoch))
hit = 0
total = 0
for i, (images, targets) in enumerate(pbar):
images = images.to(device)
targets = targets.to(device)
outputs = model(images)
outClass = outputs.cpu().detach().numpy().argmax(axis=1)
hit += (outClass == targets.cpu().numpy()).sum()
total += len(targets)
val_acc = hit / total * 100
pbar.set_postfix({'valid Acc': val_acc})
if i == valid_iter:
break
return val_acc
if __name__ == '__main__':
main()
|
class AppDelegate
#------------------------------------------------------------------------------
def applicationDidFinishLaunching(notification)
buildMenu
buildWindow
end
#------------------------------------------------------------------------------
def buildWindow
@window_controller = WindowController.alloc.init
@window_controller.showWindow(self)
@window_controller.window.orderFrontRegardless
end
end
|
<filename>test-case/src/main/java/com/zto/testcase/response/SysUserInfoJsonData.java
package com.zto.testcase.response;
import com.zto.testcase.model.RoleInfo;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
@Data
public class SysUserInfoJsonData {
private Integer id;
private String userId;
private String userName;
private String nickName;
private String userStatus;
private String mobile;
private String email;
private String appId;
private String userPwd;
private Integer loginErrorTimes;
private Date startDate;
private Date endDate;
private Date dateCreated;
private Date dateUpdated;
private List<RoleInfo> roles;
public void setStartDate(Object startDate) {
if (startDate instanceof LocalDateTime) {
LocalDateTime localDateTime = (LocalDateTime) startDate;
ZoneId zone = ZoneId.systemDefault();
Instant instant = localDateTime.atZone(zone).toInstant();
this.startDate = Date.from(instant);
} else {
Date date = new Date(Long.valueOf(startDate + ""));
this.startDate = date;
}
}
public void setDateCreated(Object dateCreated) {
if (dateCreated instanceof LocalDateTime) {
LocalDateTime localDateTime = (LocalDateTime) dateCreated;
ZoneId zone = ZoneId.systemDefault();
Instant instant = localDateTime.atZone(zone).toInstant();
this.dateCreated = Date.from(instant);
} else {
Date date = new Date(Long.valueOf(dateCreated + ""));
this.dateCreated = date;
}
}
public void setDateUpdated(Object dateUpdated) {
if (dateUpdated instanceof LocalDateTime) {
LocalDateTime localDateTime = (LocalDateTime) dateUpdated;
ZoneId zone = ZoneId.systemDefault();
Instant instant = localDateTime.atZone(zone).toInstant();
this.dateUpdated = Date.from(instant);
} else {
Date date = new Date(Long.valueOf(dateUpdated + ""));
this.dateUpdated = date;
}
}
public void setEndDate(Object endDate) {
if (endDate instanceof LocalDateTime) {
LocalDateTime localDateTime = (LocalDateTime) endDate;
ZoneId zone = ZoneId.systemDefault();
Instant instant = localDateTime.atZone(zone).toInstant();
this.endDate = Date.from(instant);
} else {
Date date = new Date(Long.valueOf(endDate + ""));
this.endDate = date;
}
}
public String getUserId() {
if (StringUtils.isBlank(StringUtils.trim(userId))) {
userId = null;
}
return userId;
}
public String getUserName() {
if (StringUtils.isBlank(StringUtils.trim(userName))) {
userName = null;
}
return userName;
}
public String getNickName() {
if (StringUtils.isBlank(StringUtils.trim(nickName))) {
nickName = null;
}
return nickName;
}
public String getUserPwd() {
if (StringUtils.isBlank(StringUtils.trim(userPwd))) {
userPwd = null;
}
return userPwd;
}
public String getUserStatus() {
if (StringUtils.isBlank(StringUtils.trim(userStatus))) {
userStatus = null;
}
return userStatus;
}
public String getMobile() {
if (StringUtils.isBlank(StringUtils.trim(mobile))) {
mobile = null;
}
return mobile;
}
public String getEmail() {
if (StringUtils.isBlank(StringUtils.trim(email))) {
email = null;
}
return email;
}
public String getAppId() {
if (StringUtils.isBlank(StringUtils.trim(appId))) {
appId = null;
}
return appId;
}
}
|
<gh_stars>0
/*
* Copyright © 2019 Apple Inc. and the ServiceTalk project authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.servicetalk.concurrent.api;
import io.servicetalk.concurrent.Cancellable;
import io.servicetalk.concurrent.CompletableSource;
import io.servicetalk.concurrent.test.internal.AwaitUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
import java.util.function.Function;
import javax.annotation.Nullable;
import static java.util.Objects.requireNonNull;
/**
* A {@link Completable} & {@link CompletableSource} whose outgoing signals to its {@link Subscriber}s can be
* controlled.
* <p>
* Behavior beyond simply delegating signals to the {@link Subscriber} is accomplished by a
* {@link Function Function<Subscriber<? super T>, Subscriber<? super T>>}. This {@link Function} is
* invoked for every {@link #subscribe(Subscriber)} invocation, and the result is used as the delegate for subsequent
* {@link #onSubscribe(Cancellable)}, {@link #onComplete()}, and
* {@link #onError(Throwable)} calls. See {@link Builder} for more information.
*
* <h3>Defaults</h3>
* <ul>
* <li>Allows sequential but not concurrent subscribers.</li>
* <li>Sends {@link #onSubscribe(Cancellable)} automatically when subscribed to.</li>
* </ul>
*/
public final class TestCompletable extends Completable implements CompletableSource {
private static final Logger LOGGER = LoggerFactory.getLogger(TestCompletable.class);
private static final AtomicReferenceFieldUpdater<TestCompletable, Subscriber> subscriberUpdater =
AtomicReferenceFieldUpdater.newUpdater(TestCompletable.class, Subscriber.class, "subscriber");
private final Function<Subscriber, Subscriber> subscriberFunction;
private final List<Throwable> exceptions = new CopyOnWriteArrayList<>();
private volatile Subscriber subscriber = new WaitingSubscriber();
private final CountDownLatch subscriberLatch = new CountDownLatch(1);
/**
* Create a {@code TestCompletable} with the defaults. See <b>Defaults</b> section of class javadoc.
*/
public TestCompletable() {
this(new Builder().buildSubscriberFunction());
}
private TestCompletable(final Function<Subscriber, Subscriber> subscriberFunction) {
this.subscriberFunction = requireNonNull(subscriberFunction);
}
/**
* Returns {@code true} if this {@link TestCompletable} has been subscribed to, {@code false} otherwise.
*
* @return {@code true} if this {@link TestCompletable} has been subscribed to, {@code false} otherwise.
*/
public boolean isSubscribed() {
return !(subscriber instanceof WaitingSubscriber);
}
/**
* Awaits until this {@link TestCompletable} is subscribed, even if interrupted. If interrupted the
* {@link Thread#isInterrupted()} will be set upon return.
*/
public void awaitSubscribed() {
AwaitUtils.awaitUninterruptibly(subscriberLatch);
}
@Override
protected void handleSubscribe(final Subscriber subscriber) {
try {
Subscriber newSubscriber = requireNonNull(subscriberFunction.apply(subscriber));
for (;;) {
Subscriber currSubscriber = this.subscriber;
if (subscriberUpdater.compareAndSet(this, currSubscriber, newSubscriber)) {
if (currSubscriber instanceof WaitingSubscriber) {
final WaitingSubscriber waiter = (WaitingSubscriber) currSubscriber;
waiter.realSubscriber(newSubscriber);
}
subscriberLatch.countDown();
break;
}
}
} catch (final Throwable t) {
record(t);
}
}
@Override
public void subscribe(final Subscriber subscriber) {
subscribeInternal(subscriber);
}
/**
* Delivers the {@link Cancellable} to the {@link Subscriber}'s {@link Subscriber#onSubscribe(Cancellable)}.
* <p>
* In the case of {@link Builder#autoOnSubscribe() auto-on-subscribe}, the delegating {@link Cancellable} sent to
* the {@link Subscriber} by the auto-on-subscribe will switch to {@code cancellable}.
*
* @param cancellable the {@link Cancellable}
*/
public void onSubscribe(final Cancellable cancellable) {
final Subscriber subscriber = checkSubscriberAndExceptions();
subscriber.onSubscribe(cancellable);
}
/**
* Completes the {@link Subscriber}.
*
* @see Subscriber#onComplete()
*/
public void onComplete() {
final Subscriber subscriber = checkSubscriberAndExceptions();
subscriber.onComplete();
}
/**
* Delivers the {@link Throwable} {@code t} to the {@link Subscriber}.
*
* @param t the error to deliver.
* @see Subscriber#onError(Throwable)
*/
public void onError(final Throwable t) {
final Subscriber subscriber = checkSubscriberAndExceptions();
subscriber.onError(t);
}
private Subscriber checkSubscriberAndExceptions() {
if (!exceptions.isEmpty()) {
final RuntimeException exception = new RuntimeException("Unexpected exception(s) encountered",
exceptions.get(0));
for (int i = 1; i < exceptions.size(); i++) {
exception.addSuppressed(exceptions.get(i));
}
throw exception;
}
return subscriber;
}
private void record(final Throwable t) {
requireNonNull(t);
LOGGER.warn("Unexpected exception", t);
exceptions.add(t);
}
/**
* Allows creation of {@link TestCompletable}s with non-default settings. For defaults, see <b>Defaults</b> section
* of class javadoc.
*/
public static class Builder {
@Nullable
private Function<Subscriber, Subscriber> autoOnSubscribeFunction =
new AutoOnSubscribeCompletableSubscriberFunction();
private Function<Subscriber, Subscriber> subscriberCardinalityFunction =
new SequentialCompletableSubscriberFunction();
/**
* Allow concurrent subscribers. Default is to allow only sequential subscribers.
*
* @return this.
* @see ConcurrentCompletableSubscriberFunction
*/
public Builder concurrentSubscribers() {
subscriberCardinalityFunction = new ConcurrentCompletableSubscriberFunction();
return this;
}
/**
* Allow concurrent subscribers, with the specified {@link ConcurrentCompletableSubscriberFunction}.
* Default is to allow only sequential subscribers.
*
* @param function the {@link ConcurrentCompletableSubscriberFunction} to use.
* @return this.
*/
public Builder concurrentSubscribers(final ConcurrentCompletableSubscriberFunction function) {
subscriberCardinalityFunction = requireNonNull(function);
return this;
}
/**
* Allow sequential subscribers. This is the default.
*
* @return this.
* @see SequentialCompletableSubscriberFunction
*/
public Builder sequentialSubscribers() {
subscriberCardinalityFunction = new SequentialCompletableSubscriberFunction();
return this;
}
/**
* Allow sequential subscribers, with the specified {@link SequentialCompletableSubscriberFunction}.
* This is the default.
*
* @param function the {@link SequentialCompletableSubscriberFunction} to use.
* @return this.
*/
public Builder sequentialSubscribers(final SequentialCompletableSubscriberFunction function) {
subscriberCardinalityFunction = requireNonNull(function);
return this;
}
/**
* Allow only a single subscriber. Default is to allow sequential subscribers.
*
* @return this.
* @see NonResubscribeableCompletableSubscriberFunction
*/
public Builder singleSubscriber() {
subscriberCardinalityFunction = new NonResubscribeableCompletableSubscriberFunction();
return this;
}
/**
* Allow only a single subscriber, with the specified {@link NonResubscribeableCompletableSubscriberFunction}.
* Default is to allow sequential subscribers.
*
* @param function the {@link NonResubscribeableCompletableSubscriberFunction} to use.
* @return this.
*/
public Builder singleSubscriber(final NonResubscribeableCompletableSubscriberFunction function) {
subscriberCardinalityFunction = requireNonNull(function);
return this;
}
/**
* Enable calling {@link Subscriber#onSubscribe(Cancellable)} automatically upon subscribe. The default is
* enabled.
*
* @return this.
* @see AutoOnSubscribeCompletableSubscriberFunction
*/
public Builder autoOnSubscribe() {
autoOnSubscribeFunction = new AutoOnSubscribeCompletableSubscriberFunction();
return this;
}
/**
* Enable calling {@link Subscriber#onSubscribe(Cancellable)} automatically upon subscribe, with the specified
* {@link AutoOnSubscribeCompletableSubscriberFunction}. The default is enabled.
*
* @param function the {@link AutoOnSubscribeCompletableSubscriberFunction} to use.
* @return this.
*/
public Builder autoOnSubscribe(final AutoOnSubscribeCompletableSubscriberFunction function) {
autoOnSubscribeFunction = requireNonNull(function);
return this;
}
/**
* Disable calling {@link Subscriber#onSubscribe(Cancellable)} automatically upon subscribe. The default is
* enabled.
*
* @return this.
*/
public Builder disableAutoOnSubscribe() {
autoOnSubscribeFunction = null;
return this;
}
/**
* Create a {@link TestCompletable} using the specified subscriber function.
* <p>
* All other settings from this {@link Builder} will be ignored.
*
* @param function The subscriber function to use.
* @return a new {@link TestCompletable}.
*/
public TestCompletable build(final Function<Subscriber, Subscriber> function) {
return new TestCompletable(function);
}
private Function<Subscriber, Subscriber> buildSubscriberFunction() {
Function<Subscriber, Subscriber> subscriberFunction =
autoOnSubscribeFunction;
subscriberFunction = andThen(subscriberFunction, subscriberCardinalityFunction);
assert subscriberFunction != null;
return subscriberFunction;
}
/**
* Create a {@link TestCompletable} as configured by the builder.
*
* @return a new {@link TestCompletable}.
*/
public TestCompletable build() {
return new TestCompletable(buildSubscriberFunction());
}
@Nullable
private static Function<Subscriber, Subscriber>
andThen(@Nullable final Function<Subscriber, Subscriber> first,
@Nullable final Function<Subscriber, Subscriber> second) {
if (first == null) {
return second;
}
if (second == null) {
return first;
}
return first.andThen(second);
}
}
private static final class WaitingSubscriber implements Subscriber {
private final SingleProcessor<Subscriber> realSubscriberSingle = new SingleProcessor<>();
@Override
public void onSubscribe(final Cancellable cancellable) {
waitForSubscriber().onSubscribe(cancellable);
}
@Override
public void onComplete() {
waitForSubscriber().onComplete();
}
@Override
public void onError(final Throwable t) {
waitForSubscriber().onError(t);
}
void realSubscriber(Subscriber subscriber) {
realSubscriberSingle.onSuccess(subscriber);
}
private Subscriber waitForSubscriber() {
try {
return realSubscriberSingle.toFuture().get();
} catch (InterruptedException | ExecutionException e) {
throw new RuntimeException(e);
}
}
}
}
|
#!/bin/bash
# Read entrypoint parameters.
CELERY_COMMAND=${1:-worker}
# Define variables.
: ${{ '{' }}{{ cookiecutter.organization|upper }}_{{ cookiecutter.project_name|upper }}_CELERY_APP:={{ cookiecutter.project_name }}.celery}
: ${{ '{' }}{{ cookiecutter.organization|upper }}_{{ cookiecutter.project_name|upper }}_CELERY_LOG_LEVEL:=info}
# Start Celery command.
DATE=$(date -u +%Y%m%dT%H%M%S%Z)
su -m celery -c "celery ${CELERY_COMMAND} \
-A ${{ '{' }}{{ cookiecutter.organization|upper }}_{{ cookiecutter.project_name|upper }}_CELERY_APP} \
-l ${{ '{' }}{{ cookiecutter.organization|upper }}_{{ cookiecutter.project_name|upper }}_CELERY_LOG_LEVEL} \
--pidfile=celery_${CELERY_COMMAND}-${DATE}.pid"
|
import datetime
def epoch_time_converter(epoch):
# Datetime object containing current time
datetime_object = datetime.datetime.fromtimestamp(epoch)
# Print the month
print(datetime_object.strftime("%B"))
# Print the day of the week
print(datetime_object.strftime("%A"))
# Print 12 hour version of time
print(datetime_object.strftime("%I:%M:%S %p"))
epoch_time_converter(1595685833)
# Output:
# July
# Saturday
# 06:10:33 PM |
#!/bin/bash
## 1- imageID ##2 keyname ##3 security group
aws ec2 run-instances --image-id $1 --key-name $2 --security-groups $3 --instance-type t2.micro --iam-instance-profile Name=$4 --monitoring Enabled=true --user-data file://install-app2-env.sh
##To get Security group id
SG=`aws ec2 describe-security-groups | grep $3 | awk '{print $3}'`
##Create Load Balancer
aws elb create-load-balancer --load-balancer-name miniproject1 --listeners "Protocol=HTTP,LoadBalancerPort=80,InstanceProtocol=HTTP,InstancePort=80" --security-groups $SG --availability-zones us-west-2a
## describe load balancer
LB=`aws elb describe-load-balancers | awk 'NR==1{print $6}'`
# Create sticky bits
aws elb create-lb-cookie-stickiness-policy --load-balancer-name miniproject1 --policy-name policy1 --cookie-expiration-period 60
## wait command for load blancers
##aws elb wait any-instance-in-service --load-balancer-name $4
##create Launcg configuration
aws autoscaling create-launch-configuration --launch-configuration-name LC1 --image-id $1 --instance-type t2.micro --key-name $2 --security-groups $3 --user-data file://install-app-env.sh --iam-instance-profile $4
# create auto scaling group
aws autoscaling create-auto-scaling-group --auto-scaling-group-name AC1 --launch-configuration-name LC1 --min-size 3 --max-size 3 --load-balancer-name miniproject1 --availability-zones us-west-2a
# create s3
aws s3api create-bucket --bucket kedarbktbefore --region us-west-2 --acl public-read-write --create-bucket-configuration LocationConstraint=us-west-2
aws s3api create-bucket --bucket kedarbktafter --region us-west-2 --acl public-read-write --create-bucket-configuration LocationConstraint=us-west-2
#create sns topic
#CREATE A TOPIC
ARN=(`aws sns create-topic --name kedar-mp2`)
echo "This is the ARN: $ARN"
echo "Creating a SQS topic"
aws sqs create-queue --queue-name knaik-sqs
#DISPLAY NAME ATTRIBUTE
aws sns set-topic-attributes --topic-arn $ARN --attribute-name DisplayName --attribute-value kedar-mp2
#Create Database
aws rds create-db-instance --db-name miniproject --db-instance-identifier mp1-sb --db-instance-class db.t2.micro --engine mysql --master-username muser --master-user-password 544miniproject --allocated-storage 5 --vpc-security-group-ids $SG --publicly-accessible --availability-zone us-west-2a
#Wait Untill Database is created
aws rds wait db-instance-available --db-instance-identifier mp1-sb
#Create an EndPoint
DBEndpoint=(`aws rds describe-db-instances --output text | grep ENDPOINT | sed -e "s/3306//g" -e "s/ //g" -e "s/ENDPOINT//g"`);
echo ${DBEndpoint[0]}
#Create table if not created by setup.php
# Connect to DB instance
# Connect to database
# Create a table
# Show Schema
mysql -h ${DBEndpoint[0]} -P 3306 -u muser -p544miniproject << EOF
use miniproject;
CREATE TABLE IF NOT EXISTS records (id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, uname VARCHAR(32) NOT NULL, email VARCHAR(32) NOT NULL, phone VARCHAR(32) NOT NULL, s3rawurl VARCHAR(255) NOT NULL, s3finishedurl VARCHAR(255) NOT NULL, status INT(1), receipt BIGINT, date DATETIME DEFAULT CURRENT_TIMESTAMP);
show tables;
EOF
##Creating replica
aws rds create-db-instance-read-replica --db-instance-identifier mp1-replica-db --source-db-instance-identifier mp1-sb
aws rds wait db-instance-available --db-instance-identifier mp1-replica-db
echo "==============================================";
echo "Create-env.sh successfully completed";
echo "==============================================";
|
<reponame>chendave/buildkit<filename>util/network/netproviders/network.go
package netproviders
import (
"os"
"github.com/moby/buildkit/solver/pb"
"github.com/moby/buildkit/util/network"
"github.com/moby/buildkit/util/network/cniprovider"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)
type Opt struct {
CNI cniprovider.Opt
Mode string
}
// Providers returns the network provider set
func Providers(opt Opt) (map[pb.NetMode]network.Provider, error) {
var defaultProvider network.Provider
switch opt.Mode {
case "cni":
cniProvider, err := cniprovider.New(opt.CNI)
if err != nil {
return nil, err
}
defaultProvider = cniProvider
case "host":
defaultProvider = network.NewHostProvider()
case "auto", "":
if _, err := os.Stat(opt.CNI.ConfigPath); err == nil {
cniProvider, err := cniprovider.New(opt.CNI)
if err != nil {
return nil, err
}
defaultProvider = cniProvider
} else {
logrus.Warnf("using host network as the default")
defaultProvider = network.NewHostProvider()
}
default:
return nil, errors.Errorf("invalid network mode: %q", opt.Mode)
}
return map[pb.NetMode]network.Provider{
pb.NetMode_UNSET: defaultProvider,
pb.NetMode_HOST: network.NewHostProvider(),
pb.NetMode_NONE: network.NewNoneProvider(),
}, nil
}
|
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class StreamUtil {
public static void copyStream(InputStream in, OutputStream out) {
try {
byte[] buf = new byte[8192]; // Use a buffer to read data from the input stream
int len;
while ((len = in.read(buf)) != -1) {
out.write(buf, 0, len); // Write the read data to the output stream
}
} catch (IOException ex) {
// Handle any exceptions by printing the stack trace
ex.printStackTrace();
} finally {
close(in);
close(out);
}
}
private static void close(InputStream in) {
try {
in.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
private static void close(OutputStream out) {
try {
out.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
} |
package com.huatuo.activity.db;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import com.huatuo.bean.SearchAddressObj;
import com.huatuo.util.CommonUtil;
import com.huatuo.util.Constants;
public class SearchDBUtil {
private static SearchDBUtil instance;
private DatabaseService ds;
private final int SIZE = 3;
public static SearchDBUtil getInstance() {
if (instance == null) {
synchronized (SearchDBUtil.class) {
if (instance == null) {
instance = new SearchDBUtil();
}
}
}
return instance;
}
/**
* 插入keywords
*
* @param context
* @param keyWords
*/
public void insertDB(Context context, int tableType, String keyWords) {
ds = new DatabaseService(context);
String tableName = getTableName(tableType);// 获取对应的biao
List<String> keyword_list = findDBOfKeyWords(context, tableType);
CommonUtil.log("keyword_list:" + keyword_list);
boolean isHas = false;
if (!CommonUtil.emptyListToString3(keyword_list)) {
// 避免存储重复数据
for (int i = 0; i < keyword_list.size(); i++) {
// 存储过
if (keyWords.trim().equals(keyword_list.get(i).trim())) {
isHas = true;
break;
} else {
isHas = false;
}
}
CommonUtil.log("==================isHas:" + isHas);
if (!isHas) {
ds.save_search_keyWords(tableName, keyWords.trim());
}
} else {
ds.save_search_keyWords(tableName, keyWords.trim());
}
}
/**
* 插入keywords
*
* @param context
* @param keyWords
*/
public void insertDB(Context context, int tableType,
SearchAddressObj searchAddressObj) {
// 要存储的搜索区域信息
String cityCode = searchAddressObj.getCityCode();
String district = searchAddressObj.getDistrict();
String areaName = searchAddressObj.getAreaName();
String lat = searchAddressObj.getLat();
String lng = searchAddressObj.getLng();
ds = new DatabaseService(context);
String tableName = getTableName(tableType);// 获取对应的biao
List<SearchAddressObj> address_list = findDBOfSearchAddres(context,
tableType, cityCode);
CommonUtil.log("cityCode:" + cityCode + "====address_list:" + address_list);
boolean isHas = false;
if (!CommonUtil.emptyListToString3(address_list)) {
// 避免存储重复数据并且同一城市不能超过二十条数据
CommonUtil.log("cityCode:" + cityCode + "====address_list.size():"
+ address_list.size());
if (address_list.size() < SIZE) {
for (int i = 0; i < address_list.size(); i++) {
SearchAddressObj searchAddressObj2 = address_list.get(i);
String cityCode2 = searchAddressObj2.getCityCode();
String district2 = searchAddressObj2.getDistrict();
String areaName2 = searchAddressObj2.getAreaName();
String lat2 = searchAddressObj2.getLat();
String lng2 = searchAddressObj2.getLng();
// 存储过
if (cityCode.equals(cityCode2) && district.equals(district2)
&& areaName.equals(areaName2)) {
isHas = true;
break;
} else {
isHas = false;
continue;
}
}
} else {
isHas = true;
updateDataOfSelectCity(tableName, address_list,
searchAddressObj);
}
CommonUtil.log("===searchAddressObj===============isHas:" + isHas);
if (!isHas) {
ds.save_search_address(tableName, searchAddressObj);
}
} else {
ds.save_search_address(tableName, searchAddressObj);
}
}
/**
* 获取对应列表
*
* @param type
* @return
*/
public String getTableName(int type) {
String tableName = "";
switch (type) {
case Constants.SEARCH_STORE_PRO:
tableName = DatabaseService.search_store_pro_table;
break;
case Constants.SEARCH_VISIT_PRO:
tableName = DatabaseService.search_visit_pro_table;
break;
case Constants.SEARCH_TECH:
tableName = DatabaseService.search_tech_table;
break;
case Constants.SEARCH_STORE:
tableName = DatabaseService.search_store_table;
break;
case Constants.SEARCH_ADDRESS_SELECTCITY:
tableName = DatabaseService.search_address_selectCity_table;
break;
}
return tableName;
}
public List<String> findDBOfKeyWords(Context context, int type) {
ds = new DatabaseService(context);
List<String> keyword_list = new ArrayList<String>();
switch (type) {
case Constants.SEARCH_STORE_PRO:
keyword_list = ds
.find_search_list(DatabaseService.search_store_pro_table);
break;
case Constants.SEARCH_VISIT_PRO:
keyword_list = ds
.find_search_list(DatabaseService.search_visit_pro_table);
break;
case Constants.SEARCH_TECH:
keyword_list = ds
.find_search_list(DatabaseService.search_tech_table);
break;
case Constants.SEARCH_STORE:
keyword_list = ds
.find_search_list(DatabaseService.search_store_table);
break;
}
if (!CommonUtil.emptyListToString3(keyword_list)) {
return keyword_list;
} else {
return null;
}
}
public List<SearchAddressObj> findDBOfSearchAddres(Context context, int type) {
ds = new DatabaseService(context);
List<SearchAddressObj> address_list = new ArrayList<SearchAddressObj>();
switch (type) {
case Constants.SEARCH_ADDRESS_SELECTCITY:
address_list = ds
.find_searchAddress_list(DatabaseService.search_address_selectCity_table);
break;
}
if (!CommonUtil.emptyListToString3(address_list)) {
return address_list;
} else {
return null;
}
}
/**
* 根据城市查询
*
* @param context
* @param type
* @param city
* @return
*/
public List<SearchAddressObj> findDBOfSearchAddres(Context context,
int type, String cityCode) {
ds = new DatabaseService(context);
List<SearchAddressObj> address_list = new ArrayList<SearchAddressObj>();
switch (type) {
case Constants.SEARCH_ADDRESS_SELECTCITY:
address_list = ds.find_searchAddress_list(
DatabaseService.search_address_selectCity_table, cityCode);
break;
}
if (!CommonUtil.emptyListToString3(address_list)) {
return address_list;
} else {
return null;
}
}
/**
* 更新数据库列表数据
*
* @param TBNAME
* @param list
* @param keyword
*/
private void updateDataOfSelectCity(String TBNAME,
List<SearchAddressObj> list, SearchAddressObj obj) {
String id= "";
int ID = 0;
for (int i = 1; i < SIZE; i++) {
//根据id进行跟新 将最早的一个更新掉
id = list.get(i-1).getId();
ID = Integer.parseInt(id);
ds.updateSearch_address_selectCityTable(TBNAME, list.get(i), ID);
}
id = list.get(SIZE - 1).getId();
ID = Integer.parseInt(id);
ds.updateSearch_address_selectCityTable(TBNAME, obj, ID);
}
/**
* 清空对应搜索记录
*
* @param context
* @param type
*/
public boolean clearSearchHistory(Context context, int type) {
ds = new DatabaseService(context);
boolean isClearSuccess = false;
switch (type) {
case Constants.SEARCH_STORE_PRO:
isClearSuccess = ds.dbClear(DatabaseService.search_store_pro_table);
break;
case Constants.SEARCH_VISIT_PRO:
isClearSuccess = ds.dbClear(DatabaseService.search_visit_pro_table);
break;
case Constants.SEARCH_TECH:
isClearSuccess = ds.dbClear(DatabaseService.search_tech_table);
break;
case Constants.SEARCH_STORE:
isClearSuccess = ds.dbClear(DatabaseService.search_store_table);
break;
case Constants.SEARCH_ADDRESS_SELECTCITY:
isClearSuccess = ds.dbClear(DatabaseService.search_address_selectCity_table);
break;
}
return isClearSuccess;
}
/**
* 清空对应搜索记录
*
* @param context
* @param type
*/
public boolean clearSearchHistoryOfSearchAddress(Context context, int type,String cityCode) {
ds = new DatabaseService(context);
boolean isClearSuccess = false;
switch (type) {
case Constants.SEARCH_ADDRESS_SELECTCITY:
isClearSuccess = ds
.deleteItemDataFromSearchAddress(DatabaseService.search_address_selectCity_table,cityCode);
break;
}
return isClearSuccess;
}
/**
* 清空对应搜索记录
*
* @param context
* @param type
*/
public void closeTable(Context context, int type) {
ds = new DatabaseService(context);
switch (type) {
case Constants.SEARCH_STORE_PRO:
ds.closeDatabase(DatabaseService.search_store_pro_table);
break;
case Constants.SEARCH_VISIT_PRO:
ds.closeDatabase(DatabaseService.search_visit_pro_table);
break;
case Constants.SEARCH_TECH:
ds.closeDatabase(DatabaseService.search_tech_table);
break;
case Constants.SEARCH_STORE:
ds.closeDatabase(DatabaseService.search_store_table);
break;
case Constants.SEARCH_ADDRESS_SELECTCITY:
ds.closeDatabase(DatabaseService.search_address_selectCity_table);
break;
}
}
}
|
package org.slos.battle.abilities.rule.target;
import org.slos.battle.GameContext;
import org.slos.battle.monster.MonsterBattleStats;
import java.util.ArrayList;
import java.util.List;
public class TargetNotFirstRule implements TargetRule {
@Override
public List<MonsterBattleStats> selectTargets(MonsterBattleStats monsterBattleStats, List<MonsterBattleStats> selectFrom, GameContext gameContext) {
if ((selectFrom == null) || selectFrom.size() == 0){
return new ArrayList<>();
}
if (selectFrom.size() == 1) {
return selectFrom;
}
gameContext.log("Target not First: " + selectFrom.subList(1, selectFrom.size()));
return selectFrom.subList(1, selectFrom.size());
}
}
|
int[] input = {10, 20, 30, 0, 40, 50};
for (int i = 0; i < input.Length - 1; i++)
{
if (input[i] == 0)
{
input[i] = (input[i - 1] + input[i + 1]) / 2;
}
} |
<reponame>rene-leanix/rx-angular
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
const ROUTES: Routes = [
{
path: 'differ',
loadChildren: () =>
import('./differ/differ.module').then(
(m) => m.DifferModule
)
},
{
path: 'strategies',
loadChildren: () =>
import('./strategies/strategies.module').then(
(m) => m.StrategiesModule
)
},
{
path: 'pipes',
loadChildren: () =>
import('./pipes/pipes.module').then(
(m) => m.PipesModule
)
},
{
path: 'rx-base-state',
loadChildren: () =>
import('./state/rx-state.module').then((mod) => mod.RxStateModule),
canActivate: [],
canActivateChild: []
},
{
path: 'structural-directives',
loadChildren: () =>
import('./structural-directives/structural-directives.module').then(
(m) => m.StructuralDirectivesModule
)
},
{
path: 'input-bindings',
loadChildren: () =>
import('./input-bindings/input-bindings.module').then(
(m) => m.InputBindingsModule
)
},
{
path: 'decorators',
loadChildren: () =>
import('./decorators/decorators.module').then(
(m) => m.DecoratorsModule
)
}
];
@NgModule({
declarations: [],
imports: [RouterModule.forChild(ROUTES)]
})
export class ExperimentsShellModule {
}
|
<reponame>askuy/juno
package model
// EventType defines the possible types of build events.
type EventType string
// Enqueued ...
const (
Enqueued EventType = "enqueued"
Started EventType = "started"
Finished EventType = "finished"
Cancelled EventType = "cancelled"
)
// Event represents a build event.
type Event struct {
Type EventType `json:"type"`
Repo Repo `json:"repo"`
Build Build `json:"build"`
Proc Proc `json:"proc"`
}
|
package com.artemzi.cores.exceptions;
public class CoreException extends RuntimeException {
public CoreException() {
this("Core exception");
}
public CoreException(String message) {
super(message);
}
public CoreException(String message, Throwable cause) {
super(message, cause);
}
}
|
<reponame>ritaswc/wechat_app_template
const AV = require('../../../utils/av-weapp.js')
Page({
data: {
orders: [],
},
onLoad: function (options) {
// 订单状态,已下单为0,已付为1,已发货为2,已收货为3
var status = parseInt(options.status);
// 存为全局变量,控制支付按钮是否显示
this.setData({
status: status
});
},
onShow: function() {
this.reloadData();
},
reloadData: function() {
// 声明一个class
// var Address = AV.Object.extend('Address');
// Object.defineProperty(
// Address.prototype, 'detail',
// {
// get: function(){
// return this.get('detail');
// },
// set: function(value) {
// this.set('detail', value);
// }
// }
// );
var that = this;
var user = AV.User.current();
var query = new AV.Query('Order');
query.include('buys');
query.include('address');
query.equalTo('user', user);
query.equalTo('status', this.data.status);
query.descending('createdAt');
query.find().then(function (orderObjects) {
that.setData({
orders: orderObjects
});
// 存储地址字段
for (var i = 0; i < orderObjects.length; i++) {
var address = orderObjects[i].get('address');
// i为0是,左值为false故取右值,i>=0时,左值为true故取左值
var addressArray = that.data.addressArray || [];
addressArray.push(address);
that.setData({
addressArray: addressArray
});
}
// loop search order, fetch the Buy objects
for (var i = 0; i < orderObjects.length; i++) {
var order = orderObjects[i];
var queryMapping = new AV.Query('OrderGoodsMap');
queryMapping.include('goods');
queryMapping.equalTo('order', order);
queryMapping.find().then(function (mappingObjects) {
var mappingArray = [];
for (var j = 0; j < mappingObjects.length; j++) {
var mappingObject = mappingObjects[j];
var mapping = {
objectId: mappingObject.get('goods').get('objectId'),
avatar: mappingObject.get('goods').get('avatar'),
title: mappingObject.get('goods').get('title'),
price: mappingObject.get('goods').get('price'),
quantity: mappingObject.get('quantity')
};
mappingArray.push(mapping);
}
// 找出orderObjectId所在的索引位置,来得到k的值
var k = 0;
var orders = that.data.orders;
for (var index = 0; index < orders.length; index++) {
var order = orders[index];
if (order.get('objectId') == mappingObject.get('order').get('objectId')) {
k = index;
break;
}
}
var mappingData = that.data.mappingData == undefined ? [] : that.data.mappingData;
mappingData[k] = mappingArray;
that.setData({
mappingData: mappingData
});
});
}
});
},
pay: function(e) {
var objectId = e.currentTarget.dataset.objectId;
var totalFee = e.currentTarget.dataset.totalFee;
wx.navigateTo({
url: '../payment/payment?orderId=' + objectId + '&totalFee=' + totalFee
});
},
receive: function(e) {
var that = this;
wx.showModal({
title: '请确认',
content: '确认要收货吗',
success: function(res) {
if (res.confirm) {
var objectId = e.currentTarget.dataset.objectId;
var order = new AV.Object.createWithoutData('Order', objectId);
order.set('status', 3);
order.save().then(function () {
wx.showToast({
'title': '确认成功'
});
that.reloadData();
});
}
}
})
},
showGoods: function (e) {
var objectId = e.currentTarget.dataset.objectId;
wx.navigateTo({
url: '../../goods/detail/detail?objectId=' + objectId
});
}
}); |
<filename>source/NuGet/javascript/content/Scripts/application/models/session.js
var Application;
(function (_, Backbone, Application) {
var Models = Application.Models || (Application.Models = {});
Models.Session = Backbone.Model.extend({
urlRoot: function () {
return Application.serverUrlPrefix + '/sessions';
},
defaults: function () {
return {
email: null,
password: <PASSWORD>,
rememberMe: false
};
},
validate: function (attributes) {
var Validation = Models.Validation;
var errors = {};
if (!attributes.email) {
Validation.addError(errors, 'email', 'Email is required.');
}
if (!attributes.password) {
Validation.addError(
errors,
'password',
'Password is required.');
}
return _.isEmpty(errors) ? void (0) : errors;
}
});
})(_, Backbone, Application || (Application = {}));
|
function countChar(string, char){
let count = 0;
for(let i=0; i < string.length; i++){
if(string.charAt(i).toLowerCase() === char.toLowerCase()){
count++;
}
}
return count;
}
# example
console.log(countChar('Hello world!', 'l')) |
import { useState } from "react";
function useJledi() {
const [open, setOpen] = useState();
const handleClose = () => {
setOpen(false);
};
const handleOpen = () => {
setOpen(true);
};
const toggleOpen = () => {
setOpen(!open);
};
return { open, handleClose, handleOpen, toggleOpen };
}
export default useJledi;
|
# Restart docker since now the mnt drive is writeable
service docker restart
docker run hello-world
if [ $? -ne 0 ]
then
exit 1
fi
# Remove the file that allows dotnet-bot paswordless, nointeractive sudoing (since we are done sudoing now).
rm /etc/sudoers.d/zzz-dotnet-bot
# Test mkdir
mkdir /mnt/j
# Make the /mnt folder writeable
chmod 777 /mnt/j
if [ $? -ne 0 ]; then
echo "Could not mkdir, VM not ready for use"
fi |
#! /usr/local/bin/ksh93 -p
#
# CDDL HEADER START
#
# The contents of this file are subject to the terms of the
# Common Development and Distribution License (the "License").
# You may not use this file except in compliance with the License.
#
# You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
# or http://www.opensolaris.org/os/licensing.
# See the License for the specific language governing permissions
# and limitations under the License.
#
# When distributing Covered Code, include this CDDL HEADER in each
# file and include the License file at usr/src/OPENSOLARIS.LICENSE.
# If applicable, add the following below this CDDL HEADER, with the
# fields enclosed by brackets "[]" replaced with your own identifying
# information: Portions Copyright [yyyy] [name of copyright owner]
#
# CDDL HEADER END
#
# $FreeBSD$
#
# Copyright 2007 Sun Microsystems, Inc. All rights reserved.
# Use is subject to license terms.
#
# ident "@(#)clean_mirror_004_pos.ksh 1.2 07/01/09 SMI"
#
. $STF_SUITE/include/libtest.kshlib
. $STF_SUITE/tests/clean_mirror/clean_mirror_common.kshlib
###############################################################################
#
# __stc_assertion_start
#
# ID: clean_mirror_004_pos
#
# DESCRIPTION:
# The secondary side of a zpool mirror can be mangled without causing damage
# to the data in the pool
#
# STRATEGY:
# 1) Write several files to the ZFS filesystem in the mirrored pool
# 2) dd from /dev/urandom over the secondary side of the mirror
# 3) verify that all the file contents are unchanged on the file system
#
# TESTABILITY: explicit
#
# TEST_AUTOMATION_LEVEL: automated
#
# CODING_STATUS: COMPLETED (2005-07-04)
#
# __stc_assertion_end
#
################################################################################
verify_runnable "global"
log_assert "The primary side of a zpool mirror may be completely mangled" \
"without affecting the content of the pool"
overwrite_verify_mirror $SIDE_SECONDARY /dev/urandom
log_pass "The overwrite had no effect on the data"
|
package dao;
import conexao.Call;
import conexao.Conexao;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import modelo.Comobox;
import sessao.SessionUtil;
import validacao.OperacaoData;
public class PagamentoDao
{
private CallableStatement cs;
private String sql;
private Connection con;
private ResultSet rs;
private PreparedStatement ps;
private String resultado;
/**
* Registrar a forma de pagamento
* @param nome a forma de pagamento
* @param idUtilizador número do utilizador que registrou a forma de pagamento
*/
public void registrarFontePagamento(String nome)
{
sql="{call PRC_REG_FONTEPAGAMENTO(?,?,?)}";
Conexao conexao = new Conexao();
if(conexao.getCon()!=null)
{
try
{
cs = conexao.getCon().prepareCall(sql);
cs.setString(1, nome);
cs.setString(2, SessionUtil.getUserlogado().getNif());
cs.setInt(3, SessionUtil.getUserlogado().getIdAgencia());
cs.execute();
conexao.desCon();
}
catch (SQLException ex)
{
Logger.getLogger(PagamentoDao.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("Erro a registrar fonte de pagamento");
}
}
}
/**
* @param idUtilizador número do utilizador
* @param designacao nome do tipo de pagamento
*/
public void registrarTipoPagamento( String designacao)
{
sql="{call PRC_REG_TIPOPAGAMENTO(?,?,?)}";
Conexao conexao = new Conexao();
if(conexao.getCon()!=null)
{
try
{
cs = conexao.getCon().prepareCall(sql);
cs.setString(1, SessionUtil.getUserlogado().getNif());
cs.setString(2, designacao);
cs.setInt(3, SessionUtil.getUserlogado().getIdAgencia());
cs.execute();
conexao.desCon();
}
catch (SQLException ex)
{
Logger.getLogger(PagamentoDao.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("Erro a registrar tipo de pagamento "+ex.getMessage());
}
}
}
// function to search payment
public ResultSet buscarPagamento(String codigoPagamento)
{
sql="{?=call FUNC_SEARCH_PAGAMENTO(?)}";
Conexao conexao = new Conexao();
if(conexao.getCon()!=null)
{
try
{
cs = conexao.getCon().prepareCall(sql);
cs.setString(1, codigoPagamento);
cs.execute();
rs = cs.getResultSet();
}
catch (SQLException ex)
{
Logger.getLogger(PagamentoDao.class.getName()).log(Level.SEVERE, null, ex);
}
}
return rs;
}
// lista todos os bancos
public ArrayList<Comobox> listaBancos()
{
@SuppressWarnings("MismatchedQueryAndUpdateOfCollection")
ArrayList<Comobox> al= new ArrayList<>();
ResultSet rs = null;
sql="select * FROM VER_BANCO";
Conexao conexao = new Conexao();
if(conexao.getCon()!=null)
{
try
{
cs = conexao.getCon().prepareCall(sql);
cs.execute();
rs=cs.executeQuery();
if (rs!=null)
{
while (rs.next())
{
al.add(new Comobox(rs.getString("ID"), rs.getString("NOME")));
}
}
rs.close();
}
catch (SQLException ex)
{
Logger.getLogger(CreditoDao.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("Erro a obter bancos "+ex.getMessage());
}
}
return al;
}
public String devolverNome(String id)
{
sql="select * FROM VER_BANCO WHERE ID=?";
Conexao conexao = new Conexao();
if(conexao.getCon()!=null)
{
try
{
ps = conexao.getCon().prepareStatement(sql);
ps.setString(1, id);
ps.execute();
rs = ps.getResultSet();
if(rs!=null)
{
while(rs.next())
{
resultado = rs.getString("NOME");
}
}
rs.close();
conexao.desCon();
} catch (SQLException ex) {
Logger.getLogger(PagamentoDao.class.getName()).log(Level.SEVERE, null, ex);
}
}
return resultado;
}
public String devolverNomeAgencia(String id)
{
sql="select * FROM VER_AGENCIA WHERE ID=?";
Conexao conexao = new Conexao();
if(conexao.getCon()!=null)
{
try
{
ps = conexao.getCon().prepareStatement(sql);
ps.setString(1, id);
ps.execute();
rs = ps.getResultSet();
if(rs!=null)
{
while(rs.next())
{
resultado = rs.getString("AGENCIA");
}
}
rs.close();
conexao.desCon();
} catch (SQLException ex) {
Logger.getLogger(PagamentoDao.class.getName()).log(Level.SEVERE, null, ex);
}
}
return resultado;
}
public String DadosPagamento(String id)
{
Conexao conexao = new Conexao();
if(conexao.getCon()!=null)
{
sql="{?=call FUNC_GET_DOCPAGAMENTO(?)}";
try
{
cs = conexao.getCon().prepareCall(sql);
cs.registerOutParameter(1, Types.VARCHAR);
cs.setString(2, id);
cs.execute();
resultado = cs.getString(1);
conexao.desCon();
System.out.println("DOC DATABASE = "+resultado);
}
catch (SQLException ex)
{
Logger.getLogger(CreditoDao.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("Erro a obter dados de pagamento "+ex.getMessage());
}
}
return resultado;
}
// efetua o pagamento como fonte semelhante
public String efetuarPagamento(String idPagamento,
String numDoc,String idBanco,String fonteP, float valorPrestacao, Date dataDocumentoPagamento)
{
sql ="{?=call FUNC_EFECTUAR_PAGANAOFAZEADO(?,?,?,?,?,?,?,?)}";
Conexao conexao = new Conexao();
if(conexao.getCon()!=null)
{
try
{
cs = conexao.getCon().prepareCall(sql);
cs.registerOutParameter(1, Types.VARCHAR);
cs.setString(2, idPagamento);
cs.setString(3, SessionUtil.getUserlogado().getNif());
cs.setString(4, numDoc);
cs.setString(5, idBanco);
cs.setString(6, fonteP);
cs.setFloat(7, valorPrestacao);
cs.setDate(8, OperacaoData.toSQLDate(dataDocumentoPagamento));
cs.setInt(9, SessionUtil.getUserlogado().getIdAgencia());
cs.execute();
resultado = cs.getString(1);
conexao.desCon();
}
catch (SQLException ex)
{
Logger.getLogger(CreditoDao.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("Erro a efetuar pagamento "+ex.getMessage());
}
}
return resultado;
}
public String EfetuarPagamento(int idPagamento,String numDoc,int idBanco,String tipoPagamento,float valorPrestacao,Date dataPagamentoPago)
{
resultado = (String) Call.callSampleFunction("FUNC_EFECTUAR_PAGAMENTO", Types.VARCHAR,
idPagamento,
Integer.valueOf(SessionUtil.getUserlogado().getNif()),
numDoc,
idBanco,
tipoPagamento,
valorPrestacao,
(dataPagamentoPago != null)? OperacaoData.toSQLDate(dataPagamentoPago): null,
SessionUtil.getUserlogado().getIdAgencia());
return resultado;
}
public Object RegObecto(String designacao,int tipoObjeto)
{
String functionName = "FUNC_REG_OBJECTO";
Object resp = Call.callSampleFunction(functionName,Types.INTEGER,
SessionUtil.getUserlogado().getNif(),
designacao,
tipoObjeto,
SessionUtil.getUserlogado().getIdAgencia()
);
return resp;
}
public ArrayList<Comobox> listaInfo(int tipoObjeto)
{
String functionName = "FUNCT_LOAD_ADM_OBJECTO";
ArrayList<Comobox> info = new ArrayList<>();
ResultSet rs = Call.callTableFunction(functionName, "*", tipoObjeto);
try
{
if(rs != null)
{
while(rs.next())
{
if(rs.getString("DESCRICAO") != null)
{
info.add( new Comobox(rs.getString("ID"), rs.getString("DESCRICAO")));
}
}
rs.close();
}
}
catch(SQLException ex)
{
System.out.println("erro a obter dados de pagamento "+ex.getMessage());
}
return info;
}
public void objectoDesativar(String idObjecto)
{
Call.callProcedure("PRC_OBJECT_DISATIVE",SessionUtil.getUserlogado().getNif(),idObjecto);
}
}
|
# -*- coding: utf-8 -*-
"""
This module provides an extension which starts a debugger when a step fails
"""
from radish.hookregistry import after
from radish.stepmodel import Step
from radish.extensionregistry import extension
import radish.utils as utils
@extension
class FailureDebugger(object):
"""
Failure debugger radish extension
"""
OPTIONS = [("--debug-after-failure", "start python debugger after failure")]
LOAD_IF = staticmethod(lambda config: config.debug_after_failure)
LOAD_PRIORITY = 20
def __init__(self):
after.each_step(self.failure_debugger)
def failure_debugger(self, step):
"""
Starts a python debugger if the step failed
"""
if step.state is not Step.State.FAILED:
return
pdb = utils.get_debugger()
pdb.set_trace()
|
public class CheckIfArrayContainsNumber {
public static boolean checkIfArrayContainsNumber(int[] arr, int num) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] == num) {
return true;
}
}
return false;
}
} |
<reponame>INC-PSTORE/psafe<gh_stars>0
/*
* table Pagination
*/
import {withStyles, withTheme} from '@material-ui/core/styles';
import React from 'react';
import {compose} from 'redux';
import styles from './styles';
import IconButton from "@material-ui/core/IconButton";
import LastPageIcon from "@material-ui/icons/LastPage";
import FirstPageIcon from "@material-ui/icons/FirstPage";
import KeyboardArrowRight from "@material-ui/icons/KeyboardArrowRight";
import KeyboardArrowLeft from "@material-ui/icons/KeyboardArrowLeft";
/* eslint-disable react/prefer-stateless-function */
export class TablePaginationActions extends React.PureComponent {
constructor(props) {
super(props);
}
handleFirstPageButtonClick = event => {
this.props.onChangePage(event, 0);
};
handleBackButtonClick = event => {
this.props.onChangePage(event, this.props.page - 1);
};
handleNextButtonClick = event => {
this.props.onChangePage(event, this.props.page + 1);
};
handleLastPageButtonClick = event => {
this.props.onChangePage(
event,
Math.max(0, Math.ceil(this.props.count / this.props.rowsPerPage) - 1),
);
};
render() {
const { classes, count, page, rowsPerPage } = this.props;
const theme = withTheme();
return (
<div className={classes.root}>
<IconButton
onClick={this.handleFirstPageButtonClick}
disabled={page === 0}
aria-label="First Page"
>
{theme && theme.direction === 'rtl' ? <LastPageIcon /> : <FirstPageIcon />}
</IconButton>
<IconButton
onClick={this.handleBackButtonClick}
disabled={page === 0}
aria-label="Previous Page"
>
{theme && theme.direction === 'rtl' ? <KeyboardArrowRight /> : <KeyboardArrowLeft />}
</IconButton>
<IconButton
onClick={this.handleNextButtonClick}
disabled={page >= Math.ceil(count / rowsPerPage) - 1}
aria-label="Next Page"
>
{theme && theme.direction === 'rtl' ? <KeyboardArrowLeft /> : <KeyboardArrowRight />}
</IconButton>
<IconButton
onClick={this.handleLastPageButtonClick}
disabled={page >= Math.ceil(count / rowsPerPage) - 1}
aria-label="Last Page"
>
{theme && theme.direction === 'rtl' ? <FirstPageIcon /> : <LastPageIcon />}
</IconButton>
</div>
);
}
}
const withMyStylesPagination = withStyles(styles);
export default compose(withMyStylesPagination)(TablePaginationActions);
|
#!/bin/bash -e
echo "================= Installing default-jdk & jre ==================="
apt-get install -q -y default-jre
apt-get install -q -y default-jdk
echo "================= Installing openjdk-8-jdk ==================="
add-apt-repository -y ppa:openjdk-r/ppa
apt-get update
apt-get install -q -y openjdk-8-jdk
update-alternatives --set java /usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java
update-alternatives --set javac /usr/lib/jvm/java-8-openjdk-amd64/bin/javac
add-apt-repository ppa:maarten-fonville/ppa
apt-get update
apt-get install -y -q icedtea-8-plugin=1.6*
update-alternatives --set javaws /usr/lib/jvm/java-8-openjdk-amd64/jre/bin/javaws
echo "================ Installing oracle-java8-installer ================="
echo oracle-java8-installer shared/accepted-oracle-license-v1-1 select true | debconf-set-selections
add-apt-repository -y ppa:webupd8team/java
apt-get update
apt-get install -y -q oracle-java8-installer
update-alternatives --set java /usr/lib/jvm/java-8-oracle/jre/bin/java
update-alternatives --set javac /usr/lib/jvm/java-8-oracle/bin/javac
update-alternatives --set javaws /usr/lib/jvm/java-8-oracle/jre/bin/javaws
echo 'export JAVA_HOME=/usr/lib/jvm/java-8-oracle' >> /etc/drydock/.env
echo 'export PATH=$PATH:/usr/lib/jvm/java-8-oracle/jre/bin' >> /etc/drydock/.env
|
#!/bin/sh
rm -rf pano-pto/
tar -xf pano-pto-1.tar.xz
|
#!/bin/bash
#-------------------------------------------------------------------------------------------------------------
#该脚本的使用方式为-->[sh xxx.sh start|stop|status|restart]
#该脚本可在服务器上的任意目录下执行,不会影响到日志的输出位置等
#-------------------------------------------------------------------------------------------------------------
# 公共参数,不要修改
PROJECT_NAME=bkci
# 服务相关修改
SERVICE_NAME=project
# HTTP端口的是占位符号 需要根据application-project.yml中设置的端口来替换
HTTP_PORT=__BKCI_PROJECT_API_PORT__
# 详细的日志console.log开关,放开注释即可打开
NOHUPLOG=/dev/null
#NOHUPLOG=${PROJECT_NAME}_${SERVICE_NAME}_console.log
#-------------------------------------------------------------------------------------------------------------
# 系统运行参数 运行环境: JDK_1.8+
#-------------------------------------------------------------------------------------------------------------
SERVICE_HOME=$(cd "$(dirname "$0")"; pwd)
if [[ ! -n "${BK_HOME}" ]]; then
BK_HOME=$(cd "$(dirname "$0")"/../..; pwd)
fi
#BK_HOME=$(cd ${BASH_SOURCE%/*}; echo ${PWD%%/${PROJECT_NAME}*})
#if [[ -f ${BK_HOME}/bksuite-${PROJECT_NAME}.env ]]; then
# source ${BK_HOME}/bksuite-${PROJECT_NAME}.env
#fi
CONF_HOME=${BK_HOME}/etc/${PROJECT_NAME}
SHELL_FILE_NAME=${0##*/}
APP_PRIVATE_CONF_DIR=${SERVICE_HOME}/config
JAR_FILE=${SERVICE_HOME}/boot-${SERVICE_NAME}.jar
LOGS_HOME=${BK_HOME}/logs/${PROJECT_NAME}/${SERVICE_NAME}/
if [[ -z "${CERT_PATH}" ]]; then
CERT_PATH=${BK_HOME}/cert
fi
if [[ ! -n "${JAVA_HOME}" ]]||[[ ! -d "${JAVA_HOME}" ]]; then
JAVA_HOME="${BK_HOME}/service/java"
if [[ ! -d "${JAVA_HOME}" ]]; then
JAVA_HOME="${BK_HOME}/common/java"
fi
export JAVA_HOME
export PATH=${JAVA_HOME}/bin:$PATH
fi
export CLASSPATH=${APP_PRIVATE_CONF_DIR}:.
function getPID(){
javaps=`${JAVA_HOME}/bin/jps -l | grep "${JAR_FILE}"`
if [[ -n "$javaps" ]]; then
PID=`echo ${javaps} | awk '{print $1}'`
else
PID=0
fi
}
HTTP_PORT_STATUS=0
# 启动job服务器
function startup() {
WEB_BASEDIR=${SERVICE_HOME}/rundata
# 说明:以下最小内存和最大内存 当配置时最好配置成一样的,32GB机器上配置16GB内存,64GB机器配置32GB内存
# export JOB_JAVA_OPTS="-Xms8g -Xmx8g"
# JAVA_OPTS="-Dserver.address=__LAN_IP__"
# JAVA_OPTS="$JAVA_OPTS -XX:ParallelGCThreads=8 -XX:+UseConcMarkSweepGC -XX:MaxGCPauseMillis=800"
# JAVA_OPTS="$JAVA_OPTS -XX:+PrintGCDetails -XX:+PrintGCDateStamps -XX:+PrintGCTimeStamps -Xloggc:$LOGS_HOME/gc_${SERVICE_NAME}.log "
JAVA_OPTS="$JAVA_OPTS -server -Dfile.encoding=UTF-8 -Djava.security.egd=file:/dev/./urandom"
JAVA_OPTS="$JAVA_OPTS -Dspring.config.location=file:${CONF_HOME}/common.yml,file:${CONF_HOME}/application-${SERVICE_NAME}.yml"
JAVA_OPTS="$JAVA_OPTS -Dservice.log.dir=${LOGS_HOME}"
export JAVA_OPTS
getPID
if [[ ${PID} -ne 0 ]]; then
echo "${PROJECT_NAME}-${SERVICE_NAME} already started(PID=$PID)"
else
echo -n "Starting ${PROJECT_NAME}-${SERVICE_NAME}"
if [[ ! -d "${LOGS_HOME}" ]]; then
mkdir -p "${LOGS_HOME}"
fi
checkPortStatus
if [[ ${HTTP_PORT_STATUS} -ne 0 ]]; then
echo "[Failed]-- http port ${HTTP_PORT} has been used!"
exit 1
fi
nohup ${JAVA_HOME}/bin/java ${JAVA_OPTS} -classpath ${CLASSPATH} -jar ${JAR_FILE} > ${NOHUPLOG} 2>&1 &
for i in $(seq 100)
do
sleep 0.5
echo -e ".\c"
getPID
if [[ ${PID} -ne 0 ]]; then
checkPortStatus " ${PID} "
if [[ ${HTTP_PORT_STATUS} -gt 0 ]]; then
break;
fi
fi
done
getPID
if [[ ${PID} -eq 0 ]]; then
echo "[Failed]"
exit 1
fi
checkPortStatus " ${PID} "
if [[ ${HTTP_PORT_STATUS} -eq 0 ]]; then
echo "[Failed]-- http port ${HTTP_PORT} start fail!"
exit 1
fi
echo "(PID=$PID)...[Success]"
fi
}
function checkPortStatus() {
# $1 is pid
if [[ -n "$1" ]]; then
dataTmp1=`lsof -nP -iTCP:${HTTP_PORT} -sTCP:LISTEN | grep "$1" -c`
else
dataTmp1=`lsof -nP -iTCP:${HTTP_PORT} -sTCP:LISTEN | wc -l`
fi
if [[ -n "${dataTmp1}" ]]; then
HTTP_PORT_STATUS=`echo ${dataTmp1} | awk '{print $1}'`
else
HTTP_PORT_STATUS=0
fi
}
# 停止job服务器
function shutdown(){
getPID
if [[ ${PID} -ne 0 ]]; then
echo -n "Stopping ${PROJECT_NAME}-${SERVICE_NAME}(PID=${PID})..."
kill ${PID}
if [[ $? -ne 0 ]]; then
echo "[Failed]"
exit 1
fi
for i in $(seq 20)
do
sleep 0.5
getPID
if [[ ${PID} -eq 0 ]]; then
checkPortStatus " ${PID} "
if [[ ${HTTP_PORT_STATUS} -eq 0 ]]; then
break
fi
fi
echo -e ".\c"
done
getPID
if [[ ${PID} -eq 0 ]]; then
echo "[Success]"
else
kill -9 ${PID}
if [[ $? -ne 0 ]]; then
echo "[Failed]"
exit 1
fi
echo "some task is running in background,force stop it.[Success]"
fi
else
echo "${PROJECT_NAME}-${SERVICE_NAME} is not running"
fi
}
function getServerStatus(){
getPID
if [[ ${PID} -ne 0 ]]; then
checkPortStatus " ${PID} "
if [[ ${HTTP_PORT_STATUS} -eq 0 ]]; then
echo "${PROJECT_NAME}-${SERVICE_NAME} port ${HTTP_PORT} is not listening(PID=${PID})";
exit 99;
fi
echo "${PROJECT_NAME}-${SERVICE_NAME} is running(PID=${PID})"
else
echo "${PROJECT_NAME}-${SERVICE_NAME} is not running"
fi
}
# 重启JOB
function restart(){
shutdown
sleep 1
startup
}
case "$1" in
restart)
restart
;;
start)
startup
;;
stop)
shutdown
;;
status)
getServerStatus
;;
*)
echo $"Usage: ${SHELL_FILE_NAME} {start|stop|status|restart}"
esac |
#!/bin/sh
# CYBERWATCH SAS - 2017
#
# Security fix for RHSA-2009:1203
#
# Security announcement date: 2009-08-10 18:17:48 UTC
# Script generation date: 2017-01-01 21:12:31 UTC
#
# Operating System: Red Hat 5
# Architecture: x86_64
#
# Vulnerable packages fix on version:
# - subversion.i386:1.4.2-4.el5_3.1
# - subversion-debuginfo.i386:1.4.2-4.el5_3.1
# - subversion-devel.i386:1.4.2-4.el5_3.1
# - mod_dav_svn.x86_64:1.4.2-4.el5_3.1
# - subversion.x86_64:1.4.2-4.el5_3.1
# - subversion-debuginfo.x86_64:1.4.2-4.el5_3.1
# - subversion-devel.x86_64:1.4.2-4.el5_3.1
# - subversion-javahl.x86_64:1.4.2-4.el5_3.1
# - subversion-perl.x86_64:1.4.2-4.el5_3.1
# - subversion-ruby.x86_64:1.4.2-4.el5_3.1
#
# Last versions recommanded by security team:
# - subversion.i386:1.6.11-12.el5_10
# - subversion-debuginfo.i386:1.6.11-12.el5_10
# - subversion-devel.i386:1.6.11-12.el5_10
# - mod_dav_svn.x86_64:1.6.11-12.el5_10
# - subversion.x86_64:1.6.11-12.el5_10
# - subversion-debuginfo.x86_64:1.6.11-12.el5_10
# - subversion-devel.x86_64:1.6.11-12.el5_10
# - subversion-javahl.x86_64:1.6.11-12.el5_10
# - subversion-perl.x86_64:1.6.11-12.el5_10
# - subversion-ruby.x86_64:1.6.11-12.el5_10
#
# CVE List:
# - CVE-2009-2411
#
# More details:
# - https://www.cyberwatch.fr/vulnerabilites
#
# Licence: Released under The MIT License (MIT), See LICENSE FILE
sudo yum install subversion.i386-1.6.11 -y
sudo yum install subversion-debuginfo.i386-1.6.11 -y
sudo yum install subversion-devel.i386-1.6.11 -y
sudo yum install mod_dav_svn.x86_64-1.6.11 -y
sudo yum install subversion.x86_64-1.6.11 -y
sudo yum install subversion-debuginfo.x86_64-1.6.11 -y
sudo yum install subversion-devel.x86_64-1.6.11 -y
sudo yum install subversion-javahl.x86_64-1.6.11 -y
sudo yum install subversion-perl.x86_64-1.6.11 -y
sudo yum install subversion-ruby.x86_64-1.6.11 -y
|
package org.jaudiotagger.tag.mp4;
import junit.framework.TestCase;
import org.jaudiotagger.AbstractTestCase;
import org.jaudiotagger.audio.AudioFile;
import org.jaudiotagger.audio.AudioFileIO;
import org.jaudiotagger.audio.mp4.EncoderType;
import org.jaudiotagger.audio.mp4.Mp4AudioHeader;
import org.jaudiotagger.audio.mp4.atom.Mp4EsdsBox;
import org.jaudiotagger.tag.FieldKey;
import org.jaudiotagger.tag.Tag;
import java.io.File;
import java.util.List;
/**
*/
public class M4aReadDrmTagTest extends TestCase
{
/**
* Test to read all metadata from an Apple iTunes encoded mp4 file, note also uses fixed genre rather than
* custom genre
*/
public void testReadFile()
{
Exception exceptionCaught = null;
try
{
File orig = new File("testdata", "test9.m4p");
if (!orig.isFile())
{
return;
}
File testFile = AbstractTestCase.copyAudioToTmp("test9.m4p");
AudioFile f = AudioFileIO.read(testFile);
Tag tag = f.getTag();
System.out.println(f.getAudioHeader());
System.out.println(tag);
//AudioInfo
//Time in seconds
assertEquals(329, f.getAudioHeader().getTrackLength());
assertEquals(44100, f.getAudioHeader().getSampleRateAsNumber());
assertEquals(new String("2"), f.getAudioHeader().getChannels());
assertEquals(128, f.getAudioHeader().getBitRateAsNumber());
assertEquals(EncoderType.DRM_AAC.getDescription(), f.getAudioHeader().getEncodingType());
//MPEG Specific
Mp4AudioHeader audioheader = (Mp4AudioHeader) f.getAudioHeader();
assertEquals(Mp4EsdsBox.Kind.MPEG4_AUDIO, audioheader.getKind());
assertEquals(Mp4EsdsBox.AudioProfile.LOW_COMPLEXITY, audioheader.getProfile());
//Ease of use methods for common fields
assertEquals("The King Of The Slums", tag.getFirst(FieldKey.ARTIST));
assertEquals("Barbarous English Fayre", tag.getFirst(FieldKey.ALBUM));
assertEquals("Simpering Blonde Bombshell", tag.getFirst(FieldKey.TITLE));
assertEquals("1990-01-01T08:00:00Z", tag.getFirst(FieldKey.YEAR));
assertEquals("1", tag.getFirst(FieldKey.TRACK));
assertEquals("12", tag.getFirst(FieldKey.TRACK_TOTAL));
assertEquals("Rock", tag.getFirst(FieldKey.GENRE));
//Cast to format specific tag
Mp4Tag mp4tag = (Mp4Tag) tag;
//Lookup by mp4 key
assertEquals("The King Of The Slums", mp4tag.getFirst(Mp4FieldKey.ARTIST));
assertEquals("Barbarous English Fayre", mp4tag.getFirst(Mp4FieldKey.ALBUM));
assertEquals("Simpering Blonde Bombshell", mp4tag.getFirst(Mp4FieldKey.TITLE));
List coverart = mp4tag.get(Mp4FieldKey.ARTWORK);
//Should be one image
assertEquals(1, coverart.size());
}
catch (Exception e)
{
e.printStackTrace();
exceptionCaught = e;
}
assertNull(exceptionCaught);
}
}
|
using System;
using System.Collections.Generic;
public class ResourceManager : IDisposable
{
private Dictionary<string, bool> resources = new Dictionary<string, bool>();
public bool AcquireResource(string resourceId)
{
if (resources.ContainsKey(resourceId) && !resources[resourceId])
{
resources[resourceId] = true;
return true;
}
return false;
}
public bool ReleaseResource(string resourceId)
{
if (resources.ContainsKey(resourceId) && resources[resourceId])
{
resources[resourceId] = false;
return true;
}
return false;
}
public void CleanupResources()
{
foreach (var resource in resources)
{
if (resource.Value)
{
resources[resource.Key] = false;
}
}
}
public void Dispose()
{
CleanupResources();
resources.Clear();
}
} |
import numpy as np
def interpolate_signal(frequency_range, freqs, cuda_res, numpy_res, idx):
# Calculate the absolute values of the original signal
cuda_res_abs = np.abs(cuda_res)
numpy_res_abs = np.abs(numpy_res)
# Interpolate the real parts of the original signal values at the given frequency range
interpolated_cuda_res = np.interp(frequency_range, freqs[idx], cuda_res_abs[idx].real)
interpolated_numpy_res = np.interp(frequency_range, freqs[idx], numpy_res_abs[idx].real)
return interpolated_cuda_res, interpolated_numpy_res |
const yuri2 = require('yuri2js');
module.exports = async function (ctx,gets) {
await yuri2.exec(gets.cmd).then(function (rel) {
ctx.res.send({output:rel})
}).catch(function (err) {
ctx.res.send({output:err})
})
}; |
'''
Classes to generate the Example.com sitemap based on django.contrib.sitemaps.
'''
from django.contrib.sitemaps import Sitemap
from django.utils.datetime_safe import datetime
from canvas.models import Category, Visibility, Comment
from django.core import urlresolvers
from django.conf import settings
import urlparse
from canvas import util
class BaseSitemap(Sitemap):
def get_urls(self, page=1, site=None):
""" A hack so that we don't have to use django.sites
"""
urls = super(BaseSitemap, self).get_urls(page, site)
if site.domain != settings.DOMAIN:
for url in urls:
url['location'] = url['location'].replace("http://"+site.domain, "", 1)
return urls
class Categories(BaseSitemap):
# Crawling category pages is important.
priority = 1.0
def items(self):
""" Returns a list of categories that are visibile.
"""
return Category.objects.filter(visibility=Visibility.PUBLIC)
def last_mod(self, category):
"""
The last time this URL has changed. For categories, we use the current time because groups get posted to all
the time.
@TODO: Figure out a way to get a more precise last_mod time
"""
return datetime.now()
def location(self, category):
return util.make_absolute_url(category.get_absolute_url(), "http:")
#class Threads(BaseSitemap):
# priority = 0.7
#
# def items(self):
# threads = Comment.objects.filter(parent_comment=None, visibility=Visibility.PUBLIC).order(score)
class StaticSitemap(BaseSitemap):
"""
Generates a sitemp for the static/direct_to_template pages.
"""
priority = 0.5
url_patterns = []
def __init__(self, url_patterns):
self.url_patterns = url_patterns
def items(self):
return self.url_patterns
def changefreq(self, obj):
return 'monthly'
def location(self, regex_url):
relative_url = regex_url.regex.pattern.replace("^", "/").replace("$", "")
return util.make_absolute_url(relative_url, "http")
|
/*
* sbt
* Copyright 2011 - 2017, Lightbend, Inc.
* Copyright 2008 - 2010, <NAME>
* Licensed under BSD-3-Clause license (see LICENSE)
*/
package sbt.internal.parser
import org.specs2.mutable._
trait AbstractSpec extends Specification with SplitExpression
|
// scriptish is a library to help you port bash scripts to Golang
//
// inspired by:
//
// - http://labix.org/pipe
// - https://github.com/bitfield/script
//
// Copyright 2019-present Ganbaro Digital Ltd
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in
// the documentation and/or other materials provided with the
// distribution.
//
// * Neither the names of the copyright holders nor the names of his
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
package scriptish
import (
"errors"
"testing"
"github.com/stretchr/testify/assert"
)
func TestRunPipelineExecutesAnotherPipeline(t *testing.T) {
// ----------------------------------------------------------------
// setup your test
testData := []string{
"this is the first line of test data",
"this is the second line of test data",
"this is the third line of test data",
"this is the fourth line of test data",
"this is the fifth line of test data",
}
expectedResult := "3\n"
subPipeline := NewPipeline(
Head(3),
CountLines(),
)
pipeline := NewPipeline(
EchoSlice(testData),
RunPipeline(subPipeline),
)
// ----------------------------------------------------------------
// perform the change
actualResult, err := pipeline.Exec().String()
// ----------------------------------------------------------------
// test the results
assert.Nil(t, err)
assert.Equal(t, expectedResult, actualResult)
}
func TestRunPipelineReturnsSubPipelinesError(t *testing.T) {
// ----------------------------------------------------------------
// setup your test
expectedError := errors.New("this is the error from our sub-pipeline")
op1 := NewSequenceStep(
func(p *Pipe) (int, error) {
return StatusNotOkay, expectedError
},
)
subPipeline := NewPipeline(
op1,
)
pipeline := NewPipeline(
RunPipeline(subPipeline),
)
// ----------------------------------------------------------------
// perform the change
_, err := pipeline.Exec().String()
// ----------------------------------------------------------------
// test the results
assert.NotNil(t, err)
assert.Equal(t, expectedError, err)
}
|
#!bin/bash
export EPA_SECRET_KEY="dummy"
export DEBUG="True"
export EMAIL_HOST_IP="127.0.0.1"
export USE_PROXY="False"
export PROXY_ADDRESS="http://proxy_address:port"
export MVS_API_HOST="https://mvs-open-plan.rl-institut.de"
export DATABASE="mysql"
export EXCHANGE_ACCOUNT="dummy@rl-institut.de"
export EXCHANGE_PW="dummy"
export EXCHANGE_EMAIL="dummy@rl-institut.de"
export EXCHANGE_SERVER="dummy"
export RECIPIENTS="dummy@b.de,dummy@a.com" |
python transformers/examples/language-modeling/run_language_modeling.py --model_name_or_path train-outputs/512+512+512-SS-N/13-model --tokenizer_name model-configs/1536-config --eval_data_file ../data/wikitext-103-raw/wiki.valid.raw --output_dir eval-outputs/512+512+512-SS-N/13-1024+0+512-N-VB-ADJ-first-256 --do_eval --per_device_eval_batch_size 1 --dataloader_drop_last --augmented --augmentation_function remove_all_but_nouns_verbs_and_adjectives_first_two_thirds_sixth --eval_function penultimate_sixth_eval |
<reponame>tamanna037/commons-geometry
/*
* 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.commons.geometry.io.euclidean.threed.obj;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.geometry.euclidean.threed.Vector3D;
import org.apache.commons.geometry.io.core.internal.SimpleTextParser;
/** Abstract base class for OBJ parsing functionality.
*/
public abstract class AbstractObjParser {
/** Text parser instance. */
private final SimpleTextParser parser;
/** The current (most recently parsed) keyword. */
private String currentKeyword;
/** Construct a new instance for parsing OBJ content from the given text parser.
* @param parser text parser to read content from
*/
protected AbstractObjParser(final SimpleTextParser parser) {
this.parser = parser;
}
/** Get the current keyword, meaning the keyword most recently parsed via the {@link #nextKeyword()}
* method. Null is returned if parsing has not started or the end of the content has been reached.
* @return the current keyword or null if parsing has not started or the end
* of the content has been reached
*/
public String getCurrentKeyword() {
return currentKeyword;
}
/** Advance the parser to the next keyword, returning true if a keyword has been found
* and false if the end of the content has been reached. Keywords consist of alphanumeric
* strings placed at the beginning of lines. Comments and blank lines are ignored.
* @return true if a keyword has been found and false if the end of content has been reached
* @throws IOException if an I/O error occurs
* @throws IllegalStateException if invalid content is found
*/
public boolean nextKeyword() throws IOException {
currentKeyword = null;
// advance to the next line if not at the start of a line
if (parser.getColumnNumber() != 1) {
discardDataLine();
}
// search for the next keyword
while (currentKeyword == null && parser.hasMoreCharacters()) {
if (!nextDataLineContent() ||
parser.peekChar() == ObjConstants.COMMENT_CHAR) {
// use a standard line discard here so we don't interpret line continuations
// within comments; the interpreted OBJ content should be the same regardless
// of the presence of comments
parser.discardLine();
} else if (parser.getColumnNumber() != 1) {
throw parser.parseError("non-blank lines must begin with an OBJ keyword or comment character");
} else if (!readKeyword()) {
throw parser.unexpectedToken("OBJ keyword");
} else {
final String keywordValue = parser.getCurrentToken();
handleKeyword(keywordValue);
currentKeyword = keywordValue;
// advance past whitespace to the next data value
discardDataLineWhitespace();
}
}
return currentKeyword != null;
}
/** Read the remaining content on the current data line, taking line continuation characters into
* account.
* @return remaining content on the current data line or null if the end of the content has
* been reached
* @throws IOException if an I/O error occurs
*/
public String readDataLine() throws IOException {
parser.nextWithLineContinuation(
ObjConstants.LINE_CONTINUATION_CHAR,
SimpleTextParser::isNotNewLinePart)
.discardNewLineSequence();
return parser.getCurrentToken();
}
/** Discard remaining content on the current data line, taking line continuation characters into
* account.
* @throws IOException if an I/O error occurs
*/
public void discardDataLine() throws IOException {
parser.discardWithLineContinuation(
ObjConstants.LINE_CONTINUATION_CHAR,
SimpleTextParser::isNotNewLinePart)
.discardNewLineSequence();
}
/** Read a whitespace-delimited 3D vector from the current data line.
* @return vector vector read from the current line
* @throws IOException if an I/O error occurs
*/
public Vector3D readVector() throws IOException {
discardDataLineWhitespace();
final double x = nextDouble();
discardDataLineWhitespace();
final double y = nextDouble();
discardDataLineWhitespace();
final double z = nextDouble();
return Vector3D.of(x, y, z);
}
/** Read whitespace-delimited double values from the current data line.
* @return double values read from the current line
* @throws IOException if an I/O error occurs
* @throws IllegalStateException if double values are not able to be parsed
*/
public double[] readDoubles() throws IOException {
final List<Double> list = new ArrayList<>();
while (nextDataLineContent()) {
list.add(nextDouble());
}
// convert to primitive array
final double[] arr = new double[list.size()];
for (int i = 0; i < list.size(); ++i) {
arr[i] = list.get(i);
}
return arr;
}
/** Get the text parser for the instance.
* @return text parser for the instance
*/
protected SimpleTextParser getTextParser() {
return parser;
}
/** Method called when a keyword is encountered in the parsed OBJ content. Subclasses should use
* this method to validate the keyword and/or update any internal state.
* @param keyword keyword encountered in the OBJ content
* @throws IOException if an I/O error occurs
* @throws IllegalStateException if the given keyword is invalid
*/
protected abstract void handleKeyword(String keyword) throws IOException;
/** Discard whitespace on the current data line, taking line continuation characters into account.
* @return text parser instance
* @throws IOException if an I/O error occurs
*/
protected SimpleTextParser discardDataLineWhitespace() throws IOException {
return parser.discardWithLineContinuation(
ObjConstants.LINE_CONTINUATION_CHAR,
SimpleTextParser::isLineWhitespace);
}
/** Discard whitespace on the current data line and return true if any more characters
* remain on the line.
* @return true if more non-whitespace characters remain on the current data line
* @throws IOException if an I/O error occurs
*/
protected boolean nextDataLineContent() throws IOException {
return discardDataLineWhitespace().hasMoreCharactersOnLine();
}
/** Get the next whitespace-delimited double on the current data line.
* @return the next whitespace-delimited double on the current line
* @throws IOException if an I/O error occurs
* @throws IllegalStateException if a double value is not able to be parsed
*/
protected double nextDouble() throws IOException {
return parser.nextWithLineContinuation(ObjConstants.LINE_CONTINUATION_CHAR,
SimpleTextParser::isNotWhitespace)
.getCurrentTokenAsDouble();
}
/** Read a keyword consisting of alphanumeric characters from the current parser position and set it
* as the current token. Returns true if a non-empty keyword was found.
* @return true if a non-empty keyword was found.
* @throws IOException if an I/O error occurs
*/
private boolean readKeyword() throws IOException {
return parser
.nextWithLineContinuation(ObjConstants.LINE_CONTINUATION_CHAR, SimpleTextParser::isAlphanumeric)
.hasNonEmptyToken();
}
}
|
import Web3 from 'web3'
import {ethers} from 'ethers'
import {MemberERC721ContractConstruct} from '@/contracts/construct'
import {MemberNFTDeployFormData} from '@/types/MemberNFT'
export const deployMemberNFT = async (
inputData: MemberNFTDeployFormData
): Promise<string> => {
let memberNFTTokenAddress = ''
if (typeof window.ethereum !== 'undefined') {
const provider = new ethers.providers.Web3Provider(window.ethereum)
const signer = provider.getSigner()
const factory = new ethers.ContractFactory(
MemberERC721ContractConstruct.abi,
MemberERC721ContractConstruct.bytecode,
signer
)
await factory
.deploy(
inputData.name,
inputData.symbol,
inputData.token_uri,
inputData.subdao_address
)
.then((res: any) => {
console.log(res)
alert('Succeeded to deploy member NFT contract')
memberNFTTokenAddress = res.address
return memberNFTTokenAddress
})
.catch((err: any) => {
console.log(err)
alert('Failed to deploy member NFT contract')
})
}
return memberNFTTokenAddress
}
export const mintMemberNFT = async (
memberNFTTokenAddress: string
): Promise<string> => {
let id: string = ''
console.log("memberNFT address: ",memberNFTTokenAddress);
if (
typeof window.ethereum !== 'undefined' &&
typeof memberNFTTokenAddress !== 'undefined'
) {
const provider = new ethers.providers.Web3Provider(window.ethereum)
const signer = provider.getSigner()
const signerAddress = await signer.getAddress()
const contract = new ethers.Contract(
memberNFTTokenAddress,
MemberERC721ContractConstruct.abi,
signer
)
contract
.original_mint(signerAddress, {value: Web3.utils.toWei('10')})
.then((d: any) => {
// console.log(d)
id = d.address
alert('Succeeded to mint member NFT!')
const filters = contract.filters['IssuedMemberToken']
if (filters !== undefined) {
provider.once('block', () => {
contract.on(filters(), (to, tokenID) => {
console.log(to, tokenID)
id = tokenID
console.log(id)
})
})
}
id = '3'
})
.catch((err: any) => {
console.log(err)
alert('Failed to mint member NFT!')
})
}
return id
}
export const checkNFTMinted = async (
memberNFTTokenAddress: string
): Promise<string> => {
if (
typeof window.ethereum !== "undefined" &&
typeof memberNFTTokenAddress !== "undefined"
) {
const provider = new ethers.providers.Web3Provider(window.ethereum);
const signer = provider.getSigner();
const signerAddress = await signer.getAddress();
const contract = new ethers.Contract(
memberNFTTokenAddress,
MemberERC721ContractConstruct.abi,
signer
);
let id = "";
let nId = await contract.ownedTokenId(signerAddress);
if (nId != 0) {
alert("You are already minted.Your Token Id is:" + nId);
id = String(nId);
}
return id;
}
return "";
};
|
require 'spec_helper'
describe "form_for().time_field", :type => :view do
describe "with default type" do
let(:sms){ FactoryGirl.create(:sms, :sent_at => Time.zone.parse('2011-12-22 14:45:00')) }
let(:tpl1){ render(:inline => FileMacros.load_view('sms_form_with_time'), :locals => { :sms => sms, :time_field_options => {:from_hour => 10, :to_hour => 22} }) } # time field from 10:00 to 22:00
let(:tpl2){ render(:inline => FileMacros.load_view('sms_form_with_time'), :locals => { :sms => sms, :time_field_options => {:from_hour => 9, :to_hour => 7} }) } # time field from 9:00 to 7:00
let(:tpl_24h){ render(:inline => FileMacros.load_view('sms_form_with_time'), :locals => { :sms => sms, :time_field_options => {:from_hour => 11, :to_hour => 11} }) } # time field from 11:00 to 10:45
it "should render successfully" do
tpl1.should_not be_nil
tpl2.should_not be_nil
tpl_24h.should_not be_nil
end
it "should have a time input" do
tpl1.should have_tag('select')
tpl1.should have_tag('select', :with => {:name => 'sms[sent_at_time]'})
tpl2.should have_tag('select')
tpl2.should have_tag('select', :with => {:name => 'sms[sent_at_time]'})
tpl_24h.should have_tag('select')
tpl_24h.should have_tag('select', :with => {:name => 'sms[sent_at_time]'})
end
it 'should have time input select options' do
tpl1.should have_tag('select') do
%w{10:00 15:45 21:45 22:00}.each do |hour|
with_option hour
end
%w{09:00 09:45 22:15 22:45}.each do |hour|
without_option hour
end
with_option '14:45', :with => {:selected => 'selected'}
end
end
it 'should do 24 hours cycle count' do
tpl2.should have_tag('select') do
%w{09:00 15:45 21:45 22:00 00:00 00:15 03:15 06:15 06:45 07:00}.each do |hour|
with_option hour
end
%w{08:00 08:45 07:15 07:45}.each do |hour|
without_option hour
end
end
end
it 'should do full 24 hours cycle' do
puts tpl_24h
tpl_24h.should have_tag('select') do
%w{09:00 15:45 21:45 22:00 00:00 00:15 03:15 06:15 06:45 07:00 08:30 10:45 11:00}.each do |hour|
with_option hour
end
end
end
end
end
|
<reponame>chcbaram/arm_seminar_fw
/*
* led.c
*
* Created on: 2018. 3. 22.
* Author: <NAME>
*/
#include "led.h"
void ledInit(void)
{
GPIO_InitTypeDef gpio_init_structure;
/* Configure the GPIO_LED pin */
gpio_init_structure.Pin = GPIO_PIN_12;
gpio_init_structure.Mode = GPIO_MODE_OUTPUT_PP;
gpio_init_structure.Pull = GPIO_PULLUP;
gpio_init_structure.Speed = GPIO_SPEED_HIGH;
HAL_GPIO_Init(GPIOG, &gpio_init_structure);
gpio_init_structure.Pin = GPIO_PIN_5;
HAL_GPIO_Init(GPIOE, &gpio_init_structure);
gpio_init_structure.Pin = GPIO_PIN_4;
HAL_GPIO_Init(GPIOE, &gpio_init_structure);
gpio_init_structure.Pin = GPIO_PIN_10;
HAL_GPIO_Init(GPIOG, &gpio_init_structure);
/* By default, turn off LED */
HAL_GPIO_WritePin(GPIOG, GPIO_PIN_12, GPIO_PIN_SET);
HAL_GPIO_WritePin(GPIOE, GPIO_PIN_5, GPIO_PIN_SET);
HAL_GPIO_WritePin(GPIOE, GPIO_PIN_4, GPIO_PIN_SET);
HAL_GPIO_WritePin(GPIOG, GPIO_PIN_10, GPIO_PIN_SET);
}
void ledOn(uint8_t ch)
{
switch(ch)
{
case 0:
HAL_GPIO_WritePin(GPIOG, GPIO_PIN_12, GPIO_PIN_RESET);
break;
case 1:
HAL_GPIO_WritePin(GPIOE, GPIO_PIN_5, GPIO_PIN_RESET);
break;
case 2:
HAL_GPIO_WritePin(GPIOE, GPIO_PIN_4, GPIO_PIN_RESET);
break;
case 3:
HAL_GPIO_WritePin(GPIOG, GPIO_PIN_10, GPIO_PIN_RESET);
break;
}
}
void ledOff(uint8_t ch)
{
switch(ch)
{
case 0:
HAL_GPIO_WritePin(GPIOG, GPIO_PIN_12, GPIO_PIN_SET);
break;
case 1:
HAL_GPIO_WritePin(GPIOE, GPIO_PIN_5, GPIO_PIN_SET);
break;
case 2:
HAL_GPIO_WritePin(GPIOE, GPIO_PIN_4, GPIO_PIN_SET);
break;
case 3:
HAL_GPIO_WritePin(GPIOG, GPIO_PIN_10, GPIO_PIN_SET);
break;
}
}
void ledToggle(uint8_t ch)
{
switch(ch)
{
case 0:
HAL_GPIO_TogglePin(GPIOG, GPIO_PIN_12);
break;
case 1:
HAL_GPIO_TogglePin(GPIOE, GPIO_PIN_5);
break;
case 2:
HAL_GPIO_TogglePin(GPIOE, GPIO_PIN_4);
break;
case 3:
HAL_GPIO_TogglePin(GPIOG, GPIO_PIN_10);
break;
}
}
|
<filename>src/main/java/com/testvagrant/ekam/internal/logger/EkamLogger.java<gh_stars>0
package com.testvagrant.ekam.internal.logger;
import com.testvagrant.ekam.config.models.LogConfig;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.util.UUID;
public class EkamLogger {
private final String filePath;
private final LogConfig logConfig;
public EkamLogger(String filePath, LogConfig logConfig) {
this.filePath = filePath;
this.logConfig = logConfig;
}
public Logger init() {
String randomName = UUID.randomUUID().toString().replace("-", "");
Logger logger = LogManager.getLogger(randomName);
return logger;
}
}
|
<reponame>kotik-coder/PULsE
package pulse.problem.laser;
import static java.lang.Math.signum;
import pulse.properties.NumericProperty;
import pulse.properties.NumericPropertyKeyword;
/**
* The simplest pulse shape defined as <math>0.5*(1 +
* sgn(<i>t</i><sub>pulse</sub> - <i>t</i>))</math>, where <math>sgn(...)</math>
* is the signum function, <sub>pulse</sub> is the pulse width.
*
* @see java.lang.Math.signum(double)
*/
public class RectangularPulse extends PulseTemporalShape {
/**
* @param time the time measured from the start of the laser pulse.
*/
@Override
public double evaluateAt(double time) {
var width = getPulseWidth();
return 0.5 / width * (1 + signum(width - time));
}
@Override
public void set(NumericPropertyKeyword type, NumericProperty property) {
// intentionally blak
}
@Override
public PulseTemporalShape copy() {
return new RectangularPulse();
}
}
|
export PATH="/usr/lib/ccache:/usr/local/lib/f90cache:/usr/lib64/ccache:/usr/local/lib64/f90cache:$PATH"
export CCACHE_UNIFY=1
export CCACHE_SLOPPINESS=file_macro,time_macros
export CCACHE_COMPRESS=1
export CCACHE_MAXSIZE=1G
export OPT="-O2 -g0"
export FOPT="-O2 -g0"
export NPY_NUM_BUILD_JOBS=2
export OPENBLAS_NUM_THREADS=1
export MKL_NUM_THREADS=1
export OMP_NUM_THREADS=1
export SOURCE_DATE_EPOCH=1506870070
run() { echo; echo "sandbox\$" "$@"; "$@"; }
# Strip Python CFLAGS bad for ccache / old code
if [ -x "$HOME/env/bin/python" ]; then
PY_CFLAGS=$($HOME/env/bin/python -c 'import sysconfig; print(sysconfig.get_config_var("CFLAGS"))')
else
PY_CFLAGS=$(python -c 'import sysconfig; print(sysconfig.get_config_var("CFLAGS"))')
fi
CFLAGS=$(echo "$PY_CFLAGS" | sed -E -e 's/(-flto|-Werror=[a-z=-]*|-g[0-9]*|-grecord-gcc-switches|-fpedantic-errors|-ffat-lto-objects|-fuse-linker-plugin)( |$)/ /g;')
export CFLAGS
export NPY_DISTUTILS_APPEND_FLAGS=0
|
package com.example.milkorder_backend.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.example.milkorder_backend.model.dto.DrinkAddDTO;
import com.example.milkorder_backend.model.entity.Drink;
import com.example.milkorder_backend.model.entity.Tip;
import java.util.List;
public interface ITipService extends IService<Tip> {
/**
* 新增小料,只有管理员才有权限
*
* @param tip
* @return 注册对象
*/
Tip executeAdd(Tip tip);
/**
* 获取小料列表
* @return
*/
List<Tip> getList();
/**
* 获取小料价格
* @param name
* @return
*/
String getTipPrice(String name);
}
|
import { Component, OnInit, Input, ElementRef, ViewChild, AfterViewInit, OnDestroy } from '@angular/core';
import { FuncParam } from 'src/app/domains';
import { FormGroup, FormControl, FormBuilder, AbstractControl, ValidatorFn, Validators } from '@angular/forms';
import { ChartService, INDEX_FX_DRAW } from 'src/app/services/chart/chart.service';
import { MatDialog, MatSelect } from '@angular/material';
import { FunctionTableDataPointsDialogComponent } from '../dialogs';
import { Overlay } from '@angular/cdk/overlay';
import { ReplaySubject, Subject, Observable } from 'rxjs';
import { takeUntil, take, startWith, map } from 'rxjs/operators';
@Component({
selector: 'app-function-settings',
templateUrl: './function-settings.component.html',
styleUrls: ['./function-settings.component.scss']
})
export class FunctionSettingsComponent implements OnInit {
private xAxisMin = -1;
private xAxisMax = 1;
public funcs: string[] = [
'exp(x)', 'cos(x)', 'sin(x)', 'x^2'
];
filteredFuncs: string[] = this.funcs;
public fxParam: FuncParam = new FuncParam('', this.xAxisMin, this.xAxisMax, 0.1, 0);
funcFormGroup: FormGroup = this.buildFuncForm(this.fxParam);
private isNewFunc(func): boolean {
const filtered = this.funcs.filter(value => value.toUpperCase() === func.toUpperCase());
return filtered.length === 0;
}
validateRange(kind: string, param: FuncParam): ValidatorFn {
return (control: AbstractControl): { [key: string]: boolean } | null => {
let error = false;
if (control.value !== undefined && !isNaN(control.value)) {
if (kind === 'min') {
error = (control.value >= param.xMax);
}
if (kind === 'max') {
error = (control.value <= param.xMin);
}
}
if (error) { return { range : true }; }
return null;
};
}
validateFunction(control: AbstractControl): { [key: string]: boolean } | null {
const InvalidFunctions = ['arc', 'cot', 'ln', 'csc'];
if ( (control.value !== undefined) && !isNaN(control.value)) {
for (const fn of InvalidFunctions) {
if (control.value.toLowerCase().includes(fn)) {
return { pattern : true };
}
}
}
return null;
}
buildFuncForm(fxParam: FuncParam = new FuncParam()): FormGroup {
const funcPattern = '(?:[0-9-+*/^()x]|abs|e\^x|log|sec|sqrt|sign|exp|a?(?:sin|cos|tan)h?)+';
const reg: RegExp = new RegExp(funcPattern);
const funcCtrl: FormControl = new FormControl(fxParam.func, {
validators: [Validators.required, Validators.pattern(reg), this.validateFunction]
});
funcCtrl.valueChanges.subscribe( (value: string) =>
this.filteredFuncs = this._filter(value)
);
return this.formBuilder.group({
xMin: new FormControl(fxParam.xMin, [Validators.required, this.validateRange('min', fxParam)]),
xMax: new FormControl(fxParam.xMax, [Validators.required, this.validateRange('max', fxParam)]),
step: new FormControl(fxParam.step, Validators.required),
deltaX: new FormControl(fxParam.deltaX, [Validators.required]),
func: funcCtrl
});
}
private _filter(value: string): string[] {
const filterValue = value.toLowerCase();
this.funcs.sort((one, two) => (one > two ? 1 : -1));
if (value !== null || value !== '') {
return this.funcs.filter(option => option.toLowerCase().includes(filterValue));
}
return this.funcs;
}
get name() {
return this.funcFormGroup.get('name') as FormControl;
}
private getError(el) {
switch (el) {
case 'xMin':
if (this.funcFormGroup.get('xMin').hasError('required')) {
return 'required';
}
if (this.funcFormGroup.get('xMin').hasError('range')) {
return 'range';
}
break;
case 'xMax':
if (this.funcFormGroup.get('xMax').hasError('required')) {
return 'required';
}
if (this.funcFormGroup.get('xMax').hasError('range')) {
return 'range';
}
break;
case 'step':
if (this.funcFormGroup.get('step').hasError('required')) {
return 'required';
}
break;
case 'deltaX':
if (this.funcFormGroup.get('deltaX').hasError('required')) {
return 'required';
}
break;
case 'func':
if (this.funcFormGroup.get('func').hasError('required')) {
return 'required';
}
if (this.funcFormGroup.get('func').hasError('pattern')) {
return 'Ipattern';
}
break;
default:
return '';
}
}
public onSubmit(post: FuncParam) {
this.clear();
this.chartService.changeFxParam(post);
this.chartService.changeChartData(INDEX_FX_DRAW, 'active' , true);
if (this.isNewFunc(post.func)) {
this.funcs = [...this.funcs, post.func];
}
}
public clear() {
this.chartService.changeChartData(INDEX_FX_DRAW, 'active' , false);
}
public reset() {
this.chartService.fxParam = new FuncParam('', this.xAxisMin, this. xAxisMax);
this.funcFormGroup = this.buildFuncForm(this.chartService.fxParam);
this.clear();
}
disable() {
return !this.funcFormGroup.valid;
}
disableClear() {
return this.disable() || !this.chartService.chartData[INDEX_FX_DRAW].active;
}
openFunctionTableDataPointsDialog(): void {
if (this.funcFormGroup.valid) {
const bodyRect = document.body.getBoundingClientRect();
const elemRect = this.elementRef.nativeElement.getBoundingClientRect();
const width = elemRect.width + 30 ;
const top = elemRect.top - 35 ;
const left = elemRect.left - 15;
const dialogRef = this.dialog.open(FunctionTableDataPointsDialogComponent, {
panelClass: 'dialog',
width: width + 'px',
position: { left: left + 'px', top: top + 'px' },
data: { param: this.funcFormGroup.value},
scrollStrategy: this.overlay.scrollStrategies.noop(),
// hasBackdrop: false,
});
}
}
constructor(
private formBuilder: FormBuilder,
private chartService: ChartService,
private dialog: MatDialog,
public elementRef: ElementRef,
private overlay: Overlay,
) { }
ngOnInit() {
}
}
|
<gh_stars>0
import Expo from 'expo-server-sdk';
// Create a new Expo SDK client
let expo = new Expo();
// Create the messages that you want to send to clents
let messages = [];
for (let pushToken of somePushTokens) {
// Each push token looks like ExponentPushToken[xxxxxxxxxxxxxxxxxxxxxx]
// Check that all your push tokens appear to be valid Expo push tokens
if (!Expo.isExpoPushToken(pushToken)) {
console.error(`Push token ${pushToken} is not a valid Expo push token`);
continue;
}
// Construct a message (see https://docs.expo.io/versions/latest/guides/push-notifications.html)
messages.push({
to: pushToken,
sound: 'default',
body: 'This is a test notification',
data: { withSome: 'data' },
})
}
// The Expo push notification service accepts batches of notifications so
// that you don't need to send 1000 requests to send 1000 notifications. We
// recommend you batch your notifications to reduce the number of requests
// and to compress them (notifications with similar content will get
// compressed).
let chunks = expo.chunkPushNotifications(messages);
(async () => {
// Send the chunks to the Expo push notification service. There are
// different strategies you could use. A simple one is to send one chunk at a
// time, which nicely spreads the load out over time:
for (let chunk of chunks) {
try {
let receipts = await expo.sendPushNotificationsAsync(chunk);
// console.log(receipts);
} catch (error) {
console.error(error);
}
}
})();
|
import React from "react";
import Sidebar from "./components/Sidebar";
export const AdminPage = () => {
return (
<>
<Sidebar />
<div>admo</div>
</>
);
};
|
#!/bin/bash
set -e
if [ -f /var/run/secrets/kubernetes.io/serviceaccount/ca.crt ]; then
keytool -import -noprompt -storepass changeit -alias dev-server -keystore $JAVA_HOME/jre/lib/security/cacerts -file /var/run/secrets/kubernetes.io/serviceaccount/ca.crt
fi
exec "$@"
|
<reponame>juaniq99/TP-POO
package game.backend;
import game.backend.element.Bomb;
import game.backend.element.Candy;
import game.backend.element.CandyColor;
import game.backend.element.Element;
import game.backend.element.HorizontalStripedCandy;
import game.backend.element.VerticalStripedCandy;
import game.backend.element.WrappedCandy;
import java.awt.Point;
public enum Figure {
F6(new Point[]{ new Point(0,-2), new Point(0,-1), new Point(0,1), new Point(0,2)}, 240, Bomb.class, false),
F15(new Point[]{ new Point(-2,0), new Point(-1,0), new Point(1,0), new Point(2,0)}, 15, Bomb.class, false),
F4(new Point[]{ new Point(0,-1), new Point(0,1), new Point(0,2)}, 112, VerticalStripedCandy.class),
F5(new Point[]{ new Point(0,-2), new Point(0,-1), new Point(0,1)}, 208, VerticalStripedCandy.class),
F13(new Point[]{ new Point(-1,0), new Point(1,0), new Point(2,0)}, 13, HorizontalStripedCandy.class),
F14(new Point[]{ new Point(-2,0), new Point(-1,0), new Point(1,0)}, 7, HorizontalStripedCandy.class),
F7(new Point[]{ new Point(0,1), new Point(0,2), new Point(1,0), new Point(2,0)}, 60, WrappedCandy.class),
F8(new Point[]{ new Point(0,-1), new Point(0,1), new Point(1,0), new Point(2,0)}, 92, WrappedCandy.class),
F9(new Point[]{ new Point(0,-2), new Point(0,-1), new Point(1,0), new Point(2,0)}, 204, WrappedCandy.class),
F16(new Point[]{ new Point(-1,0), new Point(1,0), new Point(0,1), new Point(0,2)}, 53, WrappedCandy.class),
F17(new Point[]{ new Point(-2,0), new Point(-1,0), new Point(0,1), new Point(0,2)}, 51, WrappedCandy.class),
F18(new Point[]{ new Point(-2,0), new Point(-1,0), new Point(0,-1), new Point(0,-2)}, 195, WrappedCandy.class),
F19(new Point[]{ new Point(-2,0), new Point(-1,0), new Point(0,-1), new Point(0,1)}, 83, WrappedCandy.class),
F20(new Point[]{ new Point(-1,0), new Point(1,0), new Point(0,-2), new Point(0,-1)}, 197, WrappedCandy.class),
F1(new Point[]{new Point(0,1), new Point(0,2)}, 48),
F2(new Point[]{new Point(0,-1), new Point(0,1)}, 80),
F3(new Point[]{new Point(0,-1), new Point(0,-2)}, 192),
F10(new Point[]{ new Point(1,0), new Point(2,0)}, 12),
F11(new Point[]{ new Point(-1,0), new Point(1,0)}, 5),
F12(new Point[]{ new Point(-2,0), new Point(-1,0)}, 3);
private Point[] points;
private int value;
private Class<?> replacementClass;
private boolean isCandyRepl = true;
Figure(Point[] points, int value, Class<?> replacementClass) {
this.points = points;
this.value = value;
this.replacementClass = replacementClass;
}
Figure(Point[] points, int value, Class<?> replacementClass, boolean isCandyRepl) {
this.points = points;
this.value = value;
this.replacementClass = replacementClass;
this.isCandyRepl = isCandyRepl;
}
Figure(Point[] points, int value) {
this.points = points;
this.value = value;
this.replacementClass = null;
}
public Point[] getPoints() {
return points;
}
public int size() {
return points.length;
}
public boolean hasReplacement() {
return replacementClass != null;
}
public boolean matches(int acum) {
return value == (value & acum);
}
public Element generateReplacement(CandyColor color) {
try {
Element e;
e = (Element) replacementClass.newInstance();
if (isCandyRepl) {
((Candy)e).setColor(color);
}
return e;
} catch(Exception e) {
}
return null;
}
}
|
import { css, html, LitElement, TemplateResult } from 'lit';
import { customElement, state } from 'lit/decorators.js';
import { classMap } from 'lit/directives/class-map.js';
import '../components/app-header';
import '../components/app-card';
import '../components/app-modal';
import '../components/app-button';
import '../components/loading-button';
import '../components/windows-form';
import '../components/android-form';
import '../components/ios-form';
import '../components/info-circle-tooltip';
import { Router } from '@vaadin/router';
import {
BreakpointValues,
smallBreakPoint,
largeBreakPoint,
mediumBreakPoint,
xxxLargeBreakPoint,
} from '../utils/css/breakpoints';
//@ts-ignore
import style from '../../../styles/layout-defaults.css';
import { fastAnchorCss } from '../utils/css/fast-elements';
import { fileSave } from 'browser-fs-access';
import {
checkResults,
finalCheckForPublish,
} from '../services/publish/publish-checks';
import { generatePackage, Platform } from '../services/publish';
import { getReportErrorUrl } from '../utils/error';
import { styles as ToolTipStyles } from '../components/tooltip';
import { localeStrings } from '../../locales';
import { AnalyticsBehavior, recordProcessStep } from '../utils/analytics';
import { getManifestContext, getURL } from '../services/app-info';
import { IOSAppPackageOptions } from '../utils/ios-validation';
import { WindowsPackageOptions } from '../utils/win-validation';
import { fetchOrCreateManifest } from '../services/manifest';
import { createWindowsPackageOptionsFromManifest } from '../services/publish/windows-publish';
import { AndroidPackageOptions } from '../utils/android-validation';
@customElement('app-publish')
export class AppPublish extends LitElement {
@state() errored = false;
@state() errorMessage: string | undefined;
@state() blob: Blob | File | null | undefined;
@state() testBlob: Blob | File | null | undefined;
@state() downloadFileName: string | null = null;
@state() mql = window.matchMedia(
`(min-width: ${BreakpointValues.largeUpper}px)`
);
@state() isDeskTopView = this.mql.matches;
@state() openWindowsOptions = false;
@state() openAndroidOptions = false;
@state() openiOSOptions = false;
@state() generating = false;
@state() finalChecks: checkResults | undefined;
@state() reportPackageErrorUrl = '';
readonly platforms: ICardData[] = [
{
title: 'Windows',
description:
'Publish your PWA to the Microsoft Store to make it available to the 1 billion Windows users worldwide.',
isActionCard: true,
icon: '/assets/windows_icon.svg',
renderDownloadButton: () => this.renderWindowsDownloadButton()
},
{
title: 'Android',
description:
'Publish your PWA to the Google Play Store to make your app more discoverable for Android users.',
isActionCard: true,
icon: '/assets/android_icon.svg',
renderDownloadButton: () => this.renderAndroidDownloadButton()
},
{
title: 'iOS',
description:
'Publish your PWA to the iOS App Store to make it available to iPhone and iPad users. Requires a Mac to build the package.',
isActionCard: true,
icon: '/assets/apple_icon.svg',
renderDownloadButton: () => this.renderiOSDownloadButton()
}
];
constructor() {
super();
this.mql.addEventListener('change', e => {
this.isDeskTopView = e.matches;
});
}
static get styles() {
return [
style,
fastAnchorCss,
ToolTipStyles,
css`
.header {
padding: 1rem 3rem;
}
.header p {
width: min(100%, 600px);
}
#tablet-sidebar {
display: none;
}
#desktop-sidebar {
display: block;
}
#summary-block {
padding: 16px 16px 16px 36px;
border-bottom: var(--list-border);
margin-right: 2em;
}
h1 {
font-size: var(--xlarge-font-size);
line-height: 46px;
}
#hero-p {
font-size: var(--font-size);
line-height: 24px;
max-width: 406px;
}
h2,
h4 {
font-size: var(--medium-font-size);
margin-bottom: 8px;
}
h3 {
margin-bottom: 8px;
margin-top: 0;
}
.container {
padding: 16px 16px 16px 36px;
display: flex;
flex-direction: column;
justify-items: center;
align-items: center;
}
.container .action-buttons {
display: flex;
justify-content: center;
align-items: center;
}
.container .action-buttons > app-button {
margin: 1rem;
}
.container .action-buttons fast-anchor,
.container .action-buttons app-button {
--button-width: 127px;
height: 44px;
width: var(--button-width);
}
.container .action-buttons fast-anchor {
/**
Seems like a magic value but really
this is just to match the back button next to it
*/
color: white;
box-shadow: var(--button-shadow);
border-radius: var(--button-radius);
font-weight: bold;
}
#up-next {
width: 100%;
}
ul {
list-style: none;
margin: 0;
padding: 0;
width: 100%;
}
li {
display: flex;
align-items: center;
justify-content: space-between;
padding-top: 35px;
padding-bottom: 35px;
border-bottom: var(--list-border);
}
li h3 {
font-size: var(--small-medium-font-size);
}
p {
font-size: var(--font-size);
color: var(--font-color);
max-width: 530px;
}
content-header::part(header) {
display: none;
}
.modal-image {
width: 50px;
}
#error-modal::part(modal-body) {
max-height: 36vh;
overflow-y: auto;
max-width: inherit;
overflow-x: hidden;
}
#error-modal::part(modal-body-contents) {
white-space: pre;
text-align: left;
overflow: auto;
max-height: 200px;
padding: 20px;
}
#error-link {
color: white;
font-weight: var(--font-bold);
border-radius: var(--button-radius);
background: var(--error-color);
margin-right: 8px;
padding-left: 10px;
padding-right: 10px;
box-shadow: var(--button-shadow);
}
#test-package-button {
display: block;
margin-top: 15px;
}
#test-package-button::part(underlying-button) {
--button-font-color: var(--font-color);
}
#platform-actions-block app-button,
#platform-actions-block loading-button::part(underlying-button) {
--button-width: 152px;
}
#actions {
display: flex;
flex-direction: column;
}
#actions fast-anchor.button,
#actions app-button {
margin-right: 0;
margin-top: 8px;
}
.tooltip {
height: 16px;
width: 16px;
}
hover-tooltip::part(tooltip-image) {
display: none;
}
.platform-icon {
max-width: 37px;
image-rendering: smooth;
}
ios-form {
width: 100%;
}
`,
xxxLargeBreakPoint(
css`
#report {
max-width: 69em;
}
app-sidebar {
display: block;
}
#tablet-sidebar {
display: none;
}
#desktop-sidebar {
display: block;
}
#publish-wrapper {
max-width: 69em;
background: white;
}
#windows-options-modal::part(modal-layout) {
width: 700px;
}
#ios-options-modal::part(modal-layout) {
width: 600px;
}
`
),
largeBreakPoint(
css`
#tablet-sidebar {
display: block;
}
#desktop-sidebar {
display: none;
}
`
),
mediumBreakPoint(
css`
.publish h1 {
font-size: 33px;
max-width: 10em;
margin-top: 0;
margin-bottom: 1em;
}
.publish p {
display: none;
}
li {
flex-direction: column;
align-items: flex-start;
}
#title-block {
width: 100%;
}
#title-block p {
width: unset;
}
#platform-actions-block {
width: 100%;
display: flex;
flex-direction: column;
align-items: center;
margin-top: 2em;
}
`
),
mediumBreakPoint(
css`
loading-button {
--loading-button-height: 64px;
}
loading-button::part(underlying-button) {
--font-size: 22px;
}
.container .action-buttons fast-anchor,
.container .action-buttons app-button {
--button-width: 127px;
font-size: var(--mobile-button-fontsize);
height: var(--mobile-button-height);
width: var(--button-width);
margin: 22px;
}
`,
'no-lower'
),
smallBreakPoint(css`
#error-modal::part(modal-layout) {
width: 100vw;
}
#test-package-button app-button::part(underlying-button) {
font-size: var(--font-size);
}
li {
flex-direction: column;
align-items: flex-start;
}
#title-block {
width: 100%;
}
#title-block p {
width: unset;
}
#platform-actions-block {
width: 100%;
display: flex;
flex-direction: column;
align-items: center;
margin-top: 2em;
}
.publish h1 {
font-size: 33px;
margin-top: 0;
margin-bottom: 1em;
}
.publish p {
display: none;
}
`),
];
}
async firstUpdated() {
const checks = await finalCheckForPublish();
if (checks) {
this.finalChecks = checks;
}
}
getWindowsFinalChecksErrorMessage(): string | null {
if (this.finalChecks) {
const maniCheck = this.finalChecks.manifest;
const baseIcon = this.finalChecks.baseIcon;
const validURL = this.finalChecks.validURL;
if (maniCheck === false) {
return 'Your PWA does not have a valid Web Manifest';
}
if (baseIcon === false) {
return 'Your PWA needs at least a 512x512 PNG icon';
}
if (validURL === false) {
return 'Your PWA does not have a valid URL';
}
}
return null;
}
getAndroidFinalChecksErrorMessage(): string | null {
if (this.finalChecks) {
const maniCheck = this.finalChecks.manifest;
const baseIcon = this.finalChecks.baseIcon;
const validURL = this.finalChecks.validURL;
if (maniCheck === false) {
return 'Your PWA does not have a valid Web Manifest';
}
if (baseIcon === false) {
return 'Your PWA needs at least a 512x512 PNG icon';
}
if (validURL === false) {
return 'Your PWA does not have a valid URL';
}
}
return null;
}
async generateWindowsTestPackage() {
let manifestContext = getManifestContext();
if (manifestContext.isGenerated) {
manifestContext = await fetchOrCreateManifest();
}
const options = createWindowsPackageOptionsFromManifest(manifestContext.manifest);
await this.generate("windows", options);
}
async generate(platform: Platform, options?: AndroidPackageOptions | IOSAppPackageOptions | WindowsPackageOptions) {
// Record analysis results to our analytics portal.
recordProcessStep(
'analyze-and-package-pwa',
`create-${platform}-package`,
AnalyticsBehavior.CompleteProcess,
{ url: getURL() });
try {
this.generating = true;
const packageData = await generatePackage(platform, options);
if (packageData) {
this.downloadFileName = `${packageData.appName}.zip`;
if (packageData.type === 'test') {
this.testBlob = packageData.blob;
} else {
this.blob = packageData.blob;
}
}
} catch (err) {
console.error(err);
this.showAlertModal(err as Error, platform);
recordProcessStep(
'analyze-and-package-pwa',
`create-${platform}-package-failed`,
AnalyticsBehavior.CancelProcess,
{
url: getURL(),
error: err
});
} finally {
this.generating = false;
this.openAndroidOptions = false;
this.openWindowsOptions = false;
this.openiOSOptions = false;
}
}
async download() {
if (this.blob || this.testBlob) {
await fileSave((this.blob as Blob) || (this.testBlob as Blob), {
fileName: this.downloadFileName || 'your_pwa.zip',
extensions: ['.zip'],
});
this.blob = undefined;
this.testBlob = undefined;
}
}
showAlertModal(error: string | Object, platform: Platform) {
this.errored = true;
const errorObj = error as Error;
if (errorObj.message && errorObj.stack) {
const is403 =
typeof errorObj.message === 'string' &&
errorObj.message.includes('Responded with status 403');
const isFailedToFetchManifest =
typeof errorObj.message === 'string' &&
errorObj.message.includes('Failed to retreive PWA manifest for');
if (is403) {
// Is it a 403? Then most likely it's anti-bot tech, e.g. Cloudflare, blocking us.
this.errorMessage = `PWABuilder got a 403 Forbidden error when fetching your site.\nThis can happen when your site is using Cloudflare or other anti-bot technologies.\nTry temporarily pausing Cloudflare or your anti-bot technology while running PWABuilder on your web app.\n\n${errorObj.message}\n\nStack trace: \n${errorObj.stack}`;
} else if (isFailedToFetchManifest) {
// Failed to fetch manifest? This is thrown by the Windows platform when we have anti-bot tech blocking us from downloading the manifest.
this.errorMessage = `PWABuilder was unable to download your manifest.\nThis can happen when your site is using Cloudflare or other anti-bot technology.\nTry temporarily pausing Cloudflare or your anti-bot technology while running PWABuilder on your web app.\n\n${errorObj.message}\n\nStack trace: \n${errorObj.stack}`;
} else {
this.errorMessage = `${errorObj.message}\n\nStack trace:\n${errorObj.stack}`;
}
} else if (errorObj.message) {
this.errorMessage = errorObj.message;
} else {
this.errorMessage = (error || '').toString();
}
this.reportAnError(error, platform);
}
showWindowsOptionsModal() {
this.openWindowsOptions = true;
}
showAndroidOptionsModal() {
this.openAndroidOptions = true;
}
showiOSOptionsModal() {
this.openiOSOptions = true;
}
renderContentCards(): TemplateResult[] {
return this.platforms.map(
platform => html`
<li>
<div id="title-block">
<img class="platform-icon" src="${platform.icon}" alt="platform icon" />
<h3>${platform.title}</h3>
<p>${platform.description}</p>
</div>
<!-- TODO need to fix the platform action blocks text spacing for the left. -->
<div id="platform-actions-block">
${platform.renderDownloadButton()}
</div>
</li>`
);
}
renderWindowsDownloadButton(): TemplateResult {
return html`
<app-button class="navigation" id="windows-package-button" @click="${() => this.showWindowsOptionsModal()}">
Store Package
</app-button>
<div>
<loading-button id="windows-test-pkg-btn" class="navigation secondary" ?loading=${this.generating} id="test-package-button"
@click="${this.generateWindowsTestPackage}">
Test Package
</loading-button>
<hover-tooltip
anchor="windows-test-pkg-btn"
text="Generate a package you can use to test your app on your Windows Device before going to the Microsoft Store."
link="https://github.com/pwa-builder/pwabuilder-windows-chromium-docs/blob/master/next-steps.md#1-test-your-app-on-your-windows-machine">
</hover-tooltip>
</div>
`;
}
renderAndroidDownloadButton(): TemplateResult {
return html`
<app-button class="navigation" id="android-package-button" @click="${() => this.showAndroidOptionsModal()}">
Store Package
</app-button>
`;
}
renderiOSDownloadButton(): TemplateResult {
return html`
<app-button class="navigation" id="ios-package-button" @click="${() => this.showiOSOptionsModal()}">
Store Package
</app-button>
`;
}
returnToFix() {
const resultsString = sessionStorage.getItem('results-string');
// navigate back to report-card page
// with current manifest results
Router.go(`/reportcard?results=${resultsString}`);
}
reportAnError(errorDetail: string | Object, platform: string) {
this.reportPackageErrorUrl = getReportErrorUrl(errorDetail, platform);
}
downloadCancel() {
this.blob = undefined;
this.errorMessage = undefined;
this.errored = false;
}
downloadTestCancel() {
this.testBlob = undefined;
this.errorMessage = undefined;
this.errored = false;
}
storeOptionsCancel() {
this.openWindowsOptions = false;
this.openAndroidOptions = false;
this.openiOSOptions = false;
}
render() {
return html`
<!-- error modal -->
<app-modal heading="Wait a minute!" .body="${this.errorMessage || ''}" ?open="${this.errored}" id="error-modal">
<img class="modal-image" slot="modal-image" src="/assets/warning.svg" alt="warning icon" />
<div id="actions" slot="modal-actions">
<fast-anchor target="__blank" id="error-link" class="button" .href="${this.reportPackageErrorUrl}">Report A Problem
</fast-anchor>
<app-button @click="${() => this.returnToFix()}">Return to Manifest Options</app-button>
</div>
</app-modal>
<!-- download modal -->
<app-modal ?open="${this.blob ? true : false}" heading="Download your package"
body="Your app package is ready for download." id="download-modal" @app-modal-close="${() => this.downloadCancel()}">
<img class="modal-image" slot="modal-image" src="/assets/images/store_fpo.png" alt="publish icon" />
<div slot="modal-actions">
<app-button @click="${() => this.download()}">Download</app-button>
</div>
</app-modal>
<!-- test package download modal -->
<app-modal ?open="${this.testBlob ? true : false}" heading="Test Package Download"
body="${localeStrings.input.publish.windows.test_package}" id="test-download-modal"
@app-modal-close="${() => this.downloadTestCancel()}">
<img class="modal-image" slot="modal-image" src="/assets/images/warning.svg" alt="warning icon" />
<div slot="modal-actions">
<app-button @click="${() => this.download()}">Download</app-button>
</div>
</app-modal>
<!-- windows store options modal -->
<app-modal id="windows-options-modal" heading="Windows App Options" body="Customize your Windows app below"
?open="${this.openWindowsOptions}" @app-modal-close="${() => this.storeOptionsCancel()}">
<windows-form slot="modal-form" .generating=${this.generating} @init-windows-gen="${(ev: CustomEvent) =>
this.generate('windows', ev.detail as WindowsPackageOptions)}"></windows-form>
</app-modal>
<!-- android options modal -->
<app-modal id="android-options-modal" heading="Android App Options" body="Customize your Android app below"
?open="${this.openAndroidOptions === true}" @app-modal-close="${() => this.storeOptionsCancel()}">
<android-form slot="modal-form" .generating=${this.generating} @init-android-gen="${(e: CustomEvent) =>
this.generate('android', e.detail as AndroidPackageOptions)}"></android-form>
</app-modal>
<!-- ios options modal -->
<app-modal id="ios-options-modal" heading="iOS App Options" body="Customize your iOS app below"
?open="${this.openiOSOptions === true}" @app-modal-close="${() => this.storeOptionsCancel()}">
<ios-form slot="modal-form" .generating=${this.generating}
@init-ios-gen="${(ev: CustomEvent) => this.generate('ios', ev.detail)}">
</ios-form>
</app-modal>
<div id="publish-wrapper">
<app-header></app-header>
<div id="grid" class="${classMap({
'grid-mobile': this.isDeskTopView == false,
})}">
<app-sidebar id="desktop-sidebar"></app-sidebar>
<div>
<content-header class="publish">
<h1 slot="hero-container">Your PWA is Store Ready!</h1>
<p id="hero-p" slot="hero-container">
You are now ready to ship your PWA to the app stores!
</p>
</content-header>
<app-sidebar id="tablet-sidebar"></app-sidebar>
<section id="summary-block">
<h2>Publish your PWA to stores</h2>
<p>
Generate store-ready packages for the Microsoft Store, Google
Play and more!
</p>
</section>
<section class="container">
<ul>
${this.renderContentCards()}
</ul>
<div id="up-next">
<h4>Congrats!</h4>
<p>
Make sure you check our documentation for help submitting your
generated packages! Click next to see what else you can do
with your PWA!
</p>
</div>
<div class="action-buttons">
<app-button @click="${() => this.returnToFix()}">Back</app-button>
<fast-anchor class="button" href="/congrats">Next</fast-anchor>
</div>
</section>
</div>
</div>
</div>
`;
}
}
interface ICardData {
title: 'Windows' | 'Android' | 'iOS';
description: string;
isActionCard: boolean;
icon: string;
renderDownloadButton: () => TemplateResult;
}
|
from pytest import fixture
from mysign_app.models import Company
from mysign_app.tests.factories import CompanyFactory
from mysign_app.tests.frontend.helpers import authenticate_selenium
@fixture(autouse=True)
def setup_test(selenium, live_server):
company = CompanyFactory(name="Mindhash", email="<EMAIL>")
authenticate_selenium(selenium, live_server, company=company)
selenium.maximize_window()
selenium.get(live_server.url + "/company/")
def test_form_is_filled(selenium, live_server):
company = Company.objects.first()
assert selenium.find_element_by_id('id_name').get_attribute('value') == company.name
assert selenium.find_element_by_id('id_email').get_attribute('value') == company.email
assert selenium.find_element_by_id('id_phone_number').get_attribute('value') == company.phone_number
assert selenium.find_element_by_id('id_color').get_attribute('value') == company.color[1:].upper()
assert selenium.find_element_by_id('id_text_color').get_attribute('value') == company.text_color[1:].upper()
assert selenium.find_element_by_xpath('//div[@id="div_id_logo"]/div/a').get_attribute(
'href') == live_server + company.logo.url
assert selenium.find_element_by_xpath('//div[@id="div_id_image"]/div/a').get_attribute(
'href') == live_server + company.image.url
def set_info(selector, info):
selector.clear()
selector.send_keys(info)
def test_live_reload(selenium, live_server):
# Test clearing image
selenium.find_element_by_id('image-clear_id').click()
assert selenium.find_element_by_id('screen_display_image').get_attribute(
'src') == live_server + '/static/mysign_app/image-fallback.png'
selenium.find_element_by_id('logo-clear_id').click()
assert selenium.find_element_by_id('screen_display_logo').get_attribute(
'src') == live_server + '/static/mysign_app/logo-fallback.png'
# Test field updating
set_info(selenium.find_element_by_id('id_email'), '123456')
selenium.find_element_by_id('id_name').click()
assert selenium.find_element_by_id('screen_display_email').text == '123456'
set_info(selenium.find_element_by_id('id_phone_number'), '123456')
selenium.find_element_by_id('id_name').click()
assert selenium.find_element_by_id('screen_display_phone_number').text == '123456'
set_info(selenium.find_element_by_id('id_website'), '123456')
selenium.find_element_by_id('id_name').click()
assert selenium.find_element_by_id('screen_display_website').text == '123456'
# Test color updating
selenium.find_element_by_id('id_color').clear()
selenium.find_element_by_id('id_color').send_keys('FFFFFF')
selenium.find_element_by_id('id_name').click()
assert selenium.find_element_by_id('screen_display_info').get_attribute(
'style') == 'background: rgb(255, 255, 255);'
selenium.find_element_by_id('id_text_color').clear()
selenium.find_element_by_id('id_text_color').send_keys('000000')
selenium.find_element_by_id('id_name').click()
assert selenium.find_element_by_id('screen_display_text').get_attribute('style') == 'color: rgb(0, 0, 0);'
def test_save(selenium):
set_info(selenium.find_element_by_id('id_name'), 'Example')
set_info(selenium.find_element_by_id('id_phone_number'), '+3112345678')
set_info(selenium.find_element_by_id('id_email'), '<EMAIL>')
set_info(selenium.find_element_by_id('id_website'), 'example.com')
set_info(selenium.find_element_by_id('id_color'), 'FFFFFF')
set_info(selenium.find_element_by_id('id_text_color'), '000000')
selenium.find_element_by_id('image-clear_id').click()
selenium.find_element_by_id('logo-clear_id').click()
selenium.find_element_by_id('submitButton').click()
company = Company.objects.first()
assert company.name == 'Example'
assert company.phone_number == '+3112345678'
assert company.email == '<EMAIL>'
assert company.website == 'example.com'
assert company.color == '#FFFFFF'
assert company.text_color == '#000000'
def test_save_invalid(selenium):
set_info(selenium.find_element_by_id('id_phone_number'), '1234')
selenium.find_element_by_id('submitButton').click()
assert selenium.find_element_by_id('error_1_id_phone_number')
|
#!/bin/sh
hostname=$( hostname -s )
. ${HOME}/bin/qtile/configs/volume_common.${hostname}
volume_down
update_volume
|
import { Component, OnInit } from "@angular/core";
interface ISidebarItem {
iconClass: string;
title: string;
route: string;
floatBottom: boolean;
}
@Component({
selector: "cc-sidebar",
templateUrl: "./sidebar.component.html",
styleUrls: ["./sidebar.component.scss"]
})
export class SidebarComponent implements OnInit {
items: ISidebarItem[] = [
{
iconClass: "home",
title: "Dashboard",
route: "/dashboard",
floatBottom: false
},
{
iconClass: "people",
title: "Players",
route: "/players",
floatBottom: false
},
{
iconClass: "credit-card",
title: "Banking",
route: "/banking",
floatBottom: false
},
{
iconClass: "list-rich",
title: "Game Log",
route: "/log",
floatBottom: false
},
{
iconClass: "cog",
title: "Settings",
route: "/settings",
floatBottom: true
}
];
constructor() {
}
ngOnInit() {
}
}
|
/* global require, exports, Buffer */
// @flow
const base58 = require('bs58');
const { blake2b256Hash } = require('./signing').RholangCrypto;
const h2b = require('./hex').decode;
const checksumLength = 4;
const keyLength = 32;
const coinId = '000000';
const version = '00';
const prefix = h2b(coinId + version);
/*::
export interface IRevAddress {
address: Address,
toString: () => string,
};
type Address = {
prefix: Uint8Array,
keyHash: Uint8Array,
checksum: Uint8Array,
};
*/
/**
* A RevAddress refers to a REV vault.
*
* Use `toString()` to get base58 form.
*
* Refs:
* - [RevAddress.scala](https://github.com/rchain/rchain/blob/9ae5825/rholang/src/main/scala/coop/rchain/rholang/interpreter/util/RevAddress.scala)
* - [AddressTools.scala](https://github.com/rchain/rchain/blob/9ae5825/rholang/src/main/scala/coop/rchain/rholang/interpreter/util/AddressTools.scala)
*
* @memberof REV
*/
const RevAddress = (() => {
/**
* Compute REV Address from public key
*
* @param pk ed25519 public key
*
* @memberof REV.RevAddress
*/
function fromPublicKey(pk /*: Uint8Array */) /*: IRevAddress */ {
if (keyLength !== pk.length) { throw new Error(`bad public key length: ${pk.length}`); }
const keyHash = blake2b256Hash(pk);
const payload = concat(prefix, keyHash);
const checksum = computeChecksum(payload);
const s = base58.encode(Buffer.from(concat(payload, checksum)));
return Object.freeze({
address: {
prefix,
keyHash,
checksum,
},
toString: () => s,
});
}
/**
* Parse REV Address
*
* @throws Error on ill-formed address
* @memberof REV.RevAddress
*/
function parse(address /*: string */) /*: IRevAddress */{
function validateLength(bytes) {
if (bytes.length !== prefix.length + (256 / 8) + checksumLength) {
throw new Error('Invalid address length');
}
}
function validateChecksum(bytes) {
const checksumStart = prefix.length + (256 / 8);
const [payload, checksum] = splitAt(bytes, checksumStart);
if (computeChecksum(payload) !== checksum) { throw new Error('Invalid checksum'); }
return [payload, checksum];
}
function parseKeyHash(payload) {
const [actualPrefix, keyHash] = splitAt(payload, prefix.length);
if (actualPrefix !== prefix) { throw new Error('Invalid prefix'); }
return keyHash;
}
const decodedAddress = base58.decode(address);
validateLength(decodedAddress);
const [payload, checksum] = validateChecksum(decodedAddress);
const keyHash = parseKeyHash(payload);
return Object.freeze({
address: { prefix, keyHash, checksum },
toString: () => address,
});
}
return Object.freeze({ fromPublicKey, parse });
})();
exports.RevAddress = RevAddress;
function computeChecksum(toCheck /*: Uint8Array */) /*: Uint8Array */ {
return blake2b256Hash(toCheck).slice(0, checksumLength);
}
function splitAt(bs, x) {
return [bs.slice(0, x), bs.slice(x)];
}
function concat(a, b) {
const out = new Uint8Array(a.length + b.length);
out.set(a);
out.set(b, a.length);
return out;
}
|
#!/bin/bash
# vim: ai:ts=8:sw=8:noet
set -eufCo pipefail
export SHELLOPTS
IFS=$'\t\n'
command -v git >/dev/null 2>&1 || { echo 'please install git'; exit 1; }
TMP_DIR=./tmp
SLOTH_DIR="${TMP_DIR}/sloth"
SYNC_DIR=./content/sli-plugins
PLUGINS_REPO_DIR="${TMP_DIR}/sli-plugins/plugins"
PLUGINS_DIR="${PLUGINS_REPO_DIR}/plugins"
echo "[*] Cleaning"
rm -rf ${TMP_DIR}
mkdir ${TMP_DIR}
rm -rf ${SYNC_DIR}
mkdir ${SYNC_DIR}
echo "[*] Cloning repositories"
git clone git://github.com/slok/sloth-common-sli-plugins -b main --depth 1 "${PLUGINS_REPO_DIR}"
echo "[*] Creating plugin index file"
cat > ${SYNC_DIR}/_index.md <<EOF
---
title: "SLI plugins"
weight: 980
geekdocCollapseSection: true
---
<!-- spellchecker-disable -->
{{< toc-tree >}}
<!-- spellchecker-enable -->
EOF
echo "[*] Syncing SLO examples"
PREV_DIR="${PWD}"
cd ${PLUGINS_DIR}
find . -name "README.md"|while read fname; do
# Get group name.
group_name=$(dirname "${fname}")
# Remove "./" prefix.
group_name=${group_name#./}
# Replace "/" with "-"
id="${group_name//\//-}"
# Copy readme
mkdir -p "${PREV_DIR}/${SYNC_DIR}/${id}"
cp "${fname}" "${PREV_DIR}/${SYNC_DIR}/${id}/_index.md"
done
|
<reponame>lulululululu/cpp_client_telemetry<filename>lib/shared/SchemaStub.hpp<gh_stars>1-10
//
// Copyright (c) 2015-2020 Microsoft Corporation and Contributors.
// SPDX-License-Identifier: Apache-2.0
//
#pragma once
// TODO: Replace with actual Bond-generated interfaces.
namespace Microsoft {
namespace Applications {
namespace Telemetry {
namespace Windows
{
/// <summary>
/// Levels of trace events that represents printf style logging generated by an application
/// </summary>
public enum class TraceLevel
{
/// <summary>No Tracing.</summary>
None = 0,
/// <summary>Errors.</summary>
Error = 1,
/// <summary>Warnings.</summary>
Warning = 2,
/// <summary>Informational messages.</summary>
Information = 3,
/// <summary>Trace messages.</summary>
Verbose = 4
};
/// <summary>
/// User's state to report (final values TBD)
/// </summary>
public enum class UserState
{
/// <summary>Connected: user is connected to a service. </summary>
Connected,
/// <summary>Reachable: user is reachable for a service like push notification. </summary>
Reachable,
/// <summary>SignedIn: user is signed in.</summary>
SignedIn,
/// <summary>SignedOut: user is signed out.</summary>
SignedOut
};
public enum class SessionState
{
/// <summary>Session started.</summary>
Session_Started = 0,
/// <summary>Session ended.</summary>
Session_Ended = 1,
};
public enum class TransmitProfile
{
/// <summary>Favors low transmission latency, but might consume more data bandwidth and power.</summary>
RealTime = 0,
/// <summary>Favors near real-time transmission latency. Automatically balances transmission
/// latency with data bandwidth and power consumption.</summary>
NearRealTime,
/// <summary>Favors device performance by conserving both data bandwidth and power consumption.</summary>
BestEffort,
};
public enum class EventPriority
{
/// <summary>The event priority is not specified.</summary>
Unspecified = -1,
/// <summary>The event will not be transmitted.</summary>
Off = 0,
/// <summary>low priority.</summary>
Low = 1,
/// <summary>Normal priority.</summary>
Normal = 2,
/// <summary>High priority.</summary>
High = 3
};
/// Types listed below are generalized logical concepts.
/// Each type may corresponds to multiple raw action types
/// E.g. Click can be from LButtonDown or TouchTap
/// They are commonly used to identify user engagement on the page.
public enum class ActionType
{
/// <summary>The action type is unspecified.</summary>
Unspecified = 0,
/// <summary>The action type is unknown.</summary>
Unknown = 1,
/// <summary>The action type is other.</summary>
Other = 2,
/// <summary>A mouse click.</summary>
Click = 3,
/// <summary>A pan.</summary>
Pan = 5,
/// <summary>A zoom.</summary>
Zoom = 6,
/// <summary>A hover.</summary>
Hover = 7
};
/// <summary>
/// Api Types of an operation such as ServiceApi or ClientProxy
/// </summary.
public enum class ApiType
{
/// <summary>No API type.</summary>
None = 0,
/// <summary>Service API.</summary>
ServiceApi = 1,
/// <summary>Client proxy API.</summary>
ClientProxy = 2
};
/// <summary>
/// AggregateType indicates the type of aggregated metric being reported
/// </summary>
public enum class AggregateType
{
/// <summary>The arithmetic sum.</summary>
Sum = 0,
/// <summary>The maximum.</summary>
Maximum = 1,
/// <summary>The minimum.</summary>
Minimum = 2,
/// <summary>The sum of the squares used to calculate the variance.</summary>
SumOfSquares = 3
};
/// This enum corresponds to a physical action that user has performed.
public enum class RawActionType
{
/// <summary>Raw action type unspecified.</summary>
Unspecified = 0,
/// <summary>Raw action type unknown.</summary>
Unknown = 1,
/// <summary>Raw action type other.</summary>
Other = 2,
/// <summary>Left button double-click.</summary>
LButtonDoubleClick = 11,
/// <summary>Left button down.</summary>
LButtonDown = 12,
/// <summary>Left button up.</summary>
LButtonUp = 13,
/// <summary>Middle button double-click.</summary>
MButtonDoubleClick = 14,
/// <summary>Middle button down.</summary>
MButtonDown = 15,
/// <summary>Middle button up.</summary>
MButtonUp = 16,
/// <summary>Mouse hover.</summary>
MouseHover = 17,
/// <summary>Mouse wheel.</summary>
MouseWheel = 18,
/// <summary>Mouse move.</summary>
MouseMove = 20,
/// <summary>Right button double-click.</summary>
RButtonDoubleClick = 22,
/// <summary>Right button down.</summary>
RButtonDown = 23,
/// <summary>Right button up.</summary>
RButtonUp = 24,
/// <summary>Touch tap.</summary>
TouchTap = 50,
/// <summary>Touch double-tap.</summary>
TouchDoubleTap = 51,
/// <summary>Touch long-press.</summary>
TouchLongPress = 52,
/// <summary>Touch scroll.</summary>
TouchScroll = 53,
/// <summary>Touch pan.</summary>
TouchPan = 54,
/// <summary>Touch flick.</summary>
TouchFlick = 55,
/// <summary>Touch pinch.</summary>
TouchPinch = 56,
/// <summary>Touch zoom.</summary>
TouchZoom = 57,
/// <summary>Touch rotate.</summary>
TouchRotate = 58,
/// <summary>Keyboard press.</summary>
KeyboardPress = 100,
/// <summary>Keyboard Enter.</summary>
KeyboardEnter = 101
};
public enum class InputDeviceType
{
/// <summary>Device type unspecified.</summary>
Unspecified = 0,
/// <summary>Device type unknown.</summary>
Unknown = 1,
/// <summary>Other.</summary>
Other = 2,
/// <summary>Mouse.</summary>
Mouse = 3,
/// <summary>Keyboard.</summary>
Keyboard = 4,
/// <summary>Touch.</summary>
Touch = 5,
/// <summary>Stylus.</summary>
Stylus = 6,
/// <summary>Microphone.</summary>
Microphone = 7,
/// <summary>Kinect.</summary>
Kinect = 8,
/// <summary>Camera.</summary>
Camera = 9
};
public enum class AppLifeCycleState
{
/// <summary>Lifecycle state unknown.</summary>
Unknown = 0,
/// <summary>The application launched.</summary>
Launch = 1,
/// <summary>The application exited.</summary>
Exit = 2,
/// <summary>The application suspended.</summary>
Suspend = 3,
/// <summary>The application resumed.</summary>
Resume = 4,
/// <summary>The application came back into the foreground.</summary>
Foreground = 5,
/// <summary>The application went into the background.</summary>
Background = 6
};
/// <summary>
/// PII (Personal Identifiable Information) kind used to indicate an event property value
/// </summary>
public enum class PiiKind
{
/// <summary>No PII kind.</summary>
None = 0,
/// <summary>An LDAP distinguished name.</summary>
DistinguishedName = 1,
/// <summary>Generic data.</summary>
GenericData = 2,
/// <summary>An IPV4 Internet address.</summary>
IPv4Address = 3,
/// <summary>An IPV6 Internet address.</summary>
IPv6Address = 4,
/// <summary>An e-mail subject.</summary>
MailSubject = 5,
/// <summary>A telephone number.</summary>
PhoneNumber = 6,
/// <summary>A query string.</summary>
QueryString = 7,
/// <summary>A SIP address</summary>
SipAddress = 8,
/// <summary>An e-mail address.</summary>
SmtpAddress = 9,
/// <summary>An identity.</summary>
Identity = 10,
/// <summary>A uniform resource indicator.</summary>
Uri = 11,
/// <summary>A fully-qualified domain name.</summary>
Fqdn = 12,
/// <summary>A legacy IPV4 Internet address.</summary>
IPv4AddressLegacy = 13
};
}
}
}
}
namespace Microsoft {
namespace Applications
{
// Bringing enums defined in the public namespace.
// TODO: align with the ACT enums.
typedef Telemetry::Windows::ActionType ActionType;
typedef Telemetry::Windows::InputDeviceType InputDeviceType;
typedef Telemetry::Windows::AppLifeCycleState AppLifeCycleState;
typedef Telemetry::Windows::RawActionType RawActionType;
typedef Telemetry::Windows::EventPriority EventPriority;
enum class NetworkType
{
/// <summary>The type of network is unknown.</summary>
Unknown = 0,
/// <summary>A wired network.</summary>
Wired = 1,
/// <summary>A Wi-fi network.</summary>
Wifi = 2,
/// <summary>A wireless wide-area network.</summary>
WWAN = 3,
};
enum class OsArchitectureType
{
/// <summary>The OS architecture is either unknown or is unavailable.</summary>
Unknown = 0,
/// <summary>32-bit (x86) mode.</summary>
X86 = 1,
/// <summary>64-bit (x64) mode.</summary>
X64 = 2,
/// <summary>ARM processor family.</summary>
Arm = 3,
};
enum class NetworkCost
{
/// <summary>Network cost unknown.</summary>
Unknown = 0,
/// <summary>Unmetered.</summary>
Unmetered = 1,
/// <summary>Metered.</summary>
Metered = 2,
/// <summary>[deprecated]: Do no use this value.</summary>
OverDataLimit = 3,
};
}
}
|
#! /bin/bash
CURDIR=$(/bin/pwd)
# GENERATOR="Unix Makefiles"
GENERATOR=Ninja
set -u
set -e
set -x
STAGEDIR="${CURDIR}/stage"
CMAKE_PRESET="-G Ninja -DCMAKE_CXX_COMPILER_LAUNCHER=ccache -DCMAKE_BUILD_TYPE=Debug -DCMAKE_PREFIX_PATH=${STAGEDIR}"
export CPM_SOURCE_CACHE=${HOME}/.cache/CPM
export CPM_USE_LOCAL_PACKAGES=0
export CXX=g++-10
# distclean
rm -rf build root stage stagedir
# update CPM.cmake
#XXX wget -q -O cmake/CPM.cmake https://github.com/cpm-cmake/CPM.cmake/releases/latest/download/get_cpm.cmake
# install the library
cmake -S . -B build/install ${CMAKE_PRESET} -DCMAKE_INSTALL_PREFIX=${STAGEDIR} -DCMAKE_CXX_STANDARD=20 # --trace-expand
cmake --build build/install --target install
# test the library
cmake -S test -B build/test ${CMAKE_PRESET} -DTEST_INSTALLED_VERSION=1 #NO! -DENABLE_TEST_COVERAGE=1
cmake --build build/test
cmake --build build/test --target test
# all together
# cmake -S all -B build/all ${CMAKE_PRESET} -DTEST_INSTALLED_VERSION=1 -DENABLE_TEST_COVERAGE=1
# cmake --build build/all
# cmake --build build/all --target test
# cmake --build build/all --target check-format
# check the library
cmake -S . -B build/example ${CMAKE_PRESET} -DCMAKE_EXPORT_COMPILE_COMMANDS=1
cmake --build build/example --target all
run-clang-tidy.py -p build/example -checks='-*,modernize-*,misc-*,hicpp-*,cert-*,readability-*,portability-*,performance-*,cppcore*' example
|
#! /bin/sh
set -x
make distclean
aclocal -I build --output=build/aclocal.m4
libtoolize --copy --force
# cp -f ~/cvs/config/config.guess ~/cvs/config/config.sub build/
autoheader
automake --add-missing --copy
autoreconf --localdir=build --gnu
|
<reponame>alexdao/Lumi-Vote
package com.lumivote.lumivote.bus;
import com.lumivote.lumivote.api.sunlight_responses.votes.Result;
import java.util.List;
/**
* Created by alex on 8/6/15.
*/
public class SunlightVotesEvent extends AbstractSunlightEvent {
public enum Type {
COMPLETED,
STARTED
}
private List<Result> votesList;
public SunlightVotesEvent(Type type, List<Result> votesList) {
super(type);
this.votesList = votesList;
}
public List<Result> getVotesList() {
return votesList;
}
}
|
#!/usr/bin/env bash
# macOS script to build, flash and run BL602 Firmware
set -e # Exit when any command fails
set -x # Echo commands
# Build for BL602
export CONFIG_CHIP_NAME=BL602
# Where BL602 IoT SDK is located
export BL60X_SDK_PATH=$PWD/../..
# Where blflash is located
export BLFLASH_PATH=$PWD/../../../blflash
# Build the firmware
make
# Copy firmware to blflash
cp build_out/sdk_app_st7789.bin $BLFLASH_PATH
# Flash the firmware
pushd $BLFLASH_PATH
cargo run flash sdk_app_st7789.bin \
--port /dev/tty.usbserial-1420 \
--initial-baud-rate 230400 \
--baud-rate 230400
sleep 5
popd
# Run the firmware
open -a CoolTerm
|
//
// SidebarUserCell.h
// Zulip
//
// Created by <NAME> on 12/29/13.
//
//
@class ZUser;
#import <UIKit/UIKit.h>
@interface SidebarUserCell : UITableViewCell
@property (weak, nonatomic) IBOutlet UIView *statusIcon;
@property (weak, nonatomic) IBOutlet UILabel *name;
@property (weak, nonatomic) IBOutlet UILabel *unreadCount;
@property (strong, nonatomic) ZUser *user;
@property (strong, nonatomic) NSString *status;
- (void)calculateUnreadCount;
@end
|
#!/usr/bin/env bash
set -e
trap ontrap 0
# input env
export VIM_BUILD_PREFIX=$(pwd)
export INSTALL_PREFIX="$VIM_BUILD_PREFIX/install"
export BUILD_PREFIX="$VIM_BUILD_PREFIX/src"
ontrap()
{
cd "$VIM_BUILD_PREFIX"
exec /bin/sh -i
}
# versions
export ZLIB_VERSION="1.2.11"
export LIBFFI_VERSION="3.4.2"
export PYTHON_VERSION="3.9.6"
export RUBY_VERSION="3.0.2"
export VIM_VERSION="8.2.3384"
setup_env()
{
# base env
PATH="$INSTALL_PREFIX/bin${PATH:+:${PATH}}"; export PATH
MANPATH="$INSTALL_PREFIX/share/man${MANPATH:+:${MANPATH}}"; export MANPATH
LD_RUN_PATH="$INSTALL_PREFIX/lib:$INSTALL_PREFIX/lib64${LD_RUN_PATH:+:${LD_RUN_PATH}}"; export LD_RUN_PATH
# zlib
export ZLIB_FILE="zlib-$ZLIB_VERSION.tar.gz"
export ZLIB_FOLDER="zlib-$ZLIB_VERSION"
export ZLIB_URL="https://github.com/madler/zlib/archive/refs/tags/v$ZLIB_VERSION.tar.gz"
# libffi
export LIBFFI_FILE="libffi-$LIBFFI_VERSION.tar.gz"
export LIBFFI_FOLDER="libffi-$LIBFFI_VERSION"
export LIBFFI_URL="https://github.com/libffi/libffi/releases/download/v$LIBFFI_VERSION/libffi-$LIBFFI_VERSION.tar.gz"
# python
export PYTHON_FILE="Python-$PYTHON_VERSION.tgz"
export PYTHON_FOLDER="Python-$PYTHON_VERSION"
export PYTHON_URL="https://www.python.org/ftp/python/$PYTHON_VERSION/$PYTHON_FILE"
# ruby
export RUBY_FILE="ruby-$RUBY_VERSION.tar.gz"
export RUBY_FOLDER="ruby-$RUBY_VERSION"
RUBY_VERSION_SPLIT0=$(echo "$RUBY_VERSION" | cut -d "." -f1)
RUBY_VERSION_SPLIT1=$(echo "$RUBY_VERSION" | cut -d "." -f2)
export RUBY_URL="https://cache.ruby-lang.org/pub/ruby/$RUBY_VERSION_SPLIT0.$RUBY_VERSION_SPLIT1/$RUBY_FILE"
# vim
export VIM_FILE="vim-$VIM_VERSION.tar.gz"
export VIM_FOLDER="vim-$VIM_VERSION"
export VIM_URL="https://github.com/vim/vim/archive/refs/tags/v$VIM_VERSION.tar.gz"
}
download_and_extract_targz()
{
PREFIX="$1"
FILE_NAME="${PREFIX}_FILE"
FOLDER_NAME="${PREFIX}_FOLDER"
URL_NAME="${PREFIX}_URL"
eval FILE="\$${FILE_NAME}"
eval FOLDER="\$${FOLDER_NAME}"
eval URL="\$${URL_NAME}"
cd "$BUILD_PREFIX"
if [ ! -f "$$FILE" ]; then
wget -O "$FILE" "$URL"
fi
rm -rf "$FOLDER"
tar -xzf "$FILE"
}
download_sources()
{
download_and_extract_targz "ZLIB"
download_and_extract_targz "LIBFFI"
download_and_extract_targz "PYTHON"
download_and_extract_targz "RUBY"
download_and_extract_targz "VIM"
}
cleanup_file_and_folder()
{
PREFIX="$1"
FILE_NAME="${PREFIX}_FILE"
FOLDER_NAME="${PREFIX}_FOLDER"
eval FILE="\$${FILE_NAME}"
eval FOLDER="\$${FOLDER_NAME}"
cd "$BUILD_PREFIX"
rm "$FILE"
rm -r "$FOLDER"
}
cleanup()
{
cleanup_file_and_folder "ZLIB"
cleanup_file_and_folder "LIBFFI"
cleanup_file_and_folder "PYTHON"
cleanup_file_and_folder "RUBY"
cleanup_file_and_folder "VIM"
}
build_with_configure_and_make()
{
PREFIX="$1"
FOLDER_NAME="${PREFIX}_FOLDER"
eval FOLDER="\$${FOLDER_NAME}"
args=("$@")
args[0]="--prefix=${INSTALL_PREFIX}"
cd "$BUILD_PREFIX"
cd "$FOLDER"
echo $FOLDER
echo $(pwd)
./configure "${args[@]}"
make -j $(nproc)
make install
}
build()
{
build_with_configure_and_make "ZLIB"
build_with_configure_and_make "LIBFFI"
build_with_configure_and_make "PYTHON" \
--enable-shared \
--enable-optimizations
build_with_configure_and_make "RUBY"
build_with_configure_and_make "VIM" \
--with-features=huge \
--enable-multibyte \
--enable-rubyinterp=yes \
--enable-python3interp=yes \
--with-python3-config-dir=$(python3-config --configdir) \
--enable-perlinterp=no \
--enable-luainterp=no \
--enable-gui=no \
--enable-cscope
}
# run stuff
cd "$VIM_BUILD_PREFIX"
mkdir -p "$INSTALL_PREFIX"
mkdir -p "$BUILD_PREFIX"
setup_env
download_sources
build
# cleanup
cleanup
|
#!/bin/bash
# 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.
############################################################
# You may have to set variables bellow,
# which are used for compiling thirdparties and palo itself.
############################################################
###################################################
# DO NOT change variables bellow unless you known
# what you are doing.
###################################################
# thirdparties will be downloaded and unpacked here
export TP_SOURCE_DIR=$TP_DIR/src
# thirdparties will be installed to here
export TP_INSTALL_DIR=$TP_DIR/installed
# patches for all thirdparties
export TP_PATCH_DIR=$TP_DIR/patches
# header files of all thirdparties will be intalled to here
export TP_INCLUDE_DIR=$TP_INSTALL_DIR/include
# libraries of all thirdparties will be intalled to here
export TP_LIB_DIR=$TP_INSTALL_DIR/lib
# all java libraries will be unpacked to here
export TP_JAR_DIR=$TP_INSTALL_DIR/lib/jar
#####################################################
# Download url, filename and unpaced filename
# of all thirdparties
#####################################################
# libevent
# the last release version of libevent is 2.1.8, which was released on 26 Jan 2017, that is too old.
# so we use the master version of libevent, which is downloaded on 22 Jun 2018, with commit 24236aed01798303745470e6c498bf606e88724a
LIBEVENT_DOWNLOAD="https://github.com/libevent/libevent/archive/release-2.1.12-stable.tar.gz"
LIBEVENT_NAME=libevent-release-2.1.12-stable.tar.gz
LIBEVENT_SOURCE=libevent-release-2.1.12-stable
LIBEVENT_MD5SUM="0d5a27436bf7ff8253420c8cf09f47ca"
# openssl
OPENSSL_DOWNLOAD="https://www.openssl.org/source/old/1.0.2/openssl-1.0.2k.tar.gz"
OPENSSL_NAME=openssl-1.0.2k.tar.gz
OPENSSL_SOURCE=openssl-1.0.2k
OPENSSL_MD5SUM="f965fc0bf01bf882b31314b61391ae65"
# thrift
THRIFT_DOWNLOAD="http://archive.apache.org/dist/thrift/0.13.0/thrift-0.13.0.tar.gz"
THRIFT_NAME=thrift-0.13.0.tar.gz
THRIFT_SOURCE=thrift-0.13.0
THRIFT_MD5SUM="38a27d391a2b03214b444cb13d5664f1"
# protobuf
PROTOBUF_DOWNLOAD="https://github.com/google/protobuf/archive/v3.14.0.tar.gz"
PROTOBUF_NAME=protobuf-3.14.0.tar.gz
PROTOBUF_SOURCE=protobuf-3.14.0
PROTOBUF_MD5SUM="0c9d2a96f3656ba7ef3b23b533fb6170"
# gflags
GFLAGS_DOWNLOAD="https://github.com/gflags/gflags/archive/v2.2.2.tar.gz"
GFLAGS_NAME=gflags-2.2.2.tar.gz
GFLAGS_SOURCE=gflags-2.2.2
GFLAGS_MD5SUM="1a865b93bacfa963201af3f75b7bd64c"
# glog
GLOG_DOWNLOAD="https://github.com/google/glog/archive/v0.4.0.tar.gz"
GLOG_NAME=glog-0.4.0.tar.gz
GLOG_SOURCE=glog-0.4.0
GLOG_MD5SUM="0daea8785e6df922d7887755c3d100d0"
# gtest
GTEST_DOWNLOAD="https://github.com/google/googletest/archive/release-1.10.0.tar.gz"
GTEST_NAME=googletest-release-1.10.0.tar.gz
GTEST_SOURCE=googletest-release-1.10.0
GTEST_MD5SUM="ecd1fa65e7de707cd5c00bdac56022cd"
# snappy
SNAPPY_DOWNLOAD="https://github.com/google/snappy/archive/1.1.8.tar.gz"
SNAPPY_NAME=snappy-1.1.8.tar.gz
SNAPPY_SOURCE=snappy-1.1.8
SNAPPY_MD5SUM="70e48cba7fecf289153d009791c9977f"
# gperftools
GPERFTOOLS_DOWNLOAD="https://github.com/gperftools/gperftools/archive/gperftools-2.9.1.tar.gz"
GPERFTOOLS_NAME=gperftools-2.9.1.tar.gz
GPERFTOOLS_SOURCE=gperftools-gperftools-2.9.1
GPERFTOOLS_MD5SUM="e340f1b247ff512119a2db98c1538dc1"
# zlib
ZLIB_DOWNLOAD="https://sourceforge.net/projects/libpng/files/zlib/1.2.11/zlib-1.2.11.tar.gz"
ZLIB_NAME=zlib-1.2.11.tar.gz
ZLIB_SOURCE=zlib-1.2.11
ZLIB_MD5SUM="1c9f62f0778697a09d36121ead88e08e"
# lz4
LZ4_DOWNLOAD="https://github.com/lz4/lz4/archive/v1.9.3.tar.gz"
LZ4_NAME=lz4-1.9.3.tar.gz
LZ4_SOURCE=lz4-1.9.3
LZ4_MD5SUM="3a1ab1684e14fc1afc66228ce61b2db3"
# bzip
BZIP_DOWNLOAD="https://fossies.org/linux/misc/bzip2-1.0.8.tar.gz"
BZIP_DOWNLOAD="ftp://sourceware.org/pub/bzip2/bzip2-1.0.8.tar.gz"
BZIP_NAME=bzip2-1.0.8.tar.gz
BZIP_SOURCE=bzip2-1.0.8
BZIP_MD5SUM="67e051268d0c475ea773822f7500d0e5"
# lzo2
LZO2_DOWNLOAD="http://www.oberhumer.com/opensource/lzo/download/lzo-2.10.tar.gz"
LZO2_NAME=lzo-2.10.tar.gz
LZO2_SOURCE=lzo-2.10
LZO2_MD5SUM="39d3f3f9c55c87b1e5d6888e1420f4b5"
# rapidjson
RAPIDJSON_DOWNLOAD="https://github.com/Tencent/rapidjson/archive/1a803826f1197b5e30703afe4b9c0e7dd48074f5.zip"
RAPIDJSON_NAME=rapidjson-1a803826f1197b5e30703afe4b9c0e7dd48074f5.zip
RAPIDJSON_SOURCE=rapidjson-1a803826f1197b5e30703afe4b9c0e7dd48074f5
RAPIDJSON_MD5SUM="f2212a77e055a15501477f1e390007ea"
# curl
CURL_DOWNLOAD="https://curl.se/download/curl-7.79.0.tar.gz"
CURL_NAME=curl-7.79.0.tar.gz
CURL_SOURCE=curl-7.79.0
CURL_MD5SUM="b40e4dc4bbc9e109c330556cd58c8ec8"
# RE2
RE2_DOWNLOAD="https://github.com/google/re2/archive/2021-02-02.tar.gz"
RE2_NAME=re2-2021-02-02.tar.gz
RE2_SOURCE=re2-2021-02-02
RE2_MD5SUM="48bc665463a86f68243c5af1bac75cd0"
# boost
BOOST_DOWNLOAD="https://boostorg.jfrog.io/artifactory/main/release/1.73.0/source/boost_1_73_0.tar.gz"
BOOST_NAME=boost_1_73_0.tar.gz
BOOST_SOURCE=boost_1_73_0
BOOST_MD5SUM="4036cd27ef7548b8d29c30ea10956196"
# mysql
MYSQL_DOWNLOAD="https://github.com/mysql/mysql-server/archive/mysql-5.7.18.tar.gz"
MYSQL_NAME=mysql-5.7.18.tar.gz
MYSQL_SOURCE=mysql-server-mysql-5.7.18
MYSQL_MD5SUM="58598b10dce180e4d1fbdd7cf5fa68d6"
# unix odbc
ODBC_DOWNLOAD="http://www.unixodbc.org/unixODBC-2.3.7.tar.gz"
ODBC_NAME=unixODBC-2.3.7.tar.gz
ODBC_SOURCE=unixODBC-2.3.7
ODBC_MD5SUM="274a711b0c77394e052db6493840c6f9"
# leveldb
LEVELDB_DOWNLOAD="https://github.com/google/leveldb/archive/v1.20.tar.gz"
LEVELDB_NAME=leveldb-1.20.tar.gz
LEVELDB_SOURCE=leveldb-1.20
LEVELDB_MD5SUM="298b5bddf12c675d6345784261302252"
# brpc
# incubator-brpc-1.0.0-rc02 is a stable version。 Due to the issue of the version release process,
# there may not be an official version
BRPC_DOWNLOAD="https://github.com/apache/incubator-brpc/archive/1.0.0-rc02.tar.gz"
BRPC_NAME=incubator-brpc-1.0.0-rc02.tar.gz
BRPC_SOURCE=incubator-brpc-1.0.0-rc02
BRPC_MD5SUM="863b9e53f3642fd31eeb438dbfc4f55c"
# rocksdb
ROCKSDB_DOWNLOAD="https://github.com/facebook/rocksdb/archive/v5.14.2.tar.gz"
ROCKSDB_NAME=rocksdb-5.14.2.tar.gz
ROCKSDB_SOURCE=rocksdb-5.14.2
ROCKSDB_MD5SUM="b72720ea3b1e9ca9e4ed0febfef65b14"
#cyrus-sasl
CYRUS_SASL_DOWNLOAD="https://github.com/cyrusimap/cyrus-sasl/releases/download/cyrus-sasl-2.1.27/cyrus-sasl-2.1.27.tar.gz"
CYRUS_SASL_NAME=cyrus-sasl-2.1.27.tar.gz
CYRUS_SASL_SOURCE=cyrus-sasl-2.1.27
CYRUS_SASL_MD5SUM="a33820c66e0622222c5aefafa1581083"
# librdkafka-1.8.0
LIBRDKAFKA_DOWNLOAD="https://github.com/edenhill/librdkafka/archive/v1.8.0.tar.gz"
LIBRDKAFKA_NAME=librdkafka-1.8.0.tar.gz
LIBRDKAFKA_SOURCE=librdkafka-1.8.0
LIBRDKAFKA_MD5SUM="f31bd3b7a91a486d65b740a720b925dc"
# zstd
ZSTD_DOWNLOAD="https://github.com/facebook/zstd/archive/v1.5.0.tar.gz"
ZSTD_NAME=zstd-1.5.0.tar.gz
ZSTD_SOURCE=zstd-1.5.0
ZSTD_MD5SUM="d5ac89d5df9e81243ce40d0c6a66691d"
# brotli
BROTLI_DOWNLOAD="https://github.com/google/brotli/archive/v1.0.9.tar.gz"
BROTLI_NAME="brotli-1.0.9.tar.gz"
BROTLI_SOURCE="brotli-1.0.9"
BROTLI_MD5SUM="c2274f0c7af8470ad514637c35bcee7d"
# flatbuffers
FLATBUFFERS_DOWNLOAD="https://github.com/google/flatbuffers/archive/v2.0.0.tar.gz"
FLATBUFFERS_NAME=flatbuffers-2.0.0.tar.gz
FLATBUFFERS_SOURCE=flatbuffers-2.0.0
FLATBUFFERS_MD5SUM="a27992324c3cbf86dd888268a23d17bd"
# arrow
ARROW_DOWNLOAD="https://github.com/apache/arrow/archive/apache-arrow-5.0.0.tar.gz"
ARROW_NAME="arrow-apache-arrow-5.0.0.tar.gz"
ARROW_SOURCE="arrow-apache-arrow-5.0.0"
ARROW_MD5SUM="9caf5dbd36ef4972c3a591bcfeaf59c8"
# S2
S2_DOWNLOAD="https://github.com/google/s2geometry/archive/v0.9.0.tar.gz"
S2_NAME=s2geometry-0.9.0.tar.gz
S2_SOURCE=s2geometry-0.9.0
S2_MD5SUM="293552c7646193b8b4a01556808fe155"
# BITSHUFFLE
BITSHUFFLE_DOWNLOAD="https://github.com/kiyo-masui/bitshuffle/archive/0.3.5.tar.gz"
BITSHUFFLE_NAME=bitshuffle-0.3.5.tar.gz
BITSHUFFLE_SOURCE=bitshuffle-0.3.5
BITSHUFFLE_MD5SUM="2648ec7ccd0b896595c6636d926fc867"
# CROARINGBITMAP
CROARINGBITMAP_DOWNLOAD="https://github.com/RoaringBitmap/CRoaring/archive/v0.3.4.tar.gz"
CROARINGBITMAP_NAME=CRoaring-0.3.4.tar.gz
CROARINGBITMAP_SOURCE=CRoaring-0.3.4
CROARINGBITMAP_MD5SUM="29d1fa59f86b46915c6dd92c1a9a6c75"
# fmt
FMT_DOWNLOAD="https://github.com/fmtlib/fmt/archive/7.1.3.tar.gz"
FMT_NAME="fmt-7.1.3.tar.gz"
FMT_SOURCE="fmt-7.1.3"
FMT_MD5SUM="2522ec65070c0bda0ca288677ded2831"
# parallel-hashmap
PARALLEL_HASHMAP_DOWNLOAD="https://github.com/greg7mdp/parallel-hashmap/archive/1.33.tar.gz"
PARALLEL_HASHMAP_NAME="parallel-hashmap-1.33.tar.gz"
PARALLEL_HASHMAP_SOURCE="parallel-hashmap-1.33"
PARALLEL_HASHMAP_MD5SUM="7626b5215f745c4ce59b5a4e41d16235"
# ORC
ORC_DOWNLOAD="https://archive.apache.org/dist/orc/orc-1.6.6/orc-1.6.6.tar.gz"
ORC_NAME=orc-1.6.6.tar.gz
ORC_SOURCE=orc-1.6.6
ORC_MD5SUM="26c94135111d312fb1ea4fc80d776c5f"
# jemalloc
JEMALLOC_DOWNLOAD="https://github.com/jemalloc/jemalloc/releases/download/5.2.1/jemalloc-5.2.1.tar.bz2"
JEMALLOC_NAME="jemalloc-5.2.1.tar.bz2"
JEMALLOC_SOURCE="jemalloc-5.2.1"
JEMALLOC_MD5SUM="3d41fbf006e6ebffd489bdb304d009ae"
# CCTZ
CCTZ_DOWNLOAD="https://github.com/google/cctz/archive/v2.3.tar.gz"
CCTZ_NAME="cctz-2.3.tar.gz"
CCTZ_SOURCE="cctz-2.3"
CCTZ_MD5SUM="209348e50b24dbbdec6d961059c2fc92"
# datatables, bootstrap 3 and jQuery 3
# The origin download url is always changing: https://datatables.net/download/builder?bs-3.3.7/jq-3.3.1/dt-1.10.25
# So we put it in our own http server.
# If someone can offer an official url for DataTables, please update this.
DATATABLES_DOWNLOAD="https://doris-thirdparty-repo.bj.bcebos.com/thirdparty/DataTables.zip"
DATATABLES_NAME="DataTables.zip"
DATATABLES_SOURCE="DataTables-1.10.25"
DATATABLES_MD5SUM="c8fd73997c9871e213ee4211847deed5"
# bootstrap table js
BOOTSTRAP_TABLE_JS_DOWNLOAD="https://unpkg.com/bootstrap-table@1.17.1/dist/bootstrap-table.min.js"
BOOTSTRAP_TABLE_JS_NAME="bootstrap-table.min.js"
BOOTSTRAP_TABLE_JS_FILE="bootstrap-table.min.js"
BOOTSTRAP_TABLE_JS_MD5SUM="6cc9c41eaf7e81e54e220061cc9c0432"
# bootstrap table css
BOOTSTRAP_TABLE_CSS_DOWNLOAD="https://unpkg.com/bootstrap-table@1.17.1/dist/bootstrap-table.min.css"
BOOTSTRAP_TABLE_CSS_NAME="bootstrap-table.min.css"
BOOTSTRAP_TABLE_CSS_FILE="bootstrap-table.min.css"
BOOTSTRAP_TABLE_CSS_MD5SUM="23389d4456da412e36bae30c469a766a"
# aws-c-common
AWS_C_COMMON_DOWNLOAD="https://github.com/awslabs/aws-c-common/archive/v0.4.63.tar.gz"
AWS_C_COMMON_NAME="aws-c-common-0.4.63.tar.gz"
AWS_C_COMMON_SOURCE="aws-c-common-0.4.63"
AWS_C_COMMON_MD5SUM="8298e00a0fb64779b7cf660592d50ab6"
# aws-c-event-stream
AWS_C_EVENT_STREAM_DOWNLOAD="https://github.com/awslabs/aws-c-event-stream/archive/v0.2.6.tar.gz"
AWS_C_EVENT_STREAM_NAME="aws-c-event-stream-0.2.6.tar.gz"
AWS_C_EVENT_STREAM_SOURCE="aws-c-event-stream-0.2.6"
AWS_C_EVENT_STREAM_MD5SUM="fceedde198ddbf38ffdaed08d1435f7f"
# aws-checksums
AWS_CHECKSUMS_DOWNLOAD="https://github.com/awslabs/aws-checksums/archive/v0.1.10.tar.gz"
AWS_CHECKSUMS_NAME="aws-checksums-0.1.10.tar.gz"
AWS_CHECKSUMS_SOURCE="aws-checksums-0.1.10"
AWS_CHECKSUMS_MD5SUM="2383c66f6250fa0238edbd1d779b49d3"
# aws-c-io
AWS_C_IO_DOWNLOAD="https://github.com/awslabs/aws-c-io/archive/v0.7.0.tar.gz"
AWS_C_IO_NAME="aws-c-io-0.7.0.tar.gz"
AWS_C_IO_SOURCE="aws-c-io-0.7.0"
AWS_C_IO_MD5SUM="b95a6f9d20500727231dd726c957276b"
# aws-s2n
AWS_S2N_DOWNLOAD="https://github.com/awslabs/s2n/archive/v0.10.0.tar.gz"
AWS_S2N_NAME="s2n-0.10.0.tar.gz"
AWS_S2N_SOURCE="s2n-tls-0.10.0"
AWS_S2N_MD5SUM="345aa5d2f9e82347bb3e568c22104d0e"
# aws-c-cal
AWS_C_CAL_DOWNLOAD="https://github.com/awslabs/aws-c-cal/archive/v0.4.5.tar.gz"
AWS_C_CAL_NAME="aws-c-cal-0.4.5.tar.gz"
AWS_C_CAL_SOURCE="aws-c-cal-0.4.5"
AWS_C_CAL_MD5SUM="317f3dbafae551a0fc7d70f31434e216"
# aws sdk
AWS_SDK_DOWNLOAD="https://github.com/aws/aws-sdk-cpp/archive/1.8.108.tar.gz"
AWS_SDK_NAME="aws-sdk-cpp-1.8.108.tar.gz"
AWS_SDK_SOURCE="aws-sdk-cpp-1.8.108"
AWS_SDK_MD5SUM="76d8855406e7da61f1f996c11c0b93d7"
# tsan_header
TSAN_HEADER_DOWNLOAD="https://gcc.gnu.org/git/?p=gcc.git;a=blob_plain;f=libsanitizer/include/sanitizer/tsan_interface_atomic.h;hb=refs/heads/releases/gcc-7"
TSAN_HEADER_NAME="tsan_interface_atomic.h"
TSAN_HEADER_FILE="tsan_interface_atomic.h"
TSAN_HEADER_MD5SUM="d72679bea167d6a513d959f5abd149dc"
# lzma
LZMA_DOWNLOAD="https://github.com/kobolabs/liblzma/archive/refs/heads/master.zip"
LZMA_NAME="liblzma-master.zip"
LZMA_SOURCE="liblzma-master"
LZMA_MD5SUM="ef11f2fbbfa6893b629f207a32bf730e"
# xml2
XML2_DOWNLOAD="https://gitlab.gnome.org/GNOME/libxml2/-/archive/v2.9.10/libxml2-v2.9.10.tar.gz"
XML2_NAME="libxml2-v2.9.10.tar.gz"
XML2_SOURCE="libxml2-v2.9.10"
XML2_MD5SUM="b18faee9173c3378c910f6d7d1493115"
# gsasl
GSASL_DOWNLOAD="https://ftp.gnu.org/gnu/gsasl/libgsasl-1.10.0.tar.gz"
GSASL_NAME="libgsasl-1.10.0.tar.gz"
GSASL_SOURCE="libgsasl-1.10.0"
GSASL_MD5SUM="9c8fc632da4ce108fb7581b33de2a5ce"
# hdfs3
HDFS3_DOWNLOAD="https://doris-thirdparty-repo.bj.bcebos.com/thirdparty/libhdfs3-master.zip"
HDFS3_NAME="libhdfs3-master.zip"
HDFS3_SOURCE="libhdfs3-master"
HDFS3_MD5SUM="8c071fd2e7b0b1ccc1ec9c0d073d4146"
#libdivide
LIBDIVIDE_DOWNLOAD="https://github.com/ridiculousfish/libdivide/archive/5.0.tar.gz"
LIBDIVIDE_NAME="libdivide-5.0.tar.gz"
LIBDIVIDE_SOURCE="libdivide-5.0"
LIBDIVIDE_MD5SUM="7fd16b0bb4ab6812b2e2fdc7bfb81641"
#pdqsort
PDQSORT_DOWNLOAD="http://ftp.cise.ufl.edu/ubuntu/pool/universe/p/pdqsort/pdqsort_0.0.0+git20180419.orig.tar.gz"
PDQSORT_NAME="pdqsort.tar.gz"
PDQSORT_SOURCE="pdqsort-0.0.0+git20180419"
PDQSORT_MD5SUM="39261c3e7b40aa7505662fac29f22d20"
# benchmark
BENCHMARK_DOWNLOAD="https://github.com/google/benchmark/archive/v1.5.6.tar.gz"
BENCHMARK_NAME=benchmark-1.5.6.tar.gz
BENCHMARK_SOURCE=benchmark-1.5.6
BENCHMARK_MD5SUM="668b9e10d8b0795e5d461894db18db3c"
# breakpad
# breakpad has no release version, the source is from commit@38ee0be,
# and also add lss files. See README.md in it.
BREAKPAD_DOWNLOAD="https://doris-thirdparty-repo.bj.bcebos.com/thirdparty/breakpad-src-38ee0be-with-lss.tar.gz"
BREAKPAD_NAME=breakpad-src-38ee0be-with-lss.tar.gz
BREAKPAD_SOURCE=breakpad-src-38ee0be-with-lss
BREAKPAD_MD5SUM="fd8c4f6f5cf8b5e03a4c3c39fde83368"
# all thirdparties which need to be downloaded is set in array TP_ARCHIVES
export TP_ARCHIVES="LIBEVENT
OPENSSL
THRIFT
PROTOBUF
GFLAGS
GLOG
GTEST
RAPIDJSON
SNAPPY
GPERFTOOLS
ZLIB
LZ4
BZIP
LZO2
CURL
RE2
BOOST
MYSQL
ODBC
LEVELDB
BRPC
ROCKSDB
CYRUS_SASL
LIBRDKAFKA
FLATBUFFERS
ARROW
BROTLI
ZSTD
S2
BITSHUFFLE
CROARINGBITMAP
FMT
PARALLEL_HASHMAP
ORC
JEMALLOC
CCTZ
DATATABLES
BOOTSTRAP_TABLE_JS
BOOTSTRAP_TABLE_CSS
TSAN_HEADER
AWS_C_COMMON
AWS_C_EVENT_STREAM
AWS_C_IO
AWS_C_CAL
AWS_C_IO
AWS_CHECKSUMS
AWS_S2N
AWS_SDK
LZMA
XML2
GSASL
HDFS3
LIBDIVIDE
PDQSORT
BENCHMARK
BREAKPAD"
|
<filename>snippet.js
// Helper function to tally data
let data = [];
let newArry = data.reduce((accumulator, currentVal) => {
// IF in the accumulator the item exists then return accumulator unchanged
// IF item does not exist then push to accumulator then return
if(accumulator.indexOf(currentVal.item) === -1){
accumulator.push(currentVal.item); // NOTE: push returns the lenght of an array, so don't prefix return here.
}
return accumulator;
}, []); |
#!/bin/sh
# 使用说明,用来提示输入参数
usage() {
echo "Usage: sh 执行脚本.sh [port|base|modules|stop|rm]"
exit 1
}
# 开启所需端口
port(){
firewall-cmd --add-port=80/tcp --permanent
firewall-cmd --add-port=8080/tcp --permanent
firewall-cmd --add-port=8848/tcp --permanent
firewall-cmd --add-port=9848/tcp --permanent
firewall-cmd --add-port=9849/tcp --permanent
firewall-cmd --add-port=6379/tcp --permanent
firewall-cmd --add-port=3306/tcp --permanent
firewall-cmd --add-port=9100/tcp --permanent
firewall-cmd --add-port=9200/tcp --permanent
firewall-cmd --add-port=9201/tcp --permanent
firewall-cmd --add-port=9202/tcp --permanent
firewall-cmd --add-port=9203/tcp --permanent
firewall-cmd --add-port=9300/tcp --permanent
service firewalld restart
}
# 启动基础环境(必须)
base(){
docker-compose up -d wdh-mysql wdh-redis wdh-nacos
}
# 启动程序模块(必须)
modules(){
docker-compose up -d wdh-nginx wdh-gateway wdh-auth wdh-modules-system
}
# 关闭所有环境/模块
stop(){
docker-compose stop
}
# 删除所有环境/模块
rm(){
docker-compose rm
}
# 根据输入参数,选择执行对应方法,不输入则执行使用说明
case "$1" in
"port")
port
;;
"base")
base
;;
"modules")
modules
;;
"stop")
stop
;;
"rm")
rm
;;
*)
usage
;;
esac
|
<reponame>julian-eggers/jenkins-push-automatization
package com.itelg.devops.jpa.config;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import org.junit.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import com.itelg.spring.actuator.jenkins.JenkinsHealthIndicator;
public class ActuatorConfigurationTest
{
private ApplicationContextRunner contextRunner = new ApplicationContextRunner().withConfiguration(AutoConfigurations.of(ActuatorConfiguration.class));
@Test
public void testJenkinsHealthIndicatorWithAuthentication()
{
contextRunner.withPropertyValues("jenkins.url=http://jenkins-server:8080/", "jenkins.username=admin", "jenkins.password=<PASSWORD>").run((
context) ->
{
assertThat(context).hasSingleBean(JenkinsHealthIndicator.class);
JenkinsHealthIndicator healthIndicator = context.getBean(JenkinsHealthIndicator.class);
assertEquals("http://jenkins-server:8080/", healthIndicator.getUrl());
assertEquals("admin", healthIndicator.getUsername());
assertEquals("<PASSWORD>", healthIndicator.getPassword());
});
}
@Test
public void testJenkinsHealthIndicatorWithAuthenticationButWithoutUsername()
{
contextRunner.withPropertyValues("jenkins.url=http://jenkins-server:8080/", "jenkins.username=", "jenkins.password=<PASSWORD>").run((context) ->
{
assertThat(context).hasSingleBean(JenkinsHealthIndicator.class);
JenkinsHealthIndicator healthIndicator = context.getBean(JenkinsHealthIndicator.class);
assertEquals("http://jenkins-server:8080/", healthIndicator.getUrl());
assertNull(healthIndicator.getUsername());
assertNull(healthIndicator.getPassword());
});
}
@Test
public void testJenkinsHealthIndicatorWithAuthenticationButWithoutPassword()
{
contextRunner.withPropertyValues("jenkins.url=http://jenkins-server:8080/", "jenkins.username=admin", "jenkins.password=").run((context) ->
{
assertThat(context).hasSingleBean(JenkinsHealthIndicator.class);
JenkinsHealthIndicator healthIndicator = context.getBean(JenkinsHealthIndicator.class);
assertEquals("http://jenkins-server:8080/", healthIndicator.getUrl());
assertNull(healthIndicator.getUsername());
assertNull(healthIndicator.getPassword());
});
}
@Test
public void testJenkinsHealthIndicatorWithoutAuthentication()
{
contextRunner.withPropertyValues("jenkins.url=http://jenkins-server:8080/", "jenkins.username=", "jenkins.password=").run((context) ->
{
assertThat(context).hasSingleBean(JenkinsHealthIndicator.class);
JenkinsHealthIndicator healthIndicator = context.getBean(JenkinsHealthIndicator.class);
assertEquals("http://jenkins-server:8080/", healthIndicator.getUrl());
assertNull(healthIndicator.getUsername());
assertNull(healthIndicator.getPassword());
});
}
}
|
<reponame>Marinoland/marinoland_web
#include <sstream>
#include <iostream>
#include "RestWebResponse.hpp"
using namespace std;
namespace web {
RestWebResponse::RestWebResponse(const WebResponse & cp) : WebResponse(cp) {
}
json::nodeptr RestWebResponse::getJson() {
json::nodeptr ret;
json::parse(getBody(),
[&] (json::nodeptr node)
{
ret = node;
},
[&] (string msg)
{
ret = make_shared<json::JsonNullNode>();
cerr << msg << endl;
});
return ret;
}
} |
from yourapp.models import CustomModel
class CustomModel:
def calculate_total(self, quantity, price):
return quantity * price |
<gh_stars>10-100
/*
* Copyright © 2019 IBM Corp. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package dev.ebullient.dnd.mechanics;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class ChallengeRatingTest {
@Test
public void testCalculateCR() {
int lowest = 0;
int highest = 0;
for (Type t : Type.allValues) {
for (Size s : Size.allValues) {
int cr = ChallengeRating.calculateCR(s, t);
//System.out.println(s + " " + t + ": " + cr);
if (cr < lowest) {
lowest = cr;
} else if (cr > highest) {
highest = cr;
}
}
}
Assertions.assertEquals(-3, lowest, "Lowest possible value should be -3 (CR 1/8)");
Assertions.assertTrue(highest < 23, "Highest value should be < 23");
}
}
|
#! /bin/bash
# Sets the confir params for heroku
# Uses command line parameter and env variables to populate fields in the template file.
# Source the env file to get values for the business org credentials
. ./.env
# Check for variables from env file
if [ -z $LISTENER_APPNAME ]
then
echo "App name for Listener must be defined in .env file"
exit 1
fi
#Create a new heroku app
NUMBER=$RANDOM
APPNAME="pe-quickstart-worker-"
APPNAME+=${NUMBER}
heroku create ${APPNAME}
#Attach heroku to git and push the code
#git push heroku master
#Add redis on to the new heroku app
heroku addons:attach ${LISTENER_APPNAME}::REDIS --app ${APPNAME} |
<reponame>glowroot/glowroot-instrumentation
/*
* Copyright 2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.glowroot.instrumentation.okhttp.boot;
import org.glowroot.instrumentation.api.AsyncSpan;
import org.glowroot.instrumentation.api.Setter;
import org.glowroot.instrumentation.api.Span;
import org.glowroot.instrumentation.api.ThreadContext;
import org.glowroot.instrumentation.api.TimerName;
import org.glowroot.instrumentation.api.checker.Nullable;
public class Util {
private Util() {}
public static <C> Span startOutgoingSpan(ThreadContext context, @Nullable String httpMethod,
@Nullable String uri, Setter<C> setter, C carrier, TimerName timerName) {
return context.startOutgoingSpan("HTTP", getText(httpMethod, uri), setter, carrier,
new HttpRequestMessageSupplier(httpMethod, uri), timerName);
}
public static <C> AsyncSpan startAsyncOutgoingSpan(ThreadContext context,
@Nullable String httpMethod, @Nullable String uri, Setter<C> setter, C carrier,
TimerName timerName) {
return context.startAsyncOutgoingSpan("HTTP", getText(httpMethod, uri), setter, carrier,
new HttpRequestMessageSupplier(httpMethod, uri), timerName);
}
private static String getText(@Nullable String httpMethod, @Nullable String uri) {
int maxLength = 0;
if (httpMethod != null) {
maxLength += httpMethod.length();
}
if (uri != null) {
maxLength += uri.length() + 1;
}
StringBuilder sb = new StringBuilder(maxLength);
if (httpMethod != null) {
sb.append(httpMethod);
}
if (uri != null) {
if (sb.length() != 0) {
sb.append(' ');
}
sb.append(stripQueryString(uri));
}
return sb.toString();
}
private static String stripQueryString(String uri) {
int index = uri.indexOf('?');
return index == -1 ? uri : uri.substring(0, index);
}
}
|
package gov.usgs.traveltime;
import java.util.ArrayList;
/**
* Acquire the travel-time statistics data in one degree bins, do the linear fits between the break
* flags, and release the raw statistics data.
*
* @author <NAME>
*/
public class TtStatLinFit {
double[] res, spd, obs;
boolean[] resBrk, spdBrk, obsBrk;
TtStat ttStat;
int minDelta, maxDelta;
/**
* Set up the 1 degree arrays.
*
* @param ttStat Phase statistics object
*/
protected TtStatLinFit(TtStat ttStat) {
this.ttStat = ttStat;
minDelta = ttStat.minDelta;
maxDelta = ttStat.maxDelta;
// set up the 1 degree statistics arrays.
res = new double[maxDelta - minDelta + 1];
resBrk = new boolean[maxDelta - minDelta + 1];
spd = new double[maxDelta - minDelta + 1];
spdBrk = new boolean[maxDelta - minDelta + 1];
obs = new double[maxDelta - minDelta + 1];
obsBrk = new boolean[maxDelta - minDelta + 1];
// Initialize the arrays.
for (int j = 0; j < res.length; j++) {
res[j] = Double.NaN;
resBrk[j] = false;
spd[j] = Double.NaN;
spdBrk[j] = false;
obs[j] = Double.NaN;
obsBrk[j] = false;
}
}
/**
* Add statistics for one 1 degree distance bin.
*
* @param delta Distance in degrees at the bin center
* @param res Travel-time residual bias in seconds
* @param resBrk Break the interpolation at this bin if true
* @param spd Robust estimate of the scatter of travel-time residuals
* @param spdBrk Break the interpolation at this bin if true
* @param obs Number of times this phase was observed in the defining study
* @param obsBrk Break the interpolation at this bin if true
*/
protected void add(
int delta,
double res,
boolean resBrk,
double spd,
boolean spdBrk,
double obs,
boolean obsBrk) {
this.res[delta - minDelta] = res;
this.resBrk[delta - minDelta] = resBrk;
this.spd[delta - minDelta] = spd;
this.spdBrk[delta - minDelta] = spdBrk;
this.obs[delta - minDelta] = obs;
this.obsBrk[delta - minDelta] = obsBrk;
}
/** Do the linear fits for all statistics variables. */
protected void fitAll() {
doFits(ttStat.bias, res, resBrk);
doFits(ttStat.spread, spd, spdBrk);
doFits(ttStat.observ, obs, obsBrk);
}
/**
* Do the linear fits for all segments of one statistics variable.
*
* @param interp The ArrayList where the fits will be stored
* @param value Array of parameter values
* @param brk Array of break point flags
*/
protected void doFits(ArrayList<TtStatSeg> interp, double[] value, boolean[] brk) {
int start, end = 0;
double startDelta, endDelta;
double[] b;
// Find the break points and invoke the fitter for each segment.
endDelta = minDelta;
for (int j = 0; j < value.length; j++) {
if (brk[j]) {
start = end;
end = j;
startDelta = endDelta;
endDelta = minDelta + (double) j;
b = do1Fit(start, end, minDelta, value);
interp.add(new TtStatSeg(startDelta, endDelta, b[0], b[1]));
}
}
// Fit the last segment.
start = end;
end = value.length - 1;
startDelta = endDelta;
endDelta = minDelta + (double) end;
b = do1Fit(start, end, minDelta, value);
interp.add(new TtStatSeg(startDelta, endDelta, b[0], b[1]));
fixEnds(interp);
}
/**
* Do the linear fit for one segment of one statistics variable.
*
* @param start Array index of the start of the segment
* @param end Array index of the end of the segment
* @param minDelta Minimum distance where the phase is observed in degrees
* @param value Raw statistics data to be fit
* @return An array containing the fit slope and offset
*/
protected double[] do1Fit(int start, int end, double minDelta, double[] value) {
double[][] a = new double[2][2];
double[] y = new double[2];
double[] b = new double[2];
double delta, det;
// Initialize temporary storage.
for (int i = 0; i < 2; i++) {
y[i] = 0d;
for (int j = 0; j < 2; j++) {
a[i][j] = 0d;
}
}
// Skip null bins and collect the data available.
for (int j = start; j <= end; j++) {
if (!Double.isNaN(value[j])) {
delta = minDelta + j;
y[0] += value[j] * delta;
y[1] += value[j];
a[0][0] += 1d;
a[0][1] -= delta;
a[1][1] += Math.pow(delta, 2);
}
}
a[1][0] = a[0][1];
// Do the fit.
det = a[0][0] * a[1][1] - a[0][1] * a[1][0];
b[0] = (a[0][0] * y[0] + a[0][1] * y[1]) / det;
b[1] = (a[1][0] * y[0] + a[1][1] * y[1]) / det;
return b;
}
/**
* Successive linear fits don't quite connect with each other at exactly the break point
* distances. Compute the actual cross- over distances and apply them to the end of one segment
* and the start of the next.
*
* @param interp ArrayList of linear fit segments for one parameter
*/
protected void fixEnds(ArrayList<TtStatSeg> interp) {
TtStatSeg last, cur;
cur = interp.get(0);
for (int j = 1; j < interp.size(); j++) {
last = cur;
cur = interp.get(j);
last.maxDelta = -(last.offset - cur.offset) / (last.slope - cur.slope);
cur.minDelta = last.maxDelta;
}
}
/** Print the travel-time statistics. */
protected void dumpStats() {
char[] flag;
// Print the header.
System.out.println("\n" + ttStat.phCode + " " + minDelta + " " + maxDelta);
// If the arrays still exist, dump the raw statistics.
flag = new char[3];
for (int j = 0; j < res.length; j++) {
if (resBrk[j]) flag[0] = '*';
else flag[0] = ' ';
if (spdBrk[j]) flag[1] = '*';
else flag[1] = ' ';
if (obsBrk[j]) flag[2] = '*';
else flag[2] = ' ';
System.out.format(
" %3d %7.2f%c %7.2f%c %8.1f%c\n",
j + minDelta, res[j], flag[0], spd[j], flag[1], obs[j], flag[2]);
}
}
}
|
package ru.skarpushin.swingpm.modelprops.lists;
import javax.swing.ListModel;
import ru.skarpushin.swingpm.base.HasPropertyName;
import ru.skarpushin.swingpm.base.HasValidationErrorsListEx;
public interface ModelListPropertyAccessor<E> extends ListModel, HasPropertyName, HasValidationErrorsListEx {
E get(int idx);
int indexOf(E item);
}
|
/*
*******************************************************************************
* Copyright (c) 2017, STMicroelectronics
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of STMicroelectronics nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*******************************************************************************
*/
#ifndef _VARIANT_ARDUINO_STM32_
#define _VARIANT_ARDUINO_STM32_
/*----------------------------------------------------------------------------
* Headers
*----------------------------------------------------------------------------*/
#include "PeripheralPins.h"
#ifdef __cplusplus
extern "C"{
#endif // __cplusplus
/*----------------------------------------------------------------------------
* Pins
*----------------------------------------------------------------------------*/
extern const PinName digitalPin[];
// Left Side
#define PD10 0
#define PD11 1
#define PB15 2
#define PD9 3
#define PB12 4
#define PD8 5
#define PB14 6
#define PB11 7
#define PE8 8
#define PB13 9
#define PB10 10
#define PE7 11
#define PE14 12
#define PE15 13
#define PE12 14
#define PE13 15
#define PE11 16
#define PE10 17
#define PE9 18
#define PB1 19
#define PB2 20
#define PC5 21
#define PB0 22
#define PA7 23
#define PC4 24
#define PA6 25
#define PA5 26
#define PA3 27
#define PA4 28
#define PC3 29
#define PA0 30
#define PA2 31
#define PA1 32
#define PD13 33
#define PD14 34
#define PC0 35
#define PC1 36
#define PC2 37
// Right Side
#define PA12 38
#define PA11 39
#define PA10 40
#define PD12 41
#define PC9 42
#define PA9 43
#define PA8 44
#define PC10 45
#define PC11 46
#define PC12 47
#define PD0 48
#define PD1 49
#define PD2 50
#define PD3 51
#define PD4 52
#define PD5 53
#define PB5 54
#define PB4 55
#define PB7 56
#define PB6 57
#define PB9 58
#define PB8 59
#define PE1 60
#define PE0 61
#define PE2 62
#define PE6 63
#define PE3 64
#define PE5 65
#define PB3 66
#define PE4 67
#define PD6 68
#define PD7 69
#define PC7 70
#define PC8 71
#define PD15 72
#define PC6 73
#define PC13 74
#define PA15 75
// This must be a literal
#define NUM_DIGITAL_PINS 92
// This must be a literal with a value less than or equal to MAX_ANALOG_INPUTS
#define NUM_ANALOG_INPUTS 16
#define NUM_ANALOG_FIRST 76
// On-board LED pin number
#define LED_D1 PC13
#define LED_BUILTIN LED_D1
// On-board user button
#define BTN_KEY PA15
#define USER_BTN BTN_KEY
// Below SPI and I2C definitions already done in the core
// Could be redefined here if differs from the default one
// SPI Definitions
#define PIN_SPI_MOSI PB5
#define PIN_SPI_MISO PB4
#define PIN_SPI_SCK PB3
// I2C Definitions
#define PIN_WIRE_SDA PB9
#define PIN_WIRE_SCL PB8
// Timer Definitions
//Do not use timer used by PWM pins when possible. See PinMap_PWM in PeripheralPins.c
#define TIMER_TONE TIM6
// Do not use basic timer: OC is required
#define TIMER_SERVO TIM2 //TODO: advanced-control timers don't work
// UART Definitions
// Define here Serial instance number to map on Serial generic name
#define SERIAL_UART_INSTANCE 1 //ex: 2 for Serial2 (USART2)
// DEBUG_UART could be redefined to print on another instance than 'Serial'
//#define DEBUG_UART ((USART_TypeDef *) U(S)ARTX) // ex: USART3
// DEBUG_UART baudrate, default: 9600 if not defined
//#define DEBUG_UART_BAUDRATE x
// DEBUG_UART Tx pin name, default: the first one found in PinMap_UART_TX for DEBUG_UART
//#define DEBUG_PINNAME_TX PX_n // PinName used for TX
// Default pin used for 'Serial' instance (ex: ST-Link)
// Mandatory for Firmata
#define PIN_SERIAL_RX PA10
#define PIN_SERIAL_TX PA9
#ifdef __cplusplus
} // extern "C"
#endif
/*----------------------------------------------------------------------------
* Arduino objects - C++ only
*----------------------------------------------------------------------------*/
#ifdef __cplusplus
// These serial port names are intended to allow libraries and architecture-neutral
// sketches to automatically default to the correct port name for a particular type
// of use. For example, a GPS module would normally connect to SERIAL_PORT_HARDWARE_OPEN,
// the first hardware serial port whose RX/TX pins are not dedicated to another use.
//
// SERIAL_PORT_MONITOR Port which normally prints to the Arduino Serial Monitor
//
// SERIAL_PORT_USBVIRTUAL Port which is USB virtual serial
//
// SERIAL_PORT_LINUXBRIDGE Port which connects to a Linux system via Bridge library
//
// SERIAL_PORT_HARDWARE Hardware serial port, physical RX & TX pins.
//
// SERIAL_PORT_HARDWARE_OPEN Hardware serial ports which are open for use. Their RX & TX
// pins are NOT connected to anything by default.
#define SERIAL_PORT_MONITOR Serial
#define SERIAL_PORT_HARDWARE Serial1
#endif
#endif /* _VARIANT_ARDUINO_STM32_ */
|
'use strict';
class Piece {
constructor(x, y, r, reporter) {
this.state_ = false;
this.isAnimating_ = false;
this.r_ = r;
this.shape_ = new createjs.Shape();
this.shape_.graphics.beginFill("#FF0000").drawCircle(0, 0, r);
this.shape_.scaleX = 1;
this.shape_.scaleY = 1;
this.shape_.x = x;
this.shape_.y = y;
this.shape_.alpha = 0;
this.neighbors_ = [];
this.neighbor_indexes_ = [];
this.shape_.addEventListener('click', () => {
if (this.doClick()) {
reporter.onPlayerMove();
}
});
this.shape_.addEventListener('touchstart', () => {
if (this.doClick()) {
reporter.onPlayerMove();
}
});
}
doClick(animate = true) {
const canClick = !this.isAnimating && !this.neighbors_.some(n => n.isAnimating_);
if (canClick) {
this.toggle(animate);
this.neighbors_.forEach(n => {
n.toggle(animate);
});
}
return canClick;
}
disableInput() {
this.shape_.removeAllEventListeners('click');
this.shape_.removeAllEventListeners('touchstart');
}
toggle(animate = true) {
var scale_target = 0.5;
var duration = 500;
var ease = createjs.Ease.bounceOut;
if (!animate) {
this.shape_.scaleX = this.state_ ? 1 : scale_target;
this.shape_.scaleY = this.state_ ? 1 : scale_target;
this.state_ = !this.state_;
this.shape_.graphics.clear().beginFill(this.state_ ? "#000000" : "#FF0000").drawCircle(0, 0, this.r_);
return;
}
this.shape_.graphics.clear().beginFill(this.state_ ? "#FF0000" : "#000000").drawCircle(0, 0, this.r_);
if (this.state_) {
createjs.Tween.get(this.shape_, { loop: false })
.to({ scaleX: 1, scaleY: 1 }, duration, ease)
.call(() => this.isAnimating_ = false);
} else {
createjs.Tween.get(this.shape_, { loop: false })
.to({ scaleX: scale_target, scaleY: scale_target }, duration, ease)
.call(() => this.isAnimating_ = false);
}
this.isAnimating_ = true;
this.state_ = !this.state_;
}
animateInwards(index) {
const base_x = this.shape_.x
, base_y = this.shape_.y
, xs = (Math.random() * 500) + 500
, ys = (Math.random() * 500) + 500
, offset_x = (Math.random() > 0.5) ? -xs : xs
, offset_y = (Math.random() > 0.5) ? -ys : ys
, wait_time = index * 10;
createjs.Tween.get(this.shape_, { loop: false })
.call(() => this.isAnimating_ = true)
.to({ x: base_x + offset_x, y: base_y + offset_y }, 0, createjs.Ease.linear)
.wait(wait_time)
.call(() => this.shape_.alpha = 1)
.to({ x: base_x, y: base_y }, 500, createjs.Ease.sineOut)
.call(() => this.isAnimating_ = false);
}
}
const GameState = {
Start: 0,
Playing: 1,
Rackup: 2,
Rackin: 3,
}
class Game {
constructor() {
this.canvas_ = null;
this.stage_ = null;
this.start_text_ = null;
this.background_ = null;
this.pieces_ = [];
this.level_state_ = [];
this.board_size_ = 3;
this.required_moves_ = 2;
this.player_moves_ = 0;
this.game_state_ = GameState.Start;
this.menu_button_ = document.getElementById('menu_button');
this.back_button_ = document.getElementById('back_button');
this.reset_button_ = document.getElementById('reset_button');
this.info_button_ = document.getElementById('info_button');
this.start_button_ = document.getElementById('start_button');
this.start_button_group_ = document.getElementById('start_button_group');
}
serializeState() {
return this.pieces_.map(p => p.state_);
}
deserializeState(state) {
state.forEach((s, i) => {
if (s) {
this.pieces_[i].toggle(false);
}
});
}
updateInfo() {
const text = `LEVEL: ${this.required_moves_} - MOVES: ${this.player_moves_}`;
this.info_button_.innerHTML = text;
}
resetStage() {
let width, height;
try {
width = Windows.UI.ViewManagement.ApplicationView.getForCurrentView().visibleBounds.width;
height = Windows.UI.ViewManagement.ApplicationView.getForCurrentView().visibleBounds.height;
} catch (e) {
width = window.innerWidth;
height = window.innerHeight;
}
this.canvas_.width = width;
this.canvas_.height = height;
this.stage_.removeAllChildren();
this.stage_.setBounds(0, 0, width, height);
this.background_ = new createjs.Shape();
this.background_.graphics.beginLinearGradientFill(['#C9C9C9', '#FFFFFF'], [0, 1], 0, 0, 0, height);
this.background_.graphics.drawRect(0, 0, width, height);
this.background_.x = 0;
this.background_.y = 0;
this.background_.alpha = 0;
this.stage_.addChild(this.background_);
}
resetGame() {
this.resetStage();
const width = this.canvas_.width;
const height = this.canvas_.height;
this.pieces_ = [];
const get_index = (x, y) => {
return (y * this.board_size_) + x;
}
this.player_moves_ = 0;
const minSpan = Math.min(width, height);
const maxSpan = Math.max(width, height);
const x_offset = maxSpan > width ? (maxSpan - width) / 2 : 0;
const y_offset = maxSpan > height ? (maxSpan - height) / 2 : 0;
const size = minSpan / (this.board_size_ + 1);
for (var y = 0; y < this.board_size_; ++y) {
for (var x = 0; x < this.board_size_; ++x) {
const xpos = size + (size * x) + y_offset;
const ypos = size + (size * y) + x_offset;
const piece = new Piece(xpos, ypos, (size / 2) * 0.9, this);
// determine the neighbor indexes
const neighbors = [];
if (x - 1 >= 0) neighbors.push(get_index(x - 1, y));
if (x + 1 <= (this.board_size_ - 1)) neighbors.push(get_index(x + 1, y));
if (y - 1 >= 0) neighbors.push(get_index(x, y - 1));
if (y + 1 <= (this.board_size_ - 1)) neighbors.push(get_index(x, y + 1));
piece.neighbor_indexes_ = neighbors;
this.stage_.addChild(piece.shape_);
this.pieces_.push(piece);
}
}
this.pieces_.forEach(piece => {
piece.neighbors_ = piece.neighbor_indexes_.map(i => this.pieces_[i]);
});
}
onPlayerMove() {
this.player_moves_ += 1;
this.updateInfo();
}
shufflePieces() {
var num_moves = this.required_moves_;
this.level_state_ = [];
var i = Math.floor(Math.random() * this.pieces_.length);
do {
this.level_state_.push(i);
const s = new Set(this.level_state_.slice(-3));
while (s.has(i)) {
i = this.pieces_[i].neighbor_indexes_[Math.floor(Math.random() * this.pieces_[i].neighbor_indexes_.length)];
}
} while (--num_moves);
if (this.pieces_.length) {
this.level_state_.forEach(i => {
this.pieces_[i].doClick(false);
});
}
}
animatePiecesInwards() {
this.pieces_.forEach((piece, index) => {
piece.animateInwards(index);
});
}
forceShowPieces() {
this.pieces_.forEach(p => p.shape_.alpha = 1);
}
createStartScreen() {
this.resetStage();
this.createLogo();
}
createLogo() {
const info = JSON.parse(lginfo);
const radius = this.canvas_.width / 150;
const x_offset = (this.canvas_.width / 2) - (info.width * (radius / 2));
const y_offset = (this.canvas_.height / 3) - (info.height * (radius / 2));
info.points.forEach(p => {
const shape = new createjs.Shape();
shape.graphics.beginFill('#000').drawCircle(0, 0, radius * p.scale);
shape.setTransform(x_offset + (p.x * radius), y_offset + (p.y * radius));
const wait_ms = ((p.x * 50) + (p.y * 50)) / 1;
createjs.Tween.get(shape)
.wait(wait_ms).play(
createjs.Tween.get(shape, { paused: true, loop: true })
.to({ scaleX: 0.2, scaleY: 0.2 }, 500, createjs.Ease.sineIn)
.to({ scaleX: 1, scaleY: 1 }, 500, createjs.Ease.sineOut)
);
this.stage_.addChild(shape);
});
}
createLogoGenerate() {
const text = new createjs.Text('circles', '40px Arial', '#000000');
const metrics = text.getMetrics();
const radius = this.canvas_.width / 150;
const offsets = [
[0, -1], [0, 1], [-1, 0], [1, 0]
];
const x_offset = (this.canvas_.width / 2) - (metrics.width * (radius / 2));
const y_offset = (this.canvas_.height / 3) - (metrics.height * (radius / 2));
const info = {
width: metrics.width,
height: metrics.height,
points: []
}
for (var y = 0; y < metrics.height; y += 2) {
for (var x = 0; x < metrics.width; x += 2) {
var total = 0;
offsets.forEach(offset => {
total += text.hitTest(x + offset[0], y + offset[1]);
});
const scale = total / 4;
if (scale > 0) {
info.points.push({x, y, scale});
const shape = new createjs.Shape();
shape.graphics.beginFill('#000').drawCircle(0, 0, radius * scale);
shape.setTransform(x_offset + (x * radius), y_offset + (y * radius));
const wait_ms = ((x * 50) + (y * 50)) / 1;
createjs.Tween.get(shape)
.wait(wait_ms).play(
createjs.Tween.get(shape, { paused: true, loop: true })
.to({ scaleX: 0.2, scaleY: 0.2 }, 500, createjs.Ease.sineIn)
.to({ scaleX: 1, scaleY: 1 }, 500, createjs.Ease.sineOut)
);
this.stage_.addChild(shape);
}
}
}
//console.log(JSON.stringify(info));
}
createRackupScreen() {
const span = Math.max(this.canvas_.width, this.canvas_.height) / 2;
let circle = new createjs.Shape();
circle.graphics.beginFill("#FF0000").drawCircle(0, 0, span);
circle.scaleX = 0;
circle.scaleY = 0;
circle.x = this.canvas_.width / 2;
circle.y = this.canvas_.height / 2;
const scale_target = 1.5;
const duration = 1000;
this.stage_.addChildAt(circle, 1);
createjs.Tween.get(circle, { loop: false })
.to({ scaleX: scale_target, scaleY: scale_target }, duration, createjs.Ease.linear)
.call(() => this.pieces_.forEach(p => this.stage_.removeChild(p.shape_)))
.to({ scaleX: 0, scaleY: 0 }, duration, createjs.Ease.linear)
.call(() => this.startGame());
this.menu_button_.setAttribute('style', 'display: none');
this.info_button_.setAttribute('style', 'display: none');
}
startGame() {
this.game_state_ = GameState.Playing;
this.resetGame();
this.shufflePieces();
this.animatePiecesInwards();
this.menu_button_.setAttribute('style', 'display: block');
this.info_button_.setAttribute('style', 'display: block');
this.start_button_group_.setAttribute('style', 'display: none');
this.updateInfo();
}
resetLevel() {
this.resetGame();
if (this.pieces_.length) {
this.level_state_.forEach(i => {
this.pieces_[i].doClick(false);
});
}
this.animatePiecesInwards();
}
enterStartState() {
this.game_state_ = GameState.Start;
this.board_size_ = 3;
this.createStartScreen();
this.menu_button_.setAttribute('style', 'display: none');
this.info_button_.setAttribute('style', 'display: none');
this.start_button_group_.setAttribute('style', '');
}
init() {
this.canvas_ = document.getElementById('mainCanvas');
this.stage_ = new createjs.Stage('mainCanvas');
this.stage_.enableMouseOver(10);
this.board_size_ = 3;
this.player_moves_ = 0;
createjs.Ticker.interval = 16;
createjs.Ticker.addEventListener('tick', event => {
this.tick(event);
});
document.onkeydown = event => {
if (event.key === 'q') {
this.enterStartState();
}
if (event.key === 'r') {
this.startGame();
}
if (event.key === 'u') {
this.adjustDifficulty(1);
this.startGame();
}
if (event.key === 'd') {
this.adjustDifficulty(-1);
this.startGame();
}
if (event.key === 'e') {
this.game_state_ = GameState.Rackup;
this.createRackupScreen();
}
if (event.key === 'i') {
this.game_state_ = GameState.Rackin;
this.createRackinScreen();
}
}
window.addEventListener('resize', () => {
if (this.game_state_ === GameState.Playing) {
const state = this.serializeState();
this.resetGame();
this.deserializeState(state);
this.forceShowPieces();
} else if (this.game_state_ === GameState.Start) {
this.createStartScreen();
}
});
this.back_button_.onclick = e => {
this.enterStartState();
}
this.start_button_.onclick = e => {
const offset = parseInt(e.target.getAttribute('data-level-offset'));
this.required_moves_ = offset;
this.adjustDifficulty(0);
this.startGame();
}
this.reset_button_.onclick = e => {
this.resetLevel();
}
const option_buttons = document.getElementsByClassName('start-option');
for (let i = 0; i < option_buttons.length; i++) {
const button = option_buttons[i];
button.onclick = e => {
const attr = 'data-level-offset';
this.start_button_.setAttribute(attr, e.target.getAttribute(attr));
this.start_button_.innerHTML = 'START GAME - ' + e.target.innerHTML.toUpperCase();
}
}
this.enterStartState();
}
tick(event) {
// check to see if the player has completed the puzzle
if (this.game_state_ === GameState.Playing) {
// the puzzle is solved if no pieces are moving or toggled
if (!this.pieces_.some(p => p.isAnimating_ || p.state_)) {
this.pieces_.forEach(p => p.disableInput());
this.game_state_ = GameState.Rackup;
this.adjustDifficulty(1);
this.createRackupScreen();
}
}
this.stage_.update(event);
}
adjustDifficulty(inc) {
this.required_moves_ += inc;
this.board_size_ = 3 + Math.floor(this.required_moves_ / 4);
}
}
const game = new Game();
game.init(); |
<filename>google/cloud/bigquery/v2/google-cloud-bigquery-v2-ruby/lib/google/cloud/bigquery/v2/model_services_pb.rb<gh_stars>1-10
# Generated by the protocol buffer compiler. DO NOT EDIT!
# Source: google/cloud/bigquery/v2/model.proto for package 'google.cloud.bigquery.v2'
# Original file comments:
# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'grpc'
require 'google/cloud/bigquery/v2/model_pb'
module Google
module Cloud
module Bigquery
module V2
module ModelService
class Service
include ::GRPC::GenericService
self.marshal_class_method = :encode
self.unmarshal_class_method = :decode
self.service_name = 'google.cloud.bigquery.v2.ModelService'
# Gets the specified model resource by model ID.
rpc :GetModel, ::Google::Cloud::Bigquery::V2::GetModelRequest, ::Google::Cloud::Bigquery::V2::Model
# Lists all models in the specified dataset. Requires the READER dataset
# role. After retrieving the list of models, you can get information about a
# particular model by calling the models.get method.
rpc :ListModels, ::Google::Cloud::Bigquery::V2::ListModelsRequest, ::Google::Cloud::Bigquery::V2::ListModelsResponse
# Patch specific fields in the specified model.
rpc :PatchModel, ::Google::Cloud::Bigquery::V2::PatchModelRequest, ::Google::Cloud::Bigquery::V2::Model
# Deletes the model specified by modelId from the dataset.
rpc :DeleteModel, ::Google::Cloud::Bigquery::V2::DeleteModelRequest, ::Google::Protobuf::Empty
end
Stub = Service.rpc_stub_class
end
end
end
end
end
|
'use strict';
const fs = require('fs');
const rs = fs.createReadStream('example.txt', 'utf8');
rs.on('open', () => {
console.log('Stream is opened!');
});
rs.on('data', chunk => {
console.log('----------------------chunk start----------------------');
console.log(chunk);
console.log('----------------------chunk end------------------------');
});
rs.on('close', () => {
console.log('Stream is closed!');
});
|
/**
* 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.jena.fuseki.server;
import static org.apache.jena.fuseki.server.DatasetStatus.CLOSING ;
import static org.apache.jena.fuseki.server.DatasetStatus.UNINITIALIZED ;
import java.util.* ;
import java.util.concurrent.atomic.AtomicBoolean ;
import java.util.concurrent.atomic.AtomicLong ;
import org.apache.jena.ext.com.google.common.collect.ArrayListMultimap;
import org.apache.jena.ext.com.google.common.collect.ListMultimap;
import org.apache.jena.fuseki.DEF ;
import org.apache.jena.fuseki.Fuseki ;
import org.apache.jena.query.ReadWrite ;
import org.apache.jena.sparql.core.DatasetGraph ;
import org.apache.jena.sparql.core.DatasetGraphFactory ;
import org.apache.jena.sparql.core.DatasetGraphReadOnly ;
import org.apache.jena.tdb.StoreConnection ;
import org.apache.jena.tdb.transaction.DatasetGraphTransaction ;
public class DataService { //implements DatasetMXBean {
public static DataService serviceOnlyDataService() {
return dummy ;
}
public static DataService dummy = new DataService(null) ;
static {
dummy.dataset = new DatasetGraphReadOnly(DatasetGraphFactory.createMemFixed()) ;
dummy.addEndpoint(OperationName.Query, DEF.ServiceQuery) ;
dummy.addEndpoint(OperationName.Query, DEF.ServiceQueryAlt) ;
}
private DatasetGraph dataset = null ; // Only valid if active.
private ListMultimap<OperationName, Endpoint> operations = ArrayListMultimap.create() ;
private Map<String, Endpoint> endpoints = new HashMap<>() ;
private volatile DatasetStatus state = UNINITIALIZED ;
// DataService-level counters.
private final CounterSet counters = new CounterSet() ;
private final AtomicLong requestCounter = new AtomicLong(0) ;
private final AtomicBoolean offlineInProgress = new AtomicBoolean(false) ;
private final AtomicBoolean acceptingRequests = new AtomicBoolean(true) ;
public DataService(DatasetGraph dataset) {
this.dataset = dataset ;
counters.add(CounterName.Requests) ;
counters.add(CounterName.RequestsGood) ;
counters.add(CounterName.RequestsBad) ;
}
public DatasetGraph getDataset() {
return dataset ;
}
public void addEndpoint(OperationName operationName, String endpointName) {
Endpoint endpoint = new Endpoint(operationName, endpointName) ;
endpoints.put(endpointName, endpoint) ;
operations.put(operationName, endpoint);
}
public Endpoint getOperation(String endpointName) {
return endpoints.get(endpointName) ;
}
public List<Endpoint> getOperation(OperationName opName) {
List<Endpoint> x = operations.get(opName) ;
if ( x == null )
x = Collections.emptyList() ;
return x ;
}
/** Return the OperationNames available here.
* @see #getOperation(OperationName) to get the endpoint list
*/
public Collection<OperationName> getOperations() {
return operations.keySet() ;
}
//@Override
public boolean allowUpdate() { return true ; }
public void goOffline() {
offlineInProgress.set(true) ;
acceptingRequests.set(false) ;
state = DatasetStatus.OFFLINE ;
}
public void goActive() {
offlineInProgress.set(false) ;
acceptingRequests.set(true) ;
state = DatasetStatus.ACTIVE ;
}
public boolean isAcceptingRequests() {
return acceptingRequests.get() ;
}
//@Override
public CounterSet getCounters() { return counters ; }
//@Override
public long getRequests() {
return counters.value(CounterName.Requests) ;
}
//@Override
public long getRequestsGood() {
return counters.value(CounterName.RequestsGood) ;
}
//@Override
public long getRequestsBad() {
return counters.value(CounterName.RequestsBad) ;
}
/** Counter of active read transactions */
public AtomicLong activeReadTxn = new AtomicLong(0) ;
/** Counter of active write transactions */
public AtomicLong activeWriteTxn = new AtomicLong(0) ;
/** Cumulative counter of read transactions */
public AtomicLong totalReadTxn = new AtomicLong(0) ;
/** Cumulative counter of writer transactions */
public AtomicLong totalWriteTxn = new AtomicLong(0) ;
public void startTxn(ReadWrite mode)
{
switch(mode)
{
case READ:
activeReadTxn.getAndIncrement() ;
totalReadTxn.getAndIncrement() ;
break ;
case WRITE:
activeWriteTxn.getAndIncrement() ;
totalWriteTxn.getAndIncrement() ;
break ;
}
}
public void finishTxn(ReadWrite mode)
{
switch(mode)
{
case READ:
activeReadTxn.decrementAndGet() ;
break ;
case WRITE:
activeWriteTxn.decrementAndGet() ;
break ;
}
checkShutdown() ;
}
private void checkShutdown() {
if ( state == CLOSING ) {
if ( activeReadTxn.get() == 0 && activeWriteTxn.get() == 0 )
shutdown() ;
}
}
private void shutdown() {
Fuseki.serverLog.info("Shutting down dataset") ;
dataset.close() ;
if ( dataset instanceof DatasetGraphTransaction ) {
DatasetGraphTransaction dsgtxn = (DatasetGraphTransaction)dataset ;
StoreConnection.release(dsgtxn.getLocation()) ;
}
dataset = null ;
}
}
|
<reponame>feserm/BioDWH2
package de.unibi.agbi.biodwh2.drugbank.model;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlText;
import java.util.regex.Pattern;
public final class DrugbankMetaboliteId {
private static final String[] PATTERN = {"DBMET[0-9]{5}"};
@JacksonXmlText
public String value;
@JacksonXmlProperty(isAttribute = true)
public boolean primary;
public boolean isValid() {
if (value != null)
for (String pattern : PATTERN)
if (isPatternValid(pattern))
return true;
return false;
}
private boolean isPatternValid(String pattern) {
Pattern p = Pattern.compile(pattern);
return p.matcher(value).matches();
}
}
|
<gh_stars>1-10
export default {
getCommon: state => {
return state.common || {};
}
};
|
#include "matrixGenerator.h"
#include "matrixMultiplier.h"
#include <iostream>
using namespace std;
void printMatrix(matrix* matrix);
void assertEqual(matrix& a, matrix& b);
int main()
{
matrixGenerator generator;
auto matricies = generator.generateMatricies();
matrixMultiplier multiplier;
auto multipliedOptimally = multiplier.multiplyOptimally(*matricies);
auto multipliedOrdinary = multiplier.miltiplyOrdinary(*matricies);
assertEqual(*multipliedOptimally, *multipliedOrdinary);
return 0;
}
void assertEqual(matrix& a, matrix& b)
{
if (&a == &b)
return;
if (a.size() != b.size() || a[0].size() != b[0].size())
throw exception("matricies not equal");
for (auto i = 0; i < a.size(); i++)
{
for (auto j = 0; j < a[0].size(); j++)
{
if (a[i][j] != b[i][j])
throw exception("matricies not equal");
}
}
}
void printMatrix(matrix* matrix)
{
cout << "Dimensions: " << matrix->size() << " x " << (*matrix)[0].size() << endl;
for (auto i = 0; i < matrix->size(); i++)
{
auto row = (*matrix)[i];
for (auto j = 0; j < row.size(); j++)
{
cout << row[j] << " ";
}
cout << endl;
}
} |
import os
def calculate_sum_of_integers_in_var():
try:
var_value = os.environ["VAR"]
integers = [int(x) for x in var_value.split(",")]
sum_of_integers = sum(integers)
print("The sum of integers in VAR is:", sum_of_integers)
except KeyError:
print("Error: The environment variable 'VAR' is not set.")
except ValueError:
print("Error: The value of 'VAR' is not in the correct format. It should be a sequence of comma-separated integers.")
calculate_sum_of_integers_in_var() |
#!/usr/bin/env zsh
function omz {
[[ $# -gt 0 ]] || {
_omz::help
return 1
}
local command="$1"
shift
# Subcommand functions start with _ so that they don't
# appear as completion entries when looking for `omz`
(( $+functions[_omz::$command] )) || {
_omz::help
return 1
}
_omz::$command "$@"
}
function _omz {
local -a cmds subcmds
cmds=(
'changelog:Print the changelog'
'help:Usage information'
'plugin:Manage plugins'
'pr:Manage Oh My Zsh Pull Requests'
'theme:Manage themes'
'update:Update Oh My Zsh'
)
if (( CURRENT == 2 )); then
_describe 'command' cmds
elif (( CURRENT == 3 )); then
case "$words[2]" in
changelog) local -a refs
refs=("${(@f)$(command git for-each-ref --format="%(refname:short):%(subject)" refs/heads refs/tags)}")
_describe 'command' refs ;;
plugin) subcmds=('list:List plugins')
_describe 'command' subcmds ;;
pr) subcmds=('test:Test a Pull Request' 'clean:Delete all Pull Request branches')
_describe 'command' subcmds ;;
theme) subcmds=('use:Load a theme' 'list:List themes')
_describe 'command' subcmds ;;
esac
elif (( CURRENT == 4 )); then
case "$words[2]::$words[3]" in
theme::use) compadd "$ZSH"/themes/*.zsh-theme(.N:t:r) \
"$ZSH_CUSTOM"/**/*.zsh-theme(.N:r:gs:"$ZSH_CUSTOM"/themes/:::gs:"$ZSH_CUSTOM"/:::) ;;
esac
fi
return 0
}
compdef _omz omz
## Utility functions
function _omz::confirm {
# If question supplied, ask it before reading the answer
# NOTE: uses the logname of the caller function
if [[ -n "$1" ]]; then
_omz::log prompt "$1" "${${functrace[1]#_}%:*}"
fi
# Read one character
read -r -k 1
# If no newline entered, add a newline
if [[ "$REPLY" != $'\n' ]]; then
echo
fi
}
function _omz::log {
# if promptsubst is set, a message with `` or $()
# will be run even if quoted due to `print -P`
setopt localoptions nopromptsubst
# $1 = info|warn|error|debug
# $2 = text
# $3 = (optional) name of the logger
local logtype=$1
local logname=${3:-${${functrace[1]#_}%:*}}
# Don't print anything if debug is not active
if [[ $logtype = debug && -z $_OMZ_DEBUG ]]; then
return
fi
# Choose coloring based on log type
case "$logtype" in
prompt) print -Pn "%S%F{blue}$logname%f%s: $2" ;;
debug) print -P "%F{white}$logname%f: $2" ;;
info) print -P "%F{green}$logname%f: $2" ;;
warn) print -P "%S%F{yellow}$logname%f%s: $2" ;;
error) print -P "%S%F{red}$logname%f%s: $2" ;;
esac >&2
}
## User-facing commands
function _omz::help {
cat <<EOF
Usage: omz <command> [options]
Available commands:
help Print this help message
changelog Print the changelog
plugin <command> Manage plugins
pr <command> Manage Oh My Zsh Pull Requests
theme <command> Manage themes
update Update Oh My Zsh
EOF
}
function _omz::changelog {
local version=${1:-HEAD} format=${3:-"--text"}
if ! command git -C "$ZSH" show-ref --verify refs/heads/$version &>/dev/null && \
! command git -C "$ZSH" show-ref --verify refs/tags/$version &>/dev/null && \
! command git -C "$ZSH" rev-parse --verify "${version}^{commit}" &>/dev/null; then
cat <<EOF
Usage: omz changelog [version]
NOTE: <version> must be a valid branch, tag or commit.
EOF
return 1
fi
"$ZSH/tools/changelog.sh" "$version" "${2:-}" "$format"
}
function _omz::plugin {
(( $# > 0 && $+functions[_omz::plugin::$1] )) || {
cat <<EOF
Usage: omz plugin <command> [options]
Available commands:
list List all available Oh My Zsh plugins
EOF
return 1
}
local command="$1"
shift
_omz::plugin::$command "$@"
}
function _omz::plugin::list {
local -a custom_plugins builtin_plugins
custom_plugins=("$ZSH_CUSTOM"/plugins/*(-/N:t))
builtin_plugins=("$ZSH"/plugins/*(-/N:t))
# If the command is being piped, print all found line by line
if [[ ! -t 1 ]]; then
print -l ${(q-)custom_plugins} ${(q-)builtin_plugins}
return
fi
if (( ${#custom_plugins} )); then
print -P "%U%BCustom plugins%b%u:"
print -l ${(q-)custom_plugins} | column
fi
if (( ${#builtin_plugins} )); then
(( ${#custom_plugins} )) && echo # add a line of separation
print -P "%U%BBuilt-in plugins%b%u:"
print -l ${(q-)builtin_plugins} | column
fi
}
function _omz::pr {
(( $# > 0 && $+functions[_omz::pr::$1] )) || {
cat <<EOF
Usage: omz pr <command> [options]
Available commands:
clean Delete all PR branches (ohmyzsh/pull-*)
test <PR_number_or_URL> Fetch PR #NUMBER and rebase against master
EOF
return 1
}
local command="$1"
shift
_omz::pr::$command "$@"
}
function _omz::pr::clean {
(
set -e
builtin cd -q "$ZSH"
# Check if there are PR branches
local fmt branches
fmt="%(color:bold blue)%(align:18,right)%(refname:short)%(end)%(color:reset) %(color:dim bold red)%(objectname:short)%(color:reset) %(color:yellow)%(contents:subject)"
branches="$(command git for-each-ref --sort=-committerdate --color --format="$fmt" "refs/heads/ohmyzsh/pull-*")"
# Exit if there are no PR branches
if [[ -z "$branches" ]]; then
_omz::log info "there are no Pull Request branches to remove."
return
fi
# Print found PR branches
echo "$branches\n"
# Confirm before removing the branches
_omz::confirm "do you want remove these Pull Request branches? [Y/n] "
# Only proceed if the answer is a valid yes option
[[ "$REPLY" != [yY$'\n'] ]] && return
_omz::log info "removing all Oh My Zsh Pull Request branches..."
command git branch --list 'ohmyzsh/pull-*' | while read branch; do
command git branch -D "$branch"
done
)
}
function _omz::pr::test {
# Allow $1 to be a URL to the pull request
if [[ "$1" = https://* ]]; then
1="${1:t}"
fi
# Check the input
if ! [[ -n "$1" && "$1" =~ ^[[:digit:]]+$ ]]; then
echo >&2 "Usage: omz pr test <PR_NUMBER_or_URL>"
return 1
fi
# Save current git HEAD
local branch
branch=$(builtin cd -q "$ZSH"; git symbolic-ref --short HEAD) || {
_omz::log error "error when getting the current git branch. Aborting..."
return 1
}
# Fetch PR onto ohmyzsh/pull-<PR_NUMBER> branch and rebase against master
# If any of these operations fail, undo the changes made
(
set -e
builtin cd -q "$ZSH"
# Get the ohmyzsh git remote
command git remote -v | while read remote url _; do
case "$url" in
https://github.com/ohmyzsh/ohmyzsh(|.git)) found=1; break ;;
git@github.com:ohmyzsh/ohmyzsh(|.git)) found=1; break ;;
esac
done
(( $found )) || {
_omz::log error "could not found the ohmyzsh git remote. Aborting..."
return 1
}
# Fetch pull request head
_omz::log info "fetching PR #$1 to ohmyzsh/pull-$1..."
command git fetch -f "$remote" refs/pull/$1/head:ohmyzsh/pull-$1 || {
_omz::log error "error when trying to fetch PR #$1."
return 1
}
# Rebase pull request branch against the current master
_omz::log info "rebasing PR #$1..."
command git rebase master ohmyzsh/pull-$1 || {
command git rebase --abort &>/dev/null
_omz::log warn "could not rebase PR #$1 on top of master."
_omz::log warn "you might not see the latest stable changes."
_omz::log info "run \`zsh\` to test the changes."
return 1
}
_omz::log info "fetch of PR #${1} successful."
)
# If there was an error, abort running zsh to test the PR
[[ $? -eq 0 ]] || return 1
# Run zsh to test the changes
_omz::log info "running \`zsh\` to test the changes. Run \`exit\` to go back."
command zsh -l
# After testing, go back to the previous HEAD if the user wants
_omz::confirm "do you want to go back to the previous branch? [Y/n] "
# Only proceed if the answer is a valid yes option
[[ "$REPLY" != [yY$'\n'] ]] && return
(
set -e
builtin cd -q "$ZSH"
command git checkout "$branch" -- || {
_omz::log error "could not go back to the previous branch ('$branch')."
return 1
}
)
}
function _omz::theme {
(( $# > 0 && $+functions[_omz::theme::$1] )) || {
cat <<EOF
Usage: omz theme <command> [options]
Available commands:
list List all available Oh My Zsh themes
use <theme> Load an Oh My Zsh theme
EOF
return 1
}
local command="$1"
shift
_omz::theme::$command "$@"
}
function _omz::theme::list {
local -a custom_themes builtin_themes
custom_themes=("$ZSH_CUSTOM"/**/*.zsh-theme(.N:r:gs:"$ZSH_CUSTOM"/themes/:::gs:"$ZSH_CUSTOM"/:::))
builtin_themes=("$ZSH"/themes/*.zsh-theme(.N:t:r))
# If the command is being piped, print all found line by line
if [[ ! -t 1 ]]; then
print -l ${(q-)custom_themes} ${(q-)builtin_themes}
return
fi
if (( ${#custom_themes} )); then
print -P "%U%BCustom themes%b%u:"
print -l ${(q-)custom_themes} | column
fi
if (( ${#builtin_themes} )); then
(( ${#custom_themes} )) && echo # add a line of separation
print -P "%U%BBuilt-in themes%b%u:"
print -l ${(q-)builtin_themes} | column
fi
}
function _omz::theme::use {
if [[ -z "$1" ]]; then
echo >&2 "Usage: omz theme use <theme>"
return 1
fi
# Respect compatibility with old lookup order
if [[ -f "$ZSH_CUSTOM/$1.zsh-theme" ]]; then
source "$ZSH_CUSTOM/$1.zsh-theme"
elif [[ -f "$ZSH_CUSTOM/themes/$1.zsh-theme" ]]; then
source "$ZSH_CUSTOM/themes/$1.zsh-theme"
elif [[ -f "$ZSH/themes/$1.zsh-theme" ]]; then
source "$ZSH/themes/$1.zsh-theme"
else
_omz::log error "theme '$1' not found"
return 1
fi
}
function _omz::update {
# Run update script
env ZSH="$ZSH" zsh -f "$ZSH/tools/upgrade.sh"
local ret=$?
# Update last updated file
zmodload zsh/datetime
echo "LAST_EPOCH=$(( EPOCHSECONDS / 60 / 60 / 24 ))" >! "${ZSH_CACHE_DIR}/.zsh-update"
# Remove update lock if it exists
command rm -rf "$ZSH/log/update.lock"
# Restart the zsh session
if [[ $ret -eq 0 && "$1" != --unattended ]]; then
# Check whether to run a login shell
[[ "$ZSH_ARGZERO" = -* ]] && exec -l "${ZSH_ARGZERO#-}" || exec "$ZSH_ARGZERO"
fi
}
|
from django.http import HttpResponse, Http404
from django.db.models import get_model
from django.contrib.contenttypes.models import ContentType
from tagging.models import Tag
def autocomplete(request, app_label, model):
try:
model = ContentType.objects.get(app_label=app_label, model=model)
except:
raise Http404
if not request.GET.has_key("q"):
raise Http404
else:
q = request.GET["q"]
limit = request.GET.get("limit", None)
tags = Tag.objects.filter(
items__content_type = model,
name__istartswith = q
).distinct().order_by("name")[:limit]
tag_list = "\n".join([tag.name for tag in tags if tag])
return HttpResponse(tag_list)
|
/*
* 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 com.alipay.sofa.ark.plugin.mojo;
import java.util.*;
/**
* @author qilong.zql
* @since 0.1.0
*/
public class LinkedProperties extends Properties {
private static final long serialVersionUID = 1L;
private LinkedHashMap<Object, Object> linkedHashMap = new LinkedHashMap<>(20);
@Override
public synchronized Object put(Object key, Object value) {
linkedHashMap.put(key, value);
return super.put(key, value);
}
@Override
public synchronized Object remove(Object key) {
linkedHashMap.remove(key);
return super.remove(key);
}
@Override
public synchronized Enumeration<Object> keys() {
return Collections.enumeration(linkedHashMap.keySet());
}
@Override
public Set<Map.Entry<Object, Object>> entrySet() {
return linkedHashMap.entrySet();
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.