text stringlengths 1 1.05M |
|---|
require 'active_support/core_ext/hash/indifferent_access'
require 'active_support/json'
require 'aws-sdk-resources'
require 'shoryuken'
require 'ehonda/version'
require 'ehonda/logging'
require 'ehonda/configuration'
require 'ehonda/railtie' if defined? Rails
module Ehonda
class << self
def configure
@config ||= Configuration.new
yield @config if block_given?
@config.validate! unless (ENV['RAILS_ENV'] || ENV['RACK_ENV']) == 'test'
end
def configuration
fail 'You must call Ehonda.configure before you can access any config.' unless @config
@config
end
def sns_client
::Aws::SNS::Client.new configuration.sns_options
end
def sqs_client
::Aws::SQS::Client.new configuration.sqs_options
end
end
end
|
#!/bin/bash -ex
set -xe
if [ "$(uname -m)" == "x86_64" ]; then
docker run --rm --privileged multiarch/qemu-user-static:register --reset
fi
export QEMU_STATIC_VERSION=v5.1.0-8
qemu_aarch64_sha256=58f25aa64f433225145226cc03a10b1177da8ece5c4a6b0fe38626c29093804a
qemu_arm_sha256=fa2d1f9794eac9c069b65d27b09ee0a12c82d2abac54434c531b9c8a497a611a
qemu_ppc64le_sha256=9f19aaf037a992dcfdb87eb8dafc03189d5b238398a2c2014e166c06a8586e4f
set +e
rm qemu-*-static
set -e
wget https://github.com/multiarch/qemu-user-static/releases/download/${QEMU_STATIC_VERSION}/qemu-aarch64-static
wget https://github.com/multiarch/qemu-user-static/releases/download/${QEMU_STATIC_VERSION}/qemu-arm-static
wget https://github.com/multiarch/qemu-user-static/releases/download/${QEMU_STATIC_VERSION}/qemu-ppc64le-static
sha256sum qemu-*-static
sha256sum qemu-aarch64-static | grep -F "${qemu_aarch64_sha256}"
sha256sum qemu-arm-static | grep -F "${qemu_arm_sha256}"
sha256sum qemu-ppc64le-static | grep -F "${qemu_ppc64le_sha256}"
chmod +x qemu-aarch64-static
chmod +x qemu-arm-static
chmod +x qemu-ppc64le-static
|
def fibonacci(n):
if n < 0:
print("Incorrect input")
# First Fibonacci number is 0
elif n == 0:
return 0
# Second Fibonacci number is 1
elif n == 1:
return 1
else:
return fibonacci(n-1) + fibonacci(n-2) |
import {
Entity,
PrimaryGeneratedColumn,
DeleteDateColumn,
CreateDateColumn,
Column,
UpdateDateColumn,
ManyToMany,
JoinTable
} from 'typeorm';
@Entity('book')
export class BookEntity {
@PrimaryGeneratedColumn('uuid') id: string;
@CreateDateColumn() datecreated: Date;
@UpdateDateColumn() dateupdated: Date;
@DeleteDateColumn() datedeleted: Date;
@Column('text') name: string;
@Column({
type: 'text',
nullable: true
})
imagepath: string;
@Column('text') description: string;
@Column('text') releasedate: string;
@Column({
type: 'text',
nullable: true
})
downloadlink: string;
@Column({
type: 'text',
nullable: true
})
downloadtext: string;
@Column({
type: 'text',
nullable: true
})
readlink: string;
@Column({
type: 'text',
nullable: true
})
readtext: string;
@Column('text') author: string;
@Column({
type: 'text',
nullable: true
})
publisher: string;
@Column({
type: 'decimal',
nullable: true
})
rating: number;
}
|
import merge from 'lodash.merge';
/** * Queries ** */
import {
schema as GetAllReactJSNews,
queries as GetAllReactJSNewsQueries,
resolvers as GetAllReactJSNewsResolver,
} from './reactjsnews.com/GetAllReactJSNews';
export const schema = [...GetAllReactJSNews];
export const queries = [...GetAllReactJSNewsQueries];
export const resolvers = merge(GetAllReactJSNewsResolver);
|
<filename>src/data/UserCtrlDB.java<gh_stars>0
package data;
import hibernate.HibernateUtil;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import datainterface.UserCtrl;
import domain.User;
public class UserCtrlDB implements UserCtrl {
private static UserCtrlDB instance;
public static UserCtrlDB getInstance() {
if (instance == null)
instance = new UserCtrlDB();
return instance;
}
public UserCtrlDB() {}
@Override
public User get(String username) throws Exception {
SessionFactory sf = HibernateUtil.getSessionFactory();
Session session = sf.openSession();
User res = (User) session.get(User.class, username);
session.close();
if(res == null)
throw new Exception("UserNoExist");
return res;
}
@Override
public Boolean exists(String username) {
SessionFactory sf = HibernateUtil.getSessionFactory();
Session session = sf.openSession();
User res = (User) session.get(User.class, username);
session.close();
return (res != null);
}
@Override
public List<User> all() {
SessionFactory sf = HibernateUtil.getSessionFactory();
Session session = sf.openSession();
List<User> res = (List<User>)session.createQuery("from User").list();
session.close();
return res;
}
}
|
#!/bin/sh
echo "Starting experiment"
echo "dstat: 0 containers"
dstat -m -t -o cont-0.csv 1 10
echo "dstat: 1 container"
docker run -d reproduction
pmap -X $(pidof ./a.out) > pmap1.txt
dstat -m -t -o cont-1.csv 1 10
echo "dstat: 2 containers"
docker rm -f $(docker ps -a -q)
docker run -d reproduction
docker run -d reproduction
pmap -X $(pidof ./a.out) > pmap2.txt
dstat -m -t -o cont-2.csv 1 10
echo "cleanup"
docker rm -f $(docker ps -a -q)
|
#!/usr/bin/env sh
# 确保脚本抛出遇到的错误
set -e
# 提交项目源码
git init
git add -A
git commit -m 'commit code'
# 发布到 https://<USERNAME>.github.io master
git push -f git@github.com:hengguao/hengguao.git master
# 生成静态文件
npm run docs:build
# 进入生成的文件夹
cd docs/.vuepress/dist
# 如果是发布到自定义域名
# echo 'www.example.com' > CNAME
git init
git add -A
git commit -m 'deploy docs'
# 发布到 https://<USERNAME>.github.io master:gh-pages
git push -f git@gitee.com:hengguao/hengguao.git master
cd - |
#!/bin/bash
pip install /app/uvicorn
rm -rf /app/uvicorn/.*
rm -rf /app/uvicorn/*
printf "ALLOWED_HOSTS=['*']" >> /app/example/example/settings.py
"$@"
|
#!/bin/bash
# 2021-11-22 - Install docker-ce [mostly] according to the docker instructions:
# https://docs.docker.com/engine/install/centos/
if [[ "$(id -u)" != "0" ]]; then
echo "ERROR: must run as root" >&2
echo "HINT: sudo $0"
exit 1
fi
dnf remove -y \
docker \
docker-client \
docker-client-latest \
docker-common \
docker-latest \
docker-latest-logrotate \
docker-logrotate \
docker-engine
dnf install -y yum-utils
yum-config-manager --add-repo \
https://download.docker.com/linux/centos/docker-ce.repo
dnf install -y docker-ce docker-ce-cli containerd.io
systemctl enable --now docker
usermod -a -G docker vagrant
cat <<- 'MESSAGE'
################################################################################
# #
# IMPORTANT: You must log out/in for the Linux group permissions to take #
# effect. Otherwise, you might not have access to the local Docker socket #
# to issue commands and recieve these types of errors: #
# #
# $ docker ps #
# Got permission denied while trying to connect to the Docker daemon #
# socket at unix:///var/run/docker.sock: Get #
# "http://%2Fvar%2Frun%2Fdocker.sock/v1.24/containers/json": dial unix #
# /var/run/docker.sock: connect: permission denied #
# #
################################################################################
MESSAGE
|
#!/bin/bash
# That Bash script extracts data from the
# 'por_schedule_all_uniq_YYYY_MM_to_YYYY_MM.csv.bz2'
# schedule-derived data file and derives a few other utility data files:
# * por_schedule_counts_YYYY_MM_to_YYYY_MM.csv:
# Number of weeks during which the POR have been present in schedules.
# * por_schedule_periods_YYYY_MM_to_YYYY_MM.csv:
# Number of weeks during which the POR have been present in schedules.
#
# The YYYY_MM represent the snapshot/generation dates of the schedule files,
# which have been analysed/crunched.
#
# Within the data files:
# * IATA code of the POR (point of reference, e.g., NCE for Nice)
# * The year, week number and the corresponding period,
# which correspond to the earliest and latest departure dates
# of the flight segments involving the corresponding POR.
#
##
# Temporary path
TMP_DIR="/tmp/por"
##
# Path of the executable: set it to empty when this is the current directory.
EXEC_PATH=`dirname $0`
# Trick to get the actual full-path
pushd ${EXEC_PATH} > /dev/null
EXEC_FULL_PATH=`popd`
popd > /dev/null
EXEC_FULL_PATH=`echo ${EXEC_FULL_PATH} | sed -e 's|~|'${HOME}'|'`
#
CURRENT_DIR=`pwd`
if [ ${CURRENT_DIR} -ef ${EXEC_PATH} ]
then
EXEC_PATH="."
TMP_DIR="."
fi
# If the Geonames dump file is in the current directory, then the current
# directory is certainly intended to be the temporary directory.
if [ -f ${GEO_RAW_FILENAME} ]
then
TMP_DIR="."
fi
EXEC_PATH="${EXEC_PATH}/"
TMP_DIR="${TMP_DIR}/"
if [ ! -d ${TMP_DIR} -o ! -w ${TMP_DIR} ]
then
\mkdir -p ${TMP_DIR}
fi
##
# Sanity check: that (executable) script should be located in the
# tools/ sub-directory of the OpenTravelData project Git clone
EXEC_DIR_NAME=`basename ${EXEC_FULL_PATH}`
if [ "${EXEC_DIR_NAME}" != "tools" ]
then
echo
echo "[$0:$LINENO] Inconsistency error: this script ($0) should be located in the refdata/tools/ sub-directory of the OpenTravelData project Git clone, but apparently is not. EXEC_FULL_PATH=\"${EXEC_FULL_PATH}\""
echo
exit -1
fi
##
# OpenTravelData directory
OPTD_DIR=`dirname ${EXEC_FULL_PATH}`
OPTD_DIR="${OPTD_DIR}/"
##
# OPTD sub-directories
DATA_DIR=${OPTD_DIR}opentraveldata/
TOOLS_DIR=${OPTD_DIR}tools/
##
# Log level
LOG_LEVEL=3
##
# Schedule-derived data files
POR_SKD_DIR=${DATA_DIR}por_in_schedule/
##
# MacOS 'date' vs GNU date
DATE_TOOL=date
if [ -f /usr/bin/sw_vers ]
then
DATE_TOOL=gdate
fi
##
# Snapshot date
SNAPSHOT_DATE=`$DATE_TOOL "+%Y%m%d"`
SNAPSHOT_DATE_HUMAN=`$DATE_TOOL`
##
# Retrieve the latest schedule-derived POR data files
POR_FILE_PFX1=por_schedule_all_uniq
POR_FILE_PFX2=por_schedule_counts
POR_FILE_PFX3=por_schedule_period_list
LATEST_EXTRACT_PRD=`ls ${POR_SKD_DIR}${POR_FILE_PFX1}_????_??_to_????_??.csv.bz2 2> /dev/null`
if [ "${LATEST_EXTRACT_PRD}" != "" ]
then
# (Trick to) Extract the latest entry
for myfile in ${LATEST_EXTRACT_PRD}; do echo > /dev/null; done
LATEST_EXTRACT_PRD=`echo ${myfile} | sed -e "s/${POR_FILE_PFX1}_\([0-9]\+\)_\([0-9]\+\)_to_\([0-9]\+\)_\([0-9]\+\)\.csv.bz2/\1_\2_to_\3_\4/" | xargs basename`
fi
if [ "${LATEST_EXTRACT_PRD}" != "" ]
then
LATEST_EXTRACT_PRD_BGN=`echo ${LATEST_EXTRACT_PRD} | sed -e "s/\([0-9]\+\)_\([0-9]\+\)_to_\([0-9]\+\)_\([0-9]\+\)/\1-\2-01/"`
LATEST_EXTRACT_PRD_BGN_HUMAN=`$DATE_TOOL -d ${LATEST_EXTRACT_PRD_BGN}`
LATEST_EXTRACT_PRD_END=`echo ${LATEST_EXTRACT_PRD} | sed -e "s/\([0-9]\+\)_\([0-9]\+\)_to_\([0-9]\+\)_\([0-9]\+\)/\3-\4-01/"`
LATEST_EXTRACT_PRD_END_HUMAN=`$DATE_TOOL -d ${LATEST_EXTRACT_PRD_END}`
fi
if [ "${LATEST_EXTRACT_PRD}" != "" \
-a "${LATEST_EXTRACT_PRD}" != "${SNAPSHOT_DATE}" ]
then
LATEST_DUMP_POR_SKD_ALL_FILENAME=${POR_FILE_PFX1}_${LATEST_EXTRACT_PRD}.csv.bz2
LATEST_DUMP_POR_SKD_CNT_FILENAME=${POR_FILE_PFX2}_${LATEST_EXTRACT_PRD}.csv
LATEST_DUMP_POR_SKD_PRD_FILENAME=${POR_FILE_PFX3}_${LATEST_EXTRACT_PRD}.csv
fi
LATEST_DUMP_POR_SKD_ALL_FILE=${POR_SKD_DIR}${LATEST_DUMP_POR_SKD_ALL_FILENAME}
LATEST_DUMP_POR_SKD_CNT_FILE=${POR_SKD_DIR}${LATEST_DUMP_POR_SKD_CNT_FILENAME}
LATEST_DUMP_POR_SKD_PRD_FILE=${POR_SKD_DIR}${LATEST_DUMP_POR_SKD_PRD_FILENAME}
##
# If the data file is not sorted, sort it
TMP_DUMP_POR_SKD_ALL=${TMP_DIR}${LATEST_DUMP_POR_SKD_ALL_FILENAME}.tmp
echo
echo "Check that the ${LATEST_DUMP_POR_SKD_ALL_FILENAME} file is sorted:"
echo "bzless ${LATEST_DUMP_POR_SKD_ALL_FILE}"
echo "If not sorted, sort it:"
echo "bzcat ${LATEST_DUMP_POR_SKD_ALL_FILE} | sort -t'^' -k1,1 -k4,4 -k5,5 | bzip2 > ${TMP_DUMP_POR_SKD_ALL} && mv -f ${TMP_DUMP_POR_SKD_ALL} ${LATEST_DUMP_POR_SKD_ALL_FILE}"
##
# Counting
echo
echo "Counting the number of occurences of the POR within the ${LATEST_DUMP_POR_SKD_ALL_FILE} file."
if [ ! -f "${LATEST_DUMP_POR_SKD_CNT_FILE}" ]
then
echo "Generating the ${LATEST_DUMP_POR_SKD_CNT_FILENAME} file..."
bzcat ${LATEST_DUMP_POR_SKD_ALL_FILE} | cut -d'^' -f1 | uniq -c | awk -F' ' '{print $2 "^" $1}' > ${LATEST_DUMP_POR_SKD_CNT_FILE}
echo "... done"
fi
echo "grep -e \"BER\" -e \"^NCE\" ${LATEST_DUMP_POR_SKD_CNT_FILE} =>"
grep -e "^BER" -e "^NCE" ${LATEST_DUMP_POR_SKD_CNT_FILE}
# Reporting
echo
echo "POR_SKD_DIR = ${POR_SKD_DIR}"
echo "LATEST_EXTRACT_PRD = ${LATEST_EXTRACT_PRD}"
echo "LATEST_EXTRACT_PRD_BGN = ${LATEST_EXTRACT_PRD_BGN_HUMAN}"
echo "LATEST_EXTRACT_PRD_END = ${LATEST_EXTRACT_PRD_END_HUMAN}"
echo "LATEST_DUMP_POR_SKD_ALL_FILE = ${LATEST_DUMP_POR_SKD_ALL_FILE}"
echo "LATEST_DUMP_POR_SKD_CNT_FILE = ${LATEST_DUMP_POR_SKD_CNT_FILE}"
echo "LATEST_DUMP_POR_SKD_PRD_FILE = ${LATEST_DUMP_POR_SKD_PRD_FILE}"
echo
|
<filename>pkg/parser/arguments_parser_test.go
package parser
import (
"github.com/jensneuse/graphql-go-tools/pkg/lexing/position"
"testing"
)
func TestParser_parseArgumentSet(t *testing.T) {
t.Run("string argument", func(t *testing.T) {
run(`(name: "Gophus")`,
mustParseArguments(
node(
hasName("name"),
hasPosition(position.Position{
LineStart: 1,
LineEnd: 1,
CharStart: 2,
CharEnd: 16,
}),
),
),
)
})
t.Run("multiple argument sets", func(t *testing.T) {
run(`(name: "Gophus")(name2: "Gophus")`,
mustParseArguments(
node(
hasName("name"),
),
),
mustParseArguments(
node(
hasName("name2"),
),
),
)
})
t.Run("multiple argument sets", func(t *testing.T) {
run(`(name: "Gophus")()`,
mustParseArguments(
node(
hasName("name"),
),
),
mustPanic(mustParseArguments(
node(
hasName("name2"),
),
)),
)
})
t.Run("string array argument", func(t *testing.T) {
run(`(fooBars: ["foo","bar"])`,
mustParseArguments(
node(
hasName("fooBars"),
),
),
)
})
t.Run("int array argument", func(t *testing.T) {
run(`(integers: [1,2,3])`,
mustParseArguments(
node(
hasName("integers"),
hasPosition(position.Position{
LineStart: 1,
LineEnd: 1,
CharStart: 2,
CharEnd: 19,
}),
),
),
)
})
t.Run("multiple string arguments", func(t *testing.T) {
run(`(name: "Gophus", surname: "Gophersson")`,
mustParseArguments(
node(
hasName("name"),
hasPosition(position.Position{
LineStart: 1,
LineEnd: 1,
CharStart: 2,
CharEnd: 16,
}),
),
node(
hasName("surname"),
hasPosition(position.Position{
LineStart: 1,
LineEnd: 1,
CharStart: 18,
CharEnd: 39,
}),
),
),
)
})
t.Run("invalid argument must err", func(t *testing.T) {
run(`(name: "Gophus", surname: "Gophersson"`,
mustPanic(mustParseArguments()))
})
t.Run("invalid argument must err 2", func(t *testing.T) {
run(`((name: "Gophus", surname: "Gophersson")`,
mustPanic(mustParseArguments()))
})
t.Run("invalid argument must err 3", func(t *testing.T) {
run(`(name: .)`,
mustPanic(mustParseArguments()))
})
}
|
/* eslint-env node, browser, jasmine */
const { makeFixture } = require('./__helpers__/FixtureFS.js')
const path = require('path')
const pify = require('pify')
const { plugins, statusMatrix, add, remove } = require('isomorphic-git')
describe('statusMatrix', () => {
it('statusMatrix', async () => {
// Setup
let { fs, dir, gitdir } = await makeFixture('test-statusMatrix')
plugins.set('fs', fs)
// Test
let matrix = await statusMatrix({ dir, gitdir })
expect(matrix).toEqual([
['a.txt', 1, 1, 1],
['b.txt', 1, 2, 1],
['c.txt', 1, 0, 1],
['d.txt', 0, 2, 0]
])
await add({ dir, gitdir, filepath: 'a.txt' })
await add({ dir, gitdir, filepath: 'b.txt' })
await remove({ dir, gitdir, filepath: 'c.txt' })
await add({ dir, gitdir, filepath: 'd.txt' })
matrix = await statusMatrix({ dir, gitdir })
expect(matrix).toEqual([
['a.txt', 1, 1, 1],
['b.txt', 1, 2, 2],
['c.txt', 1, 0, 0],
['d.txt', 0, 2, 2]
])
// And finally the weirdo cases
let acontent = await pify(fs.readFile)(path.join(dir, 'a.txt'))
await pify(fs.writeFile)(path.join(dir, 'a.txt'), 'Hi')
await add({ dir, gitdir, filepath: 'a.txt' })
await pify(fs.writeFile)(path.join(dir, 'a.txt'), acontent)
matrix = await statusMatrix({ dir, gitdir, pattern: 'a.txt' })
expect(matrix).toEqual([
['a.txt', 1, 1, 3]
])
await remove({ dir, gitdir, filepath: 'a.txt' })
matrix = await statusMatrix({ dir, gitdir, pattern: 'a.txt' })
expect(matrix).toEqual([
['a.txt', 1, 1, 0]
])
await pify(fs.writeFile)(path.join(dir, 'e.txt'), 'Hi')
await add({ dir, gitdir, filepath: 'e.txt' })
await pify(fs.unlink)(path.join(dir, 'e.txt'))
matrix = await statusMatrix({ dir, gitdir, pattern: 'e.txt' })
expect(matrix).toEqual([
['e.txt', 0, 0, 3]
])
})
})
|
#!/usr/bin/env sh
# generated from catkin/cmake/template/local_setup.sh.in
# since this file is sourced either use the provided _CATKIN_SETUP_DIR
# or fall back to the destination set at configure time
: ${_CATKIN_SETUP_DIR:=/home/shw/catkin_ws_legoloam/src/LeGO-LOAM/LeGO-LOAM/build/devel}
CATKIN_SETUP_UTIL_ARGS="--extend --local"
. "$_CATKIN_SETUP_DIR/setup.sh"
unset CATKIN_SETUP_UTIL_ARGS
|
require 'chewy/search/parameters/storage'
module Chewy
module Search
class Parameters
# Just a standard hash storage. Nothing to see here.
#
# @see Chewy::Search::Parameters::HashStorage
# @see Chewy::Search::Request#script_fields
# @see https://www.elastic.co/guide/en/elasticsearch/reference/5.4/search-request-script-fields.html
class ScriptFields < Storage
include HashStorage
end
end
end
end
|
<filename>VersionMonitorDeamon/src/com/cats/version/deamon/HttpDownloadFiles.java<gh_stars>0
/*
* Copyright 2015 lixiaobo
*
* VersionUpgrade project 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.cats.version.deamon;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.List;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import com.cats.version.msg.IMessageVersionUpdateRsp;
import com.cats.version.perference.UserPreference;
/**
* @author xblia2 Jun 11, 2015
*/
public class HttpDownloadFiles extends Thread
{
private static final int CACHE = 10 * 1024;
private static int iMaxTry = 3;
private IMessageVersionUpdateRsp updateRsp;
private IUpdateStatusListener statusListener;
private String lastError = "";
public HttpDownloadFiles(IMessageVersionUpdateRsp updateRsp, IUpdateStatusListener statusListener)
{
super();
this.updateRsp = updateRsp;
this.statusListener = statusListener;
}
@Override
public void run()
{
List<String> fileList = updateRsp.getUpdateFilePath();
String baseUrl = UserPreference.getInstance().getUrl();
if(fileList != null && !fileList.isEmpty())
{
for (int i = 0; i < fileList.size(); i++)
{
String fileFullName = fileList.get(i);
statusListener.notify(fileFullName, fileList.size(), i+1);
int iTry = 0;
boolean isDownSucc = false;
lastError = "";
while(!(isDownSucc = download(baseUrl + "/"+fileFullName, parseFileName(fileFullName))))
{
if(iTry >= iMaxTry)
{
break;
}
iTry++;
}
if(!isDownSucc)
{
statusListener.notifyException(lastError);
}
}
statusListener.notifyFinished();
}else
{
statusListener.notifyException("Not found upgrade file.");
}
}
private String parseFileName(String fileFullName)
{
File file = new File(fileFullName);
return file.getName();
}
public boolean download(String url, String fileName)
{
try
{
HttpClient client = HttpClients.createDefault();
HttpGet httpget = new HttpGet(url);
HttpResponse response = client.execute(httpget);
if(response.getStatusLine().getStatusCode() != 200)
{
lastError = "Error status code: " + response.getStatusLine().getStatusCode();
return false;
}
Header []headers = response.getHeaders("file_flag");
if(headers == null || headers.length == 0 || !headers[0].getValue().equals("yes"))
{
lastError = "parse httpdown response header fail";
return false;
}
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
File file = new File(System.getProperty("user.dir")
+ File.separator + fileName);
file.getParentFile().mkdirs();
FileOutputStream fileout = new FileOutputStream(file);
byte[] buffer = new byte[CACHE];
int iLen = 0;
while ((iLen = is.read(buffer)) != -1)
{
fileout.write(buffer, 0, iLen);
}
is.close();
fileout.flush();
fileout.close();
} catch (Exception e)
{
e.printStackTrace();
lastError = e.getMessage();
return false;
}
return true;
}
}
|
<reponame>wetherbeei/gopar<filename>src/github.com/tones111/go-opencl/cl/device.go
/*
* Copyright © 2012 go-opencl authors
*
* This file is part of go-opencl.
*
* go-opencl is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* go-opencl 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with go-opencl. If not, see <http://www.gnu.org/licenses/>.
*/
package cl
/*
#cgo CFLAGS: -I CL
#cgo LDFLAGS: -lOpenCL
#include "CL/opencl.h"
*/
import "C"
import (
"unsafe"
)
type DeviceType C.cl_device_type
const (
DEVICE_TYPE_DEFAULT DeviceType = C.CL_DEVICE_TYPE_DEFAULT
DEVICE_TYPE_CPU DeviceType = C.CL_DEVICE_TYPE_CPU
DEVICE_TYPE_GPU DeviceType = C.CL_DEVICE_TYPE_GPU
DEVICE_TYPE_ACCELERATOR DeviceType = C.CL_DEVICE_TYPE_ACCELERATOR
//DEVICE_TYPE_CUSTOM DeviceType = C.CL_DEVICE_TYPE_CUSTOM
DEVICE_TYPE_ALL DeviceType = C.CL_DEVICE_TYPE_ALL
)
func (t DeviceType) String() string {
mesg := deviceTypeMesg[t]
if mesg == "" {
return t.String()
}
return mesg
}
var deviceTypeMesg = map[DeviceType]string{
DEVICE_TYPE_CPU: "CPU",
DEVICE_TYPE_GPU: "GPU",
DEVICE_TYPE_ACCELERATOR: "Accelerator",
//DEVICE_TYPE_CUSTOM: "Custom",
}
type DeviceProperty C.cl_device_info
const (
DEVICE_ADDRESS_BITS DeviceProperty = C.CL_DEVICE_ADDRESS_BITS
DEVICE_AVAILABLE DeviceProperty = C.CL_DEVICE_AVAILABLE
//DEVICE_BUILT_IN_KERNELS DeviceProperty = C.CL_DEVICE_BUILT_IN_KERNELS
DEVICE_COMPILER_AVAILABLE DeviceProperty = C.CL_DEVICE_COMPILER_AVAILABLE
//DEVICE_DOUBLE_FP_CONFIG DeviceProperty = C.CL_DEVICE_DOUBLE_FP_CONFIG
DEVICE_ENDIAN_LITTLE DeviceProperty = C.CL_DEVICE_ENDIAN_LITTLE
DEVICE_ERROR_CORRECTION_SUPPORT DeviceProperty = C.CL_DEVICE_ERROR_CORRECTION_SUPPORT
DEVICE_EXECUTION_CAPABILITIES DeviceProperty = C.CL_DEVICE_EXECUTION_CAPABILITIES
DEVICE_EXTENSIONS DeviceProperty = C.CL_DEVICE_EXTENSIONS
DEVICE_GLOBAL_MEM_CACHE_SIZE DeviceProperty = C.CL_DEVICE_GLOBAL_MEM_CACHE_SIZE
DEVICE_GLOBAL_MEM_CACHE_TYPE DeviceProperty = C.CL_DEVICE_GLOBAL_MEM_CACHE_TYPE
DEVICE_GLOBAL_MEM_CACHELINE_SIZE DeviceProperty = C.CL_DEVICE_GLOBAL_MEM_CACHELINE_SIZE
DEVICE_GLOBAL_MEM_SIZE DeviceProperty = C.CL_DEVICE_GLOBAL_MEM_SIZE
//DEVICE_HALF_FP_CONFIG DeviceProperty = C.CL_DEVICE_HALF_FP_CONFIG
DEVICE_HOST_UNIFIED_MEMORY DeviceProperty = C.CL_DEVICE_HOST_UNIFIED_MEMORY
DEVICE_IMAGE_SUPPORT DeviceProperty = C.CL_DEVICE_IMAGE_SUPPORT
DEVICE_IMAGE2D_MAX_HEIGHT DeviceProperty = C.CL_DEVICE_IMAGE2D_MAX_HEIGHT
DEVICE_IMAGE2D_MAX_WIDTH DeviceProperty = C.CL_DEVICE_IMAGE2D_MAX_WIDTH
DEVICE_IMAGE3D_MAX_DEPTH DeviceProperty = C.CL_DEVICE_IMAGE3D_MAX_DEPTH
DEVICE_IMAGE3D_MAX_HEIGHT DeviceProperty = C.CL_DEVICE_IMAGE3D_MAX_HEIGHT
DEVICE_IMAGE3D_MAX_WIDTH DeviceProperty = C.CL_DEVICE_IMAGE3D_MAX_WIDTH
//DEVICE_IMAGE_MAX_BUFFER_SIZE DeviceProperty = C.CL_DEVICE_IMAGE_MAX_BUFFER_SIZE
//DEVICE_IMAGE_MAX_ARRAY_SIZE DeviceProperty = C.CL_DEVICE_IMAGE_MAX_ARRAY_SIZE
//DEVICE_LINKER_AVAILABLE DeviceProperty = C.CL_DEVICE_LINKER_AVAILABLE
DEVICE_LOCAL_MEM_SIZE DeviceProperty = C.CL_DEVICE_LOCAL_MEM_SIZE
DEVICE_LOCAL_MEM_TYPE DeviceProperty = C.CL_DEVICE_LOCAL_MEM_TYPE
DEVICE_MAX_CLOCK_FREQUENCY DeviceProperty = C.CL_DEVICE_MAX_CLOCK_FREQUENCY
DEVICE_MAX_COMPUTE_UNITS DeviceProperty = C.CL_DEVICE_MAX_COMPUTE_UNITS
DEVICE_MAX_CONSTANT_ARGS DeviceProperty = C.CL_DEVICE_MAX_CONSTANT_ARGS
DEVICE_MAX_CONSTANT_BUFFER_SIZE DeviceProperty = C.CL_DEVICE_MAX_CONSTANT_BUFFER_SIZE
DEVICE_MAX_MEM_ALLOC_SIZE DeviceProperty = C.CL_DEVICE_MAX_MEM_ALLOC_SIZE
DEVICE_MAX_PARAMETER_SIZE DeviceProperty = C.CL_DEVICE_MAX_PARAMETER_SIZE
DEVICE_MAX_READ_IMAGE_ARGS DeviceProperty = C.CL_DEVICE_MAX_READ_IMAGE_ARGS
DEVICE_MAX_SAMPLERS DeviceProperty = C.CL_DEVICE_MAX_SAMPLERS
DEVICE_MAX_WORK_GROUP_SIZE DeviceProperty = C.CL_DEVICE_MAX_WORK_GROUP_SIZE
DEVICE_MAX_WORK_ITEM_DIMENSIONS DeviceProperty = C.CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS
DEVICE_MAX_WORK_ITEM_SIZES DeviceProperty = C.CL_DEVICE_MAX_WORK_ITEM_SIZES
DEVICE_MAX_WRITE_IMAGE_ARGS DeviceProperty = C.CL_DEVICE_MAX_WRITE_IMAGE_ARGS
DEVICE_MEM_BASE_ADDR_ALIGN DeviceProperty = C.CL_DEVICE_MEM_BASE_ADDR_ALIGN
DEVICE_MIN_DATA_TYPE_ALIGN_SIZE DeviceProperty = C.CL_DEVICE_MIN_DATA_TYPE_ALIGN_SIZE
DEVICE_NAME DeviceProperty = C.CL_DEVICE_NAME
DEVICE_NATIVE_VECTOR_WIDTH_CHAR DeviceProperty = C.CL_DEVICE_NATIVE_VECTOR_WIDTH_CHAR
DEVICE_NATIVE_VECTOR_WIDTH_SHORT DeviceProperty = C.CL_DEVICE_NATIVE_VECTOR_WIDTH_SHORT
DEVICE_NATIVE_VECTOR_WIDTH_INT DeviceProperty = C.CL_DEVICE_NATIVE_VECTOR_WIDTH_INT
DEVICE_NATIVE_VECTOR_WIDTH_LONG DeviceProperty = C.CL_DEVICE_NATIVE_VECTOR_WIDTH_LONG
DEVICE_NATIVE_VECTOR_WIDTH_FLOAT DeviceProperty = C.CL_DEVICE_NATIVE_VECTOR_WIDTH_FLOAT
DEVICE_NATIVE_VECTOR_WIDTH_DOUBLE DeviceProperty = C.CL_DEVICE_NATIVE_VECTOR_WIDTH_DOUBLE
DEVICE_NATIVE_VECTOR_WIDTH_HALF DeviceProperty = C.CL_DEVICE_NATIVE_VECTOR_WIDTH_HALF
DEVICE_OPENCL_C_VERSION DeviceProperty = C.CL_DEVICE_OPENCL_C_VERSION
//DEVICE_PARENT_DEVICE DeviceProperty = C.CL_DEVICE_PARENT_DEVICE
//DEVICE_PARTITION_MAX_SUB_DEVICES DeviceProperty = C.CL_DEVICE_PARTITION_MAX_SUB_DEVICES
//DEVICE_PARTITION_PROPERTIES DeviceProperty = C.CL_DEVICE_PARTITION_PROPERTIES
//DEVICE_PARTITION_AFFINITY_DOMAIN DeviceProperty = C.CL_DEVICE_PARTITION_AFFINITY_DOMAIN
//DEVICE_PARTITION_TYPE DeviceProperty = C.CL_DEVICE_PARTITION_TYPE
DEVICE_PLATFORM DeviceProperty = C.CL_DEVICE_PLATFORM
DEVICE_PREFERRED_VECTOR_WIDTH_CHAR DeviceProperty = C.CL_DEVICE_PREFERRED_VECTOR_WIDTH_CHAR
DEVICE_PREFERRED_VECTOR_WIDTH_SHORT DeviceProperty = C.CL_DEVICE_PREFERRED_VECTOR_WIDTH_SHORT
DEVICE_PREFERRED_VECTOR_WIDTH_INT DeviceProperty = C.CL_DEVICE_PREFERRED_VECTOR_WIDTH_INT
DEVICE_PREFERRED_VECTOR_WIDTH_LONG DeviceProperty = C.CL_DEVICE_PREFERRED_VECTOR_WIDTH_LONG
DEVICE_PREFERRED_VECTOR_WIDTH_FLOAT DeviceProperty = C.CL_DEVICE_PREFERRED_VECTOR_WIDTH_FLOAT
DEVICE_PREFERRED_VECTOR_WIDTH_DOUBLE DeviceProperty = C.CL_DEVICE_PREFERRED_VECTOR_WIDTH_DOUBLE
DEVICE_PREFERRED_VECTOR_WIDTH_HALF DeviceProperty = C.CL_DEVICE_PREFERRED_VECTOR_WIDTH_HALF
//DEVICE_PRINTF_BUFFER_SIZE DeviceProperty = C.CL_DEVICE_PRINTF_BUFFER_SIZE
//DEVICE_PREFERRED_INTEROP_USER_SYNC DeviceProperty = C.CL_DEVICE_PREFERRED_INTEROP_USER_SYNC
DEVICE_PROFILE DeviceProperty = C.CL_DEVICE_PROFILE
DEVICE_PROFILING_TIMER_RESOLUTION DeviceProperty = C.CL_DEVICE_PROFILING_TIMER_RESOLUTION
DEVICE_QUEUE_PROPERTIES DeviceProperty = C.CL_DEVICE_QUEUE_PROPERTIES
//DEVICE_REFERENCE_COUNT DeviceProperty = C.CL_DEVICE_REFERENCE_COUNT
DEVICE_SINGLE_FP_CONFIG DeviceProperty = C.CL_DEVICE_SINGLE_FP_CONFIG
DEVICE_TYPE DeviceProperty = C.CL_DEVICE_TYPE
DEVICE_VENDOR DeviceProperty = C.CL_DEVICE_VENDOR
DEVICE_VENDOR_ID DeviceProperty = C.CL_DEVICE_VENDOR_ID
DEVICE_VERSION DeviceProperty = C.CL_DEVICE_VERSION
DRIVER_VERSION DeviceProperty = C.CL_DRIVER_VERSION
)
type Device struct {
id C.cl_device_id
properties map[DeviceProperty]interface{}
}
func (d *Device) Property(prop DeviceProperty) interface{} {
if value, ok := d.properties[prop]; ok {
return value
}
var data interface{}
var length C.size_t
var ret C.cl_int
switch prop {
case DEVICE_AVAILABLE,
DEVICE_COMPILER_AVAILABLE,
DEVICE_ENDIAN_LITTLE,
DEVICE_ERROR_CORRECTION_SUPPORT,
DEVICE_HOST_UNIFIED_MEMORY,
DEVICE_IMAGE_SUPPORT:
//DEVICE_LINKER_AVAILABLE,
//DEVICE_PREFERRED_INTEROP_USER_SYNC:
var val C.cl_bool
ret = C.clGetDeviceInfo(d.id, C.cl_device_info(prop), C.size_t(unsafe.Sizeof(val)), unsafe.Pointer(&val), &length)
data = val == C.CL_TRUE
case DEVICE_ADDRESS_BITS,
DEVICE_MAX_CLOCK_FREQUENCY,
DEVICE_MAX_COMPUTE_UNITS,
DEVICE_MAX_CONSTANT_ARGS,
DEVICE_MAX_READ_IMAGE_ARGS,
DEVICE_MAX_SAMPLERS,
DEVICE_MAX_WORK_ITEM_DIMENSIONS,
DEVICE_MAX_WRITE_IMAGE_ARGS,
DEVICE_MEM_BASE_ADDR_ALIGN,
DEVICE_MIN_DATA_TYPE_ALIGN_SIZE,
DEVICE_NATIVE_VECTOR_WIDTH_CHAR,
DEVICE_NATIVE_VECTOR_WIDTH_SHORT,
DEVICE_NATIVE_VECTOR_WIDTH_INT,
DEVICE_NATIVE_VECTOR_WIDTH_LONG,
DEVICE_NATIVE_VECTOR_WIDTH_FLOAT,
DEVICE_NATIVE_VECTOR_WIDTH_DOUBLE,
DEVICE_NATIVE_VECTOR_WIDTH_HALF,
//DEVICE_PARTITION_MAX_SUB_DEVICES,
DEVICE_PREFERRED_VECTOR_WIDTH_CHAR,
DEVICE_PREFERRED_VECTOR_WIDTH_SHORT,
DEVICE_PREFERRED_VECTOR_WIDTH_INT,
DEVICE_PREFERRED_VECTOR_WIDTH_LONG,
DEVICE_PREFERRED_VECTOR_WIDTH_FLOAT,
DEVICE_PREFERRED_VECTOR_WIDTH_DOUBLE,
DEVICE_PREFERRED_VECTOR_WIDTH_HALF,
//DEVICE_REFERENCE_COUNT,
DEVICE_VENDOR_ID:
var val C.cl_uint
ret = C.clGetDeviceInfo(d.id, C.cl_device_info(prop), C.size_t(unsafe.Sizeof(val)), unsafe.Pointer(&val), &length)
data = val
case DEVICE_IMAGE2D_MAX_HEIGHT,
DEVICE_IMAGE2D_MAX_WIDTH,
DEVICE_IMAGE3D_MAX_DEPTH,
DEVICE_IMAGE3D_MAX_HEIGHT,
DEVICE_IMAGE3D_MAX_WIDTH,
//DEVICE_IMAGE_MAX_BUFFER_SIZE,
//DEVICE_IMAGE_MAX_ARRAY_SIZE,
DEVICE_MAX_PARAMETER_SIZE,
DEVICE_MAX_WORK_GROUP_SIZE,
//DEVICE_PRINTF_BUFFER_SIZE,
DEVICE_PROFILING_TIMER_RESOLUTION:
var val C.size_t
ret = C.clGetDeviceInfo(d.id, C.cl_device_info(prop), C.size_t(unsafe.Sizeof(val)), unsafe.Pointer(&val), &length)
data = val
case DEVICE_GLOBAL_MEM_CACHE_SIZE,
DEVICE_GLOBAL_MEM_SIZE,
DEVICE_LOCAL_MEM_SIZE,
DEVICE_MAX_CONSTANT_BUFFER_SIZE,
DEVICE_MAX_MEM_ALLOC_SIZE:
var val C.cl_ulong
ret = C.clGetDeviceInfo(d.id, C.cl_device_info(prop), C.size_t(unsafe.Sizeof(val)), unsafe.Pointer(&val), &length)
data = val
/*case DEVICE_PLATFORM:
var val C.cl_platform_id
ret = C.clGetDeviceInfo(d.id, C.cl_device_info(prop), C.size_t(unsafe.Sizeof(val)), unsafe.Pointer(&val), &length)
data = Platform{id: val}*/
/*case DEVICE_PARENT_DEVICE:
var val C.cl_device_id
ret = C.clGetDeviceInfo(d.id, C.cl_device_info(prop), C.size_t(unsafe.Sizeof(val)), unsafe.Pointer(&val), &length)
data = Device{id: val}*/
case DEVICE_TYPE:
var val C.cl_device_type
ret = C.clGetDeviceInfo(d.id, C.cl_device_info(prop), C.size_t(unsafe.Sizeof(val)), unsafe.Pointer(&val), &length)
data = DeviceType(val)
case //DEVICE_BUILT_IN_KERNELS,
DEVICE_EXTENSIONS,
DEVICE_NAME,
DEVICE_OPENCL_C_VERSION,
DEVICE_PROFILE,
DEVICE_VENDOR,
DEVICE_VERSION,
DRIVER_VERSION:
if ret = C.clGetDeviceInfo(d.id, C.cl_device_info(prop), 0, nil, &length); ret != C.CL_SUCCESS || length < 1 {
data = ""
break
}
buf := make([]C.char, length)
if ret = C.clGetDeviceInfo(d.id, C.cl_device_info(prop), length, unsafe.Pointer(&buf[0]), &length); ret != C.CL_SUCCESS || length < 1 {
data = ""
break
}
data = C.GoStringN(&buf[0], C.int(length-1))
default:
return nil
}
if ret != C.CL_SUCCESS {
return nil
}
d.properties[prop] = data
return d.properties[prop]
}
|
#!/bin/bash
rm -f heron.wasm
rm -f heron.wat
emcc heron.cpp --no-entry -Os -s EXPORTED_FUNCTIONS=[_heron,_heron_int] -o heron.wasm
~/wabt/build/wasm2wat heron.wasm -o heron.wat |
/**
* <a href="http://www.openolat.org">
* OpenOLAT - Online Learning and Training</a><br>
* <p>
* Licensed under the Apache License, Version 2.0 (the "License"); <br>
* you may not use this file except in compliance with the License.<br>
* You may obtain a copy of the License at the
* <a href="http://www.apache.org/licenses/LICENSE-2.0">Apache homepage</a>
* <p>
* Unless required by applicable law or agreed to in writing,<br>
* software distributed under the License is distributed on an "AS IS" BASIS, <br>
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <br>
* See the License for the specific language governing permissions and <br>
* limitations under the License.
* <p>
* Initial code contributed and copyrighted by<br>
* frentix GmbH, http://www.frentix.com
* <p>
*/
package org.olat.core.commons.services.doceditor.office365;
import java.io.InputStream;
import java.util.Collection;
import java.util.Locale;
import org.olat.core.commons.services.doceditor.Access;
import org.olat.core.commons.services.doceditor.DocEditor.Mode;
import org.olat.core.commons.services.vfs.VFSMetadata;
import org.olat.core.id.Identity;
import org.olat.core.id.OLATResourceable;
import org.olat.core.util.resource.OresHelper;
import org.olat.core.util.vfs.VFSLeaf;
/**
*
* Initial date: 26.04.2019<br>
* @author uhensler, <EMAIL>, http://www.frentix.com
*
*/
public interface Office365Service {
public static final OLATResourceable REFRESH_EVENT_ORES = OresHelper
.createOLATResourceableType(Office365RefreshDiscoveryEvent.class.getSimpleName() + ":RefreshDiscovery");
boolean updateContent(Access access, InputStream fileInputStream);
boolean verifyProofKey(String requestUrl, String accessToken, String timeStamp, String proofKey, String oldProofKey);
Collection<String> getContentSecurityPolicyUrls();
String getEditorActionUrl(VFSMetadata vfsMetadata, Mode mode, Locale locale);
boolean isSupportingFormat(String suffix, Mode mode);
boolean isLockNeeded(Mode mode);
boolean isLockedForMe(VFSLeaf vfsLeaf, Identity identity);
boolean isLockedForMe(VFSLeaf vfsLeaf, VFSMetadata metadata, Identity identity);
String getLockToken(VFSLeaf vfsLeaf);
boolean lock(VFSLeaf vfsLeaf, Identity identity, String lockToken);
boolean canUnlock(VFSLeaf vfsLeaf, String lockToken);
void unlock(VFSLeaf vfsLeaf, String lockToken);
void refreshLock(VFSLeaf vfsLeaf, String lockToken);
}
|
#!/bin/bash
#;**********************************************************************;
#
# Copyright (c) 2016-2018, Intel Corporation
# 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 Intel Corporation nor the names of its contributors
# may be used to endorse or promote products derived from this software without
# specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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.
#;**********************************************************************;
source helpers.sh
cleanup() {
rm -f ek.pub ak.pub ak.name ak.name ak.log
# Evict persistent handles, we want them to always succeed and never trip
# the onerror trap.
tpm2_evictcontrol -Q -a o -c 0x8101000b 2>/dev/null || true
tpm2_evictcontrol -Q -a o -c 0x8101000c 2>/dev/null || true
# clear tpm state
tpm2_clear
if [ "$1" != "no-shut-down" ]; then
shut_down
fi
}
trap cleanup EXIT
start_up
cleanup "no-shut-down"
tpm2_createek -Q -c 0x8101000b -G rsa -p ek.pub
tpm2_createak -Q -C 0x8101000b -k 0x8101000c -G rsa -D sha256 -s rsassa -p ak.pub -n ak.name
# Find a vacant persistent handle
tpm2_createak -C 0x8101000b -k - -G rsa -D sha256 -s rsassa -p ak.pub -n ak.name > ak.log
phandle=`yaml_get_kv ak.log \"ak\-persistent\-handle\"`
tpm2_evictcontrol -Q -a o -c $phandle
exit 0
|
#!/bin/bash
OLD=$(pwd)
BASE=$( cd `dirname $0`/.. ; pwd )
cd $OLD
version=$(cat $BASE/ver/1config.version)
function clean(){
rm -rf /tmp/cljdoc
mkdir -p /tmp/cljdoc
rm -rf /tmp/stage
mkdir -p /tmp/stage
cd /tmp/stage
lein new project
cd $OLD
}
function build(){
rm -fr /tmp/stage/project/src/* /tmp/stage/project/doc/*
cp -r $BASE/1config-core/src/* /tmp/stage/project/src/
find /tmp/stage/project/src/ ! -name \*.clj -type f -delete
rm -fr /tmp/stage/project/src/META-INF/
cp $BASE/README.md $BASE/CHANGELOG.md /tmp/stage/project
cp -R $BASE/doc /tmp/stage/project/
cat > /tmp/stage/project/project.clj <<EOF
(defproject project "0.1.0-SNAPSHOT"
:scm {:name "git" :url "/project"}
:dependencies [[org.clojure/clojure "1.10.0"]
[com.brunobonacci/where "0.5.2"]
[com.brunobonacci/safely "0.5.0-alpha7"]
[amazonica "0.3.139" :exclusions
[com.amazonaws/aws-java-sdk
com.amazonaws/amazon-kinesis-client]]
[com.amazonaws/aws-java-sdk-core "1.11.513"]
[com.amazonaws/aws-java-sdk-dynamodb "1.11.513"]
[com.amazonaws/aws-java-sdk-kms "1.11.513"]
[com.amazonaws/aws-java-sdk-sts "1.11.513"]
[com.amazonaws/aws-encryption-sdk-java "1.3.6"]
[prismatic/schema "1.1.10"]
[cheshire "5.8.1"]]
)
EOF
cd /tmp/stage/project/
lein pom
lein install
git init
git add .
git commit -m 'import'
cd $OLD
echo "--------------------------------------------------------------------------"
echo "------------------------- building documentation ------------------------"
echo "--------------------------------------------------------------------------"
docker run --rm -v "/tmp/stage/project:/project" \
-v "$HOME/.m2:/root/.m2" -v /tmp/cljdoc:/app/data \
--entrypoint "clojure" \
cljdoc/cljdoc -A:cli ingest \
-p "project/project" -v "0.1.0-SNAPSHOT" \
--jar /project/target/project-0.1.0-SNAPSHOT.jar \
--pom /project/pom.xml \
--git /project --rev "master"
}
function show(){
echo "--------------------------------------------------------------------------"
echo "-------------- cljdoc preview: starting server on port 8000 --------------"
echo "- wait then open http://localhost:8000/d/project/project/0.1.0-SNAPSHOT/ -"
echo "--------------------------------------------------------------------------"
docker run --rm -p 8000:8000 -v /tmp/cljdoc:/app/data cljdoc/cljdoc
}
if [ "$1" == "refresh" ] ; then
build
echo "--------------------------------------------------------------------------"
echo "--------------------------- documentation READY --------------------------"
echo "--------------------------------------------------------------------------"
else
clean
build
show
fi
|
<reponame>handexing/wish<filename>src/main/java/com/wish/entity/LeaveBill.java
package com.wish.entity;
import com.fasterxml.jackson.annotation.JsonFormat;
import org.springframework.format.annotation.DateTimeFormat;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
/**
*
* @ClassName: LeaveBill
* @Description: 请假流程实体
* @author handx <EMAIL>
* @date 2017年5月17日 下午9:46:05
*
*/
@Entity
@Table(name = "LEAVE_BILL")
public class LeaveBill implements Serializable{
private static final long serialVersionUID = 2000001315172295755L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "ID")
private Long id;
@Column(name = "DAYS")
private Integer days;
@Column(name = "CONTENT")
private String content;
@Column(name = "REMARK")
private String remark;
@DateTimeFormat(pattern = "yyyy-MM-dd")
@JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
@Column(name = "LEAVE_DATE")
private Date leaveDate;
@DateTimeFormat(pattern = "yyyy-MM-dd")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
@Column(name = "CREATE_DATE")
private Date createDate;
@Column(name = "STATE")
private Integer state;
@ManyToOne(cascade = CascadeType.REFRESH, fetch = FetchType.EAGER)
@JoinColumn(name = "USER_ID")
User user;
public String getContent() {
return content;
}
public Date getCreateDate() {
return createDate;
}
public Integer getDays() {
return days;
}
public Long getId() {
return id;
}
public Date getLeaveDate() {
return leaveDate;
}
public String getRemark() {
return remark;
}
public Integer getState() {
return state;
}
public User getUser() {
return user;
}
public void setContent(String content) {
this.content = content;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
public void setDays(Integer days) {
this.days = days;
}
public void setId(Long id) {
this.id = id;
}
public void setLeaveDate(Date leaveDate) {
this.leaveDate = leaveDate;
}
public void setRemark(String remark) {
this.remark = remark;
}
public void setState(Integer state) {
this.state = state;
}
public void setUser(User user) {
this.user = user;
}
@Override
public String toString() {
return "Leavebill [id=" + id + ", days=" + days + ", content=" + content + ", remark=" + remark + ", leaveDate="
+ leaveDate + ", state=" + state + ", user=" + user + "]";
}
}
|
source build/envsetup.sh
export USE_CCACHE=1
export CCACHE_DIR=.ccache
prebuilts/misc/linux-x86/ccache/ccache -M 75G
lunch full_maguro-userdebug
time make -j6 && play frameworks/base/data/sounds/notifications/ogg/Capella.ogg
|
import React from 'react'
import styled from 'styled-components'
import { Link, useStaticQuery, graphql } from 'gatsby'
import { Img } from '../utils/styles'
import Slider from 'react-slick'
//Styles
const Wrapper = styled.div`
color: white;
text-align: center;
h2 {
position: relative;
top: 1rem;
font-size: 5rem;
display: inline-block;
color: black;
}
/* @media (max-width: 1024px) {
display: none;
} */
`
const Carousel = styled(Slider)`
padding-top: 1.5rem;
margin-bottom: 2rem;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.12), 0 1px 2px rgba(0, 0, 0, 0.24);
.links {
transition: ease-in-out 0.2s all;
text-align: center;
}
.slick-list {
margin: 0 25px;
}
.slick-arrow {
background-color: black;
border-radius: 50%;
width: 50px;
height: 50px;
}
.slick-slider {
}
.slick-slide {
box-sizing: border-box;
/* margin: 0 auto; */
text-align: center;
/* padding: 0 1rem; */
}
.slick-next {
}
.slick-prev {
right: 1.8rem;
}
.slick-dots {
bottom: 0;
left: 0;
}
`
const Image = styled(Img)`
border-radius: 50%;
@media (max-width: 1024px) {
width: 200px;
height: 200px;
}
`
const Slideshow = () => {
const { allShopifyProduct } = useStaticQuery(
graphql`
query {
allShopifyProduct(
sort: { fields: [createdAt], order: DESC }
filter: { tags: { eq: "Women" } }
) {
edges {
node {
id
title
handle
createdAt
images {
id
originalSrc
localFile {
childImageSharp {
fluid(maxWidth: 400, maxHeight: 400) {
...GatsbyImageSharpFluid_noBase64
}
}
}
}
}
}
}
}
`
)
const settings = {
speed: 500,
slidesToShow: 3,
autoplay: true,
autoplaySpeed: 3000,
pauseOnFocus: true,
adaptiveHeight: true,
variableWidth: true,
infinite: true,
// centerMode:true,
responsive: [
{
breakpoint: 1024,
settings: {
slidesToShow: 2,
variableWidth: false,
},
},
{
breakpoint: 576,
settings: {
slidesToShow: 1,
variableWidth: false,
arrows: false,
},
},
],
}
return (
<Wrapper>
<h2>Featured Products</h2>
<Carousel {...settings}>
{allShopifyProduct.edges ? (
allShopifyProduct.edges.map(
({
node: {
id,
handle,
title,
images: [firstImage],
},
}) => (
<Link className="links" to={`/product/${handle}/`} key={id}>
{firstImage && firstImage.localFile && (
<Image
fluid={firstImage.localFile.childImageSharp.fluid}
alt={handle}
/>
)}
</Link>
)
)
) : (
<p>No Products found!</p>
)}
</Carousel>
</Wrapper>
)
}
export default Slideshow
|
#!/bin/sh
set -e
ROOTDIR=dist
BUNDLE=${ROOTDIR}/PRACTICE1-Qt.app
CODESIGN=codesign
TEMPDIR=sign.temp
TEMPLIST=${TEMPDIR}/signatures.txt
OUT=signature.tar.gz
if [ ! -n "$1" ]; then
echo "usage: $0 <codesign args>"
echo "example: $0 -s MyIdentity"
exit 1
fi
rm -rf ${TEMPDIR} ${TEMPLIST}
mkdir -p ${TEMPDIR}
${CODESIGN} -f --file-list ${TEMPLIST} "$@" "${BUNDLE}"
for i in `grep -v CodeResources ${TEMPLIST}`; do
TARGETFILE="${BUNDLE}/`echo ${i} | sed "s|.*${BUNDLE}/||"`"
SIZE=`pagestuff $i -p | tail -2 | grep size | sed 's/[^0-9]*//g'`
OFFSET=`pagestuff $i -p | tail -2 | grep offset | sed 's/[^0-9]*//g'`
SIGNFILE="${TEMPDIR}/${TARGETFILE}.sign"
DIRNAME="`dirname ${SIGNFILE}`"
mkdir -p "${DIRNAME}"
echo "Adding detached signature for: ${TARGETFILE}. Size: ${SIZE}. Offset: ${OFFSET}"
dd if=$i of=${SIGNFILE} bs=1 skip=${OFFSET} count=${SIZE} 2>/dev/null
done
for i in `grep CodeResources ${TEMPLIST}`; do
TARGETFILE="${BUNDLE}/`echo ${i} | sed "s|.*${BUNDLE}/||"`"
RESOURCE="${TEMPDIR}/${TARGETFILE}"
DIRNAME="`dirname "${RESOURCE}"`"
mkdir -p "${DIRNAME}"
echo "Adding resource for: "${TARGETFILE}""
cp "${i}" "${RESOURCE}"
done
rm ${TEMPLIST}
tar -C ${TEMPDIR} -czf ${OUT} .
rm -rf ${TEMPDIR}
echo "Created ${OUT}"
|
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { CandidatePage } from './pages/candidate/candidate.page';
import { CandidatesPage } from './pages/candidates/candidates.page';
import { CRMemberPage } from './pages/crmember/crmember.page';
import { CRMembersPage } from './pages/crmembers/crmembers.page';
import { CRNodePage } from './pages/crnode/crnode.page';
import { HistoryPage } from './pages/history/history.page';
import { ImpeachCRMemberPage } from './pages/impeach/impeach.page';
import { RegisterUpdatePage } from './pages/register-update/register-update.page';
import { CandidateRegistrationTermsPage } from './pages/registration-terms/registration-terms.page';
import { VotePage } from './pages/vote/vote.page';
const routes: Routes = [
{ path: 'candidates', component: CandidatesPage },
{ path: 'candidate/:did', component: CandidatePage },
{ path: 'crmembers', component: CRMembersPage },
{ path: 'crmember', component: CRMemberPage },
{ path: 'impeach', component: ImpeachCRMemberPage },
{ path: 'vote', component: VotePage },
{ path: 'history', component: HistoryPage },
{ path: 'crnode', component: CRNodePage },
{ path: 'registration', component: RegisterUpdatePage },
{ path: 'update', component: RegisterUpdatePage },
{ path: 'registration-terms', component: CandidateRegistrationTermsPage },
];
@NgModule({
imports: [
RouterModule.forChild(routes)
],
exports: [RouterModule]
})
export class CRCouncilVotingRoutingModule { }
|
#ifndef CROSS_HPP
#define CROSS_HPP
#include "complex-type.h"
#ifdef FFTW3
#include <fftw3-mpi.h>
#else
#include <fftw_mpi.h>
#endif
#include <algorithm>
#include <vector>
#include "allocator.hpp"
#include "distribution.hpp"
#include "solver.hpp"
#include <string.h>
// pgCC doesn't yet play well with C99 constructs, so...
#ifdef __PGI__
extern "C" long int lrint(double x);
#endif
#define FFTW_ADDR(X) reinterpret_cast<fftw_complex*>(&(X)[0])
class CrossBase : public Distribution {
public:
// methods
CrossBase()
{
}
CrossBase(MPI_Comm comm, int ng)
: Distribution(comm, ng)
{
std::vector<int> n;
n.assign(3, ng);
initialize(comm, n);
}
CrossBase(MPI_Comm comm, std::vector<int> const & n)
: Distribution(comm, n)
{
initialize(comm, n);
}
virtual ~CrossBase()
{
#ifdef FFTW3
fftw_destroy_plan(m_plan_f);
fftw_destroy_plan(m_plan_b);
#else
fftwnd_mpi_destroy_plan(m_plan_f);
fftwnd_mpi_destroy_plan(m_plan_b);
#endif
}
// solve interfaces
//NOT SURE I DID THIS CORRECTLY FOR FFTW2 -- ADRIAN
void forward(complex_t const *rho1, complex_t const *rho2)
{
//forward rho1
#ifdef FFTW3
distribution_3_to_1(rho1, &m_buf1[0], &m_d); // rho1 --> buf1
fftw_execute(m_plan_f); // buf1 --> buf2
#else
distribution_3_to_1(rho1, &m_buf2[0], &m_d); // rho1 --> buf2
fftwnd_mpi(m_plan_f, 1, FFTW_ADDR(m_buf2), FFTW_ADDR(m_buf3),
FFTW_NORMAL_ORDER); // buf2 --> buf3
#endif
//copy transformed rho1 (in buf2) to a safe place (buf3)
memcpy( &m_buf3[0], &m_buf2[0], local_size()*sizeof(complex_t) );
//forward rho2
#ifdef FFTW3
distribution_3_to_1(rho2, &m_buf1[0], &m_d); // rho2 --> buf1
fftw_execute(m_plan_f); // buf1 --> buf2
#else
distribution_3_to_1(rho2, &m_buf2[0], &m_d); // rho2 --> buf2
fftwnd_mpi(m_plan_f, 1, FFTW_ADDR(m_buf2), FFTW_ADDR(m_buf3),
FFTW_NORMAL_ORDER); // buf2 --> buf3
#endif
}
void backward_xi(complex_t *phi)
{
//now, transformed rho1 in buf3, transformed rho2 in buf2
//need intermediate result in buf1
for(int i=0; i<local_size(); i++) {
m_buf1[i] = m_buf2[i] * conj(m_buf3[i]);
}
//it would be nice to set (0,0,0) mode to 0
int index = 0;
for (int local_k0 = 0; local_k0 < local_ng_1d(0); ++local_k0) {
int k0 = local_k0 + self_1d(0) * local_ng_1d(0);
for (int k1 = 0; k1 < local_ng_1d(1); ++k1) {
for (int k2 = 0; k2 < local_ng_1d(2); ++k2) {
if(k0 == 0 && k1==0 && k2==0) {
m_buf1[index] *= 0.0;
}
index++;
}
index += m_d.padding[2];
}
index += m_d.padding[1];
}
#ifdef FFTW3
fftw_execute(m_plan_b); // buf1 --> buf3
distribution_1_to_3(&m_buf3[0], phi, &m_d); // buf3 --> phi
#else
fftwnd_mpi(m_plan_b, 1,
(fftw_complex *) &m_buf1[0],
(fftw_complex *) &m_buf3[0],
FFTW_NORMAL_ORDER); // buf1 -->buf1
distribution_1_to_3(&m_buf1[0], phi, &m_d); // buf3 --> phi
#endif
}
// interfaces for std::vector
void forward(std::vector<complex_t> const & rho1,
std::vector<complex_t> const & rho2)
{
forward(&rho1[0], &rho2[0]);
}
void backward_xi(std::vector<complex_t> & phi)
{
backward_xi(&phi[0]);
}
// analysis interfaces
///
// calculate the k-space power spectrum
// P(modk) = Sum { |rho(k)|^2 : |k| = modk, k <- [0, ng / 2)^3, periodically extended }
///
void power_spectrum(std::vector<double> & power)
{
std::vector<complex_t, fftw_allocator<complex_t> > const & rho1 = m_buf3;
std::vector<complex_t, fftw_allocator<complex_t> > const & rho2 = m_buf2;
std::vector<int> ksq;
std::vector<double> weight;
int ng = m_d.n[0];
double volume = 1.0 * ng * ng * ng;
// cache periodic ksq
ksq.resize(ng);
double ksq_max = 0;
for (int k = 0; k < ng / 2; ++k) {
ksq[k] = k * k;
ksq_max = max(ksq_max, ksq[k]);
ksq[k + ng / 2] = (k - ng / 2) * (k - ng / 2);
ksq_max = max(ksq_max, ksq[k + ng / 2]);
}
long modk_max = lrint(sqrt(3 * ksq_max)); // round to nearest integer
// calculate power spectrum
power.resize(modk_max + 1);
power.assign(modk_max + 1, 0.0);
weight.resize(modk_max + 1);
weight.assign(modk_max + 1, 0.0);
int index = 0;
for (int local_k0 = 0; local_k0 < local_ng_1d(0); ++local_k0) {
int k0 = local_k0 + self_1d(0) * local_ng_1d(0);
double ksq0 = ksq[k0];
for (int k1 = 0; k1 < local_ng_1d(1); ++k1) {
double ksq1 = ksq[k1];
for (int k2 = 0; k2 < local_ng_1d(2); ++k2) {
double ksq2 = ksq[k2];
// round to nearest integer
long modk = lrint(sqrt(ksq0 + ksq1 + ksq2));
power[modk] += real(rho1[index] * conj(rho2[index]));
weight[modk] += volume;
index++;
}
index += m_d.padding[2];
}
index += m_d.padding[1];
}
// accumulate across processors
MPI_Allreduce(MPI_IN_PLACE, &power[0], power.size(), MPI_DOUBLE, MPI_SUM, cart_1d());
MPI_Allreduce(MPI_IN_PLACE, &weight[0], weight.size(), MPI_DOUBLE, MPI_SUM, cart_1d());
//make sure we don't divide by zero
for(int i = 0; i < weight.size(); ++i) {
weight[i] += 1.0 * (weight[i] < 1.0);
}
// scale power by weight
std::transform(power.begin(), power.end(), weight.begin(), power.begin(), std::divides<double>());
}
///
// General initialization
///
void initialize(MPI_Comm comm, std::vector<int> n, bool transposed_order = false)
{
int flags_f;
int flags_b;
distribution_init(comm, &n[0], &n[0], &m_d, false);
distribution_assert_commensurate(&m_d);
#ifdef FFTW3
fftw_mpi_init();
#endif
m_buf1.resize(local_size());
m_buf2.resize(local_size());
m_buf3.resize(local_size());
// create plan for forward and backward DFT's
flags_f = flags_b = FFTW_ESTIMATE;
#ifdef FFTW3
if (transposed_order) {
flags_f |= FFTW_MPI_TRANSPOSED_OUT;
flags_b |= FFTW_MPI_TRANSPOSED_IN;
}
m_plan_f = fftw_mpi_plan_dft_3d(n[0], n[1], n[2],
FFTW_ADDR(m_buf1), FFTW_ADDR(m_buf2),
comm, FFTW_FORWARD, flags_f);
m_plan_b = fftw_mpi_plan_dft_3d(n[0], n[1], n[2],
FFTW_ADDR(m_buf1), FFTW_ADDR(m_buf3),
comm, FFTW_BACKWARD, flags_b);
#else
m_plan_f = fftw3d_mpi_create_plan(comm, n[0], n[1], n[2], FFTW_FORWARD, flags_f);
m_plan_b = fftw3d_mpi_create_plan(comm, n[0], n[1], n[2], FFTW_BACKWARD, flags_b);
#endif
}
protected:
double max(double a, double b) { return a > b ? a : b; }
std::vector<complex_t, fftw_allocator<complex_t> > m_buf1;
std::vector<complex_t, fftw_allocator<complex_t> > m_buf2;
std::vector<complex_t, fftw_allocator<complex_t> > m_buf3;
#ifdef FFTW3
fftw_plan m_plan_f;
fftw_plan m_plan_b;
#else
fftwnd_mpi_plan m_plan_f;
fftwnd_mpi_plan m_plan_b;
#endif
};
#endif
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Sudoku_Final;
/**
*
* @author Admin
*/
public class Main_menu extends javax.swing.JFrame {
/**
* Creates new form Main_menu
*/
public Main_menu() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
jLabel2 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setBackground(new java.awt.Color(255, 255, 255));
jLabel1.setFont(new java.awt.Font("Comic Sans MS", 0, 14)); // NOI18N
jLabel1.setText("What do You want to Do ???");
jButton1.setFont(new java.awt.Font("Comic Sans MS", 0, 11)); // NOI18N
jButton1.setText("Solve a Sudoku");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButton2.setFont(new java.awt.Font("Comic Sans MS", 0, 11)); // NOI18N
jButton2.setText("Play A game");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jButton3.setFont(new java.awt.Font("Comic Sans MS", 0, 11)); // NOI18N
jButton3.setText("Random Sudoku");
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
jLabel2.setIcon(new javax.swing.ImageIcon("C:\\Users\\Admin\\Downloads\\b4c6d163dbbe72db6894bdf98af21138-infinity-logo-template.jpg")); // NOI18N
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(60, 60, 60)
.addComponent(jButton1)
.addGap(69, 69, 69)
.addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(150, 150, 150)
.addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(110, 110, 110)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 390, javax.swing.GroupLayout.PREFERRED_SIZE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(140, 140, 140)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(30, 30, 30)
.addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(80, 80, 80)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 280, javax.swing.GroupLayout.PREFERRED_SIZE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
this.dispose();
new Sudoku_Solve().setVisible(true);
}//GEN-LAST:event_jButton1ActionPerformed
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
// TODO add your handling code here:
this.dispose();
int rand = 2 + (int)(Math.random()*4);
System.out.println(rand);
switch (rand) {
case 2: new Sudoku_2().setVisible(true);
break;
case 3: new Sudoku_3().setVisible(true);
break;
case 4: new Sudoku_4().setVisible(true);
break;
case 5: new Sudoku_5().setVisible(true);
break;
}
}//GEN-LAST:event_jButton2ActionPerformed
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
// TODO add your handling code here:
this.dispose();
new Sudoku_1().setVisible(true);
}//GEN-LAST:event_jButton3ActionPerformed
/**
* @param args the command line arguments
*/
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
// End of variables declaration//GEN-END:variables
}
|
<filename>cascading-core/src/main/java/cascading/scheme/SourceCall.java
/*
* Copyright (c) 2007-2013 Concurrent, Inc. All Rights Reserved.
*
* Project and contact information: http://www.cascading.org/
*
* This file is part of the Cascading project.
*
* 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 cascading.scheme;
import cascading.tuple.TupleEntry;
/**
* SourceCall provides access to the current {@link Scheme#source(cascading.flow.FlowProcess, SourceCall)} invocation
* arguments.
* <p/>
* Use the Context to store thread local values.
*
* @param <Context>
* @param <Input>
*/
public interface SourceCall<Context, Input>
{
/**
* Method getContext returns the context of this SourceCall object.
*
* @return the context (type C) of this SourceCall object.
*/
Context getContext();
/**
* Method setContext sets the context of this SourceCall object.
*
* @param context the context of this SourceCall object.
*/
void setContext( Context context );
/**
* Method getIncomingEntry returns a pre-prepared {@link TupleEntry} to be populated
* with the input values from {@link #getInput()}.
* <p/>
* That is, using the getInput() method, retrieve the current incoming values and
* place them into the getIncomingEntry() via {@link TupleEntry#setTuple(cascading.tuple.Tuple)}
* or by modifying the tuple returned from {@link cascading.tuple.TupleEntry#getTuple()}.
* <p/>
* The returned Tuple entry is guaranteed to be the size of the declared incoming source fields.
* <p/>
* The returned TupleEntry from this method is modifiable and is intended to be re-used. This is an exception to
* the general rule that passed TupleEntry instances must not be modified.
*
* @return TupleEntry
*/
TupleEntry getIncomingEntry();
/**
* Method getInput returns the input mechanism for the underlying platform used to retrieve new values (records,
* lines, etc).
* <p/>
* Do not cache the returned value as it may change.
*
* @return the platform dependent input handler
*/
Input getInput();
}
|
<filename>codes/java/concurrency/src/main/java/tamp/ch12/Combine/Combine/Node.java
package tamp.ch12.Combine.Combine;
/*
* Node.java
*
* Created on October 29, 2005, 8:59 AM
*
* From "The Art of Multiprocessor Programming",
* by <NAME> and <NAME>.
* Copyright 2006 Elsevier Inc. All rights reserved.
*/
/**
* Node declaration for software combining tree.
*
* @author <NAME>
*/
public class Node {
enum CStatus {IDLE, FIRST, SECOND, RESULT, ROOT}
;
boolean locked; // is node locked?
CStatus cStatus; // combining status
int firstValue, secondValue; // values to be combined
int result; // result of combining
Node parent; // reference to parent
/**
* Creates a root Node
*/
public Node() {
cStatus = CStatus.ROOT;
locked = false;
}
/**
* Create a non-root Node
*/
public Node(Node _parent) {
parent = _parent;
cStatus = CStatus.IDLE;
locked = false;
}
synchronized boolean precombine() throws InterruptedException {
while (locked) wait();
switch (cStatus) {
case IDLE:
cStatus = CStatus.FIRST;
return true;
case FIRST:
locked = true;
cStatus = CStatus.SECOND;
return false;
case ROOT:
return false;
default:
throw new PanicException("unexpected Node state " + cStatus);
}
}
synchronized int combine(int combined) throws InterruptedException {
while (locked) wait();
locked = true;
firstValue = combined;
switch (cStatus) {
case FIRST:
return firstValue;
case SECOND:
return firstValue + secondValue;
default:
throw new PanicException("unexpected Node state " + cStatus);
}
}
synchronized int op(int combined) throws InterruptedException {
switch (cStatus) {
case ROOT:
int oldValue = result;
result += combined;
return oldValue;
case SECOND:
secondValue = combined;
locked = false;
notifyAll();
while (cStatus != CStatus.RESULT) wait();
locked = false;
notifyAll();
cStatus = CStatus.IDLE;
return result;
default:
throw new PanicException("unexpected Node state");
}
}
synchronized void distribute(int prior) throws InterruptedException {
switch (cStatus) {
case FIRST:
cStatus = CStatus.IDLE;
locked = false;
break;
case SECOND:
result = prior + firstValue;
cStatus = CStatus.RESULT;
break;
default:
throw new PanicException("unexpected Node state");
}
notifyAll();
}
}
|
package jwt
import (
"context"
"strings"
"github.com/suisrc/auth.zgo"
"github.com/suisrc/res.zgo"
)
// GetBearerToken 获取用户令牌
func GetBearerToken(ctx context.Context) (string, error) {
if c, ok := ctx.(res.Context); ok {
prefix := "Bearer "
if auth := c.GetHeader("Authorization"); auth != "" && strings.HasPrefix(auth, prefix) {
return auth[len(prefix):], nil
}
}
return "", auth.ErrNoneToken
}
// GetFormToken 获取用户令牌
func GetFormToken(ctx context.Context) (string, error) {
if c, ok := ctx.(res.Context); ok {
if auth := c.GetRequest().Form.Get("token"); auth != "" {
return auth, nil
}
}
return "", auth.ErrNoneToken
}
// GetCookieToken 获取用户令牌
func GetCookieToken(ctx context.Context) (string, error) {
if c, ok := ctx.(res.Context); ok {
if auth, err := c.GetRequest().Cookie("authorization"); err == nil && auth != nil && auth.Value != "" {
return auth.Value, nil
}
}
return "", auth.ErrNoneToken
}
|
def editToMakePalindrome(string):
n = len(string)
table = [[0 for x in range(n)] for x in range(n)]
# Fill the string column by column
for gap in range(1, n):
i = 0
for j in range(gap, n):
if string[i] == string[j]:
table[i][j] = table[i + 1][j - 1]
else:
table[i][j] = (min(table[i][j - 1],
table[i + 1][j]) + 1)
i += 1
anagram = ""
j = n-1
i = 0
while (i <= j):
if string[i] == string[j]:
anagram = anagram + string[i]
i += 1
j -= 1
elif (table[i][j - 1] < table[i + 1][j]):
anagram = anagram + string[j]
j -= 1
else:
anagram = anagram + string[i]
i += 1
return anagram + string[i:j+1] |
##############################################################################
# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by <NAME>, <EMAIL>, All rights reserved.
# LLNL-CODE-647188
#
# For details, see https://github.com/spack/spack
# Please also see the NOTICE and LICENSE files for our notice and the LGPL.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License (as
# published by the Free Software Foundation) version 2.1, February 1999.
#
# 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 terms and
# conditions of the GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
##############################################################################
from spack import *
class AllineaReports(Package):
"""Allinea Performance Reports are the most effective way to characterize
and understand the performance of HPC application runs. One single-page
HTML report elegantly answers a range of vital questions for any HPC site
"""
homepage = "http://www.allinea.com/products/allinea-performance-reports"
version('6.0.4', '3f13b08a32682737bc05246fbb2fcc77')
# Licensing
license_required = True
license_comment = '#'
license_files = ['licences/Licence']
license_vars = ['ALLINEA_LICENCE_FILE', 'ALLINEA_LICENSE_FILE']
license_url = 'http://www.allinea.com/user-guide/reports/Installation.html'
def url_for_version(self, version):
# TODO: add support for other architectures/distributions
url = "http://content.allinea.com/downloads/"
return url + "allinea-reports-%s-Redhat-6.0-x86_64.tar" % version
def install(self, spec, prefix):
textinstall = Executable('./textinstall.sh')
textinstall('--accept-licence', prefix)
|
#!/bin/bash
set -e
kubectl apply -f ./metrics-server/metrics-server-insecure.yaml
sleep 10
# Check deployment
kubectl get deployment metrics-server -n kube-system
# Check pod status and ready
kubectl get pods -n kube-system -l k8s-app=metrics-server
# Check apiservice status
kubectl get apiservice v1beta1.metrics.k8s.io -o yaml
# Wait a while to let metrics server takes effect
sleep 180
kubectl top nodes
kubectl top pods -A
|
<reponame>lananh265/social-network<filename>node_modules/react-icons-kit/md/ic_menu_open.js
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.ic_menu_open = void 0;
var ic_menu_open = {
"viewBox": "0 0 24 24",
"children": [{
"name": "path",
"attribs": {
"d": "M0 0h24v24H0V0z",
"fill": "none"
},
"children": []
}, {
"name": "path",
"attribs": {
"d": "M3 18h13v-2H3v2zm0-5h10v-2H3v2zm0-7v2h13V6H3zm18 9.59L17.42 12 21 8.41 19.59 7l-5 5 5 5L21 15.59z"
},
"children": []
}]
};
exports.ic_menu_open = ic_menu_open; |
<gh_stars>0
import styled from 'styled-components';
const StylesStyles = styled.section`
background-color: red;
`;
export default StylesStyles;
|
"use strict"
const assert = require("power-assert");
const UserRepository = require("../../../src/game/UserRepository.js");
const JobRepository = require("../../../src/game/JobRepository.js");
const WeaponRepository = require("../../../src/game/WeaponRepository.js");
const MockBrain = require("../mock/Brain.js");
const MockRobot = require("../mock/Robot.js");
const NodeCache = require('node-cache');
describe('UserRepository', () => {
it("should load", async () => {
const cache = new NodeCache();
cache.set("slack_user_cache", [
{"id": "a", "name": "hoge", is_bot: false},
{"id": "b", "name": "fuga", is_bot: false},
{"id": "c", "name": "piyo", is_bot: false}
]);
const mockRobot = new MockRobot(new MockBrain({
HUBOT_NODE_QUEST_USERS: {
"a": {
id: "a",
hitPoint: 10,
magicPoint: 10,
},
"b": {
id: "b",
hitPoint: 0,
magicPoint: 10,
}
}
}));
const r = new UserRepository(mockRobot, cache);
const actual = await r.load(new JobRepository(), new WeaponRepository());
assert.equal(Object.keys(actual).length, 3);
assert.deepEqual(actual.map((u) => {
return {
id: u.id,
name: u.name,
hp: u.hitPoint.current,
mp: u.magicPoint.current
}
}), [
{id: "a", name:"hoge", hp: 10, mp:10},
{id: "b", name:"fuga", hp: 0, mp:10},
{id: "c", name:"piyo", hp: 5000, mp:1000}
]);
});
it("should save and get", async () => {
const cache = new NodeCache();
cache.set("slack_user_cache", [
{"id": "a", "name": "hoge", is_bot: false},
{"id": "b", "name": "fuga", is_bot: false},
{"id": "c", "name": "piyo", is_bot: false}
]);
const mockRobot = new MockRobot(new MockBrain({
HUBOT_NODE_QUEST_USERS: {
"a": {
id: "a",
hitPoint: 10,
magicPoint: 10,
},
"b": {
id: "b",
hitPoint: 0,
magicPoint: 10,
}
}
}));
const r = new UserRepository(mockRobot, cache);
await r.load(new JobRepository(), new WeaponRepository());
const users = r.get();
const user = users.filter((u) => u.name === "hoge").pop();
user.cured(100);
r.save();
await r.load(new JobRepository(), new WeaponRepository());
const actual = r.get();
assert.equal(Object.keys(actual).length, 3);
assert.deepEqual(actual.map((u) => {
return {
id: u.id,
name: u.name,
hp: u.hitPoint.current,
mp: u.magicPoint.current
}
}), [
{id: "a", name:"hoge", hp: 110, mp:10},
{id: "b", name:"fuga", hp: 0, mp:10},
{id: "c", name:"piyo", hp: 5000, mp:1000}
]);
})
});
|
class Model:
def __init__(self):
self.name = ""
self.content = ""
@staticmethod
def new():
return Model()
def save(self):
# Implement the logic to save the object to the CMS
# This could involve database operations or file storage
def search(query):
# Implement the logic to search for objects based on the content
# Return a list of objects whose content contains the search query
# This could involve database queries or file content searches |
/**
* Created by rkapoor on 30/10/15.
*/
'use strict';
module.exports = function cssmin(grunt) {
// Load task
grunt.loadNpmTasks('grunt-contrib-cssmin');
// Options
return {
homePage: {
files: {
'public/css/production/homePage.min.css': [
'public/css/bootstrapCSS/bootstrap-slider.css',
'public/css/angularCSS/ng-slider.css',
'public/js/jscrollPaneJS/jquery.jscrollpane.css',
'public/css/JscrollPaneCSS/ItineraryPanelJscrollPane.css',
'public/css/home/inputs.css',
'public/css/krishna.css',
'public/css/home/fonts-awesome.css',
'public/css/home/flexslider.css',
'public/css/home/style4.css',
'public/css/global/stickyFooter.css'
]
}
},
travelPage: {
files: {
'public/css/production/travelPage.min.css': [
'public/css/travelPage/surya.css',
'public/css/travelPage/sarathi.css',
'public/css/home/fonts-awesome.css',
'public/css/home/flexslider.css',
'public/css/home/style4.css',
'public/js/jscrollPaneJS/jquery.jscrollpane.css',
'public/css/JscrollPaneCSS/ItineraryPanelJscrollPane.css',
'public/css/travelPage/map.css',
'public/css/global/pageLoader.css',
'public/css/global/stickyFooter.css',
'public/css/angularCSS/introjs.min.css'
]
}
},
hotelsAndPlacesPages: {
files: {
'public/css/production/hotelsAndPlacesPage.min.css': [
'public/css/bootstrapCSS/angular-timeline.css',
'public/css/bootstrapCSS/angular-timeline-bootstrap.css',
'public/css/home/fonts-awesome.css',
'public/css/hotelsAndPlacesPage/shakuni.css',
'public/css/hotelsAndPlacesPage/map.css',
'public/css/hotelsAndPlacesPage/cityPanel.css',
'public/css/home/inputs.css',
'public/css/global/pageLoader.css',
'public/css/home/flexslider.css',
'public/css/home/style4.css',
'public/css/angularCSS/introjs.min.css',
'public/js/jscrollPaneJS/jquery.jscrollpane.css',
'public/css/JscrollPaneCSS/ItineraryPanelJscrollPane.css',
'public/css/global/stickyFooter.css'
]
}
}
};
};
|
<reponame>MauroDataMapper/mdm-ui
/*
Copyright 2020-2021 University of Oxford
and Health and Social Care Information Centre, also known as NHS Digital
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.
SPDX-License-Identifier: Apache-2.0
*/
import { Component, OnDestroy, OnInit } from '@angular/core';
import { Title } from '@angular/platform-browser';
import { BroadcastService } from '@mdm/services/broadcast.service';
import { SecurityHandlerService } from '@mdm/services/handlers/security-handler.service';
import { StateHandlerService } from '@mdm/services/handlers/state-handler.service';
import { MdmResourcesService } from '@mdm/modules/resources';
import { SharedService } from '@mdm/services/shared.service';
import { MessageHandlerService } from '@mdm/services/utility/message-handler.service';
import { UserSettingsHandlerService } from '@mdm/services/utility/user-settings-handler.service';
import { ValidatorService } from '@mdm/services/validator.service';
import { EMPTY, of, Subject, Subscription } from 'rxjs';
import {
catchError,
debounceTime,
finalize,
map,
switchMap,
takeUntil
} from 'rxjs/operators';
import { MatDialog } from '@angular/material/dialog';
import { NodeConfirmClickEvent } from '@mdm/folders-tree/folders-tree.component';
import { ModelTreeService } from '@mdm/services/model-tree.service';
import {
CatalogueItemDomainType,
Classifier,
ClassifierIndexResponse,
ContainerDomainType,
DataModel,
isContainerDomainType,
MdmTreeItem,
MdmTreeItemListResponse,
ModelDomainType
} from '@maurodatamapper/mdm-resources';
import {
mapCatalogueDomainTypeToContainer,
MdmTreeLevelManager
} from './models.model';
@Component({
selector: 'mdm-models',
templateUrl: './models.component.html',
styleUrls: ['./models.component.scss']
})
export class ModelsComponent implements OnInit, OnDestroy {
formData: any = {};
activeTab = 0;
allModels: MdmTreeItem = null;
filteredModels = null;
isAdmin = this.securityHandler.isAdmin();
inSearchMode = false;
folder = '';
searchboxFocused = false;
debounceInputEvent: Subject<KeyboardEvent | InputEvent>;
subscriptions: Subscription;
// Hard
includeModelSuperseded = false;
// Soft
showSupersededModels = false;
includeDeleted = false;
showFilters = false;
currentTab = 'dataModels';
classifierLoading = false;
allClassifiers: Classifier[];
reloading = false;
currentClassification: any;
allClassifications: any;
classifiers: { children: Classifier[]; isRoot: boolean };
searchText: any;
levels: MdmTreeLevelManager = {
current: 0,
currentFocusedElement: null,
backToTree: () => {
this.levels.current = 0;
this.reloadTree();
},
focusTreeItem: (node?: MdmTreeItem) => {
if (node) {
this.levels.currentFocusedElement = node;
}
const containerType = mapCatalogueDomainTypeToContainer(
this.levels.currentFocusedElement.domainType
);
if (containerType) {
this.reloading = true;
if (
containerType !== ModelDomainType.Folders &&
containerType !== ModelDomainType.VersionedFolders
) {
this.resources.tree
.get(
containerType,
this.levels.currentFocusedElement.domainType,
this.levels.currentFocusedElement.id
)
.pipe(
catchError((error) => {
this.messageHandler.showError(
'There was a problem focusing the tree element.',
error
);
return EMPTY;
}),
finalize(() => (this.reloading = false))
)
.subscribe((response: MdmTreeItemListResponse) => {
const children = response.body;
this.levels.currentFocusedElement.children = children;
this.levels.currentFocusedElement.open = true;
this.levels.currentFocusedElement.selected = true;
const curModel = {
children: [this.levels.currentFocusedElement],
isRoot: true
};
this.filteredModels = Object.assign({}, curModel);
this.levels.current = 1;
});
}else{
this.resources.tree
.getFolder(
this.levels.currentFocusedElement.id
)
.pipe(
catchError((error) => {
this.messageHandler.showError(
'There was a problem focusing the tree element.',
error
);
return EMPTY;
}),
finalize(() => (this.reloading = false))
)
.subscribe((response: MdmTreeItemListResponse) => {
const children = response.body;
this.levels.currentFocusedElement.children = children;
this.levels.currentFocusedElement.open = true;
this.levels.currentFocusedElement.selected = true;
const curModel = {
children: [this.levels.currentFocusedElement],
isRoot: true
};
this.filteredModels = Object.assign({}, curModel);
this.levels.current = 1;
});
}
}
}
};
private unsubscribe$ = new Subject();
constructor(
private sharedService: SharedService,
private validator: ValidatorService,
private stateHandler: StateHandlerService,
private resources: MdmResourcesService,
private title: Title,
private securityHandler: SecurityHandlerService,
private broadcast: BroadcastService,
private userSettingsHandler: UserSettingsHandlerService,
protected messageHandler: MessageHandlerService,
public dialog: MatDialog,
private modelTree: ModelTreeService
) {}
ngOnInit() {
this.title.setTitle('Models');
if (this.sharedService.isLoggedIn()) {
this.includeModelSuperseded =
this.userSettingsHandler.get('includeModelSuperseded') || false;
this.showSupersededModels =
this.userSettingsHandler.get('showSupersededModels') || false;
this.includeDeleted =
this.userSettingsHandler.get('includeDeleted') || false;
}
if (
this.sharedService.searchCriteria &&
this.sharedService.searchCriteria.length > 0
) {
this.formData.filterCriteria = this.sharedService.searchCriteria;
}
this.initializeModelsTree();
this.broadcast
.onReloadCatalogueTree()
.pipe(takeUntil(this.unsubscribe$))
.subscribe(() => this.loadModelsTree(true));
this.broadcast
.onReloadClassificationTree()
.pipe(takeUntil(this.unsubscribe$))
.subscribe(() => this.loadClassifiers());
this.currentClassification = null;
this.allClassifications = [];
}
ngOnDestroy() {
if (this.subscriptions) {
this.subscriptions.unsubscribe();
}
this.unsubscribe$.next();
this.unsubscribe$.complete();
}
isLoggedIn() {
return this.sharedService.isLoggedIn();
}
tabSelected(tabIndex: number) {
switch (tabIndex) {
case 0: {
return (this.currentTab = 'models');
}
case 1: {
return (this.currentTab = 'classifications');
}
case 2: {
return (this.currentTab = 'favourites');
}
default: {
this.currentTab = 'models';
}
}
}
loadClassifiers() {
this.classifierLoading = true;
this.resources.classifier.list({ all: true }).subscribe(
(result: ClassifierIndexResponse) => {
const data = result.body.items;
this.allClassifiers = data;
data.forEach((classifier) => {
classifier.domainType = CatalogueItemDomainType.Classifier;
});
this.classifiers = {
children: data,
isRoot: true
};
this.classifierLoading = false;
},
() => {
this.classifierLoading = false;
}
);
}
loadModelsTree(noCache?: boolean) {
this.reloading = true;
// Fetch tree information from two potential sources - local folder tree and possible (external)
// subscribed catalogues
//
// Fetch one resource at a time to avoid any 404s
this.modelTree
.getLocalCatalogueTreeNodes(noCache)
.pipe(
catchError((error) => {
this.messageHandler.showError(
'There was a problem loading the model tree.',
error
);
return EMPTY;
}),
switchMap((local) => {
return this.modelTree.getSubscribedCatalogueTreeNodes().pipe(
map((subscribed) => {
if ((subscribed?.length ?? 0) === 0) {
// Display only local catalogue folders/models
return this.modelTree.createRootNode(local);
}
// Combine sub tree nodes with new parent nodes to build up roots
const localParent = this.modelTree.createLocalCatalogueNode(
local
);
const externalParent = this.modelTree.createExternalCataloguesNode(
subscribed
);
return this.modelTree.createRootNode([
localParent,
externalParent
]);
}),
catchError(() => {
this.messageHandler.showWarning(
'There was a problem loading the model tree with subscribed catalogues. Showing only local instance models.'
);
// Display only local catalogue folders/models
return of(this.modelTree.createRootNode(local));
})
);
}),
finalize(() => (this.reloading = false))
)
.subscribe((node) => {
this.allModels = node;
this.filteredModels = node;
});
}
onNodeConfirmClick($event: NodeConfirmClickEvent) {
const node = $event.next.node;
this.stateHandler
.Go(node.domainType, {
id: node.id,
edit: false,
dataModelId: node.modelId,
dataClassId: node.parentId || '',
terminologyId: node.modelId,
parentId: node.parentId
})
.then(
() => $event.setSelectedNode($event.next),
() => $event.setSelectedNode($event.current)
);
}
onNodeDbClick(node: MdmTreeItem) {
if (
isContainerDomainType(node.domainType) ||
node.domainType === CatalogueItemDomainType.DataModel ||
node.domainType === CatalogueItemDomainType.Terminology
) {
this.levels.focusTreeItem(node);
}
}
onNodeAdded() {
this.loadModelsTree();
}
loadModelsToCompare(dataModel: DataModel) {
this.resources.catalogueItem
.listSemanticLinks(dataModel.domainType, dataModel.id, { all: true })
.subscribe((result) => {
const compareToList = [];
const semanticLinks = result.body;
semanticLinks.items.forEach((link) => {
if (
['Superseded By', 'New Version Of'].indexOf(link.linkType) !== -1 &&
link.source.id === dataModel.id
) {
compareToList.push(link.target);
}
});
});
}
onFolderAddModal() {
this.modelTree
.createNewFolder({ allowVersioning: true })
.pipe(
catchError((error) => {
this.messageHandler.showError(
'There was a problem creating the Folder.',
error
);
return EMPTY;
})
)
.subscribe((response) => {
const item = response.body;
this.filteredModels.children.push(item);
this.stateHandler.Go(item.domainType, { id: item.id, edit: false });
this.messageHandler.showSuccess(
`Folder ${item.label} created successfully.`
);
this.folder = '';
this.loadModelsTree();
});
}
toggleFilterMenu() {
this.showFilters = !this.showFilters;
}
toggleFilters(filerName: string) {
this[filerName] = !this[filerName];
this.reloading = true;
if (this.sharedService.isLoggedIn()) {
this.userSettingsHandler.update(
'includeModelSuperseded',
this.includeModelSuperseded
);
this.userSettingsHandler.update(
'showSupersededModels',
this.showSupersededModels
);
this.userSettingsHandler.update('includeDeleted', this.includeDeleted);
this.userSettingsHandler.saveOnServer();
}
this.loadModelsTree();
this.showFilters = !this.showFilters;
}
initializeModelsTree() {
this.loadModelsTree();
this.loadClassifiers();
}
changeState(newState: string, type?: string, newWindow?: boolean) {
if (newWindow) {
this.stateHandler.NewWindow(newState);
return;
}
if (newState) {
if (newState === 'import') {
this.stateHandler.Go(newState, { importType: type });
} else if (newState === 'export') {
this.stateHandler.Go(newState, { exportType: type });
}
return;
}
this.stateHandler.Go(newState);
}
onSearchInputKeyDown(event: KeyboardEvent | InputEvent) {
// Initialize debounce listener if necessary
if (!this.debounceInputEvent) {
this.debounceInputEvent = new Subject<KeyboardEvent | InputEvent>();
this.subscriptions = this.debounceInputEvent
.pipe(debounceTime(300))
.subscribe((e) => {
if (e instanceof KeyboardEvent) {
switch (e.key) {
case 'Enter':
this.search();
return;
case 'Escape':
this.formData.filterCriteria = '';
this.search();
this.searchboxFocused = false;
return;
}
}
if (this.formData.filterCriteria?.length > 2) {
this.search();
}
if (this.validator.isEmpty(this.formData.filterCriteria)) {
this.search();
}
});
}
event.preventDefault();
event.stopPropagation();
this.debounceInputEvent.next(event);
return false;
}
search() {
if (this.formData.filterCriteria?.trim().length > 2) {
this.formData.ClassificationFilterCriteria = '';
this.sharedService.searchCriteria = this.formData.filterCriteria;
this.reloading = true;
this.inSearchMode = true;
this.allModels = null;
this.resources.tree
.search(ContainerDomainType.Folders, this.sharedService.searchCriteria)
.subscribe((res) => {
const result: MdmTreeItem[] = res.body;
this.reloading = false;
this.allModels = {
id: '',
domainType: CatalogueItemDomainType.Root,
children: result,
hasChildren: true,
isRoot: true,
availableActions: []
};
this.filteredModels = Object.assign({}, this.allModels);
this.searchText = this.formData.filterCriteria;
});
} else {
this.inSearchMode = false;
this.sharedService.searchCriteria = '';
this.searchText = '';
this.loadModelsTree();
}
}
classifierTreeOnSelect(node: MdmTreeItem) {
this.stateHandler.Go('classification', { id: node.id });
}
classificationFilterChange(val: string) {
if (val && val.length !== 0 && val.trim().length === 0) {
this.filterClassifications();
} else {
this.loadClassifiers();
}
}
filterClassifications() {
if (this.formData.ClassificationFilterCriteria.length > 0) {
this.formData.filterCriteria = '';
this.sharedService.searchCriteria = this.formData.ClassificationFilterCriteria;
} else {
this.loadClassifiers();
}
}
onFavouriteDbClick(node: MdmTreeItem) {
this._onFavouriteClick(node);
}
onFavouriteClick(node: MdmTreeItem) {
this._onFavouriteClick(node);
}
reloadTree() {
this.loadModelsTree(true);
}
onAddClassifier() {
this.modelTree
.createNewClassifier()
.pipe(
catchError((error) => {
this.messageHandler.showError(
'Classification name can not be empty',
error
);
return EMPTY;
})
)
.subscribe((response) => {
this.messageHandler.showSuccess('Classifier saved successfully.');
this.stateHandler.Go('classification', { id: response.body.id });
this.loadClassifiers();
});
}
private _onFavouriteClick(node: MdmTreeItem) {
this.stateHandler.Go(node.domainType, {
id: node.id
});
}
}
|
//如何创建一个http服务器
//http服务器是继承自tcp服务器 http协议是应用层协议,是基于TCP的。
//对请求和响应进行了包装
let http = require('http');
//req 流对象 是可读流
//res 是一个可写流 write
//发消息就等于客户端连接吗?不等于,当客户端连接上来之后先触发connection事件,
//然后可以多次发送请求,每次请求都会触发request事件。
let server = http.createServer();
let url = require('url');
//当客户端连接上服务器之后执行回调
server.on('connection', function (socket) {
console.log('客户端连接 ');
});
//服务器监听客户端的请求,当有请求到来的时候执行回调
/**
> POST / HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.53.0
> Accept: *
> Content-Length: 9
> Content-Type: application/x-www-form-urlencoded
>
} [9 bytes data]
*/
//req代表客户端的连接,server服务器把客户端的请求信息进行解析,然后放在req上面
//res代表响应,如果希望向客户端回应消息,需要通过 res
server.on('request', function (req, res) {
console.log(req.method);//获取请求方法名
let { pathname, query } = url.parse(req.url, true);
console.log(pathname);
console.log(query);
console.log(req.url);//获取请求路径
console.log(req.headers);//请求头对象
let result = [];
req.on('data', function (data) {
result.push(data);
});
req.on('end', function () {
let r = Buffer.concat(result);//请求体
console.log(r.toString());
//如果进行响应
res.end(r);
})
});
server.on('close', function (req, res) {
console.log('服务器关闭 ');
});
server.on('error', function (err) {
console.log('服务器错误 ');
});
server.listen(8080, function () {
console.log('server started at http://localhost:8080');
}); |
<gh_stars>100-1000
/*
* Copyright (C) 2012 Sony Mobile Communications AB
*
* This file is part of ApkAnalyser.
*
* 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 analyser.gui;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.HeadlessException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class SettingsDialog extends JDialog {
private static final long serialVersionUID = -4743615594951389745L;
MainFrame mainFrame;
JPanel mainPanel;
JTextField ejava;
JTextField adb;
public SettingsDialog(MainFrame owner, String title) throws HeadlessException
{
super(owner, title);
mainFrame = owner;
initGui();
}
void initGui() {
mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout());
JPanel allPanel = new JPanel();
allPanel.setLayout(new GridLayout(2, 0));
JPanel contPanel = new JPanel();
contPanel.setBorder(BorderFactory.createTitledBorder("Midlet settings"));
contPanel.setLayout(new GridLayout(2, 0, 4, 4));
ejava = new JTextField();
contPanel.add(new JLabel("ejava executable:"));
ejava.setText(Settings.getEjavaPath());
contPanel.add(getBrowseFieldPanel(ejava, "exe", "*.exe (ejava executable)"));
JPanel contAndroidPanel = new JPanel();
contAndroidPanel.setBorder(BorderFactory.createTitledBorder("Android settings"));
contAndroidPanel.setLayout(new GridLayout(2, 0, 4, 4));
adb = new JTextField();
contAndroidPanel.add(new JLabel("adb executable:"));
adb.setText(Settings.getAdbPath());
contAndroidPanel.add(getBrowseFieldPanel(adb, "exe", "*.exe (adb executable)"));
//allPanel.add(contPanel);
allPanel.add(contAndroidPanel);
mainPanel.add(allPanel, BorderLayout.NORTH);
JPanel bPanel = new JPanel();
bPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
JButton okBut = new JButton("OK");
JButton cancelBut = new JButton("Cancel");
bPanel.add(okBut);
bPanel.add(cancelBut);
mainPanel.add(bPanel, BorderLayout.SOUTH);
okBut.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
apply();
close();
}
});
cancelBut.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
close();
}
});
getContentPane().setLayout(new BorderLayout());
getContentPane().add(mainPanel, BorderLayout.CENTER);
}
void apply() {
Settings.setEjavaPath(ejava.getText());
Settings.setAdbPath(adb.getText());
}
void close() {
dispose();
}
JPanel getBrowseFieldPanel(final JTextField tf, final String filter, final String filterDesc) {
JPanel p = new JPanel();
p.setLayout(new BorderLayout());
p.add(tf, BorderLayout.CENTER);
JButton browseBut = new JButton("...");
p.add(browseBut, BorderLayout.EAST);
browseBut.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
File f = mainFrame.selectFile("Select file", "OK", filter, filterDesc);
if (f != null) {
tf.setText(f.getAbsolutePath());
}
}
});
return p;
}
}
|
<filename>plugin/src/com/microsoft/alm/plugin/idea/git/utils/GeneralGitHelper.java
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See License.txt in the project root.
package com.microsoft.alm.plugin.idea.git.utils;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vcs.VcsException;
import git4idea.GitBranch;
import git4idea.GitRevisionNumber;
import git4idea.repo.GitRepository;
import org.jetbrains.annotations.NotNull;
/**
* General helper class for Git functionality using Git4idea
*/
public class GeneralGitHelper {
/**
* Get the hash associated with the last commit on a branch
*
* @param project
* @param gitRepository
* @param branch
* @return
* @throws VcsException
*/
public static String getLastCommitHash(@NotNull final Project project, @NotNull final GitRepository gitRepository,
@NotNull final GitBranch branch) throws VcsException {
try {
GitRevisionNumber revision = GitRevisionNumber.resolve(project, gitRepository.getRoot(), branch.getName());
return revision.asString();
} catch (VcsException e) {
throw new VcsException(e.getCause());
}
}
}
|
#!/bin/bash
########################################################################
# Test STMP info
# Part of mailsend-go muquit@muquit.com
########################################################################
readonly DIR=$(dirname $0)
source ${DIR}/env.txt
$MAILSEND -info -smtp $SMTP_SERVER -port $TLS_PORT
$MAILSEND -info -smtp $SMTP_SERVER -port $SSL_PORT -ssl
|
const DarkMode = {
init({ toggle, currentTheme }) {
toggle.addEventListener('click', (event) => {
this._toggleSwitch(event);
});
if (currentTheme) {
document.documentElement.setAttribute('data-theme', currentTheme);
}
},
_toggleSwitch(e) {
e.stopPropagation();
const cekTheme = (event) =>
event.target.classList.value === 'light' || event.path[1].classList.value === 'light';
if (cekTheme(e)) {
document.documentElement.setAttribute('data-theme', 'dark');
e.target.classList.remove('light');
e.target.classList.add('dark');
e.path[1].classList.remove('light');
e.path[1].classList.add('dark');
localStorage.setItem('theme', 'dark');
} else {
document.documentElement.setAttribute('data-theme', 'light');
e.target.classList.remove('dark');
e.target.classList.add('light');
e.path[1].classList.remove('dark');
e.path[1].classList.add('light');
localStorage.setItem('theme', 'light');
}
},
};
export default DarkMode;
|
'use strict'
// http://localhost:7651
// https://discordapp.com/oauth2/authorize?&client_id=199938847948275714&scope=bot
const _ = require('lodash-fp')
const pathJoin = require('path').join
// const ChildProcess = require('child_process')
const discord = require('discord.js')
const tldr = require('tldr/lib/index')
const cache = require('tldr/lib/cache')
const parser = require('tldr/lib/parser')
const render = require('tldr/lib/render')
const google = require('google')
const ImagesClient = require('google-images')
const googleImage = new ImagesClient('013192016961491793777:da5hivxkymw',
'<KEY>')
const updateCache = () => cache.update(err => err
&& setTimeout(updateCache, 60000))
setInterval(updateCache, 3*24*60*60*1000)
const printBestPage = command => {
const content = cache.getPage(command)
if (!content) return 'command not found'
let i = 0
const total = []
while (i < content.length) {
const pos = content.indexOf('\n> ', i)
if (pos === -1) {
total.push(content.slice(i, content.length))
break
}
total.push(content.slice(i, pos))
i = content.indexOf('\n', pos + 3)
if (i === -1) i = content.length
total.push(`\n*${content.slice(pos + 3, i)}*`)
}
return total.filter(Boolean).join('')
.replace(/\n`/g, '\n```handlebars\n')
.replace(/`\n/g, '```\n')
}
const config = {
botToken: '<PASSWORD>0OTYx.CnZYZw.yYQ6rwJZyvpXQYXvXQ-R-FX1TQU',
self: '199939097140264961',
}
const bot = new discord.Client()
bot.loginWithToken(config.botToken)
const voices = {}
const getVoiceConnection = voiceChannel =>
voices[voiceChannel]
|| (voices[voiceChannel] = bot.joinVoiceChannel(voiceChannel))
const not = fn => v => !fn(v)
const filters = {
self: msg => msg.author.id === config.self,
userVoice: msg => msg.author.voiceChannel,
voice: msg => bot.voiceConnection,
}
let throttle = 0
const playSound = filename => ({
if: [ filters.voice, not(filters.self) ],
action: msg => //throttle
// ? msg.reply('antiflood dsl mon bichon')
getVoiceConnection(msg.author.voiceChannel)
.then(channel => {
console.log('wololo')
// throttle = setTimeout(() => throttle = 0, 3000)
return channel.playFile(pathJoin(__dirname, filename))
})
.catch(err => msg.reply(wesh(err)))
})
const actions = {
wesh: { action: msg => bot.reply(msg, 'wesh') },
yo: { action: msg => bot.reply(msg, 'bien ou bien ?') },
stop: {
if: [ filters.voice, not(filters.self) ],
action: msg => bot.voiceConnection.stopPlaying(),
},
volume: {
if: [ filters.voice, not(filters.self) ],
action: (msg, args) => bot.voiceConnection.setVolume(parseFloat(args)),
},
cheer: playSound('international.mp3'),
balek: playSound('balek.mp3'),
help: {
action: msg => msg.reply(`Available commands: man, js, css, google, !${Object.keys(actions).join(', !')}`)
},
}
const parseTxt = txt => {
const idx = txt.indexOf(' ')
if (idx < 0) {
return [ txt.slice(1), '' ]
}
return [ txt.slice(1, idx), txt.slice(idx).trim() ]
}
const wesh = _ => (console.log(_), _)
const toTest = rgx => RegExp.prototype.test.bind(rgx)
const isCmd = toTest(/^(man|tldr) \S/i)
const isJs = toTest(/^js \S/i)
const isNode = RegExp.prototype.test.bind(/^node \S/i)
const isCss = RegExp.prototype.test.bind(/^css \S/i)
const isGoogle = RegExp.prototype.test.bind(/^google \S/)
const isImg = RegExp.prototype.test.bind(/^image \S/)
const isNpm = RegExp.prototype.test.bind(/^npm \S/)
const isCaniuse = RegExp.prototype.test.bind(/^caniuse \S/)
const mapLink = l => l.link
const notW3School = url => url
&& url.indexOf('w3schools.') === -1
&& url.indexOf('davidwalsh.name') === -1
const noResult = 'No results, have some :pizza: instead'
const getLink = res => (res && res.links.length)
? res.links.map(mapLink).filter(notW3School)[0]
: noResult
bot.on('message', msg => {
const txt = msg.content
if (isGoogle(txt)) return google(txt.slice(7), (err, res) => err
? msg.reply(err.message.slice(2000)).catch(wesh)
: msg.reply(getLink(res)))
if (isJs(txt)) return google(wesh(`site:developer.mozilla.org javascript ${txt.slice(3)}`),
(err, res) => msg.reply(getLink(res)))
if (isCss(txt)) return google(wesh(`site:developer.mozilla.org css ${txt.slice(4)}`),
(err, res) => msg.reply(getLink(res)))
if (isImg(txt)) return googleImage.search(`${txt.slice(6)}`)
.then(img => img.length ? msg.reply(img[0].url) : msg.reply(noResult))
if (isNode(txt)) return google(wesh(`site:nodejs.org/api/ ${txt.slice(5)}`),
(err, res) => msg.reply(getLink(res)))
if (isNpm(txt)) return google(wesh(`site:nodejs.org/api/ ${txt.slice(5)}`),
(err, res) => msg.reply(getLink(res)))
if (isCaniuse(txt)) return google(wesh(`caniuse ${txt.slice(4)}`),
(err, res) => msg.reply(getLink(res)))
if (isCmd(txt)) return msg.reply(printBestPage(txt.split(' ')[1])).catch(console.dir)
if (txt[0] !== '!') return
const [ key, args ] = parseTxt(txt)
console.log({ key, args })
const match = actions[key]
if (!match) return
if (match.if) {
for (let f of match.if) {
if (!f(msg)) return
}
}
match.action(msg, args, key)
})
|
<reponame>rcarlosdasilva/weixin
package io.github.rcarlosdasilva.weixin.core.exception;
public class CanNotFetchOpenPlatformAccessTokenException extends RuntimeException {
private static final long serialVersionUID = 9210125893488536696L;
}
|
package io.opensphere.csvcommon.detect.location.format;
import java.util.List;
import io.opensphere.core.model.LatLonAlt.CoordFormat;
import io.opensphere.core.model.LatLonAltParser;
import io.opensphere.core.util.lang.Pair;
import io.opensphere.csvcommon.detect.location.model.LatLonColumnResults;
import io.opensphere.csvcommon.detect.location.model.LocationResults;
import io.opensphere.csvcommon.detect.location.model.PotentialLocationColumn;
import io.opensphere.importer.config.ColumnType;
/**
* The LocationFormatDetector will attempt to parse sample values for location
* data and try to determine if the existing formats are valid. It will keep
* track of the number of valid formats in the sample data and use this to
* adjust the overall column confidence. If the column is valid but there is no
* valid data, the confidence should be scored as a 0 and removed from the
* result set.
*/
public class LocationFormatDetector
{
/**
* Detect data formats.
*
* @param locationResults the location results to check
* @param rows the sample data set to check formats for
*/
public void detectLocationColumnFormats(LocationResults locationResults, List<? extends List<? extends String>> rows)
{
checkLatLonFormats(locationResults, rows, locationResults.getLatLonResults());
checkLocationFormats(locationResults, rows, locationResults.getLocationResults());
updateLocationFormats(locationResults);
}
/**
* Check location formats.
*
* @param locationResults the location results
* @param rows the rows
* @param locResults the loc results
*/
private void checkLocationFormats(LocationResults locationResults, List<? extends List<? extends String>> rows,
List<PotentialLocationColumn> locResults)
{
for (int i = locResults.size() - 1; i >= 0; i--)
{
int emptyCells = 0;
int successCount = 0;
PotentialLocationColumn potential = locResults.get(i);
for (List<? extends String> row : rows)
{
String cellValue = row.get(potential.getColumnIndex());
if (cellValue.length() > 0)
{
switch (potential.getType())
{
case POSITION:
if ("(".equals(String.valueOf(cellValue.charAt(0))) && cellValue.endsWith(")"))
{
cellValue = cellValue.substring(1, cellValue.length() - 1).trim();
}
Pair<CoordFormat, CoordFormat> formatType = LatLonAltParser.getLatLonFormat(cellValue);
if (formatType != null)
{
if (formatType.getFirstObject() != null && formatType.getSecondObject() != null)
{
successCount++;
}
potential.setLatFormat(formatType.getFirstObject());
potential.setLonFormat(formatType.getSecondObject());
}
break;
case MGRS:
if (LocationFormatter.validateMGRS(cellValue))
{
potential.setLocationFormat(CoordFormat.MGRS);
successCount++;
}
break;
case WKT_GEOMETRY:
if (LocationFormatter.validateWKTGeometry(cellValue))
{
potential.setLocationFormat(CoordFormat.WKT_GEOMETRY);
successCount++;
}
break;
case LAT:
case LON:
successCount++;
break;
default:
break;
}
}
else
{
emptyCells++;
}
}
float confidence = 0;
float rowCount = rows.size();
if (rowCount - emptyCells > 0)
{
confidence = successCount / (rowCount - emptyCells) * potential.getConfidence();
}
if (confidence > 0)
{
potential.setConfidence(confidence);
}
else
{
locationResults.removeLocationColumn(potential);
}
}
}
/**
* Check lat lon formats.
*
* @param locationResults the location results
* @param rows the rows
* @param latLonResults the lat lon results
*/
private void checkLatLonFormats(LocationResults locationResults, List<? extends List<? extends String>> rows,
List<LatLonColumnResults> latLonResults)
{
int rowCount = rows.size();
for (int i = latLonResults.size() - 1; i >= 0; i--)
{
int emptyCells = 0;
int successCount1 = 0;
int successCount2 = 0;
LatLonColumnResults potential = latLonResults.get(i);
for (List<? extends String> row : rows)
{
String lat = row.get(potential.getLatColumn().getColumnIndex());
String lon = row.get(potential.getLonColumn().getColumnIndex());
if (lat.length() > 0 && lon.length() > 0)
{
Pair<CoordFormat, CoordFormat> formatType = LatLonAltParser.getLatLonFormat(lat + " " + lon);
if (formatType != null)
{
if (formatType.getFirstObject() != null)
{
successCount1++;
}
if (formatType.getSecondObject() != null)
{
successCount2++;
}
potential.getLatColumn().setLatFormat(formatType.getFirstObject());
potential.getLonColumn().setLonFormat(formatType.getSecondObject());
}
}
else
{
emptyCells++;
}
}
setConfidences(locationResults, rowCount, emptyCells, successCount1, successCount2, potential);
}
}
/**
* Sets the confidences.
*
* @param locationResults the location results
* @param rows the number of rows
* @param emptyCells the empty cells
* @param successCount1 the success count1
* @param successCount2 the success count2
* @param potential the potential
*/
private void setConfidences(LocationResults locationResults, int rows, int emptyCells,
int successCount1, int successCount2, LatLonColumnResults potential)
{
float rowCount = rows;
float confidence1 = (successCount1 / rowCount + potential.getConfidence()) / 2.0f;
float confidence2 = (successCount2 / rowCount + potential.getConfidence()) / 2.0f;
if (confidence1 > 0 && confidence2 > 0 && !Float.isInfinite(confidence1) && !Float.isInfinite(confidence2))
{
if (Math.abs(confidence1 - confidence2) == 0.)
{
potential.setConfidence(confidence1);
}
else
{
potential.setConfidence(confidence1 + confidence2 / 2.0f);
potential.getLatColumn().setConfidence(confidence1);
potential.getLonColumn().setConfidence(confidence2);
}
}
else
{
locationResults.removeLatLonResult(potential);
}
}
/**
* If there are results whose formats were not detected, set them to
* unknown. This could happen in files where all sample rows have no data.
*
* @param locationResults the location results
*/
private void updateLocationFormats(LocationResults locationResults)
{
for (LatLonColumnResults llcr : locationResults.getLatLonResults())
{
if (llcr.getLatColumn().getLatFormat() == null)
{
llcr.getLatColumn().setLatFormat(CoordFormat.UNKNOWN);
}
if (llcr.getLonColumn().getLonFormat() == null)
{
llcr.getLonColumn().setLonFormat(CoordFormat.UNKNOWN);
}
}
for (PotentialLocationColumn plc : locationResults.getLocationResults())
{
if (plc.getLatFormat() == null && plc.getType().equals(ColumnType.LAT))
{
plc.setLatFormat(CoordFormat.UNKNOWN);
}
if (plc.getLonFormat() == null && plc.getType().equals(ColumnType.LON))
{
plc.setLonFormat(CoordFormat.UNKNOWN);
}
if (plc.getLocationFormat() == null && (plc.getType().equals(ColumnType.LAT) || plc.getType().equals(ColumnType.LON)))
{
plc.setLocationFormat(CoordFormat.UNKNOWN);
}
}
}
}
|
<gh_stars>0
package authoring.panels.attributes;
/**Allows users to change a String Field
* @author lasia
*
*/
public class StringInputField extends InputField {
public StringInputField(Setter set) {
super(set);
}
@Override
protected void updateField() {
String text = getTextField().textProperty().getValue();
setValue(text);
}
protected void getDefaultValue() {
String defaultText = (String) getValue();
getTextField().setText(defaultText);
}
} |
import assert from 'assert';
import 'jsdom-global/register';
import makeResources from './helperCreateResources.js';
import Container from '../../../src/meteoJS/modelviewer/Container.js';
import Display from '../../../src/meteoJS/modelviewer/Display.js';
import Modelviewer from '../../../src/meteoJS/Modelviewer.js';
describe('Simple modelviewer setup', () => {
// Create objects
let resources = makeResources();
let containersNode = document.createElement('div');
let modelviewer = new Modelviewer({ resources, containersNode });
modelviewer.append(
new Container(),
new Container(),
new Container()
);
// Create resources
/* intentionally after creating objects. In real world, the resources are
* loaded, after the objects are created. */
resources.getNodeByVariableCollectionId('models').variableCollection.variables.forEach(model => {
resources.getNodeByVariableCollectionId('runs').variableCollection.variables.forEach(run => {
resources.getNodeByVariableCollectionId('fields').variableCollection.variables.forEach(field => {
resources.getNodeByVariableCollectionId('levels').variableCollection.variables.forEach(level => {
if (level.id == '10m' &&
field.id != 'wind')
return;
[...Array(25).keys()].map(offset => { return offset*3*3600; })
.forEach(offset => {
if (field.id == 'geopotential' &&
(offset/3600) % 6 != 0)
return;
resources.appendImage({
variables: [model, run, field, level],
run: run.datetime,
offset
});
});
});
});
});
});
// Testing
}); |
import React from 'react'
import Hero from './hero'
import renderer from 'react-test-renderer'
test('renders hero', () => {
const tree = renderer.create(<Hero />).toJSON()
expect(tree).toMatchSnapshot()
})
test('renders hero with title and brand', () => {
const tree = renderer.create(<Hero title='bacon' brand='https://image.png' />).toJSON()
expect(tree).toMatchSnapshot()
})
|
import UIKit
class HomeViewController: UIViewController {
@IBOutlet weak var budgetLabel: UILabel!
@IBOutlet weak var remainingLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
let budget = 200
let spent = 150
budgetLabel.text = "Total Budget: \(budget)"
remainingLabel.text = "Remaining Budget: \(budget - spent)"
}
} |
#!/bin/bash
set -x
kubectl delete --ignore-not-found=true svc,pvc,deployment -l app=wordpress
kubectl delete --ignore-not-found=true secret mysql-pass
kubectl delete --ignore-not-found=true -f local-volumes.yaml
kuber=$(kubectl get pods -l app=wordpress)
if [ ${#kuber} -ne 0 ]; then
sleep 120s
fi
echo 'newpassword' > password.txt
tr -d '\n' <password.txt >.strippedpassword.txt && mv .strippedpassword.txt password.txt
kubectl create -f local-volumes.yaml
kubectl create secret generic mysql-pass --from-file=password.txt
kubectl create -f mysql-deployment.yaml
kubectl create -f wordpress-deployment.yaml
kubectl get pods
kubectl get nodes
kubectl get svc wordpress
kubectl get deployments
kubectl scale deployments/wordpress --replicas=2
|
<reponame>thehyve/genetics-sumstat-data
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# <NAME>
import sys
def main():
header = []
# Read stdin
for line in sys.stdin:
header.append(line.rstrip())
# Write as single line
sys.stdout.write('\t'.join(header) + '\n')
if __name__ == '__main__':
main()
|
<filename>src/main/java/org/olat/commons/info/ui/InfoEditFormController.java
/**
* <a href="http://www.openolat.org">
* OpenOLAT - Online Learning and Training</a><br>
* <p>
* Licensed under the Apache License, Version 2.0 (the "License"); <br>
* you may not use this file except in compliance with the License.<br>
* You may obtain a copy of the License at the
* <a href="http://www.apache.org/licenses/LICENSE-2.0">Apache homepage</a>
* <p>
* Unless required by applicable law or agreed to in writing,<br>
* software distributed under the License is distributed on an "AS IS" BASIS, <br>
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <br>
* See the License for the specific language governing permissions and <br>
* limitations under the License.
* <p>
* Initial code contributed and copyrighted by<br>
* frentix GmbH, http://www.frentix.com
* <p>
*/
package org.olat.commons.info.ui;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.olat.commons.info.InfoMessage;
import org.olat.commons.info.InfoMessageFrontendManager;
import org.olat.core.commons.modules.bc.FileUploadController;
import org.olat.core.gui.UserRequest;
import org.olat.core.gui.components.form.flexible.FormItem;
import org.olat.core.gui.components.form.flexible.FormItemContainer;
import org.olat.core.gui.components.form.flexible.elements.FileElement;
import org.olat.core.gui.components.form.flexible.elements.FormLink;
import org.olat.core.gui.components.form.flexible.elements.RichTextElement;
import org.olat.core.gui.components.form.flexible.elements.TextElement;
import org.olat.core.gui.components.form.flexible.impl.Form;
import org.olat.core.gui.components.form.flexible.impl.FormBasicController;
import org.olat.core.gui.components.form.flexible.impl.FormEvent;
import org.olat.core.gui.components.form.flexible.impl.FormLayoutContainer;
import org.olat.core.gui.components.link.Link;
import org.olat.core.gui.control.Controller;
import org.olat.core.gui.control.WindowControl;
import org.olat.core.gui.util.CSSHelper;
import org.olat.core.util.FileUtils;
import org.olat.core.util.Formatter;
import org.olat.core.util.StringHelper;
import org.olat.core.util.Util;
import org.olat.core.util.ValidationStatus;
import org.olat.core.util.vfs.VFSLeaf;
import org.olat.modules.co.ContactForm;
import org.springframework.beans.factory.annotation.Autowired;
/**
*
* Description:<br>
*
* <P>
* Initial Date: 26 jul. 2010 <br>
* @author srosse, <EMAIL>, http://www.frentix.com
*/
public class InfoEditFormController extends FormBasicController {
private static final int MESSAGE_MAX_LENGTH = 32000;
private static final String NLS_CONTACT_ATTACHMENT = "contact.attachment";
private static final String NLS_CONTACT_ATTACHMENT_EXPL = "contact.attachment.maxsize";
private TextElement titleEl;
private FileElement attachmentEl;
private RichTextElement messageEl;
private String attachmentPath;
private Set<String> attachmentPathToDelete = new HashSet<>();
private File attachementTempDir;
private long attachmentSize = 0l;
private int contactAttachmentMaxSizeInMb = 5;
private List<FormLink> attachmentLinks = new ArrayList<>();
private FormLayoutContainer uploadCont;
private Map<String,String> attachmentCss = new HashMap<>();
private Map<String,String> attachmentNames = new HashMap<>();
private final boolean showTitle;
private final InfoMessage infoMessage;
@Autowired
private InfoMessageFrontendManager infoMessageManager;
public InfoEditFormController(UserRequest ureq, WindowControl wControl, Form mainForm, boolean showTitle, InfoMessage infoMessage) {
super(ureq, wControl, LAYOUT_DEFAULT, null, mainForm);
this.showTitle = showTitle;
this.infoMessage = infoMessage;
this.attachmentPath = infoMessage.getAttachmentPath();
if (this.attachmentPath != null) {
attachementTempDir = FileUtils.createTempDir("attachements", null, null);
for (File file : infoMessageManager.getAttachmentFiles(infoMessage)) {
FileUtils.copyFileToDir(file, attachementTempDir, "Copy attachments to temp folder");
}
}
setTranslator(Util.createPackageTranslator(ContactForm.class, getLocale(), getTranslator()));
initForm(ureq);
}
@Override
protected void initForm(FormItemContainer formLayout, Controller listener, UserRequest ureq) {
formLayout.setElementCssClass("o_sel_info_form");
if(showTitle) {
setFormTitle("edit.title");
}
String title = infoMessage.getTitle();
titleEl = uifactory.addTextElement("info_title", "edit.info_title", 512, title, formLayout);
titleEl.setElementCssClass("o_sel_info_title");
titleEl.setMandatory(true);
String message = infoMessage.getMessage();
messageEl = uifactory.addRichTextElementForStringDataMinimalistic("edit.info_message", "edit.info_message", message, 18, 80,
formLayout, getWindowControl());
messageEl.getEditorConfiguration().setRelativeUrls(false);
messageEl.getEditorConfiguration().setRemoveScriptHost(false);
messageEl.getEditorConfiguration().enableCharCount();
messageEl.getEditorConfiguration().setPathInStatusBar(true);
messageEl.setMandatory(true);
messageEl.setMaxLength(MESSAGE_MAX_LENGTH);
String attachmentPage = Util.getPackageVelocityRoot(this.getClass()) + "/attachments.html";
uploadCont = FormLayoutContainer.createCustomFormLayout("file_upload_inner", getTranslator(), attachmentPage);
uploadCont.setRootForm(mainForm);
formLayout.add(uploadCont);
attachmentEl = uifactory.addFileElement(getWindowControl(), getIdentity(), "attachment", formLayout);
attachmentEl.setDeleteEnabled(true);
attachmentEl.setMaxUploadSizeKB(5000, "attachment.max.size", new String[] { "5000" });
attachmentEl.addActionListener(FormEvent.ONCHANGE);
if(infoMessage.getAttachmentPath() != null) {
for (VFSLeaf file : infoMessageManager.getAttachments(infoMessage)) {
attachmentSize += file.getSize();
FormLink removeFile = uifactory.addFormLink(file.getName(), "delete", null, uploadCont, Link.BUTTON_XSMALL);
removeFile.setIconLeftCSS("o_icon o_icon-fw o_icon_delete");
removeFile.setUserObject(file);
attachmentLinks.add(removeFile);
//pretty labels
uploadCont.setLabel(NLS_CONTACT_ATTACHMENT, null);
attachmentNames.put(file.getName(), file.getName() + " <span class='text-muted'>(" + Formatter.formatBytes(file.getSize()) + ")</span>");
attachmentCss.put(file.getName(), CSSHelper.createFiletypeIconCssClassFor(file.getName()));
}
uploadCont.contextPut("attachments", attachmentLinks);
uploadCont.contextPut("attachmentNames", attachmentNames);
uploadCont.contextPut("attachmentCss", attachmentCss);
attachmentEl.setLabel(null, null);
}
}
@Override
protected void doDispose() {
cleanUpAttachments();
super.doDispose();
}
@Override
protected void formOK(UserRequest ureq) {
//
}
@Override
protected void formInnerEvent(UserRequest ureq, FormItem source, FormEvent event) {
if(source == attachmentEl) {
String filename = attachmentEl.getUploadFileName();
if(attachementTempDir == null) {
attachementTempDir = FileUtils.createTempDir("attachements", null, null);
}
long size = attachmentEl.getUploadSize();
if(size + attachmentSize > (contactAttachmentMaxSizeInMb * 1024 * 1024)) {
showWarning(NLS_CONTACT_ATTACHMENT_EXPL, Integer.toString(contactAttachmentMaxSizeInMb));
attachmentEl.reset();
} else {
File attachment = attachmentEl.moveUploadFileTo(attachementTempDir);
// OO-48 somehow file-move can fail, check for it, display error-dialog if it failed
if(attachment == null){
attachmentEl.reset();
logError("Could not move contact-form attachment to " + attachementTempDir.getAbsolutePath(), null);
setTranslator(Util.createPackageTranslator(FileUploadController.class, getLocale(),getTranslator()));
showError("FileMoveCopyFailed","");
return;
}
attachmentEl.reset();
attachmentSize += size;
FormLink removeFile = uifactory.addFormLink(attachment.getName(), "delete", null, uploadCont, Link.BUTTON_XSMALL);
removeFile.setIconLeftCSS("o_icon o_icon-fw o_icon_delete");
removeFile.setUserObject(attachment);
attachmentLinks.add(removeFile);
//pretty labels
uploadCont.setLabel(NLS_CONTACT_ATTACHMENT, null);
attachmentNames.put(attachment.getName(), filename + " <span class='text-muted'>(" + Formatter.formatBytes(size) + ")</span>");
attachmentCss.put(attachment.getName(), CSSHelper.createFiletypeIconCssClassFor(filename));
uploadCont.contextPut("attachments", attachmentLinks);
uploadCont.contextPut("attachmentNames", attachmentNames);
uploadCont.contextPut("attachmentCss", attachmentCss);
attachmentEl.setLabel(null, null);
}
} else if (attachmentLinks.contains(source)) {
Object uploadedFile = source.getUserObject();
if (uploadedFile instanceof File) {
File file = (File) uploadedFile;
if(file.exists()) {
attachmentSize -= file.length();
attachmentPathToDelete.add(file.getName());
}
} else if (uploadedFile instanceof VFSLeaf) {
VFSLeaf leaf = (VFSLeaf) uploadedFile;
if(leaf.exists()) {
attachmentSize -= leaf.getSize();
attachmentPathToDelete.add(leaf.getName());
}
} else {
return;
}
attachmentLinks.remove(source);
uploadCont.remove(source);
if(attachmentLinks.isEmpty()) {
uploadCont.setLabel(null, null);
attachmentEl.setLabel(NLS_CONTACT_ATTACHMENT, null);
}
}
super.formInnerEvent(ureq, source, event);
}
@Override
protected boolean validateFormLogic(UserRequest ureq) {
titleEl.clearError();
messageEl.clearError();
boolean allOk = super.validateFormLogic(ureq);
String t = titleEl.getValue();
if(!StringHelper.containsNonWhitespace(t)) {
titleEl.setErrorKey("form.legende.mandatory", new String[] {});
allOk &= false;
} else if (t.length() > 500) {
titleEl.setErrorKey("input.toolong", new String[] {"500", Integer.toString(t.length())});
allOk &= false;
}
String m = messageEl.getValue();
if(!StringHelper.containsNonWhitespace(m)) {
messageEl.setErrorKey("form.legende.mandatory", new String[] {});
allOk &= false;
} else if (m.length() > MESSAGE_MAX_LENGTH) {
messageEl.setErrorKey("input.toolong", new String[] { Integer.toString(MESSAGE_MAX_LENGTH), Integer.toString(m.length()) });
allOk &= false;
}
List<ValidationStatus> validation = new ArrayList<>();
attachmentEl.validate(validation);
if(validation.size() > 0) {
allOk &= false;
}
return allOk;
}
public InfoMessage getInfoMessage() {
infoMessage.setTitle(titleEl.getValue());
infoMessage.setMessage(messageEl.getValue());
infoMessage.setAttachmentPath(attachmentPath);
return infoMessage;
}
public File getAttachements() {
return attachementTempDir;
}
public Collection<String> getAttachmentPathToDelete() {
return attachmentPathToDelete;
}
@Override
public FormLayoutContainer getInitialFormItem() {
return flc;
}
public void cleanUpAttachments() {
if(attachementTempDir != null && attachementTempDir.exists()) {
FileUtils.deleteDirsAndFiles(attachementTempDir, true, true);
attachementTempDir = null;
}
}
}
|
package core
// DxfElement is the common interface for all Dxf elements.
// Common operations should be part of this interface.
type DxfElement interface {
Equals(other DxfElement) bool
}
|
exports.sessionOptions = {
store: undefined,
secret: 'glint hint',
name: 'glint.sid',
cookie: {secure: false},
resave: false,
saveUninitialized: false
};
|
<reponame>Midiman/stepmania
// LanguagesDlg.cpp : implementation file
#define CO_EXIST_WITH_MFC
#include "global.h"
#include "stdafx.h"
#include "smpackage.h"
#include "Foreach.h"
#include "LanguagesDlg.h"
#include "SpecialFiles.h"
#include "RageUtil.h"
#include "IniFile.h"
#include "languagesdlg.h"
#include "SMPackageUtil.h"
#include "CreateLanguageDlg.h"
#include "RageFile.h"
#include "languagesdlg.h"
#include "RageFileManager.h"
#include ".\languagesdlg.h"
#include "CsvFile.h"
#include "archutils/Win32/DialogUtil.h"
#include "LocalizedString.h"
#include "arch/Dialog/Dialog.h"
#include "archutils/Win32/SpecialDirs.h"
#include "archutils/Win32/GotoURL.h"
#include "archutils/Win32/ErrorStrings.h"
// LanguagesDlg dialog
IMPLEMENT_DYNAMIC(LanguagesDlg, CDialog)
LanguagesDlg::LanguagesDlg(CWnd* pParent /*=NULL*/)
: CDialog(LanguagesDlg::IDD, pParent)
{
}
LanguagesDlg::~LanguagesDlg()
{
}
void LanguagesDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
DDX_Control(pDX, IDC_LIST_THEMES, m_listThemes);
DDX_Control(pDX, IDC_LIST_LANGUAGES, m_listLanguages);
DDX_Control(pDX, IDC_CHECK_EXPORT_ALREADY_TRANSLATED, m_buttonExportAlreadyTranslated);
}
BOOL LanguagesDlg::OnInitDialog()
{
CDialog::OnInitDialog();
DialogUtil::LocalizeDialogAndContents( *this );
vector<RString> vs;
GetDirListing( SpecialFiles::THEMES_DIR+"*", vs, true );
StripCvsAndSvn( vs );
FOREACH_CONST( RString, vs, s )
m_listThemes.AddString( *s );
if( !vs.empty() )
m_listThemes.SetSel( 0 );
OnSelchangeListThemes();
return TRUE; // return TRUE unless you set the focus to a control
}
static RString GetCurrentString( const CListBox &list )
{
// TODO: Add your control notification handler code here
int iSel = list.GetCurSel();
if( iSel == LB_ERR )
return RString();
CString s;
list.GetText( list.GetCurSel(), s );
return RString( s );
}
static void SelectString( CListBox &list, const RString &sToSelect )
{
for( int i=0; i<list.GetCount(); i++ )
{
CString s;
list.GetText( i, s );
if( s == sToSelect )
{
list.SetCurSel( i );
break;
}
}
}
void LanguagesDlg::OnSelchangeListThemes()
{
// TODO: Add your control notification handler code here
m_listLanguages.ResetContent();
RString sTheme = GetCurrentString( m_listThemes );
if( !sTheme.empty() )
{
RString sLanguagesDir = SpecialFiles::THEMES_DIR + sTheme + "/" + SpecialFiles::LANGUAGES_SUBDIR;
vector<RString> vs;
GetDirListing( sLanguagesDir+"*.ini", vs, false );
FOREACH_CONST( RString, vs, s )
{
RString sIsoCode = GetFileNameWithoutExtension(*s);
RString sLanguage = SMPackageUtil::GetLanguageDisplayString(sIsoCode);
m_listLanguages.AddString( ConvertUTF8ToACP(sLanguage) );
}
if( !vs.empty() )
m_listLanguages.SetSel( 0 );
}
OnSelchangeListLanguages();
}
static RString GetLanguageFile( const RString &sTheme, const RString &sLanguage )
{
return SpecialFiles::THEMES_DIR + sTheme + "/" + SpecialFiles::LANGUAGES_SUBDIR + sLanguage + ".ini";
}
static int GetNumValuesInIniFile( const RString &sIniFile )
{
int count = 0;
IniFile ini;
ini.ReadFile( sIniFile );
FOREACH_CONST_Child( &ini, key )
{
FOREACH_CONST_Attr( key, value )
count++;
}
return count;
}
static int GetNumIntersectingIniValues( const RString &sIniFile1, const RString &sIniFile2 )
{
int count = 0;
IniFile ini1;
ini1.ReadFile( sIniFile1 );
IniFile ini2;
ini2.ReadFile( sIniFile2 );
FOREACH_CONST_Child( &ini1, key1 )
{
const XNode *key2 = ini2.GetChild( key1->m_sName );
if( key2 == NULL )
continue;
FOREACH_CONST_Attr( key1, attr1 )
{
if( key2->GetAttr(attr1->first) == NULL)
continue;
count++;
}
}
return count;
}
void LanguagesDlg::OnSelchangeListLanguages()
{
// TODO: Add your control notification handler code here
int iTotalStrings = -1;
int iNeedTranslation = -1;
RString sTheme = GetCurrentString( m_listThemes );
RString sLanguage = GetCurrentString( m_listLanguages );
if( !sTheme.empty() )
{
RString sBaseLanguageFile = GetLanguageFile( sTheme, SpecialFiles::BASE_LANGUAGE );
iTotalStrings = GetNumValuesInIniFile( sBaseLanguageFile );
if( !sLanguage.empty() )
{
sLanguage = SMPackageUtil::GetLanguageCodeFromDisplayString( sLanguage );
RString sLanguageFile = GetLanguageFile( sTheme, sLanguage );
iNeedTranslation = iTotalStrings - GetNumIntersectingIniValues( sBaseLanguageFile, sLanguageFile );
}
}
GetDlgItem(IDC_STATIC_TOTAL_STRINGS )->SetWindowText( ssprintf(iTotalStrings==-1?"":"%d",iTotalStrings) );
GetDlgItem(IDC_STATIC_NEED_TRANSLATION )->SetWindowText( ssprintf(iNeedTranslation==-1?"":"%d",iNeedTranslation) );
GetDlgItem(IDC_BUTTON_CREATE)->EnableWindow( !sTheme.empty() );
GetDlgItem(IDC_BUTTON_DELETE)->EnableWindow( !sLanguage.empty() );
GetDlgItem(IDC_BUTTON_EXPORT)->EnableWindow( !sLanguage.empty() );
GetDlgItem(IDC_BUTTON_IMPORT)->EnableWindow( !sLanguage.empty() );
GetDlgItem(IDC_CHECK_LANGUAGE)->EnableWindow( !sLanguage.empty() );
GetDlgItem(IDC_CHECK_EXPORT_ALREADY_TRANSLATED)->EnableWindow( !sLanguage.empty() );
}
BEGIN_MESSAGE_MAP(LanguagesDlg, CDialog)
ON_LBN_SELCHANGE(IDC_LIST_THEMES, OnSelchangeListThemes)
ON_LBN_SELCHANGE(IDC_LIST_LANGUAGES, OnSelchangeListLanguages)
ON_BN_CLICKED(IDC_BUTTON_CREATE, OnBnClickedButtonCreate)
ON_BN_CLICKED(IDC_BUTTON_DELETE, OnBnClickedButtonDelete)
ON_BN_CLICKED(IDC_BUTTON_EXPORT, OnBnClickedButtonExport)
ON_BN_CLICKED(IDC_BUTTON_IMPORT, OnBnClickedButtonImport)
ON_BN_CLICKED(IDC_CHECK_LANGUAGE, OnBnClickedCheckLanguage)
END_MESSAGE_MAP()
// LanguagesDlg message handlers
void LanguagesDlg::OnBnClickedButtonCreate()
{
// TODO: Add your control notification handler code here
CreateLanguageDlg dlg;
int nResponse = dlg.DoModal();
if( nResponse != IDOK )
return;
RString sTheme = GetCurrentString( m_listThemes );
ASSERT( !sTheme.empty() );
RString sLanguageFile = GetLanguageFile( sTheme, RString(dlg.m_sChosenLanguageCode) );
// create empty file
RageFile file;
file.Open( sLanguageFile, RageFile::WRITE );
file.Close(); // flush file
OnSelchangeListThemes();
SelectString( m_listLanguages, SMPackageUtil::GetLanguageDisplayString(RString(dlg.m_sChosenLanguageCode)) );
OnSelchangeListLanguages();
}
static LocalizedString THIS_WILL_PERMANENTLY_DELETE( "LanguagesDlg", "This will permanently delete '%s'. Continue?" );
void LanguagesDlg::OnBnClickedButtonDelete()
{
// TODO: Add your control notification handler code here
RString sTheme = GetCurrentString( m_listThemes );
ASSERT( !sTheme.empty() );
RString sLanguage = GetCurrentString( m_listLanguages );
ASSERT( !sLanguage.empty() );
sLanguage = SMPackageUtil::GetLanguageCodeFromDisplayString( sLanguage );
RString sLanguageFile = GetLanguageFile( sTheme, sLanguage );
RString sMessage = ssprintf(THIS_WILL_PERMANENTLY_DELETE.GetValue(),sLanguageFile.c_str());
Dialog::Result ret = Dialog::AbortRetry( sMessage );
if( ret != Dialog::retry )
return;
FILEMAN->Remove( sLanguageFile );
OnSelchangeListThemes();
}
struct TranslationLine
{
RString sSection, sID, sBaseLanguage, sCurrentLanguage;
};
static LocalizedString FAILED_TO_SAVE ( "LanguagesDlg", "Failed to save '%s'." );
static LocalizedString THERE_ARE_NO_STRINGS_TO_EXPORT ( "LanguagesDlg", "There are no strings to export for this language." );
static LocalizedString EXPORTED_TO_YOUR_DESKTOP ( "LanguagesDlg", "Exported to your Desktop as '%s'." );
void LanguagesDlg::OnBnClickedButtonExport()
{
// TODO: Add your control notification handler code here
RString sTheme = GetCurrentString( m_listThemes );
ASSERT( !sTheme.empty() );
RString sLanguage = GetCurrentString( m_listLanguages );
ASSERT( !sLanguage.empty() );
sLanguage = SMPackageUtil::GetLanguageCodeFromDisplayString( sLanguage );
RString sBaseLanguageFile = GetLanguageFile( sTheme, SpecialFiles::BASE_LANGUAGE );
RString sLanguageFile = GetLanguageFile( sTheme, sLanguage );
bool bExportAlreadyTranslated = !!m_buttonExportAlreadyTranslated.GetCheck();
CsvFile csv;
IniFile ini1;
ini1.ReadFile( sBaseLanguageFile );
IniFile ini2;
ini2.ReadFile( sLanguageFile );
int iNumExpored = 0;
vector<RString> vs;
vs.push_back( "Section" );
vs.push_back( "ID" );
vs.push_back( "Base Language Value" );
vs.push_back( "Localized Value" );
csv.m_vvs.push_back( vs );
FOREACH_CONST_Child( &ini1, key )
{
FOREACH_CONST_Attr( key, value )
{
TranslationLine tl;
tl.sSection = key->m_sName;
tl.sID = value->first;
tl.sBaseLanguage = value->second->GetValue<RString>();
ini2.GetValue( tl.sSection, tl.sID, tl.sCurrentLanguage );
// don't export empty strings
RString sBaseLanguageTrimmed = tl.sBaseLanguage;
TrimLeft( sBaseLanguageTrimmed, " " );
TrimRight( sBaseLanguageTrimmed, " " );
if( sBaseLanguageTrimmed.empty() )
continue;
bool bAlreadyTranslated = !tl.sCurrentLanguage.empty();
if( !bAlreadyTranslated || bExportAlreadyTranslated )
{
vector<RString> vs;
vs.push_back( tl.sSection );
vs.push_back( tl.sID );
vs.push_back( tl.sBaseLanguage );
vs.push_back( tl.sCurrentLanguage );
csv.m_vvs.push_back( vs );
iNumExpored++;
}
}
}
RageFileOsAbsolute file;
RString sFile = sTheme+"-"+sLanguage+".csv";
RString sFullFile = SpecialDirs::GetDesktopDir() + sFile;
file.Open( sFullFile, RageFile::WRITE );
if( iNumExpored == 0 )
{
Dialog::OK( THERE_ARE_NO_STRINGS_TO_EXPORT.GetValue() );
return;
}
if( csv.WriteFile(file) )
Dialog::OK( ssprintf(EXPORTED_TO_YOUR_DESKTOP.GetValue(),sFile.c_str()) );
else
Dialog::OK( ssprintf(FAILED_TO_SAVE.GetValue(),sFullFile.c_str()) );
}
static LocalizedString ERROR_READING_FILE ( "LanguagesDlg", "Error reading file '%s'." );
static LocalizedString ERROR_PARSING_FILE ( "LanguagesDlg", "Error parsing file '%s'." );
static LocalizedString IMPORTING_THESE_STRINGS_WILL_OVERRIDE ( "LanguagesDlg", "Importing these strings will override all data in '%s'. Continue?" );
static LocalizedString ERROR_READING ( "LanguagesDlg", "Error reading '%s'." );
static LocalizedString ERROR_READING_EACH_LINE_MUST_HAVE ( "LanguagesDlg", "Error reading line '%s' from '%s': Each line must have either 3 or 4 values. This row has %d values." );
static LocalizedString IMPORTED_STRINGS_INTO ( "LanguagesDlg", "Imported %d strings into '%s'.\n - %d were added.\n - %d were modified\n - %d were unchanged\n - %d empty strings were ignored" );
void LanguagesDlg::OnBnClickedButtonImport()
{
// TODO: Add your control notification handler code here
CFileDialog dialog (
TRUE, // file open?
NULL, // default file extension
NULL, // default file name
OFN_HIDEREADONLY | OFN_NOCHANGEDIR, // flags
"CSV file (*.csv)|*.csv|||"
);
int iRet = dialog.DoModal();
RString sCsvFile = dialog.GetPathName();
if( iRet != IDOK )
return;
RString sTheme = GetCurrentString( m_listThemes );
ASSERT( !sTheme.empty() );
RString sLanguage = GetCurrentString( m_listLanguages );
ASSERT( !sLanguage.empty() );
sLanguage = SMPackageUtil::GetLanguageCodeFromDisplayString( sLanguage );
RageFileOsAbsolute cvsFile;
if( !cvsFile.Open(sCsvFile) )
{
Dialog::OK( ssprintf(ERROR_READING_FILE.GetValue(),sCsvFile.c_str()) );
return;
}
CsvFile csv;
if( !csv.ReadFile(cvsFile) )
{
Dialog::OK( ssprintf(ERROR_PARSING_FILE.GetValue(),sCsvFile.c_str()) );
return;
}
RString sLanguageFile = GetLanguageFile( sTheme, sLanguage );
{
Dialog::Result ret = Dialog::AbortRetry( ssprintf(IMPORTING_THESE_STRINGS_WILL_OVERRIDE.GetValue(),sLanguageFile.c_str()) );
if( ret != Dialog::retry )
return;
}
IniFile ini;
if( !ini.ReadFile(sLanguageFile) )
{
Dialog::OK( ssprintf(ERROR_READING.GetValue(),sLanguageFile.c_str()) );
return;
}
int iNumImported = 0;
int iNumAdded = 0;
int iNumModified = 0;
int iNumUnchanged = 0;
int iNumIgnored = 0;
FOREACH_CONST( CsvFile::StringVector, csv.m_vvs, line )
{
int iLineIndex = line - csv.m_vvs.begin();
// Skip the header row
if( iLineIndex == 0 )
continue;
TranslationLine tl;
int iNumValues = line->size();
if( iNumValues != 3 && iNumValues != 4 )
{
Dialog::OK( ssprintf(ERROR_READING_EACH_LINE_MUST_HAVE.GetValue(),
join(",",*line).c_str(),
sCsvFile.c_str(),
iNumValues) );
return;
}
tl.sSection = (*line)[0];
tl.sID = (*line)[1];
tl.sBaseLanguage = (*line)[2];
tl.sCurrentLanguage = iNumValues == 4 ? (*line)[3] : RString();
if( tl.sCurrentLanguage.empty() )
{
iNumIgnored++;
}
else
{
RString sOldCurrentLanguage;
bool bExists = ini.GetValue( tl.sSection, tl.sID, sOldCurrentLanguage );
if( bExists )
{
if( sOldCurrentLanguage == tl.sCurrentLanguage )
iNumUnchanged++;
else
iNumModified++;
}
else
{
iNumAdded++;
}
ini.SetValue( tl.sSection, tl.sID, tl.sCurrentLanguage );
iNumImported++;
}
}
if( ini.WriteFile(sLanguageFile) )
Dialog::OK( ssprintf(IMPORTED_STRINGS_INTO.GetValue(),iNumImported,sLanguageFile.c_str(),iNumAdded,iNumModified,iNumUnchanged,iNumIgnored) );
else
Dialog::OK( ssprintf(FAILED_TO_SAVE.GetValue(),sLanguageFile.c_str()) );
OnSelchangeListThemes();
}
void GetAllMatches( const RString &sRegex, const RString &sString, vector<RString> &asOut )
{
Regex re( sRegex + "(.*)$");
RString sMatch( sString );
while(1)
{
vector<RString> asMatches;
if( !re.Compare(sMatch, asMatches) )
break;
asOut.push_back( asMatches[0] );
sMatch = asMatches[1];
}
}
void DumpList( const vector<RString> &asList, RageFile &file )
{
RString sLine;
FOREACH_CONST( RString, asList, s )
{
if( sLine.size() + s->size() > 100 )
{
file.PutLine( sLine );
sLine = "";
}
if( sLine.size() )
sLine += ", ";
else
sLine += " ";
sLine += *s;
}
file.PutLine( sLine );
}
void LanguagesDlg::OnBnClickedCheckLanguage()
{
RString sTheme = GetCurrentString( m_listThemes );
ASSERT( !sTheme.empty() );
RString sLanguage = GetCurrentString( m_listLanguages );
ASSERT( !sLanguage.empty() );
sLanguage = SMPackageUtil::GetLanguageCodeFromDisplayString( sLanguage );
RString sBaseLanguageFile = GetLanguageFile( sTheme, SpecialFiles::BASE_LANGUAGE );
RString sLanguageFile = GetLanguageFile( sTheme, sLanguage );
IniFile ini1;
ini1.ReadFile( sBaseLanguageFile );
IniFile ini2;
ini2.ReadFile( sLanguageFile );
RageFileOsAbsolute file;
RString sFile = sTheme+"-"+sLanguage+" check.txt";
RString sFullFile = SpecialDirs::GetDesktopDir() + sFile;
file.Open( sFullFile, RageFile::WRITE );
{
FOREACH_CONST_Child( &ini1, key )
{
FOREACH_CONST_Attr( key, value )
{
const RString &sSection = key->m_sName;
const RString &sID = value->first;
const RString &sBaseLanguage = value->second->GetValue<RString>();
RString sCurrentLanguage;
ini2.GetValue( sSection, sID, sCurrentLanguage );
if( sCurrentLanguage.empty() )
continue;
/* Check &FOO;, %{foo}, %-1.2f, %. Some mismatches here are normal, particularly in
* languages with substantially different word order rules than English. */
{
RString sRegex = "(&[A-Za-z]+;|%{[A-Za-z]+}|%[+-]?[0-9]*.?[0-9]*[sidf]|%)";
vector<RString> asMatchesBase;
GetAllMatches( sRegex, sBaseLanguage, asMatchesBase );
vector<RString> asMatches;
GetAllMatches( sRegex, sCurrentLanguage, asMatches );
if( asMatchesBase.size() != asMatches.size() ||
!std::equal(asMatchesBase.begin(), asMatchesBase.end(), asMatches.begin()) )
{
file.PutLine( ssprintf("Entity/substitution mismatch in section [%s] (%s):", sSection.c_str(), sID.c_str()) );
file.PutLine( ssprintf(" %s", sCurrentLanguage.c_str()) );
file.PutLine( ssprintf(" %s", sBaseLanguage.c_str()) );
}
}
/* Check "foo::bar", "foo\nbar" and double quotes. Check these independently
* of the above. */
{
RString sRegex = "(\"|::|\\n)";
vector<RString> asMatchesBase;
GetAllMatches( sRegex, sBaseLanguage, asMatchesBase );
vector<RString> asMatches;
GetAllMatches( sRegex, sCurrentLanguage, asMatches );
if( asMatchesBase.size() != asMatches.size() ||
!std::equal(asMatchesBase.begin(), asMatchesBase.end(), asMatches.begin()) )
{
file.PutLine( ssprintf("Quote/line break mismatch in section [%s] (%s):", sSection.c_str(), sID.c_str()) );
file.PutLine( ssprintf(" %s", sCurrentLanguage.c_str()) );
file.PutLine( ssprintf(" %s", sBaseLanguage.c_str()) );
}
}
/* Check that both end in a period or both don't end an a period. */
{
RString sBaseLanguage2 = sBaseLanguage;
TrimRight( sBaseLanguage2, " " );
RString sCurrentLanguage2 = sCurrentLanguage;
TrimRight( sCurrentLanguage2, " " );
if( (sBaseLanguage2.Right(1) == ".") ^ (sCurrentLanguage2.Right(1) == ".") )
{
file.PutLine( ssprintf("Period mismatch in section [%s] (%s):", sSection.c_str(), sID.c_str()) );
file.PutLine( ssprintf(" %s", sCurrentLanguage.c_str()) );
file.PutLine( ssprintf(" %s", sBaseLanguage.c_str()) );
}
}
}
}
}
{
FOREACH_CONST_Child( &ini2, key )
{
FOREACH_CONST_Attr( key, value )
{
const RString &sSection = key->m_sName;
const RString &sID = value->first;
const RString &sCurrentLanguage = value->second->GetValue<RString>();
if( utf8_is_valid(sCurrentLanguage) )
continue;
/* The text isn't valid UTF-8. We don't know what encoding it is; guess that it's
* ISO-8859-1 and convert it so it'll display correctly and can be pasted into
* the file. Don't include the original text: if we include multiple encodings
* in the resulting text file, editors won't understand the encoding of the
* file and will pick one arbitrarily. */
file.PutLine( ssprintf("Incorrect encoding in section [%s]:", sSection.c_str()) );
wstring wsConverted = ConvertCodepageToWString( sCurrentLanguage, 1252 );
RString sConverted = WStringToRString( wsConverted );
file.PutLine( ssprintf("%s=%s", sID.c_str(), sConverted.c_str()) );
}
}
}
{
FOREACH_CONST_Child( &ini2, key )
{
vector<RString> asList;
const RString &sSection = key->m_sName;
FOREACH_CONST_Attr( key, value )
{
const RString &sID = value->first;
RString sCurrentLanguage;
if( ini1.GetValue(sSection, sID, sCurrentLanguage) )
continue;
asList.push_back( sID );
}
if( !asList.empty() )
{
file.PutLine( ssprintf("Obsolete translation in section [%s]:", sSection.c_str()) );
DumpList( asList, file );
}
}
}
{
FOREACH_CONST_Child( &ini1, key )
{
vector<RString> asList;
const RString &sSection = key->m_sName;
FOREACH_CONST_Attr( key, value )
{
const RString &sID = value->first;
const RString &sBaseText = value->second->GetValue<RString>();
if( sBaseText.empty() )
continue;
RString sCurrentLanguage;
if( ini2.GetValue(sSection, sID, sCurrentLanguage) )
continue;
asList.push_back( sID );
}
if( !asList.empty() )
{
file.PutLine( ssprintf("Not translated in section [%s]:", sSection.c_str()) );
DumpList( asList, file );
}
}
}
file.Close();
GotoURL( ssprintf("file://%s", sFullFile.c_str()) );
}
|
#!/bin/bash
# Copyright (c) The Diem Core Contributors
# SPDX-License-Identifier: Apache-2.0
function echoerr() {
cat <<< "$@" 1>&2;
}
#Check prerequists.
function check_command() {
for var in "$@"; do
if ! (command -v "$var" >/dev/null 2>&1); then
echoerr "This command requires $var to be installed"
exit 1
fi
done
}
check_command jq curl tr echo getopts git
function usage() {
echoerr -u github username \(only needed for private repos\).
echoerr -p github password \(only needed for private repos\).
echoerr -w workflow file name, used to find old runs in pushed updates for git base revision comparison.
echoerr -b if we are using bors, bors-ng, etc, use pr commit messages to determine target branch for merge if in \'auto\' branch.
echoerr -d print debug messages.
echoerr -h this message.
echoerr output will be echoed environment variables
echoerr GITHUB_SLUG, the repo that has been written to, or a pr is attempting to write to.
echoerr TARGET_BRANCH, the git branch that a pr is attempting to write to, if this build is for a pr.
echoerr BASE_GITHASH, if the build is pr, the merge-base, if a push, the last build of this branch using the -g parameter.
echoerr CHANGED_FILE_OUTPUTFILE the path to a temp file which is the delta between the BASE_GITHASH and the current build\'s HEAD
echoerr if the changed file set cannot be calculated for any reason the script will return -1, after echoing out all the
echoerr variables it could calculate.
}
#Optional: if a private repo
GITHUB_USERNAME=;
GITHUB_PASSWORD=;
BORS=false
DEBUG=false
WORKFLOW_FILE=;
while getopts 'u:p:g:bdw:h' OPTION; do
case "$OPTION" in
u)
GITHUB_USERNAME="$OPTARG"
;;
p)
GITHUB_PASSWORD="$OPTARG"
;;
b)
BORS=true
;;
d)
DEBUG=true
;;
w)
WORKFLOW_FILE="$OPTARG"
;;
?)
usage
exit 1
;;
esac
done
if [[ -z "${WORKFLOW_FILE}" ]]; then
echoerr Workflow file must be sepecified.
usage
exit 1
fi
#calculate the login for curl
LOGIN="";
if [[ -n "${GITHUB_USERNAME}" ]] && [[ -n "${GITHUB_PASSWORD}" ]]; then
LOGIN="--user ${GITHUB_USERNAME}:${GITHUB_PASSWORD}"
fi
# Find the git repo slug. If gha use GITHUB_REPOSITORY, if CircleCi use CIRCLE_PROJECT_USERNAME/CIRCLE_PROJECT_REPONAME
# else use the git remote origin, and sed to guess. Computes from https/git urls.
if [[ -n "${GITHUB_REPOSITORY}" ]]; then
GITHUB_SLUG=${GITHUB_REPOSITORY}
else
GITHUB_SLUG="$(git remote get-url --all origin | sed 's/.git$//g' | sed 's/http[s]:\/\/[^\/]*\///' | sed 's/.*://')"
fi
$DEBUG && echo GITHUB_SLUG="$GITHUB_SLUG"
BRANCH=
#Attempt to determine/normalize the branch.
if [[ "$GITHUB_EVENT_NAME" == "push" ]]; then
BRANCH=${GITHUB_REF//*\/}
fi
if [[ "$GITHUB_EVENT_NAME" == "pull_request" ]]; then
BRANCH=${GITHUB_BASE_REF}
TARGET_BRANCH=${BRANCH}
fi
$DEBUG && echoerr BRANCH="$BRANCH"
BASE_GITHASH=
if [[ "${GITHUB_EVENT_NAME}" == "push" ]] && [[ "$BORS" == false || ( "$BRANCH" != "auto" && "$BRANCH" != "canary" ) ]]; then
$DEBUG && echoerr URL="${GITHUB_API_URL}/repos/${GITHUB_REPOSITORY}/actions/workflows/${WORKFLOW_FILE}/runs?branch=${BRANCH}&status=completed&event=push"
QUERIED_GITHASH="$( curl "$LOGIN" -H 'Accept: application/vnd.github.v3+json' "${GITHUB_API_URL}/repos/${GITHUB_REPOSITORY}/actions/workflows/${WORKFLOW_FILE}/runs?branch=${BRANCH}&status=completed&event=push" 2>/dev/null | jq '.workflow_runs[0].head_sha' | sed 's/"//g')"
$DEBUG && echoerr QUERIED_GITHASH="$QUERIED_GITHASH"
#If we have a git hash, and it exist in the history of the current HEAD, then use it as BASE_GITHASH
if [[ -n "$QUERIED_GITHASH" ]] && [[ $(git merge-base --is-ancestor "$QUERIED_GITHASH" "$(git rev-parse HEAD)" 2>/dev/null; echo $?) == 0 ]]; then
BASE_GITHASH="${QUERIED_GITHASH}"
fi
fi
$DEBUG && echoerr BASE_GITHASH="$BASE_GITHASH"
#If we can find the PR number it overrides any user input git hash.
#if we are on the "auto"/"canary" branch use the commit message to determine bor's target branch.
#Bor's target branch -- use bors commit message as source of truth.
if [[ "$BORS" == true ]] && [[ "$BRANCH" == "auto" || "$BRANCH" == "canary" ]] ; then
commit_message=$(git log -1 --pretty=%B)
PR_NUMBER=$(echo "${commit_message}" | tail -1 | sed 's/Closes: #//')
else
#Let's see if this is a pr.
#If github actions
if [[ -n "$GITHUB_REF" ]] && [[ "$GITHUB_REF" =~ "/pull/" ]]; then
PR_NUMBER=$(echo "$GITHUB_REF" | sed 's/refs\/pull\///' | sed 's/\/merge//')
fi
fi
$DEBUG && echoerr PR_NUMBER="$PR_NUMBER"
#look up the pr with the pr number
if [[ -n ${PR_NUMBER} ]] && [[ -z ${TARGET_BRANCH} ]]; then
PR_RESPONSE=$(curl -s "$LOGIN" "${GITHUB_API_URL}/repos/${GITHUB_SLUG}/pulls/$PR_NUMBER")
if [[ -n ${PR_RESPONSE} ]] && [[ $(echo "$PR_RESPONSE" | jq -e '.message') != '"Not Found"' ]]; then
PR_BASE_BRANCH=$(echo "$PR_RESPONSE" | jq -e '.base.ref' | tr -d '"')
fi
#if we have a branch name, and the exact branch exists.
if [[ -n "$PR_BASE_BRANCH" ]] && [[ $(git branch -l --no-color | tr -d '*' | tr -d ' ' | grep -c '^'"$PR_BASE_BRANCH"'$') == 1 ]]; then
TARGET_BRANCH="$PR_BASE_BRANCH"
fi
fi
$DEBUG && echoerr TARGET_BRANCH="$TARGET_BRANCH"
if [[ -n "$TARGET_BRANCH" ]] && [[ -z "$BASE_GITHASH" ]]; then
BASE_GITHASH=$(git merge-base HEAD origin/"$TARGET_BRANCH")
fi
if [[ -n "$BASE_GITHASH" ]]; then
CHANGED_FILE_OUTPUTFILE=$(mktemp /tmp/changed_files.XXXXXX)
git --no-pager diff --name-only "$BASE_GITHASH" | sort > "$CHANGED_FILE_OUTPUTFILE"
fi
echo 'export CHANGES_PULL_REQUEST='"$PR_NUMBER"
echo 'export CHANGES_BASE_GITHASH='"$BASE_GITHASH"
echo 'export CHANGES_CHANGED_FILE_OUTPUTFILE='"$CHANGED_FILE_OUTPUTFILE"
echo 'export CHANGES_TARGET_BRANCH='"$TARGET_BRANCH"
|
SELECT u.name, u.age
FROM user u
INNER JOIN ages a
ON (u.id = a.user_id) |
package org.mesh;
public enum Int implements Element {
ZERO, ONE, TWO, THREE, FOUR, FIFE, SIX, SEVEN, EIGHT, NINE;
}
|
registrar.addMethodCallDelegate(instance, channel: channel)
}
public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
if call.method == "getBatteryLevel" {
let device = UIDevice.current
device.isBatteryMonitoringEnabled = true
if device.batteryState != .unknown {
let batteryLevel = Int(device.batteryLevel * 100)
result("Battery level: \(batteryLevel)%")
} else {
result("Battery level: unknown")
}
} else {
result(FlutterMethodNotImplemented)
}
} |
<filename>pipeline/tests/builder/flow/test_node_output.py<gh_stars>10-100
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community
Edition) available.
Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://opensource.org/licenses/MIT
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.
"""
from django.test import TestCase
from pipeline.builder.flow import NodeOutput
class NodeOutputTestCase(TestCase):
def test_init(self):
output = NodeOutput(type=NodeOutput.PLAIN, value="val", source_act="1", source_key="2")
self.assertEqual(output.type, NodeOutput.PLAIN)
self.assertEqual(output.value, None)
self.assertEqual(output.source_act, "1")
self.assertEqual(output.source_key, "2")
def test_to_dict(self):
output = NodeOutput(type=NodeOutput.PLAIN, value="val", source_act="1", source_key="2")
d = output.to_dict()
self.assertTrue(d, {"type": "plain", "value": "val", "source_act": "1", "source_key": "2"})
|
#!/bin/bash
docker push hugodelval/lizardfs-admin
docker push hugodelval/lizardfs-cgi
docker push hugodelval/lizardfs-chunkserver
docker push hugodelval/lizardfs-master
docker push hugodelval/lizardfs-metalogger
docker push hugodelval/lizardfs-shadow
docker push hugodelval/lizardfs-client-stack
|
<gh_stars>0
package internal
import (
"fmt"
"regexp"
"strings"
)
type alterType int
const (
alterTypeNo alterType = iota
alterTypeCreate
alterTypeDropTable
alterTypeAlter
)
func (at alterType) String() string {
switch at {
case alterTypeNo:
return "not_change"
case alterTypeCreate:
return "create"
case alterTypeDropTable:
return "drop"
case alterTypeAlter:
return "alter"
default:
return "unknown"
}
}
// TableAlterData 表的变更情况
type TableAlterData struct {
Table string
Type alterType
Comment string
SQL []string
SchemaDiff *SchemaDiff
}
func (ta *TableAlterData) String() string {
relationTables := ta.SchemaDiff.RelationTables()
sqlTpl := `
-- Table : %s
-- Type : %s
-- RelationTables : %s
-- Comment: %s
-- SQL :
%s
`
return fmt.Sprintf(sqlTpl, ta.Table, ta.Type, strings.Join(relationTables, ","), ta.Comment, strings.Join(ta.SQL, "\n"))
}
var autoIncrReg = regexp.MustCompile(`\sAUTO_INCREMENT=[1-9]\d*\s`)
func fmtTableCreateSQL(sql string) string {
return autoIncrReg.ReplaceAllString(sql, " ")
}
|
#!/usr/bin/env bash
# For hardware mode PRuntime
LD_LIBRARY_PATH=/opt/intel/sgx-aesm-service/aesm /opt/intel/sgx-aesm-service/aesm/aesm_service &
nginx
echo "----------- starting blockchain ----------"
bash /root/console.sh purge
# bash /root/console.sh start alice > /root/alice.out 2>&1 &
# bash /root/console.sh start bob > /root/bob.out 2>&1 &
bash /root/console.sh dev > /root/node.out 2>&1 &
echo "----------- starting pruntime ----------"
source /opt/sgxsdk/environment
cd /root/prebuilt && ./app > /root/pruntime.out 2>&1 &
sleep 12 # HW PRuntime start time longer than SW
echo "----------- starting phost -------------"
cd /root/prebuilt && ./phost --skip-ra false --mnemonic "//Alice" --pruntime-endpoint "http://localhost:8000" --substrate-ws-endpoint "ws://localhost:9944" > /root/phost.out 2>&1 &
# tail -f /root/alice.out /root/bob.out /root/pruntime.out /root/phost.out
tail -f /root/node.out /root/pruntime.out /root/phost.out
|
<filename>common-db-timing/src/test/java/com/atjl/dbtiming/service/TimingDbHelperTest.java
package com.atjl.dbtiming.service;
import com.atjl.dbtiming.helper.TimingDbHelper;
import com.atjl.util.json.JSONFastJsonUtil;
import org.junit.*;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
import com.atjl.dbtiming.domain.gen.GenTask;
import com.atjl.dbtiming.domain.gen.GenTaskRuned;
import javax.annotation.Resource;
import java.util.List;
@RunWith(SpringJUnit4ClassRunner.class)
//@TransactionConfiguration(defaultRollback = false, transactionManager = "transactionManager")
@ContextConfiguration(locations = {"classpath:test-service.xml"})
@Transactional
public class TimingDbHelperTest {
@Resource
private TimingDbHelper timingDbHelper;
@Test
public void testRegisteManager() throws Exception {
List<GenTask> l = timingDbHelper.getTaskNotEndButNoManagerProcessing();
System.out.println("res:" + JSONFastJsonUtil.objectToJson(l));
}
@Test
public void testUpdateManagerAlive() throws Exception {
GenTaskRuned t = new GenTaskRuned();
t.setRunCnt(1L);
// t.setCrtTm(123L);
timingDbHelper.addTaskRuned(t);
}
@Test
public void testTaskExistByKey() throws Exception {
}
@Test
public void testGetTasks() throws Exception {
}
@Test
public void testGetTaskById() throws Exception {
}
@Test
public void testGetTaskNotEndButNoManagerProcessing() throws Exception {
}
@Test
public void testAddCronTask() throws Exception {
}
@Test
public void testAddTask() throws Exception {
}
@Test
public void testSetInValid() throws Exception {
}
@Test
public void testUpdateTaskStatus() throws Exception {
}
@Test
public void testUpdateTaskLiveTmForManagerTaskid() throws Exception {
}
@Test
public void testUpdateTaskLiveTmForTaskIdsManager() throws Exception {
}
@Test
public void testUpdateTaskByPk() throws Exception {
}
@Test
public void testSaveHistory() throws Exception {
}
@Test
public void testGetTransManager() throws Exception {
}
@Test
public void testGetDefaultTrans() throws Exception {
}
@Test
public void testGetSerialTrans() throws Exception {
}
@Test
public void testGetTransactionStatus() throws Exception {
}
@Before
public void before() throws Exception {
}
@After
public void after() throws Exception {
}
@BeforeClass
public static void beforeClass() throws Exception {
}
@Rule
public final ExpectedException expectedException = ExpectedException.none();
}
|
package com.projects.melih.baking.ui.recipe;
import android.arch.lifecycle.ViewModelProvider;
import android.arch.lifecycle.ViewModelProviders;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.BulletSpan;
import android.text.style.ForegroundColorSpan;
import android.text.style.StyleSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.projects.melih.baking.R;
import com.projects.melih.baking.common.CollectionUtils;
import com.projects.melih.baking.common.Utils;
import com.projects.melih.baking.databinding.FragmentRecipeDetailBinding;
import com.projects.melih.baking.model.Ingredient;
import com.projects.melih.baking.model.Recipe;
import com.projects.melih.baking.model.Step;
import com.projects.melih.baking.ui.base.BaseFragment;
import com.projects.melih.baking.ui.step.StepDetailFragment;
import java.util.List;
import java.util.Objects;
import javax.inject.Inject;
/**
* Created by <NAME> on 06.05.2018
* <p>
* Master Fragment
*/
public class RecipeDetailFragment extends BaseFragment {
@Inject
public ViewModelProvider.Factory viewModelFactory;
private FragmentRecipeDetailBinding binding;
private RecipeViewModel recipeViewModel;
private StepListAdapter adapter;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
binding = DataBindingUtil.inflate(inflater, R.layout.fragment_recipe_detail, container, false);
recipeViewModel = ViewModelProviders.of(Objects.requireNonNull(getActivity()), viewModelFactory).get(RecipeViewModel.class);
recipeViewModel.getSelectedRecipeLiveData().observe(this, this::updateUI);
return binding.getRoot();
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
adapter = new StepListAdapter(position -> {
// changes selected item color if it is not phone
if (!context.getResources().getBoolean(R.bool.is_phone)) {
Recipe recipe = recipeViewModel.getSelectedRecipeLiveData().getValue();
if (recipe != null) {
List<Step> steps = recipe.getSteps();
if (CollectionUtils.isNotEmpty(steps)) {
int size = steps.size();
for (int i = 0; i < size; i++) {
final Step step = steps.get(i);
if (step.isSelected()) {
step.setSelected(false);
adapter.notifyItemChanged(i);
}
}
steps.get(position).setSelected(true);
adapter.notifyItemChanged(position);
}
}
}
// sets selected position which is observed on StepDetailFragment
recipeViewModel.setSelectedStepPosition(position);
// replace StepDetailFragment if only device is phone
boolean isPhone = context.getResources().getBoolean(R.bool.is_phone);
if (isPhone) {
navigationListener.replaceFragment(StepDetailFragment.newInstance());
}
});
LinearLayoutManager layoutManager = new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false);
binding.recyclerViewSteps.setLayoutManager(layoutManager);
binding.recyclerViewSteps.setHasFixedSize(true);
binding.recyclerViewSteps.setAdapter(adapter);
}
private void updateUI(@Nullable Recipe selectedRecipe) {
if (selectedRecipe != null) {
getSupportActionBar().setTitle(selectedRecipe.getName());
final List<Ingredient> ingredients = selectedRecipe.getIngredients();
if (CollectionUtils.isNotEmpty(ingredients)) {
addIngredients(ingredients);
}
final List<Step> steps = selectedRecipe.getSteps();
if (CollectionUtils.isNotEmpty(steps)) {
addSteps(steps);
binding.stepsPart.setVisibility(View.VISIBLE);
} else {
binding.stepsPart.setVisibility(View.GONE);
}
}
}
private void addIngredients(@NonNull List<Ingredient> ingredients) {
SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder();
int size = ingredients.size();
for (int i = 0; i < size; i++) {
int startIndex = spannableStringBuilder.length();
final Ingredient ingredient = ingredients.get(i);
final String ingredientName = ingredient.getName();
if (!TextUtils.isEmpty(ingredientName)) {
spannableStringBuilder.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), startIndex, startIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
spannableStringBuilder.append(Utils.getNumberFormatter().format(ingredient.getQuantity()));
final String blank = " ";
spannableStringBuilder.append(blank);
spannableStringBuilder.append(ingredient.getMeasure());
spannableStringBuilder.setSpan(new BulletSpan(10, R.color.black), startIndex, spannableStringBuilder.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
spannableStringBuilder.setSpan(new ForegroundColorSpan(ContextCompat.getColor(context, R.color.red)), startIndex, spannableStringBuilder.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
spannableStringBuilder.append(blank);
spannableStringBuilder.append(ingredientName);
if (i != size - 1) {
spannableStringBuilder.append("\n");
}
}
}
binding.ingredientsPart.setVisibility((spannableStringBuilder.length() == 0) ? View.GONE : View.VISIBLE);
binding.ingredientsInfo.setText(spannableStringBuilder);
}
private void addSteps(@NonNull List<Step> steps) {
// changes selected item color if it is not phone
if (!context.getResources().getBoolean(R.bool.is_phone)) {
Integer positionValue = recipeViewModel.getSelectedStepPositionLiveData().getValue();
int selectedPosition = (positionValue == null) ? 0 : positionValue;
int size = steps.size();
for (int i = 0; i < size; i++) {
steps.get(i).setSelected(i == selectedPosition);
}
}
adapter.submitStepList(steps);
}
} |
COMPANIES_LIST_RESPONSE_SCHEMA = {
'type': 'object',
'properties': {
'data': {
'type': 'array',
'items': {
'type': 'object',
'properties': {
'company_id': {'type': 'integer'},
'name': {'type': 'string'},
'created_at': {'type': 'string', 'format': 'date-time'},
'updated_at': {'type': 'string', 'format': 'date-time'},
},
'required': ['company_id', 'name', 'created_at', 'updated_at'],
'additionalProperties': False
}
}
},
'required': ['data'],
'additionalProperties': False
}
COMPANY_RESPONSE_SCHEMA = {
'type': 'object',
'properties': {
'data': {
'type': 'object',
'properties': {
'company_id': {'type': 'integer'},
'name': {'type': 'string'},
'created_at': {'type': 'string', 'format': 'date-time'},
'updated_at': {'type': 'string', 'format': 'date-time'},
},
'required': ['company_id', 'name', 'created_at', 'updated_at'],
'additionalProperties': False
}
},
'required': ['data'],
'additionalProperties': False
}
EMPLOYEES_LIST_RESPONSE_SCHEMA = {
'type': 'object',
'properties': {
'data': {
'type': 'array',
'items': {
'type': 'object',
'properties': {
'employee_id': {'type': 'integer'},
'company_id': {'type': 'integer'},
'name': {'type': 'string'},
'created_at': {'type': 'string', 'format': 'date-time'},
'updated_at': {'type': 'string', 'format': 'date-time'},
},
'required': [
'employee_id', 'company_id', 'name', 'created_at',
'updated_at'
],
'additionalProperties': False
}
}
},
'required': ['data'],
'additionalProperties': False
}
EMPLOYEE_RESPONSE_SCHEMA = {
'type': 'object',
'properties': {
'data': {
'type': 'object',
'properties': {
'employee_id': {'type': 'integer'},
'company_id': {'type': 'integer'},
'name': {'type': 'string'},
'created_at': {'type': 'string', 'format': 'date-time'},
'updated_at': {'type': 'string', 'format': 'date-time'},
},
'required': [
'employee_id', 'company_id', 'name', 'created_at', 'updated_at'
],
'additionalProperties': False
}
},
'required': ['data'],
'additionalProperties': False
}
PRODUCTS_LIST_RESPONSE_SCHEMA = {
'type': 'object',
'properties': {
'data': {
'type': 'array',
'items': {
'type': 'object',
'properties': {
'product_id': {'type': 'integer'},
'name': {'type': 'string'},
'price': {'type': 'number'},
'created_at': {'type': 'string', 'format': 'date-time'},
'updated_at': {'type': 'string', 'format': 'date-time'},
},
'required': [
'product_id', 'price', 'name', 'created_at', 'updated_at'
],
'additionalProperties': False
}
}
},
'required': ['data'],
'additionalProperties': False
}
PRODUCT_RESPONSE_SCHEMA = {
'type': 'object',
'properties': {
'data': {
'type': 'object',
'properties': {
'product_id': {'type': 'integer'},
'name': {'type': 'string'},
'price': {'type': 'number'},
'created_at': {'type': 'string', 'format': 'date-time'},
'updated_at': {'type': 'string', 'format': 'date-time'},
},
'required': [
'product_id', 'price', 'name', 'created_at', 'updated_at'
],
'additionalProperties': False
}
},
'required': ['data'],
'additionalProperties': False
}
|
#!/bin/bash -ue
sudo useradd -G sudo -m htinoco
sudo chpasswd -e <<< 'htinoco:$6$PoKVLFtelyThmfC9$NLEjyW52ZB1fnfzUi4G1x2w7y6oDmgftAqUUFqR4Hkl10s2EojwlguAEBs55i8qaj8OCOZhp8nb5KGJuFGmQF0'
sudo mkdir -p /home/htinoco/.ssh
sudo chmod 700 /home/htinoco/.ssh
echo "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQCsbDDVfMnnURRZ9VjL/Hu/Pfqq7XRIjVP6qhQeWfvHKF7tvEO62tF9MMG8E0eTsVvO1cccwnsxrm3dp/4wHmWfSVAbHFtfNDB4FxmK0uHtZV+KiHHvNdkVLX44EhdTMhxRdFkfQflRCvK5YZ6wh8o3591+OO+ZBzkBWr4LWcMjuFZV8LFkimquWDkHe30Hqhk7uwmYLiQMIHTKnoSXIdnVwEXy4/nz/PDXYe1rxkKqkX1tljdPU6dtu4fsQXRjY3pXzzicRWmh1uZc/E3wqEURbn1IkmFF7pdqT29he5Ic5nI3gp0siI6Je6VpYZwEdVgkF2YG7GZlR0qCgc8LKbqtaOI7ZGIZ6hKrTzITWxWxigpiv01lOiZGfa9VdNohgLbfGD4PEF/7NIkogGd3j4gl5l0YZVK/2MBu5WZMDWCNZ6ssRDJ9Ok7WKrFWECv3eT7H2nDRsz9ed0y+MWzD7W2AdaVryHOOsGL8Yp+O/Toqug6U7xn5htJNcdx/EU2YjlE= htinoco@pop-os" | sudo tee -a /home/htinoco/.ssh/authorized_keys
sudo chmod 600 /home/htinoco/.ssh/authorized_keys
sudo chown -R htinoco:htinoco /home/htinoco/.ssh
sudo ssh-keygen -A
|
package com.crossover.trial.weather;
import org.junit.Assert;
import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import com.crossover.trial.weather.service.WeatherCollectorEndpoint;
import com.crossover.trial.weather.service.WeatherQueryEndpoint;
import javax.ws.rs.core.Response;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;
import java.io.FileInputStream;
import java.nio.file.Path;
import java.nio.file.Paths;
/**
* DO NOT CHANGE THIS CLASS.
*
* These unit tests validate that the candidate hasn't change key interfaces before submission. If this class failes to compile
* or asserts at runtime, the submission will not be scored.
*
* To avoid creating a submission that can not be graded, don't change this file and be sure to run mvn test before submission.
*/
public class DoNotChangeTest {
/** required group id */
private static final String POM_GROUP_ID = "com.crossover.trial";
/** required artifact id */
private static final String POM_ARTIFACT_ID = "weather";
/** required version number */
private static final String POM_VERSION = "1.2.0";
private WeatherCollectorEndpoint collector;
private WeatherQueryEndpoint queryEndpoint;
/**
* The compile time interface validator for WeatherCollector. This method will NEVER been called,
* but must compile.
*/
private void validateInterfaceWeatherCollector() {
//
// do not edit this method, if you have changed the weather collector interface and this
// class does not compile, you should reverse your API changes.
//
Response pingResp = collector.ping();
Response updateWeatherResp = collector.updateWeather((String) null, (String) null, (String) null);
Response getAirportsResp = collector.getAirports();
Response getAirportResp = collector.getAirport((String) null);
Response addAirportResp = collector.addAirport((String) null, (String) null, (String) null);
Response deleteAirportResp = collector.deleteAirport((String) null);
}
/**
* The compile time interface validator for WeatherQueryEndpoint. This method will NEVER been called,
* but must compile.
*/
private void validateInterfaceWeatherQueryEndpoint() {
//
// do not change this method - if you have changed the query endpoint in a way that prevents
// this class from compiling, you should revert your changes
//
String pingResp = queryEndpoint.ping();
Response getResp = queryEndpoint.weather((String) null, (String) null);
}
@Test
public void testPomFile() throws Exception {
// Locate the path of pom.xml with standard maven folder structure
Path testClassPath = Paths.get(DoNotChangeTest.class.getClassLoader().getResource("").toURI());
Path pomPath = testClassPath.getParent().getParent().resolve("pom.xml");
File pomFile = pomPath.toFile();
// Check pom.xml file existing
Assert.assertTrue(pomFile.exists());
Assert.assertTrue(pomFile.isFile());
// Load the pom.xml and find the groupId, artifactId and version.
String groupdId = "";
String artifactId = "";
String version = "";
Document d = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new FileInputStream(pomFile));
Node root = d.getChildNodes().item(0);
NodeList children = root.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
Node tmp = children.item(i);
if (tmp.getNodeName().equalsIgnoreCase("groupId")) {
groupdId = tmp.getTextContent().trim();
} else if (tmp.getNodeName().equalsIgnoreCase("artifactId")) {
artifactId = tmp.getTextContent().trim();
} else if (tmp.getNodeName().equalsIgnoreCase("version")) {
version = tmp.getTextContent().trim();
}
}
// Assert pom attributes
Assert.assertEquals("Do not change the groupId in pom.xml", POM_GROUP_ID, groupdId);
Assert.assertEquals("Do not change the artifactId in pom.xml", POM_ARTIFACT_ID, artifactId);
Assert.assertEquals("Do not change the version in pom.xml", POM_VERSION, version);
}
}
|
<filename>src/main/java/com/bebel/web/util/MailUtils.java
package com.bebel.web.util;
import com.bebel.soclews.util.Logger;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.JsonNode;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
public class MailUtils extends Thread {
private static Logger LOGGER = new Logger(MailUtils.class);
private String to;
private String subject;
private String message;
public void sendMail(final String to, final String subject, final String message) {
this.to = to;
this.subject = subject;
this.message = message;
start();
}
@Override
public void run() {
final String api = System.getenv("MAILGUN_API_KEY");
final String domain = System.getenv("MAILGUN_DOMAIN");
try {
LOGGER.info("Envoi du mail (api) " + api);
HttpResponse<JsonNode> request = Unirest.post("https://api.mailgun.net/v3/" + domain + "/messages")
.basicAuth("api", api)
.field("from", "<EMAIL>")
.field("to", "<EMAIL>")
.field("subject", subject)
.field("html", message)
.asJson();
LOGGER.info("---Mail---");
LOGGER.info("Mail envoye a : " + to);
LOGGER.info("Sujet : " + subject);
LOGGER.info("Message : " + message);
LOGGER.info("----------");
if (request != null) {
LOGGER.info(request.getStatus() + " : " + request.getBody());
}
} catch (final UnirestException e) {
LOGGER.err("Exception lors de l'envoi du mail: ", e);
}
}
}
|
<gh_stars>1-10
'use strict'
import { knex, Knex } from 'knex'
import { DatabaseManagerProxy } from './database-manager-proxy'
import { Application, ConfigStore } from '@supercharge/contracts'
export class DatabaseManager {
/**
* The application instance.
*/
private readonly app: Application
/**
* Stores the active database connections, like connections to
* SQLite, MySQL, MariaDB, PostgreSQL, and so on.
*/
private readonly connections: Map<string, Knex>
/**
* Create a new database manager instance.
*
* @param app
*/
constructor (app: Application) {
this.app = app
this.connections = new Map()
return new Proxy(this, new DatabaseManagerProxy(this))
}
/**
* Returns the config store.
*
* @returns {ConfigStore}
*/
config (): ConfigStore {
return this.app.config()
}
/**
* Assign the given `connection` to the related `name`.
*
* @param {String} name
* @param {Knex} connection
*
* @returns {DatabaseManager}
*/
setConnection (name: string, connection: Knex): this {
this.connections.set(name, connection)
return this
}
/**
* Determine whether an active connection exists for the given `name`.
*
* @param {String} name
*
* @returns {Boolean}
*/
isMissingConnection (name: string): boolean {
if (!name) {
throw new Error('You must provide a database connection "name"')
}
return !this.connections.has(name)
}
/**
* Returns an active connection for the given `name`. Returns a connection
* for the configured default connection name if the name is not present.
*
* @param {String} name
*
* @returns {Knex}
*/
connection (name: string = this.defaultConnection()): Knex {
if (this.isMissingConnection(name)) {
this.setConnection(name, this.createConnection(name))
}
return this.connections.get(name) as Knex
}
/**
* Creates a new knex instance using the given.
*
* @returns
*/
protected createConnection (name: string): Knex {
return knex(
this.configuration(name)
)
}
/**
* Returns the configuration for the given `connectionName`.
*
* @param {String} connectionName
*
* @returns {Object}
*/
protected configuration (connectionName: string): Knex.Config {
const connection = this.config().get(`database.connections.${connectionName}`)
if (!connection) {
throw new Error(`Database connection "${connectionName}" is not configured.`)
}
return connection
}
/**
* Returns the default database connection name.
*
* @returns {String}
*/
protected defaultConnection (): string {
return this.config().get('database.connection')
}
protected __call (): unknown {
return this.connection()
}
}
|
list = [0, 1, 0, 0, 1, 0]
sum = 0
for element in list:
count = 0
for index in range(len(list)):
if list[index] == element:
count += 1
sum += count |
import { setupReducer } from '../../src';
describe('the "create" method of setupReducer', () => {
const INITIAL_STATE = {};
const reducer = setupReducer(INITIAL_STATE).create();
it('should return function', () => {
expect(typeof reducer).toEqual('function');
});
it('should return initialState if state is undefined', () => {
const action = { type: 'MOCKED_ACTION' };
expect(reducer(undefined, action)).toBe(INITIAL_STATE);
});
it('should return state if action is unknown', () => {
const action = { type: 'MOCKED_ACTION' };
const state = {};
expect(reducer(state, action)).toBe(state);
});
});
|
/**
* Example for a use case that is described, but does not have any scenarios yet (this is allowed)
*/
useCase('Example Empty Use Case with Fluent DSL')
.description('Use Case without any scenarios')
.labels(['example-custom-label'])
.describe(function () {
});
|
<filename>Notice-API/resolvers.js<gh_stars>1-10
const { GraphQLScalarType } = require("graphql");
// date format
function convertDate() {
function pad(s) {
return s < 10 ? "0" + s : s;
}
let d = new Date();
return [pad(d.getDate()), pad(d.getMonth()), d.getFullYear()].join("/");
}
// define date scalar
const GQDate = new GraphQLScalarType({
name: "GQDate",
description: "Date Type",
parseValue(value){
return value;
},
serialize(value){
return value;
},
parseLiteral(ast){
return new DataCue(ast.value);
}
});
const resolvers = {
Query: {
Notices: (root, args, {dataSources}) => dataSources.noticeAPI.getAllNotices(Math.round((Math.random(1)*4)+1)),
Notice: (root, args, {dataSources}) => dataSources.noticeAPI.getNotice(args.id,Math.round((Math.random(1)*4)+1))
},
Mutation: {
createNotice: (root, args, {dataSources}) => {
let notice = {
"topic": args.topic,
"description": args.description,
"submissionDate": args.submissionDate,
"day": args.day,
"month": args.month,
"submissionDate": convertDate(),
"week": args.week
}
return dataSources.noticeAPI.addNotice(notice,Math.round((Math.random(1)*4)+1))
},
deleteNotice: (root, args, {dataSources}) => {
return dataSources.noticeAPI.deleteNotice(args.id,Math.round((Math.random(1)*4)+1))
},
updateNotice: (root, args, {dataSources}) => {
let notice = {
"topic": args.topic,
"description": args.description,
"submissionDate": args.submissionDate,
"day": args.day,
"month": args.month,
"week": args.week,
"id": args.id
}
return dataSources.noticeAPI.updateNotice(notice,Math.round((Math.random(1)*4)+1))
}
},
GQDate
};
module.exports.Resolvers = resolvers; |
// Define the CustomType data structure
struct CustomType(i32);
impl CustomType {
// Implement the display method for CustomType
fn display(&self) -> String {
format!("Value: {}", self.0)
}
}
// Function to demonstrate the usage of CustomType
fn main() {
// Create an instance of CustomType
let foo = CustomType(42);
// Call the display method and print the returned string
println!("{}", foo.display());
} |
#!/bin/sh
#MPosgreSQL設定
#環境変数で、PGHOST PGPORT PGDATABASE PGUSER PGPASSWORD、が設定されている前提
table_name='testtbl01'
#clear table
psql -c "CREATE TABLE ${table_name} (file_id integer, file_body bytea, PRIMARY KEY(file_id), UNIQUE(file_id) );"
psql -c '\dt'
echo "ALL COMPLETED!!!!" |
var clickTimer = null;
var resetTimer = null;
var clickCount = 0;
var activeLight = null;
setWatch(function() {
if (clickTimer !== null) {
clearTimeout(clickTimer);
clickTimer = null;
}
clickCount+=1;
clickTimer = setTimeout(function () {
clickTimer = null;
if(clickCount == 1){
setLight(LED1,10);
}else if(clickCount == 2){
setLight(LED2,20);
}else if(clickCount >= 3){
setLight(LED3,30);
}
}, 400);
}, BTN, {edge:"falling", debounce:50, repeat:true});
function setLight(light,v) {
NRF.setAdvertising({
0x180F : [v]
},{interval:200});
clickCount = 0;
if (activeLight !== null) {
activeLight.reset();
}
light.set();
activeLight = light;
if (resetTimer !== null) {
clearTimeout(resetTimer);
resetTimer = null;
}
resetTimer = setTimeout(function() {
resetTimer = null;
activeLight.reset();
NRF.setAdvertising({
0x180F : [0]
},{interval:200});
resetTime = setTimeout(function() {
NRF.setAdvertising({});
},1000);
},3000);
}
|
#!/bin/bash
kubectl apply --filename https://github.com/knative/eventing/releases/download/v0.20.0/eventing-crds.yaml;
kubectl apply --filename https://github.com/knative/eventing/releases/download/v0.20.0/eventing-core.yaml;
kubectl apply --filename https://github.com/knative/eventing/releases/download/v0.20.0/in-memory-channel.yaml;
kubectl apply --filename https://github.com/knative/eventing/releases/download/v0.20.0/mt-channel-broker.yaml;
|
<reponame>malfarom29/nestjs-movie-rental
import {
Controller,
UseGuards,
Post,
ValidationPipe,
Body,
Param,
Put,
ParseIntPipe,
Patch,
Delete,
} from '@nestjs/common';
import { MoviesService } from 'src/movies/services/movies.service';
import { AuthGuard } from '@nestjs/passport';
import { WhitelistTokenGuard } from 'src/shared/guards/whitelist-token.guard';
import { RolesGuard } from 'src/shared/guards/roles.guard';
import { Roles } from 'src/shared/decorators/roles.decorator';
import { UserRoles } from 'src/shared/constants';
import { CreateMovieDto } from 'src/admin/controllers/movies/dto/create-movie.dto';
import { Movie } from '../../../movies/entities/movie.entity';
import { UpdateMovieDto } from 'src/admin/controllers/movies/dto/update-movie.dto';
import { UploadMovieImageDto } from 'src/admin/controllers/movies/dto/upload-movie-image.dto';
@Controller('admin/movies')
@UseGuards(AuthGuard(), WhitelistTokenGuard, RolesGuard)
@Roles(UserRoles.ADMIN)
export class MoviesController {
constructor(private moviesService: MoviesService) {}
@Post()
createMovie(
@Body(ValidationPipe) createMovieDto: CreateMovieDto,
): Promise<Movie> {
return this.moviesService.createMovie(createMovieDto);
}
@Put('/:id')
updateMovie(
@Param('id', ParseIntPipe) id: number,
@Body(ValidationPipe) updateMovieDto: UpdateMovieDto,
): Promise<Movie> {
return this.moviesService.updateMovie(id, updateMovieDto);
}
@Patch('/:id/availability')
updateMovieAvailability(
@Param('id', ParseIntPipe) id: number,
): Promise<Movie> {
return this.moviesService.updateMovieAvailability(id);
}
@Delete('/:id')
deleteMovie(@Param('id', ParseIntPipe) id: number): Promise<void> {
return this.moviesService.deleteMovie(id);
}
@Patch('/:id/signed-url')
uploadImage(
@Body(ValidationPipe) uploadMovieImageDto: UploadMovieImageDto,
@Param('id', ParseIntPipe) id: number,
): Promise<{ signedUrl: string }> {
return this.moviesService.saveImageKey(id, uploadMovieImageDto);
}
}
|
<reponame>bowlofstew/blockchain-samples
package main
var samples = `
{
"contractState": {
"activeAssets": [
"The ID of a managed asset. The resource focal point for a smart contract."
],
"nickname": "TRADELANE",
"version": "The version number of the current contract"
},
"event": {
"allottedCredits": 123.456,
"assetID": "The ID of a managed asset. The resource focal point for a smart contract.",
"boughtCredits": 123.456,
"creditsForSale": 123.456,
"creditsRequestBuy": 123.456,
"email": "Contact information of the company will be stored here",
"extension": {},
"iconUrl": "Sensor and weather value will be stored in a string. So sensorWeatherData object could refer to this definition to store its value",
"location": {
"latitude": 123.456,
"longitude": 123.456
},
"notificationRead": true,
"phoneNum": "Contact information of the company will be stored here",
"precipitation": "Sensor and weather value will be stored in a string. So sensorWeatherData object could refer to this definition to store its value",
"pricePerCredit": 123.456,
"priceRequestBuy": 123.456,
"reading": 123.456,
"sensorID": 123.456,
"sensorlocation": {
"latitude": 123.456,
"longitude": 123.456
},
"soldCredits": 123.456,
"temperatureCelsius": "Sensor and weather value will be stored in a string. So sensorWeatherData object could refer to this definition to store its value",
"temperatureFahrenheit": "Sensor and weather value will be stored in a string. So sensorWeatherData object could refer to this definition to store its value",
"threshold": 123.456,
"timestamp": "2016-08-09T15:49:18.021728986-05:00",
"tradeBuySell": "Trade values are triggered for every trade which is processed. This contract stores every trade which will be made between two companies",
"tradeCompany": "Trade values are triggered for every trade which is processed. This contract stores every trade which will be made between two companies",
"tradeCredits": "Trade values are triggered for every trade which is processed. This contract stores every trade which will be made between two companies",
"tradePrice": "Trade values are triggered for every trade which is processed. This contract stores every trade which will be made between two companies",
"tradeTimestamp": "Trade values are triggered for every trade which is processed. This contract stores every trade which will be made between two companies",
"updateBuyCredits": 123.456,
"updateBuyIndex": 123.456,
"updateSellCredits": 123.456,
"updateSellIndex": 123.456,
"windDegrees": "Sensor and weather value will be stored in a string. So sensorWeatherData object could refer to this definition to store its value",
"windGustSpeed": "Sensor and weather value will be stored in a string. So sensorWeatherData object could refer to this definition to store its value",
"windSpeed": "Sensor and weather value will be stored in a string. So sensorWeatherData object could refer to this definition to store its value"
},
"initEvent": {
"nickname": "TRADELANE",
"version": "The ID of a managed asset. The resource focal point for a smart contract."
},
"state": {
"alerts": {
"active": [
"OVERCARBONEMISSION"
],
"cleared": [
"OVERCARBONEMISSION"
],
"raised": [
"OVERCARBONEMISSION"
]
},
"allottedCredits": 123.456,
"assetID": "The ID of a managed asset. The resource focal point for a smart contract.",
"boughtCredits": 123.456,
"compliant": true,
"contactInformation": {
"email": "Contact information of the company will be stored here",
"phoneNum": "Contact information of the company will be stored here"
},
"creditsBuyList": [
"<NAME>"
],
"creditsForSale": 123.456,
"creditsRequestBuy": 123.456,
"creditsSellList": [
"<NAME>"
],
"email": "Contact information of the company will be stored here",
"extension": {},
"iconUrl": "Sensor and weather value will be stored in a string. So sensorWeatherData object could refer to this definition to store its value",
"lastEvent": {
"args": [
"parameters to the function, usually args[0] is populated with a JSON encoded event object"
],
"function": "function that created this state object",
"redirectedFromFunction": "function that originally received the event"
},
"location": {
"latitude": 123.456,
"longitude": 123.456
},
"notificationRead": true,
"phoneNum": "Contact information of the company will be stored here",
"precipitation": "Sensor and weather value will be stored in a string. So sensorWeatherData object could refer to this definition to store its value",
"priceBuyList": [
"<NAME>"
],
"pricePerCredit": 123.456,
"priceRequestBuy": 123.456,
"priceSellList": [
"<NAME>"
],
"reading": 123.456,
"sensorID": 123.456,
"sensorWeatherHistory": {
"iconUrl": "<NAME>",
"precipitation": [
"Sensor and weather value will be stored in a string. So sensorWeatherData object could refer to this definition to store its value"
],
"sensorReading": [
"Sensor and weather value will be stored in a string. So sensorWeatherData object could refer to this definition to store its value"
],
"tempCelsius": [
"Sensor and weather value will be stored in a string. So sensorWeatherData object could refer to this definition to store its value"
],
"tempFahrenheit": [
"Sensor and weather value will be stored in a string. So sensorWeatherData object could refer to this definition to store its value"
],
"timestamp": [
"2016-08-09T15:49:18.022023884-05:00"
],
"windDegrees": [
"Sensor and weather value will be stored in a string. So sensorWeatherData object could refer to this definition to store its value"
],
"windGustSpeed": [
"Sensor and weather value will be stored in a string. So sensorWeatherData object could refer to this definition to store its value"
],
"windSpeed": [
"Sensor and weather value will be stored in a string. So sensorWeatherData object could refer to this definition to store its value"
]
},
"sensorlocation": {
"latitude": 123.456,
"longitude": 123.456
},
"soldCredits": 123.456,
"temperatureCelsius": "Sensor and weather value will be stored in a string. So sensorWeatherData object could refer to this definition to store its value",
"temperatureFahrenheit": "Sensor and weather value will be stored in a string. So sensorWeatherData object could refer to this definition to store its value",
"threshold": 123.456,
"timestamp": "2016-08-09T15:49:18.022033248-05:00",
"tradeBuySell": "Trade values are triggered for every trade which is processed. This contract stores every trade which will be made between two companies",
"tradeCompany": "Trade values are triggered for every trade which is processed. This contract stores every trade which will be made between two companies",
"tradeCredits": "Trade values are triggered for every trade which is processed. This contract stores every trade which will be made between two companies",
"tradeHistory": {
"buysell": [
"Trade values are triggered for every trade which is processed. This contract stores every trade which will be made between two companies"
],
"company": [
"Trade values are triggered for every trade which is processed. This contract stores every trade which will be made between two companies"
],
"credits": [
"Trade values are triggered for every trade which is processed. This contract stores every trade which will be made between two companies"
],
"price": [
"Trade values are triggered for every trade which is processed. This contract stores every trade which will be made between two companies"
],
"timestamp": [
"2016-08-09T15:49:18.022017853-05:00"
]
},
"tradePrice": "Trade values are triggered for every trade which is processed. This contract stores every trade which will be made between two companies",
"tradeTimestamp": "Trade values are triggered for every trade which is processed. This contract stores every trade which will be made between two companies",
"txntimestamp": "Transaction timestamp matching that in the blockchain.",
"txnuuid": "Transaction UUID matching that in the blockchain.",
"updateBuyCredits": 123.456,
"updateBuyIndex": 123.456,
"updateSellCredits": 123.456,
"updateSellIndex": 123.456,
"windDegrees": "Sensor and weather value will be stored in a string. So sensorWeatherData object could refer to this definition to store its value",
"windGustSpeed": "Sensor and weather value will be stored in a string. So sensorWeatherData object could refer to this definition to store its value",
"windSpeed": "Sensor and weather value will be stored in a string. So sensorWeatherData object could refer to this definition to store its value"
}
}` |
#!/bin/bash
declare -a folders=("csharp20" "csharp21" "java" "python" "golang" "nodejs8")
export AWS_PROFILE=personal
for i in `seq 1 1000`;
do
for folder in "${folders[@]}"
do
cd $folder
pwd
sls deploy --force
cd ..
done
node invoke-functions.js
done
|
<filename>vi/.vim/bundle/pencil/app/views/editors/StrokeEditor.js
function StrokeEditor() {
PropertyEditor.call(this);
}
__extend(PropertyEditor, StrokeEditor);
StrokeEditor.prototype.setup = function () {
//setting up dasharray
var STYLES = [ [Util.getMessage("stroke.style.solid"), ""],
[Util.getMessage("stroke.style.dotted"), "1,3"],
[Util.getMessage("stroke.style.condensed.dotted"), "1,1"],
[Util.getMessage("stroke.style.dashed"), "5,5"],
[Util.getMessage("stroke.style.condensed.dashed"), "3,3"],
[Util.getMessage("stroke.style.dashed.dotted"), "8,4,1,4"],
[Util.getMessage("stroke.style.condensed.dashed.dotted"), "4,2,1,2"]
];
var strokeItems = [];
for (var i in STYLES) {
var label = STYLES[i][0];
var value = STYLES[i][1];
var item = {
label: label,
value: value
}
strokeItems.push(item);
}
this.items = strokeItems;
var thiz = this;
this.styleCombo.renderer = function (style) {
var svg = Dom.newDOMElement({
_name: "div",
"class": "StrokeStyleComboItem",
style: "width: 100px; height: 1em; position: relative;",
_children: [
{
_name: "svg",
_uri: PencilNamespaces.svg,
version: "1.1",
viewBox: "0 0 100 1",
height: "8",
width: "100",
style: "position: absolute; top: 50%; left: 0px; margin-top: -4px;",
_children: [
{
_name: "path",
_uri: PencilNamespaces.svg,
d: "m 0,0.5 100,0",
style: "fill:none;stroke:#000000;stroke-width:2;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:" + style.value + ";stroke-dashoffset:0"
}
]
}
]
});
return svg;
};
this.styleCombo.decorator = function (node, style) {
};
this.styleCombo.setItems(strokeItems);
var thiz = this;
this.styleCombo.addEventListener("p:ItemSelected", function (event) {
thiz.fireChangeEvent();
}, false);
this.strokeWidth.addEventListener("input", function (event) {
if (thiz.strokeWidth.value == "") thiz.strokeWidth.value = 1;
thiz.fireChangeEvent();
}, false);
};
StrokeEditor.prototype.setValue = function (stroke) {
this.strokeWidth.value = stroke.w;
var item = null;
for (var i = 0; i < this.items.length; i++) {
if (this.items[i].value == stroke.array) {
item = this.items[i];
break;
}
}
this.styleCombo.selectItem(item);
};
StrokeEditor.prototype.getValue = function () {
var stroke = new StrokeStyle();
stroke.w = this.strokeWidth.value;
stroke.array = this.styleCombo.getSelectedItem().value;
return stroke;
};
StrokeEditor.prototype.setDisabled = function (disabled) {
if (disabled == true) {
this.strokeWidth.setAttribute("disabled", "true");
this.styleCombo.setDisabled(true);
} else {
this.strokeWidth.removeAttribute("disabled");
this.styleCombo.setDisabled(false);
}
};
|
package com.hapramp.views.skills;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import com.hapramp.R;
import com.hapramp.models.CommunityModel;
import com.hapramp.utils.CommunityUtils;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* Created by Ankit on 6/22/2017.
*/
public class CommunityItemView extends FrameLayout {
ImageView communityIcon;
FrameLayout communityBackground;
TextView communityTitle;
private Context mContext;
private CommunityModel mCommunity;
public CommunityItemView(Context context) {
super(context);
init(context);
}
private void init(Context context) {
this.mContext = context;
View view = LayoutInflater.from(context).inflate(R.layout.community_selection_item_view, this);
communityIcon = view.findViewById(R.id.community_icon);
communityBackground = view.findViewById(R.id.community_background);
communityTitle = view.findViewById(R.id.community_title);
}
public CommunityItemView(@NonNull Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init(context);
}
public CommunityItemView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context);
}
public void setSelection(boolean selected) {
if (selected) {
communityBackground.setBackgroundResource(CommunityUtils.getFilledBackground(mCommunity.getmTag()));
} else {
communityBackground.setBackgroundResource(CommunityUtils.getBorder(mCommunity.getCommunityId()));
}
}
public int getCommunityId() {
return mCommunity.getCommunityId();
}
public void setCommunityDetails(CommunityModel communityModel) {
this.mCommunity = communityModel;
setCommunityImage(CommunityUtils.getCommunityIcon(communityModel.getmTag()));
setCommunityTitle(mCommunity.getmName());
}
private void setCommunityImage(int resId) {
try {
communityIcon.setImageResource(resId);
}catch (Exception e){
}
}
private void setCommunityTitle(String title) {
communityTitle.setText(title);
}
}
|
package com.itstore.controllers;
import com.itstore.models.Category;
import com.itstore.models.Item;
import com.itstore.models.User;
import com.itstore.services.CategoryService;
import com.itstore.services.ItemService;
import com.itstore.services.LoginService;
import com.itstore.services.SessionService;
import com.itstore.services.UserService;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
/*
* @author Tanevski
*/
@Controller
public class ItemController {
@RequestMapping(value = "/item", method = RequestMethod.GET)
public String getItem(ItemService itemService, ModelMap model, HttpServletRequest request, SessionService sessionService, LoginService loginService) {
User loggedUser = null;
sessionService.init(request);
loginService.setService(sessionService);
String theid = request.getParameter("itemId");
if (loginService.isLoggedIn()) {
loggedUser = (User) sessionService.getAttribute("user");
sessionService.setAttribute("user", loggedUser);
if (request.getParameterNames().hasMoreElements()) {
if (theid != null) {
if (!itemService.deleteItemById(Integer.parseInt(theid))) {
model.addAttribute("validationLabel", "User deletion failed!");
List<Item> allItems = itemService.getAllItems();
model.addAttribute("allItems", allItems);
model.addAttribute("loggedUserName", loggedUser.getFirstName());
return "item";
}
}
List<Item> allItems = itemService.getAllItems();
model.addAttribute("allItems", allItems);
model.addAttribute("loggedUserName", loggedUser.getFirstName());
return "item";
} else {
List<Item> allItems = itemService.getAllItems();
model.addAttribute("allItems", allItems);
model.addAttribute("loggedUserName", loggedUser.getFirstName());
return "item";
}
} else {
List<Item> allItems = itemService.getAllItems();
model.addAttribute("validationLabel", "Access restricted.");
return "login";
}
}
@RequestMapping(method = RequestMethod.GET, value = "/createitem")
public String createItemForm(HttpServletRequest request, ModelMap model, CategoryService categoryService,
SessionService sessionService, LoginService loginService, ItemService itemService) {
User loggedUser = null;
sessionService.init(request);
loginService.setService(sessionService);
if (loginService.isLoggedIn()) {
loggedUser = (User) sessionService.getAttribute("user");
sessionService.setAttribute("user", loggedUser);
List<Category> categories = categoryService.getAllCategories();
Item item = new Item();
model.addAttribute("allCategories", categories);
model.addAttribute("loggedUserName", loggedUser.getFirstName());
model.addAttribute("createItem", item);
return "createitem";
} else {
List<Item> allItems = itemService.getAllItems();
model.addAttribute("validationLabel", "Access restricted.");
return "login";
}
}
@RequestMapping(method = RequestMethod.POST, value = "/createitem")
public String processCreateItemForm(@ModelAttribute("createItem") Item item,
@RequestParam(value = "title", required = false) String title,
@RequestParam(value = "specification", required = false) String specification,
@RequestParam(value = "description", required = false) String description,
@RequestParam(value = "imageSource", required = false) String imageSource,
@RequestParam(value = "price", required = false) Integer price,
@RequestParam(value = "stock", required = false) Integer stock,
@RequestParam(value = "user.id", required = false) String userId,
@RequestParam(value = "category.id", required = false) String categoryId,
ModelMap model,
HttpServletRequest request,
ItemService itemService,
UserService userService,
SessionService sessionService,
LoginService loginService) {
User loggedUser = null;
sessionService.init(request);
loginService.setService(sessionService);
loggedUser = (User) sessionService.getAttribute("user");
if (loginService.isLoggedIn()) {
loggedUser = (User) sessionService.getAttribute("user");
item.setTitle(title);
item.setDescription(description);
item.setSpecification(specification);
item.setImageSource(imageSource);
item.setPrice(price);
item.setStock(stock);
item.setPostDate(new Date());
Category currentCategory = item.getCategory();
currentCategory.setId(Integer.parseInt(categoryId));
User currentUser = item.getUser();
currentUser.setId(loggedUser.getId());
item.setUser(loggedUser);
if (!itemService.addItem(item)) {
model.addAttribute("validationLabel", "Item creation failed!");
model.addAttribute("loggedUserName", loggedUser.getFirstName());
model.addAttribute("allItems", itemService.getAllItems());
return "item";
}
model.addAttribute("loggedUserName", loggedUser.getFirstName());
model.addAttribute("allItems", itemService.getAllItems());
return "item";
} else {
List<Item> allItems = itemService.getAllItems();
model.addAttribute("validationLabel", "Access restricted.");
return "login";
}
}
@RequestMapping(value = "/updateitem", method = RequestMethod.GET)
public String showUpdateItemForm(HttpServletRequest request, ModelMap model,
ItemService itemService, CategoryService categoryService,
SessionService sessionService, LoginService loginService) {
User loggedUser = null;
sessionService.init(request);
loginService.setService(sessionService);
if (loginService.isLoggedIn()) {
loggedUser = (User) sessionService.getAttribute("user");
if (request.getParameterNames().hasMoreElements()) {
Item item = new Item();
String theid = request.getParameter("itemId");
item.setId(Integer.parseInt(theid));
Item currentItem = itemService.findItembyId(Integer.parseInt(theid));
List<Category> categories = categoryService.getAllCategories();
model.addAttribute("updateItemForm", item);
model.addAttribute("allCategories", categories);
model.addAttribute("currentTitle", currentItem.getTitle());
model.addAttribute("currentSpecification", currentItem.getSpecification());
model.addAttribute("currentDescription", currentItem.getDescription());
model.addAttribute("currentImageSource", currentItem.getImageSource());
model.addAttribute("currentPrice", currentItem.getPrice());
model.addAttribute("currentStock", currentItem.getStock());
model.addAttribute("currentUserId", currentItem.getUser().getId());
model.addAttribute("currentCategoryId", currentItem.getCategory().getId());
model.addAttribute("loggedUserName", loggedUser.getFirstName());
return "updateitem";
} else {
Item item = new Item();
List<Category> categories = categoryService.getAllCategories();
model.addAttribute("allCategories", categories);
model.addAttribute("updateItemForm", item);
model.addAttribute("loggedUserName", loggedUser.getFirstName());
return "updateitem";
}
} else {
List<Item> allItems = itemService.getAllItems();
model.addAttribute("validationLabel", "Access restricted.");
return "login";
}
}
@RequestMapping(value = "/updateitem", method = RequestMethod.POST)
public String processUpdateItemForm(HttpServletRequest request,
@ModelAttribute(value = "updateItemForm") Item item, ItemService itemService,
ModelMap model, SessionService sessionService, LoginService loginService,
@RequestParam(value = "title", required = false) String title,
@RequestParam(value = "specification", required = false) String specification,
@RequestParam(value = "description", required = false) String description,
@RequestParam(value = "imageSource", required = false) String imageSource,
@RequestParam(value = "price", required = false) Integer price,
@RequestParam(value = "stock", required = false) Integer stock,
@RequestParam(value = "user.id", required = false) String userId,
@RequestParam(value = "category.id", required = false) String categoryId) {
User loggedUser = null;
sessionService.init(request);
loginService.setService(sessionService);
if (loginService.isLoggedIn()) {
loggedUser = (User) sessionService.getAttribute("user");
item.setTitle(title);
item.setDescription(description);
item.setSpecification(specification);
item.setImageSource(imageSource);
item.setPrice(price);
item.setStock(stock);
item.setPostDate(new Date());
User currentUser = item.getUser();
currentUser.setId(Integer.parseInt(userId));
Category currentCategory = item.getCategory();
currentCategory.setId(Integer.parseInt(categoryId));
if (!itemService.updateItem(item)) {
model.addAttribute("validationLabel", "User update failed!");
model.addAttribute("allItems", itemService.getAllItems());
model.addAttribute("loggedUserName", loggedUser.getFirstName());
return "item";
}
model.addAttribute("loggedUserName", loggedUser.getFirstName());
model.addAttribute("allItems", itemService.getAllItems());
return "item";
} else {
List<Item> allItems = itemService.getAllItems();
model.addAttribute("validationLabel", "Access restricted.");
return "login";
}
}
}
|
def sortStrings(wordsList):
sorted_list = sorted(wordsList)
return sorted_list
wordsList = ["apple", "banana", "mango", "pear"]
sorted_words = sortStrings(wordsList)
print(sorted_words) |
<reponame>joshua-r/gl<filename>src/window.cpp
#include <window.hpp>
namespace gl {
Window::Window() : m_title{"New Window"} {}
Window::Window(std::string title) : m_title{title} {}
bool Window::init(const glm::uvec2& resolution, std::string monitor_name) {
// use the primary monitor by default
GLFWmonitor* monitor = glfwGetPrimaryMonitor();
// find the monitor with the given name if one was given
if (!monitor_name.empty()) {
int monitor_count;
GLFWmonitor** monitors = glfwGetMonitors(&monitor_count);
for (int i = 0; i < monitor_count; ++i) {
auto name = std::string{glfwGetMonitorName(monitors[i])};
if (name == monitor_name) {
monitor = monitors[i];
break;
}
}
if (!monitor) {
throw std::runtime_error("Monitor '" + monitor_name + "' was not found!");
}
} else {
// get the primary monitor's name
monitor_name = std::string{glfwGetMonitorName(monitor)};
}
auto mode = glfwGetVideoMode(monitor);
if (resolution.x > 0 && resolution.y > 0) {
m_resolution = resolution;
} else {
m_resolution = glm::uvec2{mode->width, mode->height};
}
auto window = glfwCreateWindow(m_resolution.x, m_resolution.y, m_title.c_str(), monitor, nullptr);
// store the screen size
int width_mm, height_mm;
glfwGetMonitorPhysicalSize(monitor, &width_mm, &height_mm);
m_screen_size = glm::vec2{width_mm, height_mm} / 1000.0f; // convert from mm to m
if (!window) {
return false;
}
glfwMakeContextCurrent(window);
m_window = std::unique_ptr<GLFWwindow, DestroyGlfwWin>(window);
// set this class as user pointer to access it in callbacks
glfwSetWindowUserPointer(m_window.get(), this);
// error callback
glfwSetErrorCallback([](int code, const char* description) {
// simply log the error
std::cerr << "GLFW Error " << code << ": " << description << std::endl;
});
// framebuffer size callback
glfwSetFramebufferSizeCallback(m_window.get(), [](GLFWwindow* window, int width, int height) {
auto win = static_cast<Window*>(glfwGetWindowUserPointer(window));
win->on_resize(width, height);
});
// keyboard callback
glfwSetKeyCallback(m_window.get(), [](GLFWwindow* window, int key, int scancode, int action, int mods) {
auto win = static_cast<Window*>(glfwGetWindowUserPointer(window));
win->on_key(key, scancode, action, mods);
});
// mouse cursor pos callback
glfwSetCursorPosCallback(m_window.get(), [](GLFWwindow* window, double x, double y) {
auto win = static_cast<Window*>(glfwGetWindowUserPointer(window));
win->on_mouse_move(x, y);
});
// mouse button callback
glfwSetMouseButtonCallback(m_window.get(), [](GLFWwindow* window, int button, int action, int mods) {
auto win = static_cast<Window*>(glfwGetWindowUserPointer(window));
win->on_mouse_button(button, action, mods);
});
// scroll callback
glfwSetScrollCallback(m_window.get(), [](GLFWwindow* window, double x, double y) {
auto win = static_cast<Window*>(glfwGetWindowUserPointer(window));
win->on_scroll(x, y);
});
return window;
}
void Window::clear() const {
glfwMakeContextCurrent(m_window.get());
glClearColor(m_clear_color.r, m_clear_color.g, m_clear_color.b, m_clear_color.a);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}
void Window::swap_buffers() const {
glfwSwapBuffers(m_window.get());
}
const glm::vec2 Window::screen_size() const {
return m_screen_size;
}
const glm::vec4 Window::clear_color() const {
return m_clear_color;
}
bool Window::should_close() const {
return glfwWindowShouldClose(m_window.get());
}
void Window::set_screen_size(const glm::vec2& size) {
m_screen_size = size;
}
void Window::set_clear_color(const glm::vec4& clear_color) {
m_clear_color = clear_color;
}
void Window::set_should_close(bool should_close) const {
glfwSetWindowShouldClose(m_window.get(), should_close);
}
void Window::set_vsync(bool enable) const {
enable ? glfwSwapInterval(1) : glfwSwapInterval(0);
}
void Window::on_resize(int width, int height) {
m_resolution = glm::uvec2{width, height};
}
void Window::on_key(int key, int scancode, int action, int mods) {
#ifndef NDEBUG
if (action == GLFW_PRESS) {
auto key_name = glfwGetKeyName(key, scancode);
if (key_name) {
std::cout << "Key '" << key_name << "' was pressed" << std::endl;
} else {
std::cout << "Key '" << key << "' was pressed" << std::endl;
}
}
#endif
if (action == GLFW_PRESS && (key == GLFW_KEY_ESCAPE) || (key == GLFW_KEY_Q)) {
set_should_close(true);
}
}
void Window::on_mouse_move(double x, double y) {}
void Window::on_mouse_button(int button, int action, int mods) {}
void Window::on_scroll(double x, double y) {}
} // namespace gl
|
package org.allenai.ml.classification;
import com.gs.collections.api.map.primitive.ObjectDoubleMap;
import com.gs.collections.api.tuple.primitive.ObjectDoublePair;
public interface ProbabilisticClassifier<D, L> extends Classifier<D, L> {
ObjectDoubleMap<L> probabilities(D datum);
/**
* Default to just the `argMax` of the `probabilties`
*/
default L bestGuess(D datum) {
ObjectDoublePair<L> max = null;
for (ObjectDoublePair<L> pair : probabilities(datum).keyValuesView()) {
if (max == null || pair.getTwo() > max.getTwo()) {
max = pair;
}
}
return max.getOne();
}
}
|
import Car from './car';
import { goodCarsId } from './home-utils';
export default class CarsApi {
constructor(
url = 'https://private-anon-66fbb79774-carsapi1.apiary-mock.com/',
) {
this.rootEndpoint = url;
this.allCarsEndpoint = `${url}cars`;
this.goodCarsId = goodCarsId;
this.dataPromise = this.getAllCars().then((data) => this.#formatCars(data));
}
getDataPromise = () => this.dataPromise;
#formatCars = (data) => {
const dataObj = {};
data.forEach((car) => {
const id = `${car.id}`;
dataObj[id] = car;
});
return dataObj;
};
getCarEndpointFromId = (id) => `${this.allCarsEndpoint}/${id}`;
#formatData = (data) => data.map((obj) => {
const car = new Car();
car.year = obj.year;
car.id = obj.id;
car.horsepower = obj.horsepower;
car.make = obj.make;
car.model = obj.model;
car.price = obj.price;
car.imgUrl = obj.img_url;
return car;
});
getAllCars = async (url = this.allCarsEndpoint) => {
const response = await fetch(url, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
});
let data = await response.json();
data = data.filter((obj) => this.goodCarsId.includes(obj.id));
data = await this.#formatData(data);
return data;
};
}
|
package gitpipe
import (
"context"
"errors"
"fmt"
"io"
"sync"
"gitlab.com/gitlab-org/gitaly/v14/internal/git/catfile"
)
// CatfileObjectResult is a result for the CatfileObject pipeline step.
type CatfileObjectResult struct {
// err is an error which occurred during execution of the pipeline.
err error
// ObjectName is the object name as received from the revlistResultChan.
ObjectName []byte
// ObjectInfo is the object info of the object.
ObjectInfo *catfile.ObjectInfo
// obbjectReader is the reader for the raw object data. The reader must always be consumed
// by the caller.
ObjectReader io.Reader
}
// CatfileObject processes catfileInfoResults from the given channel and reads associated objects
// into memory via `git cat-file --batch`. The returned channel will contain all processed objects.
// Any error received via the channel or encountered in this step will cause the pipeline to fail.
// Context cancellation will gracefully halt the pipeline. The returned object readers must always
// be fully consumed by the caller.
func CatfileObject(
ctx context.Context,
catfileProcess catfile.Batch,
it CatfileInfoIterator,
) CatfileObjectIterator {
resultChan := make(chan CatfileObjectResult)
go func() {
defer close(resultChan)
sendResult := func(result CatfileObjectResult) bool {
// In case the context has been cancelled, we have a race between observing
// an error from the killed Git process and observing the context
// cancellation itself. But if we end up here because of cancellation of the
// Git process, we don't want to pass that one down the pipeline but instead
// just stop the pipeline gracefully. We thus have this check here up front
// to error messages from the Git process.
select {
case <-ctx.Done():
return true
default:
}
select {
case resultChan <- result:
return false
case <-ctx.Done():
return true
}
}
var objectReader *signallingReader
for it.Next() {
catfileInfoResult := it.Result()
// We mustn't try to read another object before reading the previous object
// has concluded. Given that this is not under our control but under the
// control of the caller, we thus have to wait until the blocking reader has
// reached EOF.
if objectReader != nil {
select {
case <-objectReader.doneCh:
case <-ctx.Done():
return
}
}
var object *catfile.Object
var err error
objectType := catfileInfoResult.ObjectInfo.Type
switch objectType {
case "tag":
object, err = catfileProcess.Tag(ctx, catfileInfoResult.ObjectInfo.Oid.Revision())
case "commit":
object, err = catfileProcess.Commit(ctx, catfileInfoResult.ObjectInfo.Oid.Revision())
case "tree":
object, err = catfileProcess.Tree(ctx, catfileInfoResult.ObjectInfo.Oid.Revision())
case "blob":
object, err = catfileProcess.Blob(ctx, catfileInfoResult.ObjectInfo.Oid.Revision())
default:
err = fmt.Errorf("unknown object type %q", objectType)
}
if err != nil {
sendResult(CatfileObjectResult{
err: fmt.Errorf("requesting object: %w", err),
})
return
}
objectReader = &signallingReader{
reader: object,
doneCh: make(chan interface{}),
}
if isDone := sendResult(CatfileObjectResult{
ObjectName: catfileInfoResult.ObjectName,
ObjectInfo: catfileInfoResult.ObjectInfo,
ObjectReader: objectReader,
}); isDone {
return
}
}
if err := it.Err(); err != nil {
sendResult(CatfileObjectResult{err: err})
return
}
}()
return &catfileObjectIterator{
ch: resultChan,
}
}
type signallingReader struct {
reader io.Reader
doneCh chan interface{}
closeOnce sync.Once
}
func (r *signallingReader) Read(p []byte) (int, error) {
n, err := r.reader.Read(p)
if errors.Is(err, io.EOF) {
r.closeOnce.Do(func() {
close(r.doneCh)
})
}
return n, err
}
|
import re
def extract_class_info(code: str) -> dict:
class_info = {}
class_pattern = r'context\.registerClass\((\w+),\s+constructors=\((\w+),\s*(\w+)?\),\s*icon=\'(www\/\w+\.gif)?\'\)'
matches = re.findall(class_pattern, code)
for match in matches:
class_name = match[0]
form_name = match[1]
icon = match[3] if match[3] else None
class_info[class_name] = (form_name, icon)
return class_info
# Test the function with the given code snippet
code = """
constructors=(addMemCacheProxyForm,
addMemCacheProxy),
icon='www/proxy.gif')
from .sessiondata import MemCacheSessionDataContainer
from .sessiondata import addMemCacheSessionDataContainer
from .sessiondata import addMemCacheSessionDataContainerForm
context.registerClass(MemCacheSessionDataContainer,
constructors=(addMemCacheSessionDataContainerForm,
addMemCacheSessionDataContainer),
"""
print(extract_class_info(code)) |
<filename>Lesson22/QuizTen.py
# Define a procedure is_palindrome, that takes as input a string, and returns a
# Boolean indicating if the input string is a palindrome.
# Base Case: '' => True
# Recursive Case: if first and last characters don't match => False
# if they do match, is the middle a palindrome?
def is_palindrome(word):
if word == '':
return True
else:
if word[0] == word [-1]:
new_word = word[1:-1]
return is_palindrome(new_word)
else:
return False
print is_palindrome('')
#>>> True
print is_palindrome('abab')
#>>> False
print is_palindrome('abba')
#>>> True
|
#!/bin/bash
# Generate a random string
PASS=$(openssl rand -base64 12)
CA_CERTIFICATES_DIR=/usr/share/ca-certificates/safelocalhost
TEMP_DIR=$PWD/temp
ROOT_KEY=$TEMP_DIR/root_key.key
ROOT_CRT=$TEMP_DIR/root_crt.crt
SERVER_CSR=$TEMP_DIR/server.csr
SERVER_KEY=$TEMP_DIR/server.key
SERVER_CRT=$TEMP_DIR/server.crt
PEM=$TEMP_DIR/public_certificate.pem
CNF_SETTINGS=$TEMP_DIR/cnf_settings.cnf
V3_SETTINGS=$TEMP_DIR/v3_settings.ext
# Directories
# ..................................................................................................................................................................
mkdir -p $TEMP_DIR
if [[ ! -e $CA_CERTIFICATES_DIR ]]; then
sudo mkdir -p $CA_CERTIFICATES_DIR
fi
# Create a new OpenSSL configuration
# ..................................................................................................................................................................
cat > $CNF_SETTINGS << EOL
[req]
default_bits=2048
prompt=no
default_md=sha256
distinguished_name=dn
days=1024
[dn]
C=VE
ST=ACME STATE
L=ACME CITY
O=ACME
OU=ACME DEV
emailAddress=acme@industries.com
CN=localhost
EOL
# Create a X509 v3 certificate configuration file. Notice how we’re specifying subjectAltName here.
# ..................................................................................................................................................................
cat > $V3_SETTINGS << EOL
authorityKeyIdentifier=keyid,issuer
basicConstraints=CA:FALSE
keyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment
subjectAltName = @alt_names
[alt_names]
DNS.1 = *.localhost
DNS.2 = localhost
EOL
# CREATE ROOT KEY
# ..................................................................................................................................................................
openssl genpkey -aes-256-cbc -algorithm RSA -out $ROOT_KEY -pkeyopt rsa_keygen_bits:4096 -pass pass:$PASS
# CREATE PEM
# ..................................................................................................................................................................
openssl req -x509 -new -nodes -key $ROOT_KEY -sha256 -days 1024 -out $PEM -config <( cat $CNF_SETTINGS ) -passin pass:$PASS
# CREATE ROOT CRT
# ..................................................................................................................................................................
openssl x509 -in $PEM -inform PEM -out $ROOT_CRT
# MOVE ROOT CRT TO CERTIFICATES_HOME
# ..................................................................................................................................................................
sudo cp $ROOT_CRT $CA_CERTIFICATES_DIR
# INSTALL ROOT CRT
# ..................................................................................................................................................................
sudo update-ca-certificates
# ..................................................................................................................................................................
#
# Server Client
#
# ..................................................................................................................................................................
# Create a certificate key for localhost.
# ..................................................................................................................................................................
openssl req -new -sha256 -nodes -out $SERVER_CSR -newkey rsa:2048 -keyout $SERVER_KEY -config <( cat $CNF_SETTINGS )
# A certificate signing request is issued via the root SSL certificate we created earlier to create a domain certificate for localhost. The output is a certificate file called server.crt.
# ..................................................................................................................................................................
openssl x509 -req -in $SERVER_CSR -CA $PEM -CAkey $ROOT_KEY -CAcreateserial -out $SERVER_CRT -days 500 -sha256 -extfile $V3_SETTINGS -passin pass:$PASS
|
#!/bin/bash
gcloud compute instances create $1 \
--zone us-west1-a \
--source-instance-template sniffles-template \
--create-disk=boot=yes,image=sniffles-image-v1,size=100GB \
--scopes=storage-full,compute-rw,logging-write \
--local-ssd=interface=NVME \
--metadata CHR=$2,THREADS=$3,CONFIG_FILE_URL=$4,startup-script='#!/bin/bash
git clone https://github.com/gsneha26/urWGS.git
bash -c ./urWGS/setup/mount_ssd_nvme.sh
mv urWGS /data/
export PROJECT_DIR=/data/urWGS
CONFIG_FILE_URL=$(gcloud compute instances describe $(hostname) --zone=$(gcloud compute instances list --filter="name=($(hostname))" --format "value(zone)") --format=value"(metadata[CONFIG_FILE_URL])")
gsutil cp $CONFIG_FILE_URL /data/sample.config
echo "2" > /data/sniffles_status.txt
chmod a+w -R /data/
chmod +x $PROJECT_DIR/*/*.sh
echo -e "SHELL=/bin/bash\nPATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/snap/bin\nPROJECT_DIR=$PROJECT_DIR\n*/1 * * * * bash -c $PROJECT_DIR/sniffles/run_sniffles_pipeline_wrapper.sh >> /data/stdout.log 2>> /data/stderr.log" | crontab -'
|
// Copyright 2020 The Kubernetes Authors.
// SPDX-License-Identifier: Apache-2.0
package e2e
import (
"context"
"errors"
"sort"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"sigs.k8s.io/cli-utils/pkg/apply"
applyerror "sigs.k8s.io/cli-utils/pkg/apply/error"
"sigs.k8s.io/cli-utils/pkg/apply/event"
"sigs.k8s.io/cli-utils/pkg/object"
"sigs.k8s.io/cli-utils/pkg/testutil"
"sigs.k8s.io/controller-runtime/pkg/client"
)
func continueOnErrorTest(c client.Client, invConfig InventoryConfig, inventoryName, namespaceName string) {
By("apply an invalid CRD")
applier := invConfig.ApplierFactoryFunc()
inv := invConfig.InvWrapperFunc(invConfig.InventoryFactoryFunc(inventoryName, namespaceName, "test"))
resources := []*unstructured.Unstructured{
manifestToUnstructured(invalidCrd),
withNamespace(manifestToUnstructured(pod1), namespaceName),
}
applierEvents := runCollect(applier.Run(context.TODO(), inv, resources, apply.Options{}))
expEvents := []testutil.ExpEvent{
{
// InitTask
EventType: event.InitType,
InitEvent: &testutil.ExpInitEvent{},
},
{
// InvAddTask start
EventType: event.ActionGroupType,
ActionGroupEvent: &testutil.ExpActionGroupEvent{
Action: event.InventoryAction,
GroupName: "inventory-add-0",
Type: event.Started,
},
},
{
// InvAddTask finished
EventType: event.ActionGroupType,
ActionGroupEvent: &testutil.ExpActionGroupEvent{
Action: event.InventoryAction,
GroupName: "inventory-add-0",
Type: event.Finished,
},
},
{
// ApplyTask start
EventType: event.ActionGroupType,
ActionGroupEvent: &testutil.ExpActionGroupEvent{
Action: event.ApplyAction,
GroupName: "apply-0",
Type: event.Started,
},
},
{
// Apply invalidCrd fails
EventType: event.ApplyType,
ApplyEvent: &testutil.ExpApplyEvent{
GroupName: "apply-0",
Identifier: object.UnstructuredToObjMetaOrDie(manifestToUnstructured(invalidCrd)),
Error: testutil.EqualErrorType(
applyerror.NewApplyRunError(errors.New("failed to apply")),
),
},
},
{
// Create pod1
EventType: event.ApplyType,
ApplyEvent: &testutil.ExpApplyEvent{
GroupName: "apply-0",
Operation: event.Created,
Identifier: object.UnstructuredToObjMetaOrDie(withNamespace(manifestToUnstructured(pod1), namespaceName)),
Error: nil,
},
},
{
// ApplyTask finished
EventType: event.ActionGroupType,
ActionGroupEvent: &testutil.ExpActionGroupEvent{
Action: event.ApplyAction,
GroupName: "apply-0",
Type: event.Finished,
},
},
// Note: No WaitTask when apply fails
// TODO: why no wait after create tho?
// {
// // WaitTask start
// EventType: event.ActionGroupType,
// ActionGroupEvent: &testutil.ExpActionGroupEvent{
// Action: event.WaitAction,
// Name: "wait-0",
// Type: event.Started,
// },
// },
// {
// // WaitTask finished
// EventType: event.ActionGroupType,
// ActionGroupEvent: &testutil.ExpActionGroupEvent{
// Action: event.WaitAction,
// Name: "wait-0",
// Type: event.Finished,
// },
// },
{
// InvSetTask start
EventType: event.ActionGroupType,
ActionGroupEvent: &testutil.ExpActionGroupEvent{
Action: event.InventoryAction,
GroupName: "inventory-set-0",
Type: event.Started,
},
},
{
// InvSetTask finished
EventType: event.ActionGroupType,
ActionGroupEvent: &testutil.ExpActionGroupEvent{
Action: event.InventoryAction,
GroupName: "inventory-set-0",
Type: event.Finished,
},
},
}
receivedEvents := testutil.EventsToExpEvents(applierEvents)
// sort to allow comparison of multiple ApplyTasks in the same task group
sort.Sort(testutil.GroupedEventsByID(receivedEvents))
Expect(receivedEvents).To(testutil.Equal(expEvents))
By("Verify pod1 created")
assertUnstructuredExists(c, withNamespace(manifestToUnstructured(pod1), namespaceName))
By("Verify CRD not created")
assertUnstructuredDoesNotExist(c, manifestToUnstructured(invalidCrd))
}
|
var assert = require('..')
var a = 1
var b = 2
function test(fn) {
try {
fn()
} catch(e) {
console.info(e.message)
}
}
test(function() {
assert(a == b, '%d should equal %d!', a, b)
})
test(function() {
assert.ok(a == b, '%d should equal %d!', a, b)
})
test(function() {
assert.equal(a, b, 'assert.equal(%d, %d)')
})
test(function() {
assert.equal(a, b, 'assert.equal(%d [%s], %d [%s])', a, typeof a, b, typeof b)
})
test(function() {
assert.ifError(new Error('omg'), 'Bad Error %s')
})
test(function() {
assert.ifError(new Error('omg'))
})
test(function() {
function shouldThrow(){}
assert.throws(shouldThrow, '%s should have thrown!')
})
|
<gh_stars>1-10
#!/usr/bin/python
#
# from) $VIM/tools/demoserver.pyを拝借
#
# This requires Python 2.6 or later.
from __future__ import print_function
import json
import socket
import sys
import threading
import time
try:
# Python 3
import socketserver
except ImportError:
# Python 2
import SocketServer as socketserver
shared_message = None
lock = None
# メッセージ送信用
class ThreadedTCPSendHandler(socketserver.BaseRequestHandler):
def handle(self):
print("=== [S] socket opened ===")
global shared_message
global lock
while True:
try:
data = self.request.recv(40960).decode('utf-8') # NOTE: 適当なサイズ
except socket.error:
print("=== [S] socket error ===")
break
except IOError:
print("=== [S] socket closed ===")
break
if data == '':
print("=== [S] socket closed ===")
break
# print("received: {0}".format(data))
try:
decoded = json.loads(data)
except ValueError:
print("json decoding failed")
decoded = [-1, '']
# 本分の取得
response = ''
if decoded[0] >= 0:
with lock:
shared_message = decoded[1]
response = 'sended!'
else:
response = 'what?'
encoded = json.dumps([decoded[0], response])
print("sending {0}".format(encoded))
self.request.sendall(encoded.encode('utf-8'))
# メッセージ受信用
class ThreadedTCPReceiveHandler(socketserver.BaseRequestHandler):
def handle(self):
print("=== [R] socket opened ===")
global shared_message
global lock
while True:
try:
data = self.request.recv(4096).decode('utf-8')
except socket.error:
print("=== [R] socket error ===")
break
except IOError:
print("=== [R] socket closed ===")
break
if data == '':
print("=== [R] socket closed ===")
break
print("received: {0}".format(data))
try:
decoded = json.loads(data)
except ValueError:
print("json decoding failed")
decoded = [-1, '']
if decoded[0] >= 0:
if decoded[1] == 'message':
# メッセージをひたすら待つ
# FIXME: 受信するまで終われない
while True:
message = None
with lock:
if shared_message != None:
message = shared_message
shared_message = None
if message != None:
encoded = json.dumps([decoded[0], message])
print('sending message text')
self.request.sendall(encoded.encode('utf-8'))
break
time.sleep(0.1)
else:
# 知らないリクエスト
print('unknown request {0}'.format(decoded[1]))
pass
class ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
pass
def send_server():
HOST, PORT = "localhost", 13578
return server(HOST, PORT, ThreadedTCPSendHandler)
def recv_server():
HOST, PORT = "localhost", 13579
return server(HOST, PORT, ThreadedTCPReceiveHandler)
def server(host, port, tcpHandler):
server = ThreadedTCPServer((host, port), tcpHandler)
ip, port = server.server_address
# Start a thread with the server -- that thread will then start one
# more thread for each request
server_thread = threading.Thread(target=server.serve_forever)
# Exit the server thread when the main thread terminates
server_thread.daemon = True
server_thread.start()
print("Server loop running in thread: ", server_thread.name)
print("Listening on port {0}".format(port))
return server
if __name__ == "__main__":
lock = threading.RLock()
send_server = send_server()
recv_server = recv_server()
while True:
typed = sys.stdin.readline()
if "quit" in typed:
print("Goodbye!")
break
send_server.shutdown()
send_server.server_close()
recv_server.shutdown()
recv_server.server_close()
|
# frozen_string_literal: true
require 'rails'
require 'highline/import'
module DiscourseDev
class Config
attr_reader :config, :file_path
def initialize
default_file_path = File.join(DiscourseDev.root, "config", "dev.yml")
@file_path = File.join(Rails.root, "config", "dev.yml")
default_config = YAML.load_file(default_file_path)
if File.exists?(file_path)
user_config = YAML.load_file(file_path)
else
puts "I did no detect a custom `config/dev.yml` file, creating one for you where you can amend defaults."
FileUtils.cp(default_file_path, file_path)
user_config = {}
end
@config = default_config.deep_merge(user_config).deep_symbolize_keys
end
def update!
update_site_settings
create_admin_user
create_new_user
set_seed
end
private
def update_site_settings
puts "Updating site settings..."
site_settings = config[:site_settings] || {}
site_settings.each do |key, value|
puts "#{key} = #{value}"
SiteSetting.set(key, value)
end
SiteSetting.refresh!
end
def create_admin_user
puts "Creating default admin user account..."
settings = config[:admin]
if settings.present?
create_admin_user_from_settings(settings)
else
create_admin_user_from_input
end
end
def create_new_user
settings = config[:new_user]
if settings.present?
email = settings[:email] || "<EMAIL>"
new_user = ::User.create!(
email: email,
username: settings[:username] || UserNameSuggester.suggest(email)
)
new_user.email_tokens.update_all confirmed: true
new_user.activate
end
end
def set_seed
seed = self.seed || 1
Faker::Config.random = Random.new(seed)
end
def start_date
DateTime.parse(config[:start_date])
end
def method_missing(name)
config[name.to_sym]
end
def create_admin_user_from_settings(settings)
email = settings[:email]
admin = ::User.create!(
email: email,
username: settings[:username] || UserNameSuggester.suggest(email),
password: settings[:password]
)
admin.grant_admin!
if admin.trust_level < 1
admin.change_trust_level!(1)
end
admin.email_tokens.update_all confirmed: true
admin.activate
end
def create_admin_user_from_input
begin
email = ask("Email: ")
password = ask("Password (optional, press ENTER to skip): ")
username = UserNameSuggester.suggest(email)
admin = ::User.new(
email: email,
username: username
)
if password.present?
admin.password = password
else
puts "Once site is running use https://localhost:9292/user/#{username}/become to access the account in development"
end
admin.name = ask("Full name: ") if SiteSetting.full_name_required
saved = admin.save
if saved
File.open(file_path, 'a') do | file|
file.puts("admin:")
file.puts(" username: #{admin.username}")
file.puts(" email: #{admin.email}")
file.puts(" password: #{password}") if password.present?
end
else
say(admin.errors.full_messages.join("\n"))
end
end while !saved
admin.active = true
admin.save
admin.grant_admin!
if admin.trust_level < 1
admin.change_trust_level!(1)
end
admin.email_tokens.update_all confirmed: true
admin.activate
say("\nAdmin account created successfully with username #{admin.username}")
end
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.