text stringlengths 1 1.05M |
|---|
const Steps = `
type Steps {
id: ID!
date: String
steps: Int
addBonus: Int
reduceCarbon: Float
}
`;
module.exports = Steps;
|
// ----------------------------------------------------------------------------
//
// NetworkingApiConverters.h
//
// @author <NAME> <<EMAIL>>
// @copyright Copyright (c) 2017, Roxie Mobile Ltd. All rights reserved.
// @link https://www.roxiemobile.com/
//
// ----------------------------------------------------------------------------
@import Foundation;
// ----------------------------------------------------------------------------
//! Project version number for NetworkingApiConverters.
FOUNDATION_EXPORT double NetworkingApiConvertersVersionNumber;
//! Project version string for NetworkingApiConverters.
FOUNDATION_EXPORT const unsigned char NetworkingApiConvertersVersionString[];
// ----------------------------------------------------------------------------
|
#!/bin/sh
cname()
{
local tab=$1
echo $tab | cut -d"\$" -f2
}
upper()
{
local str=$1
echo $str | tr '[a-z]' '[A-Z]'
}
for tab in $(cat table.lst)
do
cat <<EOF > $(cname $tab).sql
select
'$(upper $(cname $tab))' CNAME, to_char(systimestamp, 'yyyy-mm-dd"T"hh24:mi:ss.ff') CTIMESTAMP,
$tab.*
from
$tab
/
EOF
done
|
#!/bin/bash
if [ -z `which nginx` ]; then
apt-get update
apt-get install nginx -y
rm /etc/nginx/sites-enabled/default
systemctl restart nginx
fi
if [ -z `which varnishd` ]; then
apt-get update
apt-get install varnish -y
fi
if [ -z `which docker` ]; then
apt-get update
apt-get install -y apt-transport-https ca-certificates curl software-properties-common
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable"
apt-get update
apt-get install -y docker-ce
fi
if [ -z `which docker-compose` ]; then
curl -L https://github.com/docker/compose/releases/download/1.21.2/docker-compose-$(uname -s)-$(uname -m) -o /usr/local/bin/docker-compose
chmod +x /usr/local/bin/docker-compose
fi
useradd overrustlelogs |
#! /bin/shell
# Copyright 2019-2029 geekidea(https://github.com/geekidea)
#
# 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.
#======================================================================
# 项目停服shell脚本
# 通过项目名称查找到PID
# 然后kill -9 pid
#
# author: geekidea
# date: 2018-12-2
#======================================================================
# 项目名称
APPLICATION="spring-boot-plus"
# 项目启动jar包名称
APPLICATION_JAR="${APPLICATION}.jar"
PID=$(ps -ef | grep ${APPLICATION_JAR} | grep -v grep | awk '{ print $2 }')
if [ -z "$PID" ]
then
echo ${APPLICATION} is already stopped
else
echo kill ${PID}
kill -9 ${PID}
echo ${APPLICATION} stopped successfully
fi |
<reponame>prt2121/android-workspace
package com.prt2121.cam;
import android.content.Context;
import android.hardware.Camera;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import java.io.IOException;
/**
* Created by pt2121 on 8/17/15.
*
* http://developer.android.com/guide/topics/media/camera.html
* http://developer.android.com/training/camera/cameradirect.html
* http://developer.android.com/guide/topics/media/camera.html#custom-camera
*/
public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {
public static final String TAG = CameraPreview.class.getSimpleName();
private SurfaceHolder mHolder;
private Camera mCamera;
// /sdcard/Pictures/MyCameraApp/
public CameraPreview(Context context, Camera camera) {
super(context);
mCamera = camera;
mHolder = getHolder();
mHolder.addCallback(this);
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
public void setCamera(Camera camera) {
mCamera = camera;
}
public void surfaceCreated(SurfaceHolder holder) {
try {
mCamera.setPreviewDisplay(holder);
mCamera.startPreview();
} catch (IOException e) {
Log.d(TAG, "Error setting camera preview: " + e.getMessage());
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
// empty. Take care of releasing the Camera preview in your activity.
}
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
if (mHolder.getSurface() == null) {
return;
}
try {
mCamera.stopPreview();
} catch (Exception e) {
// ignore: tried to stop a non-existent preview
}
// set preview size and make any resize, rotate or
// reformatting changes here
// start preview with new settings
try {
mCamera.setPreviewDisplay(mHolder);
mCamera.startPreview();
} catch (Exception e) {
Log.d(TAG, "Error starting camera preview: " + e.getMessage());
}
}
}
|
from typing import List, Dict
import re
def count_html_tags(html_snippet: str, tags: List[str]) -> Dict[str, int]:
tag_counts = {}
for tag in tags:
pattern = rf'<{tag}.*?>'
count = len(re.findall(pattern, html_snippet, re.IGNORECASE))
tag_counts[tag] = count
return tag_counts |
<filename>com.archimatetool.canvas/src/com/archimatetool/canvas/model/ICanvasModelBlock.java
/**
* This program and the accompanying materials
* are made available under the terms of the License
* which accompanies this distribution in the file LICENSE.txt
*/
package com.archimatetool.canvas.model;
import com.archimatetool.help.hints.IHelpHintProvider;
import com.archimatetool.model.IBorderObject;
import com.archimatetool.model.IDiagramModelContainer;
import com.archimatetool.model.ILockable;
import com.archimatetool.model.IProperties;
import com.archimatetool.model.ITextContent;
import com.archimatetool.model.ITextPosition;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Model Block</b></em>'.
* <!-- end-user-doc -->
*
*
* @see com.archimatetool.canvas.model.ICanvasPackage#getCanvasModelBlock()
* @model superTypes="com.archimatetool.canvas.model.Iconic com.archimatetool.model.DiagramModelContainer com.archimatetool.model.Properties com.archimatetool.model.Lockable com.archimatetool.model.BorderObject com.archimatetool.canvas.model.HelpHintProvider com.archimatetool.canvas.model.HintProvider com.archimatetool.model.TextContent com.archimatetool.model.TextPosition"
* @generated
*/
public interface ICanvasModelBlock extends IIconic, IDiagramModelContainer, IProperties, ILockable, IBorderObject, IHelpHintProvider, IHintProvider, ITextContent, ITextPosition {
} // ICanvasModelBlock
|
<reponame>AliFrank608-TMW/RacingReact
import React, { Component } from 'react'
import { connect } from 'react-redux'
import { withRouter } from 'react-router-dom'
import Input from 'components/input/Input'
import TextButton from 'components/buttons/TextButton'
import TextEditContainer from 'containers/ManagerEdit/TextEditContainer'
import SyndicateBenefits from 'components/syndicate/SyndicateBenefits'
import {submitSyndicateData} from 'actions/syndicate'
import {setSyndicateName, submitSyndicateName} from 'actions/registerSyndicate/syndicateName'
import { getItem } from 'utils/storageutils'
import { USER_TOKEN } from 'data/consts'
import {
registerNameTitle,
registerNameDescription
} from 'data/syndicate'
class RegisterSyndicateNameContainer extends Component {
constructor (props) {
super(props)
this.state = {
showEdit: false,
value: ''
}
}
submitSyndicateName () {
const token = getItem(USER_TOKEN)
this.props.submitSyndicateName(token, this.props.syndicateName)
.then(() => this.props.history.push('/register-syndicate'))
}
render () {
const nameData = {
description: registerNameDescription,
featuredImage: '',
logo: ''
}
return (
<div className="register-syndicate-name-content">
<div className="col-xs-12">
<div className="col-xs-12 col-sm-10 col-md-8 col-lg-7 name-description">
<TextEditContainer
title='Edit benefits'
data={nameData}
editLabel='update benefits'
dataKey='benefits'
maxLength={2000}
submitAction={submitSyndicateData}>
{
({ value }) => {
return (
<SyndicateBenefits title={registerNameTitle} titleModifier="h2" description={registerNameDescription} />
)
}
}
</TextEditContainer>
</div>
</div>
<div className="col-xs-12">
<div className="col-xs-12 col-sm-8 col-md-6 col-lg-5 name-input-section">
<Input
inputClassName='text-center'
name='counter'
handleChange={(e) => { this.props.setSyndicateName(e.currentTarget.value) }}
handleBlur={() => {}}
placeholder={`ENTER DESIRED NAME`} />
</div>
</div>
<div className="col-xs-12 name-footer">
<div className="name-submit-button">
<TextButton
onClick={() => { this.submitSyndicateName() }}
modifier={['fluid']}
isDisabled={false}
text='APPLY FOR NAME' />
<div className="comment">
<span>This button will become active one you have selected an available name</span>
</div>
</div>
<div className="footer-image">
<span>Powered by the </span>
<img src="/assets/images/BHA_Logo1.jpg" />
</div>
</div>
</div>
)
}
}
const mapStateToProps = (state, ownProps) => {
return {
syndicateName: state.registerSyndicate.syndicateName.name,
}
}
const mapDispatchToProps = (dispatch, ownProps) => {
return {
setSyndicateName: (name) => {
dispatch(setSyndicateName(name))
},
submitSyndicateName: (token, name) => {
return dispatch(submitSyndicateName(token, name))
}
}
}
export default withRouter(connect(
mapStateToProps,
mapDispatchToProps
)(RegisterSyndicateNameContainer))
|
<filename>app/models/spree/amazon/asset.rb
module Spree
module Amazon
class Asset < Spree::Amazon::Base
attr_accessor :url
def url(style = :product)
@url[style.to_sym]
end
def initialize(_url)
@url = _url
end
end
end
end
|
const axios = require('axios');
const cheerio = require('cheerio');
const getData = async (url) => {
try {
const html = await axios.get(url);
const $ = cheerio.load(html.data);
const data = $('.data-row').map((i, el) => {
return {
data1: $(el).find('.data1').text(),
data2: $(el).find('.data2').text(),
data3: $(el).find('.data3').text(),
};
}).get();
return data;
} catch (err) {
console.log(err);
}
};
getData('https://example.com/data-page')
.then(data => console.log(data))
.catch(err => console.log(err)); |
#
# The BSD 3-Clause License. http://www.opensource.org/licenses/BSD-3-Clause
#
# This file is part of MinGW-W64(mingw-builds: https://github.com/niXman/mingw-builds) project.
# Copyright (c) 2011-2017 by niXman (i dotty nixman doggy gmail dotty com)
# Copyright (c) 2012-2015 by Alexpux (alexpux doggy gmail dotty com)
# All rights reserved.
#
# Project: MinGW-W64 ( http://sourceforge.net/projects/mingw-w64/ )
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# - Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# - Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the distribution.
# - Neither the name of the 'MinGW-W64' 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.
#
# **************************************************************************
PKG_NAME=pseh-${RUNTIME_VERSION}
PKG_DIR_NAME=pseh-${RUNTIME_VERSION}
PKG_DIR_NAME=mingw-w64/mingw-w64-libraries/pseh
PKG_TYPE=git
PKG_URLS=(
"git://git.code.sf.net/p/mingw-w64/mingw-w64|branch:$RUNTIME_BRANCH|repo:$PKG_TYPE"
)
PKG_PRIORITY=extra
#
PKG_PATCHES=()
#
PKG_EXECUTE_AFTER_PATCH=(
"autoreconf -i"
)
#
PKG_CONFIGURE_FLAGS=(
--host=$HOST
--build=$BUILD
--target=$TARGET
#
--prefix=$PREFIX
#
CFLAGS="\"$COMMON_CFLAGS\""
CXXFLAGS="\"$COMMON_CXXFLAGS\""
CPPFLAGS="\"$COMMON_CPPFLAGS\""
LDFLAGS="\"$COMMON_LDFLAGS\""
)
#
PKG_MAKE_FLAGS=(
-j$JOBS
all
)
#
PKG_INSTALL_FLAGS=(
-j$JOBS
$( [[ $STRIP_ON_INSTALL == yes ]] && echo install-strip || echo install )
)
# **************************************************************************
|
const SerialPort = require('serialport');
const aesjs = require('aes-js');
const EventEmitter = require('events');
const bigintCryptoUtils = require('bigint-crypto-utils');
const { parseData, CRC16, randHexArray, argsToByte, int64LE } = require('./utils');
const commandList = require('./command');
const chalk = require('chalk');
const semver = require('semver');
const pkg = require('../package.json');
module.exports = class SSP extends EventEmitter {
constructor(param) {
super();
if (!semver.satisfies(process.version, pkg.engines.node)) {
throw new Error(`Version Node.js must be ${pkg.engines.node}`);
}
this.eventEmitter = new EventEmitter();
this.debug = param.debug || false;
this.id = param.id || 0;
this.timeout = param.timeout || 3000;
this.encryptAllCommand = param.encryptAllCommand || true;
this.keys = {
fixedKey: param.fixedKey || '0123456701234567',
generatorKey: null,
modulusKey: null,
hostRandom: null,
hostIntKey: null,
slaveIntKey: null,
key: null
};
this.sequence = 0x80;
this.count = 0;
this.currentCommand = null;
this.aesEncryption = null;
this.enabled = false;
this.polling = false;
this.unit_type = null;
}
open(port, param = {}) {
return new Promise((resolve, reject) => {
this.port = new SerialPort(port, {
baudRate: param.baudRate || 9600,
databits: param.databits || 8,
stopbits: param.stopbits || 2,
parity: param.parity || 'none',
parser: SerialPort.parsers.raw,
autoOpen: true
});
this.port.on('error', (error) => {
reject(error);
this.emit('CLOSE');
});
this.port.on('close', (error) => {
reject(error);
this.emit('CLOSE');
});
this.port.on('open', () => {
resolve();
this.emit('OPEN');
let tmpBuffer = [];
this.port.on('data', buffer => {
let tmpArray = [...buffer];
if (this.debug) { console.log('COM ->', chalk.gray(buffer.toString('hex')), '| RAW'); }
if (tmpBuffer.length === 1) {
if ((tmpArray[0] === this.id | 0x80) || (tmpArray[0] === this.id | 0x00)) {
tmpBuffer = [0x7f].concat(tmpArray);
} else {
tmpBuffer = [];
}
} else {
if (tmpBuffer.length === 0) {
let startByte = -1;
for (let i = 0; i < tmpArray.length; i++) {
if (tmpArray[i] === 0x7f && startByte === -1 && ((tmpArray[i + 1] === this.id | 0x80) || (tmpArray[i + 1] === this.id | 0x00))) {
startByte = i;
}
}
if (startByte !== -1) {
tmpBuffer = tmpArray.slice(startByte, tmpArray.length);
} else if (tmpArray[tmpArray.length - 1] === 0x7f) {
tmpBuffer = [0x7f];
}
} else {
tmpBuffer = tmpBuffer.concat(tmpArray);
}
}
let double7F = (tmpBuffer.join(',').match(/,127,127/g) || []).length;
if (tmpBuffer.length >= tmpBuffer[2] + 5 + double7F) {
if (this.debug) { console.log('COM ->', chalk.yellow(Buffer.from(tmpBuffer.slice(0, tmpBuffer[2] + 5 + double7F)).toString('hex')), chalk.green(this.currentCommand)); }
this.eventEmitter.emit(this.currentCommand, Buffer.from(tmpBuffer.slice(0, tmpBuffer[2] + 5 + double7F).join(',').replace(/,127,127/g, ',127').split(','), tmpBuffer[2]));
tmpBuffer = tmpBuffer.slice(tmpBuffer[2] + 5 + double7F);
}
});
});
});
}
close() {
if (this.port !== undefined) {
this.port.close();
}
}
getSequence() {
this.sequence = this.sequence === 0x00 ? 0x80 : 0x00;
return this.id | this.sequence;
}
initEncryption() {
return Promise.all([
bigintCryptoUtils.prime(16),
bigintCryptoUtils.prime(16),
bigintCryptoUtils.randBetween(BigInt(2) ** BigInt(16))
])
.then(res => {
this.keys.generatorKey = res[0];
this.keys.modulusKey = res[1];
this.keys.hostRandom = res[2];
this.keys.hostIntKey = this.keys.generatorKey ** this.keys.hostRandom % this.keys.modulusKey;
return;
})
.then(() => this.exec('SET_GENERATOR', int64LE(this.keys.generatorKey)))
.then(() => this.exec('SET_MODULUS', int64LE(this.keys.modulusKey)))
.then(() => this.exec('REQUEST_KEY_EXCHANGE', int64LE(this.keys.hostIntKey)))
.then(() => {
this.count = 0;
return;
});
}
getPacket(command, args) {
let STX = 0x7F;
let STEX = 0x7E;
if (commandList[command].args && args.length === 0) { throw new Error('args missings'); }
let LENGTH = args.length + 1;
let SEQ_SLAVE_ID = this.getSequence();
let DATA = [commandList[command].code].concat(...args);
// Encrypted packet
if (this.aesEncryption !== null && (commandList[command].encrypted || this.encryptAllCommand)) {
let eCOUNT = Buffer.alloc(4);
eCOUNT.writeUInt32LE(this.count, 0);
let eCommandLine = [DATA.length].concat([...eCOUNT], DATA);
let ePACKING = randHexArray(Math.ceil((eCommandLine.length + 2) / 16) * 16 - (eCommandLine.length + 2));
eCommandLine = eCommandLine.concat(ePACKING);
eCommandLine = eCommandLine.concat(CRC16(eCommandLine));
let eDATA = [...this.aesEncryption.encrypt(eCommandLine)];
DATA = [STEX].concat(eDATA);
LENGTH = DATA.length;
}
let tmp = [SEQ_SLAVE_ID].concat(LENGTH, DATA);
let comandLine = Buffer.from([STX].concat(tmp, CRC16(tmp)).join(',').replace(/,127/g, ',127,127').split(','));
if (this.debug) { console.log('COM <-', chalk.cyan(comandLine.toString('hex')), chalk.green(this.currentCommand), this.count); }
return comandLine;
}
exec(command, args = []) {
command = command.toUpperCase();
if (commandList[command] === undefined) { throw new Error('command not found'); }
this.currentCommand = command;
let buffer = Buffer.from(this.getPacket(command, args));
return new Promise((resolve) => {
this.port.write(buffer, () => {
this.port.drain();
if (command === 'SYNC') { this.sequence = 0x80; }
});
resolve(this.newEvent(command));
})
.then(res => {
return res.status === 'TIMEOUT' ? this.exec(command, args) : res;
});
}
newEvent(command) {
return new Promise((resolve) => {
let timeout = true;
this.eventEmitter.once(command, buffer => {
timeout = false;
if (Buffer.isBuffer(buffer)) {
resolve(this.parsePacket(buffer));
} else if (buffer === 'TIMEOUT') {
if (this.debug) { console.log(chalk.red('TIMEOUT ' + command)); }
resolve({
success: false,
status: 'TIMEOUT',
command: this.currentCommand,
info: {}
});
}
});
setTimeout(() => {
if (timeout) {
this.eventEmitter.emit(this.currentCommand, 'TIMEOUT');
this.currentCommand = null;
}
}, parseInt(this.timeout));
})
.then(res => new Promise((resolve) => {
setTimeout(() => {
resolve(res);
}, 100);
}));
}
parsePacket(buffer) {
buffer = [...buffer];
if (buffer[0] === 0x7F) {
buffer = buffer.slice(1);
let DATA = buffer.slice(2, buffer[1] + 2);
let CRC = CRC16(buffer.slice(0, buffer[1] + 2));
if (CRC[0] !== buffer[buffer.length - 2] || CRC[1] !== buffer[buffer.length - 1]) {
return { success: false, error: 'Wrong CRC16' };
}
if (this.keys.key !== null && DATA[0] === 0x7E) {
DATA = this.aesEncryption.decrypt(Buffer.from(DATA.slice(1)));
if (this.debug) { console.log('Decrypted:', chalk.red(Buffer.from(DATA).toString('hex'))); }
let eLENGTH = DATA[0];
let eCOUNT = Buffer.from(DATA.slice(1, 5)).readInt32LE();
DATA = DATA.slice(5, eLENGTH + 5);
this.count = eCOUNT;
}
let parsedData = parseData(DATA, this.currentCommand, this.protocol_version, this.unit_type);
if (this.debug) {
console.log(parsedData);
}
if (this.currentCommand === 'REQUEST_KEY_EXCHANGE') {
this.createHostEncryptionKeys(parsedData.info.key);
} else if (this.currentCommand === 'SETUP_REQUEST') {
this.protocol_version = parsedData.info.protocol_version;
this.unit_type = parsedData.info.unit_type;
} else if (this.currentCommand === 'UNIT_DATA') {
this.unit_type = parsedData.info.unit_type;
}
return parsedData;
}
return { success: false, error: 'Unknown response' };
}
createHostEncryptionKeys(data) {
if (this.keys.key === null) {
this.keys.slaveIntKey = Buffer.from(data).readBigInt64LE();
this.keys.key = this.keys.slaveIntKey ** this.keys.hostRandom % this.keys.modulusKey;
this.encryptKey = Buffer.concat([
int64LE(Buffer.from(this.keys.fixedKey, 'hex').readBigInt64BE()),
int64LE(this.keys.key)
]);
this.aesEncryption = new aesjs.ModeOfOperation.ecb(this.encryptKey, null, 0);
this.count = 0;
if (this.debug) {
console.log('AES encrypt key:', chalk.red('0x' + Buffer.from(this.encryptKey).toString('hex')));
console.log('');
console.log(this.keys);
console.log('');
}
}
}
enable() {
return this.command('ENABLE')
.then(res => {
if (res.status === 'OK') {
this.enabled = true;
if (!this.polling) this.poll(true);
}
return res;
});
}
disable() {
return this.command('DISABLE')
.then(res => {
if (res.status === 'OK') {
this.enabled = false;
this.poll(false)
.then(() => {
this.emit('DISABLED');
});
}
return res;
});
}
command(command, args) {
if (this.enabled) {
let result = null;
return this.poll(false)
.then(() => this.exec(command, argsToByte(command, args, this.protocol_version)))
.then(res => {
result = res;
if (!this.polling) return this.poll(true);
return () => { };
})
.then(() => result);
}
return this.exec(command, argsToByte(command, args, this.protocol_version));
}
poll(status = true) {
if (status) {
this.polling = true;
return this.exec('POLL')
.then(result => {
if (result.info) {
let res = result.info;
if (!Array.isArray(result.info)) res = [result.info];
res.forEach((info) => {
this.emit(info.name, info);
// Device reports disabled event on each poll during smart epmy or dispensing, so need to encounter that
// Maybe there is better solution, but found no clue in docs
if (res.length === 1 && info.name === 'DISABLED') {
this.poll(false);
}
});
}
if (this.polling) {
this.poll();
} else {
this.eventEmitter.emit('POLL_STOP');
}
return;
});
}
if (this.polling !== false) {
this.polling = false;
return new Promise((resolve) => {
this.eventEmitter.once('POLL_STOP', () => {
resolve();
});
});
}
return new Promise((resolve) => { resolve(); });
}
};
|
<reponame>helenarodcal/etsy-bdd
package com.serenitydojo.etsy.basket;
import org.openqa.selenium.By;
public class ShoppingBasket {
public static By CONTENT = By.id("content");
}
|
/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2019, Locus Robotics
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef FUSE_CONSTRAINTS_MARGINAL_COST_FUNCTION_H
#define FUSE_CONSTRAINTS_MARGINAL_COST_FUNCTION_H
#include <fuse_core/eigen.h>
#include <fuse_core/local_parameterization.h>
#include <ceres/cost_function.h>
#include <vector>
namespace fuse_constraints
{
/**
* @brief Implements a cost function designed for precomputed marginal distributions
*
* The cost function is of the form:
*
* || ||^2
* cost(x) = || A1 * (x1 - x1_bar) + A2 * (x2 - x2_bar) + ... + An * (xn - xn_bar) + b ||
* || ||
*
* where, the A matrices and the b vector are fixed, x_bar is the linearization point used when calculating the A
* matrices and b vector, and the minus operator in (x - x_bar) is provided by the variable's local parameterization.
*
* The A matrices can have any number of rows, but they must all be the same. The number of columns of each A matrix
* must match the associated variable's local parameterization size, and the number of rows of each x_bar must match
* the associated variable's global size. The cost function will have the same number of residuals as the rows of A.
*/
class MarginalCostFunction : public ceres::CostFunction
{
public:
/**
* @brief Construct a cost function instance
*
* @param[in] A The A matrix of the marginal cost (of the form A*(x - x_bar) + b)
* @param[in] b The b vector of the marginal cost (of the form A*(x - x_bar) + b)
* @param[in] x_bar The linearization point of the involved variables
* @param[in] local_parameterizations The local parameterization associated with the variable
*/
MarginalCostFunction(
const std::vector<fuse_core::MatrixXd>& A,
const fuse_core::VectorXd& b,
const std::vector<fuse_core::VectorXd>& x_bar,
const std::vector<fuse_core::LocalParameterization::SharedPtr>& local_parameterizations);
/**
* @brief Destructor
*/
virtual ~MarginalCostFunction() = default;
/**
* @brief Compute the cost values/residuals, and optionally the Jacobians, using the provided variable/parameter
* values
*/
bool Evaluate(
double const* const* parameters,
double* residuals,
double** jacobians) const override;
private:
const std::vector<fuse_core::MatrixXd>& A_; //!< The A matrices of the marginal cost
const fuse_core::VectorXd& b_; //!< The b vector of the marginal cost
const std::vector<fuse_core::LocalParameterization::SharedPtr>& local_parameterizations_; //!< Parameterizations
const std::vector<fuse_core::VectorXd>& x_bar_; //!< The linearization point of each variable
};
} // namespace fuse_constraints
#endif // FUSE_CONSTRAINTS_MARGINAL_COST_FUNCTION_H
|
#!/bin/bash
set -x
if [[ $@ == *"$STI_SCRIPTS_PATH"* ]]; then
exec "$@"
else
exec $APP_ROOT/etc/entrypoint.sh "$@"
fi
|
<reponame>NowacekLab/Duke-Whale-TagDataVis
import React, {useState} from 'react';
import { useLocation, useHistory } from 'react-router-dom';
import { useSelector } from 'react-redux';
import {makeStyles} from '@material-ui/core/styles';
import routes from '../../routes.json';
import SideBarComp from "./SideBarComp";
import HomeIcon from '@material-ui/icons/Home';
import Divider from "@material-ui/core/Divider";
import IconButton from '@material-ui/core/IconButton';
import Tooltip from "@material-ui/core/Tooltip";
import {useDispatch} from 'react-redux';
import EqualizerIcon from '@material-ui/icons/Equalizer';
import UploadAction from "../Upload/UploadAction";
import Button from '@material-ui/core/Button';
import Typography from '@material-ui/core/Typography';
import ImportExportIcon from '@material-ui/icons/ImportExport';
import {notifsActionsHandler} from '../../functions/reduxHandlers/handlers';
import AnimatedDialogWrapper from '../Animated/AnimatedDialogWrapper';
import MahalDialogWrapper from '../MahalPOI/MahalDialogWrapper';
import SettingsIcon from '@material-ui/icons/Settings';
import ExportHTMLWrapper from '../ExportHTML/ExportHTMLDialogWrapper';
import SettingSizeDialog from '../Settings/SettingSizeDialog';
import SettingCriticalDialog from '../Settings/SettingCriticalDialog';
import DivesDialogWrapper from '../Dives/DivesDialogWrapper';
import WaveletsDialogWrapper from '../Wavelets/WaveletsDialogWrapper';
import AcousticsDialogWrapper from '../Acoustics/AcousticsDialogWrapper';
//@ts-ignore
const remote = require('electron').remote;
const shell = remote.shell;
const useStyles = makeStyles({
content: {
height: "100%",
display: 'flex',
flexDirection: 'column'
},
text: {
fontFamily: "HelveticaNeue-Light",
color: "#fff",
},
bottomBtnCont: {
position: "absolute",
bottom: "0px",
display: "flex",
width: "100%",
justifyContent: "space-between"
},
bannerSuperCont: {
zIndex: 100,
bottom: 20,
left: 200,
right: 0,
position: "fixed",
display: "flex",
alignItems: 'center',
justifyContent: 'center',
},
btnActive: {
color: "white",
backgroundColor: "rgba(0,0,0,0.1)",
transition: "all 0.15s linear",
backgroundSize: "110% 110%"
},
btnInactive: {
color: "white",
opacity: 0.5,
transition: "all 0.15s linear"
},
linkDivider: {
color: "white",
background: "white",
}
});
const SideBarContent = () => {
const classes = useStyles();
const history = useHistory();
const dispatch = useDispatch();
// TODO: extract bottom animate action out of sidebar into own component for notif handler to get separate component name
const notifActionHandler = new notifsActionsHandler(dispatch, "Side Bar Action");
//@ts-ignore
const forceLoad = useSelector(state => state.forceLoad);
const {pathname} = useLocation();
const isNavEnabled = () => {
return true;
}
const navIfEnabled = (navRoute: string) => {
const navEnabled = isNavEnabled();
if (!navEnabled) return;
history.push(navRoute);
}
const [animatedDialogOpen, setAnimatedDialogOpen] = useState(false);
const handleAnimatedDialogClose = () => {
setAnimatedDialogOpen(false);
}
const [mahalDialogOpen, setMahalDialogOpen] = useState(false);
const handleMahalDialogClose = () => {
setMahalDialogOpen(false);
}
const [exportHTMLOpen, setExportHTMLOpen] = useState(false);
const handleExportHTMLClose = () => {
setExportHTMLOpen(false);
}
const [diveDialogOpen, setDiveDialogOpen] = useState(false);
const handleDiveDialogClose = () => {
setDiveDialogOpen(false);
}
const [waveletsDialogOpen, setWaveletsDialogOpen] = useState(false);
const handleWaveletsDialogClose = () => {
setWaveletsDialogOpen(false);
}
const [acousticsDialogOpen, setAcousticsDialogOpen] = useState(false);
const handleAcousticsDialogClose = () => {
setAcousticsDialogOpen(false);
}
const [critSettingsOpen, setCritSettingsOpen] = useState(false);
const handleCritSettingsClose = () => {
setCritSettingsOpen(false);
}
const [sizeSettingsOpen, setSizeSettingsOpen] = useState(false);
const handleSizeSettingsClose = () => {
setSizeSettingsOpen(false);
}
const [darkMode, setDarkMode] = useState(false);
const testing = () => {
// console.log(screen);
// console.log(screen.getPrimaryDisplay().workAreaSize);
// console.log(remote.getCurrentWindow().getSize());
// if (!darkMode) {
// document.body.setAttribute('data-theme', 'dark');
// setDarkMode(true);
// } else {
// document.body.removeAttribute('data-theme');
// setDarkMode(false);
// }
try {
const tempPath = "C:\\Users\\joonl\\AppData\\Roaming\\Electron";
shell.showItemInFolder(tempPath);
} catch(error) {
}
}
return(
<SideBarComp>
<div style={{
height: '100%'
}}>
<div className={classes.content}>
<UploadAction />
<Divider
style={{background: "white"}}
variant="middle"
/>
<Tooltip
title={
<Typography>
Home
</Typography>
}
placement="right"
arrow
>
<IconButton
onClick={() => {
navIfEnabled(routes.HOME)
}}
>
<HomeIcon className={pathname === routes.HOME ? classes.btnActive : classes.btnInactive} />
</IconButton>
</Tooltip>
<Tooltip
title={
<div
style={{
display: 'flex',
flexDirection: 'column',
alignContent: 'center',
gap: "10px",
padding: "5px"
}}
>
<Typography>
Data View
</Typography>
<Button
onClick={() => {
navIfEnabled(routes.GRAPHS)
}}
style={{
color: "white",
fontWeight: pathname === routes.GRAPHS ? "bolder" : "normal",
border: "1px solid white"
}}
>
Created Graphs
</Button>
<Button
onClick={() => {
navIfEnabled(routes.EDITOR)
}}
style={{
color: "white",
fontWeight: pathname === routes.EDITOR ? "bolder" : "normal",
border: "1px solid white"
}}
>
Custom Graphing
</Button>
</div>
}
interactive={true}
leaveDelay={300}
placement="right"
arrow
>
<IconButton>
<EqualizerIcon className={pathname === routes.GRAPHS || pathname === routes.EDITOR ? classes.btnActive : classes.btnInactive} />
</IconButton>
</Tooltip>
<Tooltip
title={
<div
style={{
display: 'flex',
justifyContent: "center",
alignItems: "center",
flexDirection: "column",
gap: "10px",
padding: "5px"
}}
>
<Typography>
Generate
</Typography>
<div
style={{
display: 'grid',
gridTemplateColumns: "repeat(2, 1fr)",
gridTemplateRows: "repeat(2, 1fr)",
}}
>
<Button
style={{
color: "white",
fontWeight: "normal",
border: "1px solid white",
margin: "5px"
}}
onClick={() => setAnimatedDialogOpen(true)}
>
3D Animation
</Button>
<Button
style={{
color: "white",
fontWeight: "normal",
border: "1px solid white",
margin: "5px"
}}
onClick={() => setMahalDialogOpen(true)}
>
Mahal POI
</Button>
<Button
style={{
color: "white",
fontWeight: "normal",
border: "1px solid white",
margin: "5px"
}}
onClick={() => setExportHTMLOpen(true)}
>
Export HTML
</Button>
<Button
style={{
color: "white",
fontWeight: "normal",
border: "1px solid white",
margin: "5px"
}}
onClick={() => setDiveDialogOpen(true)}
>
Dives
</Button>
<Button
style={{
color: "white",
fontWeight: "normal",
border: "1px solid white",
margin: "5px"
}}
onClick={() => setWaveletsDialogOpen(true)}
>
Wavelets
</Button>
<Button
style={{
color: "white",
fontWeight: "normal",
border: "1px solid white",
margin: "5px"
}}
onClick={() => setAcousticsDialogOpen(true)}
>
Acoustics
</Button>
</div>
</div>
}
interactive={true}
leaveDelay={300}
placement="right"
arrow
disableFocusListener
>
<IconButton>
<ImportExportIcon className={pathname === routes.EXPORT ? classes.btnActive : classes.btnInactive}/>
</IconButton>
</Tooltip>
<AnimatedDialogWrapper
showDialog={animatedDialogOpen}
handleClose={handleAnimatedDialogClose}
handleBack={handleAnimatedDialogClose}
/>
<MahalDialogWrapper
showDialog={mahalDialogOpen}
handleClose={handleMahalDialogClose}
handleBack={handleMahalDialogClose}
/>
<ExportHTMLWrapper
showDialog={exportHTMLOpen}
handleClose={handleExportHTMLClose}
handleBack={handleExportHTMLClose}
/>
<DivesDialogWrapper
showDialog={diveDialogOpen}
handleClose={handleDiveDialogClose}
handleBack={handleDiveDialogClose}
/>
<WaveletsDialogWrapper
showDialog={waveletsDialogOpen}
handleClose={handleWaveletsDialogClose}
handleBack={handleWaveletsDialogClose}
/>
<AcousticsDialogWrapper
showDialog={acousticsDialogOpen}
handleClose={handleAcousticsDialogClose}
handleBack={handleAcousticsDialogClose}
/>
<Tooltip
title={
<div
style={{
display: 'flex',
justifyContent: "center",
alignItems: "center",
flexDirection: "column",
gap: "10px",
padding: "5px",
}}
>
<Typography>
Settings
</Typography>
<div
style={{
display: 'grid',
gridTemplateColumns: "repeat(2, 1fr)",
gridTemplateRows: "auto",
}}
>
<Button
style={{
color: "white",
fontWeight: "normal",
border: "1px solid white",
margin: "5px"
}}
onClick={() => setSizeSettingsOpen(true)}
>
Window Size
</Button>
<Button
style={{
color: "white",
fontWeight: "normal",
border: "1px solid white",
margin: "5px"
}}
onClick={() => setCritSettingsOpen(true)}
>
Critical
</Button>
</div>
</div>
}
interactive={true}
leaveDelay={300}
placement="right"
arrow
disableFocusListener
>
<IconButton
style={{
marginTop: "auto"
}}
>
<SettingsIcon className={sizeSettingsOpen || critSettingsOpen ? classes.btnActive : classes.btnInactive}/>
</IconButton>
</Tooltip>
<SettingSizeDialog
showModal={sizeSettingsOpen}
handleClose={handleSizeSettingsClose}
handleBack={handleSizeSettingsClose}
/>
<SettingCriticalDialog
showModal={critSettingsOpen}
handleClose={handleCritSettingsClose}
handleBack={handleCritSettingsClose}
/>
</div>
</div>
</SideBarComp>
)
}
export default SideBarContent; |
<reponame>vuesalad/vueducks<filename>vue.js.adv.hello/test/dnd/dnd.basic.test.js
import { describe, expect, test } from 'vitest'
import * as util from '~/dnd/adding.js'
describe('this is unit teset', () => {
test('individual tst', () => {
expect(util.addThree(6)).toBe(9)
})
})
|
fetch_bashit(){
local dest="${1?}"
if [ ! -d "${dest}" ]; then
git clone --depth=1 \
"https://github.com/Bash-it/bash-it.git" \
"${dest}"
fi
}
|
from math import sqrt
def calcDistance(p1, p2):
return sqrt( (p2[0] - p1[0])**2 + (p2[1] - p1[1])**2 )
point1 = [2, 4]
point2 = [10, 6]
distance = calcDistance(point1, point2)
print("Distance between the two points is", distance) |
<reponame>gaunthan/design-patterns-by-golang
package adapter
type VideoOutputter struct {
out HDMIPort
}
func (o *VideoOutputter) Start() {
o.out = make(HDMIPort)
go func() {
defer close(o.out)
// outputs 0 1 2 ... 9
for i := 0; i < 10; i++ {
o.out <- i
}
}()
}
func (o *VideoOutputter) GetOutput() HDMIPort {
return o.out
}
|
def fibonacci(n):
x, y = 0, 1
while x < n:
print(x, end="\t")
x, y = y, x + y |
<filename>Graph/src/GraphBFS.java
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
public class GraphBFS {
private Graph G;
private boolean[] visited;
private ArrayList<Integer> order = new ArrayList<>();
public GraphBFS(Graph G){
this.G = G;
visited = new boolean[G.V()];
for (int v = 0; v < G.V(); v++) {
if(!visited[v])
bfs(v);
}
}
private void bfs(int s){
Queue<Integer> queue = new LinkedList<>();
queue.add(s);
visited[s] = true;
while(!queue.isEmpty()){
int v = queue.remove();
order.add(v);
for(int w: G.adj(v)){
if(!visited[w]){
queue.add(w);
visited[w] = true;
}
}
}
}
public Iterable<Integer> order(){
return order;
}
public static void main(String[] args)
{
Graph g = new Graph("g.txt");
GraphBFS graphBFS = new GraphBFS(g);
System.out.println("BFS Order : " + graphBFS.order());
}
}
|
package io.opensphere.core.modulestate;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import io.opensphere.core.util.collections.New;
/** List of tags for a state file. */
@XmlRootElement(name = "tags", namespace = ModuleStateController.STATE_NAMESPACE)
@XmlAccessorType(XmlAccessType.NONE)
public class TagList implements Iterable<String>
{
/** The list of tags. */
@XmlElement(name = "tag", namespace = ModuleStateController.STATE_NAMESPACE)
private final List<String> myTags = New.list();
/** Default constructor. */
public TagList()
{
}
/**
* Constructor with tags.
*
* @param tags The tags.
*/
public TagList(Collection<? extends String> tags)
{
myTags.addAll(tags);
}
/**
* Get the tags.
*
* @return The tags.
*/
public List<String> getTags()
{
return myTags;
}
@Override
public Iterator<String> iterator()
{
return myTags.iterator();
}
/**
* Set the tags.
*
* @param tags The tags.
*/
public void setTags(Collection<? extends String> tags)
{
myTags.clear();
myTags.addAll(tags);
}
}
|
public float calculateScaleFactor(float value, float maxScale) {
// Ensure the value is within the valid range
value = Math.max(0, Math.min(value, 1.0f));
// Calculate the scale factor within the range of 0 to maxScale
return value * maxScale;
} |
package com.java110.things.entity.sip;
import com.java110.things.sip.Server;
import com.java110.things.sip.codec.Frame;
import com.java110.things.sip.remux.Observer;
import javax.sip.Dialog;
import java.util.Date;
import java.util.concurrent.ConcurrentLinkedDeque;
public class PushStreamDevice {
/**
* 设备ID
*/
private String deviceId;
/**
* ssrc
* invite下发时携带字段
* 终端摄像头推流会携带上
*/
private Integer ssrc;
/**
* sip callId
*/
private String callId;
private Dialog dialog;
/**
* rtmp推流名称
*/
private String streamName;
/**
* 网络通道ID
*/
private String channelId;
/**
* 是否正在推流
*/
private boolean pushing;
/**
* 创建时间
*/
private Date createDate;
/**
* 推流时间
*/
private Date pushStreamDate;
/**
* 监听的收流端口
*/
private int port;
/**
* 是否是 tcp传输音视频
*/
private boolean isTcp;
/**
* 接受的视频帧队列
*/
private ConcurrentLinkedDeque<Frame> frameDeque = new ConcurrentLinkedDeque<Frame>();
/**
* 接受流的Server
*/
private Server server;
/**
* 处理封装流的监听者
*/
private Observer observer;
/**
* 拉流地址
*/
private String pullRtmpAddress;
public PushStreamDevice(String deviceId, Integer ssrc, String callId, String streamName, int port,
boolean isTcp, Server server,Observer observer,String pullRtmpAddress) {
this.deviceId = deviceId;
this.ssrc = ssrc;
this.callId = callId;
this.streamName = streamName;
this.port = port;
this.isTcp = isTcp;
this.server = server;
this.observer = observer;
this.pullRtmpAddress = pullRtmpAddress;
}
public Integer getSsrc() {
return ssrc;
}
public void setSsrc(Integer ssrc) {
this.ssrc = ssrc;
}
public String getDeviceId() {
return deviceId;
}
public void setDeviceId(String deviceId) {
this.deviceId = deviceId;
}
public String getChannelId() {
return channelId;
}
public void setChannelId(String channelId) {
this.channelId = channelId;
}
public boolean isPushing() {
return pushing;
}
public void setPushing(boolean pushing) {
this.pushing = pushing;
}
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
public Date getPushStreamDate() {
return pushStreamDate;
}
public void setPushStreamDate(Date pushStreamDate) {
this.pushStreamDate = pushStreamDate;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public boolean isTcp() {
return isTcp;
}
public void setTcp(boolean isTcp) {
this.isTcp = isTcp;
}
public ConcurrentLinkedDeque<Frame> getFrameDeque() {
return frameDeque;
}
public void setFrameDeque(ConcurrentLinkedDeque<Frame> frameDeque) {
this.frameDeque = frameDeque;
}
public String getCallId() {
return callId;
}
public void setCallId(String callId) {
this.callId = callId;
}
public String getStreamName() {
return streamName;
}
public void setStreamName(String streamName) {
this.streamName = streamName;
}
public Server getServer() {
return server;
}
public void setServer(Server server) {
this.server = server;
}
public Observer getObserver() {
return observer;
}
public void setObserver(Observer observer) {
this.observer = observer;
}
public String getPullRtmpAddress() {
return pullRtmpAddress;
}
public void setPullRtmpAddress(String pullRtmpAddress) {
this.pullRtmpAddress = pullRtmpAddress;
}
public Dialog getDialog() {
return dialog;
}
public void setDialog(Dialog dialog) {
this.dialog = dialog;
}
}
|
# SPDX-License-Identifier: BSD-3-Clause
source helpers.sh
start_up
cleanup() {
rm -f policy.bin obj.pub pub.out primary.ctx
if [ $(ina "$@" "keep-context") -ne 0 ]; then
rm -f context.out
fi
if [ $(ina "$@" "no-shut-down") -ne 0 ]; then
shut_down
fi
}
trap cleanup EXIT
cleanup "no-shut-down"
# Keep the algorithm specifiers mixed to test friendly and raw
# values.
for gAlg in `populate_hash_algs 'and alg != "keyedhash"'`; do
for GAlg in rsa xor ecc aes; do
echo tpm2_createprimary -Q -g $gAlg -G $GAlg -c context.out
tpm2_createprimary -Q -g $gAlg -G $GAlg -c context.out
cleanup "no-shut-down" "keep-context"
for Atype in o e n; do
tpm2_createprimary -Q -C $Atype -g $gAlg -G $GAlg -c context.out
cleanup "no-shut-down" "keep-context"
done
done
done
policy_orig="f28230c080bbe417141199e36d18978228d8948fc10a6a24921b9eba6bb1d988"
#test for createprimary objects with policy authorization structures
echo -n "$policy_orig" | xxd -r -p > policy.bin
tpm2_createprimary -Q -C o -G rsa -g sha256 -c context.out -L policy.bin \
-a 'restricted|decrypt|fixedtpm|fixedparent|sensitivedataorigin'
tpm2_readpublic -c context.out > pub.out
policy_new=$(yaml_get_kv pub.out "authorization policy")
test "$policy_orig" == "$policy_new"
# Test that -u can be specified to pass a TPMU_PUBLIC_ID union
# in this case TPM2B_PUBLIC_KEY_RSA (256 bytes of zero)
printf '\x00\x01' > ud.1
dd if=/dev/zero bs=256 count=1 of=ud.2
cat ud.1 ud.2 > unique.dat
tpm2_createprimary -C o -G rsa2048:aes128cfb -g sha256 -c prim.ctx \
-a 'restricted|decrypt|fixedtpm|fixedparent|sensitivedataorigin|userwithauth|noda' \
-u unique.dat
test -f prim.ctx
# Test that -g/-G do not need to be specified.
tpm2_createprimary -Q -c context.out
# Test that -o does not need to be specified.
tpm2_createprimary -Q
# Test for session leaks
BEFORE=$(tpm2_getcap handles-loaded-session; tpm2_getcap handles-saved-session)
tpm2_createprimary -Q
AFTER=$(tpm2_getcap handles-loaded-session; tpm2_getcap handles-saved-session)
test "${BEFORE}" = "${AFTER}"
exit 0
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var get_style_1 = require("./get-style");
function getHeight(el, defaultValue) {
var width = get_style_1.default(el, 'width', defaultValue);
if (width === 'auto') {
width = el.offsetWidth;
}
return parseFloat(width);
}
exports.default = getHeight;
//# sourceMappingURL=get-width.js.map |
def suggest_alternative(word):
try:
from spellchecker import SpellChecker
except:
print("Error: spellchecker module not installed")
return None
spell = SpellChecker()
possible_words = spell.candidates(word)
if len(possible_words) > 0:
return possible_words
else:
return []
if __name__=="__main__":
print(suggest_alternative("apple")) |
const invariant = require('invariant')
function mapEffect (effect, callback) {
invariant(typeof callback === 'function', 'callback must be a function')
if (!effect) {
return effect
}
invariant(typeof effect === 'function', 'Effects must be functions or falsy')
return function _mapEffect (dispatch) {
function intercept (message) {
dispatch(callback(message))
}
return effect(intercept)
}
}
function batchEffects (effects) {
for (let i = 0; i < effects.length; i++) {
const effect = effects[i]
invariant(
!effect || typeof effect === 'function',
'Effects must be functions or falsy'
)
}
return function _batchEffects (dispatch) {
return effects.map(effect => {
if (effect) {
return effect(dispatch)
}
})
}
}
function ensureProgram (program) {
invariant(program, 'program must be truthy')
invariant(Array.isArray(program.init), 'program.init must be an array')
invariant(
typeof program.update === 'function',
'program.update must be a function'
)
invariant(
typeof program.view === 'function',
'program.view must be a function'
)
invariant(
!program.done || typeof program.done === 'function',
'program.done must be a function if included'
)
}
function mapProgram (program, callback) {
ensureProgram(program)
invariant(typeof callback === 'function', 'callback must be a function')
const start = program.init
const init = [start[0], mapEffect(start[1], callback)]
function update (msg, state) {
const change = program.update(msg, state)
return [change[0], mapEffect(change[1], callback)]
}
function view (state, dispatch) {
return program.view(state, msg => dispatch(callback(msg)))
}
return { init, update, view, done: program.done }
}
function batchPrograms (programs, containerView) {
invariant(Array.isArray(programs), 'programs must be an array')
invariant(
typeof containerView === 'function',
'containerView must be a function'
)
const embeds = []
const states = []
const effects = []
const programCount = programs.length
for (let i = 0; i < programCount; i++) {
const index = i
const program = programs[index]
ensureProgram(program)
const embed = mapProgram(program, data => ({ index, data }))
embeds.push(embed)
states.push(embed.init[0])
effects.push(embed.init[1])
}
const init = [states, batchEffects(effects)]
function update (msg, state) {
const { index, data } = msg
const change = embeds[index].update(data, state[index])
const newState = state.slice(0)
newState[index] = change[0]
return [newState, change[1]]
}
function view (state, dispatch) {
const programViews = embeds.map((embed, index) => () =>
embed.view(state[index], dispatch)
)
return containerView(programViews)
}
function done (state) {
for (let i = 0; i < programCount; i++) {
const done = embeds[i].done
if (done) {
done(state[i])
}
}
}
return { init, update, view, done }
}
function assembleProgram ({
data,
dataOptions,
logic,
logicOptions,
view,
viewOptions
}) {
return Object.assign(
{
view (model, dispatch) {
return view(model, dispatch, viewOptions)
}
},
logic(data(dataOptions), logicOptions)
)
}
exports.mapEffect = mapEffect
exports.batchEffects = batchEffects
exports.mapProgram = mapProgram
exports.batchPrograms = batchPrograms
exports.assembleProgram = assembleProgram
|
<gh_stars>0
export * from './sts-server';
|
#!/bin/sh
### -----
### Level 2 Setup
###
### Calling this file will cascade to fall the levels below it until it hits the floor.
### -----
/bin/sh ./level_1_archlinux.sh
echo " "
echo " >>>>> Level 2 >>> Organization, editors, converters, media and utilities"
echo " "
echo "Install productvity apps ..."
pacman -S --noconfirm calcurse
echo "Install latex ..."
pacman -S --noconfirm pandoc texlive-core texlive-science texlive-latexextra minted
echo "Install graphics ..."
pacman -S --noconfirm imagemagick
echo "Install video ..."
pacman -S --noconfirm mpv vlc smplayer mplayer
echo "Install audio ..."
pacman -S --noconfirm cmus
echo "Install disk utils ..."
pacman -S --noconfirm hdparm
echo "Install compression tools ..."
pacman -S --noconfirm p7zip unrar zip unzip
echo "Install file/archiving tools ..."
pacman -S --noconfirm ncdu sshfs borg
echo "Install Development environments ..."
pacman -S --noconfirm docker docker-compose docker-machine vagrant virtualbox
echo "Install Ansible ..."
pacman -S --noconfirm ansible ansible-lint
echo "Install Development tools ..."
pacman -S --noconfirm meld kdiff3
|
<filename>EIDSS v6/android.java/workspace/EIDSS/src/com/bv/eidss/web/WebApiClient.java
package com.bv.eidss.web;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.text.ParseException;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.StatusLine;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.Credentials;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.AbstractHttpClient;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Base64;
import com.bv.eidss.model.BaseReferenceType;
import com.bv.eidss.model.GisBaseReferenceType;
// http://www.vogella.com/articles/AndroidJSON/article.html
public class WebApiClient {
private String _url;
private HttpClient _client;
int _timeout;
public WebApiClient(String url, String Organization, String User, String Password, int timeout) throws KeyManagementException, UnrecoverableKeyException, KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {
_url = url;
_timeout = timeout;
_client = getNewHttpClient(); //new DefaultHttpClient();
Credentials creds = new UsernamePasswordCredentials(Organization + "@" + User, Password);
((AbstractHttpClient)_client).getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), creds);
}
private HttpClient getNewHttpClient() throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException, KeyManagementException, UnrecoverableKeyException {
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(null, null);
SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
HttpConnectionParams.setConnectionTimeout(params, _timeout * 60 * 1000);
HttpConnectionParams.setSoTimeout(params, _timeout * 60 * 1000);
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
registry.register(new Scheme("https", sf, 443));
ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
DefaultHttpClient client = new DefaultHttpClient(ccm, params);
return client;
}
private static String Decode(String content){
byte[] data = Base64.decode(content, Base64.DEFAULT);
try {
return new String(data, "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
private String postJson(String url, JSONObject data) throws ClientProtocolException, IOException{
StringBuilder builder = new StringBuilder();
HttpPost httpPost = new HttpPost(url);
StringEntity entity = new StringEntity(data.toString());
httpPost.setEntity(entity);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
HttpResponse response = _client.execute(httpPost);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entityOut = response.getEntity();
InputStream content = entityOut.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
return builder.toString();
}
String errorMessage = "";
Header errorHeader = response.getFirstHeader("ErrorMessage");
if (errorHeader != null)
errorMessage = Decode(errorHeader.getValue());
throw new HttpResponseException(statusCode, errorMessage);
}
private byte[] getBytes(String url) throws ClientProtocolException, IOException{
HttpGet httpGet = new HttpGet(url);
HttpResponse response = _client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
byte[] buffer = new byte[1000000];
byte[] buffer1 = new byte[1024];
int alllen = 0;
int len = content.read(buffer1);
while(len >= 0){
System.arraycopy(buffer1, 0, buffer, alllen, len);
alllen += len;
len = content.read(buffer1);
}
byte[] ret = new byte[alllen];
System.arraycopy(buffer, 0, ret, 0, alllen);
return ret;
}
throw new HttpResponseException(statusCode, "");
}
private String getJson(String url) throws ClientProtocolException, IOException{
StringBuilder builder = new StringBuilder();
HttpGet httpGet = new HttpGet(url);
HttpResponse response = _client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
return builder.toString();
}
String errorMessage = "";
Header errorHeader = response.getFirstHeader("ErrorMessage");
if (errorHeader != null)
errorMessage = Decode(errorHeader.getValue());
throw new HttpResponseException(statusCode, errorMessage);
}
private void AddRefType(VectorBaseReferenceRaw ref, long type) {
BaseReferenceRaw r = new BaseReferenceRaw();
r.idfsBaseReference = 0;
r.idfsReferenceType = type;
r.intHACode = -1;
r.strDefault = "";
ref.add(r);
}
private void AddGisRefType(VectorGisBaseReferenceRaw ref, long type) {
GisBaseReferenceRaw r = new GisBaseReferenceRaw();
r.idfsBaseReference = 0;
r.idfsReferenceType = type;
r.strDefault = "";
ref.add(r);
}
private void AddRef(VectorBaseReferenceRaw ref, long type) throws ClientProtocolException, JSONException, IOException {
JSONArray jsonArray = new JSONArray(getJson(_url + "/api/BaseReferenceRaw/" + type));
for (int i = 0; i < jsonArray.length(); i++) {
ref.add(new BaseReferenceRaw(jsonArray.getJSONObject(i)));
}
}
private void AddRefTranslation(VectorBaseReferenceTranslationRaw ref, long type, String lang) throws ClientProtocolException, JSONException, IOException {
JSONArray jsonArray = new JSONArray(getJson(_url + "/api/BaseReferenceTranslationRaw/" + type + "?lang=" + lang));
for (int i = 0; i < jsonArray.length(); i++) {
ref.add(new BaseReferenceTranslationRaw(jsonArray.getJSONObject(i)));
}
}
private void AddGisRef(VectorGisBaseReferenceRaw ref) throws ClientProtocolException, JSONException, IOException {
JSONArray jsonArray = new JSONArray(getJson(_url + "/api/GisBaseReferenceRaw"));
for (int i = 0; i < jsonArray.length(); i++) {
ref.add(new GisBaseReferenceRaw(jsonArray.getJSONObject(i)));
}
}
private void AddGisRefTranslation(VectorGisBaseReferenceTranslationRaw ref, String lang) throws ClientProtocolException, JSONException, IOException {
JSONArray jsonArray = new JSONArray(getJson(_url + "/api/GisBaseReferenceTranslationRaw?lang=" + lang));
for (int i = 0; i < jsonArray.length(); i++) {
ref.add(new GisBaseReferenceTranslationRaw(jsonArray.getJSONObject(i)));
}
}
public String Version() throws ClientProtocolException, IOException{
return getJson(_url + "/api/AndroidVersion");
}
public byte[] App() throws ClientProtocolException, IOException{
return getBytes(_url + "/api/AndroidApp");
}
public String Check() throws ClientProtocolException, IOException{
return getJson(_url + "/api/check");
}
public HumanCaseInfoOut HumanCaseSave(HumanCaseInfoIn hc) throws JSONException, ParseException, ClientProtocolException, IOException{
JSONObject in = hc.json();
JSONObject out = new JSONObject(postJson(_url + "/api/HumanCase", in));
return new HumanCaseInfoOut(out);
}
public VetCaseInfoOut VetCaseSave(VetCaseInfoIn vc) throws JSONException, ParseException, ClientProtocolException, IOException{
JSONObject in = vc.json();
JSONObject out = new JSONObject(postJson(_url + "/api/VetCase", in));
return new VetCaseInfoOut(out);
}
public VectorBaseReferenceRaw LoadReferences() throws Exception{
VectorBaseReferenceRaw allref = new VectorBaseReferenceRaw();
AddRefType(allref, BaseReferenceType.rftDiagnosis);
AddRefType(allref, BaseReferenceType.rftHumanAgeType);
AddRefType(allref, BaseReferenceType.rftHumanGender);
AddRefType(allref, BaseReferenceType.rftFinalState);
AddRefType(allref, BaseReferenceType.rftHospStatus);
AddRefType(allref, BaseReferenceType.rftCaseType);
AddRefType(allref, BaseReferenceType.rftCaseReportType);
AddRefType(allref, BaseReferenceType.rftSpeciesList);
AddRef(allref, BaseReferenceType.rftDiagnosis);
AddRef(allref, BaseReferenceType.rftHumanAgeType);
AddRef(allref, BaseReferenceType.rftHumanGender);
AddRef(allref, BaseReferenceType.rftFinalState);
AddRef(allref, BaseReferenceType.rftHospStatus);
AddRef(allref, BaseReferenceType.rftCaseType);
AddRef(allref, BaseReferenceType.rftCaseReportType);
AddRef(allref, BaseReferenceType.rftSpeciesList);
int find = -1;
for(int i = 0; i < allref.size(); i++){
if (allref.get(i).idfsBaseReference == 50815490000000L){ // CaseReportType.Both
find = i;
break;
}
}
if (find > 0){
allref.remove(find);
}
return allref;
}
public VectorBaseReferenceTranslationRaw LoadReferenceTranslations() throws Exception{
VectorBaseReferenceTranslationRaw allref = new VectorBaseReferenceTranslationRaw();
AddRefTranslation(allref, BaseReferenceType.rftDiagnosis, "en");
AddRefTranslation(allref, BaseReferenceType.rftDiagnosis, "ru");
AddRefTranslation(allref, BaseReferenceType.rftDiagnosis, "ka");
AddRefTranslation(allref, BaseReferenceType.rftHumanAgeType, "en");
AddRefTranslation(allref, BaseReferenceType.rftHumanAgeType, "ru");
AddRefTranslation(allref, BaseReferenceType.rftHumanAgeType, "ka");
AddRefTranslation(allref, BaseReferenceType.rftHumanGender, "en");
AddRefTranslation(allref, BaseReferenceType.rftHumanGender, "ru");
AddRefTranslation(allref, BaseReferenceType.rftHumanGender, "ka");
AddRefTranslation(allref, BaseReferenceType.rftFinalState, "en");
AddRefTranslation(allref, BaseReferenceType.rftFinalState, "ru");
AddRefTranslation(allref, BaseReferenceType.rftFinalState, "ka");
AddRefTranslation(allref, BaseReferenceType.rftHospStatus, "en");
AddRefTranslation(allref, BaseReferenceType.rftHospStatus, "ru");
AddRefTranslation(allref, BaseReferenceType.rftHospStatus, "ka");
AddRefTranslation(allref, BaseReferenceType.rftCaseType, "en");
AddRefTranslation(allref, BaseReferenceType.rftCaseType, "ru");
AddRefTranslation(allref, BaseReferenceType.rftCaseType, "ka");
AddRefTranslation(allref, BaseReferenceType.rftCaseReportType, "en");
AddRefTranslation(allref, BaseReferenceType.rftCaseReportType, "ru");
AddRefTranslation(allref, BaseReferenceType.rftCaseReportType, "ka");
AddRefTranslation(allref, BaseReferenceType.rftSpeciesList, "en");
AddRefTranslation(allref, BaseReferenceType.rftSpeciesList, "ru");
AddRefTranslation(allref, BaseReferenceType.rftSpeciesList, "ka");
return allref;
}
public VectorGisBaseReferenceRaw LoadGisReferences() throws Exception{
VectorGisBaseReferenceRaw allref = new VectorGisBaseReferenceRaw();
AddGisRefType(allref, GisBaseReferenceType.rftCountry);
AddGisRefType(allref, GisBaseReferenceType.rftRegion);
AddGisRefType(allref, GisBaseReferenceType.rftRayon);
AddGisRefType(allref, GisBaseReferenceType.rftSettlement);
AddGisRef(allref);
return allref;
}
public VectorGisBaseReferenceTranslationRaw LoadGisReferenceTranslations() throws Exception{
VectorGisBaseReferenceTranslationRaw allref = new VectorGisBaseReferenceTranslationRaw();
AddGisRefTranslation(allref, "en");
AddGisRefTranslation(allref, "ru");
AddGisRefTranslation(allref, "ka");
return allref;
}
}
|
"""Resource for AWS CloudTrail Trails"""
from typing import Type
from botocore.client import BaseClient
from altimeter.aws.resource.resource_spec import ListFromAWSResult
from altimeter.aws.resource.cloudtrail import CloudTrailResourceSpec
from altimeter.core.graph.field.scalar_field import ScalarField
from altimeter.core.graph.schema import Schema
class CloudTrailTrailResourceSpec(CloudTrailResourceSpec):
"""Resource representing a CloudTrail Trail"""
type_name = "trail"
schema = Schema(
ScalarField("Name"),
ScalarField("S3BucketName"),
ScalarField("IncludeGlobalServiceEvents"),
ScalarField("IsMultiRegionTrail"),
)
@classmethod
def list_from_aws(
cls: Type["CloudTrailTrailResourceSpec"], client: BaseClient, account_id: str, region: str,
) -> ListFromAWSResult:
"""Return a dict of dicts of the format:
{'trail_1_arn': {trail_1_dict},
'trail_2_arn': {trail_2_dict},
...}
Where the dicts represent results from describe_trails."""
trails = {}
resp = client.describe_trails(includeShadowTrails=False)
for trail in resp.get("trailList", []):
resource_arn = trail["TrailARN"]
trails[resource_arn] = trail
return ListFromAWSResult(resources=trails)
|
#!/bin/bash
mafonct()
{
echo "param : $1"
}
mafonct allo
afficherinfo()
{
echo "------------"
echo "kernel : " `uname -rs`
echo "------------------"
}
afficherinfo
|
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.u1F686 = void 0;
var u1F686 = {
"viewBox": "0 0 2600 2760.837",
"children": [{
"name": "path",
"attribs": {
"d": "M1723 347q144 0 247 103t103 247v964q0 134-90.5 233.5T1761 2008v172q0 32-22.5 54.5T1685 2257q-32 0-54.5-22.5T1608 2180v-170H992v170q0 32-22.5 54.5T915 2257t-54-22.5-22-54.5v-172q-133-14-222.5-113.5T527 1661V697q0-144 103-247t247-103h846zM901 1570.5q-38-36.5-89-36.5-53 0-90 37t-37 90q0 52 37 89.5t90 37.5q51 0 89-37t38-90q0-54-38-90.5zm976.5.5q-37.5-37-88.5-37-53 0-90 37t-37 90q0 52 37 89.5t90 37.5q52 0 89-37.5t37-89.5q0-53-37.5-90zm40.5-919q0-76-56-132t-132-56H870q-77 0-133 55.5T681 652v239q0 77 56 133t133 56h860q77 0 132.5-56t55.5-133V652z"
},
"children": []
}]
};
exports.u1F686 = u1F686; |
<reponame>AliFrank608-TMW/RacingReact<filename>src/components/socialmedia/SocialIcon/index.js
/**
* @module react
*/
import React from 'react'
/**
* @module PropTypes
*/
import PropTypes from 'prop-types'
/**
* @module classNames
*/
import classNames from 'utils/classnames'
/**
* @module Icon
*/
import Icon from 'components/icon'
/**
* @module getSocialMediaLinks
*/
import { getSocialMediaLinks } from 'utils/socialmedia'
/**
* SocialIcon
* @param {Object} props
* @return {React.Component}
*/
const SocialIcon = props => {
const {
className,
modifier
} = props
// Construct class names.
const modifiedClassNames = classNames('social-icon', className)
return (
<a className={modifiedClassNames} target='_blank' href={getSocialMediaLinks(modifier)}>
<Icon
modifier={modifier} />
</a>
)
}
/**
* propTypes
* @type {Object}
*/
SocialIcon.propTypes = {
className: PropTypes.oneOfType([
PropTypes.string,
PropTypes.arrayOf(PropTypes.string)
]),
modifier: PropTypes.string
}
/**
* defaultProps
* @type {Object}
*/
SocialIcon.defaultProps = {
className: ''
}
/**
* @module SocialIcon
*/
export default SocialIcon
|
#!/usr/bin/env sh
# count_files.sh
# Check if the argument is provided
if [ -z "$1" ]; then
echo "Usage: $0 <directory_path>"
exit 1
fi
# Check if the provided path is a directory
if [ ! -d "$1" ]; then
echo "Error: $1 is not a directory"
exit 1
fi
# Count the files and directories recursively
file_count=$(find "$1" -type f | wc -l)
dir_count=$(find "$1" -type d | wc -l)
# Output the results
echo "Total files: $file_count"
echo "Total directories: $dir_count" |
<reponame>jingxianwen/E3SM<filename>cime/src/externals/pio2/src/clib/pio_lists.c<gh_stars>1-10
/**
* @file
* PIO list functions.
*/
#include <config.h>
#include <pio.h>
#include <pio_internal.h>
#include <string.h>
#include <stdio.h>
#include <uthash.h>
static io_desc_t *pio_iodesc_list = NULL;
static io_desc_t *current_iodesc = NULL;
static iosystem_desc_t *pio_iosystem_list = NULL;
static file_desc_t *pio_file_list = NULL;
static file_desc_t *current_file = NULL;
/**
* Add a new entry to the global list of open files.
*
* @param file pointer to the file_desc_t struct for the new file.
* @author <NAME>
*/
void
pio_add_to_file_list(file_desc_t *file)
{
assert(file);
/* Keep a global pointer to the current file. */
current_file = file;
/* Add file to list. */
HASH_ADD_INT(pio_file_list, pio_ncid, file);
}
/**
* Given ncid, find the file_desc_t data for an open file. The ncid
* used is the interally generated pio_ncid.
*
* @param ncid the PIO assigned ncid of the open file.
* @param cfile1 pointer to a pointer to a file_desc_t. The pointer
* will get a copy of the pointer to the file info.
*
* @returns 0 for success, error code otherwise.
* @author <NAME>
*/
int
pio_get_file(int ncid, file_desc_t **cfile1)
{
file_desc_t *cfile = NULL;
PLOG((2, "pio_get_file ncid = %d", ncid));
/* Caller must provide this. */
if (!cfile1)
return PIO_EINVAL;
/* Find the file pointer. */
if (current_file && current_file->pio_ncid == ncid)
cfile = current_file;
else
HASH_FIND_INT(pio_file_list, &ncid, cfile);
/* If not found, return error. */
if (!cfile)
return PIO_EBADID;
current_file = cfile;
/* We depend on every file having a pointer to the iosystem. */
if (!cfile->iosystem)
return PIO_EINVAL;
/* Let's just ensure we have a valid IO type. */
pioassert(iotype_is_valid(cfile->iotype), "invalid IO type", __FILE__, __LINE__);
/* Copy pointer to file info. */
*cfile1 = cfile;
return PIO_NOERR;
}
/**
* Delete a file from the list of open files.
*
* @param ncid ID of file to delete from list
* @returns 0 for success, error code otherwise
* @author <NAME>, <NAME>
*/
int
pio_delete_file_from_list(int ncid)
{
file_desc_t *cfile = NULL;
int ret;
/* Find the file pointer. */
if (current_file && current_file->pio_ncid == ncid)
cfile = current_file;
else
HASH_FIND_INT(pio_file_list, &ncid, cfile);
if (cfile)
{
HASH_DEL(pio_file_list, cfile);
if (current_file == cfile)
current_file = pio_file_list;
/* Free the varlist entries for this file. */
while (cfile->varlist)
if ((ret = delete_var_desc(cfile->varlist->varid, &cfile->varlist)))
return pio_err(NULL, cfile, ret, __FILE__, __LINE__);
/* Free the memory used for this file. */
free(cfile);
return PIO_NOERR;
}
/* No file was found. */
return PIO_EBADID;
}
/**
* Delete iosystem info from list.
*
* @param piosysid the iosysid to delete
* @returns 0 on success, error code otherwise
* @author <NAME>
*/
int
pio_delete_iosystem_from_list(int piosysid)
{
iosystem_desc_t *ciosystem, *piosystem = NULL;
PLOG((1, "pio_delete_iosystem_from_list piosysid = %d", piosysid));
for (ciosystem = pio_iosystem_list; ciosystem; ciosystem = ciosystem->next)
{
PLOG((3, "ciosystem->iosysid = %d", ciosystem->iosysid));
if (ciosystem->iosysid == piosysid)
{
if (piosystem == NULL)
pio_iosystem_list = ciosystem->next;
else
piosystem->next = ciosystem->next;
free(ciosystem);
return PIO_NOERR;
}
piosystem = ciosystem;
}
return PIO_EBADID;
}
/**
* Add iosystem info to list.
*
* @param ios pointer to the iosystem_desc_t info to add.
* @returns 0 on success, error code otherwise
* @author <NAME>
*/
int
pio_add_to_iosystem_list(iosystem_desc_t *ios)
{
iosystem_desc_t *cios;
int i = 1;
assert(ios);
ios->next = NULL;
cios = pio_iosystem_list;
if (!cios)
pio_iosystem_list = ios;
else
{
i++;
while (cios->next)
{
cios = cios->next;
i++;
}
cios->next = ios;
}
ios->iosysid = i << 16;
return ios->iosysid;
}
/**
* Get iosystem info from list.
*
* @param iosysid id of the iosystem
* @returns pointer to iosystem_desc_t, or NULL if not found.
* @author <NAME>
*/
iosystem_desc_t *
pio_get_iosystem_from_id(int iosysid)
{
iosystem_desc_t *ciosystem;
PLOG((2, "pio_get_iosystem_from_id iosysid = %d", iosysid));
for (ciosystem = pio_iosystem_list; ciosystem; ciosystem = ciosystem->next)
if (ciosystem->iosysid == iosysid)
return ciosystem;
return NULL;
}
/**
* Count the number of open iosystems.
*
* @param niosysid pointer that will get the number of open iosystems.
* @returns 0 for success.
* @author <NAME>
*/
int
pio_num_iosystem(int *niosysid)
{
int count = 0;
/* Count the elements in the list. */
for (iosystem_desc_t *c = pio_iosystem_list; c; c = c->next)
{
PLOG((3, "pio_num_iosystem c->iosysid %d", c->iosysid));
count++;
}
/* Return count to caller via pointer. */
if (niosysid)
*niosysid = count;
return PIO_NOERR;
}
/**
* Add an iodesc.
*
* @param iodesc io_desc_t pointer to data to add to list.
* @returns 0 for success, error code otherwise.
* @author <NAME>, <NAME>
*/
int
pio_add_to_iodesc_list(io_desc_t *iodesc)
{
HASH_ADD_INT(pio_iodesc_list, ioid, iodesc);
current_iodesc = iodesc;
return PIO_NOERR;
}
/**
* Get an iodesc.
*
* @param ioid ID of iodesc to get.
* @returns pointer to the iodesc struc.
* @author <NAME>
*/
io_desc_t *
pio_get_iodesc_from_id(int ioid)
{
io_desc_t *ciodesc=NULL;
if (current_iodesc && current_iodesc->ioid == ioid)
ciodesc = current_iodesc;
else
{
HASH_FIND_INT(pio_iodesc_list, &ioid, ciodesc);
current_iodesc = ciodesc;
}
return ciodesc;
}
/**
* Delete an iodesc.
*
* @param ioid ID of iodesc to delete.
* @returns 0 on success, error code otherwise.
* @author <NAME>
*/
int
pio_delete_iodesc_from_list(int ioid)
{
io_desc_t *ciodesc;
ciodesc = pio_get_iodesc_from_id(ioid);
if (ciodesc)
{
HASH_DEL(pio_iodesc_list, ciodesc);
if (current_iodesc == ciodesc)
current_iodesc = pio_iodesc_list;
free(ciodesc);
return PIO_NOERR;
}
return PIO_EBADID;
}
/**
* Add var_desc_t info to the list.
*
* @param varid the varid of the variable.
* @param rec_var non-zero if this is a record var.
* @param pio_type the PIO type.
* @param pio_type_size size of the PIO type in bytes
* @param mpi_type the MPI type.
* @param mpi_type_size size of the MPI type in bytes.
* @param varlist pointer to list to add to.
* @returns 0 for success, error code otherwise.
* @author <NAME>
*/
int
add_to_varlist(int varid, int rec_var, int pio_type, int pio_type_size,
MPI_Datatype mpi_type, int mpi_type_size, var_desc_t **varlist)
{
var_desc_t *var_desc;
/* Check inputs. */
pioassert(varid >= 0 && varlist, "invalid input", __FILE__, __LINE__);
/* Allocate storage. */
if (!(var_desc = calloc(1, sizeof(var_desc_t))))
return PIO_ENOMEM;
/* Set values. */
var_desc->varid = varid;
var_desc->rec_var = rec_var;
var_desc->pio_type = pio_type;
var_desc->pio_type_size = pio_type_size;
var_desc->mpi_type = mpi_type;
var_desc->mpi_type_size = mpi_type_size;
var_desc->record = -1;
HASH_ADD_INT(*varlist, varid, var_desc);
return PIO_NOERR;
}
/**
* Get a var_desc_t info for a variable.
*
* @param varid ID of variable to get var_desc_t of.
* @param varlist pointer to list of var_desc_t.
* @param var_desc pointer that gets pointer to var_desc_t struct.
* @returns 0 for success, error code otherwise.
* @author <NAME>
*/
int
get_var_desc(int varid, var_desc_t **varlist, var_desc_t **var_desc)
{
var_desc_t *my_var=NULL;
/* Check inputs. */
pioassert(varlist, "invalid input", __FILE__, __LINE__);
/* Empty varlist. */
if (!*varlist)
return PIO_ENOTVAR;
HASH_FIND_INT( *varlist, &varid, my_var);
/* Did we find it? */
if (!my_var)
return PIO_ENOTVAR;
else
*var_desc = my_var;
return PIO_NOERR;
}
/**
* Delete var_desc_t info for a variable.
*
* @param varid ID of variable to delete.
* @param varlist pointer to list of var_desc_t.
* @returns 0 on success, error code otherwise.
* @author <NAME>
*/
int
delete_var_desc(int varid, var_desc_t **varlist)
{
var_desc_t *v;
int ret;
/* Check inputs. */
pioassert(varid >= 0 && varlist, "invalid input", __FILE__, __LINE__);
/* Null list means no variables to delete. */
if (!*varlist)
return PIO_ENOTVAR;
if ((ret = get_var_desc( varid, varlist, &v)))
return ret;
HASH_DEL(*varlist, v);
/* Free memory. */
if (v->fillvalue)
free(v->fillvalue);
free(v);
return PIO_NOERR;
}
|
/*
* Copyright 2015 The SageTV Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "stdafx.h"
#ifndef __CAM_CTRL_h__
#define __CAM_CTRL_h__
#ifdef __cplusplus
extern "C" {
#endif
#ifdef WIN32
#if( _MSC_VER <= 800 )
#pragma pack(1)
#else
#include <pshpack1.h>
#endif
#endif
#define FIREDTV_CAM "FIREDTV " //8 bytes tag
#define TECHNOTREND_CAM "TECHNTD " //8 bytes tag
#define ANYSEE_CAM "ANYSEE "
#define UNKNOWN_CAM "UNKNOWN " //8 bytes tag
#define TECHNOTREND_VENDOR_ID "1131"
#define FIREDTV_VENDOR_ID "xxxx"
#define FIREDTV_MFG "Digital Everywhere"
#define TECHNOTREND_MFG "TechnoTrend"
#define ANYSEE_MFG "Advanced Multimedia Technology Co.,Ltd. Korea"
#define ANYSEE_VENDOR_ID "1c73"
//typedef struct
//{
// short pid;
// short service;
// short channel;
// void* parser;
// void* tbl;
// char* data;
// short length;
//} SECTION_INFO;
typedef long (*DATA_DUMP)( void* context, short bytes, void* mesg );
DEFINE_GUID(IID_KSPROPSETID_FIREDTV,
0xab132414, 0xd060, 0x11d0, 0x85, 0x83, 0x00, 0xc0, 0x4f, 0xd9, 0xba, 0xf3);
#define KSPROPERTY_FIRESAT_SELECT_MULTIPLEX_DVB_S 0
#define KSPROPERTY_FIRESAT_SELECT_SERVICE_DVB_S 1
#define KSPROPERTY_FIRESAT_SELECT_PIDS_DVB_S 2
#define KSPROPERTY_FIRESAT_SIGNAL_STRENGTH_TUNER 3
#define KSPROPERTY_FIRESAT_DRIVER_VERSION 4
#define KSPROPERTY_FIRESAT_SELECT_MULTIPLEX_DVB_T 5
#define KSPROPERTY_FIRESAT_SELECT_PIDS_DVB_T 6
#define KSPROPERTY_FIRESAT_SELECT_MULTIPLEX_DVB_C 7
#define KSPROPERTY_FIRESAT_SELECT_PIDS_DVB_C 8
#define KSPROPERTY_FIRESAT_GET_FRONTEND_STATUS 9
#define KSPROPERTY_FIRESAT_GET_SYSTEM_INFO 10
#define KSPROPERTY_FIRESAT_GET_FIRMWARE_VERSION 11
#define KSPROPERTY_FIRESAT_LNB_CONTROL 12
#define KSPROPERTY_FIRESAT_GET_LNB_PARAM 13
#define KSPROPERTY_FIRESAT_SET_LNB_PARAM 14
#define KSPROPERTY_FIRESAT_SET_POWER_STATUS 15
#define KSPROPERTY_FIRESAT_SET_AUTO_TUNE_STATUS 16
#define KSPROPERTY_FIRESAT_FIRMWARE_UPDATE 17
#define KSPROPERTY_FIRESAT_FIRMWARE_UPDATE_STATUS 18
#define KSPROPERTY_FIRESAT_CI_RESET 19
#define KSPROPERTY_FIRESAT_CI_WRITE_TPDU 20
#define KSPROPERTY_FIRESAT_CI_READ_TPDU 21
#define KSPROPERTY_FIRESAT_HOST2CA 22
#define KSPROPERTY_FIRESAT_CA2HOST 23
#define KSPROPERTY_FIRESAT_GET_BOARD_TEMP 24
#define KSPROPERTY_FIRESAT_TUNE_QPSK 25
#define KSPROPERTY_FIRESAT_REMOTE_CONTROL_REGISTER 26
#define KSPROPERTY_FIRESAT_REMOTE_CONTROL_CANCEL 27
#define KSPROPERTY_FIRESAT_GET_CI_STATUS 28
#define KSPROPERTY_FIRESAT_TEST_INTERFACE 29
#define CI_MMI_REQUEST 0x0100
#define CI_PMT_REPLY 0x0080
#define CI_DATE_TIME_REQEST 0x0040
#define CI_APP_INFO_AVAILABLE 0x0020
#define CI_MODULE_PRESENT 0x0010
#define CI_MODULE_IS_DVB 0x0008
#define CI_MODULE_ERROR 0x0004
#define CI_MODULE_INIT_READY 0x0002
#define CI_ERR_MSG_AVAILABLE 0x0001
#define CAM_CLOSE 0
#define CAM_INITIALIZED 1
#define CAM_OPEN 2
#define CAM_PENDING 3
#define CAM_ENABLED 4
#define CAM_SKIP 5
#define CAM_ERROR -1
#define CAM_NULL 0x80
#define MAX_PMT_SIZE (1024+12)
typedef struct {
char TAG[8]; //common TAG
int state;
void *env;
void *pCapInfo;
bool OnPMTEnable;
} CAM_CTRL_HEADER;
typedef struct {
unsigned long bCurrentTransponder; //4
unsigned long bFullTransponder; //8
unsigned long uLnb; //12
unsigned long uFrequency; //16
unsigned long uSymbolRate; //20
unsigned char uFecInner; //21
unsigned char uPolarization; //22
unsigned char dummy1; //23
unsigned char dummy2; //24
unsigned char uNumberOfValidPids; //25
unsigned char dummy3; //26
unsigned short pids[16];
} DVB_S_PIDS;
typedef struct {
unsigned long bCurrentTransponder; //Set TRUE
unsigned long bFullTransponder; //Set FALSE when selecting PIDs
unsigned long uFrequency; // kHz 47.000-860.000
unsigned char uBandwidth; // BANDWIDTH_8_MHZ, BANDWIDTH_7_MHZ, BANDWIDTH_6_MHZ
unsigned char uConstellation; // CONSTELLATION_DVB_T_QPSK,CONSTELLATION_QAM_16,CONSTELLATION_QAM_64,OFDM_AUTO
unsigned char uCodeRateHP; // CR_12,CR_23,CR_34,CR_56,CR_78,OFDM_AUTO
unsigned char uCodeRateLP; // CR_12,CR_23,CR_34,CR_56,CR_78,OFDM_AUTO
unsigned char uGuardInterval; // GUARD_INTERVAL_1_32,GUARD_INTERVAL_1_16,GUARD_INTERVAL_1_8,GUARD_INTERVAL_1_4,OFDM_AUTO
unsigned char uTransmissionMode; // TRANSMISSION_MODE_2K, TRANSMISSION_MODE_8K, OFDM_AUTO
unsigned char uHierarchyInfo; // HIERARCHY_NONE,HIERARCHY_1,HIERARCHY_2,HIERARCHY_4,OFDM_AUTO
unsigned char dummy; //pading
unsigned char uNumberOfValidPids; // 1-16
unsigned char dummy2; //
unsigned short pids[16];
} DVB_T_PIDS;
//typedef struct {
// unsigned char slot;
// unsigned char tag;
// unsigned char pad1;
// unsigned char pad2;
// unsigned char more;
// unsigned char pad3;
// unsigned char pad4;
// unsigned char pad5;
// unsigned short length;
// } FIREDTV_CA_HEAD;
typedef struct {
unsigned char data1[MAX_PMT_SIZE];
unsigned char data2[MAX_PMT_SIZE];
} FIREDTV_CA;
#define FIREDTV_CA_OFFSET 10
typedef struct {
CAM_CTRL_HEADER header;
unsigned serviceID;
FIREDTV_CA ca_data;
} FIREDTV;
///////////////////////////////////////////////////////////////////////
//Anysee
///////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
//CI/CAM
///////////////////////////////////////////////////////////////////////////////
struct DtvCIApi {
virtual HRESULT WINAPI OpenCILib(HWND hwnd,int iPortIndex);
virtual HRESULT WINAPI CI_Control(DWORD command, LPARAM *pParam, LPARAM *pRetParam);
virtual HRESULT WINAPI SetanyseeCIPMTSection(long lSize, BYTE *pBuf) PURE;
};
#define MAX_DEVICES_NUM 32
typedef struct _anyseeCIDevicesInfo_
{
CHAR pBuffer[MAX_DEVICES_NUM][256]; // Filter graph device path(=DisplayName)
DWORD dwLength[MAX_DEVICES_NUM]; // The length of pBuffer
DWORD dwFGIndex[MAX_DEVICES_NUM]; // Filter graph device path(=DisplayName) index(1, 2, 3, ...)
DWORD dwADIndex[MAX_DEVICES_NUM]; // anysee device number(1, 2, 3, ...)
}ANYSEECIDEVICESINFO, *PANYSEECIDEVICESINFO;
#define CIAPI_API
typedef DWORD (WINAPI* pCreateDtvCIAPI)(DtvCIApi **);
CIAPI_API DWORD WINAPI CreateDtvCIAPI(DtvCIApi **);
typedef DWORD (WINAPI* pDestroyDtvCIAPI)(DtvCIApi **);
CIAPI_API DWORD WINAPI DestroyDtvCIAPI(DtvCIApi **);
typedef int (WINAPI* pGetanyseeNumberofDevices)();
CIAPI_API int WINAPI GetanyseeNumberofDevices();
typedef int (WINAPI* pGetanyseeNumberofDevicesEx)(PANYSEECIDEVICESINFO pList);
CIAPI_API int WINAPI GetanyseeNumberofDevicesEx(PANYSEECIDEVICESINFO pList);
// Add
typedef void ( *pCIStateFunc)(int nPort, int nCmd, char *str); // CI Status Callback Function.
typedef void ( *pCIMessageFunc)(int nPort, PVOID pData); // CI Munu Data Callback Function.
#define WM_ANYSEE_CI_MESSAGE WM_USER + 0x1620 // Menu Data sending Message
#define WM_ANYSEE_CI_STATES WM_USER + 0x1621 // CI Status sending Message
typedef struct _tagCIStatus
{
int nSize; // struct size
int nPortNum; // Device number
char strMsg[256]; // string data
}tagCIStatus, *ptagCIStatus;
typedef struct {
int line_count;
int alloc_count;
unsigned char strs[32][256]; // menu string data
} MMIStrsBlock;
typedef struct _tagCIMessages
{
int nSize; // struct size
int nPortNum; // Device Port Number
int nSlotNum; // Slot Number
int nMuLines; // Menu Lines
int nOptLines; // Option message Lines
int nBlind; // Requestion to input CAM = 1 , CAM Menu = 2
int nBlindLen; // nBlind == 1, Total input key.
int nInputCount; // User input Key count
char SlotTitle[256]; // CAM name
MMIStrsBlock MMIMsg; // Menu Message 0 ~ 2 Index , Option Message 3 ~ nOptLines Index
} tagCIMsgs, *ptagCIMsgs;
enum CI_KEY_MAP{
BTN_NUM_0 = 1,
BTN_NUM_1 = 2,
BTN_NUM_2 = 3,
BTN_NUM_3 = 4,
BTN_NUM_4 = 5,
BTN_NUM_5 = 6,
BTN_NUM_6 = 7,
BTN_NUM_7 = 8,
BTN_NUM_8 = 9,
BTN_NUM_9 = 10,
BTN_MENU = 20,
BTN_EXIT = 21,
BTN_ARROW_UP = 22,
BTN_ARROW_DOWN = 23,
BTN_ARROW_LEFT = 24,
BTN_ARROW_RIGHT = 25,
BTN_SELECT = 26,
BTN_CLEAR = 30
};
enum CI_MESSAGE_COMMAND{
CI_MSG_EXTRACTED_CAM = 2002, // CAM Extracting Message.
CI_MSG_CLEAR = 2100, // Clear message
CI_MSG_INITIALIZATION_CAM = 2101, // CAM Initializing message
CI_MSG_INSERT_CAM = 2102, // CAM initialization finishing message.
CI_SEND_PMT_COMPLET = 2103 // PMT Set up message.
};
enum CI_CONTROL_COMMAND{
CI_CONTROL_GET_DEVICE_NUM = 1100, // Connected Set number
CI_CONTROL_IS_OPEN = 1104, // Check the status of connected set.
CI_CONTROL_SET_KEY = 1105, // Key setting.
CI_CONTROL_SET_TDT = 1106, // TDT setting.
CI_CONTROL_SET_PMT = 1110, // PMT setting
CI_CONTROL_IS_PLUG_OPEN = 2000 // Check the status of connected set and set callback func.
};
typedef struct {
CAM_CTRL_HEADER header;
unsigned serviceID;
int state;
int portNum;
DtvCIApi *CILib;
HINSTANCE hLibHandle;
pCreateDtvCIAPI CreateCI;
pDestroyDtvCIAPI DestroyCI;
pGetanyseeNumberofDevicesEx GetanyseeNumberofDevicesEx;
} ANYSEE;
////////////////////////////////////////////////////////////////////////
//Technotrend
////////////////////////////////////////////////////////////////////////
typedef enum _tt_ConnectionType
{
LscPhone =1,
LscCable =2,
LscInternet =3,
LscSerial
} TTCONNTYPE;
typedef enum _TechnoTrendDeviceType
{
TypeUnknown = 0,
DevTypeB2=1, // Budget 2
DevTypeB3=2, // Budget 3 aka TT-budget T-3000
DevTypeUsb2=3, // USB 2.0
DevTypeUsb2Pinnacle=4 // USB 2.0 Pinnacle
} TTDEVTYPE;
typedef struct
{
char nStatus; // CI status
char* pMenuTitleString; // menu title string
unsigned short* pCaSystemIDs; // cam system ID's
unsigned short wNoOfCaSystemIDs; // number of cam system ID's
} SLOTINF;
typedef void (__stdcall* PFN_CI_OnSlotStatus)(DWORD Context, char nSlot, char nStatus, SLOTINF* csInfo);
typedef void (__stdcall* PFN_CI_OnCAStatus)(DWORD Context, char nSlot, char nReplyTag, unsigned short wStatus);
typedef struct
{
PFN_CI_OnSlotStatus onSlotStatus;
void* onSlotStatusContext;
PFN_CI_OnCAStatus onCAStatus;
void* onCAStatusContext;
} CallbackFunctionsSlim;
typedef unsigned int (__stdcall* pfn_bdaapiOpenHWIdx)(unsigned int DevType, unsigned int uiDevID);
typedef int (__stdcall* pfn_bdaapiOpenCISlim)(unsigned int hOpen, CallbackFunctionsSlim CbFuncPointer);
typedef int (__stdcall* pfn_bdaapiOpenCIWithoutPointer)(unsigned int hOpen);
typedef int (__stdcall* pfn_bdaapiCIGetSlotStatus)(unsigned int hOpen, char nSlot);
typedef int (__stdcall* pfn_bdaapiCloseCI)(unsigned int hOpen);
typedef void(__stdcall* pfn_bdaapiClose)(unsigned int hOpen);
typedef int (__stdcall* pfn_bdaapiCIReadPSIFastDrvDemux)(unsigned int hOpen, int PNR);
typedef int (__stdcall* pfn_bdaapiSetDiSEqCMsg)(unsigned int hOpen, int* data, char length, char repeat, char toneburst, int polarity);
typedef int (__stdcall* pfn_bdaapiSetDVBTAntPwr)(unsigned int hOpen, bool bAntPwrOnOff);
typedef int (__stdcall* pfn_bdaapiGetDVBTAntPwr)(unsigned int hOpen, int* uiAntPwrOnOff);
typedef struct {
CAM_CTRL_HEADER header;
char status;
int serviceID;
int deviceType;
int handle;
HMODULE hLibHandle;
CallbackFunctionsSlim CFS;
pfn_bdaapiOpenHWIdx bdaapiOpenHWIdx;
pfn_bdaapiOpenCISlim bdaapiOpenCISlim;
pfn_bdaapiOpenCIWithoutPointer bdaapiOpenCIWithoutPointer;
pfn_bdaapiCIGetSlotStatus bdaapiCIGetSlotStatus;
pfn_bdaapiCloseCI bdaapiCloseCI;
pfn_bdaapiClose bdaapiClose;
pfn_bdaapiCIReadPSIFastDrvDemux bdaapiCIReadPSIFastDrvDemux;
pfn_bdaapiSetDiSEqCMsg bdaapiSetDiSEqCMsg;
pfn_bdaapiSetDVBTAntPwr bdaapiSetDVBTAntPwr;
pfn_bdaapiGetDVBTAntPwr bdaapiGetDVBTAntPwr;
} TECHNOTREND;
int IsCAMInitialized( JNIEnv *env, DShowCaptureInfo* pCapInfo );
int IsCAMValid( JNIEnv *env, DShowCaptureInfo* pCapInfo );
int ReleaseCAM( JNIEnv *env, DShowCaptureInfo* pCapInfo );
int InitialCAM( JNIEnv *env, DShowCaptureInfo* pCapInfo, char* pDeviceName );
int OpenCAM( JNIEnv *env, DShowCaptureInfo* pCapInfo );
int CloseCAM( JNIEnv *env, DShowCaptureInfo* pCapInfo );
long OnCamPMT( void* context, short bytes, void* mesg );
int SwitchCamChannel( JNIEnv *env, DShowCaptureInfo* pCapInfo, int serviceId, int encryptionFlag );
void EnableCAMPMT( JNIEnv *env, DShowCaptureInfo* pCapInfo );
void DisableCAMPMT( JNIEnv *env, DShowCaptureInfo* pCapInfo );
#ifdef __cplusplus
}
#endif
#endif
|
# recipes/default.rb
# Installs InfluxDB
chef_gem 'toml-rb' do
compile_time false if respond_to?(:compile_time)
end
chef_gem 'influxdb' do
compile_time false if respond_to?(:compile_time)
end
influxdb_install 'influxdb' do
include_repository node['influxdb']['include_repository']
install_version node['influxdb']['version']
install_type node['influxdb']['install_type']
action [:install]
end
influxdb_config node['influxdb']['config_file_path'] do
config node['influxdb']['config']
end
service 'influxdb' do
action [:enable, :start]
end
|
def filter_even_numbers(numbers):
result = []
for number in numbers:
if (number % 2) != 0:
result.append(number)
return result
result = filter_even_numbers([1, 2, 3, 4])
print(result) |
# This script downloads and builds linux and python sources, and outputs
# the snakeware structure in the build/ directory.
# linux kernel version
KERNEL_MAJ=v5.x
KERNEL_MIN=5.6.14
# python version
PYTHON_VER=3.8.3
# snakeware dirs
SNAKEWARE=$PWD
SRC=$PWD/src
BLD=$PWD/build
mkdir -p $SRC
mkdir -p $BLD
mkdir -p $BLD/etc/init.d $BLD/proc $BLD/sys $BLD/dev $BLD/tmp $BLD/boot $BLD/bin
chmod 1777 $BLD/tmp
# copy libs
#\TODO build these libs from source
mkdir -p $BLD/usr/lib $BLD/usr/lib64
# python dependencies
cp /usr/lib/libcrypt.so.1 $BLD/usr/lib
cp /usr/lib/libc.so.6 $BLD/usr/lib/
cp /usr/lib/libpython3.8.so.1.0 $BLD/usr/lib/
cp /usr/lib64/ld-linux-x86-64.so.2 $BLD/usr/lib64/
cp /usr/lib/libpthread.so.0 $BLD/usr/lib/
cp /usr/lib/libdl.so.2 $BLD/usr/lib/
cp /usr/lib/libutil.so.1 $BLD/usr/lib/
cp /usr/lib/libm.so.6 $BLD/usr/lib/
cp /lib/libgcc_s.so.1 $BLD/usr/lib/
# pygame dependencies
cp /usr/lib/libSDL-1.2.so.0 $BLD/usr/lib/
cp /usr/lib/libz.so.1 $BLD/usr/lib/
cp /lib/libSDL_ttf-2.0.so.0 $BLD/usr/lib/
cp /lib/libfreetype.so.6 $BLD/usr/lib/
cp /lib/libbz2.so.1.0 $BLD/usr/lib/
cp /lib/libpng16.so.16 $BLD/usr/lib/
cp /lib/libharfbuzz.so.0 $BLD/usr/lib/
cp /lib/libglib-2.0.so.0 $BLD/usr/lib/
cp /lib/libgraphite2.so.3 $BLD/usr/lib/
cp /lib/libpcre.so.1 $BLD/usr/lib/
mkdir -p $BLD/lib $BLD/lib64
cp $BLD/usr/lib/* $BLD/lib/
cp $BLD/usr/lib64/* $BLD/lib64/
# GET SOURCES
cd $SRC
if [ ! -d "linux-$KERNEL_MIN" ]; then
echo "Downloading kernel source..."
wget https://cdn.kernel.org/pub/linux/kernel/$KERNEL_MAJ/linux-$KERNEL_MIN.tar.xz
tar xf linux-$KERNEL_MIN.tar.xz
rm linux-$KERNEL_MIN.tar.xz
fi
if [ ! -d "Python-$PYTHON_VER" ]; then
echo "Downloading python source..."
wget https://www.python.org/ftp/python/3.8.3/Python-$PYTHON_VER.tar.xz
tar xf Python-$PYTHON_VER.tar.xz
rm Python-$PYTHON_VER.tar.xz
fi
if [ ! -d "busybox" ]; then
echo "Downloading busybox source..."
git clone https://git.busybox.net/busybox
fi
# BUILD SOURCES
# build kernel with default config
#\TODO better config?
cp $SNAKEWARE/config/kernel-config $SRC/linux-$KERNEL_MIN/.config
cd $SRC/linux-$KERNEL_MIN
make -j4
make modules
make modules_install INSTALL_MOD_PATH=$BLD/
cp arch/x86/boot/bzImage $BLD/boot/vmlinuz
# build python
cd $SRC/Python-$PYTHON_VER
./configure --prefix=$BLD/usr/
make -j4
make install
# build busybox
cd $SRC/busybox
make defconfig
export LDFLAGS="--static"
make -j4
make install
#sudo chmod 4755 _install/bin/busybox
sudo chown root _install/bin/busybox
cp -a _install/* $BLD/
rm $BLD/linuxrc
cd $BLD
ln -s bin/busybox init
# create /etc/init.d/rcS
cat << EOF > $BLD/etc/init.d/rcS
#!/bin/sh
mount -a
mdev -s
/bin/hostname -F /etc/hostname
/sbin/ifconfig lo 127.0.0.1 up
while [ 1 ]
do
clear
/usr/bin/python3
done
EOF
chmod +x $BLD/etc/init.d/rcS
# create /etc/fstab
cat << EOF > $BLD/etc/fstab
proc /proc proc defaults 0 0
sysfs /sys sysfs defaults 0 0
devpts /dev/pts devpts defaults 0 0
tmpfs /dev/shm tmpfs defaults 0 0
EOF
# create /etc/hostname
echo 'localhost' > $BLD/etc/hostname
|
#!/bin/sh
# Copyright (c) 2014-2019 The XBit Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
export LC_ALL=C
set -e
ROOTDIR=dist
BUNDLE="${ROOTDIR}/XBit-Qt.app"
CODESIGN=codesign
TEMPDIR=sign.temp
TEMPLIST=${TEMPDIR}/signatures.txt
OUT=signature-osx.tar.gz
OUTROOT=osx
if [ -z "$1" ]; then
echo "usage: $0 <codesign args>"
echo "example: $0 -s MyIdentity"
exit 1
fi
rm -rf ${TEMPDIR} ${TEMPLIST}
mkdir -p ${TEMPDIR}
${CODESIGN} -f --file-list ${TEMPLIST} "$@" "${BUNDLE}"
grep -v CodeResources < "${TEMPLIST}" | while read i; do
TARGETFILE="${BUNDLE}/$(echo "${i}" | sed "s|.*${BUNDLE}/||")"
SIZE=$(pagestuff "$i" -p | tail -2 | grep size | sed 's/[^0-9]*//g')
OFFSET=$(pagestuff "$i" -p | tail -2 | grep offset | sed 's/[^0-9]*//g')
SIGNFILE="${TEMPDIR}/${OUTROOT}/${TARGETFILE}.sign"
DIRNAME="$(dirname "${SIGNFILE}")"
mkdir -p "${DIRNAME}"
echo "Adding detached signature for: ${TARGETFILE}. Size: ${SIZE}. Offset: ${OFFSET}"
dd if="$i" of="${SIGNFILE}" bs=1 skip=${OFFSET} count=${SIZE} 2>/dev/null
done
grep CodeResources < "${TEMPLIST}" | while read i; do
TARGETFILE="${BUNDLE}/$(echo "${i}" | sed "s|.*${BUNDLE}/||")"
RESOURCE="${TEMPDIR}/${OUTROOT}/${TARGETFILE}"
DIRNAME="$(dirname "${RESOURCE}")"
mkdir -p "${DIRNAME}"
echo "Adding resource for: \"${TARGETFILE}\""
cp "${i}" "${RESOURCE}"
done
rm ${TEMPLIST}
tar -C "${TEMPDIR}" -czf "${OUT}" .
rm -rf "${TEMPDIR}"
echo "Created ${OUT}"
|
def add_without_plus(a, b):
while b:
carry = a & b
a = a ^ b
b = carry << 1
return a |
package com.designre.blog.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.designre.blog.model.entity.ArticleTag;
public interface ArticleTagMapper extends BaseMapper<ArticleTag> {
}
|
namespace Shuriken {
export class Collider {
private shuriken: Shuriken;
private currentCollisionPairs: Array<[IEntity, IEntity]> = [];
constructor(shuriken: Shuriken) {
this.shuriken = shuriken;
}
public update() {
this.currentCollisionPairs = [];
const ent = this.shuriken.entities.all();
for (let i = 0; i < ent.length; i++) {
for (let j = i + 1; j < ent.length; j++) {
this.currentCollisionPairs.push([ent[i], ent[j]]);
}
}
// test collisions
while (this.currentCollisionPairs.length > 0) {
const pair = this.currentCollisionPairs.shift();
if (this.isColliding(pair[0], pair[1])) {
this.collision(pair[0], pair[1]);
}
}
}
public createEntity(entity: IEntity) {
const allEntities = this.shuriken.entities.all();
for (const e of allEntities) {
if (e !== entity) { // decouple from when c.entities adds to _entities
this.currentCollisionPairs.push([e, entity]);
}
}
}
public destroyEntity(entity: IEntity) {
// if coll detection happening, remove any pairs that include entity
for (let i = this.currentCollisionPairs.length - 1; i >= 0; i--) {
if (this.currentCollisionPairs[i][0] === entity ||
this.currentCollisionPairs[i][1] === entity) {
this.currentCollisionPairs.splice(i, 1);
}
}
}
public isColliding(obj1: IEntity, obj2: IEntity) {
return obj1 !== obj2 &&
this.isSetupForCollisions(obj1) &&
this.isSetupForCollisions(obj2) &&
this.isIntersecting(obj1, obj2);
}
public isIntersecting(obj1: IEntity, obj2: IEntity) {
const obj1BoundingBox = this.getBoundingBox(obj1);
const obj2BoundingBox = this.getBoundingBox(obj2);
if (obj1BoundingBox === ColliderShape.RECTANGLE && obj2BoundingBox === ColliderShape.RECTANGLE) {
return Maths.rectanglesIntersecting(obj1, obj2);
} else if (obj1BoundingBox === ColliderShape.CIRCLE && obj2BoundingBox === ColliderShape.RECTANGLE) {
return Maths.circleAndRectangleIntersecting(obj1, obj2);
} else if (obj1BoundingBox === ColliderShape.RECTANGLE && obj2BoundingBox === ColliderShape.CIRCLE) {
return Maths.circleAndRectangleIntersecting(obj2, obj1);
} else if (obj1BoundingBox === ColliderShape.CIRCLE && obj2BoundingBox === ColliderShape.CIRCLE) {
return Maths.circlesIntersecting(obj1, obj2);
} else {
throw new Error("Objects being collision tested have unsupported bounding box types.");
}
}
private isSetupForCollisions(obj: IEntity) {
return obj.center !== undefined && obj.size !== undefined;
}
private collision(entity1: IEntity, entity2: IEntity) {
this.notifyEntityOfCollision(entity1, entity2);
this.notifyEntityOfCollision(entity2, entity1);
}
// todo move on entity ??
private getBoundingBox(obj: IEntity): ColliderShape {
return obj.boundingBox || ColliderShape.RECTANGLE;
}
private notifyEntityOfCollision(entity: IEntity, other: IEntity) {
if (entity.collision !== undefined) {
entity.collision(other);
}
}
}
}
|
package com.ing.baker.baas.protocol
import akka.actor.ActorRef
/**
* A Protocol executed after finding a candidate match between a QuestMandated and an InteractionAgent, it makes sure
* that 1 QuestMandated commits with 1 InteractionAgent only and vice versa, without leaving orphan agents.
*/
sealed trait ProtocolQuestCommit
object ProtocolQuestCommit {
case class Considering(agent: ActorRef) extends ProtocolQuestCommit
case class Commit(mandated: ActorRef, execute: ProtocolInteractionExecution.ExecuteInstance) extends ProtocolQuestCommit
case object QuestTaken extends ProtocolQuestCommit
}
|
set -xe
pacman -S cvc4 coinor-cbc
|
#! /bin/bash
#SBATCH -o /home/hpc/pr63so/di69fol/workspace/SWEET_2015_12_26/benchmarks_performance/rexi_tests_lrz_freq_waves/2015_12_27_scalability_nr_fd/run_nr_fd_cart_cgrid_t004_n0128_r0001_a1.txt
###SBATCH -e /home/hpc/pr63so/di69fol/workspace/SWEET_2015_12_26/benchmarks_performance/rexi_tests_lrz_freq_waves/2015_12_27_scalability_nr_fd/run_nr_fd_cart_cgrid_t004_n0128_r0001_a1.err
#SBATCH -J nr_fd_cart_cgrid_t004_n0128_r0001_a1
#SBATCH --get-user-env
#SBATCH --clusters=mpp2
#SBATCH --ntasks=1
#SBATCH --cpus-per-task=4
#SBATCH --exclusive
#SBATCH --export=NONE
#SBATCH --time=02:00:00
#declare -x NUMA_BLOCK_ALLOC_VERBOSITY=1
declare -x KMP_AFFINITY="granularity=thread,compact,1,0"
declare -x OMP_NUM_THREADS=4
echo "OMP_NUM_THREADS=$OMP_NUM_THREADS"
echo
. /etc/profile.d/modules.sh
module unload gcc
module unload fftw
module unload python
module load python/2.7_anaconda_nompi
module unload intel
module load intel/16.0
module unload mpi.intel
module load mpi.intel/5.1
module load gcc/5
cd /home/hpc/pr63so/di69fol/workspace/SWEET_2015_12_26/benchmarks_performance/rexi_tests_lrz_freq_waves/2015_12_27_scalability_nr_fd
cd ../../../
. local_software/env_vars.sh
# force to use FFTW WISDOM data
declare -x SWEET_FFTW_LOAD_WISDOM_FROM_FILE="FFTW_WISDOM_nofreq_T4"
time -p mpiexec.hydra -genv OMP_NUM_THREADS 4 -envall -ppn 7 -n 1 ./build/nr_fd_cart_cgrid_tyes_a1 --initial-freq-x-mul=2.0 --initial-freq-y-mul=1.0 -f 1 -g 1 -H 1 -X 1 -Y 1 --compute-error 1 -t 50 -R 4 -C 0.3 -N 128 -U 0 -S 0 --timestepping-mode 0 --staggering 1 -C 0.3
|
// ============================================================================
//
// Copyright (C) 2006-2021 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
// ============================================================================
package org.talend.designer.mapper.ui.visualmap.table;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.TrayDialog;
import org.eclipse.jface.fieldassist.IContentProposal;
import org.eclipse.jface.fieldassist.IContentProposalListener;
import org.eclipse.jface.fieldassist.IContentProposalProvider;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.viewers.CellEditor;
import org.eclipse.jface.viewers.ComboBoxCellEditor;
import org.eclipse.jface.viewers.DialogCellEditor;
import org.eclipse.jface.viewers.ICellEditorListener;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.ExtendedModifyEvent;
import org.eclipse.swt.custom.ExtendedModifyListener;
import org.eclipse.swt.custom.ScrolledComposite;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.events.ControlEvent;
import org.eclipse.swt.events.ControlListener;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.FocusListener;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.swt.events.MouseTrackListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Cursor;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Layout;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.ToolItem;
import org.eclipse.ui.dialogs.SearchPattern;
import org.talend.commons.exception.PersistenceException;
import org.talend.commons.ui.runtime.exception.ExceptionHandler;
import org.talend.commons.ui.runtime.expressionbuilder.IExpressionBuilderDialogController;
import org.talend.commons.ui.runtime.image.EImage;
import org.talend.commons.ui.runtime.image.ImageProvider;
import org.talend.commons.ui.runtime.swt.tableviewer.TableViewerCreatorColumnNotModifiable;
import org.talend.commons.ui.runtime.swt.tableviewer.TableViewerCreatorNotModifiable;
import org.talend.commons.ui.runtime.swt.tableviewer.TableViewerCreatorNotModifiable.LAYOUT_MODE;
import org.talend.commons.ui.runtime.swt.tableviewer.behavior.CellEditorValueAdapter;
import org.talend.commons.ui.runtime.swt.tableviewer.behavior.DefaultTableLabelProvider;
import org.talend.commons.ui.runtime.swt.tableviewer.behavior.IColumnColorProvider;
import org.talend.commons.ui.runtime.swt.tableviewer.behavior.ITableCellValueModifiedListener;
import org.talend.commons.ui.runtime.swt.tableviewer.behavior.TableCellValueModifiedEvent;
import org.talend.commons.ui.runtime.swt.tableviewer.celleditor.CellEditorDialogBehavior;
import org.talend.commons.ui.runtime.swt.tableviewer.celleditor.ExtendedTextCellEditor;
import org.talend.commons.ui.runtime.swt.tableviewer.data.ModifiedObjectInfo;
import org.talend.commons.ui.runtime.swt.tableviewer.selection.ILineSelectionListener;
import org.talend.commons.ui.runtime.swt.tableviewer.selection.LineSelectionEvent;
import org.talend.commons.ui.runtime.thread.AsynchronousThreading;
import org.talend.commons.ui.runtime.utils.ControlUtils;
import org.talend.commons.ui.runtime.utils.TableUtils;
import org.talend.commons.ui.runtime.ws.WindowSystem;
import org.talend.commons.ui.swt.colorstyledtext.UnnotifiableColorStyledText;
import org.talend.commons.ui.swt.extended.table.AbstractExtendedTableViewer;
import org.talend.commons.ui.swt.extended.table.ExtendedTableModel;
import org.talend.commons.ui.swt.proposal.ContentProposalAdapterExtended;
import org.talend.commons.ui.swt.proposal.ExtendedTextCellEditorWithProposal;
import org.talend.commons.ui.swt.proposal.ProposalUtils;
import org.talend.commons.ui.swt.tableviewer.IModifiedBeanListener;
import org.talend.commons.ui.swt.tableviewer.ModifiedBeanEvent;
import org.talend.commons.ui.swt.tableviewer.TableViewerCreator;
import org.talend.commons.ui.swt.tableviewer.TableViewerCreatorColumn;
import org.talend.commons.ui.swt.tableviewer.behavior.DefaultCellModifier;
import org.talend.commons.utils.data.bean.IBeanPropertyAccessors;
import org.talend.commons.utils.data.list.IListenableListListener;
import org.talend.commons.utils.data.list.ListenableListEvent;
import org.talend.commons.utils.threading.ExecutionLimiterImproved;
import org.talend.commons.utils.time.TimeMeasure;
import org.talend.core.CorePlugin;
import org.talend.core.GlobalServiceRegister;
import org.talend.core.IService;
import org.talend.core.language.ECodeLanguage;
import org.talend.core.language.LanguageManager;
import org.talend.core.model.metadata.IMetadataColumn;
import org.talend.core.model.metadata.IMetadataTable;
import org.talend.core.model.metadata.MetadataTalendTypeFilter;
import org.talend.core.model.metadata.MetadataToolHelper;
import org.talend.core.model.metadata.types.JavaTypesManager;
import org.talend.core.model.process.IConnection;
import org.talend.core.model.process.Problem;
import org.talend.core.model.properties.ConnectionItem;
import org.talend.core.model.properties.Item;
import org.talend.core.model.repository.ERepositoryObjectType;
import org.talend.core.model.repository.IRepositoryViewObject;
import org.talend.core.model.utils.NodeUtil;
import org.talend.core.runtime.services.IExpressionBuilderDialogService;
import org.talend.core.ui.metadata.editor.MetadataTableEditorView;
import org.talend.core.ui.proposal.TalendProposalProvider;
import org.talend.designer.abstractmap.model.table.IDataMapTable;
import org.talend.designer.abstractmap.model.tableentry.IColumnEntry;
import org.talend.designer.abstractmap.model.tableentry.ITableEntry;
import org.talend.designer.abstractmap.ui.IDataMapTableView;
import org.talend.designer.core.ui.editor.connections.Connection;
import org.talend.designer.core.ui.editor.connections.ConnectionTrace;
import org.talend.designer.core.utils.DesignerUtilities;
import org.talend.designer.mapper.MapperMain;
import org.talend.designer.mapper.external.connection.IOConnection;
import org.talend.designer.mapper.i18n.Messages;
import org.talend.designer.mapper.managers.MapperManager;
import org.talend.designer.mapper.managers.UIManager;
import org.talend.designer.mapper.model.table.AbstractInOutTable;
import org.talend.designer.mapper.model.table.InputTable;
import org.talend.designer.mapper.model.table.OutputTable;
import org.talend.designer.mapper.model.tableentry.AbstractInOutTableEntry;
import org.talend.designer.mapper.model.tableentry.ExpressionFilterEntry;
import org.talend.designer.mapper.model.tableentry.FilterTableEntry;
import org.talend.designer.mapper.model.tableentry.GlobalMapEntry;
import org.talend.designer.mapper.model.tableentry.InputColumnTableEntry;
import org.talend.designer.mapper.model.tableentry.OutputColumnTableEntry;
import org.talend.designer.mapper.model.tableentry.TableEntryLocation;
import org.talend.designer.mapper.model.tableentry.VarTableEntry;
import org.talend.designer.mapper.ui.color.ColorInfo;
import org.talend.designer.mapper.ui.color.ColorProviderMapper;
import org.talend.designer.mapper.ui.dialog.ListStringValueDialog;
import org.talend.designer.mapper.ui.dnd.DragNDrop;
import org.talend.designer.mapper.ui.event.MousePositionAnalyser;
import org.talend.designer.mapper.ui.event.ResizeHelper;
import org.talend.designer.mapper.ui.event.ResizeHelper.RESIZE_MODE;
import org.talend.designer.mapper.ui.font.FontInfo;
import org.talend.designer.mapper.ui.font.FontProviderMapper;
import org.talend.designer.mapper.ui.image.ImageInfo;
import org.talend.designer.mapper.ui.image.ImageProviderMapper;
import org.talend.designer.mapper.ui.proposal.expression.ExpressionProposalProvider;
import org.talend.designer.mapper.ui.tabs.StyledTextHandler;
import org.talend.designer.mapper.ui.visualmap.zone.InputsZone;
import org.talend.designer.mapper.ui.visualmap.zone.Zone;
import org.talend.repository.model.IProxyRepositoryFactory;
import org.talend.repository.model.IProxyRepositoryService;
import org.talend.repository.model.RepositoryNode;
import org.talend.repository.ui.dialog.RepositoryReviewDialog;
/**
* DOC amaumont class global comment. Detailled comment <br/>
*
* $Id$
*
*/
public abstract class DataMapTableView extends Composite implements IDataMapTableView, PropertyChangeListener {
public static final String REPOSITORY = "Repository";
public static final String BUILT_IN = "Built-In";
private final Point realToolbarSize = new Point(0, 0);
private Table tableForEntries;
private final ResizeHelper resizeHelper = new ResizeHelper();
protected MapperManager mapperManager;
protected TableViewerCreator tableViewerCreatorForColumns;
protected IDataMapTable abstractDataMapTable;
protected Composite headerComposite;
protected GridData warnLabelData;
protected Label warningLabel;
protected Label nameLabel;
private ToolItem minimizeButton;
protected ToolItem condensedItem;
protected int heightForRestore;
protected Layout parentLayout;
protected TableViewerCreator tableViewerCreatorForFilters;
protected TableViewerCreator tableViewerCreatorForGlobalMap;
protected TableViewerCreator mapSettingViewerCreator;
protected Table tableForConstraints;
protected Table tableForGlobalMap;
protected Table mapSettingTable;
private boolean executeSelectionEvent = true;
protected ToolBar toolBarActions;
private ExpressionProposalProvider expressionProposalProvider;
protected Point expressionEditorTextSelectionBeforeFocusLost;
protected Text lastExpressionEditorTextWhichLostFocus;
protected Composite centerComposite;
private Text columnExpressionTextEditor;
private Text constraintExpressionTextEditor;
private Text columnNameTextFilter;
private Label filterImageLabel;
private Label expressionImageLabel;
private Cursor currentCursor;
private final ExpressionColorProvider expressionColorProvider;
private Listener showErrorMessageListener;
protected boolean forceExecuteSelectionEvent;
private AbstractExtendedTableViewer<IColumnEntry> extendedTableViewerForColumns;
protected AbstractExtendedTableViewer<FilterTableEntry> extendedTableViewerForFilters;
protected AbstractExtendedTableViewer<GlobalMapEntry> extendedTableViewerForGlobalMap;
protected AbstractExtendedTableViewer<GlobalMapEntry> extendedTableViewerForMapSetting;
private static Image imageKey;
private static Image imageEmpty;
private static int constraintCounter = 0;
protected static final int TIME_BEFORE_NEW_REFRESH_BACKGROUND = 150;
protected static final int OFFSET_HEIGHT_TRIGGER = 15;
protected static final int COLUMN_EXPRESSION_SIZE_WEIGHT = 60;
protected static final int COLUMN_NAME_SIZE_WEIGHT = 40;
protected static final int ADJUST_WIDTH_VALUE = 0;
private static final int HEADER_HEIGHT = 23;
public static final String ID_NAME_COLUMN = "ID_NAME_COLUMN"; //$NON-NLS-1$
public static final String PREVIEW_COLUMN = "PREVIEW_COLUMN"; //$NON-NLS-1$
public static final String ID_OPERATOR = "ID_OPERATOR"; //$NON-NLS-1$
public static final String ID_EXPRESSION_COLUMN = "ID_EXPRESSION_COLUMN"; //$NON-NLS-1$
public static final String MAP_SETTING_COLUMN = "MAP_SETTING_COLUMN"; //$NON-NLS-1$
public static final String MATCH_MODEL_SETTING = "Match Model"; //$NON-NLS-1$
public static final String LOOKUP_MODEL_SETTING = "Lookup Model"; //$NON-NLS-1$
public static final String JOIN_MODEL_SETTING = "Join Model"; //$NON-NLS-1$
public static final String PERSISTENCE_MODEL_SETTING = "Store temp data"; //$NON-NLS-1$
public static final String OUTPUT_REJECT = "Catch output reject"; //$NON-NLS-1$
public static final String LOOK_UP_INNER_JOIN_REJECT = "Catch lookup inner join reject"; //$NON-NLS-1$
public static final String SCHEMA_TYPE = "Schema Type"; //$NON-NLS-1$
public static final String SCHEMA_ID = "Schema Id"; //$NON-NLS-1$
public static final String SCHEMA_SETTING_COLUMN = "Schema Setting Column"; //$NON-NLS-1$
public static final String SCHEMA_ID_SETTING_COLUMN = "Schema ID Setting Column"; //$NON-NLS-1$
public static final String COLUMN_NAME = "Column"; //$NON-NLS-1$
protected GridData tableForConstraintsGridData;
protected GridData tableForSchemaIDGridData;
protected GridData tableForGlobalMapGridData;
protected GridData tableForMapSettingGridData;
private ExpressionProposalProvider expressionProposalProviderForExpressionFilter;
private UnnotifiableColorStyledText expressionFilterText;
private Button openExpressionBuilder; // hywang
// add
// for
// 9225
public static final String DEFAULT_EXPRESSION_FILTER = "<Type your filter expression>"; //$NON-NLS-1$ // DO NOT TRANSLATE IT !
public static final String DEFAULT_POST_MATCHING_EXPRESSION_FILTER = "";
// Messages.getString("DataMapTableView.defaultPostMatchingFilterExpression"); //$NON-NLS-1$
public static final String DEFAULT_OUT_EXPRESSION_FILTER = "";
public static final String DEFAULT_FILTER = "";//$NON-NLS-1$
// Messages.getString("DataMapTableView.defaultOutputFilterExpression"); //$NON-NLS-1$
private static final String EXPRESSION_FILTER_ENTRY = "EXPRESSION_FILTER_ENTRY"; //$NON-NLS-1$
private String previousTextForExpressionFilter;
private ContentProposalAdapterExtended proposalForExpressionFilterText;
private ExecutionLimiterImproved executionLimiterForCheckProblemsExpressionFilter;
private ExecutionLimiterImproved executionLimiterForExpressionFilterSetText = null;
private ContentProposalAdapterExtended expressionProposalStyledText;
private ToolItem activateFilterCheck;
private ToolItem columnNameFilter;
private boolean previousStateCheckFilter;
private TableViewer viewer;
private boolean previousColumnNameFilter;
private IExpressionBuilderDialogController dialog;
private boolean customSized;
protected int changedOptions = 0;
private Color color = null;
protected Color previewColor = null;
private boolean needInitProposals = false;
protected MetadataTalendTypeFilter talendTypeFilter;
/**
* doc
*/
enum CellValueType {
BOOL,
SCHEMA_TYPE,
SCHEMA_ID,
LOOKUP_MODEL,
MATCH_MODEL,
JOIN_MODEL,
PERSISTENCE_MODEL
}
/**
*
* Call loaded() method after instanciate this class.
*
* @param parent
* @param style
* @param abstractDataMapTable
* @param mapperManager
*/
public DataMapTableView(Composite parent, int style, IDataMapTable abstractDataMapTable, MapperManager mapperManager) {
super(parent, style);
this.mapperManager = mapperManager;
this.abstractDataMapTable = abstractDataMapTable;
this.talendTypeFilter = NodeUtil.createMetadataTalendTypeFilter(mapperManager.getAbstractMapComponent());
expressionColorProvider = new ExpressionColorProvider();
color = new Color(Display.getDefault(), 238, 238, 0);
previewColor = new Color(Display.getDefault(), 235, 0, 219);
createComponents();
addListeners();
mapperManager.addTablePair(DataMapTableView.this, abstractDataMapTable);
if (abstractDataMapTable instanceof AbstractInOutTable) {
IOConnection ioConnection = ((AbstractInOutTable) abstractDataMapTable).getConnection();
if (ioConnection != null && ioConnection.getConnecion() != null) {
IConnection connection = ioConnection.getConnecion();
if (connection instanceof Connection) {
ConnectionTrace connectionTrace = ((Connection) connection).getConnectionTrace();
if (connectionTrace != null) {
connectionTrace.addPropertyChangeListener(this);
}
}
}
}
}
private void createComponents() {
final Display display = this.getDisplay();
// final Color listForeground =
// display.getSystemColor(SWT.COLOR_WIDGET_FOREGROUND);
if (WindowSystem.isGTK()) {
Color systemColor = display.getSystemColor(SWT.COLOR_WIDGET_BACKGROUND);
setBackground(new Color(display, systemColor.getRed(), systemColor.getGreen(), systemColor.getBlue()));
setBackgroundMode(SWT.INHERIT_NONE);
} else {
Color listBackground = display.getSystemColor(SWT.COLOR_WIDGET_LIGHT_SHADOW);
this.setBackground(listBackground);
}
GridLayout mainLayout = new GridLayout();
int marginMainLayout = 0;
mainLayout.marginLeft = marginMainLayout;
mainLayout.marginRight = marginMainLayout;
mainLayout.marginTop = marginMainLayout;
mainLayout.marginBottom = marginMainLayout;
mainLayout.marginWidth = marginMainLayout;
mainLayout.marginHeight = marginMainLayout;
int spacingMainLayout = 2;
mainLayout.horizontalSpacing = spacingMainLayout;
mainLayout.verticalSpacing = spacingMainLayout;
setLayout(mainLayout);
headerComposite = new Composite(this, SWT.NONE);
GridData headerGridData = new GridData(GridData.FILL_HORIZONTAL);
headerGridData.heightHint = getHeaderHeight();
headerComposite.setLayoutData(headerGridData);
GridLayout headerLayout = new GridLayout();
int margin = 0;
headerLayout.marginLeft = 3;
headerLayout.marginRight = margin;
headerLayout.marginTop = margin;
headerLayout.marginBottom = margin;
headerLayout.marginWidth = margin;
headerLayout.marginHeight = margin;
int spacing = 2;
headerLayout.horizontalSpacing = spacing;
headerLayout.verticalSpacing = spacing;
headerComposite.setLayout(headerLayout);
warningLabel = new Label(headerComposite, SWT.NONE);
warningLabel.setImage(ImageProvider.getImage(EImage.WARNING_ICON));
warnLabelData = new GridData();
warningLabel.setLayoutData(warnLabelData);
warnLabelData.exclude = true;
nameLabel = new Label(headerComposite, SWT.NONE);
nameLabel.setFont(FontProviderMapper.getFont(FontInfo.FONT_SYSTEM_BOLD));
if (abstractDataMapTable instanceof OutputTable && ((OutputTable) abstractDataMapTable).getIsJoinTableOf() != null) {
nameLabel.setText("Join Table " + abstractDataMapTable.getName() + " linked with "
+ ((OutputTable) abstractDataMapTable).getIsJoinTableOf());
} else {
nameLabel.setText(abstractDataMapTable.getName());
}
nameLabel.setToolTipText(abstractDataMapTable.getName());
GridData dataNameLabel = new GridData(GridData.FILL_HORIZONTAL);
dataNameLabel.minimumWidth = nameLabel.getText().length() * 8;
nameLabel.setLayoutData(dataNameLabel);
// nameLabel.setBackground(nameLabel.getDisplay().getSystemColor(SWT.COLOR_RED));
int rightStyle = toolbarNeedToHaveRightStyle() ? SWT.RIGHT : SWT.NONE;
toolBarActions = new ToolBar(headerComposite, SWT.FLAT | rightStyle | SWT.NONE);
// toolBarActions.setBackground(nameLabel.getDisplay().getSystemColor(SWT.COLOR_BLUE));
if (addToolItems()) {
addToolItemSeparator();
}
minimizeButton = new ToolItem(toolBarActions, SWT.PUSH);
realToolbarSize.x += 45;
Point sizeToolBar = toolBarActions.computeSize(SWT.DEFAULT, SWT.DEFAULT);
// System.out.println(getDataMapTable().getName());
// System.out.println("sizeToolBar:" + sizeToolBar);
GridData gridDataToolbar = new GridData();
// gridData.grabExcessHorizontalSpace = true;
// gridData.horizontalAlignment = SWT.END;
gridDataToolbar.heightHint = sizeToolBar.y;
if (toolbarNeedToHaveRightStyle() && WindowSystem.isWIN32()) {
if (realToolbarSize != null) {
gridDataToolbar.widthHint = realToolbarSize.x;
// System.out.println("realToolbarSize:" + realToolbarSize);
}
// to correct invalid margin when SWT.RIGHT style set in ToolBar
// gridData.widthHint -= 48;
}
if (WindowSystem.isGTK()) {
gridDataToolbar.heightHint = 26;
}
toolBarActions.setLayoutData(gridDataToolbar);
// gridData.widthHint = 50;
headerLayout.numColumns = headerComposite.getChildren().length;
centerComposite = new Composite(this, SWT.NONE);
GridData centerData = new GridData(GridData.FILL_BOTH);
centerComposite.setLayoutData(centerData);
GridLayout centerLayout = new GridLayout(3, false);
int marginCenterLayout = 0;
centerLayout.marginLeft = marginCenterLayout;
centerLayout.marginRight = marginCenterLayout;
centerLayout.marginTop = marginCenterLayout;
centerLayout.marginBottom = marginCenterLayout;
centerLayout.marginWidth = marginCenterLayout;
centerLayout.marginHeight = marginCenterLayout;
int spacingCenterLayout = 2;
centerLayout.horizontalSpacing = spacingCenterLayout;
centerLayout.verticalSpacing = spacingCenterLayout;
centerComposite.setLayout(centerLayout);
createMapSettingTable();
// if (abstractDataMapTable instanceof InputTable || abstractDataMapTable instanceof OutputTable) {
// createSchemaSettingTable();
// createSchemaIDSettingTable();
// }
if (mapperManager.isAdvancedMap() && this instanceof OutputDataMapTableView) {
createExpressionFilter(DEFAULT_OUT_EXPRESSION_FILTER);
createColumnNameFilter();
initExtraTable();
} else {
initExtraTable();
}
createContent();
if (!mapperManager.componentIsReadOnly()) {
new DragNDrop(mapperManager, tableForEntries, true, true);
}
Composite footerComposite = new Composite(this, SWT.NONE);
GridData footerGridData = new GridData(10, 2);
footerComposite.setLayoutData(footerGridData);
if (WindowSystem.isGTK()) {
sizeToolBar = toolBarActions.computeSize(SWT.DEFAULT, SWT.DEFAULT);
gridDataToolbar.widthHint = sizeToolBar.x + 20;
headerComposite.layout();
}
}
/**
* DOC amaumont Comment method "createContent".
*/
protected abstract void createContent();
protected abstract void createMapSettingTable();
protected void initMapSettingColumns(final TableViewerCreator<GlobalMapEntry> tableViewerCreator) {
final Table table = tableViewerCreator.getTable();
TableViewerCreatorColumn column = new TableViewerCreatorColumn(tableViewerCreator);
column.setTitle("Property");
column.setWeight(COLUMN_NAME_SIZE_WEIGHT);
column.setModifiable(true);
column.setBeanPropertyAccessors(new IBeanPropertyAccessors<GlobalMapEntry, Object>() {
public Object get(GlobalMapEntry bean) {
return bean.getName();
}
public void set(GlobalMapEntry bean, Object value) {
// do nothing
}
});
column.setColorProvider(new IColumnColorProvider<GlobalMapEntry>() {
public Color getBackgroundColor(GlobalMapEntry bean) {
if (needColumnBgColor(bean)) {
return color;
}
return null;
}
public Color getForegroundColor(GlobalMapEntry bean) {
// TODO Auto-generated method stub
return null;
}
});
final TableViewerCreatorColumn valueColumn = new TableViewerCreatorColumn(tableViewerCreator);
valueColumn.setTitle("Value");
valueColumn.setId(MAP_SETTING_COLUMN);
valueColumn.setWeight(COLUMN_NAME_SIZE_WEIGHT);
// CellEditorValueAdapter comboValueAdapter = CellEditorValueAdapterFactory.getComboAdapterForComboCellEditor("String"); //$NON-NLS-1$
// cellEditor = new ComboBoxCellEditor();
// cellEditor.create(table);
// CCombo functCombo = (CCombo) cellEditor.getControl();
// functCombo.setEditable(false);
// valueColumn.setCellEditor(cellEditor, comboValueAdapter);
final CustomDialogCellEditor cellEditor = new CustomDialogCellEditor(CellValueType.SCHEMA_ID) {
@Override
protected Object openDialogBox(Control cellEditorWindow) {
Object obj = super.openDialogBox(cellEditorWindow);
if (obj == null) {
return openCustomCellDialog(cellEditorWindow.getShell(), this.getType());
}
return obj;
};
};
cellEditor.create(table);
if (!mapperManager.componentIsReadOnly()) {
valueColumn.setCellEditor(cellEditor);
}
valueColumn.setBeanPropertyAccessors(getMapSettingValueAccess(cellEditor));
valueColumn.setModifiable(true);
valueColumn.setColorProvider(new IColumnColorProvider<GlobalMapEntry>() {
public Color getBackgroundColor(GlobalMapEntry bean) {
if (needColumnBgColor(bean)) {
return color;
}
return null;
}
public Color getForegroundColor(GlobalMapEntry bean) {
// TODO Auto-generated method stub
return null;
}
});
}
/**
* DOC ycbai Comment method "openCustomCellDialog".
*
* @param shell
* @return
*/
protected Object openCustomCellDialog(Shell shell, CellValueType type) {
return null;
}
/**
* DOC ycbai Comment method "getSchemaSettingValueAccess".
*
* @param functComboBox
* @return
*/
protected IBeanPropertyAccessors<GlobalMapEntry, Object> getSchemaSettingValueAccess(final ComboBoxCellEditor functComboBox) {
return new IBeanPropertyAccessors<GlobalMapEntry, Object>() {
public Object get(GlobalMapEntry bean) {
functComboBox.setItems(new String[] { BUILT_IN, REPOSITORY });
IDataMapTable parent = bean.getParent();
AbstractInOutTable table = (AbstractInOutTable) parent;
if (SCHEMA_TYPE.equals(bean.getName())) {
if (bean.getExpression() == null) {
return table.getId() == null ? BUILT_IN : REPOSITORY;
}
return bean.getExpression();
}
return "";
}
public void set(GlobalMapEntry bean, Object value) {
if (value == null) {
return;
}
if (SCHEMA_TYPE.equals(bean.getName())) {
bean.setExpression(String.valueOf(value));
showSchemaIDSetting(REPOSITORY.equals(value));
}
}
};
}
protected IBeanPropertyAccessors<GlobalMapEntry, Object> getMapSettingValueAccess(final CellEditor cellEditor) {
return null;
}
protected boolean needColumnBgColor(GlobalMapEntry bean) {
return false;
}
// only called when open the tmap
protected void initCondensedItemImage() {
}
protected ImageInfo getCondencedItemImage(int i) {
switch (i) {
case 0:
return ImageInfo.CONDENSED_TOOL_ICON;
case 1:
return ImageInfo.CONDENSED_TOOL_ICON1;
case 2:
return ImageInfo.CONDENSED_TOOL_ICON2;
case 3:
return ImageInfo.CONDENSED_TOOL_ICON3;
case 4:
return ImageInfo.CONDENSED_TOOL_ICON4;
case 5:
return ImageInfo.CONDENSED_TOOL_ICON5;
case 6:
return ImageInfo.CONDENSED_TOOL_ICON6;
default:
return null;
}
}
/**
* DOC amaumont Comment method "addToolItemSeparator".
*/
protected void addToolItemSeparator() {
ToolItem separator = new ToolItem(toolBarActions, SWT.SEPARATOR);
separator.setWidth(10);
getRealToolbarSize().x += separator.getWidth();
// separator.setControl(headerComposite);
}
/**
* DOC amaumont Comment method "createTableForColumns".
*/
protected void createTableForColumns() {
this.extendedTableViewerForColumns = new AbstractExtendedTableViewer<IColumnEntry>(
abstractDataMapTable.getTableColumnsEntriesModel(), centerComposite) {
@Override
protected void createColumns(TableViewerCreator<IColumnEntry> tableViewerCreator, Table table) {
initColumnsOfTableColumns(tableViewerCreator);
}
/*
* (non-Javadoc)
*
* @see org.talend.commons.ui.swt.extended.table.AbstractExtendedTableViewer#initTableListeners()
*/
@Override
protected void initTableListeners() {
super.initTableListeners();
}
/*
* (non-Javadoc)
*
* @see
* org.talend.commons.ui.swt.extended.macrotable.AbstractExtendedTableViewer#setTableViewerCreatorOptions
* (org.talend.commons.ui.swt.tableviewer.TableViewerCreator)
*/
@Override
protected void setTableViewerCreatorOptions(final TableViewerCreator<IColumnEntry> newTableViewerCreator) {
super.setTableViewerCreatorOptions(newTableViewerCreator);
newTableViewerCreator.setColumnsResizableByDefault(true);
newTableViewerCreator.setBorderVisible(false);
newTableViewerCreator.setLayoutMode(LAYOUT_MODE.FILL_HORIZONTAL);
newTableViewerCreator.setKeyboardManagementForCellEdition(true);
// tableViewerCreatorForColumns.setUseCustomItemColoring(this.getDataMapTable()
// instanceof
// AbstractInOutTable);
newTableViewerCreator.setFirstColumnMasked(true);
if (getDataMapTable() instanceof AbstractInOutTable) {
if (imageKey == null) {
imageKey = org.talend.commons.ui.runtime.image.ImageProvider.getImage(EImage.KEY_ICON);
}
if (imageEmpty == null) {
imageEmpty = org.talend.commons.ui.runtime.image.ImageProvider.getImage(EImage.EMPTY);
}
}
newTableViewerCreator.setLabelProvider(new DefaultTableLabelProvider(newTableViewerCreator) {
@Override
public Color getBackground(Object element, int columnIndex) {
return getBackgroundCellColor(newTableViewerCreator, element, columnIndex);
}
@Override
public Color getForeground(Object element, int columnIndex) {
return getForegroundCellColor(newTableViewerCreator, element, columnIndex);
}
@Override
public Image getColumnImage(Object element, int columnIndex) {
return getColumnImageExecute(element, columnIndex);
}
/**
* DOC amaumont Comment method "getColumnImageExecute".
*
* @param element
* @param columnIndex
* @return
*/
private Image getColumnImageExecute(Object element, int columnIndex) {
TableViewerCreatorColumnNotModifiable column = newTableViewerCreator.getColumns().get(columnIndex);
if (getDataMapTable() instanceof AbstractInOutTable) {
AbstractInOutTableEntry entry = (AbstractInOutTableEntry) element;
if (column.getId().equals(ID_NAME_COLUMN)) {
if (entry.getMetadataColumn().isKey()) {
return imageKey;
} else {
return imageEmpty;
}
}
}
if (column.getImageProvider() != null) {
return column.getImageProvider().getImage(element);
}
return null;
}
});
}
};
tableViewerCreatorForColumns = this.extendedTableViewerForColumns.getTableViewerCreator();
if (getZone() == Zone.INPUTS || getZone() == Zone.OUTPUTS) {
viewer = tableViewerCreatorForColumns.getTableViewer();
viewer.addFilter(new selectorViewerFilter());
}
this.extendedTableViewerForColumns.setCommandStack(mapperManager.getCommandStack());
tableForEntries = tableViewerCreatorForColumns.getTable();
GridData tableEntriesGridData = new GridData(SWT.FILL, SWT.FILL, true, true);
tableEntriesGridData.grabExcessVerticalSpace = true;
tableEntriesGridData.horizontalSpan = 3; // for 10690
tableEntriesGridData.minimumHeight = tableForEntries.getHeaderHeight() + tableForEntries.getItemHeight();
tableForEntries.setLayoutData(tableEntriesGridData);
tableViewerCreatorForColumns.setCellModifier(new TableCellModifier(tableViewerCreatorForColumns));
addTableForColumnsListeners();
}
/**
* DOC amaumont Comment method "addTableForColumnsListeners".
*/
private void addTableForColumnsListeners() {
tableViewerCreatorForColumns.addCellValueModifiedListener(new ITableCellValueModifiedListener() {
public void cellValueModified(TableCellValueModifiedEvent e) {
unselectAllEntriesIfErrorDetected(e);
}
});
final TableViewer tableViewerForEntries = tableViewerCreatorForColumns.getTableViewer();
tableViewerForEntries.addSelectionChangedListener(new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
int[] selectionIndices = tableViewerForEntries.getTable().getSelectionIndices();
if (selectionIndices.length > 0) {
selectThisDataMapTableView();
onSelectedEntries(event.getSelection(), selectionIndices);
// bug 18414
MetadataTableEditorView metadataTableEditorView = null;
if (getZone() == Zone.INPUTS) {
metadataTableEditorView = mapperManager.getUiManager().getInputMetaEditorView();
} else if (getZone() == Zone.OUTPUTS) {
metadataTableEditorView = mapperManager.getUiManager().getOutputMetaEditorView();
}
if (metadataTableEditorView != null) {
metadataTableEditorView.getTableViewerCreator().refresh();
}
}
}
});
tableForEntries.addListener(SWT.DragDetect, new Listener() {
public void handleEvent(Event event) {
onSelectedEntries(tableViewerForEntries.getSelection(), tableViewerForEntries.getTable().getSelectionIndices());
}
});
tableViewerCreatorForColumns.getSelectionHelper().addAfterSelectionListener(new ILineSelectionListener() {
public void handle(LineSelectionEvent e) {
if (forceExecuteSelectionEvent) {
forceExecuteSelectionEvent = false;
onSelectedEntries(tableViewerForEntries.getSelection(), tableViewerForEntries.getTable()
.getSelectionIndices());
}
}
});
tableForEntries.addListener(SWT.KeyDown, new Listener() {
public void handleEvent(Event event) {
processEnterKeyDown(tableViewerCreatorForColumns, event);
}
});
abstractDataMapTable.getTableColumnsEntriesModel().addModifiedBeanListener(new IModifiedBeanListener<IColumnEntry>() {
public void handleEvent(ModifiedBeanEvent<IColumnEntry> event) {
TableViewerCreator tableViewerCreator = tableViewerCreatorForColumns;
ITableEntry tableEntry = event.bean;
parseExpression(event, tableViewerCreator, tableEntry);
}
});
if (abstractDataMapTable instanceof InputTable) {
InputTable inputTable = (InputTable) abstractDataMapTable;
inputTable.getTableGlobalMapEntriesModel().addAfterOperationListListener(
new IListenableListListener<GlobalMapEntry>() {
public void handleEvent(ListenableListEvent<GlobalMapEntry> event) {
if (DataMapTableView.this.canBeResizedAtPreferedSize()) {
resizeAtExpandedSize();
}
}
});
inputTable.getTableGlobalMapEntriesModel().addModifiedBeanListener(new IModifiedBeanListener<GlobalMapEntry>() {
public void handleEvent(ModifiedBeanEvent<GlobalMapEntry> event) {
TableViewerCreator tableViewerCreator = tableViewerCreatorForGlobalMap;
ITableEntry tableEntry = event.bean;
parseExpression(event, tableViewerCreator, tableEntry);
}
});
}
if (abstractDataMapTable instanceof OutputTable) {
OutputTable outputTable = (OutputTable) abstractDataMapTable;
outputTable.getTableFiltersEntriesModel().addAfterOperationListListener(
new IListenableListListener<FilterTableEntry>() {
public void handleEvent(ListenableListEvent<FilterTableEntry> event) {
if (DataMapTableView.this.canBeResizedAtPreferedSize()) {
resizeAtExpandedSize();
}
}
});
outputTable.getTableFiltersEntriesModel().addModifiedBeanListener(new IModifiedBeanListener<FilterTableEntry>() {
public void handleEvent(ModifiedBeanEvent<FilterTableEntry> event) {
TableViewerCreator tableViewerCreator = tableViewerCreatorForFilters;
ITableEntry tableEntry = event.bean;
parseExpression(event, tableViewerCreator, tableEntry);
}
});
}
// add menu listener
tableForEntries.addMouseListener(new MouseAdapter() {
@Override
public void mouseDown(MouseEvent e) {
if (e.button == 3 && getZone() == Zone.OUTPUTS) {
Menu mainMenu = new Menu(tableForEntries);
tableForEntries.setMenu(mainMenu);
// menu:apply routine
MenuItem applyRoutineItem = new MenuItem(mainMenu, SWT.PUSH);
applyRoutineItem.setText(Messages.getString("DataMapTableView.menu.applyRoutine"));
// Add menu listeners
final IService service = GlobalServiceRegister.getDefault().getService(IExpressionBuilderDialogService.class);
applyRoutineItem.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event event) {
IExpressionBuilderDialogController dialogForTable = ((IExpressionBuilderDialogService) service)
.getExpressionBuilderInstance(DataMapTableView.this.getCenterComposite(), null,
mapperManager.getAbstractMapComponent(), true);
if (dialogForTable instanceof TrayDialog) {
TrayDialog parentDialog = (TrayDialog) dialogForTable;
dialogForTable.setDefaultExpression(expressionFilterText.getText());
if (Window.OK == parentDialog.open()) {
String expressionForTable = dialogForTable.getExpressionForTable();
TableItem[] selectedTableItems = tableForEntries.getSelection();
for (TableItem tableItem : selectedTableItems) {
ITableEntry currentModifiedEntry = (ITableEntry) tableItem.getData();
String currentExpr = currentModifiedEntry.getExpression();
if (StringUtils.isNotEmpty(expressionForTable) && !expressionForTable.equals(currentExpr)) {
String replacedExpression = expressionForTable;
if (!StringUtils.isEmpty(currentExpr)) {
replacedExpression = expressionForTable.replace("${0}", currentExpr);//$NON-NLS-1$
}
mapperManager.changeEntryExpression(currentModifiedEntry, replacedExpression);
StyledTextHandler textTarget = mapperManager.getUiManager().getTabFolderEditors()
.getStyledTextHandler();
textTarget.setCurrentEntry(currentModifiedEntry);
textTarget.setTextWithoutNotifyListeners(replacedExpression);
mapperManager.getUiManager().parseNewExpression(replacedExpression,
currentModifiedEntry, false);
}
}
}
}
}
});
}
}
});
}
/**
* DOC amaumont Comment method "initShowMessageErrorListener".
*
* @param table
*/
protected void initShowMessageErrorListener(final Table table) {
showErrorMessageListener = new Listener() {
public void handleEvent(Event event) {
switch (event.type) {
case SWT.MouseMove:
String defaultToolTip = null;
if (WindowSystem.isGTK() && table.getToolTipText() != null) {
defaultToolTip = " "; //$NON-NLS-1$
}
Point cursorPositionFromTableOrigin = TableUtils.getCursorPositionFromTableOrigin(table, event);
TableColumn tableColumn = TableUtils.getTableColumn(table, cursorPositionFromTableOrigin);
if (tableColumn == null) {
setTableToolTipText(table, null, null, defaultToolTip);
return;
}
TableItem tableItem = TableUtils.getTableItem(table, cursorPositionFromTableOrigin);
if (tableItem == null) {
setTableToolTipText(table, tableColumn, null, defaultToolTip);
return;
}
ITableEntry tableEntry = (ITableEntry) tableItem.getData();
String toolTip = null;
if (tableEntry.getProblems() != null) {
List<Problem> problems = tableEntry.getProblems();
toolTip = createErrorContentForTooltip(problems);
}
if (WindowSystem.isGTK() && toolTip == null && table.getToolTipText() != null) {
toolTip = defaultToolTip;
}
// System.out.println("toolTip="+toolTip);
// System.out.println("table.getToolTipText()="+table.getToolTipText());
setTableToolTipText(table, tableColumn, tableEntry, toolTip);
break;
default:
}
}
/**
* DOC amaumont Comment method "setTableToolTipText".
*
* @param table
* @param tableColumn
* @param text
*/
private void setTableToolTipText(final Table table, TableColumn tableColumn, ITableEntry tableEntry, String text) {
table.setToolTipText(text);
}
};
table.addListener(SWT.MouseMove, showErrorMessageListener);
}
/**
* DOC amaumont Comment method "addEntriesActionsComponents".
*
* @return true if one or more ToolItem has been added
*/
protected abstract boolean addToolItems();
/**
* DOC amaumont Comment method "initTableConstraints".
*/
protected abstract void initExtraTable();
/**
* DOC amaumont Comment method "addListeners".
*/
protected void addListeners() {
final UIManager uiManager = mapperManager.getUiManager();
MouseTrackListener mouseTracker = new MouseTrackListener() {
public void mouseEnter(MouseEvent e) {
}
public void mouseExit(MouseEvent e) {
setDefaultCursor();
resizeHelper.stopDrag();
}
public void mouseHover(MouseEvent e) {
}
};
this.addMouseTrackListener(mouseTracker);
SelectionListener scrollListener = new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent event) {
uiManager.refreshBackground(true, false);
}
};
tableForEntries.getVerticalBar().addSelectionListener(scrollListener);
// /////////////////////////////////////////////////////////////////
addManualTableResizeListeners(uiManager);
// /////////////////////////////////////////////////////////////////
// /////////////////////////////////////////////////////////////////
Listener onSelectDataMapTableViewListener = new Listener() {
public void handleEvent(Event event) {
switch (event.type) {
case SWT.MouseDown:
onSelectDataMapTableView();
break;
default:
}
}
};
this.addListener(SWT.MouseDown, onSelectDataMapTableViewListener);
headerComposite.addListener(SWT.MouseDown, onSelectDataMapTableViewListener);
nameLabel.addListener(SWT.MouseDown, onSelectDataMapTableViewListener);
// /////////////////////////////////////////////////////////////////
// /////////////////////////////////////////////////////////////////
minimizeButton.addSelectionListener(new SelectionListener() {
public void widgetDefaultSelected(SelectionEvent e) {
// TODO Auto-generated method stub
}
public void widgetSelected(SelectionEvent e) {
minimizeTable(!abstractDataMapTable.isMinimized());
}
});
// /////////////////////////////////////////////////////////////////
initShowMessageErrorListener(tableForEntries);
this.addDisposeListener(new DisposeListener() {
public void widgetDisposed(DisposeEvent e) {
removeListenerForTrace();
if (color != null) {
color.dispose();
color = null;
}
if (previewColor != null) {
previewColor.dispose();
previewColor = null;
}
}
});
}
private void removeListenerForTrace() {
if (abstractDataMapTable instanceof AbstractInOutTable) {
IOConnection ioConnection = ((AbstractInOutTable) abstractDataMapTable).getConnection();
if (ioConnection != null && ioConnection.getConnecion() != null) {
IConnection connection = ioConnection.getConnecion();
if (connection instanceof Connection) {
ConnectionTrace connectionTrace = ((Connection) connection).getConnectionTrace();
if (connectionTrace != null) {
connectionTrace.removePropertyChangeListener(this);
}
}
}
}
}
/**
* DOC amaumont Comment method "addManualTableResizeListeners".
*
* @param uiManager
*/
private void addManualTableResizeListeners(final UIManager uiManager) {
this.addDisposeListener(new DisposeListener() {
public void widgetDisposed(DisposeEvent e) {
if (currentCursor != null) {
currentCursor.dispose();
}
}
});
Listener tableResizerListener = new Listener() {
public void handleEvent(Event event) {
MousePositionAnalyser mpa = new MousePositionAnalyser(DataMapTableView.this);
Point eventPoint = new Point(event.x, event.y);
boolean leftMouseButton = (event.stateMask & SWT.BUTTON1) != 0 || event.button == 1;
switch (event.type) {
case SWT.MouseMove:
if (resizeHelper.isDragging()) {
Point newPoint = convertToParentOrigin(DataMapTableView.this, eventPoint);
Point dragPoint = resizeHelper.getLastDragPoint();
Point diff = new Point(newPoint.x - dragPoint.x, newPoint.y - dragPoint.y);
if (mpa.isOnLeftBorder(eventPoint)) {
diff.x *= -1;
}
Rectangle rect = DataMapTableView.this.getClientArea();
rect.width += 2 * DataMapTableView.this.getBorderWidth();
rect.height += 2 * DataMapTableView.this.getBorderWidth();
RESIZE_MODE currentMode = resizeHelper.getCurrentMode();
int newWidth = (currentMode == RESIZE_MODE.HORIZONTAL || currentMode == RESIZE_MODE.BOTH) ? rect.width
+ diff.x * 2 : rect.width;
int newHeight = (currentMode == RESIZE_MODE.VERTICAL || currentMode == RESIZE_MODE.BOTH) ? rect.height
+ diff.y : rect.height;
if (newHeight < getMinimumHeight() + OFFSET_HEIGHT_TRIGGER && diff.y < 0) {
changeMinimizeState(true);
newHeight = getMinimumHeight();
} else if (newHeight > getMinimumHeight() + OFFSET_HEIGHT_TRIGGER && diff.y > 0) {
changeMinimizeState(false);
}
changeSize(new Point(newWidth, newHeight), false, true);
resizeHelper.setLastDragPoint(newPoint);
customSized = true;
} else if (!resizeHelper.isDragging()) {
Cursor cursor = null;
if (mpa.isOnLeftBottomCorner(eventPoint)) {
// cursor = new
// Cursor(dataMapTableView.getDisplay(),
// org.eclipse.swt.SWT.CURSOR_SIZESW);
// resizeHelper.setCurrentMode(RESIZE_MODE.BOTH);
} else if (mpa.isOnRightBottomCorner(eventPoint)) {
// cursor = new
// Cursor(dataMapTableView.getDisplay(),
// org.eclipse.swt.SWT.CURSOR_SIZESE);
// resizeHelper.setCurrentMode(RESIZE_MODE.BOTH);
} else if (mpa.isOnLeftBorder(eventPoint)) {
// cursor = new
// Cursor(dataMapTableView.getDisplay(),
// org.eclipse.swt.SWT.CURSOR_SIZEE);
// resizeHelper.setCurrentMode(RESIZE_MODE.HORIZONTAL);
} else if (mpa.isOnRightBorder(eventPoint)) {
// cursor = new
// Cursor(dataMapTableView.getDisplay(),
// org.eclipse.swt.SWT.CURSOR_SIZEW);
// resizeHelper.setCurrentMode(RESIZE_MODE.HORIZONTAL);
} else if (mpa.isOnBottomBorder(eventPoint)) {
cursor = new Cursor(DataMapTableView.this.getDisplay(), org.eclipse.swt.SWT.CURSOR_SIZES);
resizeHelper.setCurrentMode(RESIZE_MODE.VERTICAL);
}
if (cursor != null) {
DataMapTableView.this.setCursor(cursor);
} else {
setDefaultCursor();
resizeHelper.setCurrentMode(RESIZE_MODE.NONE);
}
}
break;
case SWT.MouseDown:
if (leftMouseButton) {
if (mpa.isOnLeftBorder(eventPoint) || mpa.isOnRightBorder(eventPoint) || mpa.isOnBottomBorder(eventPoint)) {
resizeHelper.startDrag(convertToParentOrigin(DataMapTableView.this, new Point(event.x, event.y)));
} else {
setDefaultCursor();
}
parentLayout = DataMapTableView.this.getParent().getLayout();
DataMapTableView.this.getParent().setLayout(null);
}
break;
case SWT.MouseUp:
if (leftMouseButton) {
resizeHelper.stopDrag();
// gridData = (GridData)
// dataMapTableView.getLayoutData();
// gridData.exclude = false;
DataMapTableView.this.getParent().setLayout(parentLayout);
DataMapTableView.this.getParent().layout();
uiManager.resizeTablesZoneViewAtComputedSize(getZone());
uiManager.refreshBackground(true, false);
}
break;
case SWT.MouseExit:
setDefaultCursor();
break;
default:
}
}
};
this.addListener(SWT.MouseMove, tableResizerListener);
this.addListener(SWT.MouseDown, tableResizerListener);
this.addListener(SWT.MouseUp, tableResizerListener);
}
/**
* DOC amaumont Comment method "showTableConstraints".
*/
protected void showTableConstraints(boolean visible) {
if (visible) {
tableForConstraintsGridData.exclude = false;
tableForConstraints.setVisible(true);
if (WindowSystem.isGTK()) {
updateGridDataHeightForTableConstraints();
}
} else {
tableForConstraintsGridData.exclude = true;
tableForConstraints.setVisible(false);
}
tableViewerCreatorForFilters.getTableViewer().refresh();
resizeAtExpandedSize();
}
/**
* DOC ycbai Comment method "enableDiaplayViewer".
*
* @param enable
*/
public void enableDiaplayViewer(boolean isRepository) {
MetadataTableEditorView metadataEditorView = mapperManager.getUiManager().getMetadataEditorView(getZone());
if (mapperManager.componentIsReadOnly()) {
metadataEditorView.setReadOnly(true);
} else {
metadataEditorView.setReadOnly(isRepository);
}
}
/**
* DOC ycbai Comment method "showSchemaIDSetting".
*
* @param visible
*/
public void showSchemaIDSetting(boolean visible) {
ExtendedTableModel<GlobalMapEntry> tableMapSettingEntriesModel = ((AbstractInOutTable) abstractDataMapTable)
.getTableMapSettingEntriesModel();
if (tableMapSettingEntriesModel != null && visible) {
tableMapSettingEntriesModel.add(new GlobalMapEntry(abstractDataMapTable, SCHEMA_ID, null));
} else {
GlobalMapEntry schemaIDMapEntry = getGlobalMapEntryByNameFromList(tableMapSettingEntriesModel.getBeansList(),
SCHEMA_ID);
if (schemaIDMapEntry != null) {
IDataMapTable parent = schemaIDMapEntry.getParent();
AbstractInOutTable table = (AbstractInOutTable) parent;
table.setId(null);
tableMapSettingEntriesModel.remove(schemaIDMapEntry);
refreshCondensedImage(table, schemaIDMapEntry.getName());
}
}
mapSettingViewerCreator.layout();
mapSettingViewerCreator.getTableViewer().refresh();
}
/**
* DOC ycbai Comment method "getGlobalMapEntryByNameFromList".
*
* @param list
* @param name
* @return
*/
private GlobalMapEntry getGlobalMapEntryByNameFromList(List<GlobalMapEntry> list, String name) {
if (list == null || name == null) {
return null;
}
for (GlobalMapEntry mapEntry : list) {
if (name.equals(mapEntry.getName())) {
return mapEntry;
}
}
return null;
}
protected void showTableMapSetting(boolean visible) {
if (visible) {
tableForMapSettingGridData.exclude = false;
mapSettingTable.setVisible(true);
if (WindowSystem.isGTK()) {
mapSettingViewerCreator.layout();
}
mapSettingViewerCreator.getTableViewer().setSelection(null);
} else {
tableForMapSettingGridData.exclude = true;
mapSettingTable.setVisible(false);
}
mapSettingViewerCreator.getTableViewer().refresh();
resizeAtExpandedSize();
}
/**
* DOC amaumont Comment method "showTableConstraints".
*/
public void showTableGlobalMap(boolean visible) {
if (visible) {
tableForGlobalMapGridData.exclude = false;
tableForGlobalMap.setVisible(true);
if (WindowSystem.isGTK()) {
updateGridDataHeightForTableGlobalMap();
tableViewerCreatorForGlobalMap.refreshTableEditorControls();
}
InputTable inputTable = (InputTable) getDataMapTable();
ExtendedTableModel<GlobalMapEntry> tableGlobalMapEntriesModel = inputTable.getTableGlobalMapEntriesModel();
if (tableGlobalMapEntriesModel != null) {
List<GlobalMapEntry> beansList = tableGlobalMapEntriesModel.getBeansList();
for (GlobalMapEntry globalMapEntry : beansList) {
mapperManager.getUiManager().parseExpression(globalMapEntry.getExpression(), globalMapEntry, false, false,
false);
}
}
} else {
tableForGlobalMapGridData.exclude = true;
tableForGlobalMap.setVisible(false);
InputTable inputTable = (InputTable) getDataMapTable();
ExtendedTableModel<GlobalMapEntry> tableGlobalMapEntriesModel = inputTable.getTableGlobalMapEntriesModel();
if (tableGlobalMapEntriesModel != null) {
List<GlobalMapEntry> beansList = tableGlobalMapEntriesModel.getBeansList();
for (GlobalMapEntry globalMapEntry : beansList) {
mapperManager.removeLinksOf(globalMapEntry);
}
}
}
tableViewerCreatorForGlobalMap.getTableViewer().refresh();
resizeAtExpandedSize();
}
/**
* DOC amaumont Comment method "onSelectDataMapTableView".
*/
protected void onSelectDataMapTableView() {
mapperManager.getUiManager().selectDataMapTableView(this, true, true);
}
/**
* DOC amaumont Comment method "initClumns".
*/
public abstract void initColumnsOfTableColumns(TableViewerCreator tableViewerCreator);
public TableViewerCreator getTableViewerCreatorForColumns() {
return this.tableViewerCreatorForColumns;
}
public TableViewerCreator getTableViewerCreatorForFilters() {
return this.tableViewerCreatorForFilters;
}
public TableViewerCreator getTableViewerCreatorForGlobalMap() {
return this.tableViewerCreatorForGlobalMap;
}
public Point convertToParentOrigin(Composite child, Point point) {
Rectangle bounds = child.getBounds();
return new Point(bounds.x + point.x, bounds.y + point.y);
}
private void setDefaultCursor() {
Cursor cursor = new Cursor(DataMapTableView.this.getDisplay(), 0);
DataMapTableView.this.setCursor(cursor);
}
@Override
public void dispose() {
super.dispose();
}
public MapperManager getMapperManager() {
return this.mapperManager;
}
public abstract Zone getZone();
/**
* DOC amaumont Comment method "resizeWithPreferredSize".
*/
public void resizeAtExpandedSize() {
changeSize(getPreferredSize(false, true, false), true, true);
}
/**
*
* Change size of the DataMapTableView.
*
* @param newWidth
* @param newHeight
* @param refreshNow refresh background with links if true
* @param recalculateParentSize
*/
public void changeSize(Point newSize, boolean refreshNow, boolean recalculateParentSize) {
if (newSize.y < getMinimumHeight()) {
newSize.y = getMinimumHeight();
}
FormData formData = (FormData) DataMapTableView.this.getLayoutData();
formData.width = newSize.x;
formData.height = newSize.y;
DataMapTableView.this.setSize(newSize);
UIManager uiManager = mapperManager.getUiManager();
if (recalculateParentSize) {
uiManager.resizeTablesZoneViewAtComputedSize(getZone());
}
if (refreshNow) {
uiManager.refreshBackground(true, false);
} else {
uiManager.refreshBackground(true, TIME_BEFORE_NEW_REFRESH_BACKGROUND, true);
}
// dataMapTableView.redraw();
// dataMapTableView.layout(true, true);
}
public void onSelectedEntries(ISelection selection, int[] selectionIndices) {
UIManager uiManager = mapperManager.getUiManager();
List<ITableEntry> selectionEntries = uiManager.extractSelectedTableEntries(selection);
if (executeSelectionEvent) {
uiManager.selectLinks(DataMapTableView.this, selectionEntries, false, false);
uiManager.selectLinkedMetadataEditorEntries(this, selectionIndices);
}
if (selectionIndices.length == 1 && mapperManager.componentIsReadOnly()) {
ITableEntry tableEntry = selectionEntries.get(0);
StyledText styledText = mapperManager.getUiManager().getTabFolderEditors().getStyledTextHandler().getStyledText();
styledText.setEnabled(true);
styledText.setEditable(false);
styledText.setText(tableEntry.getExpression() == null ? "" : tableEntry.getExpression()); //$NON-NLS-1$
}
}
public IDataMapTable getDataMapTable() {
return this.abstractDataMapTable;
}
/**
* DOC amaumont Comment method "setTableSelection".
*
* @param selectionIndices
*/
public void setTableSelection(int[] selectionIndices) {
this.executeSelectionEvent = false;
this.tableViewerCreatorForColumns.getSelectionHelper().setSelection(selectionIndices);
this.executeSelectionEvent = true;
}
protected void createFiltersToolItems() {
boolean isErrorReject = false;
if (!(getDataMapTable() instanceof OutputTable)) {
return;
}
isErrorReject = ((OutputTable) getDataMapTable()).isErrorRejectTable();
condensedItem = new ToolItem(toolBarActions, SWT.CHECK);
condensedItem.setEnabled(!isErrorReject);
condensedItem.setSelection(((OutputTable) abstractDataMapTable).isActivateCondensedTool());
condensedItem.setToolTipText("tMap settings");
initCondensedItemImage();
condensedItem.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
((OutputTable) abstractDataMapTable).setActivateCondensedTool(condensedItem.getSelection());
showTableMapSetting(condensedItem.getSelection());
}
});
if (mapperManager.isAdvancedMap()) {
createActivateFilterCheck();
createColumnNameFilterCheck();
} else {
ToolItem addFilterButton = new ToolItem(toolBarActions, SWT.PUSH);
addFilterButton.setEnabled(!mapperManager.componentIsReadOnly() && !isErrorReject);
addFilterButton.setToolTipText(Messages.getString("DataMapTableView.buttonTooltip.addFilterRow")); //$NON-NLS-1$
addFilterButton.setImage(ImageProviderMapper.getImage(ImageInfo.ADD_FILTER_ICON));
// /////////////////////////////////////////////////////////////////
if (addFilterButton != null) {
addFilterButton.addSelectionListener(new SelectionListener() {
public void widgetDefaultSelected(SelectionEvent e) {
}
public void widgetSelected(SelectionEvent e) {
Table tableConstraints = tableViewerCreatorForFilters.getTable();
int index = tableConstraints.getItemCount();
int[] selection = tableViewerCreatorForFilters.getTable().getSelectionIndices();
if (selection.length > 0) {
index = selection[selection.length - 1] + 1;
}
mapperManager.addNewFilterEntry(DataMapTableView.this, "newFilter" + ++constraintCounter, index); //$NON-NLS-1$
updateGridDataHeightForTableConstraints();
DataMapTableView.this.changeSize(DataMapTableView.this.getPreferredSize(false, true, true), true, true);
tableViewerCreatorForFilters.getTableViewer().refresh();
mapperManager.getUiManager().refreshBackground(true, false);
showTableConstraints(true);
changeMinimizeState(false);
tableViewerCreatorForFilters.layout();
}
});
}
// /////////////////////////////////////////////////////////////////
}
}
/**
* DOC amaumont Comment method "createActivateFilterCheck".
*/
protected void createActivateFilterCheck() {
AbstractInOutTable table = (AbstractInOutTable) getDataMapTable();
boolean isErrorReject = false;
if (getDataMapTable() instanceof OutputTable) {
isErrorReject = getMapperManager().ERROR_REJECT.equals(getDataMapTable().getName());
}
activateFilterCheck = new ToolItem(toolBarActions, SWT.CHECK);
activateFilterCheck.setEnabled(!mapperManager.componentIsReadOnly() && !isErrorReject);
previousStateCheckFilter = table.isActivateExpressionFilter();
activateFilterCheck.setSelection(table.isActivateExpressionFilter());
activateFilterCheck.setToolTipText(Messages.getString("DataMapTableView.buttonTooltip.ExpressionFilter")); //$NON-NLS-1$
activateFilterCheck.setImage(ImageProviderMapper.getImage(ImageInfo.ACTIVATE_FILTER_ICON));
// /////////////////////////////////////////////////////////////////
if (activateFilterCheck != null) {
activateFilterCheck.addSelectionListener(new SelectionListener() {
public void widgetDefaultSelected(SelectionEvent e) {
}
public void widgetSelected(SelectionEvent e) {
updateExepressionFilterTextAndLayout(true);
previousStateCheckFilter = activateFilterCheck.getSelection();
}
});
}
// /////////////////////////////////////////////////////////////////
}
protected void createColumnNameFilterCheck() {
AbstractInOutTable table = (AbstractInOutTable) getDataMapTable();
boolean isErrorReject = false;
if (getDataMapTable() instanceof OutputTable) {
isErrorReject = getMapperManager().ERROR_REJECT.equals(getDataMapTable().getName());
}
//
columnNameFilter = new ToolItem(toolBarActions, SWT.CHECK);
columnNameFilter.setEnabled(!mapperManager.componentIsReadOnly() && !isErrorReject);
previousColumnNameFilter = table.isActivateColumnNameFilter();
columnNameFilter.setSelection(table.isActivateColumnNameFilter());
columnNameFilter.setToolTipText(Messages.getString("DataMapTableView.buttonTooltip.ColumnNameFilter")); //$NON-NLS-1$
columnNameFilter.setImage(ImageProviderMapper.getImage(ImageInfo.TMAP_FILTER_ICON));
if (columnNameFilter != null) {
columnNameFilter.addSelectionListener(new SelectionListener() {
public void widgetDefaultSelected(SelectionEvent e) {
}
public void widgetSelected(SelectionEvent e) {
updateColumnNameFilterTextAndLayout(true);
previousColumnNameFilter = columnNameFilter.getSelection();
}
});
}
}
protected void createToolItems() {
}
public void minimizeTable(boolean minimize) {
Point size = DataMapTableView.this.getSize();
if (minimize) {
// System.out.println("store height before minimize"+size.y);
this.heightForRestore = size.y - 4;
changeSize(new Point(size.x, getHeaderHeight()), true, true);
changeMinimizeState(true);
} else {
if (heightForRestore != getHeaderHeight() && heightForRestore > 0) {
size.y = heightForRestore;
} else {
size = DataMapTableView.this.getPreferredSize(false, true, false);
}
changeSize(size, true, true);
changeMinimizeState(false);
}
}
public void changeMinimizeState(boolean newStateIsMinimized) {
if (newStateIsMinimized) {
abstractDataMapTable.setMinimized(true);
minimizeButton.setSelection(true);
minimizeButton.setImage(ImageProviderMapper.getImage(ImageInfo.RESTORE_ICON));
minimizeButton.setToolTipText(Messages.getString("DataMapTableView.buttonTooltip.restore")); //$NON-NLS-1$
} else {
abstractDataMapTable.setMinimized(false);
minimizeButton.setSelection(false);
minimizeButton.setImage(ImageProviderMapper.getImage(ImageInfo.MINIMIZE_ICON));
minimizeButton.setToolTipText(Messages.getString("DataMapTableView.buttonTooltip.minimize")); //$NON-NLS-1$
}
}
/**
*
* Return current size of DataMapTableView.
*
* @return
*/
public Point getPreferredSize() {
return getPreferredSize(false, false, false);
}
public boolean canBeResizedAtPreferedSize() {
return !customSized;
}
/**
*
* DOC amaumont Comment method "getPreferredSize".
*
* @param newTableEntryWillBeAdded
* @param expandedSize
* @param newConstraintEntryWillBeAdded
* @return
*/
public Point getPreferredSize(boolean newTableEntryWillBeAdded, boolean expandedSize, boolean newConstraintEntryWillBeAdded) {
int heightOffset = 0;
int tableEntryItemHeight = tableViewerCreatorForColumns.getTable().getItemHeight();
// heightOffset += newTableEntryWillBeAdded ? tableEntryItemHeight : 0;
heightOffset += newConstraintEntryWillBeAdded ? tableViewerCreatorForFilters.getTable().getItemHeight() : 0;
int newHeight = this.computeSize(SWT.DEFAULT, SWT.DEFAULT).y - tableEntryItemHeight + heightOffset;
if (WindowSystem.isGTK()) {
newHeight += tableEntryItemHeight;
}
if (tableViewerCreatorForColumns.getInputList().size() == 0) {
newHeight += tableEntryItemHeight;
} else {
newHeight += 5;
}
if (abstractDataMapTable.isMinimized() && !expandedSize) {
newHeight = getMinimumHeight();
}
return new Point(this.getSize().x, newHeight);
}
private int getMinimumHeight() {
if (WindowSystem.isGTK()) {
if (hasDropDownToolBarItem()) {
return 38;
} else {
return 28;
}
} else {
return 24;
}
}
public void registerStyledExpressionEditor(final StyledTextHandler styledTextHandler) {
if (columnExpressionTextEditor != null) {
attachCellExpressionToStyledTextEditor(tableViewerCreatorForColumns, columnExpressionTextEditor, styledTextHandler);
}
if (constraintExpressionTextEditor != null) {
attachCellExpressionToStyledTextEditor(tableViewerCreatorForFilters, constraintExpressionTextEditor,
styledTextHandler);
}
}
/**
* DOC amaumont Comment method "attachCellExpressionToStyledTextEditor".
*
* @param tableViewerCreator TODO
* @param styledTextHandler
* @param expressionEditorText2
*/
protected void attachCellExpressionToStyledTextEditor(final TableViewerCreator tableViewerCreator,
final Text expressionTextEditor, final StyledTextHandler styledTextHandler) {
expressionTextEditor.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
ITableEntry currentModifiedEntry = (ITableEntry) tableViewerCreator.getModifiedObjectInfo()
.getCurrentModifiedBean();
styledTextHandler.setCurrentEntry(currentModifiedEntry);
Text text = (Text) e.widget;
// if (Math.abs(text.getText().length() - styledTextHandler.getStyledText().getText().length()) > 1) {
styledTextHandler.setTextWithoutNotifyListeners(text.getText());
// highlightLineAndSetSelectionOfStyledText(expressionTextEditor);
// }
}
});
expressionTextEditor.addKeyListener(new TextCellEditorToMapperStyledTextKeyListener(expressionTextEditor,
styledTextHandler));
expressionTextEditor.addMouseListener(new MouseListener() {
public void mouseDoubleClick(MouseEvent e) {
highlightLineAndSetSelectionOfStyledText(expressionTextEditor);
}
public void mouseDown(MouseEvent e) {
highlightLineAndSetSelectionOfStyledText(expressionTextEditor);
}
public void mouseUp(MouseEvent e) {
}
});
}
private void highlightLineAndSetSelectionOfStyledText(final Text expressionTextEditor) {
highlightLineAndSetSelectionOfStyledTextFromTextControl(expressionTextEditor);
}
/**
* DOC amaumont Comment method "highlightLineAndSetSelectionOfStyledText".
*
* @param expressionTextEditor
*/
protected void highlightLineAndSetSelectionOfStyledTextFromTextControl(final Control textWidget) {
final StyledTextHandler styledTextHandler = mapperManager.getUiManager().getTabFolderEditors().getStyledTextHandler();
Runnable runnable = new Runnable() {
public void run() {
StyledText styledText = styledTextHandler.getStyledText();
if (styledText.isDisposed()) {
return;
}
String text = ControlUtils.getText(textWidget);
Point selection = ControlUtils.getSelection(textWidget);
String lineDelimiter = ControlUtils.getLineDelimiter(textWidget);
if (selection.x - 1 > 0) {
while (lineDelimiter.equals(text.charAt(selection.x - 1))) {
selection.x++;
}
}
if (selection.y - 1 > 0) {
while (lineDelimiter.equals(text.charAt(selection.y - 1))) {
selection.y++;
}
}
int length = styledText.getText().length();
if (selection.x < 0) {
selection.x = 0;
}
if (selection.x > length) {
selection.x = length;
}
if (selection.y < 0) {
selection.y = 0;
}
if (selection.y > length) {
selection.y = length;
}
styledText.setSelection(selection);
styledTextHandler.highlightLineOfCursorPosition(selection);
}
};
new AsynchronousThreading(50, true, DataMapTableView.this.getDisplay(), runnable).start();
}
/**
*
* Init proposals of Text control, and StyledText in tab "Expression editor".
*
* @param textControl
* @param zones
* @param tableViewerCreator
* @param currentModifiedEntry
*/
protected void initExpressionProposals(final ExtendedTextCellEditorWithProposal cellEditor, Zone[] zones,
final TableViewerCreator tableViewerCreator, ITableEntry currentModifiedEntry) {
if (this.expressionProposalProvider == null) {
this.expressionProposalProvider = createExpressionProposalProvider();
}
this.expressionProposalProvider.init(abstractDataMapTable, zones, currentModifiedEntry);
cellEditor.setContentProposalProvider(this.expressionProposalProvider);
cellEditor.setData(expressionProposalProvider.getVariables());
StringBuffer id = new StringBuffer();
id.append(mapperManager.getAbstractMapComponent().getUniqueName() + "=>"); //$NON-NLS-1$
// TDI-3065:Expression Builder for Var in tMap does not show Var name correctly
// TableItem[] items = tableViewerCreator.getTable().getSelection();
// if (items.length == 1) {
// Object item = items[0].getData();
// if (item instanceof AbstractInOutTableEntry) {
// AbstractInOutTableEntry entry = (AbstractInOutTableEntry) item;
// id.append(entry.getParent().getName() + "=>");//$NON-NLS-1$
// id.append(entry.getMetadataColumn().getLabel());
// } else if (item instanceof VarTableEntry) {
// VarTableEntry entry = (VarTableEntry) item;
// id.append(entry.getParent().getName() + "=>");//$NON-NLS-1$
// id.append(entry.getName());
// }
// }
cellEditor.setOwnerId(id.toString());
if (!needInitProposals) {
StyledTextHandler styledTextHandler = mapperManager.getUiManager().getTabFolderEditors().getStyledTextHandler();
styledTextHandler.getStyledText().setEnabled(true);
ContentProposalAdapterExtended expressionProposalStyledText = styledTextHandler.getContentProposalAdapter();
expressionProposalStyledText.setContentProposalProvider(this.expressionProposalProvider);
}
}
/**
* DOC amaumont Comment method "initExpressionProposalProvider".
*/
protected ExpressionProposalProvider createExpressionProposalProvider() {
IContentProposalProvider[] contentProposalProviders = new IContentProposalProvider[0];
if (!MapperMain.isStandAloneMode()) {
contentProposalProviders = new IContentProposalProvider[] { new TalendProposalProvider(mapperManager
.getAbstractMapComponent().getProcess()) };
}
return new ExpressionProposalProvider(mapperManager, contentProposalProviders);
}
protected ExtendedTextCellEditor createExpressionCellEditor(final TableViewerCreator tableViewerCreator,
TableViewerCreatorColumn column, final Zone[] zones, boolean isConstraintExpressionCellEditor) {
IService expressionBuilderDialogService = GlobalServiceRegister.getDefault().getService(
IExpressionBuilderDialogService.class);
CellEditorDialogBehavior behavior = new CellEditorDialogBehavior();
final ExtendedTextCellEditorWithProposal cellEditor = new ExtendedTextCellEditorWithProposal(
tableViewerCreator.getTable(), SWT.MULTI | SWT.BORDER, column, behavior) {
@Override
public void activate() {
// UIManager uiManager = mapperManager.getUiManager();
//
// ITableEntry currentModifiedBean = (ITableEntry) tableViewerCreator.getModifiedObjectInfo()
// .getCurrentModifiedBean();
//
// ArrayList<ITableEntry> selectedTableEntry = new ArrayList<ITableEntry>(1);
// selectedTableEntry.add(currentModifiedBean);
//
// uiManager.selectLinks(DataMapTableView.this, selectedTableEntry, true, false);
//
// uiManager.applyActivatedCellEditorsForAllTables(tableViewerCreator);
super.activate();
}
};
dialog = ((IExpressionBuilderDialogService) expressionBuilderDialogService).getExpressionBuilderInstance(
tableViewerCreator.getCompositeParent(), cellEditor, mapperManager.getAbstractMapComponent());
behavior.setCellEditorDialog(dialog);
final Text expressionTextEditor = cellEditor.getTextControl();
if (isConstraintExpressionCellEditor) {
constraintExpressionTextEditor = expressionTextEditor;
} else {
columnExpressionTextEditor = expressionTextEditor;
}
cellEditor.addListener(new ICellEditorListener() {
Text text = expressionTextEditor;
public void applyEditorValue() {
// System.out.println("applyEditorValue:text='" + text.getText() + "'");
ModifiedObjectInfo modifiedObjectInfo = tableViewerCreator.getModifiedObjectInfo();
mapperManager.getUiManager().parseNewExpression(text.getText(),
(ITableEntry) modifiedObjectInfo.getCurrentModifiedBean(), true);
checkChangementsAfterEntryModifiedOrAdded(false);
}
public void cancelEditor() {
ModifiedObjectInfo modifiedObjectInfo = tableViewerCreator.getModifiedObjectInfo();
text.setText((String) modifiedObjectInfo.getOriginalPropertyBeanValue());
ITableEntry tableEntry = (ITableEntry) (modifiedObjectInfo.getCurrentModifiedBean() != null ? modifiedObjectInfo
.getCurrentModifiedBean() : modifiedObjectInfo.getPreviousModifiedBean());
String originalExpression = (String) modifiedObjectInfo.getOriginalPropertyBeanValue();
mapperManager.getUiManager().parseNewExpression(originalExpression, tableEntry, true);
}
public void editorValueChanged(boolean oldValidState, boolean newValidState) {
if (expressionTextEditor.isFocusControl() || lastExpressionEditorTextWhichLostFocus == expressionTextEditor) {
ModifiedObjectInfo modifiedObjectInfo = tableViewerCreator.getModifiedObjectInfo();
ITableEntry tableEntry = (ITableEntry) (modifiedObjectInfo.getCurrentModifiedBean() != null ? modifiedObjectInfo
.getCurrentModifiedBean() : modifiedObjectInfo.getPreviousModifiedBean());
mapperManager.getUiManager().parseNewExpression(text.getText(), tableEntry, false);
resizeTextEditor(text, tableViewerCreator);
}
}
});
expressionTextEditor.addControlListener(new ControlListener() {
ExecutionLimiterImproved executionLimiter = null;
public void controlMoved(ControlEvent e) {
}
public void controlResized(ControlEvent e) {
if (executionLimiter == null) {
executionLimiter = new ExecutionLimiterImproved(50, true) {
@Override
public void execute(boolean isFinalExecution, Object data) {
if (isFinalExecution) {
expressionTextEditor.getDisplay().syncExec(new Runnable() {
public void run() {
if (expressionTextEditor.isDisposed()) {
return;
}
resizeTextEditor(expressionTextEditor, tableViewerCreator);
}
});
}
}
};
}
executionLimiter.startIfExecutable();
}
});
expressionTextEditor.addFocusListener(new FocusListener() {
public void focusGained(FocusEvent e) {
// System.out.println("expressionTextEditor focusGained:Text.getText()='"+((Text) e.widget).getText() +
// "'");
ITableEntry currentModifiedEntry = (ITableEntry) tableViewerCreator.getModifiedObjectInfo()
.getCurrentModifiedBean();
if (LanguageManager.getCurrentLanguage().equals(ECodeLanguage.JAVA)) {
if (currentModifiedEntry instanceof AbstractInOutTableEntry) {
IMetadataColumn column = ((AbstractInOutTableEntry) currentModifiedEntry).getMetadataColumn();
String typeToGenerate = JavaTypesManager.getTypeToGenerate(column.getTalendType(), column.isNullable());
cellEditor.setExpressionType(typeToGenerate);
} else if (currentModifiedEntry instanceof VarTableEntry) {
boolean nullable = ((VarTableEntry) currentModifiedEntry).isNullable();
String talendType = ((VarTableEntry) currentModifiedEntry).getType();
String typeToGenerate = JavaTypesManager.getTypeToGenerate(talendType, nullable);
cellEditor.setExpressionType(typeToGenerate);
// TDI-23838 : High CPU and hang when working on "Var" section on MacOS
if ("".equals(currentModifiedEntry.getExpression()) || currentModifiedEntry.getExpression() == null) {
needInitProposals = true;
}
}
}
initExpressionProposals(cellEditor, zones, tableViewerCreator, currentModifiedEntry);
resizeTextEditor(expressionTextEditor, tableViewerCreator);
StyledTextHandler styledTextHandler = mapperManager.getUiManager().getTabFolderEditors().getStyledTextHandler();
if (styledTextHandler.getCurrentEntry() != currentModifiedEntry) {
styledTextHandler.setCurrentEntry(currentModifiedEntry);
styledTextHandler.setTextWithoutNotifyListeners(currentModifiedEntry.getExpression() == null ? "" : currentModifiedEntry.getExpression()); //$NON-NLS-1$
}
}
public void focusLost(FocusEvent e) {
expressionEditorTextSelectionBeforeFocusLost = expressionTextEditor.getSelection();
lastExpressionEditorTextWhichLostFocus = expressionTextEditor;
}
});
column.setCellEditor(cellEditor, new CellEditorValueAdapter() {
@Override
public Object getCellEditorTypedValue(CellEditor cellEditor, Object originalTypedValue) {
return super.getCellEditorTypedValue(cellEditor, originalTypedValue);
}
@Override
public String getColumnText(CellEditor cellEditor, Object bean, Object cellEditorTypedValue) {
return super.getColumnText(cellEditor, bean, cellEditorTypedValue).replaceAll("[\r\n\t]+", " ... "); //$NON-NLS-1$ //$NON-NLS-2$
}
@Override
public Object getOriginalTypedValue(CellEditor cellEditor, Object cellEditorTypedValue) {
return super.getOriginalTypedValue(cellEditor, cellEditorTypedValue);
}
});
return cellEditor;
}
private void resizeTextEditor(Text textEditor, TableViewerCreator tableViewerCreator) {
Point currentSize = textEditor.getSize();
Rectangle currentBounds = textEditor.getBounds();
String text = textEditor.getText();
Table currentTable = tableViewerCreator.getTable();
int itemHeight = currentTable.getItemHeight();
int minHeight = itemHeight + 3;
int maxHeight = 2 * itemHeight + 4;
int newHeight = 0;
if ((text.contains("\n") || text.contains("\r")) && currentBounds.y + maxHeight < currentTable.getBounds().height) { //$NON-NLS-1$ //$NON-NLS-2$
newHeight = maxHeight;
} else {
newHeight = minHeight;
}
if (currentSize.y != newHeight) {
textEditor.setSize(textEditor.getSize().x, newHeight);
}
}
/**
* DOC amaumont Comment method "updateGridDataHeightForTableConstraints".
*/
public void updateGridDataHeightForTableConstraints() {
int moreSpace = WindowSystem.isGTK() ? tableForConstraints.getItemHeight() : 0;
tableForConstraintsGridData.heightHint = ((OutputTable) abstractDataMapTable).getFilterEntries().size()
* tableForConstraints.getItemHeight() + tableForConstraints.getItemHeight() / 2 + moreSpace;
if (WindowSystem.isGTK()) {
tableViewerCreatorForFilters.layout();
}
}
/**
* DOC amaumont Comment method "updateGridDataHeightForTableConstraints".
*/
public void updateGridDataHeightForTableGlobalMap() {
int moreSpace = WindowSystem.isGTK() ? tableForGlobalMap.getItemHeight() : 0;
int size = ((InputTable) abstractDataMapTable).getGlobalMapEntries().size();
if (size < 3) {
tableForGlobalMapGridData.heightHint = size
* (tableForGlobalMap.getItemHeight() + tableForGlobalMap.getItemHeight() / 2) + moreSpace;
} else {
tableForGlobalMapGridData.heightHint = size * (tableForGlobalMap.getItemHeight()) + moreSpace;
}
if (WindowSystem.isGTK() || WindowSystem.isOSX()) {
tableViewerCreatorForGlobalMap.layout();
}
}
/**
* DOC amaumont Comment method "unselectAllEntries".
*/
public void unselectAllEntries() {
unselectAllColumnEntries();
unselectAllConstraintEntries();
unselectAllGlobalMapEntries();
}
/**
* DOC amaumont Comment method "unselectAllConstraintEntries".
*/
public void unselectAllConstraintEntries() {
// nothing by default, override if necessary
}
/**
* DOC amaumont Comment method "unselectAllGlobalMapEntries".
*/
public void unselectAllGlobalMapEntries() {
// nothing by default, override if necessary
}
/**
* DOC amaumont Comment method "unselectAllColumnEntries".
*/
public void unselectAllColumnEntries() {
tableViewerCreatorForColumns.getSelectionHelper().deselectAll();
}
/*
* (non-Javadoc)
*
* @see org.eclipse.swt.widgets.Control#setCursor(org.eclipse.swt.graphics.Cursor)
*/
@Override
public void setCursor(Cursor cursor) {
if (this.currentCursor != null) {
this.currentCursor.dispose();
}
this.currentCursor = cursor;
super.setCursor(cursor);
}
/**
* DOC amaumont Comment method "selectThisDataMapTableView".
*/
protected void selectThisDataMapTableView() {
UIManager uiManager = mapperManager.getUiManager();
if (uiManager.getCurrentSelectedInputTableView() != DataMapTableView.this
&& uiManager.getCurrentSelectedOutputTableView() != DataMapTableView.this) {
uiManager.selectDataMapTableView(DataMapTableView.this, true, false);
}
}
/**
*
* Provide a color provider for Constraints table and dataMap table.
*
*
* <br/>
*
*/
class ExpressionColorProvider {
/**
* DOC amaumont Comment method "getBackgroundColor".
*
* @param expression
*/
public Color getBackgroundColor(boolean validCell) {
if (validCell) {
return null;
} else {
return ColorProviderMapper.getColor(ColorInfo.COLOR_BACKGROUND_ERROR_EXPRESSION_CELL);
}
}
/**
* DOC amaumont Comment method "getBackgroundColor".
*
* @param expression
*/
public Color getForegroundColor(boolean validCell) {
// if (validCell) {
// return null;
// } else {
// return ColorProviderMapper.getColor(ColorInfo.COLOR_FOREGROUND_ERROR_EXPRESSION_CELL);
// }
return null;
}
}
protected ExpressionColorProvider getExpressionColorProvider() {
return this.expressionColorProvider;
}
/**
* DOC amaumont Comment method "getCommonBackgroundColor".
*
* @param element
* @param columnIndex
* @return
*/
protected Color getBackgroundCellColor(TableViewerCreatorNotModifiable tableViewerCreator, Object element, int columnIndex) {
ITableEntry entry = (ITableEntry) element;
TableViewerCreatorColumnNotModifiable column = (TableViewerCreatorColumnNotModifiable) tableViewerCreator.getColumns()
.get(columnIndex);
if (column.getId().equals(ID_EXPRESSION_COLUMN)) {
return expressionColorProvider.getBackgroundColor(entry.getProblems() == null ? true : false);
} else if (column.getId().equals(PREVIEW_COLUMN)) {
return ColorProviderMapper.getColor(ColorInfo.COLOR_TMAP_PREVIEW);
}
return null;
}
/**
* DOC amaumont Comment method "getCommonBackgroundColor".
*
* @param element
* @param columnIndex
* @return
*/
protected Color getForegroundCellColor(TableViewerCreatorNotModifiable tableViewerCreator, Object element, int columnIndex) {
ITableEntry entry = (ITableEntry) element;
TableViewerCreatorColumnNotModifiable column = (TableViewerCreatorColumnNotModifiable) tableViewerCreator.getColumns()
.get(columnIndex);
if (column.getId().equals(ID_EXPRESSION_COLUMN)) {
return expressionColorProvider.getForegroundColor(entry.getProblems() == null ? true : false);
}
return null;
}
/**
* DOC amaumont Comment method "unselectAllEntriesIfErrorDetected".
*
* @param e
*/
protected void unselectAllEntriesIfErrorDetected(TableCellValueModifiedEvent e) {
if (e.column.getId().equals(ID_EXPRESSION_COLUMN)) {
ITableEntry currentEntry = (ITableEntry) e.bean;
TableViewer tableViewer = null;
if (currentEntry instanceof IColumnEntry) {
tableViewer = DataMapTableView.this.getTableViewerCreatorForColumns().getTableViewer();
} else if (currentEntry instanceof FilterTableEntry) {
tableViewer = DataMapTableView.this.getTableViewerCreatorForFilters().getTableViewer();
}
if (currentEntry.getProblems() != null) {
tableViewer.getTable().deselectAll();
}
}
}
/**
* DOC amaumont Comment method "processEnterKeyDown".
*
* @param tableViewer
* @param event
*/
protected void processEnterKeyDown(final TableViewerCreator tableViewerCreator, Event event) {
if (event.character == '\r') {
Object element = null;
if (tableViewerCreator.getTable().getSelectionCount() == 1) {
element = tableViewerCreator.getTable().getSelection()[0].getData();
} else {
element = tableViewerCreator.getModifiedObjectInfo().getPreviousModifiedBean();
}
if (element != null) {
int indexColumn = tableViewerCreator.getColumn(ID_EXPRESSION_COLUMN).getIndex();
tableViewerCreator.getTableViewer().editElement(element, indexColumn);
}
}
}
public abstract boolean toolbarNeedToHaveRightStyle();
public abstract boolean hasDropDownToolBarItem();
/**
* DOC amaumont Comment method "parseExpression".
*
* @param event
* @param tableViewerCreator
* @param tableEntry
*/
private void parseExpression(ModifiedBeanEvent event, TableViewerCreator tableViewerCreator, ITableEntry tableEntry) {
if (event.column == tableViewerCreator.getColumn(DataMapTableView.ID_EXPRESSION_COLUMN)) {
mapperManager.getUiManager().parseExpression(tableEntry.getExpression(), tableEntry, false, false, false);
if (headerComposite != null && !headerComposite.isDisposed()) {
mapperManager.getUiManager().refreshBackground(false, false);
}
}
}
/**
* Getter for extendedTableViewerForColumns.
*
* @return the extendedTableViewerForColumns
*/
public AbstractExtendedTableViewer<IColumnEntry> getExtendedTableViewerForColumns() {
return this.extendedTableViewerForColumns;
}
/**
* Getter for extendedTableViewerForFilters.
*
* @return the extendedTableViewerForFilters
*/
public AbstractExtendedTableViewer<FilterTableEntry> getExtendedTableViewerForFilters() {
return this.extendedTableViewerForFilters;
}
protected Composite getCenterComposite() {
return this.centerComposite;
}
protected ExpressionProposalProvider getExpressionProposalProvider() {
return this.expressionProposalProvider;
}
public int getHeaderHeight() {
if (WindowSystem.isGTK()) {
return HEADER_HEIGHT + (hasDropDownToolBarItem() ? 10 : 2);
} else {
return HEADER_HEIGHT + (hasDropDownToolBarItem() ? 8 : 0);
}
}
public void checkChangementsAfterEntryModifiedOrAdded(boolean forceEvaluation) {
}
public Point getRealToolbarSize() {
return realToolbarSize;
}
/**
* DOC amaumont Comment method "createExpressionFilter".
*
* @param defaultValue TODO
*/
protected void createExpressionFilter(final String defaultText) {
if (mapperManager.isAdvancedMap() && getDataMapTable() instanceof AbstractInOutTable) {
final AbstractInOutTable table = (AbstractInOutTable) getDataMapTable();
IPreferenceStore preferenceStore = CorePlugin.getDefault().getPreferenceStore();
expressionImageLabel = new Label(getCenterComposite(), SWT.NONE);
expressionImageLabel.setImage(ImageProviderMapper.getImage(ImageInfo.ACTIVATE_FILTER_ICON));
expressionImageLabel.setVisible(table.isActivateExpressionFilter());
expressionFilterText = new UnnotifiableColorStyledText(getCenterComposite(), SWT.BORDER | SWT.V_SCROLL,
preferenceStore, LanguageManager.getCurrentLanguage().getName());
// hywang add for 9225
openExpressionBuilder = new Button(getCenterComposite(), SWT.PUSH);
openExpressionBuilder.setImage(ImageProvider.getImage(EImage.THREE_DOTS_ICON));
openExpressionBuilder.setVisible(table.isActivateExpressionFilter());
openExpressionBuilder.addSelectionListener(new SelectionListener() {
IService expressionBuilderDialogService = GlobalServiceRegister.getDefault().getService(
IExpressionBuilderDialogService.class);
IExpressionBuilderDialogController dialogForTable = ((IExpressionBuilderDialogService) expressionBuilderDialogService)
.getExpressionBuilderInstance(DataMapTableView.this.getCenterComposite(), null,
mapperManager.getAbstractMapComponent());
public void widgetDefaultSelected(SelectionEvent e) {
}
public void widgetSelected(SelectionEvent e) {
if (dialogForTable instanceof TrayDialog) {
TrayDialog parentDialog = (TrayDialog) dialogForTable;
dialogForTable.setDefaultExpression(expressionFilterText.getText());
if (Window.OK == parentDialog.open()) {
String expressionForTable = dialogForTable.getExpressionForTable();
ControlUtils.setText(expressionFilterText, expressionForTable);
if (isFilterEqualsToDefault(expressionForTable)) {
table.getExpressionFilter().setExpression(null);
} else {
table.getExpressionFilter().setExpression(expressionForTable);
}
checkProblemsForExpressionFilter(false, true);
ITableEntry currentExpressionFilterEntry = null;
StyledTextHandler textTarget = mapperManager.getUiManager().getTabFolderEditors()
.getStyledTextHandler();
if (textTarget.getCurrentEntry() != null) {
currentExpressionFilterEntry = textTarget.getCurrentEntry();
} else {
currentExpressionFilterEntry = table.getExpressionFilter();
}
mapperManager.getUiManager().parseNewExpression(textTarget.getStyledText().getText(),
currentExpressionFilterEntry, false);
}
}
}
});
if (mapperManager.componentIsReadOnly()) {
expressionFilterText.setEditable(false);
openExpressionBuilder.setEnabled(false);
expressionImageLabel.setEnabled(false);
}
GridData gridData1 = new GridData();
gridData1.exclude = !table.isActivateExpressionFilter();
openExpressionBuilder.setLayoutData(gridData1);
GridData gridData2 = new GridData();
gridData2.exclude = !table.isActivateExpressionFilter();
expressionImageLabel.setLayoutData(gridData2);
//
GridData gridData = new GridData(GridData.FILL_HORIZONTAL);
gridData.minimumHeight = 10;
// gridData.grabExcessVerticalSpace = true;
gridData.heightHint = 32;
gridData.minimumWidth = 25;
gridData.widthHint = 50;
expressionFilterText.setLayoutData(gridData);
String expressionFilter = table.getExpressionFilter().getExpression();
if (expressionFilter != null && !"".equals(expressionFilter.trim())) { //$NON-NLS-1$
expressionFilterText.setText(expressionFilter);
} else {
expressionFilterText.setText(defaultText);
}
new DragNDrop(mapperManager, expressionFilterText, false, true);
expressionFilterText.setVisible(table.isActivateExpressionFilter());
gridData.exclude = !table.isActivateExpressionFilter();
expressionFilterText.addFocusListener(new FocusListener() {
public void focusGained(FocusEvent e) {
redrawExpressionFilter();
Control text = (Control) e.getSource();
if (defaultText.equals(ControlUtils.getText(text))) {
ControlUtils.setText(text, ""); //$NON-NLS-1$
}
ExpressionFilterEntry currentExpressionFilterEntry = table.getExpressionFilter();
// currentExpressionFilterEntry.setExpression(ControlUtils.getText(text));
mapperManager.getUiManager().selectLinks(DataMapTableView.this,
Arrays.<ITableEntry> asList(currentExpressionFilterEntry), true, false);
if (!mapperManager.isSearchOption()) {
expressionFilterText.setBackground(null);
expressionFilterText.setForeground(null);
}
StyledTextHandler styledTextHandler = mapperManager.getUiManager().getTabFolderEditors()
.getStyledTextHandler();
styledTextHandler.setCurrentEntry(currentExpressionFilterEntry);
previousTextForExpressionFilter = currentExpressionFilterEntry.getExpression() == null ? "" : currentExpressionFilterEntry.getExpression(); //$NON-NLS-1$
styledTextHandler.getStyledText().setText(previousTextForExpressionFilter);
expressionFilterText.setToolTipText(null);
styledTextHandler.getStyledText().setEnabled(true);
styledTextHandler.getStyledText().setEditable(true);
expressionProposalStyledText = styledTextHandler.getContentProposalAdapter();
expressionProposalProviderForExpressionFilter.init(table, getValidZonesForExpressionFilterField(),
table.getExpressionFilter());
if (expressionProposalStyledText != null) {
expressionProposalStyledText.setContentProposalProvider(expressionProposalProviderForExpressionFilter);
}
mapperManager.getUiManager().selectLinks(DataMapTableView.this,
Arrays.<ITableEntry> asList(currentExpressionFilterEntry), true, false);
colorExpressionFilterFromProblems(table, false);
}
public void focusLost(FocusEvent e) {
Control text = (Control) e.getSource();
if ("".equals(ControlUtils.getText(text).trim())) { //$NON-NLS-1$
ControlUtils.setText(text, defaultText);
}
setExpressionFilterFromStyledText(table, text);
checkProblemsForExpressionFilter(false, true);
}
});
Listener showTooltipErrorListener = new Listener() {
public void handleEvent(Event event) {
switch (event.type) {
case SWT.MouseMove:
if (table.getExpressionFilter().getProblems() != null && !expressionFilterText.isFocusControl()) {
String tooltip = createErrorContentForTooltip(table.getExpressionFilter().getProblems());
expressionFilterText.setToolTipText(tooltip);
} else {
expressionFilterText.setToolTipText(null);
}
break;
default:
}
}
};
expressionFilterText.addListener(SWT.MouseMove, showTooltipErrorListener);
if (executionLimiterForExpressionFilterSetText == null) {
executionLimiterForExpressionFilterSetText = new ExecutionLimiterImproved(50, true) {
@Override
public void execute(boolean isFinalExecution, Object data) {
if (isFinalExecution) {
expressionFilterText.getDisplay().syncExec(new Runnable() {
public void run() {
if (expressionFilterText.isDisposed()) {
return;
}
// to correct bug of CR when content
// is multiline
if (expressionFilterText.getText() != null) {
expressionFilterText.setText(expressionFilterText.getText());
}
}
});
}
}
};
}
expressionFilterText.addControlListener(new ControlListener() {
public void controlMoved(ControlEvent e) {
redrawExpressionFilter();
}
public void controlResized(ControlEvent e) {
redrawExpressionFilter();
}
});
ControlListener listenerForCorrectWrapBug = new ControlListener() {
public void controlMoved(ControlEvent e) {
redrawExpressionFilter();
}
public void controlResized(ControlEvent e) {
correctAsynchStyledTextWrapBug();
}
};
ScrolledComposite scrolledCompositeView = null;
if (getZone() == Zone.INPUTS) {
scrolledCompositeView = getMapperManager().getUiManager().getScrolledCompositeViewInputs();
} else if (getZone() == Zone.OUTPUTS) {
scrolledCompositeView = getMapperManager().getUiManager().getScrolledCompositeViewOutputs();
}
scrolledCompositeView.addControlListener(listenerForCorrectWrapBug);
SelectionListener selectionListenerToCorrectWrapBug = new SelectionListener() {
public void widgetDefaultSelected(SelectionEvent e) {
}
public void widgetSelected(SelectionEvent e) {
redrawExpressionFilter();
}
};
scrolledCompositeView.getVerticalBar().addSelectionListener(selectionListenerToCorrectWrapBug);
expressionFilterText.getVerticalBar().addSelectionListener(selectionListenerToCorrectWrapBug);
// expressionFilterText.addExtendedModifyListener(new
// ExtendedModifyListener() {
//
// public void modifyText(ExtendedModifyEvent event) {
// StyledTextHandler styledTextHandler =
// mapperManager.getUiManager().getTabFolderEditors().getStyledTextHandler();
// styledTextHandler.getStyledText().replaceTextRange(event.start,
// event.length, event.replacedText);
// }
//
// });
ExpressionEditorToMapperStyledTextKeyListener keyAndModifyListener = new ExpressionEditorToMapperStyledTextKeyListener(
expressionFilterText, mapperManager.getUiManager().getTabFolderEditors().getStyledTextHandler());
expressionFilterText.addExtendedModifyListener(keyAndModifyListener);
expressionFilterText.addKeyListener(keyAndModifyListener);
// expressionFilterText.addKeyListener(new KeyListener() {
//
// /*
// * (non-Javadoc)
// *
// * @see
// org.eclipse.swt.events.KeyListener#keyPressed(org.eclipse.swt.events.KeyEvent)
// */
// public void keyPressed(KeyEvent e) {
//
// Control text = (Control) e.getSource();
// setExpressionFilterFromStyledText(table, text);
// StyledTextHandler styledTextHandler =
// mapperManager.getUiManager().getTabFolderEditors()
// .getStyledTextHandler();
// styledTextHandler.getStyledText().setText(expressionFilterText.getText());
//
// }
//
// public void keyReleased(KeyEvent e) {
//
// mapperManager.getUiManager().parseNewExpression(expressionFilterText.getText(),
// table.getExpressionFilter(), false);
//
// }
// });
}
}
protected void createColumnNameFilter() {
if (mapperManager.isAdvancedMap() && getDataMapTable() instanceof AbstractInOutTable) {
final AbstractInOutTable table = (AbstractInOutTable) getDataMapTable();
IPreferenceStore preferenceStore = CorePlugin.getDefault().getPreferenceStore();
filterImageLabel = new Label(getCenterComposite(), SWT.NONE);
filterImageLabel.setImage(ImageProviderMapper.getImage(ImageInfo.TMAP_FILTER_ICON));
filterImageLabel.setVisible(table.isActivateColumnNameFilter());
columnNameTextFilter = new Text(getCenterComposite(), SWT.BORDER);
if (mapperManager.componentIsReadOnly()) {
columnNameTextFilter.setEditable(false);
filterImageLabel.setEnabled(false);
}
GridData gridData1 = new GridData();
gridData1.exclude = !table.isActivateColumnNameFilter();
gridData1.horizontalAlignment = GridData.HORIZONTAL_ALIGN_CENTER;
filterImageLabel.setLayoutData(gridData1);
GridData nameFilterTextGridData = new GridData(GridData.FILL_HORIZONTAL);
nameFilterTextGridData.minimumHeight = 10;
nameFilterTextGridData.heightHint = 20;
nameFilterTextGridData.minimumWidth = 25;
nameFilterTextGridData.widthHint = 50;
columnNameTextFilter.setLayoutData(nameFilterTextGridData);
String columnNameFilter = table.getColumnNameFilter();
if (columnNameFilter != null && !DEFAULT_FILTER.equals(columnNameFilter.trim())) {
columnNameTextFilter.setText(columnNameFilter);
} else {
columnNameTextFilter.setText(DEFAULT_FILTER);
}
columnNameTextFilter.setVisible(table.isActivateColumnNameFilter());
nameFilterTextGridData.exclude = !table.isActivateColumnNameFilter();
//
columnNameTextFilter.setBackground(ColorProviderMapper.getColor(ColorInfo.COLOR_BACKGROUND_VALID_EXPRESSION_CELL));
columnNameTextFilter.setForeground(ColorProviderMapper.getColor(ColorInfo.COLOR_FOREGROUND_VALID_EXPRESSION_CELL));
columnNameTextFilter.addFocusListener(new FocusListener() {
public void focusGained(FocusEvent e) {
redrawColumnNameFilter();
Control text = (Control) e.getSource();
if (DEFAULT_FILTER.equals(ControlUtils.getText(text))) {
ControlUtils.setText(text, DEFAULT_FILTER);
}
}
public void focusLost(FocusEvent e) {
Control text = (Control) e.getSource();
String currentContent = ControlUtils.getText(text);
if (currentContent != null && DEFAULT_FILTER.equals(currentContent.trim())) {
ControlUtils.setText(text, DEFAULT_FILTER);
table.setColumnNameFilter(DEFAULT_FILTER);
} else {
table.setColumnNameFilter(currentContent);
}
}
});
columnNameTextFilter.addControlListener(new ControlListener() {
public void controlMoved(ControlEvent e) {
redrawColumnNameFilter();
}
public void controlResized(ControlEvent e) {
redrawColumnNameFilter();
}
});
columnNameTextFilter.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
parseColumnNameFilterRefresh();
}
});
}
}
public String getNameFilter() {
return this.columnNameTextFilter.getText().trim();
}
class selectorViewerFilter extends ViewerFilter {
@Override
public boolean select(Viewer viewer, Object parentElement, Object element) {
String pattern = getNameFilter();
if (!columnNameFilter.getSelection()) {
pattern = "";
}
SearchPattern matcher = new SearchPattern();
// SearchPattern for dynamic search/exact match/fuzzy match
matcher.setPattern("*" + pattern.trim() + "*");
if (element instanceof OutputColumnTableEntry) {
OutputColumnTableEntry outputColumn = (OutputColumnTableEntry) element;
//
if (outputColumn.getParent() instanceof OutputTable) {
IMetadataColumn metadataColumn = outputColumn.getMetadataColumn();
if (metadataColumn != null && (!matcher.matches(metadataColumn.getLabel()))) {
return false;
}
}
}
if (element instanceof InputColumnTableEntry) {
InputColumnTableEntry inputColumn = (InputColumnTableEntry) element;
if (inputColumn.getParent() instanceof InputTable) {
IMetadataColumn metadataColumn = inputColumn.getMetadataColumn();
if (metadataColumn != null && (!matcher.matches(metadataColumn.getLabel()))) {
return false;
}
}
}
return true;
}
}
/**
* DOC amaumont Comment method "onExpressionFilterTextResized".
*/
private void redrawExpressionFilter() {
// System.out.println("Filter text resized" +
// System.currentTimeMillis());
if (!expressionFilterText.isDisposed()) {
expressionFilterText.redraw();
}
}
private void redrawColumnNameFilter() {
if (!columnNameTextFilter.isDisposed()) {
columnNameTextFilter.redraw();
}
}
/**
* DOC amaumont Comment method "checkProblemsForExpressionFilter".
*/
public void checkProblemsForExpressionFilterWithDelay() {
if (this.executionLimiterForCheckProblemsExpressionFilter == null) {
this.executionLimiterForCheckProblemsExpressionFilter = new ExecutionLimiterImproved(2000, true) {
/*
* (non-Javadoc)
*
* @see org.talend.commons.utils.threading.ExecutionLimiter#execute(boolean)
*/
@Override
protected void execute(boolean isFinalExecution, Object data) {
if (!expressionFilterText.isDisposed()) {
expressionFilterText.getDisplay().asyncExec(new Runnable() {
public void run() {
checkProblemsForExpressionFilter(true, true);
}
});
}
}
};
}
executionLimiterForCheckProblemsExpressionFilter.resetTimer();
executionLimiterForCheckProblemsExpressionFilter.startIfExecutable(true, null);
}
public void checkProblemsForExpressionFilter(boolean forceRecompile, boolean colorAllowed) {
if (this.getDataMapTable() instanceof AbstractInOutTable) {
AbstractInOutTable table = (AbstractInOutTable) this.getDataMapTable();
if (table.isActivateExpressionFilter() && !isFilterEqualsToDefault(expressionFilterText.getText())) {
String nextText = expressionFilterText.getText();
if (nextText != null && previousTextForExpressionFilter != null
&& !nextText.trim().equals(previousTextForExpressionFilter.trim()) || forceRecompile) {
mapperManager.getProblemsManager().checkProblemsForTableEntry(table.getExpressionFilter(), true);
} else {
mapperManager.getProblemsManager().checkProblemsForTableEntry(table.getExpressionFilter(), false);
}
} else {
table.getExpressionFilter().setProblems(null);
}
colorExpressionFilterFromProblems(table, colorAllowed);
}
}
/**
* DOC amaumont Comment method "colorExpressionFilterFromProblems".
*
* @param table
* @param colorAllowed TODO
*/
private void colorExpressionFilterFromProblems(AbstractInOutTable table, boolean colorAllowed) {
List<Problem> problems = table.getExpressionFilter().getProblems();
if (problems != null && colorAllowed) {
expressionFilterText.setColoring(false);
if (!mapperManager.isSearchOption()) {
expressionFilterText
.setBackground(ColorProviderMapper.getColor(ColorInfo.COLOR_BACKGROUND_ERROR_EXPRESSION_CELL));
expressionFilterText
.setForeground(ColorProviderMapper.getColor(ColorInfo.COLOR_FOREGROUND_ERROR_EXPRESSION_CELL));
}
} else {
expressionFilterText.setColoring(true);
if (!mapperManager.isSearchOption()) {
expressionFilterText
.setBackground(ColorProviderMapper.getColor(ColorInfo.COLOR_BACKGROUND_VALID_EXPRESSION_CELL));
expressionFilterText
.setForeground(ColorProviderMapper.getColor(ColorInfo.COLOR_FOREGROUND_VALID_EXPRESSION_CELL));
}
}
}
/**
* DOC amaumont Comment method "registerProposalForExpressionFilter".
*/
public void configureExpressionFilter() {
if (mapperManager.isAdvancedMap() && getDataMapTable() instanceof AbstractInOutTable) {
final AbstractInOutTable table = (AbstractInOutTable) getDataMapTable();
if (this.expressionProposalProviderForExpressionFilter == null) {
this.expressionProposalProviderForExpressionFilter = createExpressionProposalProvider();
}
expressionProposalProviderForExpressionFilter.init(table, getValidZonesForExpressionFilterField(),
table.getExpressionFilter());
table.getExpressionFilter().setName(EXPRESSION_FILTER_ENTRY);
this.proposalForExpressionFilterText = ProposalUtils.getCommonProposal(expressionFilterText,
expressionProposalProviderForExpressionFilter);
this.proposalForExpressionFilterText.addContentProposalListener(new IContentProposalListener() {
public void proposalAccepted(IContentProposal proposal) {
new AsynchronousThreading(50, false, expressionFilterText.getDisplay(), new Runnable() {
/*
* (non-Javadoc)
*
* @see java.lang.Runnable#run()
*/
public void run() {
if (!expressionFilterText.isDisposed()) {
mapperManager.getUiManager().parseNewExpression(expressionFilterText.getText(),
table.getExpressionFilter(), false);
}
}
}).start();
}
});
checkProblemsForExpressionFilter(false, true);
}
}
/**
* DOC amaumont Comment method "getValidZonesForExpressionFilterField".
*
* @return
*/
protected abstract Zone[] getValidZonesForExpressionFilterField();
/**
* DOC amaumont Comment method "createErrorContentForTooltip".
*
* @param problems
* @return
*/
private String createErrorContentForTooltip(List<Problem> problems) {
String toolTip;
toolTip = ""; //$NON-NLS-1$
for (Problem problem : problems) {
String description = problem.getDescription().replaceAll("[\r\n\t]", ""); //$NON-NLS-1$ //$NON-NLS-2$
toolTip += description + "\n"; //$NON-NLS-1$
}
return toolTip;
}
/**
* This method must be called when all widgets has been created.
*/
public void loaded() {
}
/**
* Getter for expressionFilterText.
*
* @return the expressionFilterText
*/
public UnnotifiableColorStyledText getExpressionFilterText() {
return this.expressionFilterText;
}
public Text getColumnNameFilterText() {
return this.columnNameTextFilter;
}
/**
* DOC amaumont Comment method "correctAsynchStyledTextWrapBug".
*/
private void correctAsynchStyledTextWrapBug() {
if (!expressionFilterText.isDisposed()) {
new AsynchronousThreading(100, false, expressionFilterText.getDisplay(), new Runnable() {
/*
* (non-Javadoc)
*
* @see java.lang.Runnable#run()
*/
public void run() {
// System.out.println("scrolledCompositeView.addControlListener(new
// ControlListener()"
// + System.currentTimeMillis());
redrawExpressionFilter();
}
}).start();
}
}
/**
* DOC amaumont Comment method "setExpressionFilterFromStyledText".
*
* @param table
* @param text
*/
public void setExpressionFilterFromStyledText(final AbstractInOutTable table, Control text) {
String currentContent = ControlUtils.getText(text);
if (isFilterEqualsToDefault(currentContent)) {
table.getExpressionFilter().setExpression(null);
} else {
table.getExpressionFilter().setExpression(currentContent);
}
}
/**
* Check expression errors, show or hide text widget.
*
* @param buttonPressed TODO
* @param activateFilterCheck
*/
protected void updateExepressionFilterTextAndLayout(boolean buttonPressed) {
final AbstractInOutTable table = (AbstractInOutTable) getDataMapTable();
GridData gridData = (GridData) expressionFilterText.getLayoutData();
GridData gridData2 = (GridData) openExpressionBuilder.getLayoutData();
GridData gridData3 = (GridData) expressionImageLabel.getLayoutData();
if (activateFilterCheck.getSelection()) {
expressionFilterText.setVisible(true);
gridData.exclude = false;
table.setActivateExpressionFilter(true);
// hywang add
openExpressionBuilder.setVisible(true);
gridData2.exclude = false;
expressionImageLabel.setVisible(true);
gridData3.exclude = false;
mapperManager.getUiManager().parseExpression(expressionFilterText.getText(), table.getExpressionFilter(), false,
false, false);
} else {
expressionFilterText.setVisible(false);
gridData.exclude = true;
table.setActivateExpressionFilter(false);
// hywang add
openExpressionBuilder.setVisible(false);
gridData2.exclude = true;
expressionImageLabel.setVisible(false);
gridData3.exclude = true;
mapperManager.removeTableEntry(table.getExpressionFilter());
}
// updateGridDataHeightForTableConstraints();
if (buttonPressed) {
DataMapTableView.this.changeSize(DataMapTableView.this.getPreferredSize(false, true, false), true, true);
}
DataMapTableView.this.layout();
mapperManager.getUiManager().refreshBackground(true, false);
if (expressionFilterText.isVisible() && buttonPressed) {
new AsynchronousThreading(50, false, mapperManager.getUiManager().getDisplay(), new Runnable() {
public void run() {
TimeMeasure.begin(Messages.getString("DataMapTableView.checkProblem")); //$NON-NLS-1$
checkProblemsForExpressionFilter(expressionFilterText.isFocusControl(), false);
TimeMeasure.end(Messages.getString("DataMapTableView.checkProblem")); //$NON-NLS-1$
}
}).start();
expressionFilterText.setFocus();
if (DataMapTableView.this.getZone() == Zone.INPUTS) {
ScrolledComposite scrolledZoneView = mapperManager.getUiManager().getScrolledCompositeViewInputs();
Point point = expressionFilterText.getDisplay().map(expressionFilterText,
mapperManager.getUiManager().getTablesZoneViewInputs(), new Point(0, 0));
mapperManager.getUiManager().setPositionOfVerticalScrollBarZone(scrolledZoneView, point.y - 20);
}
}
correctAsynchStyledTextWrapBug();
}
protected void updateColumnNameFilterTextAndLayout(boolean buttonPressed) {
final AbstractInOutTable table = (AbstractInOutTable) getDataMapTable();
GridData gridData = (GridData) columnNameTextFilter.getLayoutData();
GridData gridData1 = (GridData) filterImageLabel.getLayoutData();
if (columnNameFilter.getSelection()) {
columnNameTextFilter.setVisible(true);
gridData.exclude = false;
table.setActiveColumnNameFilter(true);
gridData1.exclude = false;
filterImageLabel.setVisible(true);
} else {
columnNameTextFilter.setVisible(false);
gridData.exclude = true;
table.setActiveColumnNameFilter(false);
gridData1.exclude = true;
filterImageLabel.setVisible(false);
}
parseColumnNameFilterRefresh();
if (buttonPressed) {
DataMapTableView.this.changeSize(DataMapTableView.this.getPreferredSize(false, true, false), true, true);
}
DataMapTableView.this.layout();
mapperManager.getUiManager().refreshBackground(true, false);
if (columnNameTextFilter.isVisible() && buttonPressed) {
columnNameTextFilter.setFocus();
}
}
private void parseColumnNameFilterRefresh() {
notifyFocusLost();
viewer.refresh();
if (abstractDataMapTable instanceof OutputTable) {
OutputTable outputTable = (OutputTable) abstractDataMapTable;
List<IColumnEntry> oldOuputEntries = outputTable.getDataMapTableEntries();
// Table tableViewerForEntries = tableViewerCreatorForColumns.getTableViewer().getTable();
if (oldOuputEntries != null) {
for (IColumnEntry entry : oldOuputEntries) {
if (entry instanceof OutputColumnTableEntry) {
OutputColumnTableEntry outputEntry = (OutputColumnTableEntry) entry;
if (outputEntry.getExpression() != null) {
String[] expressions = outputEntry.getExpression().split("\\s+");
for (String expression : expressions) {
mapperManager.getUiManager().parseNewFilterColumn(expression, outputEntry, false);
mapperManager.getUiManager().refreshBackground(false, false);
}
}
}
}
resizeAtExpandedSize();
}
}
if (abstractDataMapTable instanceof InputTable) {
InputTable inputTable = (InputTable) abstractDataMapTable;
List<IColumnEntry> oldInputEntries = inputTable.getDataMapTableEntries();
if (oldInputEntries != null) {
for (IColumnEntry entry : oldInputEntries) {
if (entry instanceof InputColumnTableEntry) {
// InputColumnTableEntry inputEntry = (InputColumnTableEntry) entry;
StyledTextHandler textTarget = mapperManager.getUiManager().getTabFolderEditors().getStyledTextHandler();
if (textTarget.getStyledText().getText() != null && textTarget.getCurrentEntry() != null) {
String[] expressions = textTarget.getStyledText().getText().split("\\s+");
for (String expression : expressions) {
mapperManager.getUiManager().parseNewFilterColumn(expression, textTarget.getCurrentEntry(),
false);
mapperManager.getUiManager().refreshBackground(false, false);
}
}
mapperManager.getUiManager().refreshBackground(true, false);
}
}
resizeAtExpandedSize();
}
}
}
/**
*
* DOC amaumont InputDataMapTableView class global comment. Detailled comment <br/>
*
*/
class ExpressionEditorToMapperStyledTextKeyListener implements ExtendedModifyListener, KeyListener {
private final Control textWidget;
private final StyledTextHandler textTarget;
private boolean modifyListenerAllowed;
/**
* DOC amaumont TextKeyListener constructor comment.
*/
public ExpressionEditorToMapperStyledTextKeyListener(StyledText textWidgetSrc, StyledTextHandler textTarget) {
super();
this.textWidget = textWidgetSrc;
this.textTarget = textTarget;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.swt.events.KeyListener#keyPressed(org.eclipse.swt.events.KeyEvent)
*/
public void keyPressed(KeyEvent e) {
}
public void keyReleased(KeyEvent e) {
// highlightLineOfCursorPosition();
mapperManager.getUiManager().parseNewExpression(textTarget.getStyledText().getText(), textTarget.getCurrentEntry(),
false);
}
/*
* (non-Javadoc)
*
* @see org.eclipse.swt.custom.ExtendedModifyListener#modifyText(org.eclipse.swt.custom.ExtendedModifyEvent)
*/
public void modifyText(ExtendedModifyEvent event) {
// if (modifyListenerAllowed) {
if (isFilterEqualsToDefault(ControlUtils.getText(textWidget))) {
textTarget.setTextWithoutNotifyListeners(""); //$NON-NLS-1$
} else {
textTarget.setTextWithoutNotifyListeners(ControlUtils.getText(textWidget));
}
highlightLineAndSetSelectionOfStyledTextFromTextControl(textWidget);
// }
}
}
public boolean isFilterEqualsToDefault(String value) {
if (DEFAULT_POST_MATCHING_EXPRESSION_FILTER.equals(value) || DEFAULT_OUT_EXPRESSION_FILTER.equals(value)
|| DEFAULT_EXPRESSION_FILTER.equals(value)) {
return true;
}
return false;
}
/**
*
* DOC amaumont InputDataMapTableView class global comment. Detailled comment <br/>
*
*/
class TextCellEditorToMapperStyledTextKeyListener implements KeyListener {
private final Control textWidget;
private final StyledTextHandler textTarget;
/**
* DOC amaumont TextKeyListener constructor comment.
*/
public TextCellEditorToMapperStyledTextKeyListener(Text textWidgetSrc, StyledTextHandler textTarget) {
super();
this.textWidget = textWidgetSrc;
this.textTarget = textTarget;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.swt.events.KeyListener#keyPressed(org.eclipse.swt.events.KeyEvent)
*/
public void keyPressed(KeyEvent e) {
// System.out.println("e.character=" + e.character);
// System.out.println("keyCode=" + e.keyCode);
// TUP-29766
if (WindowSystem.isBigSurOrLater() && e.character == '\t') {
ITableEntry currentModifiedEntry = textTarget.getCurrentEntry();
currentModifiedEntry.setExpression(ControlUtils.getText(textWidget));
viewer.getTable().deselectAll();
viewer.refresh(currentModifiedEntry);
return;
}
boolean ctrl = (e.stateMask & SWT.CTRL) != 0;
boolean altgr = (e.stateMask & SWT.ALT) != 0;
if (e.character == '\0' || ctrl && !altgr) {
highlightLineAndSetSelectionOfStyledTextFromTextControl(textWidget);
} else {
UnnotifiableColorStyledText mapperColorStyledText = (UnnotifiableColorStyledText) textTarget.getStyledText();
Point selection = ControlUtils.getSelection(textWidget);
if (e.character == '\r' || e.character == '\u001b') {
e.doit = false;
textTarget.setTextWithoutNotifyListeners(ControlUtils.getText(textWidget));
highlightLineAndSetSelectionOfStyledTextFromTextControl(textWidget);
} else {
if (e.character == SWT.BS || e.character == SWT.DEL) {
if (selection.x == selection.y) {
if (e.character == SWT.BS) {
if (selection.x - 1 > 0 && mapperColorStyledText.getText().length() > selection.x - 1) {
char previousChar = mapperColorStyledText.getText().charAt(selection.x - 1);
if (previousChar == '\n') {
mapperColorStyledText.replaceTextRangeWithoutNotifyListeners(selection.x - 2, 2, ""); //$NON-NLS-1$
} else {
mapperColorStyledText.replaceTextRangeWithoutNotifyListeners(selection.x - 1, 1, ""); //$NON-NLS-1$
}
}
} else {
if (selection.x < mapperColorStyledText.getText().length()) {
char nextChar = mapperColorStyledText.getText().charAt(selection.x);
if (nextChar == '\r') {
mapperColorStyledText.replaceTextRangeWithoutNotifyListeners(selection.x, 2, ""); //$NON-NLS-1$
} else {
mapperColorStyledText.replaceTextRangeWithoutNotifyListeners(selection.x, 1, ""); //$NON-NLS-1$
}
}
}
} else {
if (selection.y <= mapperColorStyledText.getCharCount()) {
mapperColorStyledText.replaceTextRangeWithoutNotifyListeners(selection.x, selection.y
- selection.x, ""); //$NON-NLS-1$
}
highlightLineAndSetSelectionOfStyledTextFromTextControl(textWidget);
}
} else {
// System.out.println("selection.x="+selection.x);
// System.out.println("selection.y="+selection.y);
// System.out.println("mapperColorStyledText.getText()="+mapperColorStyledText.getText().length()
// );
if (selection.y <= mapperColorStyledText.getCharCount()) {
mapperColorStyledText.replaceTextRangeWithoutNotifyListeners(selection.x, selection.y - selection.x,
String.valueOf(e.character));
}
highlightLineAndSetSelectionOfStyledTextFromTextControl(textWidget);
}
}
}
}
public void keyReleased(KeyEvent e) {
// highlightLineOfCursorPosition();
}
}
/**
* Getter for activateFilterCheck.
*
* @return the activateFilterCheck
*/
protected ToolItem getActivateFilterCheck() {
return this.activateFilterCheck;
}
/**
* Getter for previousStateCheckFilter.
*
* @return the previousStateCheckFilter
*/
protected boolean isPreviousStateCheckFilter() {
return this.previousStateCheckFilter;
}
/**
* Sets the previousStateCheckFilter.
*
* @param previousStateCheckFilter the previousStateCheckFilter to set
*/
protected void setPreviousStateCheckFilter(boolean previousStateCheckFilter) {
this.previousStateCheckFilter = previousStateCheckFilter;
}
protected void refreshCondensedImage(AbstractInOutTable table, String option) {
}
/**
* DOC ycbai DataMapTableView class global comment. Detailled comment
*/
class CustomDialogCellEditor extends DialogCellEditor {
private CellValueType type;
private final Map<String, String> oldMappingMap = new HashMap<String, String>();
public CustomDialogCellEditor() {
type = CellValueType.BOOL;
}
public CustomDialogCellEditor(CellValueType type) {
this.type = type;
}
@Override
protected Object openDialogBox(Control cellEditorWindow) {
Shell shell = cellEditorWindow.getShell();
if (type == CellValueType.BOOL) {
ListStringValueDialog<String> dialog = new ListStringValueDialog<String>(shell, new String[] { "true", "false" }); //$NON-NLS-1$ //$NON-NLS-2$
if (dialog.open() == IDialogConstants.OK_ID) {
return dialog.getSelectStr();
}
} else if (type == CellValueType.SCHEMA_TYPE) {
ListStringValueDialog<String> dialog = new ListStringValueDialog<String>(shell, new String[] { BUILT_IN,
REPOSITORY });
if (dialog.open() == IDialogConstants.OK_ID) {
return dialog.getSelectStr();
}
} else if (type == CellValueType.SCHEMA_ID) {
RepositoryReviewDialog dialog = new RepositoryReviewDialog(shell, ERepositoryObjectType.METADATA_CON_TABLE);
if (dialog.open() == IDialogConstants.OK_ID) {
RepositoryNode node = dialog.getResult();
while (node.getObject().getProperty().getItem() == null
|| (!(node.getObject().getProperty().getItem() instanceof ConnectionItem))) {
node = node.getParent();
}
String id = dialog.getResult().getObject().getProperty().getId();
String name = dialog.getResult().getObject().getLabel();
String value = id + " - " + name; //$NON-NLS-1$
IMetadataTable repositoryMetadata = MetadataToolHelper.getMetadataFromRepository(value);
List<IMetadataColumn> columns = repositoryMetadata.getListColumns();
if (columns != null) {
MetadataTableEditorView metadataEditorView = mapperManager.getUiManager()
.getMetadataEditorView(getZone());
ExtendedTableModel<IMetadataColumn> extendedTableModel = metadataEditorView.getExtendedTableModel();
List<IMetadataColumn> copyedAllList = new ArrayList<IMetadataColumn>(extendedTableModel.getBeansList());
if (abstractDataMapTable instanceof OutputTable) {
OutputTable outputTable = (OutputTable) abstractDataMapTable;
List<IColumnEntry> oldOuputEntries = outputTable.getDataMapTableEntries();
if (oldOuputEntries != null) {
for (IColumnEntry entry : oldOuputEntries) {
if (entry instanceof OutputColumnTableEntry) {
OutputColumnTableEntry outputEntry = (OutputColumnTableEntry) entry;
String expression = outputEntry.getExpression();
String columnname = outputEntry.getName();
if (expression != null) {
oldMappingMap.put(columnname, expression);
}
}
}
}
}
// handle related table, save original expression
List<DataMapTableView> relatedOutputsTableView = mapperManager.getUiManager().getRelatedOutputsTableView(
DataMapTableView.this);
for (IMetadataColumn metadataColumn : columns) {
for (DataMapTableView tableView : relatedOutputsTableView) {
IDataMapTable retrieveAbstractDataMapTable = mapperManager
.retrieveAbstractDataMapTable(tableView);
String tableName = retrieveAbstractDataMapTable.getName();
ITableEntry metadataTableEntry = mapperManager.retrieveTableEntry(new TableEntryLocation(
tableName, metadataColumn.getLabel()));
mapperManager.getUiManager().getOldMappingMap()
.put(tableName + "_" + metadataTableEntry.getName(), metadataTableEntry.getExpression());
}
}
// avoid UIManager#handleEvent execute afterOperationListener
// resize fire focuseLost to applyEditorValue remove the columnViewEditorListener
// after extendedTableModel remove/add reset back the original customSized
boolean isCustom = DataMapTableView.this.customSized;
try {
DataMapTableView.this.customSized = true;
extendedTableModel.removeAll(copyedAllList);
for (IMetadataColumn metaColumnToAdd : columns) {
String label = metaColumnToAdd.getLabel();
String expression = oldMappingMap.get(label);
if (expression != null && !"".equals(expression)) {
metaColumnToAdd.setExpression(expression);
}
}
extendedTableModel.addAll(columns);
mapperManager.getUiManager().parseAllExpressionsForAllTables();
mapperManager.getUiManager().getOldMappingMap().clear();
oldMappingMap.clear();
} finally {
DataMapTableView.this.customSized = isCustom;
}
if (canBeResizedAtPreferedSize()) {
changeSize(getPreferredSize(true, false, false), true, true);
}
return value;
}
}
}
return null;
}
/**
* Sets the type.
*
* @param type the type to set
*/
public void setType(CellValueType type) {
this.type = type;
}
/**
* Getter for type.
*
* @return the type
*/
public CellValueType getType() {
return this.type;
}
}
public abstract void notifyFocusLost();
public void propertyChange(PropertyChangeEvent evt) {
notifyFocusLost();
String request = evt.getPropertyName();
if (request.equals("positionChange") || request.equals(ConnectionTrace.TRACE_PROP)) { //$NON-NLS-1$
if (!tableViewerCreatorForColumns.getTable().isDisposed()) {
tableViewerCreatorForColumns.refresh();
InputsZone inputsZone = mapperManager.getUiManager().getInputsZone();
if (inputsZone != null && !inputsZone.isDisposed() && inputsZone.getToolbar() != null) {
inputsZone.getToolbar().refreshCurrentRow();
}
}
}
}
/**
* DOC ycbai Comment method "getSchemaDisplayName".
*
* @param id
* @return
*/
protected String getSchemaDisplayName(String id) {
if (StringUtils.isEmpty(id)) {
return null;
}
String[] values = id.split(" - ");
String itemId = values[0];
String name = values[1];
try {
IProxyRepositoryFactory factory = ((IProxyRepositoryService) GlobalServiceRegister.getDefault().getService(
IProxyRepositoryService.class)).getProxyRepositoryFactory();
IRepositoryViewObject object = factory.getLastVersion(itemId);
if (object == null) {
return null;
}
Item item = object.getProperty().getItem();
if (item instanceof ConnectionItem) {
ConnectionItem lastItemUsed = (ConnectionItem) item;
return DesignerUtilities.getRepositoryAliasName(lastItemUsed) + ":" //$NON-NLS-1$
+ lastItemUsed.getProperty().getLabel() + " - " + name;
}
} catch (PersistenceException e) {
ExceptionHandler.process(e);
}
return null;
}
/**
* DOC ycbai DataMapTableView class global comment. Detailled comment
*/
class TableCellModifier extends DefaultCellModifier {
/**
* DOC talend TableCellModifier constructor comment.
*
* @param tableViewerCreator
*/
public TableCellModifier(TableViewerCreator tableViewerCreator) {
super(tableViewerCreator);
}
@Override
public boolean canModify(Object bean, String idColumn) {
if (bean instanceof InputColumnTableEntry) {
InputColumnTableEntry column = (InputColumnTableEntry) bean;
if (column.getParent() instanceof InputTable) {
boolean isMainConnection = ((InputTable) getDataMapTable()).isMainConnection();
if (!isMainConnection) {
TableViewerCreatorNotModifiable creator = getTableViewerCreator();
TableViewerCreatorColumnNotModifiable operatorColumn = creator.getColumn(ID_OPERATOR);
if (operatorColumn != null) {
if (StringUtils.trimToNull(column.getExpression()) == null) {
operatorColumn.setModifiable(false);
} else {
operatorColumn.setModifiable(true);
}
}
}
}
}
return super.canModify(bean, idColumn);
}
}
/**
* Get unique name with the given name.
*
* @param titleName
*/
public abstract String findUniqueName(String baseName);
}
|
SELECT title, rating
FROM movies
WHERE year > 2012 AND rating > 8 |
import Taro from "@tarojs/taro";
import React, { Component } from 'react'
import { View, Text, Image, Button } from '@tarojs/components'
import PieIcon from '../../img/icons/pie.png'
import BarIcon from '../../img/icons/bar.png'
import LineIcon from '../../img/icons/line.png'
import FunnelIcon from '../../img/icons/funnel.png'
import GaugeIcon from '../../img/icons/gauge.png'
import HeatmapIcon from '../../img/icons/heatmap.png'
import RadarIcon from '../../img/icons/radar.png'
import ScatterIcon from '../../img/icons/scatter.png'
import './index.less'
interface ChartItem {
id: string;
name: string;
img: string
}
interface ButtonItem {
id: string;
name: string;
}
interface IndexState {
charts: ChartItem[];
}
interface Index {}
class Index extends Component<{}, IndexState> {
constructor(props) {
super(props);
this.state = {
charts: [
{ id: 'bar', name: '柱状图', img: BarIcon },
{ id: 'line', name: '折线图', img: LineIcon },
{ id: 'pie', name: '饼图', img: PieIcon },
{ id: 'scatter', name: '散点图', img: ScatterIcon },
{ id: 'radar', name: '雷达图', img: RadarIcon },
{ id: 'heatmap', name: '热力图', img: HeatmapIcon },
// { id: 'map', name: '地图', img: MapIcon },
{ id: 'gauge', name: '仪表盘', img: GaugeIcon },
{ id: 'funnel', name: '漏斗图', img: FunnelIcon },
]
}
}
gotoEcharts(type) {
Taro.navigateTo({ url: `/pages/${type}/index` });
}
render() {
return (
<View className='panel'>
{this.state.charts.map((chart) => {
return (
<View
className='chart-with-img'
onClick={this.gotoEcharts.bind(this, chart.id)}
key={chart.id}
>
<Image src={chart.img} />
<Text>{chart.name}</Text>
</View>
);
})}
<Button type='default' onClick={this.gotoEcharts.bind(this, 'more')}>一个页面多个图表</Button>
</View>
);
}
}
export default Index
|
var status;
const async = require('async');
const gitInitilize=require('./gitInitilize');
const gitUpdate=require('./gitUpdate');
var gitMod=function(repoPath, callback) {
const spawn=require('child_process').spawn;
//ls -lh /usr
// var res = repoName.split("/");
// res=res[res.length-1];
// const parent=spawn('pwd',{cwd: path});
const gitmodule=spawn('find', ['-name', '.gitmodules'],{cwd:repoPath});
gitmodule.stderr.on('data', (data)=> {
status=`${data}`;
console.log(status);
});
gitmodule.stdout.on('data', (data)=> {
status=`${data}`;
console.log(status);
});
gitmodule.on('close', (code) => {
console.log(`Status:${code}`);
if(code !== 0) { callback(new Error('git clone exited with code', code)); return; }
// callback(null,status);
else if(status!=='undefined')
{
async.series([
gitInitilize.bind(null,repoPath),
gitUpdate.bind(null,repoPath)
],
function (err, result) {
// result now equals 'done'
if(err) { console.error('Deploy Failed with error', err); return; }
console.log('cloned submodules');
callback(null);
});
}
else
{
callback(null);
}
});
}
module.exports = gitMod; |
#!/bin/sh
#
# This file and its contents are supplied under the terms of the
# Common Development and Distribution License ("CDDL"), version 1.0.
# You may only use this file in accordance with the terms of version
# 1.0 of the CDDL.
#
# A full copy of the text of the CDDL should have accompanied this
# source. A copy of the CDDL is also available via the Internet at
# http://www.illumos.org/license/CDDL.
#
#
# Copyright 2014 Nexenta Systems, Inc. All rights reserved.
#
# Helper program to run nltest
[ -n "$CODEMGR_WS" ] || {
echo "Need a buildenv to set CODEMGR_WS=..."
exit 1;
}
ROOT=${CODEMGR_WS}/proto/root_i386
LD_LIBRARY_PATH=$ROOT/usr/lib:$ROOT/lib
export LD_LIBRARY_PATH
$ROOT/usr/sbin/nltest "$@"
|
<gh_stars>0
import java.io.PrintStream;
import java.util.stream.IntStream;
/**
* Implementation of the optimal (OPT) page replacement
* algorithm for OS paging.
*
* @author <NAME>
* @version 1.0
*
* @TODO This algorithm is returning a value of 15 for the test reference string, while a value of 13 is expected.
*/
class OPTReplacement extends Replacement {
// Counter that keeps track of how many of the reference
// pages we've already serviced
private int count = 0;
// Copy of the reference string for class-level use
private int[] refString;
OPTReplacement(int pageFrameCount) {
super(pageFrameCount);
}
/**
* Inserts the specified page into the page frame.
*
* @param pageNumber The page number being inserted into the page frame.
*/
@Override
public void insert(int pageNumber) {
// Increment the count to show we've service a page
count++;
if (!IntStream.of(pageFrame).anyMatch(i -> i == pageNumber)) {
// Specified page number is not in page frame
// Therefore, we insert the page and this is a fault
// Increment the fault count
faultCount++;
// Determine the optimal position for the page
pointer = findOptimal();
// Insert the page in the calculated optimal position
pageFrame[pointer] = pageNumber;
}
}
/**
* Inserts all of the specified pages into the page frame
* and writes the number of faults encountered.
*
* @param referenceString The reference pages to be inserted.
*/
@Override
public void insertAll(int[] referenceString, PrintStream out) {
refString = referenceString;
// Insert each element in the reference string
// into the page frame
for(int i : referenceString) insert(i);
// Write to the provided printstream the fault count
out.println("OPT faults: " + faultCount);
}
/**
* Determines and returns the index of the optimal page
* to replace in the page frame.
* @return Index of optimal page to replace.
*/
private int findOptimal() {
// Specifies the distance each page is from
// being inserted again into the page frame
int[] distance = new int[pageFrameCount];
// Initialize each distance to a max
for (int i = 0; i < distance.length; i++) distance[i] = Integer.MAX_VALUE;
// Loop through each distance to set it's actual value
for (int i = 0; i < pageFrameCount; i++) {
int distanceCount = 0;
// Loop through each of the remaining reference pages
for (int j = 0; j < count; j++) {
// Compare the reference page to the current element in the page frame
if (refString[j] == pageFrame[i]) {
// If matching, this is the distance for this page
distance[i] = distanceCount;
break;
}
// Increment the distance count
distanceCount++;
}
}
// Return the index of the greatest distance
return getIndexOfMax(distance);
}
/**
* Retrieves the index of the max element in the specified array.
* @param array The array whose max element's index should be found.
* @return Index of the max element in the specified array.
*/
private static int getIndexOfMax(int[] array) {
int max = 0;
for (int i = 0; i < array.length; i++) {
int newNumber = array[i];
if (newNumber > array[max]) {
max = i;
}
}
return max;
}
}
|
#!/usr/bin/env bash
python setup.py sdist bdist_wheel
pip install ./dist/* --force-reinstall
rm -rf dist |
from sklearn.model_selection import train_test_split
# Load the features and labels
X = features
y = labels
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
# Create an ML model to classify 3 types of fruits
from sklearn.ensemble import RandomForestClassifier
model = RandomForestClassifier()
# Train the model
model.fit(X_train, y_train)
# Test the model
accuracy = model.score(X_test, y_test)
print("Model Accuracy:", accuracy) |
#!/usr/bin/env sh
QUEUEDIR=$HOME/.msmtpqueue
for i in $QUEUEDIR/*.mail; do
grep -E -s --color -h '(^From:|^To:|^Subject:)' "$i" || echo "No mail in queue";
echo " "
done
|
#!/bin/bash
sleep 2
ldapmodify -x -D "cn=admin,cn=config" -w config -f /db/org.ldif
ldapadd -x -D "cn=admin,o=insee,c=fr" -w admin -f /db/ou.ldif
ldapadd -x -D "cn=admin,o=insee,c=fr" -w admin -f /db/groups.ldif
ldapadd -x -D "cn=admin,o=insee,c=fr" -w admin -f /db/people.ldif
tail -f /dev/null |
#!/bin/bash -Eeu
# ROOT_DIR must be set
MERKELY_CHANGE=merkely/change:latest
MERKELY_OWNER=cyber-dojo
MERKELY_PIPELINE=shas
# - - - - - - - - - - - - - - - - - - -
merkely_fingerprint()
{
echo "docker://${CYBER_DOJO_SHAS_IMAGE}:${CYBER_DOJO_SHAS_TAG}"
}
# - - - - - - - - - - - - - - - - - - -
merkely_declare_pipeline()
{
local -r hostname="${1}"
docker run \
--env MERKELY_COMMAND=declare_pipeline \
--env MERKELY_OWNER=${MERKELY_OWNER} \
--env MERKELY_PIPELINE=${MERKELY_PIPELINE} \
--env MERKELY_API_TOKEN=${MERKELY_API_TOKEN} \
--env MERKELY_HOST="${hostname}" \
--rm \
--volume ${ROOT_DIR}/Merkelypipe.json:/data/Merkelypipe.json \
${MERKELY_CHANGE}
}
# - - - - - - - - - - - - - - - - - - -
on_ci_merkely_declare_pipeline()
{
if ! on_ci ; then
return
fi
merkely_declare_pipeline https://staging.app.merkely.com
merkely_declare_pipeline https://app.merkely.com
}
# - - - - - - - - - - - - - - - - - - -
merkely_log_artifact()
{
local -r hostname="${1}"
docker run \
--env MERKELY_COMMAND=log_artifact \
--env MERKELY_OWNER=${MERKELY_OWNER} \
--env MERKELY_PIPELINE=${MERKELY_PIPELINE} \
--env MERKELY_FINGERPRINT=$(merkely_fingerprint) \
--env MERKELY_IS_COMPLIANT=TRUE \
--env MERKELY_ARTIFACT_GIT_COMMIT=${CYBER_DOJO_SHAS_SHA} \
--env MERKELY_ARTIFACT_GIT_URL=https://github.com/${MERKELY_OWNER}/${MERKELY_PIPELINE}/commit/${CYBER_DOJO_SHAS_SHA} \
--env MERKELY_CI_BUILD_NUMBER=${CIRCLE_BUILD_NUM} \
--env MERKELY_CI_BUILD_URL=${CIRCLE_BUILD_URL} \
--env MERKELY_API_TOKEN=${MERKELY_API_TOKEN} \
--env MERKELY_HOST="${hostname}" \
--rm \
--volume /var/run/docker.sock:/var/run/docker.sock \
${MERKELY_CHANGE}
}
# - - - - - - - - - - - - - - - - - - -
on_ci_merkely_log_artifact()
{
if ! on_ci ; then
return
fi
merkely_log_artifact https://staging.app.merkely.com
merkely_log_artifact https://app.merkely.com
}
# - - - - - - - - - - - - - - - - - - -
merkely_log_evidence()
{
local -r hostname="${1}"
docker run \
--env MERKELY_COMMAND=log_evidence \
--env MERKELY_OWNER=${MERKELY_OWNER} \
--env MERKELY_PIPELINE=${MERKELY_PIPELINE} \
--env MERKELY_FINGERPRINT=$(merkely_fingerprint) \
--env MERKELY_EVIDENCE_TYPE=branch-coverage \
--env MERKELY_IS_COMPLIANT=TRUE \
--env MERKELY_DESCRIPTION="server & client line-coverage reports" \
--env MERKELY_USER_DATA="$(evidence_json_path)" \
--env MERKELY_CI_BUILD_URL=${CIRCLE_BUILD_URL} \
--env MERKELY_API_TOKEN=${MERKELY_API_TOKEN} \
--env MERKELY_HOST="${hostname}" \
--rm \
--volume "$(evidence_json_path):$(evidence_json_path)" \
--volume /var/run/docker.sock:/var/run/docker.sock \
${MERKELY_CHANGE}
}
# - - - - - - - - - - - - - - - - - - -
on_ci_merkely_log_evidence()
{
if ! on_ci ; then
return
fi
write_evidence_json
merkely_log_evidence https://staging.app.merkely.com
merkely_log_evidence https://app.merkely.com
}
# - - - - - - - - - - - - - - - - - - -
write_evidence_json()
{
echo '{ "server": ' > "$(evidence_json_path)"
cat "${ROOT_DIR}/test/server/reports/coverage.json" >> "$(evidence_json_path)"
echo ', "client": ' >> "$(evidence_json_path)"
cat "${ROOT_DIR}/test/client/reports/coverage.json" >> "$(evidence_json_path)"
echo '}' >> "$(evidence_json_path)"
}
# - - - - - - - - - - - - - - - - - - -
evidence_json_path()
{
echo "${ROOT_DIR}/test/evidence.json"
}
|
import unittest
import time
import random
"""
Polacz posortowane listy w posortowana liste.
"""
# Wersja 1
def polacz_posortowane_listy_v1(lista_a, lista_b):
if not lista_a:
return list(lista_b)
if not lista_b:
return list(lista_a)
lista_c = []
i = 0
j = 0
while i < len(lista_a) and j < len(lista_b):
if lista_a[i] < lista_b[j]:
lista_c.append(lista_a[i])
i += 1
else:
lista_c.append(lista_b[j])
j += 1
for k in range(i, len(lista_a)):
lista_c.append(lista_a[k])
for k in range(j, len(lista_b)):
lista_c.append(lista_b[k])
return lista_c
# Wersja 2
def polacz_posortowane_listy_v2(lista_a, lista_b):
if not lista_a:
return list(lista_b)
if not lista_b:
return list(lista_a)
lista_c = []
if lista_a[-1] > lista_b[-1]:
lista_a, lista_b = lista_b, lista_a
it = iter(lista_b)
element_listy_b = it.__next__()
lista_c = []
for element_listy_a in lista_a:
try:
while lista_b and element_listy_b < element_listy_a:
lista_c.append(element_listy_b)
element_listy_b = it.__next__()
except StopIteration:
break
lista_c.append(element_listy_a)
lista_c.append(element_listy_b)
lista_c.extend(it)
return lista_c
# Wersja 3
def polacz_posortowane_listy_v3(lista_a, lista_b):
if not lista_a:
return list(lista_b)
if not lista_b:
return list(lista_a)
return sorted(lista_a + lista_b)
# Testy Poprawnosci
a = [5, 7, 11]
b = [1, 3, 8, 14]
c = [1, 3, 5, 7, 8, 11, 14]
assert polacz_posortowane_listy_v1(a, b) == c
assert polacz_posortowane_listy_v2(a, b) == c
assert polacz_posortowane_listy_v3(a, b) == c
# Testy Predkosci
def zmierz_czas(n, f):
a = [random.random() for i in range(n)]
b = [random.random() for i in range(n)]
start = time.time()
f(a, b)
end = time.time()
return end - start
lista_funkcji = [
polacz_posortowane_listy_v1,
polacz_posortowane_listy_v2,
polacz_posortowane_listy_v3,
]
for f in lista_funkcji:
print([zmierz_czas(10, f), zmierz_czas(10 ** 3, f), zmierz_czas(10 ** 6, f)])
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.spark.sql.hive.execution
import scala.collection.JavaConversions._
import org.apache.hadoop.hive.common.`type`.{HiveDecimal, HiveVarchar}
import org.apache.hadoop.hive.conf.HiveConf
import org.apache.hadoop.hive.ql.metadata.{Partition => HivePartition}
import org.apache.hadoop.hive.serde.serdeConstants
import org.apache.hadoop.hive.serde2.ColumnProjectionUtils
import org.apache.hadoop.hive.serde2.objectinspector._
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorUtils.ObjectInspectorCopyOption
import org.apache.hadoop.hive.serde2.objectinspector.primitive._
import org.apache.hadoop.hive.serde2.typeinfo.TypeInfoUtils
import org.apache.spark.annotation.DeveloperApi
import org.apache.spark.sql.catalyst.expressions._
import org.apache.spark.sql.catalyst.types.{BooleanType, DataType}
import org.apache.spark.sql.execution._
import org.apache.spark.sql.hive._
import org.apache.spark.util.MutablePair
/**
* :: DeveloperApi ::
* The Hive table scan operator. Column and partition pruning are both handled.
*
* @param attributes Attributes to be fetched from the Hive table.
* @param relation The Hive table be be scanned.
* @param partitionPruningPred An optional partition pruning predicate for partitioned table.
*/
@DeveloperApi
case class HiveTableScan(
attributes: Seq[Attribute],
relation: MetastoreRelation,
partitionPruningPred: Option[Expression])(
@transient val context: HiveContext)
extends LeafNode
with HiveInspectors {
require(partitionPruningPred.isEmpty || relation.hiveQlTable.isPartitioned,
"Partition pruning predicates only supported for partitioned tables.")
// Bind all partition key attribute references in the partition pruning predicate for later
// evaluation.
private[this] val boundPruningPred = partitionPruningPred.map { pred =>
require(
pred.dataType == BooleanType,
s"Data type of predicate $pred must be BooleanType rather than ${pred.dataType}.")
BindReferences.bindReference(pred, relation.partitionKeys)
}
@transient
private[this] val hadoopReader = new HadoopTableReader(relation.tableDesc, context)
/**
* The hive object inspector for this table, which can be used to extract values from the
* serialized row representation.
*/
@transient
private[this] lazy val objectInspector =
relation.tableDesc.getDeserializer.getObjectInspector.asInstanceOf[StructObjectInspector]
/**
* Functions that extract the requested attributes from the hive output. Partitioned values are
* casted from string to its declared data type.
*/
@transient
protected lazy val attributeFunctions: Seq[(Any, Array[String]) => Any] = {
attributes.map { a =>
val ordinal = relation.partitionKeys.indexOf(a)
if (ordinal >= 0) {
val dataType = relation.partitionKeys(ordinal).dataType
(_: Any, partitionKeys: Array[String]) => {
castFromString(partitionKeys(ordinal), dataType)
}
} else {
val ref = objectInspector.getAllStructFieldRefs
.find(_.getFieldName == a.name)
.getOrElse(sys.error(s"Can't find attribute $a"))
val fieldObjectInspector = ref.getFieldObjectInspector
(row: Any, _: Array[String]) => {
val data = objectInspector.getStructFieldData(row, ref)
unwrapData(data, fieldObjectInspector)
}
}
}
}
private[this] def castFromString(value: String, dataType: DataType) = {
Cast(Literal(value), dataType).eval(null)
}
private def addColumnMetadataToConf(hiveConf: HiveConf) {
// Specifies IDs and internal names of columns to be scanned.
val neededColumnIDs = attributes.map(a => relation.output.indexWhere(_.name == a.name): Integer)
val columnInternalNames = neededColumnIDs.map(HiveConf.getColumnInternalName(_)).mkString(",")
if (attributes.size == relation.output.size) {
ColumnProjectionUtils.setFullyReadColumns(hiveConf)
} else {
ColumnProjectionUtils.appendReadColumnIDs(hiveConf, neededColumnIDs)
}
ColumnProjectionUtils.appendReadColumnNames(hiveConf, attributes.map(_.name))
// Specifies types and object inspectors of columns to be scanned.
val structOI = ObjectInspectorUtils
.getStandardObjectInspector(
relation.tableDesc.getDeserializer.getObjectInspector,
ObjectInspectorCopyOption.JAVA)
.asInstanceOf[StructObjectInspector]
val columnTypeNames = structOI
.getAllStructFieldRefs
.map(_.getFieldObjectInspector)
.map(TypeInfoUtils.getTypeInfoFromObjectInspector(_).getTypeName)
.mkString(",")
hiveConf.set(serdeConstants.LIST_COLUMN_TYPES, columnTypeNames)
hiveConf.set(serdeConstants.LIST_COLUMNS, columnInternalNames)
}
addColumnMetadataToConf(context.hiveconf)
private def inputRdd = if (!relation.hiveQlTable.isPartitioned) {
hadoopReader.makeRDDForTable(relation.hiveQlTable)
} else {
hadoopReader.makeRDDForPartitionedTable(prunePartitions(relation.hiveQlPartitions))
}
/**
* Prunes partitions not involve the query plan.
*
* @param partitions All partitions of the relation.
* @return Partitions that are involved in the query plan.
*/
private[hive] def prunePartitions(partitions: Seq[HivePartition]) = {
boundPruningPred match {
case None => partitions
case Some(shouldKeep) => partitions.filter { part =>
val dataTypes = relation.partitionKeys.map(_.dataType)
val castedValues = for ((value, dataType) <- part.getValues.zip(dataTypes)) yield {
castFromString(value, dataType)
}
// Only partitioned values are needed here, since the predicate has already been bound to
// partition key attribute references.
val row = new GenericRow(castedValues.toArray)
shouldKeep.eval(row).asInstanceOf[Boolean]
}
}
}
override def execute() = {
inputRdd.mapPartitions { iterator =>
if (iterator.isEmpty) {
Iterator.empty
} else {
val mutableRow = new GenericMutableRow(attributes.length)
val mutablePair = new MutablePair[Any, Array[String]]()
val buffered = iterator.buffered
// NOTE (lian): Critical path of Hive table scan, unnecessary FP style code and pattern
// matching are avoided intentionally.
val rowsAndPartitionKeys = buffered.head match {
// With partition keys
case _: Array[Any] =>
buffered.map { case array: Array[Any] =>
val deserializedRow = array(0)
val partitionKeys = array(1).asInstanceOf[Array[String]]
mutablePair.update(deserializedRow, partitionKeys)
}
// Without partition keys
case _ =>
val emptyPartitionKeys = Array.empty[String]
buffered.map { deserializedRow =>
mutablePair.update(deserializedRow, emptyPartitionKeys)
}
}
rowsAndPartitionKeys.map { pair =>
var i = 0
while (i < attributes.length) {
mutableRow(i) = attributeFunctions(i)(pair._1, pair._2)
i += 1
}
mutableRow: Row
}
}
}
}
override def output = attributes
}
|
# webcam=$(system_profiler SPCameraDataType | grep Live\ Streamer | sed 's/://' | sed 's/ //')
webcam=$(system_profiler SPCameraDataType | grep Logitech\ Webcam\ C930e | sed 's/://' | sed 's/ //')
delay=1
if [ -z "$webcam" ]; then
webcam="FaceTime HD Camera (Built-in)"
fi
export WEBCAM=$webcam
export LOL_DELAY=$delay
export LOLCOMMITS_DEVICE=$webcam
|
<filename>src/main/java/com/shimizukenta/hokuyoopticalparallel/dme/DME.java
package com.shimizukenta.hokuyoopticalparallel.dme;
import java.io.IOException;
import java.net.SocketAddress;
import java.net.StandardSocketOptions;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.DatagramChannel;
import java.util.Arrays;
import java.util.Collection;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import com.shimizukenta.hokuyoopticalparallel.AbstractHokuyoOpticalParallel;
import com.shimizukenta.hokuyoopticalparallel.CommunicateStateChangeListener;
import com.shimizukenta.hokuyoopticalparallel.IOLog;
/**
* This class is implements DME-Communicating, open/close, send/receive.
*
* @author kenta-shimizu
*
*/
public final class DME extends AbstractHokuyoOpticalParallel<DMEReceivePacket, Boolean> {
private final ExecutorService execServ = Executors.newCachedThreadPool(r -> {
Thread th = new Thread(r);
th.setDaemon(true);
return th;
});
private Collection<DatagramChannel> channels = new CopyOnWriteArrayList<>();
private final DMEConfig config;
private boolean opened;
private boolean closed;
private boolean lastCommunicateState;
public DME(DMEConfig config) {
super();
this.config = config;
this.opened = false;
this.closed = false;
this.lastCommunicateState = false;
}
/**
* Create new instance and open.
*
* @param config
* @return DME instance
* @throws IOException
*/
public static DME open(DMEConfig config) throws IOException {
final DME inst = new DME(config);
try {
inst.open();
}
catch ( IOException e ) {
try {
inst.close();
}
catch ( IOException giveup ) {
}
throw e;
}
return inst;
}
@Override
public void open() throws IOException {
synchronized ( this ) {
if ( this.closed ) {
throw new IOException("Already closed");
}
if ( this.opened ) {
throw new IOException("Already opened");
}
this.opened = true;
}
execServ.execute(this.createWriteBytesQueueTask());
execServ.execute(this.createReceivePacketQueueTask());
execServ.execute(this.createOpenChannelTask());
}
@Override
public void close() throws IOException {
synchronized ( this ) {
if ( this.closed ) {
return ;
}
this.closed = true;
}
try {
execServ.shutdown();
if ( ! execServ.awaitTermination(1L, TimeUnit.MILLISECONDS ) ) {
execServ.shutdownNow();
if ( ! execServ.awaitTermination(5L, TimeUnit.SECONDS ) ) {
throw new IOException("ExecutorService#shutdown failed");
}
}
}
catch ( InterruptedException ignore ) {
}
}
@Override
public void write(byte[] bs) throws IOException {
final int bufferSize = bs.length;
for ( DatagramChannel channel : channels ) {
for ( SocketAddress remote : config.connects() ) {
final ByteBuffer buffer = ByteBuffer.allocate(bufferSize);
buffer.put(bs);
((Buffer)buffer).flip();
while ( buffer.hasRemaining() ) {
int w = channel.send(buffer, remote);
if ( w <= 0 ) {
break;
}
}
}
}
}
@Override
public boolean addCommunicateStateChangeListener(CommunicateStateChangeListener<Boolean> l) {
synchronized ( this ) {
l.changed(this.lastCommunicateState);
return super.addCommunicateStateChangeListener(l);
}
}
private void changeCommunicateState() {
boolean f = ! this.channels.isEmpty();
if ( f != this.lastCommunicateState ) {
this.lastCommunicateState = f;
putCommunicateStateChanged(f);
}
}
private void addChannel(DatagramChannel channel) {
synchronized ( this ) {
this.channels.add(channel);
changeCommunicateState();
}
}
private void clearChannel() {
synchronized ( this ) {
this.channels.clear();
changeCommunicateState();
}
}
private static interface InterruptableRunnable {
public void run() throws InterruptedException;
}
private Runnable createLoopTask(InterruptableRunnable r) {
return new Runnable() {
@Override
public void run() {
try {
for ( ;; ) {
r.run();
}
}
catch ( InterruptedException ignore ) {
}
}
};
}
private Runnable createOpenChannelTask() {
return createLoopTask(() -> {
try {
final SocketAddress local = config.bindSocketAddress()
.orElseThrow(() -> new IOException("Bind-Address not setted"));
try (
DatagramChannel channel = DatagramChannel.open();
) {
channel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
channel.bind(local);
addChannel(channel);
final String localAddrString = channel.getLocalAddress().toString();
final Collection<Callable<Object>> tasks = Arrays.asList(
this.createReadingTask(channel),
() -> {
try {
synchronized ( this ) {
channel.wait();
}
}
catch ( InterruptedException ignore ) {
}
return null;
});
try {
putOpenedLog(localAddrString);
execServ.invokeAny(tasks);
}
catch (ExecutionException e ) {
putIOLog(e.getCause());
}
finally {
putClosedLog(localAddrString);
}
}
finally {
clearChannel();
}
}
catch ( IOException e ) {
putIOLog(e);
}
{
long t = (long)(config.rebindSeconds() * 1000.0F);
if ( t > 0 ) {
TimeUnit.MILLISECONDS.sleep(t);
}
}
});
}
private Callable<Object> createReadingTask(DatagramChannel channel) {
return new Callable<Object>() {
@Override
public Object call() {
final Collection<Inner> inners = config.connects().stream()
.map(a -> new Inner(a))
.collect(Collectors.toList());
final ByteBuffer buffer = ByteBuffer.allocate(1024);
try {
for ( ;; ) {
((Buffer)buffer).clear();
SocketAddress remote = channel.receive(buffer);
((Buffer)buffer).flip();
byte[] bs = new byte[buffer.remaining()];
buffer.get(bs);
for ( Inner i : inners ) {
i.put(bs, remote);
}
}
}
catch ( InterruptedException ignore ) {
}
catch ( ClosedChannelException ignore ) {
}
catch ( IOException e ) {
putIOLog(e);
}
return null;
}
};
}
private static final byte LF = (byte)0xA;
private class Inner {
private final ByteBuffer buffer = ByteBuffer.allocate(DMEReceivePacket.DataSize);
private final SocketAddress refAddr;
private Inner(SocketAddress remote) {
this.refAddr = remote;
}
private void put(byte[] bs, SocketAddress remote) throws InterruptedException {
if ( remote != null && refAddr.equals(remote) ) {
for ( byte b : bs ) {
if ( buffer.hasRemaining() ) {
buffer.put(b);
} else {
if (b == LF) {
((Buffer)buffer).flip();
byte[] bb = new byte[buffer.remaining()];
buffer.get(bb);
((Buffer)buffer).clear();
DMEReceivePacket p = new DMEReceivePacket(bb, remote);
if ( p.isR() ) {
recvPacketQueue.put(p);
}
putReceivedLog(p);
}
}
}
}
}
}
private final BlockingQueue<DMEReceivePacket> recvPacketQueue = new LinkedBlockingQueue<>();
private Runnable createReceivePacketQueueTask() {
return createLoopTask(() -> {
putReceiveData(recvPacketQueue.take());
});
}
private final BlockingQueue<byte[]> writeBytesQueue = new LinkedBlockingQueue<>();
private Runnable createWriteBytesQueueTask() {
return createLoopTask(() -> {
byte[] bs = writeBytesQueue.take();
try {
write(bs);
}
catch ( ClosedChannelException ignore ) {
}
catch ( IOException e ) {
putIOLog(e);
}
TimeUnit.MILLISECONDS.sleep(20L);
});
}
/**
* Send Input Data.
*
* @param packet
* @throws InterruptedException
*/
public void send(DMESendPacket packet) throws InterruptedException {
putTrySendLog(packet);
writeBytesQueue.put(packet.getBytes());
}
/**
* Send Input Data.
*
* @param input
* @throws InterruptedException
*/
public void send(DMEInputData input) throws InterruptedException {
send(DMESendPacket.from(input));
}
/**
* Send Input Data.
*
* @param inputs
* @throws InterruptedException
*/
public void send(DMEInput... inputs) throws InterruptedException {
send(DMESendPacket.from(inputs));
}
/**
* Send Mode Data.
*
* @param packet
* @throws InterruptedException
*/
public void send(DMEModePacket packet) throws InterruptedException {
putTrySendLog(packet);
writeBytesQueue.put(packet.getBytes());
}
/**
* Send Mode Data.
*
* @param mode
* @throws InterruptedException
*/
public void send(DMEModeData mode) throws InterruptedException {
send(DMEModePacket.from(mode));
}
/**
* Send Mode Data.
*
* @param modes
* @throws InterruptedException
*/
public void send(DMEMode... modes) throws InterruptedException {
send(DMEModePacket.from(modes));
}
private void putOpenedLog(Object value) {
putIOLog(new IOLog("opened", value));
}
private void putClosedLog(Object value) {
putIOLog(new IOLog("closed", value));
}
private void putReceivedLog(Object value) {
putIOLog(new IOLog("received", value));
}
private void putTrySendLog(Object value) {
putIOLog(new IOLog("try-send", value));
}
}
|
import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { ActivatedRoute, Router } from '@angular/router';
import { ErrorHandlerService } from '../../services/error-handler.service';
import { AlertifyService } from '../../services/alertify.service';
import { ApiUserService } from '../../services/api-user.service';
@Component({
selector: 'app-user-detail',
templateUrl: './user-detail.component.html',
styleUrls: ['./user-detail.component.css'],
providers: [ApiUserService,AlertifyService,ErrorHandlerService],
encapsulation: ViewEncapsulation.None
})
export class UserDetailComponent implements OnInit {
user = {};
constructor(private handler: ErrorHandlerService, private userservice: ApiUserService, private router: Router, private route: ActivatedRoute, private http: HttpClient, private alertify: AlertifyService) { }
ngOnInit() {
this.getUserDetail(this.route.snapshot.params['id']);
}
getUserDetail(id) {
this.userservice.getUser(id)
.subscribe(user => {
this.user = user;
}, (err) => {
this.handler.handleError(err);
console.log(err);
});
}
deleteUser(id) {
this.alertify.confirm(
'Delete user', 'Are you sure to delete it?',
() => {
this.userservice.deleteUser(id)
.subscribe(res => {
this.router.navigate(['/users']);
}, (err) => {
this.handler.handleError(err);
console.log(err);
});
});
}
}
|
#ifndef _WINDMILL_MAN_H_
#define _WINDMILL_MAN_H_
#include "z3D/z3D.h"
void EnFu_rUpdate(Actor* thisx, GlobalContext* globalCtx);
#endif //_WINDMILL_MAN_H_
|
#!/bin/bash
# TODO(deklerk) Add integration tests when it's secure to do so. b/64723143
# Fail on any error
set -eo pipefail
# Display commands being run
set -x
# cd to project dir on Kokoro instance
cd git/google-api-go-client
go version
# Set $GOPATH
export GOPATH="$HOME/go"
export GOCLOUD_HOME=$GOPATH/src/google.golang.org/api/
export PATH="$GOPATH/bin:$PATH"
mkdir -p $GOCLOUD_HOME
# Move code into $GOPATH and get dependencies
git clone . $GOCLOUD_HOME
cd $GOCLOUD_HOME
try3() { eval "$*" || eval "$*" || eval "$*"; }
download_deps() {
if [[ `go version` == *"go1.11"* ]] || [[ `go version` == *"go1.12"* ]]; then
export GO111MODULE=on
# All packages, including +build tools, are fetched.
try3 go mod download
else
# Because we don't provide -tags tools, the +build tools
# dependencies aren't fetched.
try3 go get -v -t ./...
fi
}
download_deps
./internal/kokoro/vet.sh
# Run tests and tee output to log file, to be pushed to GCS as artifact.
go test -race -v -short ./... 2>&1 | tee $KOKORO_ARTIFACTS_DIR/$KOKORO_GERRIT_CHANGE_NUMBER.txt
|
#!/bin/bash
# Function to handle errors
handle_error() {
echo "Error occurred during build process. Exiting."
exit 1
}
# Install dependencies using npm
npm install || handle_error
# Display build completion message
echo "******** build end ******" |
<reponame>sunlightlabs/regulations-scraper
from fabric.api import *
from ssh_util import *
from collections import OrderedDict
import os, sys, json, datetime
VERBOSE = False
TASKS_ALWAYS = [
('local', ['rdg_scrape']),
('local', ['rdg_download']),
('local', ['extract']),
('local', ['create_dockets']),
('local', ['rdg_scrape_dockets']),
('local', ['match_text']),
('local', ['add_to_search']),
]
TASK_SETS = {
'major': [
('local', ['rdg_dump_api']),
('local', ['rdg_parse_api']),
] + TASKS_ALWAYS + [
('local', ['run_aggregates', '-A']),
('remote', ['analyze_regs', '-F']),
],
'minor': [
('local', ['rdg_simple_update']),
] + TASKS_ALWAYS + [
('local', ['run_aggregates']),
('remote', ['analyze_regs', '-F']),
]
}
ADMINS = []
EMAIL_SENDER = ''
EMAIL_API_KEY = ''
LOCK_DIR = '/tmp'
LOG_DIR = '/var/log/scrape'
try:
from local_settings import *
except:
pass
def send_email(recipients, subject, message):
from postmark import PMMail
message = PMMail(
to = ','.join(recipients),
subject = '[regs] %s' % subject,
text_body = message,
api_key = EMAIL_API_KEY,
sender = EMAIL_SENDER
)
message.send(test=False)
def run_local(command):
os.chdir(os.path.expanduser('~/regulations-scraper/regscrape'))
out = local(' '.join([sys.executable, command]), capture=True)
return out
def run_remote(command):
with cd('~/sparerib'):
with prefix('source ~/.virtualenvs/sparerib_pypy/bin/activate'):
return run(command)
def handle_completion(message, results):
output = '%s\nComplete results:\n%s' % (message, json.dumps(results, indent=4))
print output
if ADMINS:
send_email(ADMINS, message, output)
def acquire_lock():
lock_path = os.path.join(LOCK_DIR, 'regs.lock')
if os.path.exists(lock_path):
raise RuntimeError("Can't acquire lock.")
else:
lock = open(lock_path, 'w')
lock.write(str(os.getpid()))
lock.close()
def release_lock():
lock_path = os.path.join(LOCK_DIR, 'regs.lock')
os.unlink(lock_path)
@hosts(ssh_config('regs-fe'))
def run_regs(start_with=None, end_with=None, task_set=None):
try:
# use a lock file to keep multiple instances from trying to run simultaneously, which, among other things, consumes all of the memory on the high-CPU instance
acquire_lock()
except:
print 'Unable to acquire lock.'
if ADMINS:
send_email(ADMINS, "Aborting: can't acquire lock", "Can't start processing due to inability to acquire lock.")
sys.exit(1)
# get some logging stuff ready
now = datetime.datetime.now()
today = now.date().isoformat()
month = today.rsplit('-', 1)[0]
month_log_path = os.path.join(LOG_DIR, month)
if not os.path.exists(month_log_path):
os.mkdir(month_log_path)
if not (task_set and task_set in TASK_SETS):
# is it Sunday?
is_sunday = now.weekday() == 6
# have we run already today?
run_already = len([log_file for log_file in os.listdir(month_log_path) if log_file.startswith(today)]) > 0
if is_sunday and not run_already:
task_set = 'major'
else:
task_set = 'minor'
all_tasks = TASK_SETS[task_set]
print 'Starting task set "%s"...' % task_set
start_with = start_with if start_with is not None else all_tasks[0][1][0]
end_with = end_with if end_with is not None else all_tasks[-1][1][0]
first_task_idx = [i for i in range(len(all_tasks)) if all_tasks[i][1][0] == start_with][0]
last_task_idx = [i for i in range(len(all_tasks)) if all_tasks[i][1][0] == end_with][0]
tasks = all_tasks[first_task_idx:(last_task_idx+1)]
runners = {
'remote': run_remote,
'local': run_local
}
results = OrderedDict()
for func, command in tasks:
try:
output = runners[func](' '.join(['./run.py' if func == 'local' else './manage.py'] + command + ['--parsable']))
try:
results[command[0]] = json.loads(output)
except ValueError:
results[command[0]] = {'raw_results': output}
if VERBOSE and ADMINS:
send_email(ADMINS, 'Results of %s' % command[0], 'Results of %s:\n%s' % (command[0], json.dumps(results[command[0]], indent=4)))
except SystemExit:
results[command[0]] = 'failed'
handle_completion('Aborting at step: %s' % command[0], results)
if command[0] == "rdg_simple_update":
release_lock()
sys.exit(1)
handle_completion('All steps completed.', results)
logfile = open(os.path.join(month_log_path, now.isoformat() + ".json"), "w")
logfile.write(json.dumps(results, indent=4))
logfile.close()
release_lock()
|
<reponame>trith/trith<filename>lib/trith/reader.rb
module Trith
##
# The Trith code parser.
#
# @see http://sxp.rubyforge.org/
class Reader
##
# @param [String, #to_s] url
# @param [Hash{Symbol => Object}] options
# @return [Enumerable<Object>]
def self.read_url(url, options = {})
SXP.read_url(url, options)
end
##
# @param [Enumerable<String>] filenames
# @param [Hash{Symbol => Object}] options
# @return [Enumerable<Object>]
def self.read_files(*filenames)
SXP.read_files(*filenames)
end
##
# @param [String, #to_s] filename
# @param [Hash{Symbol => Object}] options
# @return [Enumerable<Object>]
def self.read_file(filename, options = {})
SXP.read_file(filename, options)
end
##
# @param [IO, StringIO, String] input
# @param [Hash{Symbol => Object}] options
# @return [Enumerable<Object>]
def self.read_all(input, options = {})
SXP.read_all(input, options)
end
##
# @param [IO, StringIO, String] input
# @param [Hash{Symbol => Object}] options
# @return [Object]
def self.read(input, options = {})
SXP.read(input, options)
end
# Prevent the instantiation of this class:
private_class_method :new
end # class Reader
end # module Trith
|
<gh_stars>0
import { Args, PLSArg, Remap } from "./Args";
import { Parser } from "./parser/Parser";
import { CompilerGLSL } from "./compiler/glsl/CompilerGLSL";
import { Resource, ShaderResources } from "./compiler/ShaderResources";
import { Compiler } from "./compiler/Compiler";
import { inherit_combined_sampler_bindings, rename_interface_variable } from "./utils/util";
import { PlsRemap } from "./compiler/glsl/PlsRemap";
import { ExecutionModel } from "./spirv/ExecutionModel";
import { Decoration } from "./spirv/Decoration";
import { StorageClass } from "./spirv/StorageClass";
import { Dict } from "./utils/Dict";
function stage_to_execution_model(stage: string): ExecutionModel
{
if (stage === "vert")
return ExecutionModel.Vertex;
else if (stage === "frag")
return ExecutionModel.Fragment;
/*else if (stage === "comp")
return ExecutionModel.GLCompute;
else if (stage === "tesc")
return ExecutionModel.TessellationControl;
else if (stage === "tese")
return ExecutionModel.TessellationEvaluation;
else if (stage === "geom")
return ExecutionModel.Geometry;*/
else
throw new Error("Invalid stage!");
}
export function compile_iteration(args: Args, spirv_file: Uint32Array, unnamedUBOInfo: Dict<string[]>): string
{
const spirv_parser = new Parser(spirv_file);
spirv_parser.parse();
const combined_image_samplers: boolean = true;
const build_dummy_sampler = false;
const compiler = new CompilerGLSL(spirv_parser.get_parsed_ir());
compiler.unnamed_ubo_info = unnamedUBOInfo;
if (args.variable_type_remaps.length !== 0)
{
const remap_cb = (type, name) => {
for (let remap of args.variable_type_remaps)
if (name === remap.variable_name)
return remap.new_variable_type;
return name;
};
compiler.set_variable_type_remap_callback(remap_cb);
}
for (let masked of args.masked_stage_outputs)
compiler.mask_stage_output_by_location(masked.first, masked.second);
for (let masked of args.masked_stage_builtins)
compiler.mask_stage_output_by_builtin(masked);
for (let rename of args.entry_point_rename)
compiler.rename_entry_point(rename.old_name, rename.new_name, rename.execution_model);
const entry_points = compiler.get_entry_points_and_stages();
let entry_point = args.entry;
let model = ExecutionModel.Max;
if (args.entry_stage && args.entry_stage.length > 0)
{
model = stage_to_execution_model(args.entry_stage);
if (!entry_point || entry_point === "")
{
// Just use the first entry point with this stage.
for (let e of entry_points) {
if (e.execution_model === model)
{
entry_point = e.name;
break;
}
}
if (!entry_point)
{
throw new Error(`Could not find an entry point with stage: ${args.entry_stage}`);
}
}
else
{
// Make sure both stage and name exists.
let exists = false;
for (let e of entry_points)
{
if (e.execution_model === model && e.name === entry_point)
{
exists = true;
break;
}
}
if (!exists)
{
throw new Error(`Could not find an entry point %s with stage: ${args.entry_stage}`);
}
}
}
else if (entry_point && entry_point !== "")
{
// Make sure there is just one entry point with this name, or the stage
// is ambiguous.
let stage_count = 0;
for (let e of entry_points)
{
if (e.name === entry_point)
{
stage_count++;
model = e.execution_model;
}
}
if (stage_count === 0)
{
throw new Error(`There is no entry point with name: ${entry_point}`);
}
else if (stage_count > 1)
{
throw new Error(`There is more than one entry point with name: ${entry_point}. Use --stage.`);
}
}
if (entry_point && entry_point !== "")
compiler.set_entry_point(entry_point, model);
if (!args.set_version && !compiler.get_common_options().version)
{
throw new Error("Didn't specify GLSL version and SPIR-V did not specify language.");
}
const opts = compiler.get_common_options();
if (args.set_version)
opts.version = args.version;
// if (args.set_es)
// opts.es = args.es;
opts.force_temporary = args.force_temporary;
opts.separate_shader_objects = args.sso;
opts.flatten_multidimensional_arrays = args.flatten_multidimensional_arrays;
opts.enable_420pack_extension = args.use_420pack_extension;
opts.vertex.fixup_clipspace = args.fixup;
opts.vertex.flip_vert_y = args.yflip;
opts.vertex.support_nonzero_base_instance = args.support_nonzero_baseinstance;
opts.emit_push_constant_as_uniform_buffer = args.glsl_emit_push_constant_as_ubo;
opts.emit_uniform_buffer_as_plain_uniforms = args.glsl_emit_ubo_as_plain_uniforms;
opts.force_flattened_io_blocks = args.glsl_force_flattened_io_blocks;
opts.keep_unnamed_ubos = args.glsl_keep_unnamed_ubos;
opts.remove_attribute_layouts = args.glsl_remove_attribute_layouts;
opts.preprocess_spec_const = args.preprocess_spec_const;
opts.specialization_constant_prefix = args.specialization_constant_prefix;
opts.ovr_multiview_view_count = args.glsl_ovr_multiview_view_count;
opts.emit_line_directives = args.emit_line_directives;
opts.enable_storage_image_qualifier_deduction = args.enable_storage_image_qualifier_deduction;
opts.force_zero_initialized_variables = args.force_zero_initialized_variables;
for (let fetch of args.glsl_ext_framebuffer_fetch)
compiler.remap_ext_framebuffer_fetch(fetch.first, fetch.second, !args.glsl_ext_framebuffer_fetch_noncoherent);
if (build_dummy_sampler)
{
const sampler = compiler.build_dummy_sampler_for_combined_images();
if (sampler !== 0)
{
// Set some defaults to make validation happy.
compiler.set_decoration(sampler, Decoration.DescriptorSet, 0);
compiler.set_decoration(sampler, Decoration.Binding, 0);
}
}
let res: ShaderResources;
if (args.remove_unused)
{
const active = compiler.get_active_interface_variables();
res = compiler.get_shader_resources(active);
compiler.set_enabled_interface_variables(active);
}
else
res = compiler.get_shader_resources();
if (args.flatten_ubo)
{
for (let ubo of res.uniform_buffers)
compiler.flatten_buffer_block(ubo.id);
for (let ubo of res.push_constant_buffers)
compiler.flatten_buffer_block(ubo.id);
}
const pls_inputs = remap_pls(args.pls_in, res.stage_inputs, res.subpass_inputs);
const pls_outputs = remap_pls(args.pls_out, res.stage_outputs, null);
compiler.remap_pixel_local_storage(pls_inputs, pls_outputs);
for (let ext of args.extensions)
compiler.require_extension(ext);
for (let remap of args.remaps)
{
if (remap_generic(compiler, res.stage_inputs, remap))
continue;
if (remap_generic(compiler, res.stage_outputs, remap))
continue;
if (remap_generic(compiler, res.subpass_inputs, remap))
continue;
}
for (let rename of args.interface_variable_renames)
{
if (rename.storageClass === StorageClass.Input)
rename_interface_variable(compiler, res.stage_inputs, rename.location, rename.variable_name);
else if (rename.storageClass === StorageClass.Output)
rename_interface_variable(compiler, res.stage_outputs, rename.location, rename.variable_name);
else
{
throw new Error("error at --rename-interface-variable <in|out> ...");
}
}
if (combined_image_samplers)
{
compiler.build_combined_image_samplers();
if (args.combined_samplers_inherit_bindings)
inherit_combined_sampler_bindings(compiler);
// Give the remapped combined samplers new names.
for (let remap of compiler.get_combined_image_samplers())
{
compiler.set_name(remap.combined_id, "SPIRV_Cross_Combined" + compiler.get_name(remap.image_id) +
compiler.get_name(remap.sampler_id));
}
}
const ret = compiler.compile();
/*if (args.dump_resources)
{
compiler->update_active_builtins();
print_resources(*compiler, res);
print_push_constant_resources(*compiler, res.push_constant_buffers);
print_spec_constants(*compiler);
print_capabilities_and_extensions(*compiler);
}*/
return ret;
}
function remap_generic(compiler: Compiler, resources: Resource[], remap: Remap): boolean
{
const elm = resources.find(res => { return res.name === remap.src_name; });
if (elm)
{
compiler.set_remapped_variable_state(elm.id, true);
compiler.set_name(elm.id, remap.dst_name);
compiler.set_subpass_input_remapped_components(elm.id, remap.components);
return true;
}
else
return false;
}
function remap_pls(pls_variables: PLSArg[], resources: Resource[], secondary_resources: Resource[]): PlsRemap[]
{
const ret: PlsRemap[] = [];
for (let pls of pls_variables)
{
let found = false;
for (let res of resources)
{
if (res.name === pls.name)
{
ret.push(new PlsRemap(res.id, pls.format));
found = true;
break;
}
}
if (!found && secondary_resources)
{
for (let res of secondary_resources)
{
if (res.name === pls.name)
{
ret.push(new PlsRemap(res.id, pls.format));
found = true;
break;
}
}
}
if (!found)
throw new Error(`Did not find stage input/output/target with name ${pls.name}`);
}
return ret;
}
|
<reponame>laerciocrestani/br_nfe<filename>test/factories/product/nfe/item_tax/cofins.rb
FactoryGirl.define do
factory :product_item_tax_cofins, class: BrNfe::Product::Nfe::ItemTax::Cofins do
codigo_cst '04'
end
end |
package bd.edu.daffodilvarsity.classmanager.fragments;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
import bd.edu.daffodilvarsity.classmanager.R;
import bd.edu.daffodilvarsity.classmanager.otherclasses.ClassDetails;
import bd.edu.daffodilvarsity.classmanager.otherclasses.HelperClass;
import bd.edu.daffodilvarsity.classmanager.otherclasses.RoutineObj;
import timber.log.Timber;
/**
* A simple {@link Fragment} subclass.
*/
public class AddNewClassDetails extends Fragment implements View.OnClickListener {
private EditText courseCode;
private EditText roomNo;
private EditText courseName;
private EditText priority;
private EditText time;
private EditText teacherInitial;
private Spinner shift;
private Spinner dayOfWeek;
private Spinner section;
public AddNewClassDetails() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_add_new_class_details, container, false);
initializeVariables(view);
initializeSpinners();
return view;
}
private void initializeVariables(View view) {
view.findViewById(R.id.add_data).setOnClickListener(this);
courseCode = view.findViewById(R.id.course_code);
courseName = view.findViewById(R.id.course_name);
courseCode.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
courseName.setText(HelperClass.getCourseNameFromCourseCode(shift.getSelectedItem().toString(),String.valueOf(charSequence)));
}
@Override
public void afterTextChanged(Editable editable) {
}
});
roomNo = view.findViewById(R.id.room_no);
teacherInitial = view.findViewById(R.id.teacher_initial);
time = view.findViewById(R.id.time);
priority = view.findViewById(R.id.priority);
shift = view.findViewById(R.id.shift);
dayOfWeek = view.findViewById(R.id.day_of_week);
section = view.findViewById(R.id.section_spinner);
}
private void initializeSpinners() {
String[] shift = new String[]{"Day","Evening"};
String[] section = HelperClass.getAllSections();
String[] dayOfWeek = HelperClass.getSevenDaysOfWeek().toArray(new String[HelperClass.getSixDaysOfWeek().size()]);
ArrayAdapter shiftAdapter = new ArrayAdapter(getContext(),android.R.layout.simple_spinner_item,shift);
ArrayAdapter sectionAdapter = new ArrayAdapter(getContext(),android.R.layout.simple_spinner_item,section);
ArrayAdapter dayOfWeekAdapter = new ArrayAdapter(getContext(),android.R.layout.simple_spinner_item,dayOfWeek);
shiftAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sectionAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
dayOfWeekAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
this.section.setAdapter(sectionAdapter);
this.dayOfWeek.setAdapter(dayOfWeekAdapter);
this.shift.setAdapter(shiftAdapter);
}
private void checkAndAddData() {
final ClassDetails cd = new ClassDetails();
if (courseCode.getText().toString().trim().isEmpty() || courseName.getText().toString().trim().isEmpty() || priority.getText().toString().trim().isEmpty() || roomNo.getText().toString().trim().isEmpty() || time.getText().toString().trim().isEmpty() || teacherInitial.getText().toString().trim().isEmpty()) {
makeToast("Please fill all fields.");
return;
} else {
cd.setCourseCode(courseCode.getText().toString().trim());
cd.setCourseName(courseName.getText().toString().trim());
cd.setPriority(Float.parseFloat(priority.getText().toString().trim()));
cd.setRoom(roomNo.getText().toString().trim());
cd.setTime(time.getText().toString().trim());
cd.setTeacherInitial(teacherInitial.getText().toString().trim());
cd.setSection(section.getSelectedItem().toString());
cd.setDayOfWeek(dayOfWeek.getSelectedItem().toString().trim());
cd.setShift(shift.getSelectedItem().toString().trim());
}
DocumentReference docRef = FirebaseFirestore.getInstance().document("/routine/routine/");
docRef.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
@Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
RoutineObj routime = documentSnapshot.toObject(RoutineObj.class);
if (cd.getShift().equals(HelperClass.SHIFT_DAY)) {
String jsonRoutineDay = routime.getDay();
ArrayList<ClassDetails> classes = parseFromJson(jsonRoutineDay);
classes.add(cd);
showAlertDialog("Are you sure?","Please double check before adding a new class.",classes);
} else {
if (cd.getShift().equals(HelperClass.SHIFT_DAY)) {
String jsonRoutineEve = routime.getEvening();
ArrayList<ClassDetails> classes = parseFromJson(jsonRoutineEve);
classes.add(cd);
showAlertDialog("Are you sure?","Please double check before adding a new class.",classes);
}
}
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Timber.e(e);
makeToast("Failed to load.\nPlease check your connection.");
}
});
}
private void updateClasses(String shift,String classes) {
DocumentReference docRef = FirebaseFirestore.getInstance().document("/routine/routine/");
docRef.update(shift,classes).addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
makeToast("Added Successfully.");
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
makeToast("Failed to add.\nPlease check your connection.");
}
});
}
private ArrayList<ClassDetails> parseFromJson(String json) {
Type type = new TypeToken<ArrayList<ClassDetails>>(){}.getType();
Gson gson = new Gson();
return gson.fromJson(json,type);
}
private String parseToJson(ArrayList<ClassDetails> classes) {
Gson gson = new Gson();
return gson.toJson(classes);
}
private void showAlertDialog(String title, String body, final ArrayList<ClassDetails> classes) {
AlertDialog alertDialog = new AlertDialog.Builder(getContext())
.setTitle(title)
.setMessage(body)
.setPositiveButton("Proceed", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
updateClasses("day",parseToJson(classes));
}
})
.setNegativeButton("Cancel",null)
.create();
alertDialog.show();
}
@Override
public void onClick(View view) {
if (view.getId() == R.id.add_data) {
checkAndAddData();
}
}
private void makeToast(String text) {
if (getContext() != null) {
Toast.makeText(getContext(), text, Toast.LENGTH_SHORT).show();
}
}
}
|
#!/usr/bin/env bash
clear
my_dir="$(dirname "$0")"
. $my_dir/set_env.sh
echo "MMAR_ROOT set to $MMAR_ROOT"
additional_options="$*"
AUTOML_DIR_NAME=$1
########################################### check on arguments
if [[ -z $AUTOML_DIR_NAME ]] ;then
AUTOML_DIR_NAME=trn_autoML
fi
########################################### check on arguments
TRAIN_CONFIG=${AUTOML_DIR_NAME}.json
echo removing dir ${AUTOML_DIR_NAME}
rm -R $MMAR_ROOT/automl/${AUTOML_DIR_NAME}
python -u -m nvmidl.apps.automl.train \
-m $MMAR_ROOT \
--set \
run_id=${AUTOML_DIR_NAME} \
trainconf=${TRAIN_CONFIG} \
workers=0:0:0:0:0:0:0:0 \
traceout=console \
${additional_options}
# workers=0:1:2:3 \
# workers=0:0:0:0:0:0:0:0 \
|
#! /bin/bash
PRGNAME="file"
### File (a utility to determine file type)
# Утилита для определения типа файла
ROOT="/"
source "${ROOT}check_environment.sh" || exit 1
source "${ROOT}unpack_source_archive.sh" "${PRGNAME}" || exit 1
TMP_DIR="/tmp/pkg-${PRGNAME}-${VERSION}"
rm -rf "${TMP_DIR}"
mkdir -pv "${TMP_DIR}"
./configure \
--prefix=/usr || exit 1
make || make -j1 || exit 1
# make check
make install DESTDIR="${TMP_DIR}"
/bin/cp -vR "${TMP_DIR}"/* /
cat << EOF > "/var/log/packages/${PRGNAME}-${VERSION}"
# Package: ${PRGNAME} (a utility to determine file type)
#
# This is utility, used to identify files.
#
# Home page: https://www.darwinsys.com/file/
# Download: ftp://ftp.astron.com/pub/${PRGNAME}/${PRGNAME}-${VERSION}.tar.gz
#
EOF
source "${ROOT}write_to_var_log_packages.sh" \
"${TMP_DIR}" "${PRGNAME}-${VERSION}"
|
function makeData() {
"use strict";
var data = makeRandomData(100, 1e15);
// data.push({x: 0, y: 0});
return data;
}
function run(div, data, Plottable) {
"use strict";
// doesn't exist on master yet
if (Plottable.Scale.ModifiedLog == null) {
return;
}
var svg = div.append("svg").attr("height", 500);
var doAnimate = true;
var circleRenderer;
var xScale = new Plottable.Scale.Linear();
var xAxis = new Plottable.Axis.Numeric(xScale, "bottom");
var yScale = new Plottable.Scale.ModifiedLog();
var yAxis = new Plottable.Axis.Numeric(yScale, "left", new Plottable.Formatter.SISuffix());
yAxis.showEndTickLabel("top", false);
yAxis.showEndTickLabel("bottom", false);
circleRenderer = new Plottable.Plot.Scatter(xScale, yScale).addDataset(data);
circleRenderer.attr("r", 8);
circleRenderer.attr("opacity", 0.75);
circleRenderer.animate(doAnimate);
var gridlines = new Plottable.Component.Gridlines(xScale, yScale);
var circleChart = new Plottable.Component.Table([[yAxis, circleRenderer.merge(gridlines)],
[null, xAxis]]);
circleChart.renderTo(svg);
var cb = function(x, y){
d = circleRenderer.dataset().data();
circleRenderer.dataset().data(d);
};
circleRenderer.registerInteraction(
new Plottable.Interaction.Click().callback(cb)
);
}
|
# This script uses Autorest to generate service's client library
# == Prerequisites ==
# Nodejs version >= 6.11.2 - https://nodejs.org/en/download/
# NPM version >= 3.10.10 - https://www.npmjs.com/get-npm
# Autorest version >= 1.2.2 - https://www.npmjs.com/package/autorest
autorest --input-file=http://localhost:5000/swagger/v1/swagger.json --csharp --output-folder=AutorestClient --namespace=Lykke.Service.EthereumSamurai.AutorestClient |
<gh_stars>1-10
package com.modesteam.urutau.controller;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.easymock.EasyMock;
import org.junit.Before;
import org.junit.Test;
import com.modesteam.urutau.service.AdministratorService;
public class AdministratorCreatorFilterTest {
private final Logger logger = Logger.getLogger(AdministratorCreatorFilter.class);
private ServletRequest request;
private ServletResponse response;
private FilterChain chain;
private AdministratorService administratorService;
@Before
public void setUp() throws ServletException, IOException {
logger.setLevel(Level.DEBUG);
this.request = mock(ServletRequest.class);
this.response = mock(ServletResponse.class);
when(request.getRequestDispatcher("/administrator/createFirstAdministrator"))
.thenReturn(EasyMock.createMock(RequestDispatcher.class));
this.chain = mock(FilterChain.class);
this.administratorService = mock(AdministratorService.class);
}
@Test
public void doFilterWhenExistAdmin() throws IOException, ServletException {
AdministratorCreatorFilter filter = new AdministratorCreatorFilter();
when(administratorService.existAdministrator()).thenReturn(true);
doNothing().when(chain).doFilter(request, response);
filter.setAdministratorService(administratorService);
filter.doFilter(request, response, chain);
}
@Test
public void doFilterWhenNotExistAdmin() throws IOException, ServletException {
AdministratorCreatorFilter filter = new AdministratorCreatorFilter();
when(administratorService.existAdministrator()).thenReturn(false);
doNothing().when(chain).doFilter(request, response);
filter.setAdministratorService(administratorService);
filter.doFilter(request, response, chain);
}
}
|
<reponame>FelixRilling/logby<gh_stars>0
interface Level {
val: number;
name?: string;
}
export { Level };
|
<filename>src/logger.js
const log4js = require("log4js");
log4js.levels.addLevels({
NOTICE: { value: log4js.levels.getLevel("INFO").level + 1, colour: "green" },
});
const logger = log4js.getLogger();
logger.level = process.env.LOG_LEVEL || "debug";
module.exports = logger;
|
#!/bin/bash
# Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
set -e # Exit immediately when one of the commands fails.
# Prerequisites: The following envvars should be set when running this script.
# - ANDROID_HOME: Android SDK location (tested with Android SDK 29)
# - JAVA_HOME: Java SDK location (tested with Open JDK 8)
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null 2>&1 && pwd)"
EXAMPLES_DIR="$(realpath "${SCRIPT_DIR}/../examples")"
# Keep a list of blacklisted android apps directories which should be excluded
# from the builds.
# TODO(b/154114877): Restore smart_reply after resolving aapt_version build issues.
SKIPPED_BUILDS="
smart_reply/android
"
function build_android_example {
# Check if this directory appears in the skipped builds list.
RELATIVE_DIR="${1#"${EXAMPLES_DIR}/"}"
if echo "${SKIPPED_BUILDS}" | grep -qx "${RELATIVE_DIR}"; then
echo "WARNING: Skipping build for ${RELATIVE_DIR}."
return 0
fi
echo "=== BUILD STARTED: ${RELATIVE_DIR} ==="
pushd "$1" > /dev/null
# Check if the directory contains a gradle wrapper.
if [[ -x "$1/gradlew" ]]; then
# Run the "build" task with the gradle wrapper.
./gradlew clean build --stacktrace
elif [[ -x "$1/finish/gradlew" ]]; then
# Accommodate codelab directory
./finish/gradlew clean build --stacktrace
else
echo "ERROR: Gradle wrapper could not be found under ${RELATIVE_DIR}."
exit 1
fi
popd > /dev/null
echo "=== BUILD FINISHED: ${RELATIVE_DIR} ==="
echo
echo
}
build_android_example "$1"
|
#!/bin/bash
source common.sh
#here we can set what versions we want to clone
sh ./$1
#sh ./buildclone-estos6.3.sh
echo "3.1 kms-cmake-utils"
mkdir kms-cmake-utils-build
cd kms-cmake-utils-build/
mingw64-cmake ../kms-cmake-utils/
mingw64-make
pause
sudo mingw64-make install
cd ..
# getcmakemodules needs 'cd kms-cmake-utils'
getcmakemodules
pwd
pause
echo "3.20 glib"
cd glib/
./autogen.sh
mingw64-configure \
--disable-directsound --disable-direct3d \
--disable-examples --disable-gtk-doc --disable-winscreencap \
--disable-winks --disable-wasapi --disable-opencv
mingw64-make
pause
sudo mingw64-make install
cd ..
echo "3.2 kurento-module-creator"
cd kurento-module-creator/
make
pause
sudo make install
cd ..
echo "3.3 gstreamer-1.7.x/1.8.1 (Fork of github/kurento/gstreamer 06.06.2017"
cd gstreamer/
./autogen.sh ## Ignore configuration errors
mingw64-configure --disable-tools --disable-tests --disable-benchmarks --disable-examples --disable-debug --libexec=/usr/x86_64-w64-mingw32/sys-root/mingw/libexec
make
pause
sudo make install
cd ..
echo "3.4 gst-plugins-base-1.5"
cd gst-plugins-base/
./autogen.sh ## Ignore configuration errors
mingw64-configure --disable-debug
mingw64-make
pause
sudo mingw64-make install
cd ..
echo "3.5 jsoncpp"
mkdir jsoncpp-build
cd jsoncpp-build/
mingw64-cmake -DCMAKE_BUILD_TYPE=Release ../jsoncpp
mingw64-make
pause
sudo mingw64-make install
cd ..
echo "3.6 kms-jsonrpc"
mkdir kms-jsonrpc-build
cd kms-jsonrpc-build/
mingw64-cmake -DCMAKE_BUILD_TYPE=Release -DCMAKE_MODULE_PATH=$cmakemodules ../kms-jsonrpc
pause
sudo mingw64-make install
cd ..
echo "3.7 libvpx"
cd libvpx/
eval `rpm --eval %{mingw64_env}`
export AS=yasm
./configure --target=x86_64-win64-gcc --prefix=/usr/x86_64-w64-mingw32/sys-root/mingw/
mingw64-make
pause
sudo mingw64-make install
cd ..
echo "3.8 kms-core"
# if this is executed using root, cmake will not find the kurentocreator
if [[ $EUID == 0 ]]; then
echo "Build this step as root will lead to troubles later! (e.g. kurentocreator will not be found) Stop here now."
exit
fi
mkdir kms-core-build
cd kms-core-build/
mingw64-cmake -DCMAKE_BUILD_TYPE=Release -DCMAKE_MODULE_PATH=$cmakemodules -DCMAKE_INSTALL_PREFIX=/usr/x86_64-w64-mingw32/sys-root/mingw -DKURENTO_MODULES_DIR=/usr/x86_64-w64-mingw32/sys-root/mingw/share/kurento/modules/ ../kms-core
mingw64-make
pause
sudo mingw64-make install
cd ..
echo "3.9 libevent"
cd libevent/
./autogen.sh ## However, you should not build using configured Makefile
mingw64-configure
mingw64-make
pause
sudo mingw64-make install
cd ..
echo "3.10 kurento-media-server"
mkdir kurento-media-server-build
cd kurento-media-server-build/
mingw64-cmake -DCMAKE_BUILD_TYPE=Release -DCMAKE_MODULE_PATH=$cmakemodules ../kurento-media-server
mingw64-make
pause
sudo mingw64-make install
cd ..
echo "3.11 usersctp"
cd usrsctp/
./bootstrap
mingw64-configure
mingw64-make
pause
sudo mingw64-make install
cd ..
echo "3.12 openwebrtc-gst-plugins"
cd openwebrtc-gst-plugins/
./autogen.sh ## Ignore configuration errors
mingw64-configure
mingw64-make
pause
sudo mingw64-make install
sudo rm /usr/x86_64-w64-mingw32/sys-root/mingw/bin/libgstsctp-1.5.dll
sudo ln -s /usr/x86_64-w64-mingw32/sys-root/mingw/lib/libgstsctp-1.5.dll /usr/x86_64-w64-mingw32/sys-root/mingw/bin/libgstsctp-1.5.dll
cd ..
echo "3.13 libnice"
cd libnice/
./autogen.sh ## Ignore configuration errors
mingw64-configure
mingw64-make
pause
sudo mingw64-make install
cd ..
echo "3.14 kms-elements"
mkdir kms-elements-build
cd kms-elements-build/
mingw64-cmake -DCMAKE_BUILD_TYPE=Release -DCMAKE_MODULE_PATH=$cmakemodules -DCMAKE_INSTALL_PREFIX=/usr/x86_64-w64-mingw32/sys-root/mingw -DKURENTO_MODULES_DIR=/usr/x86_64-w64-mingw32/sys-root/mingw/share/kurento/modules/ ../kms-elements
mingw64-make
pause
sudo mingw64-make install
cd ..
echo "3.15 opencv"
cd opencv
mkdir ../opencv-build
cd ../opencv-build
mingw64-cmake \
-DBUILD_PERF_TESTS=false \
-DBUILD_TESTS=false \
-DWITH_DSHOW=false \
-DWITH_WIN32UI=false \
-DWITH_OPENCL=false \
-DWITH_VFW=false \
-DBUILD_ZLIB=false \
-DBUILD_TIFF=false \
-DBUILD_JASPER=false \
-DBUILD_JPEG=false \
-DBUILD_PNG=false \
-DBUILD_OPENEXR=false \
-DWITH_FFMPEG=false \
-DBUILD_opencv_flann=OFF \
-DBUILD_opencv_photo=OFF \
-DBUILD_opencv_video=OFF \
-DBUILD_opencv_ml=OFF \
../opencv
sed -i 's/-isystem\ \/usr\/x86_64-w64-mingw32\/sys-root\/mingw\/include/ /g' \
modules/core/CMakeFiles/opencv_core.dir/includes_CXX.rsp
sed -i 's/-isystem\ \/usr\/x86_64-w64-mingw32\/sys-root\/mingw\/include\ / /g' ./modules/highgui/CMakeFiles/opencv_highgui.dir/includes_CXX.rsp
mingw64-make
sudo mingw64-make install
sudo cp unix-install/opencv.pc /usr/x86_64-w64-mingw32/sys-root/mingw/lib/pkgconfig/
sudo rm /usr/x86_64-w64-mingw32/sys-root/mingw/lib/libopencv_core.a
sudo ln -s /usr/x86_64-w64-mingw32/sys-root/mingw/x64/mingw/lib/libopencv_core2413.dll.a \
/usr/x86_64-w64-mingw32/sys-root/mingw/lib/libopencv_core.a
sudo rm /usr/x86_64-w64-mingw32/sys-root/mingw/lib/libopencv_highgui.a
sudo ln -s /usr/x86_64-w64-mingw32/sys-root/mingw/x64/mingw/lib/libopencv_highgui2413.dll.a \
/usr/x86_64-w64-mingw32/sys-root/mingw/lib/libopencv_highgui.a
sudo rm /usr/x86_64-w64-mingw32/sys-root/mingw/lib/libopencv_imgproc.a
sudo ln -s /usr/x86_64-w64-mingw32/sys-root/mingw/x64/mingw/lib/libopencv_imgproc2413.dll.a \
/usr/x86_64-w64-mingw32/sys-root/mingw/lib/libopencv_imgproc.a
sudo rm /usr/x86_64-w64-mingw32/sys-root/mingw/lib/libopencv_objdetect.a
sudo ln -s /usr/x86_64-w64-mingw32/sys-root/mingw/x64/mingw/lib/libopencv_objdetect2413.dll.a \
/usr/x86_64-w64-mingw32/sys-root/mingw/lib/libopencv_objdetect.a
sudo rm /usr/x86_64-w64-mingw32/sys-root/mingw/bin/libopencv_core2413.dll
sudo rm /usr/x86_64-w64-mingw32/sys-root/mingw/bin/libopencv_highgui2413.dll
sudo rm /usr/x86_64-w64-mingw32/sys-root/mingw/bin/libopencv_imgproc2413.dll
sudo rm /usr/x86_64-w64-mingw32/sys-root/mingw/bin/libopencv_objdetect2413.dll
sudo ln -s /usr/x86_64-w64-mingw32/sys-root/mingw/x64/mingw/bin/libopencv_core2413.dll /usr/x86_64-w64-mingw32/sys-root/mingw/bin/libopencv_core2413.dll
sudo ln -s /usr/x86_64-w64-mingw32/sys-root/mingw/x64/mingw/bin/libopencv_highgui2413.dll /usr/x86_64-w64-mingw32/sys-root/mingw/bin/libopencv_highgui2413.dll
sudo ln -s /usr/x86_64-w64-mingw32/sys-root/mingw/x64/mingw/bin/libopencv_imgproc2413.dll /usr/x86_64-w64-mingw32/sys-root/mingw/bin/libopencv_imgproc2413.dll
sudo ln -s /usr/x86_64-w64-mingw32/sys-root/mingw/x64/mingw/bin/libopencv_objdetect2413.dll /usr/x86_64-w64-mingw32/sys-root/mingw/bin/libopencv_objdetect2413.dll
cd ..
echo "3.16 kms-filters"
mkdir kms-filters-build
cd kms-filters-build/
mingw64-cmake -DCMAKE_BUILD_TYPE=Release \
-DCMAKE_MODULE_PATH=$cmakemodules \
-DCMAKE_INSTALL_PREFIX=/usr/x86_64-w64-mingw32/sys-root/mingw \
-DKURENTO_MODULES_DIR=/usr/x86_64-w64-mingw32/sys-root/mingw/share/kurento/modules/ \
-DCMAKE_C_FLAGS="-Wno-error=deprecated-declarations" \
../kms-filters
mingw64-make
pause
sudo mingw64-make install
cd ..
echo "3.17 gst-plugins-good"
cd gst-plugins-good/
./autogen.sh
mingw64-configure \
--disable-wavpack --disable-valgrind --disable-directsound \
--disable-libcaca --disable-waveform \
--libexec=/usr/x86_64-w64-mingw32/sys-root/mingw/libexec \
--disable-debug --disable-gtk-doc --disable-examples
printf "all:\ninstall:\nclean:\nuninstall:\n" > tests/Makefile
mingw64-make
pause
sudo mingw64-make install
cd ..
echo "3.18 libsrtp"
cd libsrtp/
mingw64-configure
mingw64-make
pause
sudo mingw64-make install
cd ..
echo "3.19 gst-plugins-bad"
cd gst-plugins-bad/
./autogen.sh
mingw64-configure \
--disable-directsound --disable-direct3d --disable-debug \
--disable-examples --disable-gtk-doc --disable-winscreencap \
--disable-winks --disable-wasapi --disable-opencv
sed -i 's/\buint\b/unsigned/g' ext/opencv/gstmotioncells.cpp ## We may need this later
printf "all:\ninstall:\nclean:\nuninstall:\n" > tests/Makefile
mingw64-make
pause
sudo mingw64-make install
cd ..
#echo "3.21 gst-libav"
#cd gst-libav/
#./autogen.sh
#mingw64-configure \
# --disable-directsound --disable-direct3d \
# --disable-examples --disable-gtk-doc --disable-winscreencap \
# --disable-winks --disable-wasapi --disable-opencv
#printf "all:\ninstall:\nclean:\nuninstall:\n" > tests/Makefile
#mingw64-make
#pause
##sudo mingw64-make install
#cd ..
#echo "3.22 openssl"
#cd openssl/
#./Configure shared --cross-compile-prefix=x86_64-w64-mingw32- mingw64
#mingw64-make depend
#mingw64-make
#cp libeay32.dll libcrypto-10.dll
#cp ssleay32.dll libssl-10.dll
#pause
##sudo mingw64-make install
#cd ..
echo "BUILD DONE."
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
############## Input UTF-8 cases ##################
# See http://clagnut.com/blog/2380/ for list of pangrams
# Note: doesn't work goog for all languages (e.g. for Thai)
input_utf8_test_suite = {
"name": "Input UTF-8 tests",
"scenarios": [
{
"name": "String in chinese",
"args": ["-b", "basic", "--col-separator", "|"],
"input": '''\
視野無限廣|窗外有藍天
微風迎客,軟語伴茶|中国智造
''',
"output": u'''\
+--------------------+------------+
| 視野無限廣 | 窗外有藍天 |
| 微風迎客,軟語伴茶 | 中国智造 |
+--------------------+------------+
'''
},
{
"name": "String in french",
"args": ["-b", "basic", "--col-separator", "|"],
"input": '''\
Voyez le brick|géant que
j’examine près du|wharf
''',
"output": u'''\
+-------------------+-----------+
| Voyez le brick | géant que |
| j’examine près du | wharf |
+-------------------+-----------+
'''
},
{
"name": "String in german",
"args": ["-b", "basic", "--col-separator", "|"],
"input": '''\
<NAME> zwölf Boxkämpfer quer über den großen|Falsches Üben von Xylophonmusik quält jeden größeren Zwerg
Franz jagt im komplett verwahrlosten Taxi quer durch Bayern
''',
"output": u'''\
+-------------------------------------------------------------+------------------------------------------------------------+
| Victor jagt zwölf Boxkämpfer quer über den großen | Falsches Üben von Xylophonmusik quält jeden größeren Zwerg |
| Franz jagt im komplett verwahrlosten Taxi quer durch Bayern | |
+-------------------------------------------------------------+------------------------------------------------------------+
'''
},
{
"name": "String in greek",
"args": ["-b", "basic", "--col-separator", "|"],
"input": '''\
Ταχίστη αλώπηξ βαφής ψημένη γη|δρασκελίζει υπέρ νωθρού κυνός Takhístè alôpèx vaphês psèménè gè
Ξεσκεπάζω τὴν ψυχοφθόρα βδελυγμία|Xeskepazó tin psychofthóra vdelygmía
''',
"output": u'''\
+-----------------------------------+-----------------------------------------------------------------+
| Ταχίστη αλώπηξ βαφής ψημένη γη | δρασκελίζει υπέρ νωθρού κυνός Takhístè alôpèx vaphês psèménè gè |
| Ξεσκεπάζω τὴν ψυχοφθόρα βδελυγμία | Xeskepazó tin psychofthóra vdelygmía |
+-----------------------------------+-----------------------------------------------------------------+
'''
},
{
"name": "String in japanese",
"args": ["-b", "basic", "--col-separator", "|"],
"input": '''\
いろはにほへと ちりぬるを わかよ|たれそ つねならむ うゐのおくやま けふこ
色は匂へど 散りぬるを 我が世誰ぞ 常ならむ 有|為の奥山 今日越えて 浅き夢見じ 酔ひもせず
''',
"output": u'''\
+----------------------------------------------+-------------------------------------------+
| いろはにほへと ちりぬるを わかよ | たれそ つねならむ うゐのおくやま けふこ |
| 色は匂へど 散りぬるを 我が世誰ぞ 常ならむ 有 | 為の奥山 今日越えて 浅き夢見じ 酔ひもせず |
+----------------------------------------------+-------------------------------------------+
'''
},
{
"name": "String in korean",
"args": ["-b", "basic", "--col-separator", "|"],
"input": '''\
키스의|고유조건은 입술끼리
만나야 하고 특별한|기술은 필요치 않다
''',
"output": u'''\
+--------------------+---------------------+
| 키스의 | 고유조건은 입술끼리 |
| 만나야 하고 특별한 | 기술은 필요치 않다 |
+--------------------+---------------------+
'''
},
{
"name": "String in russian",
"args": ["-b", "basic", "--col-separator", "|"],
"input": '''\
Съешь же ещё|этих мягких французских булок
да выпей|чаю
''',
"output": u'''\
+--------------+-------------------------------+
| Съешь же ещё | этих мягких французских булок |
| да выпей | чаю |
+--------------+-------------------------------+
'''
},
]}
|
<filename>js/Column.js<gh_stars>0
/*eslint-env browser */
/*globals require: false, module: false */
'use strict';
var React = require('react');
var ReactDOM = require('react-dom');
var _ = require('ucsc-xena-client/dist/underscore_ext');
var MenuItem = require('react-bootstrap/lib/MenuItem');
var Dropdown = require('react-bootstrap/lib/Dropdown');
var Button = require('react-bootstrap/lib/Button');
var Badge = require('react-bootstrap/lib/Badge');
var Tooltip = require('react-bootstrap/lib/Tooltip');
var OverlayTrigger = require('react-bootstrap/lib/OverlayTrigger');
var DefaultTextInput = require('ucsc-xena-client/dist/views/DefaultTextInput');
var {RefGeneAnnotation} = require('ucsc-xena-client/dist/refGeneExons');
var ResizeOverlay = require('ucsc-xena-client/dist/views/ResizeOverlay');
var widgets = require('ucsc-xena-client/dist/columnWidgets');
var aboutDatasetMenu = require('ucsc-xena-client/dist/views/aboutDatasetMenu');
var spinner = require('ucsc-xena-client/dist/ajax-loader.gif');
var xenaRoot = 'https://genome-cancer.ucsc.edu/proj/site/xena';
// XXX move this?
function download([fields, rows]) {
var txt = _.map([fields].concat(rows), row => row.join('\t')).join('\n');
// use blob for bug in chrome: https://code.google.com/p/chromium/issues/detail?id=373182
var url = URL.createObjectURL(new Blob([txt], { type: 'text/tsv' }));
var a = document.createElement('a');
var filename = 'xenaDownload.tsv';
_.extend(a, { id: filename, download: filename, href: url });
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
var styles = {
badge: {
fontSize: '100%',
// Fix the width so it doesn't change if the label changes. This is important
// when resizing, because we (unfortunately) inspect the DOM to discover
// the minimum width we need to draw the column controls. If the label changes
// to a different character, the width will be different, and our minimum width
// becomes invalid.
width: 24
},
status: {
pointerEvents: 'none',
textAlign: 'center',
zIndex: 1,
position: 'absolute',
top: 0,
left: 0,
width: '100%',
height: '100%',
backgroundColor: 'rgba(255, 255, 255, 0.6)'
},
error: {
textAlign: 'center',
pointerEvents: 'all',
cursor: 'pointer'
},
columnMenuToggle: {
position: 'absolute',
left: 0,
top: 0,
width: '100%',
height: '100%'
}
};
function getStatusView(status, onReload) {
if (status === 'loading') {
return (
<div style={styles.status}>
<img style={{textAlign: 'center'}} src={spinner}/>
</div>);
}
if (status === 'error') {
return (
<div style={styles.status}>
<span
onClick={onReload}
title='Error loading data. Click to reload.'
style={styles.error}
className='glyphicon glyphicon-warning-sign Sortable-handle'
aria-hidden='true'/>
</div>);
}
return null;
}
var Column = React.createClass({
onResizeStop: function (size) {
this.props.onResize(this.props.id, size);
},
onRemove: function () {
this.props.onRemove(this.props.id);
},
onDownload: function () {
download(this.refs.plot.download());
},
onViz: function () {
this.props.onViz(this.props.id);
},
onKm: function () {
this.props.onKm(this.props.id);
},
onMode: function (ev, newMode) {
this.props.onMode(this.props.id, newMode);
},
onColumnLabel: function (value) {
this.props.onColumnLabel(this.props.id, value);
},
onFieldLabel: function (value) {
this.props.onFieldLabel(this.props.id, value);
},
onMuPit: function () {
// Construct the url, which will be opened in new window
let rows = _.getIn(this.props, ['data', 'req', 'rows']),
uriList = _.uniq(_.map(rows, n => `${n.chr}:${n.start.toString()}`)).join(','),
url = `http://mupit.icm.jhu.edu/?gm=${uriList}`;
window.open(url);
},
onReload: function () {
this.props.onReload(this.props.id);
},
getControlWidth: function () {
var controlWidth = ReactDOM.findDOMNode(this.refs.controls).getBoundingClientRect().width,
labelWidth = ReactDOM.findDOMNode(this.refs.label).getBoundingClientRect().width;
return controlWidth + labelWidth;
},
render: function () {
var {id, label, samples, column, index,
zoom, data, datasetMeta, fieldFormat, sampleFormat, disableKM, onClick, tooltip} = this.props,
{width, columnLabel, fieldLabel, user} = column,
[kmDisabled, kmTitle] = disableKM(id),
status = _.get(data, 'status'),
// move this to state to generalize to other annotations.
doRefGene = _.get(data, 'refGene'),
sortHelp = <Tooltip className='xena'>Drag to change column order</Tooltip>,
menuHelp = <Tooltip className='xena'>Column menu</Tooltip>,
moveIcon = (
<OverlayTrigger placement='top' overlay={sortHelp}>
<span
className="glyphicon glyphicon-resize-horizontal Sortable-handle"
aria-hidden="true">
</span>
</OverlayTrigger>);
return (
<div className='Column' style={{width: width, position: 'relative'}}>
<br/>
{/* Using Dropdown instead of SplitButton so we can put a Tooltip on the caret. :-p */}
<Dropdown ref='controls' bsSize='xsmall'>
<Button componentClass='label'>
{moveIcon}
</Button>
{/* If OverlayTrigger contains Dropdown.Toggle, the toggle doesn't work. So we invert the nesting and use a span to cover the trigger area. */}
<Dropdown.Toggle componentClass='label'>
<OverlayTrigger placement='top' overlay={menuHelp}>
<span style={styles.columnMenuToggle}></span>
</OverlayTrigger>
</Dropdown.Toggle>
<Dropdown.Menu>
<MenuItem title={kmTitle} onSelect={this.onKm} disabled={kmDisabled}>Kaplan Meier Plot</MenuItem>
<MenuItem onSelect={this.onDownload}>Download</MenuItem>
{aboutDatasetMenu(datasetMeta(id), xenaRoot)}
</Dropdown.Menu>
</Dropdown>
<Badge ref='label' style={styles.badge} className='pull-right'>{label}</Badge>
<br/>
<DefaultTextInput
onChange={this.onColumnLabel}
value={{default: columnLabel, user: user.columnLabel}} />
<DefaultTextInput
onChange={this.onFieldLabel}
value={{default: fieldLabel, user: user.fieldLabel}} />
<div style={{height: 20}}>
{doRefGene ?
<RefGeneAnnotation
width={width}
refGene={_.values(data.refGene)[0]}
layout={column.layout}
position={{gene: column.fields[0]}}/> : null}
</div>
<ResizeOverlay
onResizeStop={this.onResizeStop}
width={width}
minWidth={this.getControlWidth}
height={zoom.height}>
<div style={{position: 'relative'}}>
{widgets.column({ref: 'plot', id, column, data, index, zoom, samples, onClick, fieldFormat, sampleFormat, tooltip})}
{getStatusView(status, this.onReload)}
</div>
</ResizeOverlay>
{widgets.legend({column, data})}
</div>
);
}
});
module.exports = Column;
|
#!/bin/bash
#SBATCH --job-name=arr-GAM-Setophaga_discolor
#SBATCH -N 1 #number of tasks
#SBATCH -n 1 #number of nodes
#SBATCH -c 4 #cpus
#SBATCH --qos=general #queue (same as partition)
#SBATCH --partition=general #partition - can also specify 'himem'
#SBATCH --mem=30G #memory requested
#SBATCH -o /labs/Tingley/phenomismatch/Bird_Phenology/Data/Processed/arrival_GAM_2020-07-10/arr-GAM-Setophaga_discolor.out #STDOUT
#SBATCH -e /labs/Tingley/phenomismatch/Bird_Phenology/Data/Processed/arrival_GAM_2020-07-10/arr-GAM-Setophaga_discolor.err #STDERR
#echos name of node
echo `hostname`
module load gcc/6.4.0
module load singularity/3.0.2
singularity exec -B /labs/Tingley -B /UCHC /isg/shared/apps/R/3.5.2/R.sif Rscript /labs/Tingley/phenomismatch/Bird_Phenology/Scripts/2-arr-GAM/2-arr-GAM.R Setophaga_discolor 2002 2017
#displays amount of memory used
sstat --format="AveCPU,AvePages,AveRSS,MaxRSS,AveVMSize,MaxVMSize" $SLURM_JOBID.batch
|
<filename>public/js/users.js<gh_stars>0
let userModal = $('#user-modal');
let userId;
let Toast = Swal.mixin({
toast: true,
position: 'top-end',
showConfirmButton: false,
timer: 3000
});
//add user//
$(document).on('click','.add-user-btn',function(){
$('.text-danger').remove();
userModal.find('.form-submit').removeAttr('id').attr('id','add-user-form');
userModal.find('.modal-title').text('Add Customer');
userModal.find('#username').attr('disabled',false).attr('name','username');
userModal.find('#email').attr('disabled',false).attr('name','email');
$('#add-user-form').trigger('reset');
$('#add-user-form').find('#roles').val('').change();
$('.password-section').html('<div class="col-lg-6">\n' +
' <div class="form-group password">\n' +
' <label for="password">Password</label><span class="required">*</span>\n' +
' <input type="password" name="password" class="form-control" id="password">\n' +
' </div>\n' +
' </div>\n' +
' <div class="col-lg-6">\n' +
' <div class="form-group password_confirmation">\n' +
' <label for="password_confirmation">Confirm Password</label><span class="required">*</span>\n' +
' <input type="password" name="password_confirmation" class="form-control" id="password_confirmation">\n' +
' </div>\n' +
' </div>');
userModal.modal('toggle');
});
let addForm = $('#add-user-form');
$(document).on('submit','#add-user-form',function(f){
f.preventDefault();
let data = $(this).serializeArray();
$.ajax({
'url' : '/users',
'type' : 'POST',
'data' : data,
beforeSend: function(){
$('#add-user-form').find('input[type=submit]').attr('disabled',true).val('Saving...');
},success: function(response){
console.log(response);
if(response.success === true)
{
let table = $('#user-list').DataTable();
table.ajax.reload(null, false);
$('#add-user-form').trigger('reset');
$('#add-user-form').find('#roles').val('').change();
Toast.fire({
type: 'success',
title: response.message
})
}
$('#add-user-form').find('input[type=submit]').attr('disabled',false).val('Save');
},error: function(xhr, status, error){
console.log(xhr);
errorDisplay(xhr.responseJSON.errors);
addForm.find('input, select, textarea').attr('disabled',false);
$('#add-user-form').find('input[type=submit]').attr('disabled',false).val('Save');
}
});
clear_errors('firstname','lastname','date_of_birth','username','email','password','password_<PASSWORD>','roles');
});
//end add user//
//edit user //
let editForm = $('#edit-user-form');
$(document).on('click','.edit-user-btn',function(){
userId = this.id;
$('.text-danger').remove();
$('.password-section').html('');
userModal.find('.form-submit').removeAttr('id').attr('id','edit-user-form');
userModal.find('.modal-title').text('Edit Customer');
userModal.find('#username, #email').attr('disabled',true).removeAttr('name');
$.ajax({
'url' : '/users/'+userId+'/edit',
'type' : 'GET',
beforeSend: function(){
},success: function(response){
$.each(response,function(key, value){
$('#'+key).val(value).change();
});
},error: function(xhr, status, error){
console.log(xhr);
}
});
userModal.modal('toggle');
});
$(document).on('submit','#edit-user-form',function(f){
f.preventDefault()
let data = $(this).serializeArray();
$.ajax({
'url' : '/users/'+userId,
'type' : 'PUT',
'data' : data,
beforeSend: function(){
$('#edit-user-form').find('input[type=submit]').attr('disabled',true).val('Saving...');
},success: function(response){
console.log(response);
if(response.success === true)
{
let table = $('#user-list').DataTable();
table.ajax.reload(null, false);
Toast.fire({
type: 'success',
title: response.message
})
}else if(response.success === false){
Toast.fire({
type: 'warning',
title: response.message
})
}
$('#edit-user-form').find('input[type=submit]').attr('disabled',false).val('Save');
},error: function(xhr, status, error){
console.log(xhr);
errorDisplay(xhr.responseJSON.errors);
$('#edit-user-form').find('input[type=submit]').attr('disabled',false).val('Save');
}
});
clear_errors('firstname','lastname','date_of_birth','roles')
});
//end edit user //
//delete user//
$(document).on('click','.delete-user-btn',function(){
userId = this.id;
$tr = $(this).closest('tr');
let data = $tr.children("td").map(function () {
return $(this).text();
}).get();
Swal.fire({
title: 'Remove Customer?',
text: data[0],
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, remove it!'
}).then((result) => {
if (result.value === true) {
$.ajax({
'url' : '/users/'+userId,
'type' : 'DELETE',
'headers': {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
beforeSend: function(){
},success: function(response){
if(response.success === true)
{
let table = $('#user-list').DataTable();
table.ajax.reload(null, false);
Swal.fire(
'Removed!',
response.message,
'success'
)
}
},error: function(xhr, status, error){
console.log(xhr);
}
});
}
})
});
//end delete user//
|
#!/bin/sh
# CYBERWATCH SAS - 2017
#
# Security fix for USN-2514-1
#
# Security announcement date: 2015-02-26 00:00:00 UTC
# Script generation date: 2017-01-01 21:04:16 UTC
#
# Operating System: Ubuntu 12.04 LTS
# Architecture: i386
#
# Vulnerable packages fix on version:
# - linux-image-3.2.0-1460-omap4:3.2.0-1460.80
#
# Last versions recommanded by security team:
# - linux-image-3.2.0-1460-omap4:3.2.0-1460.80
#
# CVE List:
# - CVE-2015-0239
# - CVE-2013-7421
# - CVE-2014-7970
# - CVE-2014-8160
# - CVE-2014-9529
# - CVE-2014-9584
# - CVE-2014-9585
# - CVE-2014-9644
#
# More details:
# - https://www.cyberwatch.fr/vulnerabilites
#
# Licence: Released under The MIT License (MIT), See LICENSE FILE
sudo apt-get install --only-upgrade linux-image-3.2.0-1460-omap4=3.2.0-1460.80 -y
|
import { Hook, HookContext } from '@feathersjs/feathers';
/**
* "Starts" or "ends" the meeting if this is the second person to join,
* or the second to last person to leave, respectively.
*/
// eslint-disable-next-line @typescript-eslint/no-unused-vars
export default (options = {}): Hook => {
return async (context: HookContext): Promise<HookContext> => {
const addingParticipant = context.data['$addToSet'] && context.data['$addToSet'].active_participants;
const removingParticipant = context.data['$pull'] && context.data['$pull'].active_participants;
// if we are not adding or removing a participant, or we don't have an ID, skip this hook
if (!(addingParticipant || removingParticipant) || !context.id) {
return context;
}
const mtg = await context.app.service('meetings').get(context.id);
// if active_participants doesn't exist, this is the first participant, don't start or end
// loose null eq
if (mtg.active_participants == null || mtg.active_participants.length === 0) {
return context;
}
// a meeting can be considered active when there are two or more people in it
// in this case we are going from 1 -> 2 participants
if (addingParticipant && mtg.active_participants.length === 1) {
if (!mtg.meeting_start) {
context.data.meeting_start = Date.now() - mtg.meeting_start_ts;
}
// it is possible that a user can leave a meeting and immediately rejoin (due to technical issues, etc)
// we don't want this to trigger a new meeting!
// e.g. two people are in a meeting, one person has to refresh
// so if there is still one person in the meeting and a user joins,
// nullify the meeting_end time
if (mtg.meeting_end) {
context.data.meeting_end = null;
}
}
// a meeting can be considered inactive ('ended') when there is only one person in the meeting
// in this case we are going from 2 -> 1 participant
if (removingParticipant && !mtg.end_time && mtg.active_participants.length === 2) {
context.data.meeting_end = Date.now() - mtg.meeting_start_ts;
}
return context;
};
};
|
import jwt
# Create the JWT token
payload = {
'jti': str(uuid.uuid4()), # Unique identifier
'exp': datetime.datetime.utcnow() + datetime.timedelta(hours=1), # Expiry time
'sub': username # Username
}
# Generate and sign the token
token = jwt.encode(payload, secret, algorithm = 'HS256')
# Authenticate the user
def authenticateUser(username, token):
try:
payload = jwt.decode(token, secret, algorithms=['HS256'])
if payload['sub'] == username:
return True
else:
return False
except:
return False |
#!/bin/bash
sudo apt-get update
sudo apt-get install \
apt-transport-https \
ca-certificates \
curl \
gnupg-agent \
software-properties-common
curl -fsSL https://download.docker.com/linux/debian/gpg | sudo apt-key add -
sudo apt-key fingerprint 0EBFCD88
sudo add-apt-repository \
"deb [arch=amd64] https://download.docker.com/linux/debian \
$(lsb_release -cs) \
stable"
sudo apt-get update
sudo apt-get install docker-ce docker-ce-cli containerd.io
# Docker installed!
clear
echo "Docker Installed!"
docker --version
sleep 1
echo "Installing docker-compose..."
sleep 2
sudo curl -L "https://github.com/docker/compose/releases/download/1.26.0/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
sudo chmod +x /usr/local/bin/docker-compose
sudo ln -s /usr/local/bin/docker-compose /usr/bin/docker-compose
echo "Docker Compose Installed"
docker-compose --version
sleep 2
echo "Adicionando grupo docker.."
sudo groupadd docker
sudo usermod -aG docker $USER
newgrp docker
|
<filename>src/server/router/index.js
import makeRouter from 'koa-router';
const router = makeRouter();
router.get('/*', async(ctx, next) => {
await next();
});
export default router;
|
packages="avrdude-doc arduino-mk"
sudo apt-get install $packages
|
#include "cascaded_shadow_map_util.h"
#include <cassert>
#include <array>
#include <cmath>
#include <algorithm>
#include "glm_util.h"
#define MAX_CASCADES 4
Cascades calc_cascades(int cascade_count, Transform camera_transform, PerspectiveData perspective_data, glm::quat orientation)
{
assert(cascade_count == 3);
float percents[MAX_CASCADES + 1];
percents[0] = 0.0f;
percents[1] = 0.006f;
percents[2] = 0.05f;
percents[3] = 1.0f;
float fov = perspective_data.fov;
float aspect = perspective_data.aspect;
float z_near = perspective_data.z_near;
float z_far = perspective_data.z_far;
float t = std::tan(fov / 2.0f);
Transform reverse_transform;
reverse_transform.rotation = orientation;
Transform concat_transform = transform_inverse(reverse_transform) * camera_transform;
float splits[MAX_CASCADES + 1];
glm::vec3 split_ranges[MAX_CASCADES + 1][2];
for (int isplit = 0; isplit < cascade_count + 1; ++isplit) {
float split = z_near + percents[isplit] * (z_far - z_near);
splits[isplit] = split;
float by = split * t;
float bx = by * aspect;
std::array<glm::vec3, 4> corners = {
glm::vec3(-bx, -by, -split),
glm::vec3(bx, -by, -split),
glm::vec3(bx, by, -split),
glm::vec3(-bx, by, -split)
};
for (int icorner = 0; icorner < 4; ++icorner) {
corners[icorner] = transform_point(concat_transform, corners[icorner]);
}
auto x_minmax = std::minmax({ corners[0].x, corners[1].x, corners[2].x, corners[3].x });
auto y_minmax = std::minmax({ corners[0].y, corners[1].y, corners[2].y, corners[3].y });
auto z_minmax = std::minmax({ corners[0].z, corners[1].z, corners[2].z, corners[3].z });
float x_min = x_minmax.first;
float x_max = x_minmax.second;
float y_min = y_minmax.first;
float y_max = y_minmax.second;
float z_min = z_minmax.first;
float z_max = z_minmax.second;
split_ranges[isplit][0] = glm::vec3(x_min, y_min, z_min);
split_ranges[isplit][1] = glm::vec3(x_max, y_max, z_max);
}
std::vector<Transform> ortho_transforms(cascade_count);
std::vector<OrthographicData> ortho_datas(cascade_count);
for (int isplit = 0; isplit < cascade_count; ++isplit) {
glm::vec3 range_min_near = split_ranges[isplit][0];
glm::vec3 range_max_near = split_ranges[isplit][1];
glm::vec3 range_min_far = split_ranges[isplit + 1][0];
glm::vec3 range_max_far = split_ranges[isplit + 1][1];
float x_min = std::min(range_min_near.x, range_min_far.x);
float y_min = std::min(range_min_near.y, range_min_far.y);
float z_min = std::min(range_min_near.z, range_min_far.z);
float x_max = std::max(range_max_near.x, range_max_far.x);
float y_max = std::max(range_max_near.y, range_max_far.y);
float z_max = std::max(range_max_near.z, range_max_far.z);
float ortho_x = (x_min + x_max) / 2.0f;
float ortho_y = (y_min + y_max) / 2.0f;
float ortho_z = z_max;
float abs_left = (x_max - x_min) / 2.0f;
float abs_bottom = (y_max - y_min) / 2.0f;
float ortho_left = -abs_left;
float ortho_right = abs_left;
float ortho_bottom = -abs_bottom;
float ortho_top = abs_bottom;
float ortho_z_near = 0.0f;
float ortho_z_far = z_max - z_min;
Transform ortho_transform;
OrthographicData ortho_data;
ortho_transform.translation = quat_transform_point(orientation, glm::vec3(ortho_x, ortho_y, ortho_z));
ortho_transform.rotation = orientation;
ortho_data.left = ortho_left;
ortho_data.right = ortho_right;
ortho_data.bottom = ortho_bottom;
ortho_data.top = ortho_top;
ortho_data.z_near = ortho_z_near;
ortho_data.z_far = ortho_z_far;
ortho_transforms[isplit] = ortho_transform;
ortho_datas[isplit] = ortho_data;
}
Cascades res;
res.cascade_count = cascade_count;
res.splits.assign(splits + 1, splits + cascade_count + 1); // skip near, include far
res.ortho_transforms = ortho_transforms;
res.ortho_datas = ortho_datas;
return res;
}
|
angular.module("oxymoron.directives.contentFor", [])
.directive("contentFor", [
"$compile", function($compile) {
return {
compile: function(el, attrs, transclude) {
var template = el.html();
return {
pre: function(scope, iElement, iAttrs, controller) {
var DOMElements = angular.element(document.querySelectorAll('[ng-yield="'+iAttrs.contentFor+'"]'));
if (DOMElements.attr("only-text") == "true") {
template = el.text().replace(/(?:\r\n|\r|\n)/g, ' ');
}
DOMElements.html((DOMElements.attr("prefix") || "") + template + (DOMElements.attr("postfix") || ""))
$compile(DOMElements)(scope);
return iElement.remove();
}
};
}
};
}
]) |
#!/bin/sh
echo "uploading spark yarn archive"
cd ${SPARK_HOME}
tar -czvf spark-yarn-archive.tar.gz -C jars/ .
${HADOOP_HOME}/bin/hdfs dfs -put -f spark-yarn-archive.tar.gz /apps/spark/spark-yarn-archive.tar.gz
echo "finished uploading spark yarn archive" |
from typing import DefaultDict, Optional, Tuple
import cv2 as cv
import numpy as np
from creevey.constants import PathOrStr
def record_mean_brightness(
image: np.array, inpath: PathOrStr, log_dict: DefaultDict[str, dict]
) -> np.array:
"""
Calculate mean image brightness
Image is assumed to be grayscale if it has a single channel, RGB if
it has three channels, RGBA if it has four. Brightness is calculated
by converting to grayscale if necessary and then taking the mean
pixel value.
Parameters
----------
image
inpath
Image input path
log_dict
Dictionary of image metadata
Side effect
-----------
Adds a "mean_brightness" items to log_dict[inpath]
"""
if len(image.shape) == 3:
num_bands = image.shape[2]
elif len(image.shape) == 2:
num_bands = 1
else:
raise ValueError('Image array must have two or three dimensions')
if num_bands == 1:
image_gray = image
elif num_bands == 3:
image_gray = cv.cvtColor(src=image, code=cv.COLOR_RGB2GRAY)
elif num_bands == 4:
image_gray = cv.cvtColor(src=image, code=cv.COLOR_RGBA2GRAY)
else:
raise ValueError(
f'{inpath} image has {num_bands} channels. Only 1-channel '
f'grayscale, 3-channel RGB, and 4-channel RGBA images are '
f'supported.'
)
log_dict[inpath]['mean_brightness'] = image_gray.mean()
return image
def resize(
image: np.array,
shape: Optional[Tuple[int, int]] = None,
min_dim: Optional[int] = None,
**kwargs,
) -> np.array:
"""
Resize input image
`shape` or `min_dim` needs to be specified with `partial` before
this function can be used in a Creevey pipeline.
`kwargs` is included only for compatibility with the
`CustomReportingPipeline` class.
Parameters
----------
image
NumPy array with two spatial dimensions and optionally an
additional channel dimension
shape
Desired output shape in pixels in the form (height, width)
min_dim
Desired minimum spatial dimension in pixels; image will be
resized so that it has this length along its smaller spatial
dimension while preseving aspect ratio as closely as possible.
Exactly one of `shape` and `min_dim` must be `None`.
Returns
-------
NumPy array with specified shape
"""
_validate_resize_inputs(shape, min_dim)
if min_dim is not None:
shape = _find_min_dim_shape(image, min_dim)
resized = cv.resize(image, dsize=shape[::-1])
return resized
def _validate_resize_inputs(shape, min_dim) -> None:
if (shape is None) + (min_dim is None) == 1:
pass
else:
raise ValueError('Exactly one of `shape` and `min_dim` must be None')
def _find_min_dim_shape(image, min_dim):
in_height, in_width = image.shape[:2]
aspect_ratio = in_width / in_height
format = 'tall' if aspect_ratio < 1 else 'wide'
if format == 'tall':
out_width = min_dim
out_height = round(out_width / aspect_ratio, 1)
else:
out_height = min_dim
out_width = round(out_height * aspect_ratio, 1)
return (int(out_height), int(out_width))
|
package com.toddfast.mutagen.cassandra.test.mutations;
import com.netflix.astyanax.Keyspace;
import com.netflix.astyanax.MutationBatch;
import com.netflix.astyanax.connectionpool.exceptions.ConnectionException;
import com.netflix.astyanax.model.ColumnFamily;
import com.netflix.astyanax.serializers.StringSerializer;
import com.toddfast.mutagen.MutagenException;
import com.toddfast.mutagen.State;
import com.toddfast.mutagen.basic.SimpleState;
import com.toddfast.mutagen.cassandra.AbstractCassandraMutation;
/**
*
* @author <NAME>
*/
public class V003 extends AbstractCassandraMutation {
/**
*
*
*/
public V003(Keyspace keyspace) {
super(keyspace);
state=new SimpleState<Integer>(3);
}
@Override
public State<Integer> getResultingState() {
return state;
}
/**
* Return a canonical representative of the change in string form
*
*/
@Override
protected String getChangeSummary() {
return "update 'Test1' set value1='chicken', value2='sneeze' "+
"where key='row2';";
}
@Override
protected void performMutation(Context context) {
context.debug("Executing mutation {}",state.getID());
final ColumnFamily<String,String> CF_TEST1=
ColumnFamily.newColumnFamily("Test1",
StringSerializer.get(),StringSerializer.get());
MutationBatch batch=getKeyspace().prepareMutationBatch();
batch.withRow(CF_TEST1,"row2")
.putColumn("value1","chicken")
.putColumn("value2","sneeze");
try {
batch.execute();
}
catch (ConnectionException e) {
throw new MutagenException("Could not update columnfamily Test1",e);
}
}
final ColumnFamily<String,String> CF_TEST1=
ColumnFamily.newColumnFamily("Test1",
StringSerializer.get(),StringSerializer.get());
private State<Integer> state;
}
|
// Package config store all necessary configuration parameters for the project.
package config
|
<gh_stars>1-10
var InterStella_cart = (function() {
"use strict";
var InterStella_cart = function(core)
{
this.core = core;
};
InterStella_cart.prototype.load_rom = function(rom)
{
this.rom = new Uint8Array(rom);
// Assume that everything is a 4K cartridge for now.
// We'll worry about cartridge type detection and banking later.
// That means we don't have any work to do here.
};
InterStella_cart.prototype.read = function(address)
{
address = address % this.rom.length;
return this.rom[address];
};
InterStella_cart.prototype.write = function(address, value)
{
address = address % this.rom.length;
this.rom[address] = value;
};
return InterStella_cart;
})();
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.