repo_name stringlengths 6 101 | path stringlengths 4 300 | text stringlengths 7 1.31M |
|---|---|---|
ytong82/leetcode-in-java | lt897/src/main/java/rookie/java/leetcode/lt897/App.java | package rookie.java.leetcode.lt897;
import rookie.java.leetcode.lt897.iterative.Solution;
public class App {
public static void main( String[] args ) {
/*TreeNode root = new TreeNode(5);
TreeNode node = new TreeNode(3);
TreeNode node2 = new TreeNode(6);
root.left = node;
root.right = node2;
TreeNode node3 = new TreeNode(2);
TreeNode node4 = new TreeNode(4);
node.left = node3;
node.right = node4;
TreeNode node5 = new TreeNode(1);
node3.left = node5;
TreeNode node6 = new TreeNode(8);
node2.right = node6;
TreeNode node7 = new TreeNode(7);
TreeNode node8 = new TreeNode(9);
node6.left = node7;
node6.right = node8; */
TreeNode root = new TreeNode(2);
TreeNode node = new TreeNode(1);
TreeNode node2 = new TreeNode(4);
TreeNode node3 = new TreeNode(3);
root.left = node;
root.right = node2;
node2.left = node3;
Solution solution = new Solution();
TreeNode head = solution.increasingBST(root);
while (head != null) {
System.out.printf("%s-> ", head.val);
head = head.right;
}
}
}
|
H2u-Hwng/CodinGame | Compete/Class of Code/Fastest Mode/log.py | # Problem: https://docs.google.com/document/d/1YHc6R-GoARbkeyZrlb6Zk5a9TvKoaKKy6YxtSOGM5cw/edit?usp=sharing
from math import log
n = int(input())
r = log(n,2)
print(int(r) if '.0' in str(r) else -1)
|
appsignal/mono | lib/mono/cli.rb | # frozen_string_literal: true
require "yaml"
require "pathname"
require "optparse"
module Mono
module Cli
class Base
include Shell
include Command::Helper
def initialize(options = {})
@options = options
@config = Config.new(YAML.safe_load(File.read("mono.yml")))
@language = Language.for(config.language).new(config)
find_packages
validate(options)
end
def packages
dependency_tree.packages
end
def dependency_tree
@dependency_tree ||= DependencyTree.new(@packages)
end
private
attr_reader :options, :config, :language
def find_packages
package_class = PackageBase.for(config.language)
if config.monorepo?
packages_dir = config.packages_dir
directories = Dir.glob("*", :base => packages_dir)
.sort
.select { |pkg| File.directory?(File.join(packages_dir, pkg)) }
if language.respond_to? :select_packages
directories = language.select_packages(directories)
end
selected_packages = options[:packages]
@packages = []
directories.each do |package|
path = File.join(packages_dir, package)
package = package_class.new(package, path, config)
if selected_packages && !selected_packages.include?(package.name)
next
end
@packages << package
end
else
# Single package repo
pathname = Pathname.new(Dir.pwd)
package = pathname.basename
@packages = [package_class.new(package, ".", config)]
end
end
def validate(options)
selected_packages = options[:packages]
if config.monorepo? && selected_packages
selected_packages.each do |package_name|
next if packages.find { |package| package.name == package_name }
# One of the selected packages was not found. Exit mono.
raise PackageNotFound, package_name
end
end
end
def run_hooks(command, type)
hooks = config.hooks(command, type)
return unless hooks.any?
puts "Running hooks: #{command}: #{type}"
hooks.each do |hook|
run_command hook
end
end
def parallel?
options[:parallel]
end
def current_branch
`git rev-parse --abbrev-ref HEAD`.chomp
end
def local_changes?
`git status -s -u`.split("\n").each do |change|
change.gsub!(/^.. /, "")
end.any?
end
def exit_cli(message)
raise Mono::Error, message
end
def exit_with_status(status)
puts "Exiting..."
exit status
end
end
class Wrapper
def initialize(options)
@options = options
end
def execute
parse_global_options
execute_command
end
def execute_command # rubocop:disable Metrics/CyclomaticComplexity
command = @options.shift
case command
when "init"
Mono::Cli::Init.new.execute
when "bootstrap"
Mono::Cli::Bootstrap.new(bootstrap_options).execute
when "unbootstrap"
Mono::Cli::Unbootstrap.new(unbootstrap_options).execute
when "clean"
Mono::Cli::Clean.new(clean_options).execute
when "build"
Mono::Cli::Build.new(build_options).execute
when "test"
Mono::Cli::Test.new(test_options).execute
when "publish"
Mono::Cli::Publish.new(publish_options).execute
when "changeset"
subcommand = @options.shift
case subcommand
when "add"
Mono::Cli::Changeset::Add.new.execute
when "status"
puts "Not implemented in prototype. " \
"But this would print the next determined version number."
exit_cli_with_status 1
end
when "run"
Mono::Cli::Custom.new(*custom_options).execute
else
puts "Unknown command: #{command}"
puts "Run `mono --help` for the list of available commands."
exit_cli_with_status 1
end
rescue Mono::Error => error
puts "A Mono error was encountered during the `mono #{command}` " \
"command. Stopping operation."
puts
puts "#{error.class}: #{error.message}"
exit_cli_with_status 1
rescue StandardError => error
puts "An unexpected error was encountered during the " \
"`mono #{command}` command. Stopping operation."
puts
raise error
rescue Interrupt
puts "User interrupted command. Exiting..."
exit 1
end
private
AVAILABLE_COMMANDS = %w[
init
bootstrap
unbootstrap
clean
build
test
publish
changeset
run
].freeze
def exit_cli_with_status(status)
exit status
end
def parse_global_options
OptionParser.new do |o|
o.banner = "Usage: mono <command> [options]"
o.on "-v", "--version", "Print version and exit" do |_arg|
puts "Mono #{Mono::VERSION}"
exit_cli_with_status 0
end
o.on "-h", "--help", "Show help and exit" do
puts o
exit_cli_with_status 0
end
o.separator ""
o.separator "Available commands: #{AVAILABLE_COMMANDS.join(", ")}"
end.order!(@options)
end
def bootstrap_options
params = {}
OptionParser.new do |opts|
opts.banner = "Usage: mono publish [options]"
opts.on "--[no-]ci",
"Bootstrap the project optimized for CI environments" do |value|
params[:ci] = value
end
end.parse(@options)
params
end
def unbootstrap_options
params = {}
OptionParser.new do |opts|
opts.banner = "Usage: mono unbootstrap [options]"
end.parse(@options)
params
end
def clean_options
params = {}
OptionParser.new do |opts|
opts.banner = "Usage: mono clean [options]"
opts.on "-p", "--package package1,package2,package3", Array,
"Select packages to clean" do |value|
params[:packages] = value
end
end.parse(@options)
params
end
def build_options
params = {}
OptionParser.new do |opts|
opts.banner = "Usage: mono build [options]"
opts.on "-p", "--package package1,package2,package3", Array,
"Select packages to build" do |value|
params[:packages] = value
end
end.parse(@options)
params
end
def test_options
params = {}
OptionParser.new do |opts|
opts.banner = "Usage: mono test [options]"
opts.on "-p", "--package package1,package2,package3", Array,
"Select packages to test" do |value|
params[:packages] = value
end
end.parse(@options)
params
end
def publish_options
params = {}
OptionParser.new do |opts|
opts.banner = "Usage: mono publish [options]"
opts.on "-p", "--package package1,package2,package3", Array,
"Select packages to publish" do |value|
params[:packages] = value
end
opts.on "--alpha", "Release an alpha prerelease" do
params[:prerelease] = "alpha"
end
opts.on "--beta", "Release a beta prerelease" do
params[:prerelease] = "beta"
end
opts.on "--rc", "Release a rc prerelease" do
params[:prerelease] = "rc"
end
end.parse(@options)
params
end
def custom_options
params = {}
OptionParser.new do |opts|
opts.banner = "Usage: mono run [options] -- <command>"
opts.on "-p", "--package package1,package2,package3", Array,
"Select packages to run command in" do |value|
params[:packages] = value
end
opts.on "--[no-]parallel", "Run commands in parallel" do |value|
params[:parallel] = value
end
end.parse!(@options)
[@options, params]
end
end
end
end
Dir.glob("cli/*", :base => __dir__).each do |file|
require "mono/#{file}"
end
|
jzlotek/drexel-cs451 | src/main/java/tbc/server/Lobby.java | <gh_stars>0
package tbc.server;
import tbc.client.checkers.Board;
import tbc.client.checkers.Color;
import tbc.client.checkers.Piece;
import tbc.client.components.ComponentStore;
import tbc.shared.GameState;
import tbc.shared.Move;
import tbc.util.ConsoleWrapper;
import tbc.util.SerializationUtilJSON;
import tbc.util.SocketUtil;
import tbc.util.UUIDUtil;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.UUID;
public class Lobby extends Thread {
protected ArrayList<Player> players = new ArrayList<Player>();
protected boolean gameRunning;
protected final int maxPlayers = 2;
protected Board gameBoard;
private UUID uuid;
// generic constructor
public Lobby() {
this.uuid = UUIDUtil.getUUID();
}
/*
* Constructor that takes in two players, automatically starts the game
*/
public Lobby(Player player1, Player player2) throws Exception {
this();
this.addPlayer(player1);
this.addPlayer(player2);
}
@Override
public void run() {
while (this.players.size() < 2) {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
}
}
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
}
this.gameBoard = new Board();
String received;
String response;
Socket p1_socket = players.get(0).getSocket();
Socket p2_socket = players.get(1).getSocket();
Color[] randomize = new Color[]{Color.WHITE, Color.RED};
Collections.shuffle(Arrays.asList(randomize));
GameState gs = new GameState("Initial Game State", this.gameBoard);
gs.yourTurn = false;
Socket finalP1_socket = p1_socket;
gs.yourColor = randomize[0];
if (randomize[0] == Color.WHITE) {
gs.yourTurn = true;
}
new Thread(() -> SocketUtil.sendGameState(gs, finalP1_socket)).run();
ConsoleWrapper.WriteLn("Sent p1 board state" + p1_socket.toString());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Socket finalP2_socket = p2_socket;
gs.yourColor = randomize[1];
gs.yourTurn = false;
if (randomize[1] == Color.WHITE) {
gs.yourTurn = true;
}
new Thread(() -> SocketUtil.sendGameState(gs, finalP2_socket)).run();
ConsoleWrapper.WriteLn("Sent p2 board state " + p2_socket.toString());
GameState userGameState;
// make sure that player[0] is the first player
if (randomize[0] == Color.RED) {
Player tmp = this.players.get(0);
this.players.set(0, this.players.get(1));
this.players.set(1, tmp);
Socket tmpSocket = p1_socket;
p1_socket = p2_socket;
p2_socket = tmpSocket;
}
// start gameRunning loop
this.gameRunning = true;
while (this.gameRunning) {
this.checkSockets();
userGameState = null;
boolean isMoveValid = false;
while (!isMoveValid) {
// read the move in from current player's turn
try {
received = SocketUtil.readFromSocket(p1_socket);
userGameState = (GameState) SerializationUtilJSON.deserialize(received);
} catch (Exception ex) {
ex.printStackTrace();
}
// if the move is valid, we must output to player two
// and we update the locally stored board in the stor
String backup = "";
try {
backup = SerializationUtilJSON.serialize(this.gameBoard);
} catch (Exception e) {
e.printStackTrace();
}
for (Move move : userGameState.moves) {
if (this.isLegalMove(move)) {
isMoveValid = true;
Piece p = this.gameBoard.getPiece(move.getOldLocation());
this.gameBoard.movePiece(p, move.getOldLocation(), move.getNewLocation());
} else { // else we throw player one a warning and prompt for another move
response = "Move Invalid! Please make a valid move.";
SocketUtil.sendGameState(new GameState(response), p1_socket);
isMoveValid = false;
try {
this.gameBoard = (Board) SerializationUtilJSON.deserialize(backup);
} catch (Exception e) {
e.printStackTrace();
}
break;
}
}
}
try {
Thread.sleep(1000);
} catch (Exception e) {
}
// accept game state and send confirmation to p1_socket
GameState newState = new GameState("success");
newState.yourTurn = false;
newState.board = this.gameBoard;
SocketUtil.sendGameState(newState, p1_socket);
try {
Thread.sleep(1000);
} catch (Exception e) {
}
// send updated move to p2_socket
newState = new GameState("New Move");
newState.yourTurn = true;
newState.moves = userGameState.moves;
newState.board = this.gameBoard;
SocketUtil.sendGameState(newState, p2_socket);
// check for winner
if (this.hasWinner()) {
if(this.gameBoard.getPiecesForColor(randomize[0]).size() == 0){
// player 2 wins
SocketUtil.sendGameState(new GameState("You've won!"), players.get(1).getSocket());
SocketUtil.sendGameState(new GameState("You've lost!"), players.get(0).getSocket());
} else {
// player 1 wins
SocketUtil.sendGameState(new GameState("You've won!"), players.get(0).getSocket());
SocketUtil.sendGameState(new GameState("You've lost!"), players.get(1).getSocket());
}
break;
}
// swap players so we do not have to repeat code
Socket tmp = p1_socket;
p1_socket = p2_socket;
p2_socket = tmp;
}
// after the game is over, send a closing message to the players and close the sockets
SocketUtil.sendGameState(new GameState("Game Over! Thanks for playing."), p1_socket);
SocketUtil.sendGameState(new GameState("Game Over! Thanks for playing."), p2_socket);
players.get(0).setInGame(false);
players.get(1).setInGame(false);
try {
players.get(0).socket.close();
players.get(1).socket.close();
} catch (Exception ex){
// ignore error
}
}
/*
* Adds a player to the lobby if there is room, or else throws a message back to the player
*/
public void addPlayer(Player newPlayer) {
ConsoleWrapper.WriteLn("Attempting to add player: " + newPlayer.getSocket() + " to lobby: " + this.getUUID().toString());
if (this.players.size() < this.maxPlayers) {
synchronized (Server.class) {
if (this.players.size() < this.maxPlayers) {
ConsoleWrapper.WriteLn("Added player: " + newPlayer.getSocket() + " to lobby: " + this.getUUID().toString());
this.players.add(newPlayer);
} else {
SocketUtil.sendGameState(new GameState("Unable to add " + newPlayer.getSocket() + " to lobby. Lobby full"), newPlayer.getSocket());
}
}
}
}
/*
* Function that validates if a move in the form of a message is valid
*/
public boolean isLegalMove(Move move) {
if (move == null) {
return false;
}
ArrayList<Move> validMoves = gameBoard.getValidMoves((this.gameBoard.getPiece(move.getOldLocation())));
for (Move validMove : validMoves) {
if (validMove.equals(move)) {
return true;
}
}
return false;
}
/*
* Function that checks if we have a winner after a specific move has been made
*/
public boolean hasWinner() {
Board board = (Board) ComponentStore.getInstance().get("board");
if (board != null) {
return board.hasWinner();
}
return false;
}
public boolean isGameRunning() {
return this.gameRunning;
}
public void checkSockets() {
for (Player p : this.players) {
if (p.getSocket().isClosed()) {
this.gameRunning = false;
}
}
if (this.players.get(0).getSocket().isClosed() || this.players.get(1).getSocket().isClosed()) {
try {
this.players.get(0).closeSocket();
} catch (Exception e) {
ConsoleWrapper.WriteLn("Player 1 Has Disconnected");
}
try {
this.players.get(1).closeSocket();
} catch (Exception e) {
ConsoleWrapper.WriteLn("Player 2 Has Disconnected");
}
}
}
public UUID getUUID() {
return this.uuid;
}
} |
wieldo/meteor-app | imports/app/filter/highlight-auto.js | <reponame>wieldo/meteor-app
import hljs from "highlight.js";
import jsfy from "jsfy";
export default () => {
return function(input) {
if (input) {
return hljs.highlightAuto(jsfy(input)).value;
}
return input;
};
};
|
preversewharf45/freetype-demo | engine/src/external/opengl/openglbuffer.h |
/*
* Implementation of the graphics buffer class interface
*/
#ifdef __OPENGL__
#ifndef __OPENGL_BUFFER_H__
#define __OPENGL_BUFFER_H__
#include "openglhelper.h"
#include <graphics/buffer.h>
#include <graphics/bufferlayout.h>
namespace engine { namespace external { namespace opengl {
//------------- VERTEX BUFFER -------------
class OpenGLVertexBuffer : public engine::graphics::VertexBuffer {
public:
OpenGLVertexBuffer(const void * data, size_t size, graphics::BufferUsage usage);
~OpenGLVertexBuffer();
public:
virtual void Bind() const override;
virtual void UnBind() const override;
virtual void SubData(const void * data, size_t size, size_t offset) override;
virtual void * Map() override;
virtual void UnMap() override;
virtual void SetBufferLayout(utils::StrongHandle<graphics::BufferLayout> & layout) override;
inline virtual utils::StrongHandle<graphics::BufferLayout> GetBufferLayout() const override { return m_Layout; };
inline virtual size_t GetSize() const override { return m_Size; }
private:
GLuint m_ID;
size_t m_Size;
utils::StrongHandle<graphics::BufferLayout> m_Layout;
graphics::BufferUsage m_Usage;
bool m_IsMapped;
};
// ------------- UNIFORM BUFFER -------------
class OpenGLUniformBuffer : public engine::graphics::UniformBuffer {
public:
OpenGLUniformBuffer(const void * data, size_t size, graphics::BufferUsage usage);
~OpenGLUniformBuffer();
public:
virtual void Bind(unsigned int block) const override;
virtual void UnBind() const override;
virtual void SubData(const void * data, size_t size, size_t offset) override;
private:
GLuint m_ID;
size_t m_Size;
mutable GLuint m_Block;
};
} } }
#endif //__OPENGL_BUFFER_H__
#endif //__OPENGL__ |
tencentyun/xiaowei-device-sdk | Device/CtrlModule/xweicontrol/App/AudioFocusManager.cpp | /*
* Tencent is pleased to support the open source community by making XiaoweiSDK Demo Codes available.
*
* Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the MIT License (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://opensource.org/licenses/MIT
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*
*/
#ifndef AudioFocusManager_cpp
#define AudioFocusManager_cpp
#include "logger.h"
#include "AudioFocusManager.hpp"
#include "Util.hpp"
#include "TXCServices.hpp"
#include <sstream>
#define MAX_FOCUS 3
static int s_cookie = 0;
SDK_API tcx_xwei_audio_focus_interface audio_focus_interface = {0};
CFocusItem::CFocusItem()
: id(0), cookie(0), listener(NULL)
{
}
CFocusItem::~CFocusItem()
{
listener = NULL;
}
std::string CFocusItem::ToString()
{
std::stringstream str;
str << "cookie=";
str << cookie;
str << ",hint=";
str << Util::ToString(hint);
str << ",listener=";
str << listener;
return str.str();
}
TXCAudioFocusManager::TXCAudioFocusManager()
{
audio_focus_manager_impl_ = new TXCAudioFocusManagerImpl;
audio_focus_manager_impl_->SetAudioFocusChangeCallback(this);
}
TXCAudioFocusManager::~TXCAudioFocusManager()
{
AbandonAllAudioFocus();
delete audio_focus_manager_impl_;
}
AUDIOFOCUS_REQUEST_RESULT TXCAudioFocusManager::RequestAudioFocus(SESSION id)
{
CFocusItem *item = GetFocusItem(id);
if (item != NULL)
{
return RequestAudioFocus(id, item->listener, item->hint);
}
return AUDIOFOCUS_REQUEST_FAILED;
}
AUDIOFOCUS_REQUEST_RESULT TXCAudioFocusManager::RequestAudioFocus(SESSION id, OnAudioFocusChangeListener *listener, DURATION_HINT duration)
{
if (duration < AUDIOFOCUS_GAIN || duration > AUDIOFOCUS_GAIN_TRANSIENT_EXCLUSIVE || listener == NULL)
{
return AUDIOFOCUS_REQUEST_FAILED;
}
CFocusItem *item = GetFocusItem(id);
if (item == NULL)
{
item = new CFocusItem;
item->id = id;
item->cookie = CreateCookie(id);
m_id_item[id] = item;
m_cookie_item[item->cookie] = item;
}
item->listener = listener;
item->hint = duration;
m_lis_item[item->listener] = item;
// 请求焦点
if (audio_focus_interface.on_request_audio_focus)
{
AUDIOFOCUS_REQUEST_RESULT result = audio_focus_interface.on_request_audio_focus(item->cookie, item->hint);
if (AUDIOFOCUS_REQUEST_GRANTED == result)
{
OnAudioFocusChangeCallback(item->cookie, item->hint);
}
return result;
}
return audio_focus_manager_impl_->RequestAudioFocus(item->cookie, item->hint);
}
AUDIOFOCUS_REQUEST_RESULT TXCAudioFocusManager::AbandonAudioFocus(SESSION id)
{
CFocusItem *item = GetFocusItem(id);
if (item != NULL)
{
return AbandonAudioFocus(item);
}
return AUDIOFOCUS_REQUEST_GRANTED;
}
AUDIOFOCUS_REQUEST_RESULT TXCAudioFocusManager::AbandonAudioFocus(OnAudioFocusChangeListener *listener)
{
if (listener == NULL)
{
return AUDIOFOCUS_REQUEST_GRANTED;
}
CFocusItem *item = GetFocusItem(listener);
if (item != NULL)
{
return AbandonAudioFocus(item);
}
return AUDIOFOCUS_REQUEST_GRANTED;
}
AUDIOFOCUS_REQUEST_RESULT TXCAudioFocusManager::AbandonAudioFocus(CFocusItem *item)
{
AUDIOFOCUS_REQUEST_RESULT result = AUDIOFOCUS_REQUEST_GRANTED;
if (item != NULL)
{
// 释放焦点
if (audio_focus_interface.on_abandon_audio_focus)
{
result = audio_focus_interface.on_abandon_audio_focus(item->cookie);
}
else
{
result = audio_focus_manager_impl_->AbandonAudioFocus(item->cookie);
}
if (AUDIOFOCUS_REQUEST_GRANTED == result)
{
OnAudioFocusChangeCallback(item->cookie, AUDIOFOCUS_LOSS);
}
}
return result;
}
AUDIOFOCUS_REQUEST_RESULT TXCAudioFocusManager::AbandonAllAudioFocus()
{
TLOG_TRACE("TXCAudioFocusManager::AbandonAllAudioFocus");
// 释放焦点
if (audio_focus_interface.on_abandon_audio_focus)
{
audio_focus_interface.on_abandon_audio_focus(-1); // -1 表示释放所有
}
else
{
audio_focus_manager_impl_->AbandonAllAudioFocus();
}
for (std::map<OnAudioFocusChangeListener *, CFocusItem *>::iterator iter = m_lis_item.begin(); iter != m_lis_item.end(); iter++)
{
OnAudioFocusChangeCallback(iter->second->cookie, AUDIOFOCUS_LOSS);
}
TLOG_TRACE("TXCAudioFocusManager::AbandonAllAudioFocus m_id_item[%d] m_cookie_item[%d] m_lis_item[%d] ", m_id_item.size(), m_cookie_item.size(), m_lis_item.size());
m_id_item.clear();
m_cookie_item.clear();
m_lis_item.clear();
return AUDIOFOCUS_REQUEST_GRANTED;
}
AUDIOFOCUS_REQUEST_RESULT TXCAudioFocusManager::RequestAudioFocusWithCookie(int cookie, OnAudioFocusChangeListener *listener, DURATION_HINT duration)
{
if (duration < AUDIOFOCUS_GAIN || duration > AUDIOFOCUS_GAIN_TRANSIENT_EXCLUSIVE || listener == NULL)
{
return AUDIOFOCUS_REQUEST_FAILED;
}
CFocusItem *item = GetFocusItemWithCookie(cookie);
if (item == NULL)
{
item = new CFocusItem;
item->cookie = cookie;
m_cookie_item[item->cookie] = item;
}
item->listener = listener;
item->hint = duration;
m_lis_item[item->listener] = item;
// 请求焦点
if (audio_focus_interface.on_request_audio_focus)
{
AUDIOFOCUS_REQUEST_RESULT result = audio_focus_interface.on_request_audio_focus(item->cookie, item->hint);
if (AUDIOFOCUS_REQUEST_GRANTED == result)
{
OnAudioFocusChangeCallback(item->cookie, item->hint);
}
return result;
}
return audio_focus_manager_impl_->RequestAudioFocus(item->cookie, item->hint);
}
AUDIOFOCUS_REQUEST_RESULT TXCAudioFocusManager::AbandonAudioFocusWithCookie(int cookie)
{
CFocusItem *item = GetFocusItemWithCookie(cookie);
if (item != NULL)
{
return AbandonAudioFocus(item);
}
return AUDIOFOCUS_REQUEST_GRANTED;
}
CFocusItem *TXCAudioFocusManager::GetFocusItem(SESSION id)
{
std::map<int, CFocusItem *>::iterator itor = m_id_item.find(id);
if (itor != m_id_item.end())
{
return itor->second;
}
return NULL;
}
CFocusItem *TXCAudioFocusManager::GetFocusItem(OnAudioFocusChangeListener *listener)
{
std::map<OnAudioFocusChangeListener *, CFocusItem *>::iterator itor = m_lis_item.find(listener);
if (itor != m_lis_item.end())
{
return itor->second;
}
return NULL;
}
CFocusItem *TXCAudioFocusManager::GetFocusItemWithCookie(int cookie)
{
std::map<int, CFocusItem *>::iterator itor = m_cookie_item.find(cookie);
if (itor != m_cookie_item.end())
{
return itor->second;
}
return NULL;
}
void TXCAudioFocusManager::SetAudioFocus(DURATION_HINT hint)
{
audio_focus_manager_impl_->SetAudioFocus(hint);
}
void TXCAudioFocusManager::OnAudioFocusChangeCallback(int cookie, DURATION_HINT focus_change)
{
CFocusItem *item = GetFocusItemWithCookie(cookie);
if (item != NULL && item->listener != NULL)
{
TLOG_TRACE("TXCAudioFocusManager::OnAudioFocusChangeCallback cookie=%d hint=%s", cookie, Util::ToString(focus_change).c_str());
item->listener->OnAudioFocusChange(focus_change);
}
if (focus_change == AUDIOFOCUS_LOSS)
{
Release(item);
}
}
void TXCAudioFocusManager::Release(CFocusItem *item)
{
if (item != NULL)
{
m_id_item.erase(item->id);
m_cookie_item.erase(item->cookie);
m_lis_item.erase(item->listener);
// 如果是Out,需要delete
COuterFocusListener *lis = dynamic_cast<COuterFocusListener *>(item->listener);
if (lis != NULL)
{
delete lis;
}
delete item;
}
}
int TXCAudioFocusManager::CreateCookie(int id)
{
std::map<int, int>::iterator itor = m_id_cookie.find(id);
if (itor != m_id_cookie.end())
{
return itor->second;
}
int cookie = ++s_cookie;
m_id_cookie[id] = cookie;
return cookie;
}
// 过滤掉焦点类型的消息
bool TXCAudioFocusManager::HandleAudioFocusMessage(SESSION id, XWM_EVENT event, XWPARAM arg1, XWPARAM arg2)
{
TLOG_TRACE("sessionId=%d TXCAudioFocusManager::HandleAudioFocusMessage event=%s, arg1=%ld, arg2=%ld.", id, Util::ToString(event).c_str(), arg1, arg2);
switch (event)
{
case XWM_REQUEST_AUDIO_FOCUS:
{
if (id == -1)
{
int cookie = (int)reinterpret_cast<long>(arg1);
DURATION_HINT hint = (DURATION_HINT) reinterpret_cast<long>(arg2);
COuterFocusListener *listener = new COuterFocusListener;
listener->cookie = cookie;
TXCServices::instance()->GetAudioFocusManager()->RequestAudioFocusWithCookie(cookie, listener, hint);
}
else
{
TXCServices::instance()->GetAudioFocusManager()->RequestAudioFocus(id);
}
return true;
}
case XWM_ABANDON_AUDIO_FOCUS:
{
if ((bool)arg1)
{
TXCServices::instance()->GetAudioFocusManager()->AbandonAllAudioFocus();
}
else
{
int cookie = 0;
if (arg2 != NULL)
{
cookie = (int)reinterpret_cast<long>(arg2);
}
if (cookie > 0)
{
TXCServices::instance()->GetAudioFocusManager()->AbandonAudioFocusWithCookie(cookie);
}
else
{
TXCServices::instance()->GetAudioFocusManager()->AbandonAudioFocus(id);
}
}
return true;
}
case XWM_SET_AUDIO_FOCUS:
{
TXCServices::instance()->GetAudioFocusManager()->SetAudioFocus((DURATION_HINT)(reinterpret_cast<long>(arg1)));
return true;
}
case XWM_SET_AUDIO_FOCUS_INTERFACE_CHANGE:
{
TXCServices::instance()->GetAudioFocusManager()->OnAudioFocusChangeCallback((int)(reinterpret_cast<long>(arg1)), (DURATION_HINT)(reinterpret_cast<long>(arg2)));
return true;
}
default:
break;
}
return false;
}
audio_focus_change_function g_focus_change;
void COuterFocusListener::OnAudioFocusChange(int focusChange)
{
if (g_focus_change)
{
g_focus_change(cookie, focusChange);
}
}
SDK_API void txc_set_audio_focus_change_callback(audio_focus_change_function func)
{
g_focus_change = func;
}
SDK_API void txc_request_audio_focus(int &cookie, DURATION_HINT duration)
{
if (cookie <= 0)
{
cookie = ++s_cookie;
}
post_message(-1, XWM_REQUEST_AUDIO_FOCUS, XWPARAM((long)cookie), XWPARAM(duration));
}
SDK_API void txc_abandon_audio_focus(int cookie)
{
post_message(-1, XWM_ABANDON_AUDIO_FOCUS, XWPARAM(0), XWPARAM((long)cookie));
}
SDK_API void txc_abandon_all_audio_focus()
{
post_message(-1, XWM_ABANDON_AUDIO_FOCUS, XWPARAM(1), NULL);
}
SDK_API void txc_set_audio_focus(DURATION_HINT focus)
{
post_message(-1, XWM_SET_AUDIO_FOCUS, XWPARAM(focus), NULL);
}
SDK_API void txc_set_audio_focus_interface_change(int cookie, DURATION_HINT duration)
{
post_message(-1, XWM_SET_AUDIO_FOCUS_INTERFACE_CHANGE, XWPARAM((long)cookie), XWPARAM(duration));
}
#endif /* AudioFocusManager_cpp */
|
fabriciocgf/IOT_LoRa_Dashboard | test/DataModel/Config/WidgetData/DataWidgetData/MapWidgetDataTest.js | import Mocha, {
describe,
it,
before
} from 'mocha';
import {
MapWidgetData
} from '../../../../../src/DataModel/Config/WidgetData/DataWidgetData/MapWidgetData.js';
import Jsdom from 'mocha-jsdom';
import Chai, {
expect
} from 'chai';
import {
View
} from '../../../../../src/View/View.js';
/**
* This one will test the WidgetConfig Class
* @param string
* The displayed name of this test suite
*/
describe('Class WidgetConfigTest: Basic tests: ', () => {
let _view = null;
let $ = null;
let L = null;
Jsdom();
// first initialization of view
before(function(done) {
// init window and jquery globaly
this.jsdom = require('jsdom-global')();
global.$ = global.jQuery = require('jquery');
$ = require('jquery');
global.L = require('leaflet');
global.WIDGET_TYPE_BARGRAPH = 1;
global.WIDGET_TYPE_GAUGE = 2;
global.WIDGET_TYPE_LINEGRAPH = 3;
global.WIDGET_TYPE_MAP = 4;
global.WIDGET_TYPE_PLAINDATA = 5;
global.WIDGET_TYPE_PLAINTEXT = 6;
global.WIDGET_TYPE_THERMOMETER = 7;
global.WIDGET_TYPE_TRAFFICLIGHT = 8;
global.TYPE_OBJECT = 9;
global.MARKER_TYPE_PLAIN = 0;
global.MARKER_TYPE_PLAINVALUE = 1;
global.MARKER_TYPE_TRAFFICLIGHT = 2;
global.MARKER_TYPE_HISTORY = 3;
done();
});
it('constructor works', function(done) {
let mapWidgetData = new MapWidgetData();
expect(mapWidgetData).to.be.instanceof(Object);
done();
});
it('setAttributes & getPosition test', function(done) {
let mapWidgetData = new MapWidgetData();
let temp = {
"position": {
"x": 4,
"y": 2
},
"size": {
"x": 42,
"y": 24
}
};
mapWidgetData.setAttributes(temp);
expect(mapWidgetData.getPosition()).equal(temp.position);
done();
});
it('setAttributes & getSize test', function(done) {
let mapWidgetData = new MapWidgetData();
let temp = {
"position": {
"x": 4,
"y": 2
},
"size": {
"x": 42,
"y": 24
}
};
mapWidgetData.setAttributes(temp);
expect(mapWidgetData.getSize()).equal(temp.size);
done();
});
it('set- & getPosition test', function(done) {
let mapWidgetData = new MapWidgetData();
let temp = {
"x": 4,
"y": 2
};
mapWidgetData.setPosition(temp);
expect(mapWidgetData.getPosition()).equal(temp);
done();
});
it('set- & getSize test', function(done) {
let mapWidgetData = new MapWidgetData();
let temp = {
"x": 20,
"y": 12
};
mapWidgetData.setSize(temp);
expect(mapWidgetData.getSize()).equal(temp);
done();
});
it('method getID test', function(done) {
let mapWidgetData = new MapWidgetData(10);
expect(mapWidgetData.getID()).equal(10);
done();
});
it('method getType test', function(done) {
let mapWidgetData = new MapWidgetData(22);
expect(mapWidgetData.getType()).equal(4);
done();
});
it('method getDataCallback test', function(done) {
let mapWidgetData = new MapWidgetData(85);
expect(mapWidgetData.getDataCallback().length).equal(1);
done();
});
it('method newData test', function(done) {
let mapWidgetData = new MapWidgetData(85);
mapWidgetData.newData(88);
expect(mapWidgetData.allData[0]).equal(88);
done();
});
it('method getDataCallback test', function(done) {
let mapWidgetData = new MapWidgetData(76);
let paramMap = {
DataStream_name: true,
DataStream_description: false,
DataStream_observationType: false,
DataStream_unitOfMeasurement: true,
DataStream_observedArea: false,
DataStream_phenomenonTime: true,
DataStream_resultTime: false,
Observation_phenomenonTime: false,
Observation_resultTime: false,
Observation_result: true,
Observation_resultQuality: false,
Observation_validTime: false,
Observation_parameters: false,
FeatureOfInterest_name: true,
FeatureOfInterest_description: true,
FeatureOfInterest_encodingType: true,
FeatureOfInterest_feature: true,
ObservedProperty_name: false,
ObservedProperty_definition: false,
ObservedProperty_description: false,
Sensor_name: false,
Sensor_description: false,
Sensor_encodingType: false,
Sensor_metadata: false,
Thing_name: false,
Thing_description: false,
Thing_properties: false,
Thing_HistoricalLocations: true,
Thing_Location_name: true,
Thing_Location_description: true,
Thing_Location_encodingType: true,
Thing_Location_location: true
};
for(let k in mapWidgetData.getParameterMap()) {
expect(mapWidgetData.getParameterMap()[k]).equal(paramMap[k]);
}
done();
});
it('method set- & getQueryIDs test', function(done) {
let mapWidgetData = new MapWidgetData(42);
let IDs = [1, 2, 3];
mapWidgetData.setQueryIDs(IDs);
expect(mapWidgetData.getQueryIDs()).equal(IDs);
done();
});
it('destroy test', function(done) {
let view = new View();
let mapWidgetData = new MapWidgetData(22);
view._gridstack = view._gridstack || {addWidget: () => {}, removeWidget: () => {}};
view.addWidget(22, '');
mapWidgetData.destroy();
expect(mapWidgetData.dataCallbacks.length).equal(0);
done();
});
it('method getQueryParams test', function(done) {
let mapWidgetData = new MapWidgetData();
expect(mapWidgetData.getQueryParams()[0].type).equal(TYPE_OBJECT);
done();
});
it('method setConfigurableData test', function(done) {
let mapWidgetData = new MapWidgetData(1);
let newConfData = {
// View configuration
title: {
data: 'Map Widget',
type: TYPE_STRING
},
zoom: {
data: 13,
type: TYPE_INTEGER
},
mapURL: {
data: 'https://{s}.tile.iosb.fraunhofer.de/tiles/osmde/{z}/{x}/{y}.png',
type: TYPE_STRING
},
attribution: {
data: "Map data © <a href='http://openstreetmap.org'>OpenStreetMap</a> contributors, <a href='http://creativecommons.org/licenses/by-sa/2.0/'>CC-BY-SA</a>",
type: TYPE_STRING
},
latitude: {
data: 49.014,
type: TYPE_NUMBER
},
longitude: {
data: 8.404,
type: TYPE_NUMBER
},
// Data filter
timeIntervalRelative: {
data: true,
type: TYPE_BOOLEAN
},
timeIntervalUnit: {
data: UNIT_MINUTE,
type: TYPE_DROPDOWN,
options: {
second: UNIT_SECOND,
minute: UNIT_MINUTE,
hour: UNIT_HOUR,
day: UNIT_DAY,
month: UNIT_MONTH,
year: UNIT_YEAR
}
},
timeInterval: {
data: 5,
type: TYPE_INTEGER
},
startTime: {
data: new Date(),
type: TYPE_DATE
},
endTime: {
data: new Date(),
type: TYPE_DATE
},
// ST configuration Attention: multiple Sensors are possible
sensorThingsConfiguration: {
data: [{
data: {
dataStreamUrl: {
data: '',
type: TYPE_FUZZY_SENSOR_SEARCH
},
mqttEnabled: {
data: false,
type: TYPE_BOOLEAN
},
mqttUrl: {
data: '',
type: TYPE_STRING
},
mqttBaseTopic: {
data: '',
type: TYPE_STRING
},
updateIntervalMs: {
data: 1000,
type: TYPE_INTEGER
},
overlayType: {
data: MARKER_TYPE_PLAIN,
type: TYPE_DROPDOWN,
options: {
plainMarker: MARKER_TYPE_PLAIN,
plainValueMarker: MARKER_TYPE_PLAINVALUE,
trafficLightMarker: MARKER_TYPE_TRAFFICLIGHT,
historyLine: MARKER_TYPE_HISTORY
}
},
thresholdMiddle: {
data: 0,
type: TYPE_NUMBER
},
thresholdUpper: {
data: 0,
type: TYPE_NUMBER
},
lowerRangeColor: {
data: COLOR_GREEN,
type: TYPE_DROPDOWN,
options: {
red: COLOR_RED,
yellow: COLOR_YELLOW,
green: COLOR_GREEN
}
},
middleRangeColor: {
data: COLOR_YELLOW,
type: TYPE_DROPDOWN,
options: {
red: COLOR_RED,
yellow: COLOR_YELLOW,
green: COLOR_GREEN
}
},
upperRangeColor: {
data: COLOR_RED,
type: TYPE_DROPDOWN,
options: {
red: COLOR_RED,
yellow: COLOR_YELLOW,
green: COLOR_GREEN
}
}
},
type: TYPE_OBJECT
}],
type: TYPE_ARRAY
}
};
mapWidgetData.setConfigurableData(newConfData);
expect(mapWidgetData.getConfigurableData()).equal(newConfData);
done();
});
}); |
13927729580/hmdm-android | app/src/main/java/com/hmdm/launcher/App.java | <reponame>13927729580/hmdm-android<gh_stars>10-100
/*
* Headwind MDM: Open Source Android MDM Software
* https://h-mdm.com
*
* Copyright (C) 2019 Headwind Solutions LLC (http://h-sms.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hmdm.launcher;
import android.app.Application;
import com.jakewharton.picasso.OkHttp3Downloader;
import com.squareup.picasso.Picasso;
public class App extends Application {
@Override
public void onCreate() {
super.onCreate();
Picasso.Builder builder = new Picasso.Builder(this);
builder.downloader(new OkHttp3Downloader(this,Integer.MAX_VALUE));
Picasso built = builder.build();
//built.setIndicatorsEnabled(true);
//built.setLoggingEnabled(true);
Picasso.setSingletonInstance(built);
}
}
|
Abhis-123/Mallmetering | frontend/src/superadmin/components/setting/GeneralSetting.js | <filename>frontend/src/superadmin/components/setting/GeneralSetting.js
import { Container } from '@material-ui/core'
import React, { Component } from 'react'
class GeneralSetting extends Component {
render() {
return (
<Container fluid className="main-content-container px-4 mt-3">
<div className="card">
</div>
</Container>
)
}
}
export default GeneralSetting
|
arifparvez14/Basic-and-competetive-programming | Basic-Programming/Basic/Array_search.c | <reponame>arifparvez14/Basic-and-competetive-programming
#include <stdio.h>
int main()
{
int i,n,a[100],item,found=0;
printf("How many number do u want:");
scanf("%d",&n);
printf("\nEnter Elements of array:");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("The elements are:");
for(i=0;i<n;i++)
{
printf("%4d",a[i]);
}
printf("\nwhat item do you want to find:");
scanf("%d",&item);
for(i=0;i<n;i++)
{
if(item==a[i])
found=found+1;
else
continue;
}
if(found>=1)
printf("Item Found");
else
printf("Item not Found");
}
|
mnutt/davros | app/components/davros-dropzone.js | <gh_stars>100-1000
import { bind } from '@ember/runloop';
import FileDropzone from 'ember-file-upload/components/file-dropzone/component';
import DragListener from 'ember-file-upload/system/drag-listener';
import { action } from '@ember/object';
const dragListener = new DragListener();
export default class DavrosUploader extends FileDropzone {
@action
addBodyEventListeners() {
dragListener.addEventListeners('body', {
dragenter: bind(this, 'didEnterDropzone'),
dragleave: bind(this, 'didLeaveDropzone'),
dragover: bind(this, 'didDragOver'),
drop: bind(this, 'didDrop'),
});
}
@action
removeBodyEventListeners() {
dragListener.removeEventListeners('body');
}
}
|
showerhhh/leetcode_java | src/t394.java | <filename>src/t394.java<gh_stars>0
import java.util.Stack;
public class t394 {
public static void main(String[] args) {
String s = "3[a2[c]]";
Solution_t394 solution = new Solution_t394();
System.out.println(solution.decodeString(s));
}
}
class Solution_t394 {
public String decodeString(String s) {
Stack<Integer> stack1 = new Stack<>();
Stack<String> stack2 = new Stack<>();
int multi = 0;
String res = "";
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (Character.isDigit(ch)) {
// 数字
multi = multi * 10 + (ch - '0');
} else if (Character.isAlphabetic(ch)) {
// 字母
res += ch;
} else if (ch == '[') {
// 左括号
stack1.push(multi);
stack2.push(res);
multi = 0;
res = "";
} else {
// 右括号
StringBuilder tmp = new StringBuilder();
int t = stack1.pop();
for (int j = 0; j < t; j++) {
tmp.append(res);
}
res = stack2.pop() + tmp.toString();
}
}
return res;
}
} |
pawanup/thirdandgrove-com-gatsby | src/components/Capability/index.js | export { default } from './Capability';
|
TankNee/marktext | src/muya/lib/contentState/htmlBlock.js | import { VOID_HTML_TAGS, HTML_TAGS } from '../config'
import { inlineRules } from '../parser/rules'
const HTML_BLOCK_REG = /^<([a-zA-Z\d-]+)(?=\s|>)[^<>]*?>$/
const htmlBlock = ContentState => {
ContentState.prototype.createHtmlBlock = function (code) {
const block = this.createBlock('figure')
block.functionType = 'html'
const { preBlock, preview } = this.createPreAndPreview('html', code)
this.appendChild(block, preBlock)
this.appendChild(block, preview)
return block
}
ContentState.prototype.initHtmlBlock = function (block) {
let htmlContent = ''
const text = block.children[0].text
const matches = inlineRules.html_tag.exec(text)
if (matches) {
const tag = matches[3]
const content = matches[4] || ''
const openTag = matches[2]
const closeTag = matches[5]
const isVoidTag = VOID_HTML_TAGS.indexOf(tag) > -1
if (closeTag) {
htmlContent = text
} else if (isVoidTag) {
htmlContent = text
if (content) {
// TODO: @jocs notice user that the html is not valid.
console.warn('Invalid html content.')
}
} else {
htmlContent = `${openTag}\n${content}\n</${tag}>`
}
} else {
htmlContent = `<div>\n${text}\n</div>`
}
block.type = 'figure'
block.functionType = 'html'
block.text = htmlContent
block.children = []
const { preBlock, preview } = this.createPreAndPreview('html', htmlContent)
this.appendChild(block, preBlock)
this.appendChild(block, preview)
return preBlock // preBlock
}
ContentState.prototype.updateHtmlBlock = function (block) {
const { type } = block
if (type !== 'li' && type !== 'p') return false
const { text } = block.children[0]
const match = HTML_BLOCK_REG.exec(text)
const tagName = match && match[1] && HTML_TAGS.find(t => t === match[1])
return VOID_HTML_TAGS.indexOf(tagName) === -1 && tagName ? this.initHtmlBlock(block) : false
}
}
export default htmlBlock
|
SebastianWeberKamp/KAMP4APS | edu.kit.ipd.sdq.kamp4aps.aps/src/edu/kit/ipd/sdq/kamp4aps/model/aPS/BusComponents/BusComponentsFactory.java | /**
*/
package edu.kit.ipd.sdq.kamp4aps.model.aPS.BusComponents;
import org.eclipse.emf.ecore.EFactory;
/**
* <!-- begin-user-doc -->
* The <b>Factory</b> for the model.
* It provides a create method for each non-abstract class of the model.
* <!-- end-user-doc -->
* @see edu.kit.ipd.sdq.kamp4aps.model.aPS.BusComponents.BusComponentsPackage
* @generated
*/
public interface BusComponentsFactory extends EFactory {
/**
* The singleton instance of the factory.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
BusComponentsFactory eINSTANCE = edu.kit.ipd.sdq.kamp4aps.model.aPS.BusComponents.impl.BusComponentsFactoryImpl.init();
/**
* Returns a new object of class '<em>Bus Box</em>'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return a new object of class '<em>Bus Box</em>'.
* @generated
*/
BusBox createBusBox();
/**
* Returns a new object of class '<em>Bus Master</em>'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return a new object of class '<em>Bus Master</em>'.
* @generated
*/
BusMaster createBusMaster();
/**
* Returns a new object of class '<em>Bus Slave</em>'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return a new object of class '<em>Bus Slave</em>'.
* @generated
*/
BusSlave createBusSlave();
/**
* Returns a new object of class '<em>Bus Cable</em>'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return a new object of class '<em>Bus Cable</em>'.
* @generated
*/
BusCable createBusCable();
/**
* Returns a new object of class '<em>Profibus DP Box</em>'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return a new object of class '<em>Profibus DP Box</em>'.
* @generated
*/
ProfibusDPBox createProfibusDPBox();
/**
* Returns a new object of class '<em>Profibus DP Master</em>'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return a new object of class '<em>Profibus DP Master</em>'.
* @generated
*/
ProfibusDPMaster createProfibusDPMaster();
/**
* Returns a new object of class '<em>Profibus DP Slave</em>'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return a new object of class '<em>Profibus DP Slave</em>'.
* @generated
*/
ProfibusDPSlave createProfibusDPSlave();
/**
* Returns a new object of class '<em>Profibus DP Cable</em>'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return a new object of class '<em>Profibus DP Cable</em>'.
* @generated
*/
ProfibusDPCable createProfibusDPCable();
/**
* Returns a new object of class '<em>Ether CAT Box</em>'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return a new object of class '<em>Ether CAT Box</em>'.
* @generated
*/
EtherCATBox createEtherCATBox();
/**
* Returns a new object of class '<em>Ether CAT Master</em>'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return a new object of class '<em>Ether CAT Master</em>'.
* @generated
*/
EtherCATMaster createEtherCATMaster();
/**
* Returns a new object of class '<em>Ether CAT Slave</em>'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return a new object of class '<em>Ether CAT Slave</em>'.
* @generated
*/
EtherCATSlave createEtherCATSlave();
/**
* Returns a new object of class '<em>Ether CAT Cable</em>'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return a new object of class '<em>Ether CAT Cable</em>'.
* @generated
*/
EtherCATCable createEtherCATCable();
/**
* Returns the package supported by this factory.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the package supported by this factory.
* @generated
*/
BusComponentsPackage getBusComponentsPackage();
} //BusComponentsFactory
|
Devteamvietnam/iTap | src/main/java/com/devteam/module/account/AccountModel.java | package com.devteam.module.account;
import java.util.List;
import com.devteam.module.account.entity.*;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@NoArgsConstructor
@Getter @Setter
public class AccountModel {
String loginId;
Account account;
UserProfile userProfile;
OrgProfile orgProfile;
public AccountModel(String loginId) {
this.loginId = loginId;
}
public AccountModel(Account account) {
this.loginId = account.getLoginId();
this.account = account;
}
public AccountModel withAccount(Account account) {
this.account = account;
return this;
}
public AccountModel withOrgProfile(OrgProfile profile) {
this.orgProfile = profile;
return this;
}
public AccountModel withUserProfile(UserProfile profile) {
this.userProfile = profile;
return this;
}
}
|
miren521/qirui_saas | app/admin/view/public/js/goods_edit_attr.js | <gh_stars>1-10
var form, laytpl, layerIndex = -1, repeatFlag = false;
var selectedBrand = [];//已选品牌
var selectedBrandCopy = [];//已选品牌初始不变,用于防止已关联的品牌,进行误操作
var deleteBrand = [];//要删除的品牌
var attrValueList = [];// 属性值列表
var deleteAttrValueList = [];//要删除的属性值
$(function () {
$(".ns-custom-panel .custom-panel-content .panel-content li.selected-brand-list span").each(function () {
var brand_id = $(this).attr("data-brand-id");
var id = $(this).attr("data-id");
selectedBrand.push(brand_id);
selectedBrandCopy.push({id: id, brand_id: brand_id});
});
layui.use(['form', 'laytpl'], function () {
form = layui.form;
laytpl = layui.laytpl;
//编辑商品类型信息
form.on('submit(save_attr)', function (data) {
if (repeatFlag) return false;
repeatFlag = true;
$.ajax({
url: ns.url("admin/goodsattr/editAttr"),
data: data.field,
dataType: 'json',
type: 'post',
success: function (data) {
layer.msg(data.message);
if (data.code == 0) {
layer.close(layerIndex);
location.reload();
} else {
repeatFlag = false;
}
}
});
return false;
});
//编辑关联品牌
form.on('submit(save_brand)', function (data) {
if (repeatFlag) return false;
repeatFlag = true;
var brand_id_arr = [];
$(".brand-list ul.selected li").each(function () {
var brand_id = $(this).attr("data-brand-id");
var id = $(this).attr("data-id");
//只添加未关联的品牌
if (!id) brand_id_arr.push(brand_id);
});
if (deleteBrand.length > 0) {
//删除已关联的品牌
$.ajax({
url: ns.url("admin/goodsattr/deleteAttrClassBrand"),
data: {attr_class_id: attr_class_id, id_arr: deleteBrand.toString()},
dataType: 'json',
type: 'post',
async: false,
success: function (data) {
if (brand_id_arr.length === 0) {
layer.close(layerIndex);
layer.msg(data.message);
location.hash = "";
location.reload();
}
}
});
}
if (brand_id_arr.length > 0) {
data.field.brand_id_arr = brand_id_arr.toString();
//添加新关联的品牌
$.ajax({
url: ns.url("admin/goodsattr/addAttrClassBrand"),
data: data.field,
dataType: 'json',
type: 'post',
success: function (data) {
layer.msg(data.message);
if (data.code == 0) {
layer.close(layerIndex);
location.hash = "";
location.reload();
} else {
repeatFlag = false;
}
}
});
}
return false;
});
form.verify({
attr_value: function (value) {
if ($("select[name='attr_type']").val() != 3 && value.length == 0) {
return "请输入属性值名称";
}
},
num: function (value) {
if (value == '') {
return;
}
if (value%1 != 0) {
return '排序数值必须为整数';
}
if (value < 0) {
return '排序数值必须为大于0';
}
}
});
//添加属性、属性值
form.on('submit(save_add_attribute)', function (data) {
if (repeatFlag) return false;
repeatFlag = true;
if (data.field.attr_type != 3) {
var value = [];
for (var i = 0; i < attrValueList.length; i++) {
value.push(attrValueList[i].attr_value_name);
}
data.field.attr_value_list = value.toString();
} else {
data.field.is_query = 0;
}
//开启规格属性后,不参与筛选
if (data.field.is_spec == 1) {
data.field.is_query = 0;
}
var attr_id = 0;
// console.log(data.field);
// return false;
// 添加属性
$.ajax({
url: ns.url("admin/goodsattr/addattribute"),
data: data.field,
dataType: 'json',
type: 'post',
async: false,
success: function (res) {
attr_id = res.data;
if (data.field.attr_type == 3) {
layer.msg(res.message);
if (res.code == 0) {
layer.close(layerIndex);
location.hash = "";
location.reload();
} else {
repeatFlag = false;
}
}
}
});
//输入类型不需要添加属性值
if (data.field.attr_type != 3) {
// 添加属性值
addAttributeValue(attr_id, function (res) {
layer.msg(res.message);
layer.close(layerIndex);
location.hash = "";
location.reload();
});
}
return false;
});
var table = new Table({
elem: '#attribute_list',
url: ns.url("admin/goodsattr/getAttributeList"),
where: {attr_class_id: attr_class_id},
page: false,
parseData: function (data) {
return {
"code": data.code,
"msg": data.message,
"count": data.data.length,
"data": data.data
};
},
cols: [
[
{
field: 'attr_name',
title: '属性名称',
width: '12%',
unresize: 'false'
},
{
title: '属性类型',
width: '10%',
unresize: 'false',
templet: function (data) {
var h = '';
if (data.attr_type == 1) {
h = '单选';
} else if (data.attr_type == 2) {
h = '多选';
} else if (data.attr_type == 3) {
h = '输入';
}
return h;
}
},
{
title: '是否参与筛选',
width: '12%',
unresize: 'false',
templet: function (data) {
var h = data.is_query == 1 ? "是" : "否";
return h;
}
},
{
title: '是否规格属性',
width: '13%',
unresize: 'false',
templet: function (data) {
var h = data.is_spec == 1 ? "是" : "否";
return h;
}
},
{
field: 'attr_value_list',
title: '属性值',
width: '20%',
unresize: 'false'
},
{
field: 'site_name',
title: '店铺名称',
width: '10%',
unresize: 'false'
},
{
unresize: 'false',
field: 'sort',
title: '排序',
width: '10%',
align: 'center',
},
{
title: '操作',
width: '13%',
toolbar: '#attributeOperation',
unresize: 'false'
}
]
]
});
/**
* 监听工具栏操作
*/
table.tool(function (obj) {
var data = obj.data;
switch (obj.event) {
case 'edit':
editAttributePopup(data.attr_id);
break;
case 'delete':
deleteAttribute(data.attr_id);
break;
case 'change':
modifyAttributeSite(data.attr_id);
break;
}
});
//修改属性、属性值
form.on('submit(save_edit_attribute)', function (data) {
if (repeatFlag) return false;
repeatFlag = true;
if (data.field.attr_type != 3) {
var value = [];
for (var i = 0; i < attrValueList.length; i++) {
value.push(attrValueList[i].attr_value_name);
}
data.field.attr_value_list = value.toString();
} else {
data.field.is_query = 0;
}
//开启规格属性后,不参与筛选
if (data.field.is_spec == 1) {
data.field.is_query = 0;
}
if (deleteAttrValueList.length > 0) {
// 删除已存在的属性值
$.ajax({
url: ns.url("admin/goodsattr/deleteAttributeValue"),
data: {attr_class_id: attr_class_id, attr_value_id_arr: deleteAttrValueList.toString()},
dataType: 'json',
type: 'post',
async: false,
success: function (data) {
}
});
}
// 修改已存在的属性值
var isEditAttrValue = [];//已存在的属性值集合
for (var i = 0; i < attrValueList.length; i++) {
//只有已存在的属性值和修改过的属性值才进行push
if (attrValueList[i].is_add && attrValueList[i].is_change) {
attrValueList[i].attr_id = data.field.attr_id;
attrValueList[i].attr_class_id = attr_class_id;
isEditAttrValue.push(attrValueList[i]);
}
}
if (isEditAttrValue.length > 0) {
$.ajax({
url: ns.url("admin/goodsattr/editAttributeValue"),
data: {attr_class_id: attr_class_id, data: JSON.stringify(isEditAttrValue)},
dataType: 'json',
type: 'post',
async: false,
success: function (data) {
}
});
}
if (data.field.attr_type != 3) {
// 添加新的属性值
addAttributeValue(data.field.attr_id);
}
// 修改属性
$.ajax({
url: ns.url("admin/goodsattr/editAttribute"),
data: data.field,
dataType: 'json',
type: 'post',
async: false,
success: function (data) {
layer.msg(data.message);
if (data.code == 0) {
layer.close(layerIndex);
location.hash = "";
location.reload();
} else {
repeatFlag = false;
}
}
});
return false;
});
});
// 已选品牌点击事件
$("body").on("click", ".brand-list ul.selected li", function () {
if ($(this).hasClass("selected")) return;
var _self = this;
var id = $(this).attr("data-id");//已关联品牌
var brand_id = $(this).attr("data-brand-id");
var index = selectedBrand.indexOf(brand_id);//匹配下标
if (id) {
//删除已关联品牌需要再次确认
layerIndex = layer.confirm('当前品牌已关联商品分类,移除后数据会发生不可逆转的行为,请谨慎操作', function () {
deleteBrand.push(id);
$(".brand-list ul.unselected li[data-brand-id='" + brand_id + "']").removeClass("selected");
$(_self).remove();
selectedBrand.splice(index, 1);
layer.close(layerIndex);
});
} else {
$(".brand-list ul.unselected li[data-brand-id='" + brand_id + "']").removeClass("selected");
$(this).remove();
selectedBrand.splice(index, 1);
}
});
// 未选品牌点击事件
$("body").on("click", ".brand-list ul.unselected li", function () {
if ($(this).hasClass("selected")) return;
var brand_id = $(this).attr("data-brand-id");
var brand_name = $(this).children().text();
var id = 0;
//检测当前操作的品牌是否属于已关联的品牌
for (var i = 0; i < selectedBrandCopy.length; i++) {
if (selectedBrandCopy[i].brand_id == brand_id) {
id = selectedBrandCopy[i].id;
break;
}
}
if (id == 0) {
var li = '<li data-brand-id="' + brand_id + '">';
} else {
var li = '<li data-brand-id="' + brand_id + '" data-id="' + id + '" class="ns-text-color-black">';
}
li += '<span>' + brand_name + '</span>';
li += '<i class="layui-icon layui-icon-delete ns-bg-color"></i>';
li += '</li>';
$(".brand-list ul.selected").append(li);
$(this).addClass("selected");
selectedBrand.push(brand_id);
//检测是否要删除的品牌,只有已关联的才能操作
if (id > 0 && deleteBrand.indexOf(id) > -1) {
deleteBrand.splice(deleteBrand.indexOf(id), 1);
}
});
//监听属性值键盘输入事件
$("body").on("keyup", ".attribute-value-list .table-wrap .layui-table input", function () {
var name = $(this).attr("name");
var index = $(this).attr("data-index");
if (name == "attr_value_name") attrValueList[index].attr_value_name = $(this).val();
if (name == "attr_value_sort") attrValueList[index].sort = $(this).val();
attrValueList[index].is_change = true;//标记已修改
});
});
/**
* 打开编辑商品类型弹出框
*/
function editAttrClassPopup() {
var edit_attr_class = $("#editAttrClass").html();
laytpl(edit_attr_class).render({}, function (html) {
layerIndex = layer.open({
title: '编辑商品类型',
skin: 'layer-tips-class',
type: 1,
area: ['550px'],
content: html,
});
});
}
//获取品牌分页列表
function getBrandPageList(page) {
page = page || 1;
$.ajax({
url: ns.url("admin/goodsattr/getBrandPageList"),
data: {page: page, limit: 20},
dataType: 'json',
type: 'post',
success: function (res) {
var data = res.data;
for (var i = 0; i < data.list.length; i++) {
if (selectedBrand.indexOf(data.list[i].brand_id.toString()) > -1) {
data.list[i].selected = true;
} else {
data.list[i].selected = false;
}
}
var edit_brand = $("#brandList").html();
laytpl(edit_brand).render(data.list, function (html) {
$("#brand-wrap").html(html);
});
var page = new Page({
elem: 'page',
count: data.count,
limit: 20,
callback: function (res) {
getBrandPageList(res.page);
}
});
}
});
}
/**
* 编辑关联品牌弹出框
*/
function editBrandPopup() {
var edit_brand = $("#editBrand").html();
laytpl(edit_brand).render({}, function (html) {
layerIndex = layer.open({
title: '编辑关联品牌',
skin: 'layer-tips-class',
type: 1,
area: ['750px', '600px'],
content: html,
success: function () {
getBrandPageList();
}
});
});
}
/**
* 打开添加属性弹出框
*/
function addAttributePopup() {
var add_attr = $("#addAttribute").html();
laytpl(add_attr).render({}, function (html) {
layerIndex = layer.open({
title: '添加属性',
skin: 'layer-tips-class',
type: 1,
area: ['800px', '500px'],
content: html,
success: function () {
form.render();
form.on('select(attr_type)', function (data) {
if (data.value == 3) {
$(".js-is-query").hide();
$(".attribute-value-list").hide();
} else {
$(".js-is-query").show();
$(".attribute-value-list").show();
}
//检测是否开启规格属性
if($("input[name='is_spec']").is(":checked")) {
if (data.value == 1) {
$(".js-is-query").hide();
$(".js-is-spec").show();
} else {
$(".js-is-spec").hide();
}
}
});
form.on('switch(is_spec)', function (data) {
var h = '';
if (this.checked) {
h += '<option value="1">单选</option>';
$(".js-is-query").hide();
} else {
h += '<option value="1">单选</option>';
h += '<option value="2">多选</option>';
h += '<option value="3">输入</option>';
$(".js-is-query").show();
}
$("select[name='attr_type']").html(h);
form.render("select");
});
attrValueList = [];
addAttrValue();
}
});
});
}
//添加属性值
function addAttrValue() {
attrValueList.push({
attr_value_name: "",
sort: 0
});
refreshAttrValueList();
var scrollHeight = $(".attribute-value-list .table-wrap").prop("scrollHeight");
$(".attribute-value-list .table-wrap").scrollTop(scrollHeight)
}
//刷新属性值列表
function refreshAttrValueList() {
var h = '';
for (var i = 0; i < attrValueList.length; i++) {
var item = attrValueList[i];
h += '<tr>';
h += '<td><input name="attr_value_name" type="text" value="' + item.attr_value_name + '" data-index="' + i + '" placeholder="请输入属性值名称" lay-verify="attr_value" class="layui-input ns-len-mid" autocomplete="off"></td>';
h += '<td><input name="attr_value_sort" type="text" value="' + item.sort + '" data-index="' + i + '" placeholder="请输入排序" lay-verify="num" class="layui-input ns-len-small" autocomplete="off"></td>';
h += '<td><a class="ns-text-color" href="javascript:deleteAttrValue(' + i + ');">删除</a></td>';
h += '</tr>';
}
$(".attribute-value-list .layui-table tbody").html(h);
}
//删除属性值
function deleteAttrValue(index) {
if (attrValueList[index].is_add) {
//删除已添加的属性值需要再次确认
layerIndex = layer.confirm('属性值已使用,请谨慎操作', function () {
deleteAttrValueList.push(attrValueList[index].attr_value_id);
attrValueList.splice(index, 1);
refreshAttrValueList();
layer.close(layerIndex);
});
} else {
attrValueList.splice(index, 1);
refreshAttrValueList();
}
}
//删除属性
function deleteAttribute(attr_id) {
//删除属性需要再次确认
layerIndex = layer.confirm('确定要删除吗?', function () {
if (repeatFlag) return false;
repeatFlag = true;
$.ajax({
url: ns.url("admin/goodsattr/deleteAttribute"),
data: {attr_class_id: attr_class_id, attr_id: attr_id},
dataType: 'json',
type: 'post',
success: function (data) {
layer.msg(data.message);
if (data.code == 0) {
layer.close(layerIndex);
location.hash = "";
location.reload();
} else {
repeatFlag = false;
}
}
});
layer.close(layerIndex);
});
}
function modifyAttributeSite(attr_id) {
layer.confirm('确定要转移到平台吗?', function() {
$.ajax({
url: ns.url("admin/goodsattr/modifyattributesite"),
data: {attr_class_id: attr_class_id, attr_id: attr_id},
dataType: 'JSON',
type: 'POST',
success: function (res) {
layer.msg(res.message);
if (res.code == 0) {
location.hash = "";
location.reload();
}
}
});
});
}
/**
* 打开编辑属性弹出框
*/
function editAttributePopup(attr_id) {
$.ajax({
url: ns.url("admin/goodsattr/getAttributeDetail"),
data: {attr_class_id: attr_class_id, attr_id: attr_id},
dataType: 'json',
type: 'post',
success: function (res) {
if (res.code == 0) {
var data = res.data;
var edit_attr = $("#editAttribute").html();
laytpl(edit_attr).render(data, function (html) {
var area = ['800px', '500px'];
if (data.attr_type == 3) {
area = ['800px', '350px'];
}
layerIndex = layer.open({
title: '编辑属性',
skin: 'layer-tips-class',
type: 1,
area: area,
content: html,
success: function () {
form.render();
if (data.is_spec == 1) {
$(".js-is-query").hide();
}
if (data.attr_type == 3) {
$(".js-is-query").hide();
$(".attribute-value-list").hide();
}
form.on('switch(is_spec)', function (data) {
//检测是否开启规格属性
if (data.elem.checked) {
$(".js-is-query").hide();
$("input[name=is_spec]").val(1);
} else {
$(".js-is-query").show();
$("input[name=is_spec]").val(0);
}
});
attrValueList = [];//每次编辑时清空属性值集合
if (data.attr_type != 3 && data.value) {
for (var i = 0; i < data.value.length; i++) {
attrValueList.push({
attr_value_name: data.value[i].attr_value_name,
sort: data.value[i].sort,
is_add: true,// 已添加属性值进行标识
attr_value_id: data.value[i].attr_value_id
});
}
refreshAttrValueList();
}
}
});
});
}
}
});
}
//添加属性值
function addAttributeValue(attr_id, callback) {
attr_id = attr_id || 0;
// 添加属性值
var addAttrValue = [];
for (var i = 0; i < attrValueList.length; i++) {
if (!attrValueList[i].is_add) {
attrValueList[i].attr_id = attr_id;
attrValueList[i].attr_class_id = attr_class_id;
addAttrValue.push(attrValueList[i]);
}
}
if (addAttrValue.length > 0) {
$.ajax({
url: ns.url("admin/goodsattr/addAttributeValue"),
data: {attr_class_id: attr_class_id, value: JSON.stringify(addAttrValue)},
dataType: 'json',
type: 'post',
async: false,
success: function (data) {
if (callback) callback(data);
}
});
}
} |
Next-Gen-UI/Code-Dynamics | Leetcode/0395. Longest Substring with At Least K Repeating Characters/0395.java | <reponame>Next-Gen-UI/Code-Dynamics<filename>Leetcode/0395. Longest Substring with At Least K Repeating Characters/0395.java<gh_stars>0
class Solution {
public int longestSubstring(String s, int k) {
int ans = 0;
for (int n = 1; n <= 26; ++n)
ans = Math.max(ans, longestSubstringWithNUniqueCharacters(s, k, n));
return ans;
}
private int longestSubstringWithNUniqueCharacters(final String s, int k, int n) {
int ans = 0;
int uniqueChars = 0; // unique chars in current substring s[l..r]
int noLessThanK = 0; // # of chars >= k
int[] count = new int[128];
for (int l = 0, r = 0; r < s.length(); ++r) {
if (count[s.charAt(r)] == 0)
++uniqueChars;
if (++count[s.charAt(r)] == k)
++noLessThanK;
while (uniqueChars > n) {
if (count[s.charAt(l)] == k)
--noLessThanK;
if (--count[s.charAt(l)] == 0)
--uniqueChars;
++l;
}
if (noLessThanK == n) // unique chars also == n
ans = Math.max(ans, r - l + 1);
}
return ans;
}
}
|
wangz315/RecipeCollection | app/src/main/java/comp3350/recipecollection/objects/Ingredient.java | package comp3350.recipecollection.objects;
public class Ingredient{
private String name;
private double amount;
private String units;
public Ingredient()
{
name = null;
amount = 0;
units = null;
}
public Ingredient(String newName, double newAmount, String newUnits)
{
name = newName;
amount = newAmount;
units = newUnits;
}
public String getName()
{
return name;
}
public double getAmount()
{
return amount;
}
public String getUnits()
{
return units;
}
public void setName(String newName)
{
name = newName;
}
public void setAmount(double newAmount)
{
amount = newAmount;
}
public void setUnits(String newUnits)
{
units = newUnits;
}
public boolean equals(Object object)
{
boolean result;
Ingredient i;
result = false;
if(object instanceof Ingredient)
{
i = (Ingredient) object;
if(i.name.equals(name))
{
result = true;
}
}
return result;
}
public String toString()
{
String str = String.format("%-10s %4.1f %s", name, amount, units);
return str;
}
}
|
wmarkow/xmb2mybb | xmb2mybb-core/src/main/java/vtech/xmb/grabber/db/mybb/repositories/MybbUserFieldsRepository.java | package vtech.xmb.grabber.db.mybb.repositories;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import vtech.xmb.grabber.db.mybb.entities.MybbUser;
import vtech.xmb.grabber.db.mybb.entities.MybbUserFields;
@Repository
public interface MybbUserFieldsRepository extends CrudRepository<MybbUserFields, Long> {
}
|
MCMDEV/InvUI | InvUI/src/main/java/de/studiocode/invui/animation/impl/SoundAnimation.java | package de.studiocode.invui.animation.impl;
import org.bukkit.Sound;
public abstract class SoundAnimation extends BaseAnimation {
public SoundAnimation(int tickDelay, boolean sound) {
super(tickDelay);
if (sound) addShowHandler((frame, index) -> getCurrentViewers().forEach(player ->
player.playSound(player.getLocation(), Sound.ENTITY_ITEM_PICKUP, 1, 1)));
}
}
|
nguyenb-adsk/maya-usd | lib/usd/utils/util.cpp | //
// Copyright 2020 Autodesk
//
// 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 "util.h"
#include <pxr/usd/pcp/layerStack.h>
#include <pxr/usd/sdf/layer.h>
#include <pxr/usd/usd/prim.h>
#include <pxr/usd/usd/primCompositionQuery.h>
#include <pxr/usd/usd/primRange.h>
#include <pxr/usd/usd/references.h>
#include <pxr/usd/usd/stage.h>
PXR_NAMESPACE_USING_DIRECTIVE
namespace {
std::map<std::string, std::string> getDict(const UsdPrimCompositionQueryArc& arc)
{
std::string arcType;
switch (arc.GetArcType()) {
case PcpArcTypeRoot: arcType = "PcpArcTypeRoot"; break;
case PcpArcTypeReference: arcType = "PcpArcTypeReference"; break;
case PcpArcTypePayload: arcType = "PcpArcTypePayload"; break;
case PcpArcTypeInherit: arcType = "PcpArcTypeInherit"; break;
case PcpArcTypeSpecialize: arcType = "PcpArcTypeSpecialize"; break;
case PcpArcTypeVariant: arcType = "PcpArcTypeVariant"; break;
default: break;
}
auto introducingLayer = arc.GetIntroducingLayer();
auto introducingNode = arc.GetIntroducingNode();
return {
{ "arcType", arcType },
{ "hasSpecs", arc.HasSpecs() ? "True" : "False" },
{ "introLayer", introducingLayer ? introducingLayer->GetRealPath() : "" },
{ "introLayerStack",
introducingNode
? introducingNode.GetLayerStack()->GetIdentifier().rootLayer->GetRealPath()
: "" },
{ "introPath", arc.GetIntroducingPrimPath().GetString() },
{ "isAncestral", arc.IsAncestral() ? "True" : "False" },
{ "isImplicit", arc.IsImplicit() ? "True" : "False" },
{ "isIntroRootLayer", arc.IsIntroducedInRootLayerStack() ? "True" : "False" },
{ "isIntroRootLayerPrim", arc.IsIntroducedInRootLayerPrimSpec() ? "True" : "False" },
{ "nodeLayerStack",
arc.GetTargetNode().GetLayerStack()->GetIdentifier().rootLayer->GetRealPath() },
{ "nodePath", arc.GetTargetNode().GetPath().GetString() },
};
}
void replaceReferenceItems(
const UsdPrim& oldPrim,
const SdfPath& newPath,
const SdfReferencesProxy& referencesList,
SdfListOpType op)
{
// set the listProxy based on the SdfListOpType
SdfReferencesProxy::ListProxy listProxy = referencesList.GetAppendedItems();
if (op == SdfListOpTypePrepended) {
listProxy = referencesList.GetPrependedItems();
} else if (op == SdfListOpTypeOrdered) {
listProxy = referencesList.GetOrderedItems();
} else if (op == SdfListOpTypeAdded) {
listProxy = referencesList.GetAddedItems();
} else if (op == SdfListOpTypeDeleted) {
listProxy = referencesList.GetDeletedItems();
}
// fetching the existing SdfReference items and using
// the Replace() method to replace them with updated SdfReference items.
for (const SdfReference ref : listProxy) {
if (MayaUsdUtils::isInternalReference(ref)) {
SdfPath finalPath;
if (oldPrim.GetPath() == ref.GetPrimPath()) {
finalPath = newPath;
} else if (ref.GetPrimPath().HasPrefix(oldPrim.GetPath())) {
finalPath = ref.GetPrimPath().ReplacePrefix(oldPrim.GetPath(), newPath);
}
if (finalPath.IsEmpty()) {
continue;
}
// replace the old reference with new one
SdfReference newRef;
newRef.SetPrimPath(finalPath);
listProxy.Replace(ref, newRef);
}
}
}
} // namespace
namespace MayaUsdUtils {
SdfLayerHandle defPrimSpecLayer(const UsdPrim& prim)
{
// Iterate over the layer stack, starting at the highest-priority layer.
// The source layer is the one in which there exists a def primSpec, not
// an over.
SdfLayerHandle defLayer;
auto layerStack = prim.GetStage()->GetLayerStack();
for (auto layer : layerStack) {
auto primSpec = layer->GetPrimAtPath(prim.GetPath());
if (primSpec && (primSpec->GetSpecifier() == SdfSpecifierDef)) {
defLayer = layer;
break;
}
}
return defLayer;
}
SdfPrimSpecHandle getPrimSpecAtEditTarget(const UsdPrim& prim)
{
auto stage = prim.GetStage();
return stage->GetEditTarget().GetPrimSpecForScenePath(prim.GetPath());
}
void printCompositionQuery(const UsdPrim& prim, std::ostream& os)
{
UsdPrimCompositionQuery query(prim);
os << "[\n";
// the composition arcs are always returned in order from strongest
// to weakest regardless of the filter.
for (const auto& arc : query.GetCompositionArcs()) {
const auto& arcDic = getDict(arc);
os << "{\n";
std::for_each(arcDic.begin(), arcDic.end(), [&](const auto& it) {
os << it.first << ": " << it.second << '\n';
});
os << "}\n";
}
os << "]\n\n";
}
bool updateInternalReferencesPath(const UsdPrim& oldPrim, const SdfPath& newPath)
{
SdfChangeBlock changeBlock;
for (const auto& p : oldPrim.GetStage()->Traverse()) {
if (p.HasAuthoredReferences()) {
auto primSpec = getPrimSpecAtEditTarget(p);
if (primSpec) {
SdfReferencesProxy referencesList = primSpec->GetReferenceList();
// update append/prepend lists individually
replaceReferenceItems(oldPrim, newPath, referencesList, SdfListOpTypeAppended);
replaceReferenceItems(oldPrim, newPath, referencesList, SdfListOpTypePrepended);
}
}
}
return true;
}
bool isInternalReference(const SdfReference& ref)
{
#if USD_VERSION_NUM >= 2008
return ref.IsInternal();
#else
return ref.GetAssetPath().empty();
#endif
}
} // namespace MayaUsdUtils
|
yanzhaoyl/lin-cms-java-core | core/src/main/java/io/github/talelin/core/util/EncryptUtil.java | package io.github.talelin.core.util;
import com.amdelamar.jhash.Hash;
import com.amdelamar.jhash.algorithms.Type;
import com.amdelamar.jhash.exception.InvalidHashException;
/**
* 加密工具类
*
* @author pedro@TaleLin
*/
public class EncryptUtil {
/**
* 设置密文密码
*
* @param password <PASSWORD>
* @return 加密密码
*/
public static String encrypt(String password) {
char[] chars = password.toCharArray();
return Hash.password(chars).algorithm(Type.PBKDF2_SHA256).create();
}
/**
* 验证加密密码
*
* @param encryptedPassword 密文密码
* @param plainPassword <PASSWORD>
* @return 验证是否成功
*/
public static boolean verify(String encryptedPassword, String plainPassword) {
char[] chars = plainPassword.toCharArray();
try {
return Hash.password(chars).algorithm(Type.PBKDF2_SHA256).verify(encryptedPassword);
} catch (InvalidHashException e) {
return false;
}
}
}
|
kandelk/Training-Repository | sample/Aws/emr/Analysis/analysis.py | <gh_stars>0
import io
from configparser import ConfigParser
from pyspark.sql import functions as func, SparkSession
from pyspark.sql.functions import col
from sample.Tweets.Utils.plot_utils import *
def get_dataframe_from_view(view):
return spark.read.jdbc(
url=db_url,
table=view,
properties=db_properties
)
def analyze_tweets():
tweets_view = get_dataframe_from_view('managers_view')
count_by_date_list = tweets_view \
.groupBy(func.col("created_at")) \
.count() \
.sort(col("created_at").asc()) \
.collect()
counts_list = [int(row['count']) for row in count_by_date_list]
dates_list = [row['created_at'] for row in count_by_date_list]
create_and_save_hbar(counts_list, dates_list, save_plot_folder, 'tweet')
def analyze_youtube_by_date():
youtube_view = get_dataframe_from_view("youtube_view")
count_by_date_list = youtube_view \
.groupBy(func.col("publishedAt")) \
.count() \
.sort(col("publishedAt").asc()) \
.collect()
counts_list = [int(row['count']) for row in count_by_date_list]
dates_list = [row['publishedAt'] for row in count_by_date_list]
create_and_save_hbar(counts_list, dates_list, save_plot_folder, 'youtube-date')
def analyze_youtube_by_channel():
youtube_view = get_dataframe_from_view("youtube_view")
count_by_date_list = youtube_view \
.groupBy(func.col("channelTitle")) \
.count() \
.sort(col("channelTitle").asc()) \
.collect()
counts_list = [int(row['count']) for row in count_by_date_list]
dates_list = [row['channelTitle'] for row in count_by_date_list]
create_and_save_hbar(counts_list, dates_list, save_plot_folder, 'youtube-channel')
def main():
analyze_tweets()
analyze_youtube_by_date()
analyze_youtube_by_channel()
if __name__ == "__main__":
spark = SparkSession.builder \
.getOrCreate()
sc = spark.sparkContext
config_list = sc.textFile("s3://project.tweet.functions/resources/settings.ini").collect()
buf = io.StringIO("\n".join(config_list))
config = ConfigParser()
config.read_file(buf)
db_conf = config['postgresql']
db_url = db_conf['url_rds']
db_properties = {'user': db_conf['username'], 'password': db_conf['password'], 'driver': db_conf['driver']}
save_plot_folder = config['s3']['plot_save_bucket']
main()
|
fleetbase/navigator-app | src/features/Shared/NavigationScreen.js | <reponame>fleetbase/navigator-app
import React, { useState, useEffect, useCallback, createRef } from 'react';
import { ScrollView, View, Text, TouchableOpacity, TextInput, ActivityIndicator, RefreshControl, Alert, Dimensions } from 'react-native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { FontAwesomeIcon } from '@fortawesome/react-native-fontawesome';
import { faTimes, faLocationArrow } from '@fortawesome/free-solid-svg-icons';
import { Order, Place } from '@fleetbase/sdk';
import { useMountedState, useLocale, useDriver, useFleetbase } from 'hooks';
import { getCurrentLocation, formatCurrency, formatKm, formatDistance, calculatePercentage, translate, logError, isEmpty, isArray, getColorCode, titleize, formatMetaValue } from 'utils';
import { format } from 'date-fns';
import MapboxNavigation from '@homee/react-native-mapbox-navigation';
import FastImage from 'react-native-fast-image';
import OrderStatusBadge from 'ui/OrderStatusBadge';
import tailwind from 'tailwind';
const NavigationScreen = ({ navigation, route }) => {
const { _order, _destination } = route.params;
const insets = useSafeAreaInsets();
const isMounted = useMountedState();
const actionSheetRef = createRef();
const fleetbase = useFleetbase();
const [driver, setDriver] = useDriver();
const [locale] = useLocale();
const [order, setOrder] = useState(new Order(_order, fleetbase.getAdapter()));
const [destination, setDestination] = useState(new Place(_destination, fleetbase.getAdapter()));
const [origin, setOrigin] = useState(null);
const [isLoading, setIsLoading] = useState(false);
const extractOriginCoordinates = useCallback((_origin) => {
if (_origin?.coordinates && isArray(_origin?.coordinates)) {
return _origin?.coordinates?.reverse();
}
if (_origin?.coords && _origin?.coords?.latitude && _origin?.coords?.longitude) {
return [ _origin?.coords?.longitude, _origin?.coords?.latitude];
}
});
const coords = {
origin: extractOriginCoordinates(origin),
destination: destination?.getAttribute('location.coordinates'),
};
const isReady = isArray(coords?.origin) && isArray(coords?.destination);
const trackDriverLocation = useCallback((event) => {
// const { distanceTraveled, durationRemaining, fractionTraveled, distanceRemaining } = event.nativeEvent;
const { latitude, longitude } = event.nativeEvent;
return driver.track({ latitude, longitude }).catch(logError);
});
useEffect(() => {
getCurrentLocation().then(setOrigin).catch(logError);
}, [isMounted]);
return (
<View style={[tailwind('bg-gray-800 h-full')]}>
<View style={[tailwind('z-50 bg-gray-800 border-b border-gray-900 shadow-lg'), { paddingTop: insets.top }]}>
<View style={tailwind('flex flex-row items-start justify-between px-4 py-2 overflow-hidden')}>
<View style={tailwind('flex-1 flex items-start')}>
<View style={tailwind('flex flex-row items-center')}>
<FontAwesomeIcon icon={faLocationArrow} style={tailwind('text-blue-100 mr-2')} />
<Text style={tailwind('text-xl font-semibold text-blue-100')}>Navigation</Text>
</View>
<Text style={tailwind('text-gray-50')} numberOfLines={1}>
{destination.getAttribute('address')}
</Text>
</View>
<View>
<TouchableOpacity onPress={() => navigation.goBack()} style={tailwind('')}>
<View style={tailwind('rounded-full bg-gray-900 w-10 h-10 flex items-center justify-center')}>
<FontAwesomeIcon icon={faTimes} style={tailwind('text-red-400')} />
</View>
</TouchableOpacity>
</View>
</View>
</View>
{isReady ? (
<MapboxNavigation
origin={coords.origin}
destination={coords.destination}
showsEndOfRouteFeedback={true}
onLocationChange={trackDriverLocation}
onRouteProgressChange={(event) => {
const { distanceTraveled, durationRemaining, fractionTraveled, distanceRemaining } = event.nativeEvent;
}}
onError={(event) => {
const { message } = event.nativeEvent;
}}
onCancelNavigation={() => navigation.goBack()}
onArrive={() => {
// Called when you arrive at the destination.
}}
/>
) : (
<View style={tailwind('flex items-center justify-center h-full w-full bg-gray-600 -mt-14')}>
<ActivityIndicator size={'large'} color={getColorCode('text-blue-300')} />
</View>
)}
</View>
);
};
export default NavigationScreen;
|
bwittman/shadow | src/main/java/shadow/tac/nodes/TACCatchRet.java | package shadow.tac.nodes;
import shadow.ShadowException;
import shadow.tac.TACVisitor;
public class TACCatchRet extends TACNode {
private final TACCatchPad catchPad;
private final TACLabel label;
public TACCatchRet(TACNode node, TACCatchPad catchPad, TACLabel label) {
super(node);
this.catchPad = catchPad;
this.label = label;
}
public TACLabel getLabel() {
return label;
}
public TACCatchPad getCatchPad() {
return catchPad;
}
@Override
public int getNumOperands() {
return 0;
}
@Override
public TACOperand getOperand(int num) {
throw new IndexOutOfBoundsException("" + num);
}
@Override
public void accept(TACVisitor visitor) throws ShadowException {
visitor.visit(this);
}
}
|
H-Tatsuhiro/Com_Pro-Cpp | AtCoder/pakencamp-2020-day1/a/main.cpp | <reponame>H-Tatsuhiro/Com_Pro-Cpp
#include <iostream>
#include <cmath>
#include <algorithm>
#include <vector>
using namespace std;
int main() {
cout << 2021 << endl;
}
|
abhi0987/photocraft-image-editing-app | Pencil/app/src/main/java/pencil/abhishek/io/pencil/Photo_list.java | package pencil.abhishek.io.pencil;
import android.app.Dialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.graphics.Rect;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityOptionsCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.support.v7.widget.Toolbar;
import android.system.Os;
import android.text.Spannable;
import android.text.SpannableString;
import android.util.Log;
import android.util.TypedValue;
import android.view.Display;
import android.view.GestureDetector;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import com.adobe.creativesdk.aviary.AdobeImageIntent;
import com.adobe.creativesdk.aviary.internal.filters.ToolLoaderFactory;
import com.adobe.creativesdk.aviary.internal.headless.utils.MegaPixels;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import pencil.abhishek.io.pencil.Adapter.pic_adapter;
import pencil.abhishek.io.pencil.utills.TypefaceSpan;
public class Photo_list extends AppCompatActivity {
public static int REQUST_SHOW = 654 ;
RecyclerView recyclerView;
private int columnWidth;
private int imageWidth;
public static final int GRID_PADDING = 2;
float padding;
ArrayList<String> picList ;
String bucket;
public static pic_adapter picAdapter ;
ArrayList<Integer> hList ;
ArrayList<Integer> wList;
SharedPreferences pref_shp , show_pref;
@Override
public void finish() {
Intent returnIntent = new Intent();
setResult(RESULT_OK);
super.finish();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_photo_list);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
show_pref = getSharedPreferences("STORE_EACH_PIC",MODE_PRIVATE);
pref_shp = getSharedPreferences("STORE_ALBUM_NAME",MODE_PRIVATE);
// bucket = getIntent().getStringExtra("Bucket_name");
bucket = pref_shp.getString("BUCKET_NAME",null);
SpannableString s = new SpannableString(bucket.toUpperCase());
s.setSpan(new TypefaceSpan(this, "urban.otf"), 0, s.length(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
getSupportActionBar().setTitle(s);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
InitilizeGridLayout();
recyclerView = (RecyclerView) findViewById(R.id.recyclerView_pic);
recyclerView.setLayoutManager(new GridLayoutManager(this,2));
recyclerView.addItemDecoration(new GridSpaceItemDecoration(2,dpToPx(2),true));
new load_pic_sync().execute();
recyclerView.addOnItemTouchListener(new RecyclerTouchListener(this, recyclerView, new ClickListener() {
@Override
public void onClick(View view, int position) {
SharedPreferences.Editor editor = show_pref.edit();
Intent show_intent = new Intent(Photo_list.this,Show_Image.class);
editor.putString("one_image",picList.get(position));
editor.putInt("postion",position);
editor.commit();
// show_intent.putExtra("Img_uri_string",picList.get(position));
// show_intent.putExtra("position_",position);
startActivityForResult(show_intent,REQUST_SHOW);
overridePendingTransition(R.anim.activity_open_scale,R.anim.activity_close_scale);
}
@Override
public void onLongClick(View view, int position) {
}
}));
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode==REQUST_SHOW && resultCode == RESULT_OK){
recreate();
picAdapter.notifyDataSetChanged();
}
}
@Override
public void onBackPressed() {
super.onBackPressed();
overridePendingTransition(R.anim.activity_open_scale,R.anim.activity_close_scale);
}
public static interface ClickListener {
public void onClick(View view, int position);
public void onLongClick(View view, int position);
}
static class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {
private GestureDetector gestureDetector;
private ClickListener clickListener;
public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final ClickListener clickListener) {
this.clickListener = clickListener;
gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
@Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null) {
clickListener.onLongClick(child, recyclerView.getChildPosition(child));
}
}
});
}
@Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
clickListener.onClick(child, rv.getChildPosition(child));
}
return false;
}
@Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
@Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
public class load_pic_sync extends AsyncTask<Void,Void,Void>{
@Override
protected Void doInBackground(Void... params) {
getImagesOfBucket(bucket);
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
picAdapter = new pic_adapter(getBaseContext(),picList,hList,columnWidth);
recyclerView.setAdapter(picAdapter);
}
private void getImagesOfBucket(String bucket) {
picList = new ArrayList<>();
hList = new ArrayList<>();
wList = new ArrayList<>();
final String orderBy = MediaStore.Images.Media.DATE_ADDED;
final String[] columns = { MediaStore.Images.Media.DATA,MediaStore.Images.Media._ID ,MediaStore.Images.Media.HEIGHT, MediaStore.Images.Media.WIDTH};
String searchParams = null;
searchParams = "bucket_display_name = \"" + bucket + "\"";
Cursor mPhotoCursor = getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns,
searchParams, null, orderBy + " DESC");
if (mPhotoCursor.moveToFirst()){
do {
String imgdata = mPhotoCursor.getString(mPhotoCursor.getColumnIndex(MediaStore.Images.Media.DATA));
int height = mPhotoCursor.getInt(mPhotoCursor.getColumnIndex(MediaStore.Images.Media.HEIGHT));
int width = mPhotoCursor.getInt(mPhotoCursor.getColumnIndex(MediaStore.Images.Media.WIDTH));
picList.add(imgdata);
hList.add(height);
wList.add(width);
}while (mPhotoCursor.moveToNext());
}
mPhotoCursor.close();
}
}
private void InitilizeGridLayout() {
Resources r = getResources();
padding = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
GRID_PADDING, r.getDisplayMetrics());
// Column width
imageWidth = getScreenWidth();
columnWidth = (int) ((getScreenWidth() - ((
2 + 1) * padding)) /
2);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case android.R.id.home:
onBackPressed();
overridePendingTransition(R.anim.activity_open_scale,R.anim.activity_close_scale);
return true ;
default:
return super.onOptionsItemSelected(item);
}
}
public class GridSpaceItemDecoration extends RecyclerView.ItemDecoration{
private int spanCount;
private int spacing;
private boolean includeEdge;
public GridSpaceItemDecoration(int spanCount, int spacing, boolean includeEdge) {
this.spanCount = spanCount;
this.spacing = spacing;
this.includeEdge = includeEdge;
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
super.getItemOffsets(outRect, view, parent, state);
int position = parent.getChildAdapterPosition(view); // item position
int column = position % spanCount; // item column
if (includeEdge) {
outRect.left = spacing - column * spacing / spanCount; // spacing - column * ((1f / spanCount) * spacing)
outRect.right = (column + 1) * spacing / spanCount; // (column + 1) * ((1f / spanCount) * spacing)
if (position < spanCount) { // top edge
outRect.top = spacing;
}
outRect.bottom = spacing; // item bottom
} else {
outRect.left = column * spacing / spanCount; // column * ((1f / spanCount) * spacing)
outRect.right = spacing - (column + 1) * spacing / spanCount; // spacing - (column + 1) * ((1f / spanCount) * spacing)
if (position >= spanCount) {
outRect.top = spacing; // item top
}
}
}
}
private int dpToPx(int dp) {
Resources r = getResources();
return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, r.getDisplayMetrics()));
}
public int getScreenWidth(){
int columnWidth;
WindowManager wm = (WindowManager)getBaseContext().getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
final Point point = new Point();
try{
display.getSize(point);
}catch (NoSuchMethodError e){
point.x = display.getWidth();
point.y = display.getHeight();
}
columnWidth=point.x;
return columnWidth;
}
}
|
ljcservice/autumn | src/main/java/com/ts/util/ConvertCharacter.java | package com.ts.util;
import java.util.HashMap;
import java.util.Map;
public class ConvertCharacter {
private static Map<String,String> map = new HashMap<String,String>();
static{
map.put("<", "<");
map.put(">", ">");
map.put("/", "⁄");
map.put("\"", """);
}
public static String specilConvertCharacter(String content){
if(content==null) return content;
for(String s: map.keySet()){
content = content.replaceAll(s, map.get(s));
}
return content;
}
}
|
YoungTeam/kratos | net/yt/kratos/net/frontend/hanlder/command/UseHandler.java | <filename>net/yt/kratos/net/frontend/hanlder/command/UseHandler.java<gh_stars>0
/*
* Copyright 2019 YoungTeam@Sogou Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package yt.kratos.net.frontend.hanlder.command;
import yt.kratos.mysql.proto.ErrorCode;
import yt.kratos.net.frontend.FrontendConnection;
/**
* @ClassName: UseHandler
* @Description: TODO(这里用一句话描述这个类的作用)
* @author YoungTeam
* @date 2019年1月22日 下午11:48:10
*
*/
public class UseHandler {
public static void handle(String sql, FrontendConnection c, int offset) {
String schema = sql.substring(offset).trim();
int length = schema.length();
if (length > 0) {
if (schema.charAt(0) == '`' && schema.charAt(length - 1) == '`') {
schema = schema.substring(1, length - 2);
}
}
// 表示当前连接已经指定了schema
if (c.getSchema() != null) {
if (c.getSchema().equals(schema)) {
c.writeOk();
} else {
c.writeErrMessage(ErrorCode.ER_DBACCESS_DENIED_ERROR, "Not allowed to change the database!");
}
return;
}
c.setSchema(schema);
c.writeOk();
}
}
|
gglin001/popart | willow/src/patterns/adamdecompose.cpp | // Copyright (c) 2020 Graphcore Ltd. All rights reserved.
#include <memory>
#include <onnxutil.hpp>
#include <popart/ces/concatce.hpp>
#include <popart/ces/flattence.hpp>
#include <popart/ces/slicece.hpp>
#include <popart/graph.hpp>
#include <popart/ir.hpp>
#include <popart/op/accumulate.hpp>
#include <popart/op/adamcombo.hpp>
#include <popart/op/adamupdater.hpp>
#include <popart/op/adamvarupdate.hpp>
#include <popart/op/cast.hpp>
#include <popart/op/collectives/replicatedallreduce.hpp>
#include <popart/op/concat.hpp>
#include <popart/op/copyvarupdate.hpp>
#include <popart/op/div.hpp>
#include <popart/op/lamb.hpp>
#include <popart/op/slice.hpp>
#include <popart/patterns/adamdecompose.hpp>
#include <popart/tensor.hpp>
#include <popart/tensorinfo.hpp>
#include <popart/topocons.hpp>
namespace popart {
namespace {
TensorId getLossScaleDerivativeTensorId(TensorId tid, Op *combo) {
// Replaces lossScaling_ with tid. This handles cases
// where each comboOp has a specific lossScaling tensor.
auto id = tid;
auto lsId = combo->inId(AdamComboOp::getLsInIndex());
auto lsPrefix = std::string(reservedLossScalingPrefix());
auto pos = lsId.find(lsPrefix);
if (pos != std::string::npos) {
id = lsId;
id.replace(pos, lsPrefix.length(), tid);
}
// If a non-specific lossScaling tensor is used, then we want
// have a derivative per VirtualGraph to avoid IpuCopies
// in the optimizer step. Note: These are harmless if a specific lossScaling
// tensor is used.
if (combo->hasVirtualGraphId()) {
id += "_vgid" + std::to_string(combo->getVirtualGraphId());
}
return id;
}
} // namespace
bool AdamDecompose::matches(Op *op) const {
return op->isConvertibleTo<AdamComboOp>();
}
std::vector<const Tensor *> AdamDecompose::touches(Op *) const { return {}; }
std::pair<Op *, TensorId>
AdamDecompose::rescaleAccl(Graph &graph,
AdamComboOp *combo,
bool accl1,
TensorId acclId,
TensorId gradIntoAcclId,
TensorId rescaleRatioId) const {
std::string acclName = accl1 ? "_accl1" : "_accl2";
OptimizerValue value = accl1 ? combo->initB1 : combo->initB2;
AccumulationType type = accl1 ? AccumulationType::MovingAverage
: (combo->mode == AdamMode::AdaMax
? AccumulationType::Infinity
: AccumulationType::MovingAverageSquare);
// The updated accl
TensorId updatedAcclId = graph.getIr().createIntermediateTensorId(acclId);
auto acclOp = graph.createConnectedOp<RescaleAccumulateOp>(
{{VarUpdateOp::getVarToUpdateInIndex(), acclId},
{VarUpdateWithUpdaterOp::getUpdaterInIndex(), gradIntoAcclId},
{RescaleAccumulateOp::getRescaleRatioInIndex(), rescaleRatioId}},
{{VarUpdateOp::getUpdatedVarOutIndex(), updatedAcclId}},
type,
value,
Op::Settings(graph, combo->name() + acclName));
transferBaseProperties(combo, acclOp);
if (!value.isConst()) {
TensorId valueTensorId = accl1
? combo->inId(AdamComboOp::getBeta1InIndex())
: combo->inId(AdamComboOp::getBeta2InIndex());
acclOp->connectInTensor(AccumulateOp::getFactorInIndex(), valueTensorId);
}
if (combo->withGradAccum) {
acclOp->settings.executionContext =
ExecutionContext::AccumulateOuterFragment;
acclOp->setExecutionPhase({});
acclOp->settings.schedulePriority = 0.0;
}
graph.getIr().addAdditionalModelProtoTensor(acclId);
return {acclOp, updatedAcclId};
}
TensorId AdamDecompose::rescaleRatio(Graph &graph, AdamComboOp *combo) const {
// When using `scaledOptimizerState` and nonConst lossScaling
// if the loss scaling changes the optimizer state must also
// be rescaled to match the new value. This can be done by rescaling
// at the same time as accumulating.
// To achieve this a tensor is added to graph which equals:
// ratio = lossScaling / previousLossScaling
// At the end of each optimizer step, previousLossScaling is assigned to
// lossScaling. This gives the behaviour that between steps if the user calls
// OptimizerFromHost with a new lossScaling value:
// ratio != 1 -> state will be rescaled
// otherwise:
// ratio = 1 -> state will keep the same scaling
auto &ir = graph.getIr();
TensorId lossScalingId = combo->inId(AdamComboOp::getLsInIndex());
TensorId prevLossScalingId = getLossScaleDerivativeTensorId(
reservedPreviousLossScalingPrefix(), combo);
if (!graph.getTensors().contains(prevLossScalingId)) {
if (ir.tensorExistsInInitialisers(prevLossScalingId)) {
auto tp = onnxutil::getTensorProto(ir.getModel(), prevLossScalingId);
graph.getTensors().addVarInit(prevLossScalingId, &tp);
} else {
TensorInfo lsInfo(DataType::FLOAT, {});
std::vector<float> lsData(lsInfo.nelms(), combo->initLs.val());
graph.getTensors().addVarInit(prevLossScalingId, lsInfo, lsData.data());
ir.addAdditionalModelProtoTensor(prevLossScalingId);
}
}
TensorId ratioId =
getLossScaleDerivativeTensorId(reservedLossScalingRatioPrefix(), combo);
if (!graph.getTensors().contains(ratioId)) {
auto calcRatio = graph.createConnectedOp<DivOp>(
{{0, lossScalingId}, {1, prevLossScalingId}},
{{0, ratioId}},
Onnx::Operators::Div_7,
Op::Settings(graph, combo->name() + "_lsRatio"));
transferBaseProperties(combo, calcRatio);
TensorId updatedPrevLossScalingId =
ir.createIntermediateTensorId(prevLossScalingId);
auto updatePrevLossScaling = graph.createConnectedOp<CopyVarUpdateOp>(
{{0, prevLossScalingId}, {1, lossScalingId}},
{{0, updatedPrevLossScalingId}},
Op::Settings(graph, combo->name() + "_updatePrevLossScaling"));
transferBaseProperties(combo, updatePrevLossScaling);
if (combo->withGradAccum) {
calcRatio->settings.executionContext =
ExecutionContext::AccumulateOuterFragment;
calcRatio->setExecutionPhase({});
calcRatio->settings.schedulePriority = 0.0;
updatePrevLossScaling->settings.executionContext =
ExecutionContext::AccumulateOuterFragment;
updatePrevLossScaling->setExecutionPhase({});
updatePrevLossScaling->settings.schedulePriority = 0.0;
}
graph.topoCons->insert(calcRatio, updatePrevLossScaling);
}
return ratioId;
}
bool AdamDecompose::apply(Op *op) const {
auto &graph = op->getGraph();
// matches must have verified the correctness before this call
auto combo = static_cast<AdamComboOp *>(op);
Tensor *weightGrad =
combo->inTensor(VarUpdateWithUpdaterOp::getUpdaterInIndex());
Tensor *weight = combo->inTensor(VarUpdateOp::getVarToUpdateInIndex());
Tensor *newWeight = combo->outTensor(VarUpdateOp::getUpdatedVarOutIndex());
TensorId weightGradId = weightGrad->id;
TensorId weightId = weight->id;
TensorId updatedWeightId = newWeight->id;
// Qualified tensor names for key tensors of the Adam/Lamb optimizers
auto stepId = reservedStepPrefix() + weightId;
auto accumId = reservedAccumPrefix() + weightId;
auto accl1Id = reservedAccl1Prefix() + weightId;
auto accl2Id = reservedAccl2Prefix() + weightId;
auto adamUpdaterId = reservedAdamUpdaterPrefix() + weightId;
auto lambR1SqId = reservedLambR1SqPrefix() + weightId;
auto lambR2SqId = reservedLambR2SqPrefix() + weightId;
if (combo->mode == AdamMode::Adam || combo->mode == AdamMode::Lamb ||
combo->mode == AdamMode::AdaMax) {
// Step
addStateTensor<float>(graph, stepId, TensorInfo(DataType::FLOAT, {}));
graph.getIr().addAdditionalModelProtoTensor(stepId);
}
if (weightGrad->info.dataType() != weight->info.dataType()) {
throw error("Currently, weight and weight gradient should have the same "
"type in AdamDecompose, this is outstanding work");
}
auto weightInfo = weight->info;
auto weightShape = weightInfo.shape();
// Accumulator
if (combo->withGradAccum) {
addStateTensor(graph, accumId, weightShape, combo->accumType);
}
// 1st momentum (accl1)
addStateTensor(graph, accl1Id, weightShape, combo->accl1Type);
// 2nd momentum (accl2)
addStateTensor(graph, accl2Id, weightShape, combo->accl2Type);
TensorId gradIntoAcclId = weightGradId;
TensorId gradIntoAccumId = weightGradId;
if (combo->reductionType == OptimizerReductionType::GradReduce) {
TensorId reducedId = gradReduce(graph, combo, weightGradId);
gradIntoAcclId = reducedId;
gradIntoAccumId = reducedId;
}
// Gradient accumulation
if (combo->withGradAccum) {
gradIntoAcclId =
gradAccum(graph,
combo,
accumId,
gradIntoAccumId,
combo->reductionType == OptimizerReductionType::AccumReduce);
}
// Cast if accumulator is fp16, and optimizer state is fp32.
if (!combo->scaledOptimizerState && combo->accumType == DataType::FLOAT16 &&
combo->accl1Type == DataType::FLOAT &&
combo->accl2Type == DataType::FLOAT) {
gradIntoAcclId =
gradCast(graph, combo, gradIntoAcclId, combo->withGradAccum);
}
// Remaining ops run after the gradient accumulation loop (if enabled)
// Gradient unscaling
TensorId gsId =
combo->initGs.isConst() ? "" : combo->inId(AdamComboOp::getGsInIndex());
gradIntoAcclId = gradUnscale(
graph, combo, combo->initGs, gsId, gradIntoAcclId, combo->withGradAccum);
// L2 regularization
if (combo->decayMode == WeightDecayMode::L2Regularization) {
TensorId wdId =
combo->initWd.isConst() ? "" : combo->inId(AdamComboOp::getWdInIndex());
gradIntoAcclId = regularizeL2(graph,
combo,
combo->initWd,
wdId,
weightId,
gradIntoAcclId,
combo->withGradAccum);
}
Op *accl1Op;
Op *accl2Op;
TensorId updatedAccl1Id;
TensorId updatedAccl2Id;
if (!combo->scaledOptimizerState || combo->initLs.isConst()) {
// Don't use RescaledAccumulateOp if loss scaling is constant
// 1st momentum
auto accl1 = accl(graph,
combo,
accl1Id,
gradIntoAcclId,
AccumulationType::MovingAverage,
combo->initB1,
combo->initB1.isConst()
? ""
: combo->inId(AdamComboOp::getBeta1InIndex()),
"_accl1",
combo->withGradAccum);
accl1Op = accl1.first;
updatedAccl1Id = accl1.second;
// 2nd momentum
auto accl2 = accl(
graph,
combo,
accl2Id,
gradIntoAcclId,
combo->mode == AdamMode::AdaMax ? AccumulationType::Infinity
: AccumulationType::MovingAverageSquare,
combo->initB2,
combo->initB2.isConst() ? ""
: combo->inId(AdamComboOp::getBeta2InIndex()),
"_accl1",
combo->withGradAccum);
accl2Op = accl2.first;
updatedAccl2Id = accl2.second;
} else {
// Use RescaleAccumulateOp to handle changes in loss scaling.
auto rescaleRatioId = rescaleRatio(graph, combo);
// 1st momentum
auto accl1 = rescaleAccl(
graph, combo, true, accl1Id, gradIntoAcclId, rescaleRatioId);
accl1Op = accl1.first;
updatedAccl1Id = accl1.second;
// 2nd momentum
auto accl2 = rescaleAccl(
graph, combo, false, accl2Id, gradIntoAcclId, rescaleRatioId);
accl2Op = accl2.first;
updatedAccl2Id = accl2.second;
}
// The accumulator updater
if (combo->withGradAccum && !runningMeanReduction(graph)) {
// runningMeanReduction will zero the accumulator
// in the first instance of calling accumulateOp so no need to zero here.
zeroAccumulator(graph, combo, {accl1Op, accl2Op}, accumId);
}
// Adam updater term
auto adamUpdOpUp = std::make_unique<AdamUpdaterOp>(
combo->mode,
combo->decayMode == WeightDecayMode::Decay ? combo->initWd
: OptimizerValue(0.0f, true),
combo->initB1,
combo->initB2,
combo->initEps,
Op::Settings(graph, combo->name() + "_adamupdater"));
auto adamUpdOp = adamUpdOpUp.get();
transferBaseProperties(combo, adamUpdOp);
graph.moveIntoGraph(std::move(adamUpdOpUp));
if (combo->decayMode == WeightDecayMode::Decay &&
(!combo->initWd.isConst() || combo->initWd.val() > 0.0f)) {
// Weight (for weight decay)
logging::pattern::trace("Connecting input {} to {} at {}",
weightId,
adamUpdOp->str(),
AdamUpdaterOp::getVarInIndex());
adamUpdOp->connectInTensor(AdamUpdaterOp::getVarInIndex(), weightId);
}
// 1st momentum
logging::pattern::trace("Connecting input {} to {} at {}",
updatedAccl1Id,
adamUpdOp->str(),
AdamUpdaterOp::getAccl1InIndex());
adamUpdOp->connectInTensor(AdamUpdaterOp::getAccl1InIndex(), updatedAccl1Id);
// 2nd momentum
logging::pattern::trace("Connecting input {} to {} at {}",
updatedAccl2Id,
adamUpdOp->str(),
AdamUpdaterOp::getAccl2InIndex());
adamUpdOp->connectInTensor(AdamUpdaterOp::getAccl2InIndex(), updatedAccl2Id);
if (combo->mode == AdamMode::Adam || combo->mode == AdamMode::Lamb ||
combo->mode == AdamMode::AdaMax) {
// step
logging::pattern::trace("Connecting input {} to {} at {}",
stepId,
adamUpdOp->str(),
AdamUpdaterOp::getStepInIndex());
adamUpdOp->connectInTensor(AdamUpdaterOp::getStepInIndex(), stepId);
}
// Optimizer parameters
if (!combo->initWd.isConst()) {
adamUpdOp->connectInTensor(AdamUpdaterOp::getWdInIndex(),
combo->inId(AdamComboOp::getWdInIndex()));
}
if (!combo->initB1.isConst()) {
adamUpdOp->connectInTensor(AdamUpdaterOp::getBeta1InIndex(),
combo->inId(AdamComboOp::getBeta1InIndex()));
}
if (!combo->initB2.isConst()) {
adamUpdOp->connectInTensor(AdamUpdaterOp::getBeta2InIndex(),
combo->inId(AdamComboOp::getBeta2InIndex()));
}
if (!combo->initEps.isConst()) {
adamUpdOp->connectInTensor(AdamUpdaterOp::getEpsInIndex(),
combo->inId(AdamComboOp::getEpsInIndex()));
}
// Updater term
adamUpdOp->createAndConnectOutTensor(AdamUpdaterOp::getUpdaterOutIndex(),
adamUpdaterId);
adamUpdOp->setup();
if (combo->withGradAccum) {
adamUpdOp->settings.executionContext =
ExecutionContext::AccumulateOuterFragment;
adamUpdOp->setExecutionPhase({});
adamUpdOp->settings.schedulePriority = 0.0;
}
// Lamb R1 & R2
//
// If max weight norm is set to a constant 0, then the condition
// in AdamVarUpdate that uses the outputs of LambSquare
// will never be satisfied. So we can optimize away these operations.
bool use_lamb =
(combo->mode == AdamMode::Lamb || combo->mode == AdamMode::LambNoBias) &&
!(combo->initMwn.isConst() && combo->initMwn.val() == 0);
if (use_lamb) {
auto lambR1OpUp = std::make_unique<LambSquareOp>(
Op::Settings(graph, combo->name() + "_lamb1"));
auto lambR1Op = lambR1OpUp.get();
transferBaseProperties(combo, lambR1Op);
graph.moveIntoGraph(std::move(lambR1OpUp));
logging::pattern::trace("Connecting input {} to {} at {}",
weightId,
lambR1Op->str(),
LambSquareOp::getInIndex());
lambR1Op->connectInTensor(LambSquareOp::getInIndex(), weightId);
lambR1Op->createAndConnectOutTensor(VarUpdateOp::getUpdatedVarOutIndex(),
lambR1SqId);
lambR1Op->setup();
auto lambR2OpUp = std::make_unique<LambSquareOp>(
Op::Settings(graph, combo->name() + "_lamb2"));
auto lambR2Op = lambR2OpUp.get();
transferBaseProperties(combo, lambR2Op);
graph.moveIntoGraph(std::move(lambR2OpUp));
logging::pattern::trace("Connecting input {} to {} at {}",
adamUpdaterId,
lambR2Op->str(),
LambSquareOp::getInIndex());
lambR2Op->connectInTensor(LambSquareOp::getInIndex(), adamUpdaterId);
lambR2Op->createAndConnectOutTensor(LambSquareOp::getOutIndex(),
lambR2SqId);
lambR2Op->setup();
if (combo->withGradAccum) {
lambR1Op->settings.executionContext =
ExecutionContext::AccumulateOuterFragment;
lambR1Op->setExecutionPhase({});
lambR1Op->settings.schedulePriority = 0.0;
lambR2Op->settings.executionContext =
ExecutionContext::AccumulateOuterFragment;
lambR2Op->setExecutionPhase({});
lambR2Op->settings.schedulePriority = 0.0;
}
}
// Var update
auto adamVarUpdOpUp = std::make_unique<AdamVarUpdateOp>(
combo->initLr,
combo->initMwn,
Op::Settings(graph, combo->name() + "_var_update"));
auto adamVarUpdOp = adamVarUpdOpUp.get();
transferBaseProperties(combo, adamVarUpdOp);
graph.moveIntoGraph(std::move(adamVarUpdOpUp));
// Weight
logging::pattern::trace("Connecting input {} to {} at {}",
weightId,
adamVarUpdOp->str(),
AdamVarUpdateOp::getVarToUpdateInIndex());
adamVarUpdOp->connectInTensor(AdamVarUpdateOp::getVarToUpdateInIndex(),
weightId);
// Updater
logging::pattern::trace("Connecting input {} to {} at {}",
adamUpdaterId,
adamVarUpdOp->str(),
AdamVarUpdateOp::getUpdaterInIndex());
adamVarUpdOp->connectInTensor(AdamVarUpdateOp::getUpdaterInIndex(),
adamUpdaterId);
if (use_lamb) {
adamVarUpdOp->connectInTensor(AdamVarUpdateOp::getLambR1SqInIndex(),
lambR1SqId);
adamVarUpdOp->connectInTensor(AdamVarUpdateOp::getLambR2SqInIndex(),
lambR2SqId);
}
// Optimizer parameters
if (!combo->initLr.isConst()) {
adamVarUpdOp->connectInTensor(AdamVarUpdateOp::getLrInIndex(),
combo->inId(AdamComboOp::getLrInIndex()));
}
if (!combo->initMwn.isConst()) {
adamVarUpdOp->connectInTensor(AdamVarUpdateOp::getMwnInIndex(),
combo->inId(AdamComboOp::getMwnInIndex()));
}
if (combo->withGradAccum) {
adamVarUpdOp->settings.executionContext =
ExecutionContext::AccumulateOuterFragment;
adamVarUpdOp->setExecutionPhase({});
adamVarUpdOp->settings.schedulePriority = 0.0;
} else {
graph.topoCons->transfer(combo, adamVarUpdOp);
}
// deleting combo op now, so that its output can be re-connected
combo->disconnectAllInputs();
combo->disconnectAllOutputs();
graph.eraseOp(combo->id);
adamVarUpdOp->connectOutTensor(AdamVarUpdateOp::getUpdatedVarOutIndex(),
updatedWeightId);
adamVarUpdOp->setup();
return true;
}
namespace {
// Not registering this pattern, as we want it to run at a special time (after
// matmul serialization)
static AddPatternName<AdamDecompose> registerName("AdamDecompose");
} // namespace
} // namespace popart
|
bbiletskyy/pipeline-oriented-analytics | tests/pipeline_oriented_analytics/transformer/feature/add_minutes_test.py | <reponame>bbiletskyy/pipeline-oriented-analytics
import pytest
from pyspark.sql.types import TimestampType
from datetime import datetime
from pipeline_oriented_analytics.transformer.feature import AddMinutes
class TestAddMinutes(object):
def test_transform(self, spark):
df = spark.createDataFrame([(datetime(2017, 7, 9, 0, 9, 23))], TimestampType())
AddMinutes(-20, 'value', '20_mins_before') \
.transform(df).select('20_mins_before').collect()[0][0] == datetime(2017, 7, 8, 23, 49, 23)
|
sneumann/CRIMSy | ui/src/main/java/de/ipb_halle/lbac/material/bean/MaterialOverviewBean.java | <gh_stars>0
/*
* Leibniz Bioactives Cloud
* Copyright 2017 Leibniz-Institut f. Pflanzenbiochemie
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package de.ipb_halle.lbac.material.bean;
import de.ipb_halle.lbac.admission.UserBean;
import de.ipb_halle.lbac.items.bean.ItemBean;
import de.ipb_halle.lbac.material.Material;
import de.ipb_halle.lbac.material.service.MaterialService;
import de.ipb_halle.lbac.navigation.Navigator;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.enterprise.context.SessionScoped;
import javax.inject.Inject;
import javax.inject.Named;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
/**
*
* @author fmauz
*/
@SessionScoped
@Named
public class MaterialOverviewBean implements Serializable {
private List<Material> materials = new ArrayList<>();
private Logger logger = LogManager.getLogger(this.getClass().getName());
@Inject
private MaterialBean materialEditBean;
@Inject
private MaterialService materialService;
@Inject
private Navigator navigator;
@Inject
private UserBean userBean;
@Inject ItemBean itemBean;
@PostConstruct
public void init() {
}
public List<Material> getReadableMaterials() {
return materialService.getReadableMaterials();
}
public boolean isNotAllowed(Material m, String action) {
return false;
}
public void actionCreateNewMaterial() {
materialEditBean.startMaterialCreation();
navigator.navigate("material/materialsEdit");
}
public void actionEditMaterial(Material m) {
try {
m.setHistory(materialService.loadHistoryOfMaterial(m.getId()));
materialEditBean.startMaterialEdit(m);
} catch (Exception e) {
logger.error(e);
}
navigator.navigate("material/materialsEdit");
}
public void actionDeactivateMaterial(Material m) {
materialService.deactivateMaterial(
m.getId(),
userBean.getCurrentAccount());
}
public void actionCreateNewItem(Material m){
itemBean.actionStartItemCreation(m);
navigator.navigate("item/itemEdit");
}
}
|
zipated/src | third_party/android_tools/sdk/sources/android-25/android/service/voice/VoiceInteractionSession.java | /**
* Copyright (C) 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.service.voice;
import android.annotation.Nullable;
import android.app.Activity;
import android.app.Dialog;
import android.app.Instrumentation;
import android.app.VoiceInteractor;
import android.app.assist.AssistContent;
import android.app.assist.AssistStructure;
import android.content.ComponentCallbacks2;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.graphics.Region;
import android.inputmethodservice.SoftInputWindow;
import android.os.Binder;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.os.UserHandle;
import android.util.ArrayMap;
import android.util.DebugUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.widget.FrameLayout;
import com.android.internal.app.IVoiceInteractionManagerService;
import com.android.internal.app.IVoiceInteractionSessionShowCallback;
import com.android.internal.app.IVoiceInteractor;
import com.android.internal.app.IVoiceInteractorCallback;
import com.android.internal.app.IVoiceInteractorRequest;
import com.android.internal.os.HandlerCaller;
import com.android.internal.os.SomeArgs;
import java.io.FileDescriptor;
import java.io.PrintWriter;
import java.lang.ref.WeakReference;
import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;
/**
* An active voice interaction session, providing a facility for the implementation
* to interact with the user in the voice interaction layer. The user interface is
* initially shown by default, and can be created be overriding {@link #onCreateContentView()}
* in which the UI can be built.
*
* <p>A voice interaction session can be self-contained, ultimately calling {@link #finish}
* when done. It can also initiate voice interactions with applications by calling
* {@link #startVoiceActivity}</p>.
*/
public class VoiceInteractionSession implements KeyEvent.Callback, ComponentCallbacks2 {
static final String TAG = "VoiceInteractionSession";
static final boolean DEBUG = false;
/**
* Flag received in {@link #onShow}: originator requested that the session be started with
* assist data from the currently focused activity.
*/
public static final int SHOW_WITH_ASSIST = 1<<0;
/**
* Flag received in {@link #onShow}: originator requested that the session be started with
* a screen shot of the currently focused activity.
*/
public static final int SHOW_WITH_SCREENSHOT = 1<<1;
/**
* Flag for use with {@link #onShow}: indicates that the session has been started from the
* system assist gesture.
*/
public static final int SHOW_SOURCE_ASSIST_GESTURE = 1<<2;
/**
* Flag for use with {@link #onShow}: indicates that the application itself has invoked
* the assistant.
*/
public static final int SHOW_SOURCE_APPLICATION = 1<<3;
/**
* Flag for use with {@link #onShow}: indicates that an Activity has invoked the voice
* interaction service for a local interaction using
* {@link Activity#startLocalVoiceInteraction(Bundle)}.
*/
public static final int SHOW_SOURCE_ACTIVITY = 1<<4;
// Keys for Bundle values
/** @hide */
public static final String KEY_DATA = "data";
/** @hide */
public static final String KEY_STRUCTURE = "structure";
/** @hide */
public static final String KEY_CONTENT = "content";
/** @hide */
public static final String KEY_RECEIVER_EXTRAS = "receiverExtras";
final Context mContext;
final HandlerCaller mHandlerCaller;
final KeyEvent.DispatcherState mDispatcherState = new KeyEvent.DispatcherState();
IVoiceInteractionManagerService mSystemService;
IBinder mToken;
int mTheme = 0;
LayoutInflater mInflater;
TypedArray mThemeAttrs;
View mRootView;
FrameLayout mContentFrame;
SoftInputWindow mWindow;
boolean mInitialized;
boolean mWindowAdded;
boolean mWindowVisible;
boolean mWindowWasVisible;
boolean mInShowWindow;
final ArrayMap<IBinder, Request> mActiveRequests = new ArrayMap<IBinder, Request>();
final Insets mTmpInsets = new Insets();
final WeakReference<VoiceInteractionSession> mWeakRef
= new WeakReference<VoiceInteractionSession>(this);
final IVoiceInteractor mInteractor = new IVoiceInteractor.Stub() {
@Override
public IVoiceInteractorRequest startConfirmation(String callingPackage,
IVoiceInteractorCallback callback, VoiceInteractor.Prompt prompt, Bundle extras) {
ConfirmationRequest request = new ConfirmationRequest(callingPackage,
Binder.getCallingUid(), callback, VoiceInteractionSession.this,
prompt, extras);
addRequest(request);
mHandlerCaller.sendMessage(mHandlerCaller.obtainMessageO(MSG_START_CONFIRMATION,
request));
return request.mInterface;
}
@Override
public IVoiceInteractorRequest startPickOption(String callingPackage,
IVoiceInteractorCallback callback, VoiceInteractor.Prompt prompt,
VoiceInteractor.PickOptionRequest.Option[] options, Bundle extras) {
PickOptionRequest request = new PickOptionRequest(callingPackage,
Binder.getCallingUid(), callback, VoiceInteractionSession.this,
prompt, options, extras);
addRequest(request);
mHandlerCaller.sendMessage(mHandlerCaller.obtainMessageO(MSG_START_PICK_OPTION,
request));
return request.mInterface;
}
@Override
public IVoiceInteractorRequest startCompleteVoice(String callingPackage,
IVoiceInteractorCallback callback, VoiceInteractor.Prompt message, Bundle extras) {
CompleteVoiceRequest request = new CompleteVoiceRequest(callingPackage,
Binder.getCallingUid(), callback, VoiceInteractionSession.this,
message, extras);
addRequest(request);
mHandlerCaller.sendMessage(mHandlerCaller.obtainMessageO(MSG_START_COMPLETE_VOICE,
request));
return request.mInterface;
}
@Override
public IVoiceInteractorRequest startAbortVoice(String callingPackage,
IVoiceInteractorCallback callback, VoiceInteractor.Prompt message, Bundle extras) {
AbortVoiceRequest request = new AbortVoiceRequest(callingPackage,
Binder.getCallingUid(), callback, VoiceInteractionSession.this,
message, extras);
addRequest(request);
mHandlerCaller.sendMessage(mHandlerCaller.obtainMessageO(MSG_START_ABORT_VOICE,
request));
return request.mInterface;
}
@Override
public IVoiceInteractorRequest startCommand(String callingPackage,
IVoiceInteractorCallback callback, String command, Bundle extras) {
CommandRequest request = new CommandRequest(callingPackage,
Binder.getCallingUid(), callback, VoiceInteractionSession.this,
command, extras);
addRequest(request);
mHandlerCaller.sendMessage(mHandlerCaller.obtainMessageO(MSG_START_COMMAND,
request));
return request.mInterface;
}
@Override
public boolean[] supportsCommands(String callingPackage, String[] commands) {
Message msg = mHandlerCaller.obtainMessageIOO(MSG_SUPPORTS_COMMANDS,
0, commands, null);
SomeArgs args = mHandlerCaller.sendMessageAndWait(msg);
if (args != null) {
boolean[] res = (boolean[])args.arg1;
args.recycle();
return res;
}
return new boolean[commands.length];
}
};
final IVoiceInteractionSession mSession = new IVoiceInteractionSession.Stub() {
@Override
public void show(Bundle sessionArgs, int flags,
IVoiceInteractionSessionShowCallback showCallback) {
mHandlerCaller.sendMessage(mHandlerCaller.obtainMessageIOO(MSG_SHOW,
flags, sessionArgs, showCallback));
}
@Override
public void hide() {
mHandlerCaller.sendMessage(mHandlerCaller.obtainMessage(MSG_HIDE));
}
@Override
public void handleAssist(final Bundle data, final AssistStructure structure,
final AssistContent content, final int index, final int count) {
// We want to pre-warm the AssistStructure before handing it off to the main
// thread. We also want to do this on a separate thread, so that if the app
// is for some reason slow (due to slow filling in of async children in the
// structure), we don't block other incoming IPCs (such as the screenshot) to
// us (since we are a oneway interface, they get serialized). (Okay?)
Thread retriever = new Thread("AssistStructure retriever") {
@Override
public void run() {
Throwable failure = null;
if (structure != null) {
try {
structure.ensureData();
} catch (Throwable e) {
Log.w(TAG, "Failure retrieving AssistStructure", e);
failure = e;
}
}
mHandlerCaller.sendMessage(mHandlerCaller.obtainMessageOOOOII(MSG_HANDLE_ASSIST,
data, failure == null ? structure : null, failure, content,
index, count));
}
};
retriever.start();
}
@Override
public void handleScreenshot(Bitmap screenshot) {
mHandlerCaller.sendMessage(mHandlerCaller.obtainMessageO(MSG_HANDLE_SCREENSHOT,
screenshot));
}
@Override
public void taskStarted(Intent intent, int taskId) {
mHandlerCaller.sendMessage(mHandlerCaller.obtainMessageIO(MSG_TASK_STARTED,
taskId, intent));
}
@Override
public void taskFinished(Intent intent, int taskId) {
mHandlerCaller.sendMessage(mHandlerCaller.obtainMessageIO(MSG_TASK_FINISHED,
taskId, intent));
}
@Override
public void closeSystemDialogs() {
mHandlerCaller.sendMessage(mHandlerCaller.obtainMessage(MSG_CLOSE_SYSTEM_DIALOGS));
}
@Override
public void onLockscreenShown() {
mHandlerCaller.sendMessage(mHandlerCaller.obtainMessage(MSG_ON_LOCKSCREEN_SHOWN));
}
@Override
public void destroy() {
mHandlerCaller.sendMessage(mHandlerCaller.obtainMessage(MSG_DESTROY));
}
};
/**
* Base class representing a request from a voice-driver app to perform a particular
* voice operation with the user. See related subclasses for the types of requests
* that are possible.
*/
public static class Request {
final IVoiceInteractorRequest mInterface = new IVoiceInteractorRequest.Stub() {
@Override
public void cancel() throws RemoteException {
VoiceInteractionSession session = mSession.get();
if (session != null) {
session.mHandlerCaller.sendMessage(
session.mHandlerCaller.obtainMessageO(MSG_CANCEL, Request.this));
}
}
};
final String mCallingPackage;
final int mCallingUid;
final IVoiceInteractorCallback mCallback;
final WeakReference<VoiceInteractionSession> mSession;
final Bundle mExtras;
Request(String packageName, int uid, IVoiceInteractorCallback callback,
VoiceInteractionSession session, Bundle extras) {
mCallingPackage = packageName;
mCallingUid = uid;
mCallback = callback;
mSession = session.mWeakRef;
mExtras = extras;
}
/**
* Return the uid of the application that initiated the request.
*/
public int getCallingUid() {
return mCallingUid;
}
/**
* Return the package name of the application that initiated the request.
*/
public String getCallingPackage() {
return mCallingPackage;
}
/**
* Return any additional extra information that was supplied as part of the request.
*/
public Bundle getExtras() {
return mExtras;
}
/**
* Check whether this request is currently active. A request becomes inactive after
* calling {@link #cancel} or a final result method that completes the request. After
* this point, further interactions with the request will result in
* {@link java.lang.IllegalStateException} errors; you should not catch these errors,
* but can use this method if you need to determine the state of the request. Returns
* true if the request is still active.
*/
public boolean isActive() {
VoiceInteractionSession session = mSession.get();
if (session == null) {
return false;
}
return session.isRequestActive(mInterface.asBinder());
}
void finishRequest() {
VoiceInteractionSession session = mSession.get();
if (session == null) {
throw new IllegalStateException("VoiceInteractionSession has been destroyed");
}
Request req = session.removeRequest(mInterface.asBinder());
if (req == null) {
throw new IllegalStateException("Request not active: " + this);
} else if (req != this) {
throw new IllegalStateException("Current active request " + req
+ " not same as calling request " + this);
}
}
/**
* Ask the app to cancel this current request.
* This also finishes the request (it is no longer active).
*/
public void cancel() {
try {
if (DEBUG) Log.d(TAG, "sendCancelResult: req=" + mInterface);
finishRequest();
mCallback.deliverCancel(mInterface);
} catch (RemoteException e) {
}
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder(128);
DebugUtils.buildShortClassTag(this, sb);
sb.append(" ");
sb.append(mInterface.asBinder());
sb.append(" pkg=");
sb.append(mCallingPackage);
sb.append(" uid=");
UserHandle.formatUid(sb, mCallingUid);
sb.append('}');
return sb.toString();
}
void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
writer.print(prefix); writer.print("mInterface=");
writer.println(mInterface.asBinder());
writer.print(prefix); writer.print("mCallingPackage="); writer.print(mCallingPackage);
writer.print(" mCallingUid="); UserHandle.formatUid(writer, mCallingUid);
writer.println();
writer.print(prefix); writer.print("mCallback=");
writer.println(mCallback.asBinder());
if (mExtras != null) {
writer.print(prefix); writer.print("mExtras=");
writer.println(mExtras);
}
}
}
/**
* A request for confirmation from the user of an operation, as per
* {@link android.app.VoiceInteractor.ConfirmationRequest
* VoiceInteractor.ConfirmationRequest}.
*/
public static final class ConfirmationRequest extends Request {
final VoiceInteractor.Prompt mPrompt;
ConfirmationRequest(String packageName, int uid, IVoiceInteractorCallback callback,
VoiceInteractionSession session, VoiceInteractor.Prompt prompt, Bundle extras) {
super(packageName, uid, callback, session, extras);
mPrompt = prompt;
}
/**
* Return the prompt informing the user of what will happen, as per
* {@link android.app.VoiceInteractor.ConfirmationRequest
* VoiceInteractor.ConfirmationRequest}.
*/
@Nullable
public VoiceInteractor.Prompt getVoicePrompt() {
return mPrompt;
}
/**
* Return the prompt informing the user of what will happen, as per
* {@link android.app.VoiceInteractor.ConfirmationRequest
* VoiceInteractor.ConfirmationRequest}.
* @deprecated Prefer {@link #getVoicePrompt()} which allows multiple voice prompts.
*/
@Nullable
public CharSequence getPrompt() {
return (mPrompt != null ? mPrompt.getVoicePromptAt(0) : null);
}
/**
* Report that the voice interactor has confirmed the operation with the user, resulting
* in a call to
* {@link android.app.VoiceInteractor.ConfirmationRequest#onConfirmationResult
* VoiceInteractor.ConfirmationRequest.onConfirmationResult}.
* This finishes the request (it is no longer active).
*/
public void sendConfirmationResult(boolean confirmed, Bundle result) {
try {
if (DEBUG) Log.d(TAG, "sendConfirmationResult: req=" + mInterface
+ " confirmed=" + confirmed + " result=" + result);
finishRequest();
mCallback.deliverConfirmationResult(mInterface, confirmed, result);
} catch (RemoteException e) {
}
}
void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
super.dump(prefix, fd, writer, args);
writer.print(prefix); writer.print("mPrompt=");
writer.println(mPrompt);
}
}
/**
* A request for the user to pick from a set of option, as per
* {@link android.app.VoiceInteractor.PickOptionRequest VoiceInteractor.PickOptionRequest}.
*/
public static final class PickOptionRequest extends Request {
final VoiceInteractor.Prompt mPrompt;
final VoiceInteractor.PickOptionRequest.Option[] mOptions;
PickOptionRequest(String packageName, int uid, IVoiceInteractorCallback callback,
VoiceInteractionSession session, VoiceInteractor.Prompt prompt,
VoiceInteractor.PickOptionRequest.Option[] options, Bundle extras) {
super(packageName, uid, callback, session, extras);
mPrompt = prompt;
mOptions = options;
}
/**
* Return the prompt informing the user of what they are picking, as per
* {@link android.app.VoiceInteractor.PickOptionRequest VoiceInteractor.PickOptionRequest}.
*/
@Nullable
public VoiceInteractor.Prompt getVoicePrompt() {
return mPrompt;
}
/**
* Return the prompt informing the user of what they are picking, as per
* {@link android.app.VoiceInteractor.PickOptionRequest VoiceInteractor.PickOptionRequest}.
* @deprecated Prefer {@link #getVoicePrompt()} which allows multiple voice prompts.
*/
@Nullable
public CharSequence getPrompt() {
return (mPrompt != null ? mPrompt.getVoicePromptAt(0) : null);
}
/**
* Return the set of options the user is picking from, as per
* {@link android.app.VoiceInteractor.PickOptionRequest VoiceInteractor.PickOptionRequest}.
*/
public VoiceInteractor.PickOptionRequest.Option[] getOptions() {
return mOptions;
}
void sendPickOptionResult(boolean finished,
VoiceInteractor.PickOptionRequest.Option[] selections, Bundle result) {
try {
if (DEBUG) Log.d(TAG, "sendPickOptionResult: req=" + mInterface
+ " finished=" + finished + " selections=" + selections
+ " result=" + result);
if (finished) {
finishRequest();
}
mCallback.deliverPickOptionResult(mInterface, finished, selections, result);
} catch (RemoteException e) {
}
}
/**
* Report an intermediate option selection from the request, without completing it (the
* request is still active and the app is waiting for the final option selection),
* resulting in a call to
* {@link android.app.VoiceInteractor.PickOptionRequest#onPickOptionResult
* VoiceInteractor.PickOptionRequest.onPickOptionResult} with false for finished.
*/
public void sendIntermediatePickOptionResult(
VoiceInteractor.PickOptionRequest.Option[] selections, Bundle result) {
sendPickOptionResult(false, selections, result);
}
/**
* Report the final option selection for the request, completing the request
* and resulting in a call to
* {@link android.app.VoiceInteractor.PickOptionRequest#onPickOptionResult
* VoiceInteractor.PickOptionRequest.onPickOptionResult} with false for finished.
* This finishes the request (it is no longer active).
*/
public void sendPickOptionResult(
VoiceInteractor.PickOptionRequest.Option[] selections, Bundle result) {
sendPickOptionResult(true, selections, result);
}
void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
super.dump(prefix, fd, writer, args);
writer.print(prefix); writer.print("mPrompt=");
writer.println(mPrompt);
if (mOptions != null) {
writer.print(prefix); writer.println("Options:");
for (int i=0; i<mOptions.length; i++) {
VoiceInteractor.PickOptionRequest.Option op = mOptions[i];
writer.print(prefix); writer.print(" #"); writer.print(i); writer.println(":");
writer.print(prefix); writer.print(" mLabel=");
writer.println(op.getLabel());
writer.print(prefix); writer.print(" mIndex=");
writer.println(op.getIndex());
if (op.countSynonyms() > 0) {
writer.print(prefix); writer.println(" Synonyms:");
for (int j=0; j<op.countSynonyms(); j++) {
writer.print(prefix); writer.print(" #"); writer.print(j);
writer.print(": "); writer.println(op.getSynonymAt(j));
}
}
if (op.getExtras() != null) {
writer.print(prefix); writer.print(" mExtras=");
writer.println(op.getExtras());
}
}
}
}
}
/**
* A request to simply inform the user that the voice operation has completed, as per
* {@link android.app.VoiceInteractor.CompleteVoiceRequest
* VoiceInteractor.CompleteVoiceRequest}.
*/
public static final class CompleteVoiceRequest extends Request {
final VoiceInteractor.Prompt mPrompt;
CompleteVoiceRequest(String packageName, int uid, IVoiceInteractorCallback callback,
VoiceInteractionSession session, VoiceInteractor.Prompt prompt, Bundle extras) {
super(packageName, uid, callback, session, extras);
mPrompt = prompt;
}
/**
* Return the message informing the user of the completion, as per
* {@link android.app.VoiceInteractor.CompleteVoiceRequest
* VoiceInteractor.CompleteVoiceRequest}.
*/
@Nullable
public VoiceInteractor.Prompt getVoicePrompt() {
return mPrompt;
}
/**
* Return the message informing the user of the completion, as per
* {@link android.app.VoiceInteractor.CompleteVoiceRequest
* VoiceInteractor.CompleteVoiceRequest}.
* @deprecated Prefer {@link #getVoicePrompt()} which allows a separate visual message.
*/
@Nullable
public CharSequence getMessage() {
return (mPrompt != null ? mPrompt.getVoicePromptAt(0) : null);
}
/**
* Report that the voice interactor has finished completing the voice operation, resulting
* in a call to
* {@link android.app.VoiceInteractor.CompleteVoiceRequest#onCompleteResult
* VoiceInteractor.CompleteVoiceRequest.onCompleteResult}.
* This finishes the request (it is no longer active).
*/
public void sendCompleteResult(Bundle result) {
try {
if (DEBUG) Log.d(TAG, "sendCompleteVoiceResult: req=" + mInterface
+ " result=" + result);
finishRequest();
mCallback.deliverCompleteVoiceResult(mInterface, result);
} catch (RemoteException e) {
}
}
void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
super.dump(prefix, fd, writer, args);
writer.print(prefix); writer.print("mPrompt=");
writer.println(mPrompt);
}
}
/**
* A request to report that the current user interaction can not be completed with voice, as per
* {@link android.app.VoiceInteractor.AbortVoiceRequest VoiceInteractor.AbortVoiceRequest}.
*/
public static final class AbortVoiceRequest extends Request {
final VoiceInteractor.Prompt mPrompt;
AbortVoiceRequest(String packageName, int uid, IVoiceInteractorCallback callback,
VoiceInteractionSession session, VoiceInteractor.Prompt prompt, Bundle extras) {
super(packageName, uid, callback, session, extras);
mPrompt = prompt;
}
/**
* Return the message informing the user of the problem, as per
* {@link android.app.VoiceInteractor.AbortVoiceRequest VoiceInteractor.AbortVoiceRequest}.
*/
@Nullable
public VoiceInteractor.Prompt getVoicePrompt() {
return mPrompt;
}
/**
* Return the message informing the user of the problem, as per
* {@link android.app.VoiceInteractor.AbortVoiceRequest VoiceInteractor.AbortVoiceRequest}.
* @deprecated Prefer {@link #getVoicePrompt()} which allows a separate visual message.
*/
@Nullable
public CharSequence getMessage() {
return (mPrompt != null ? mPrompt.getVoicePromptAt(0) : null);
}
/**
* Report that the voice interactor has finished aborting the voice operation, resulting
* in a call to
* {@link android.app.VoiceInteractor.AbortVoiceRequest#onAbortResult
* VoiceInteractor.AbortVoiceRequest.onAbortResult}. This finishes the request (it
* is no longer active).
*/
public void sendAbortResult(Bundle result) {
try {
if (DEBUG) Log.d(TAG, "sendConfirmResult: req=" + mInterface
+ " result=" + result);
finishRequest();
mCallback.deliverAbortVoiceResult(mInterface, result);
} catch (RemoteException e) {
}
}
void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
super.dump(prefix, fd, writer, args);
writer.print(prefix); writer.print("mPrompt=");
writer.println(mPrompt);
}
}
/**
* A generic vendor-specific request, as per
* {@link android.app.VoiceInteractor.CommandRequest VoiceInteractor.CommandRequest}.
*/
public static final class CommandRequest extends Request {
final String mCommand;
CommandRequest(String packageName, int uid, IVoiceInteractorCallback callback,
VoiceInteractionSession session, String command, Bundle extras) {
super(packageName, uid, callback, session, extras);
mCommand = command;
}
/**
* Return the command that is being executed, as per
* {@link android.app.VoiceInteractor.CommandRequest VoiceInteractor.CommandRequest}.
*/
public String getCommand() {
return mCommand;
}
void sendCommandResult(boolean finished, Bundle result) {
try {
if (DEBUG) Log.d(TAG, "sendCommandResult: req=" + mInterface
+ " result=" + result);
if (finished) {
finishRequest();
}
mCallback.deliverCommandResult(mInterface, finished, result);
} catch (RemoteException e) {
}
}
/**
* Report an intermediate result of the request, without completing it (the request
* is still active and the app is waiting for the final result), resulting in a call to
* {@link android.app.VoiceInteractor.CommandRequest#onCommandResult
* VoiceInteractor.CommandRequest.onCommandResult} with false for isCompleted.
*/
public void sendIntermediateResult(Bundle result) {
sendCommandResult(false, result);
}
/**
* Report the final result of the request, completing the request and resulting in a call to
* {@link android.app.VoiceInteractor.CommandRequest#onCommandResult
* VoiceInteractor.CommandRequest.onCommandResult} with true for isCompleted.
* This finishes the request (it is no longer active).
*/
public void sendResult(Bundle result) {
sendCommandResult(true, result);
}
void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
super.dump(prefix, fd, writer, args);
writer.print(prefix); writer.print("mCommand=");
writer.println(mCommand);
}
}
static final int MSG_START_CONFIRMATION = 1;
static final int MSG_START_PICK_OPTION = 2;
static final int MSG_START_COMPLETE_VOICE = 3;
static final int MSG_START_ABORT_VOICE = 4;
static final int MSG_START_COMMAND = 5;
static final int MSG_SUPPORTS_COMMANDS = 6;
static final int MSG_CANCEL = 7;
static final int MSG_TASK_STARTED = 100;
static final int MSG_TASK_FINISHED = 101;
static final int MSG_CLOSE_SYSTEM_DIALOGS = 102;
static final int MSG_DESTROY = 103;
static final int MSG_HANDLE_ASSIST = 104;
static final int MSG_HANDLE_SCREENSHOT = 105;
static final int MSG_SHOW = 106;
static final int MSG_HIDE = 107;
static final int MSG_ON_LOCKSCREEN_SHOWN = 108;
class MyCallbacks implements HandlerCaller.Callback, SoftInputWindow.Callback {
@Override
public void executeMessage(Message msg) {
SomeArgs args = null;
switch (msg.what) {
case MSG_START_CONFIRMATION:
if (DEBUG) Log.d(TAG, "onConfirm: req=" + msg.obj);
onRequestConfirmation((ConfirmationRequest) msg.obj);
break;
case MSG_START_PICK_OPTION:
if (DEBUG) Log.d(TAG, "onPickOption: req=" + msg.obj);
onRequestPickOption((PickOptionRequest) msg.obj);
break;
case MSG_START_COMPLETE_VOICE:
if (DEBUG) Log.d(TAG, "onCompleteVoice: req=" + msg.obj);
onRequestCompleteVoice((CompleteVoiceRequest) msg.obj);
break;
case MSG_START_ABORT_VOICE:
if (DEBUG) Log.d(TAG, "onAbortVoice: req=" + msg.obj);
onRequestAbortVoice((AbortVoiceRequest) msg.obj);
break;
case MSG_START_COMMAND:
if (DEBUG) Log.d(TAG, "onCommand: req=" + msg.obj);
onRequestCommand((CommandRequest) msg.obj);
break;
case MSG_SUPPORTS_COMMANDS:
args = (SomeArgs)msg.obj;
if (DEBUG) Log.d(TAG, "onGetSupportedCommands: cmds=" + args.arg1);
args.arg1 = onGetSupportedCommands((String[]) args.arg1);
args.complete();
args = null;
break;
case MSG_CANCEL:
if (DEBUG) Log.d(TAG, "onCancel: req=" + ((Request)msg.obj));
onCancelRequest((Request) msg.obj);
break;
case MSG_TASK_STARTED:
if (DEBUG) Log.d(TAG, "onTaskStarted: intent=" + msg.obj
+ " taskId=" + msg.arg1);
onTaskStarted((Intent) msg.obj, msg.arg1);
break;
case MSG_TASK_FINISHED:
if (DEBUG) Log.d(TAG, "onTaskFinished: intent=" + msg.obj
+ " taskId=" + msg.arg1);
onTaskFinished((Intent) msg.obj, msg.arg1);
break;
case MSG_CLOSE_SYSTEM_DIALOGS:
if (DEBUG) Log.d(TAG, "onCloseSystemDialogs");
onCloseSystemDialogs();
break;
case MSG_DESTROY:
if (DEBUG) Log.d(TAG, "doDestroy");
doDestroy();
break;
case MSG_HANDLE_ASSIST:
args = (SomeArgs)msg.obj;
if (DEBUG) Log.d(TAG, "onHandleAssist: data=" + args.arg1
+ " structure=" + args.arg2 + " content=" + args.arg3
+ " activityIndex=" + args.argi5 + " activityCount=" + args.argi6);
if (args.argi5 == 0) {
doOnHandleAssist((Bundle) args.arg1, (AssistStructure) args.arg2,
(Throwable) args.arg3, (AssistContent) args.arg4);
} else {
doOnHandleAssistSecondary((Bundle) args.arg1, (AssistStructure) args.arg2,
(Throwable) args.arg3, (AssistContent) args.arg4,
args.argi5, args.argi6);
}
break;
case MSG_HANDLE_SCREENSHOT:
if (DEBUG) Log.d(TAG, "onHandleScreenshot: " + msg.obj);
onHandleScreenshot((Bitmap) msg.obj);
break;
case MSG_SHOW:
args = (SomeArgs)msg.obj;
if (DEBUG) Log.d(TAG, "doShow: args=" + args.arg1
+ " flags=" + msg.arg1
+ " showCallback=" + args.arg2);
doShow((Bundle) args.arg1, msg.arg1,
(IVoiceInteractionSessionShowCallback) args.arg2);
break;
case MSG_HIDE:
if (DEBUG) Log.d(TAG, "doHide");
doHide();
break;
case MSG_ON_LOCKSCREEN_SHOWN:
if (DEBUG) Log.d(TAG, "onLockscreenShown");
onLockscreenShown();
break;
}
if (args != null) {
args.recycle();
}
}
@Override
public void onBackPressed() {
VoiceInteractionSession.this.onBackPressed();
}
}
final MyCallbacks mCallbacks = new MyCallbacks();
/**
* Information about where interesting parts of the input method UI appear.
*/
public static final class Insets {
/**
* This is the part of the UI that is the main content. It is
* used to determine the basic space needed, to resize/pan the
* application behind. It is assumed that this inset does not
* change very much, since any change will cause a full resize/pan
* of the application behind. This value is relative to the top edge
* of the input method window.
*/
public final Rect contentInsets = new Rect();
/**
* This is the region of the UI that is touchable. It is used when
* {@link #touchableInsets} is set to {@link #TOUCHABLE_INSETS_REGION}.
* The region should be specified relative to the origin of the window frame.
*/
public final Region touchableRegion = new Region();
/**
* Option for {@link #touchableInsets}: the entire window frame
* can be touched.
*/
public static final int TOUCHABLE_INSETS_FRAME
= ViewTreeObserver.InternalInsetsInfo.TOUCHABLE_INSETS_FRAME;
/**
* Option for {@link #touchableInsets}: the area inside of
* the content insets can be touched.
*/
public static final int TOUCHABLE_INSETS_CONTENT
= ViewTreeObserver.InternalInsetsInfo.TOUCHABLE_INSETS_CONTENT;
/**
* Option for {@link #touchableInsets}: the region specified by
* {@link #touchableRegion} can be touched.
*/
public static final int TOUCHABLE_INSETS_REGION
= ViewTreeObserver.InternalInsetsInfo.TOUCHABLE_INSETS_REGION;
/**
* Determine which area of the window is touchable by the user. May
* be one of: {@link #TOUCHABLE_INSETS_FRAME},
* {@link #TOUCHABLE_INSETS_CONTENT}, or {@link #TOUCHABLE_INSETS_REGION}.
*/
public int touchableInsets;
}
final ViewTreeObserver.OnComputeInternalInsetsListener mInsetsComputer =
new ViewTreeObserver.OnComputeInternalInsetsListener() {
public void onComputeInternalInsets(ViewTreeObserver.InternalInsetsInfo info) {
onComputeInsets(mTmpInsets);
info.contentInsets.set(mTmpInsets.contentInsets);
info.visibleInsets.set(mTmpInsets.contentInsets);
info.touchableRegion.set(mTmpInsets.touchableRegion);
info.setTouchableInsets(mTmpInsets.touchableInsets);
}
};
public VoiceInteractionSession(Context context) {
this(context, new Handler());
}
public VoiceInteractionSession(Context context, Handler handler) {
mContext = context;
mHandlerCaller = new HandlerCaller(context, handler.getLooper(),
mCallbacks, true);
}
public Context getContext() {
return mContext;
}
void addRequest(Request req) {
synchronized (this) {
mActiveRequests.put(req.mInterface.asBinder(), req);
}
}
boolean isRequestActive(IBinder reqInterface) {
synchronized (this) {
return mActiveRequests.containsKey(reqInterface);
}
}
Request removeRequest(IBinder reqInterface) {
synchronized (this) {
return mActiveRequests.remove(reqInterface);
}
}
void doCreate(IVoiceInteractionManagerService service, IBinder token) {
mSystemService = service;
mToken = token;
onCreate();
}
void doShow(Bundle args, int flags, final IVoiceInteractionSessionShowCallback showCallback) {
if (DEBUG) Log.v(TAG, "Showing window: mWindowAdded=" + mWindowAdded
+ " mWindowVisible=" + mWindowVisible);
if (mInShowWindow) {
Log.w(TAG, "Re-entrance in to showWindow");
return;
}
try {
mInShowWindow = true;
if (!mWindowVisible) {
if (!mWindowAdded) {
mWindowAdded = true;
View v = onCreateContentView();
if (v != null) {
setContentView(v);
}
}
}
onShow(args, flags);
if (!mWindowVisible) {
mWindowVisible = true;
mWindow.show();
}
if (showCallback != null) {
mRootView.invalidate();
mRootView.getViewTreeObserver().addOnPreDrawListener(
new ViewTreeObserver.OnPreDrawListener() {
@Override
public boolean onPreDraw() {
mRootView.getViewTreeObserver().removeOnPreDrawListener(this);
try {
showCallback.onShown();
} catch (RemoteException e) {
Log.w(TAG, "Error calling onShown", e);
}
return true;
}
});
}
} finally {
mWindowWasVisible = true;
mInShowWindow = false;
}
}
void doHide() {
if (mWindowVisible) {
mWindow.hide();
mWindowVisible = false;
onHide();
}
}
void doDestroy() {
onDestroy();
if (mInitialized) {
mRootView.getViewTreeObserver().removeOnComputeInternalInsetsListener(
mInsetsComputer);
if (mWindowAdded) {
mWindow.dismiss();
mWindowAdded = false;
}
mInitialized = false;
}
}
void initViews() {
mInitialized = true;
mThemeAttrs = mContext.obtainStyledAttributes(android.R.styleable.VoiceInteractionSession);
mRootView = mInflater.inflate(
com.android.internal.R.layout.voice_interaction_session, null);
mRootView.setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
mWindow.setContentView(mRootView);
mRootView.getViewTreeObserver().addOnComputeInternalInsetsListener(mInsetsComputer);
mContentFrame = (FrameLayout)mRootView.findViewById(android.R.id.content);
}
/**
* Equivalent to {@link VoiceInteractionService#setDisabledShowContext
* VoiceInteractionService.setDisabledShowContext(int)}.
*/
public void setDisabledShowContext(int flags) {
try {
mSystemService.setDisabledShowContext(flags);
} catch (RemoteException e) {
}
}
/**
* Equivalent to {@link VoiceInteractionService#getDisabledShowContext
* VoiceInteractionService.getDisabledShowContext}.
*/
public int getDisabledShowContext() {
try {
return mSystemService.getDisabledShowContext();
} catch (RemoteException e) {
return 0;
}
}
/**
* Return which show context flags have been disabled by the user through the system
* settings UI, so the session will never get this data. Returned flags are any combination of
* {@link VoiceInteractionSession#SHOW_WITH_ASSIST VoiceInteractionSession.SHOW_WITH_ASSIST} and
* {@link VoiceInteractionSession#SHOW_WITH_SCREENSHOT
* VoiceInteractionSession.SHOW_WITH_SCREENSHOT}. Note that this only tells you about
* global user settings, not about restrictions that may be applied contextual based on
* the current application the user is in or other transient states.
*/
public int getUserDisabledShowContext() {
try {
return mSystemService.getUserDisabledShowContext();
} catch (RemoteException e) {
return 0;
}
}
/**
* Show the UI for this session. This asks the system to go through the process of showing
* your UI, which will eventually culminate in {@link #onShow}. This is similar to calling
* {@link VoiceInteractionService#showSession VoiceInteractionService.showSession}.
* @param args Arbitrary arguments that will be propagated {@link #onShow}.
* @param flags Indicates additional optional behavior that should be performed. May
* be any combination of
* {@link VoiceInteractionSession#SHOW_WITH_ASSIST VoiceInteractionSession.SHOW_WITH_ASSIST} and
* {@link VoiceInteractionSession#SHOW_WITH_SCREENSHOT
* VoiceInteractionSession.SHOW_WITH_SCREENSHOT}
* to request that the system generate and deliver assist data on the current foreground
* app as part of showing the session UI.
*/
public void show(Bundle args, int flags) {
if (mToken == null) {
throw new IllegalStateException("Can't call before onCreate()");
}
try {
mSystemService.showSessionFromSession(mToken, args, flags);
} catch (RemoteException e) {
}
}
/**
* Hide the session's UI, if currently shown. Call this when you are done with your
* user interaction.
*/
public void hide() {
if (mToken == null) {
throw new IllegalStateException("Can't call before onCreate()");
}
try {
mSystemService.hideSessionFromSession(mToken);
} catch (RemoteException e) {
}
}
/**
* You can call this to customize the theme used by your IME's window.
* This must be set before {@link #onCreate}, so you
* will typically call it in your constructor with the resource ID
* of your custom theme.
*/
public void setTheme(int theme) {
if (mWindow != null) {
throw new IllegalStateException("Must be called before onCreate()");
}
mTheme = theme;
}
/**
* Ask that a new activity be started for voice interaction. This will create a
* new dedicated task in the activity manager for this voice interaction session;
* this means that {@link Intent#FLAG_ACTIVITY_NEW_TASK Intent.FLAG_ACTIVITY_NEW_TASK}
* will be set for you to make it a new task.
*
* <p>The newly started activity will be displayed to the user in a special way, as
* a layer under the voice interaction UI.</p>
*
* <p>As the voice activity runs, it can retrieve a {@link android.app.VoiceInteractor}
* through which it can perform voice interactions through your session. These requests
* for voice interactions will appear as callbacks on {@link #onGetSupportedCommands},
* {@link #onRequestConfirmation}, {@link #onRequestPickOption},
* {@link #onRequestCompleteVoice}, {@link #onRequestAbortVoice},
* or {@link #onRequestCommand}
*
* <p>You will receive a call to {@link #onTaskStarted} when the task starts up
* and {@link #onTaskFinished} when the last activity has finished.
*
* @param intent The Intent to start this voice interaction. The given Intent will
* always have {@link Intent#CATEGORY_VOICE Intent.CATEGORY_VOICE} added to it, since
* this is part of a voice interaction.
*/
public void startVoiceActivity(Intent intent) {
if (mToken == null) {
throw new IllegalStateException("Can't call before onCreate()");
}
try {
intent.migrateExtraStreamToClipData();
intent.prepareToLeaveProcess(mContext);
int res = mSystemService.startVoiceActivity(mToken, intent,
intent.resolveType(mContext.getContentResolver()));
Instrumentation.checkStartActivityResult(res, intent);
} catch (RemoteException e) {
}
}
/**
* Set whether this session will keep the device awake while it is running a voice
* activity. By default, the system holds a wake lock for it while in this state,
* so that it can work even if the screen is off. Setting this to false removes that
* wake lock, allowing the CPU to go to sleep. This is typically used if the
* session decides it has been waiting too long for a response from the user and
* doesn't want to let this continue to drain the battery.
*
* <p>Passing false here will release the wake lock, and you can call later with
* true to re-acquire it. It will also be automatically re-acquired for you each
* time you start a new voice activity task -- that is when you call
* {@link #startVoiceActivity}.</p>
*/
public void setKeepAwake(boolean keepAwake) {
if (mToken == null) {
throw new IllegalStateException("Can't call before onCreate()");
}
try {
mSystemService.setKeepAwake(mToken, keepAwake);
} catch (RemoteException e) {
}
}
/**
* Request that all system dialogs (and status bar shade etc) be closed, allowing
* access to the session's UI. This will <em>not</em> cause the lock screen to be
* dismissed.
*/
public void closeSystemDialogs() {
if (mToken == null) {
throw new IllegalStateException("Can't call before onCreate()");
}
try {
mSystemService.closeSystemDialogs(mToken);
} catch (RemoteException e) {
}
}
/**
* Convenience for inflating views.
*/
public LayoutInflater getLayoutInflater() {
return mInflater;
}
/**
* Retrieve the window being used to show the session's UI.
*/
public Dialog getWindow() {
return mWindow;
}
/**
* Finish the session. This completely destroys the session -- the next time it is shown,
* an entirely new one will be created. You do not normally call this function; instead,
* use {@link #hide} and allow the system to destroy your session if it needs its RAM.
*/
public void finish() {
if (mToken == null) {
throw new IllegalStateException("Can't call before onCreate()");
}
try {
mSystemService.finish(mToken);
} catch (RemoteException e) {
}
}
/**
* Initiatize a new session. At this point you don't know exactly what this
* session will be used for; you will find that out in {@link #onShow}.
*/
public void onCreate() {
doOnCreate();
}
private void doOnCreate() {
mTheme = mTheme != 0 ? mTheme
: com.android.internal.R.style.Theme_DeviceDefault_VoiceInteractionSession;
mInflater = (LayoutInflater)mContext.getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
mWindow = new SoftInputWindow(mContext, "VoiceInteractionSession", mTheme,
mCallbacks, this, mDispatcherState,
WindowManager.LayoutParams.TYPE_VOICE_INTERACTION, Gravity.BOTTOM, true);
mWindow.getWindow().addFlags(
WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED |
WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN |
WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR);
initViews();
mWindow.getWindow().setLayout(MATCH_PARENT, MATCH_PARENT);
mWindow.setToken(mToken);
}
/**
* Called when the session UI is going to be shown. This is called after
* {@link #onCreateContentView} (if the session's content UI needed to be created) and
* immediately prior to the window being shown. This may be called while the window
* is already shown, if a show request has come in while it is shown, to allow you to
* update the UI to match the new show arguments.
*
* @param args The arguments that were supplied to
* {@link VoiceInteractionService#showSession VoiceInteractionService.showSession}.
* @param showFlags The show flags originally provided to
* {@link VoiceInteractionService#showSession VoiceInteractionService.showSession}.
*/
public void onShow(Bundle args, int showFlags) {
}
/**
* Called immediately after stopping to show the session UI.
*/
public void onHide() {
}
/**
* Last callback to the session as it is being finished.
*/
public void onDestroy() {
}
/**
* Hook in which to create the session's UI.
*/
public View onCreateContentView() {
return null;
}
public void setContentView(View view) {
mContentFrame.removeAllViews();
mContentFrame.addView(view, new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT));
mContentFrame.requestApplyInsets();
}
void doOnHandleAssist(Bundle data, AssistStructure structure, Throwable failure,
AssistContent content) {
if (failure != null) {
onAssistStructureFailure(failure);
}
onHandleAssist(data, structure, content);
}
void doOnHandleAssistSecondary(Bundle data, AssistStructure structure, Throwable failure,
AssistContent content, int index, int count) {
if (failure != null) {
onAssistStructureFailure(failure);
}
onHandleAssistSecondary(data, structure, content, index, count);
}
/**
* Called when there has been a failure transferring the {@link AssistStructure} to
* the assistant. This may happen, for example, if the data is too large and results
* in an out of memory exception, or the client has provided corrupt data. This will
* be called immediately before {@link #onHandleAssist} and the AssistStructure supplied
* there afterwards will be null.
*
* @param failure The failure exception that was thrown when building the
* {@link AssistStructure}.
*/
public void onAssistStructureFailure(Throwable failure) {
}
/**
* Called to receive data from the application that the user was currently viewing when
* an assist session is started. If the original show request did not specify
* {@link #SHOW_WITH_ASSIST}, this method will not be called.
*
* @param data Arbitrary data supplied by the app through
* {@link android.app.Activity#onProvideAssistData Activity.onProvideAssistData}.
* May be null if assist data has been disabled by the user or device policy.
* @param structure If available, the structure definition of all windows currently
* displayed by the app. May be null if assist data has been disabled by the user
* or device policy; will be an empty stub if the application has disabled assist
* by marking its window as secure.
* @param content Additional content data supplied by the app through
* {@link android.app.Activity#onProvideAssistContent Activity.onProvideAssistContent}.
* May be null if assist data has been disabled by the user or device policy; will
* not be automatically filled in with data from the app if the app has marked its
* window as secure.
*/
public void onHandleAssist(@Nullable Bundle data, @Nullable AssistStructure structure,
@Nullable AssistContent content) {
}
/**
* Called to receive data from other applications that the user was or is interacting with,
* that are currently on the screen in a multi-window display environment, not including the
* currently focused activity. This could be
* a free-form window, a picture-in-picture window, or another window in a split-screen display.
* <p>
* This method is very similar to
* {@link #onHandleAssist} except that it is called
* for additional non-focused activities along with an index and count that indicates
* which additional activity the data is for. {@code index} will be between 1 and
* {@code count}-1 and this method is called once for each additional window, in no particular
* order. The {@code count} indicates how many windows to expect assist data for, including the
* top focused activity, which continues to be returned via {@link #onHandleAssist}.
* <p>
* To be responsive to assist requests, process assist data as soon as it is received,
* without waiting for all queued activities to return assist data.
*
* @param data Arbitrary data supplied by the app through
* {@link android.app.Activity#onProvideAssistData Activity.onProvideAssistData}.
* May be null if assist data has been disabled by the user or device policy.
* @param structure If available, the structure definition of all windows currently
* displayed by the app. May be null if assist data has been disabled by the user
* or device policy; will be an empty stub if the application has disabled assist
* by marking its window as secure.
* @param content Additional content data supplied by the app through
* {@link android.app.Activity#onProvideAssistContent Activity.onProvideAssistContent}.
* May be null if assist data has been disabled by the user or device policy; will
* not be automatically filled in with data from the app if the app has marked its
* window as secure.
* @param index the index of the additional activity that this data
* is for.
* @param count the total number of additional activities for which the assist data is being
* returned, including the focused activity that is returned via
* {@link #onHandleAssist}.
*/
public void onHandleAssistSecondary(@Nullable Bundle data, @Nullable AssistStructure structure,
@Nullable AssistContent content, int index, int count) {
}
/**
* Called to receive a screenshot of what the user was currently viewing when an assist
* session is started. May be null if screenshots are disabled by the user, policy,
* or application. If the original show request did not specify
* {@link #SHOW_WITH_SCREENSHOT}, this method will not be called.
*/
public void onHandleScreenshot(@Nullable Bitmap screenshot) {
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
return false;
}
public boolean onKeyLongPress(int keyCode, KeyEvent event) {
return false;
}
public boolean onKeyUp(int keyCode, KeyEvent event) {
return false;
}
public boolean onKeyMultiple(int keyCode, int count, KeyEvent event) {
return false;
}
/**
* Called when the user presses the back button while focus is in the session UI. Note
* that this will only happen if the session UI has requested input focus in its window;
* otherwise, the back key will go to whatever window has focus and do whatever behavior
* it normally has there. The default implementation simply calls {@link #hide}.
*/
public void onBackPressed() {
hide();
}
/**
* Sessions automatically watch for requests that all system UI be closed (such as when
* the user presses HOME), which will appear here. The default implementation always
* calls {@link #hide}.
*/
public void onCloseSystemDialogs() {
hide();
}
/**
* Called when the lockscreen was shown.
*/
public void onLockscreenShown() {
hide();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
}
@Override
public void onLowMemory() {
}
@Override
public void onTrimMemory(int level) {
}
/**
* Compute the interesting insets into your UI. The default implementation
* sets {@link Insets#contentInsets outInsets.contentInsets.top} to the height
* of the window, meaning it should not adjust content underneath. The default touchable
* insets are {@link Insets#TOUCHABLE_INSETS_FRAME}, meaning it consumes all touch
* events within its window frame.
*
* @param outInsets Fill in with the current UI insets.
*/
public void onComputeInsets(Insets outInsets) {
outInsets.contentInsets.left = 0;
outInsets.contentInsets.bottom = 0;
outInsets.contentInsets.right = 0;
View decor = getWindow().getWindow().getDecorView();
outInsets.contentInsets.top = decor.getHeight();
outInsets.touchableInsets = Insets.TOUCHABLE_INSETS_FRAME;
outInsets.touchableRegion.setEmpty();
}
/**
* Called when a task initiated by {@link #startVoiceActivity(android.content.Intent)}
* has actually started.
*
* @param intent The original {@link Intent} supplied to
* {@link #startVoiceActivity(android.content.Intent)}.
* @param taskId Unique ID of the now running task.
*/
public void onTaskStarted(Intent intent, int taskId) {
}
/**
* Called when the last activity of a task initiated by
* {@link #startVoiceActivity(android.content.Intent)} has finished. The default
* implementation calls {@link #finish()} on the assumption that this represents
* the completion of a voice action. You can override the implementation if you would
* like a different behavior.
*
* @param intent The original {@link Intent} supplied to
* {@link #startVoiceActivity(android.content.Intent)}.
* @param taskId Unique ID of the finished task.
*/
public void onTaskFinished(Intent intent, int taskId) {
hide();
}
/**
* Request to query for what extended commands the session supports.
*
* @param commands An array of commands that are being queried.
* @return Return an array of booleans indicating which of each entry in the
* command array is supported. A true entry in the array indicates the command
* is supported; false indicates it is not. The default implementation returns
* an array of all false entries.
*/
public boolean[] onGetSupportedCommands(String[] commands) {
return new boolean[commands.length];
}
/**
* Request to confirm with the user before proceeding with an unrecoverable operation,
* corresponding to a {@link android.app.VoiceInteractor.ConfirmationRequest
* VoiceInteractor.ConfirmationRequest}.
*
* @param request The active request.
*/
public void onRequestConfirmation(ConfirmationRequest request) {
}
/**
* Request for the user to pick one of N options, corresponding to a
* {@link android.app.VoiceInteractor.PickOptionRequest VoiceInteractor.PickOptionRequest}.
*
* @param request The active request.
*/
public void onRequestPickOption(PickOptionRequest request) {
}
/**
* Request to complete the voice interaction session because the voice activity successfully
* completed its interaction using voice. Corresponds to
* {@link android.app.VoiceInteractor.CompleteVoiceRequest
* VoiceInteractor.CompleteVoiceRequest}. The default implementation just sends an empty
* confirmation back to allow the activity to exit.
*
* @param request The active request.
*/
public void onRequestCompleteVoice(CompleteVoiceRequest request) {
}
/**
* Request to abort the voice interaction session because the voice activity can not
* complete its interaction using voice. Corresponds to
* {@link android.app.VoiceInteractor.AbortVoiceRequest
* VoiceInteractor.AbortVoiceRequest}. The default implementation just sends an empty
* confirmation back to allow the activity to exit.
*
* @param request The active request.
*/
public void onRequestAbortVoice(AbortVoiceRequest request) {
}
/**
* Process an arbitrary extended command from the caller,
* corresponding to a {@link android.app.VoiceInteractor.CommandRequest
* VoiceInteractor.CommandRequest}.
*
* @param request The active request.
*/
public void onRequestCommand(CommandRequest request) {
}
/**
* Called when the {@link android.app.VoiceInteractor} has asked to cancel a {@link Request}
* that was previously delivered to {@link #onRequestConfirmation},
* {@link #onRequestPickOption}, {@link #onRequestCompleteVoice}, {@link #onRequestAbortVoice},
* or {@link #onRequestCommand}.
*
* @param request The request that is being canceled.
*/
public void onCancelRequest(Request request) {
}
/**
* Print the Service's state into the given stream. This gets invoked by
* {@link VoiceInteractionSessionService} when its Service
* {@link android.app.Service#dump} method is called.
*
* @param prefix Text to print at the front of each line.
* @param fd The raw file descriptor that the dump is being sent to.
* @param writer The PrintWriter to which you should dump your state. This will be
* closed for you after you return.
* @param args additional arguments to the dump request.
*/
public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
writer.print(prefix); writer.print("mToken="); writer.println(mToken);
writer.print(prefix); writer.print("mTheme=#"); writer.println(Integer.toHexString(mTheme));
writer.print(prefix); writer.print("mInitialized="); writer.println(mInitialized);
writer.print(prefix); writer.print("mWindowAdded="); writer.print(mWindowAdded);
writer.print(" mWindowVisible="); writer.println(mWindowVisible);
writer.print(prefix); writer.print("mWindowWasVisible="); writer.print(mWindowWasVisible);
writer.print(" mInShowWindow="); writer.println(mInShowWindow);
if (mActiveRequests.size() > 0) {
writer.print(prefix); writer.println("Active requests:");
String innerPrefix = prefix + " ";
for (int i=0; i<mActiveRequests.size(); i++) {
Request req = mActiveRequests.valueAt(i);
writer.print(prefix); writer.print(" #"); writer.print(i);
writer.print(": ");
writer.println(req);
req.dump(innerPrefix, fd, writer, args);
}
}
}
}
|
fuldaros/paperplane_kernel_wileyfox-spark | sources/drivers/misc/mediatek/gpu/mt6735/mali/drivers/gpu/arm/midgard/mali_kbase_instr.c | /*
*
* (C) COPYRIGHT ARM Limited. All rights reserved.
*
* This program is free software and is provided to you under the terms of the
* GNU General Public License version 2 as published by the Free Software
* Foundation, and any use by you of this program is subject to the terms
* of such GNU licence.
*
* A copy of the licence is included with the program, and can also be obtained
* from Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*
*/
/**
* @file mali_kbase_instr.c
* Base kernel instrumentation APIs.
*/
#include <mali_kbase.h>
#include <mali_midg_regmap.h>
/**
* @brief Issue Cache Clean & Invalidate command to hardware
*/
static void kbasep_instr_hwcnt_cacheclean(struct kbase_device *kbdev)
{
unsigned long flags;
unsigned long pm_flags;
u32 irq_mask;
KBASE_DEBUG_ASSERT(NULL != kbdev);
spin_lock_irqsave(&kbdev->hwcnt.lock, flags);
/* Wait for any reset to complete */
while (kbdev->hwcnt.state == KBASE_INSTR_STATE_RESETTING) {
spin_unlock_irqrestore(&kbdev->hwcnt.lock, flags);
wait_event(kbdev->hwcnt.cache_clean_wait,
kbdev->hwcnt.state != KBASE_INSTR_STATE_RESETTING);
spin_lock_irqsave(&kbdev->hwcnt.lock, flags);
}
KBASE_DEBUG_ASSERT(kbdev->hwcnt.state == KBASE_INSTR_STATE_REQUEST_CLEAN);
/* Enable interrupt */
spin_lock_irqsave(&kbdev->pm.power_change_lock, pm_flags);
irq_mask = kbase_reg_read(kbdev, GPU_CONTROL_REG(GPU_IRQ_MASK), NULL);
kbase_reg_write(kbdev, GPU_CONTROL_REG(GPU_IRQ_MASK), irq_mask | CLEAN_CACHES_COMPLETED, NULL);
spin_unlock_irqrestore(&kbdev->pm.power_change_lock, pm_flags);
/* clean&invalidate the caches so we're sure the mmu tables for the dump buffer is valid */
KBASE_TRACE_ADD(kbdev, CORE_GPU_CLEAN_INV_CACHES, NULL, NULL, 0u, 0);
kbase_reg_write(kbdev, GPU_CONTROL_REG(GPU_COMMAND), GPU_COMMAND_CLEAN_INV_CACHES, NULL);
kbdev->hwcnt.state = KBASE_INSTR_STATE_CLEANING;
spin_unlock_irqrestore(&kbdev->hwcnt.lock, flags);
}
STATIC mali_error kbase_instr_hwcnt_enable_internal(struct kbase_device *kbdev, struct kbase_context *kctx, struct kbase_uk_hwcnt_setup *setup)
{
unsigned long flags, pm_flags;
mali_error err = MALI_ERROR_FUNCTION_FAILED;
struct kbasep_js_device_data *js_devdata;
u32 irq_mask;
int ret;
u64 shader_cores_needed;
KBASE_DEBUG_ASSERT(NULL != kctx);
KBASE_DEBUG_ASSERT(NULL != kbdev);
KBASE_DEBUG_ASSERT(NULL != setup);
KBASE_DEBUG_ASSERT(NULL == kbdev->hwcnt.suspended_kctx);
shader_cores_needed = kbase_pm_get_present_cores(kbdev, KBASE_PM_CORE_SHADER);
js_devdata = &kbdev->js_data;
/* alignment failure */
if ((setup->dump_buffer == 0ULL) || (setup->dump_buffer & (2048 - 1)))
goto out_err;
/* Override core availability policy to ensure all cores are available */
kbase_pm_ca_instr_enable(kbdev);
/* Mark the context as active so the GPU is kept turned on */
/* A suspend won't happen here, because we're in a syscall from a userspace
* thread. */
kbase_pm_context_active(kbdev);
/* Request the cores early on synchronously - we'll release them on any errors
* (e.g. instrumentation already active) */
kbase_pm_request_cores_sync(kbdev, MALI_TRUE, shader_cores_needed);
spin_lock_irqsave(&kbdev->hwcnt.lock, flags);
if (kbdev->hwcnt.state == KBASE_INSTR_STATE_RESETTING) {
/* GPU is being reset */
spin_unlock_irqrestore(&kbdev->hwcnt.lock, flags);
wait_event(kbdev->hwcnt.wait, kbdev->hwcnt.triggered != 0);
spin_lock_irqsave(&kbdev->hwcnt.lock, flags);
}
if (kbdev->hwcnt.state != KBASE_INSTR_STATE_DISABLED) {
/* Instrumentation is already enabled */
spin_unlock_irqrestore(&kbdev->hwcnt.lock, flags);
goto out_unrequest_cores;
}
/* Enable interrupt */
spin_lock_irqsave(&kbdev->pm.power_change_lock, pm_flags);
irq_mask = kbase_reg_read(kbdev, GPU_CONTROL_REG(GPU_IRQ_MASK), NULL);
kbase_reg_write(kbdev, GPU_CONTROL_REG(GPU_IRQ_MASK), irq_mask | PRFCNT_SAMPLE_COMPLETED, NULL);
spin_unlock_irqrestore(&kbdev->pm.power_change_lock, pm_flags);
/* In use, this context is the owner */
kbdev->hwcnt.kctx = kctx;
/* Remember the dump address so we can reprogram it later */
kbdev->hwcnt.addr = setup->dump_buffer;
/* Remember all the settings for suspend/resume */
if (&kbdev->hwcnt.suspended_state != setup)
memcpy(&kbdev->hwcnt.suspended_state, setup, sizeof(kbdev->hwcnt.suspended_state));
/* Request the clean */
kbdev->hwcnt.state = KBASE_INSTR_STATE_REQUEST_CLEAN;
kbdev->hwcnt.triggered = 0;
/* Clean&invalidate the caches so we're sure the mmu tables for the dump buffer is valid */
ret = queue_work(kbdev->hwcnt.cache_clean_wq, &kbdev->hwcnt.cache_clean_work);
KBASE_DEBUG_ASSERT(ret);
spin_unlock_irqrestore(&kbdev->hwcnt.lock, flags);
/* Wait for cacheclean to complete */
wait_event(kbdev->hwcnt.wait, kbdev->hwcnt.triggered != 0);
KBASE_DEBUG_ASSERT(kbdev->hwcnt.state == KBASE_INSTR_STATE_IDLE);
/* Schedule the context in */
kbasep_js_schedule_privileged_ctx(kbdev, kctx);
/* Configure */
kbase_reg_write(kbdev, GPU_CONTROL_REG(PRFCNT_CONFIG), (kctx->as_nr << PRFCNT_CONFIG_AS_SHIFT) | PRFCNT_CONFIG_MODE_OFF, kctx);
kbase_reg_write(kbdev, GPU_CONTROL_REG(PRFCNT_BASE_LO), setup->dump_buffer & 0xFFFFFFFF, kctx);
kbase_reg_write(kbdev, GPU_CONTROL_REG(PRFCNT_BASE_HI), setup->dump_buffer >> 32, kctx);
kbase_reg_write(kbdev, GPU_CONTROL_REG(PRFCNT_JM_EN), setup->jm_bm, kctx);
kbase_reg_write(kbdev, GPU_CONTROL_REG(PRFCNT_SHADER_EN), setup->shader_bm, kctx);
kbase_reg_write(kbdev, GPU_CONTROL_REG(PRFCNT_L3_CACHE_EN), setup->l3_cache_bm, kctx);
kbase_reg_write(kbdev, GPU_CONTROL_REG(PRFCNT_MMU_L2_EN), setup->mmu_l2_bm, kctx);
/* Due to PRLAM-8186 we need to disable the Tiler before we enable the HW counter dump. */
if (kbase_hw_has_issue(kbdev, BASE_HW_ISSUE_8186))
kbase_reg_write(kbdev, GPU_CONTROL_REG(PRFCNT_TILER_EN), 0, kctx);
else
kbase_reg_write(kbdev, GPU_CONTROL_REG(PRFCNT_TILER_EN), setup->tiler_bm, kctx);
kbase_reg_write(kbdev, GPU_CONTROL_REG(PRFCNT_CONFIG), (kctx->as_nr << PRFCNT_CONFIG_AS_SHIFT) | PRFCNT_CONFIG_MODE_MANUAL, kctx);
/* If HW has PRLAM-8186 we can now re-enable the tiler HW counters dump */
if (kbase_hw_has_issue(kbdev, BASE_HW_ISSUE_8186))
kbase_reg_write(kbdev, GPU_CONTROL_REG(PRFCNT_TILER_EN), setup->tiler_bm, kctx);
spin_lock_irqsave(&kbdev->hwcnt.lock, flags);
if (kbdev->hwcnt.state == KBASE_INSTR_STATE_RESETTING) {
/* GPU is being reset */
spin_unlock_irqrestore(&kbdev->hwcnt.lock, flags);
wait_event(kbdev->hwcnt.wait, kbdev->hwcnt.triggered != 0);
spin_lock_irqsave(&kbdev->hwcnt.lock, flags);
}
kbdev->hwcnt.state = KBASE_INSTR_STATE_IDLE;
kbdev->hwcnt.triggered = 1;
wake_up(&kbdev->hwcnt.wait);
spin_unlock_irqrestore(&kbdev->hwcnt.lock, flags);
err = MALI_ERROR_NONE;
dev_dbg(kbdev->dev, "HW counters dumping set-up for context %p", kctx);
return err;
out_unrequest_cores:
kbase_pm_unrequest_cores(kbdev, MALI_TRUE, shader_cores_needed);
kbase_pm_context_idle(kbdev);
out_err:
return err;
}
/**
* @brief Enable HW counters collection
*
* Note: will wait for a cache clean to complete
*/
mali_error kbase_instr_hwcnt_enable(struct kbase_context *kctx, struct kbase_uk_hwcnt_setup *setup)
{
struct kbase_device *kbdev;
mali_bool access_allowed;
kbdev = kctx->kbdev;
KBASE_DEBUG_ASSERT(NULL != kctx);
/* Determine if the calling task has access to this capability */
access_allowed = kbase_security_has_capability(kctx, KBASE_SEC_INSTR_HW_COUNTERS_COLLECT, KBASE_SEC_FLAG_NOAUDIT);
if (MALI_FALSE == access_allowed)
return MALI_ERROR_FUNCTION_FAILED;
return kbase_instr_hwcnt_enable_internal(kbdev, kctx, setup);
}
KBASE_EXPORT_SYMBOL(kbase_instr_hwcnt_enable)
/**
* @brief Disable HW counters collection
*
* Note: might sleep, waiting for an ongoing dump to complete
*/
mali_error kbase_instr_hwcnt_disable(struct kbase_context *kctx)
{
unsigned long flags, pm_flags;
mali_error err = MALI_ERROR_FUNCTION_FAILED;
u32 irq_mask;
struct kbase_device *kbdev;
KBASE_DEBUG_ASSERT(NULL != kctx);
kbdev = kctx->kbdev;
KBASE_DEBUG_ASSERT(NULL != kbdev);
while (1) {
spin_lock_irqsave(&kbdev->hwcnt.lock, flags);
if (kbdev->hwcnt.state == KBASE_INSTR_STATE_DISABLED) {
/* Instrumentation is not enabled */
spin_unlock_irqrestore(&kbdev->hwcnt.lock, flags);
goto out;
}
if (kbdev->hwcnt.kctx != kctx) {
/* Instrumentation has been setup for another context */
spin_unlock_irqrestore(&kbdev->hwcnt.lock, flags);
goto out;
}
if (kbdev->hwcnt.state == KBASE_INSTR_STATE_IDLE)
break;
spin_unlock_irqrestore(&kbdev->hwcnt.lock, flags);
/* Ongoing dump/setup - wait for its completion */
wait_event(kbdev->hwcnt.wait, kbdev->hwcnt.triggered != 0);
}
kbdev->hwcnt.state = KBASE_INSTR_STATE_DISABLED;
kbdev->hwcnt.triggered = 0;
/* Disable interrupt */
spin_lock_irqsave(&kbdev->pm.power_change_lock, pm_flags);
irq_mask = kbase_reg_read(kbdev, GPU_CONTROL_REG(GPU_IRQ_MASK), NULL);
kbase_reg_write(kbdev, GPU_CONTROL_REG(GPU_IRQ_MASK), irq_mask & ~PRFCNT_SAMPLE_COMPLETED, NULL);
spin_unlock_irqrestore(&kbdev->pm.power_change_lock, pm_flags);
/* Disable the counters */
kbase_reg_write(kbdev, GPU_CONTROL_REG(PRFCNT_CONFIG), 0, kctx);
kbdev->hwcnt.kctx = NULL;
kbdev->hwcnt.addr = 0ULL;
kbase_pm_ca_instr_disable(kbdev);
kbase_pm_unrequest_cores(kbdev, MALI_TRUE, kbase_pm_get_present_cores(kbdev, KBASE_PM_CORE_SHADER));
spin_unlock_irqrestore(&kbdev->hwcnt.lock, flags);
/* Release the context. This had its own Power Manager Active reference */
kbasep_js_release_privileged_ctx(kbdev, kctx);
/* Also release our Power Manager Active reference */
kbase_pm_context_idle(kbdev);
dev_dbg(kbdev->dev, "HW counters dumping disabled for context %p", kctx);
err = MALI_ERROR_NONE;
out:
return err;
}
KBASE_EXPORT_SYMBOL(kbase_instr_hwcnt_disable)
/**
* @brief Configure HW counters collection
*/
mali_error kbase_instr_hwcnt_setup(struct kbase_context *kctx, struct kbase_uk_hwcnt_setup *setup)
{
mali_error err = MALI_ERROR_FUNCTION_FAILED;
struct kbase_device *kbdev;
KBASE_DEBUG_ASSERT(NULL != kctx);
kbdev = kctx->kbdev;
KBASE_DEBUG_ASSERT(NULL != kbdev);
if (NULL == setup) {
/* Bad parameter - abort */
goto out;
}
if (setup->dump_buffer != 0ULL) {
/* Enable HW counters */
err = kbase_instr_hwcnt_enable(kctx, setup);
} else {
/* Disable HW counters */
err = kbase_instr_hwcnt_disable(kctx);
}
out:
return err;
}
/**
* @brief Issue Dump command to hardware
*
* Notes:
* - does not sleep
*/
mali_error kbase_instr_hwcnt_dump_irq(struct kbase_context *kctx)
{
unsigned long flags;
mali_error err = MALI_ERROR_FUNCTION_FAILED;
struct kbase_device *kbdev;
KBASE_DEBUG_ASSERT(NULL != kctx);
kbdev = kctx->kbdev;
KBASE_DEBUG_ASSERT(NULL != kbdev);
spin_lock_irqsave(&kbdev->hwcnt.lock, flags);
if (kbdev->hwcnt.kctx != kctx) {
/* The instrumentation has been setup for another context */
goto unlock;
}
if (kbdev->hwcnt.state != KBASE_INSTR_STATE_IDLE) {
/* HW counters are disabled or another dump is ongoing, or we're resetting */
goto unlock;
}
kbdev->hwcnt.triggered = 0;
/* Mark that we're dumping - the PF handler can signal that we faulted */
kbdev->hwcnt.state = KBASE_INSTR_STATE_DUMPING;
/* Reconfigure the dump address */
kbase_reg_write(kbdev, GPU_CONTROL_REG(PRFCNT_BASE_LO), kbdev->hwcnt.addr & 0xFFFFFFFF, NULL);
kbase_reg_write(kbdev, GPU_CONTROL_REG(PRFCNT_BASE_HI), kbdev->hwcnt.addr >> 32, NULL);
/* Start dumping */
KBASE_TRACE_ADD(kbdev, CORE_GPU_PRFCNT_SAMPLE, NULL, NULL, kbdev->hwcnt.addr, 0);
kbase_reg_write(kbdev, GPU_CONTROL_REG(GPU_COMMAND), GPU_COMMAND_PRFCNT_SAMPLE, kctx);
dev_dbg(kbdev->dev, "HW counters dumping done for context %p", kctx);
err = MALI_ERROR_NONE;
unlock:
spin_unlock_irqrestore(&kbdev->hwcnt.lock, flags);
return err;
}
KBASE_EXPORT_SYMBOL(kbase_instr_hwcnt_dump_irq)
/**
* @brief Tell whether the HW counters dump has completed
*
* Notes:
* - does not sleep
* - success will be set to MALI_TRUE if the dump succeeded or
* MALI_FALSE on failure
*/
mali_bool kbase_instr_hwcnt_dump_complete(struct kbase_context *kctx, mali_bool * const success)
{
unsigned long flags;
mali_bool complete = MALI_FALSE;
struct kbase_device *kbdev;
KBASE_DEBUG_ASSERT(NULL != kctx);
kbdev = kctx->kbdev;
KBASE_DEBUG_ASSERT(NULL != kbdev);
KBASE_DEBUG_ASSERT(NULL != success);
spin_lock_irqsave(&kbdev->hwcnt.lock, flags);
if (kbdev->hwcnt.state == KBASE_INSTR_STATE_IDLE) {
*success = MALI_TRUE;
complete = MALI_TRUE;
} else if (kbdev->hwcnt.state == KBASE_INSTR_STATE_FAULT) {
*success = MALI_FALSE;
complete = MALI_TRUE;
kbdev->hwcnt.state = KBASE_INSTR_STATE_IDLE;
}
spin_unlock_irqrestore(&kbdev->hwcnt.lock, flags);
return complete;
}
KBASE_EXPORT_SYMBOL(kbase_instr_hwcnt_dump_complete)
/**
* @brief Issue Dump command to hardware and wait for completion
*/
mali_error kbase_instr_hwcnt_dump(struct kbase_context *kctx)
{
unsigned long flags;
mali_error err = MALI_ERROR_FUNCTION_FAILED;
struct kbase_device *kbdev;
KBASE_DEBUG_ASSERT(NULL != kctx);
kbdev = kctx->kbdev;
KBASE_DEBUG_ASSERT(NULL != kbdev);
err = kbase_instr_hwcnt_dump_irq(kctx);
if (MALI_ERROR_NONE != err) {
/* Can't dump HW counters */
goto out;
}
/* Wait for dump & cacheclean to complete */
wait_event(kbdev->hwcnt.wait, kbdev->hwcnt.triggered != 0);
spin_lock_irqsave(&kbdev->hwcnt.lock, flags);
if (kbdev->hwcnt.state == KBASE_INSTR_STATE_RESETTING) {
/* GPU is being reset */
spin_unlock_irqrestore(&kbdev->hwcnt.lock, flags);
wait_event(kbdev->hwcnt.wait, kbdev->hwcnt.triggered != 0);
spin_lock_irqsave(&kbdev->hwcnt.lock, flags);
}
if (kbdev->hwcnt.state == KBASE_INSTR_STATE_FAULT) {
err = MALI_ERROR_FUNCTION_FAILED;
kbdev->hwcnt.state = KBASE_INSTR_STATE_IDLE;
} else {
/* Dump done */
KBASE_DEBUG_ASSERT(kbdev->hwcnt.state == KBASE_INSTR_STATE_IDLE);
err = MALI_ERROR_NONE;
}
spin_unlock_irqrestore(&kbdev->hwcnt.lock, flags);
out:
return err;
}
KBASE_EXPORT_SYMBOL(kbase_instr_hwcnt_dump)
/**
* @brief Clear the HW counters
*/
mali_error kbase_instr_hwcnt_clear(struct kbase_context *kctx)
{
unsigned long flags;
mali_error err = MALI_ERROR_FUNCTION_FAILED;
struct kbase_device *kbdev;
KBASE_DEBUG_ASSERT(NULL != kctx);
kbdev = kctx->kbdev;
KBASE_DEBUG_ASSERT(NULL != kbdev);
spin_lock_irqsave(&kbdev->hwcnt.lock, flags);
if (kbdev->hwcnt.state == KBASE_INSTR_STATE_RESETTING) {
/* GPU is being reset */
spin_unlock_irqrestore(&kbdev->hwcnt.lock, flags);
wait_event(kbdev->hwcnt.wait, kbdev->hwcnt.triggered != 0);
spin_lock_irqsave(&kbdev->hwcnt.lock, flags);
}
/* Check it's the context previously set up and we're not already dumping */
if (kbdev->hwcnt.kctx != kctx || kbdev->hwcnt.state != KBASE_INSTR_STATE_IDLE)
goto out;
/* Clear the counters */
KBASE_TRACE_ADD(kbdev, CORE_GPU_PRFCNT_CLEAR, NULL, NULL, 0u, 0);
kbase_reg_write(kbdev, GPU_CONTROL_REG(GPU_COMMAND), GPU_COMMAND_PRFCNT_CLEAR, kctx);
err = MALI_ERROR_NONE;
out:
spin_unlock_irqrestore(&kbdev->hwcnt.lock, flags);
return err;
}
KBASE_EXPORT_SYMBOL(kbase_instr_hwcnt_clear)
/**
* Workqueue for handling cache cleaning
*/
void kbasep_cache_clean_worker(struct work_struct *data)
{
struct kbase_device *kbdev;
unsigned long flags;
kbdev = container_of(data, struct kbase_device, hwcnt.cache_clean_work);
mutex_lock(&kbdev->cacheclean_lock);
kbasep_instr_hwcnt_cacheclean(kbdev);
spin_lock_irqsave(&kbdev->hwcnt.lock, flags);
/* Wait for our condition, and any reset to complete */
while (kbdev->hwcnt.state == KBASE_INSTR_STATE_RESETTING ||
kbdev->hwcnt.state == KBASE_INSTR_STATE_CLEANING) {
spin_unlock_irqrestore(&kbdev->hwcnt.lock, flags);
wait_event(kbdev->hwcnt.cache_clean_wait,
(kbdev->hwcnt.state != KBASE_INSTR_STATE_RESETTING
&& kbdev->hwcnt.state != KBASE_INSTR_STATE_CLEANING));
spin_lock_irqsave(&kbdev->hwcnt.lock, flags);
}
KBASE_DEBUG_ASSERT(kbdev->hwcnt.state == KBASE_INSTR_STATE_CLEANED);
/* All finished and idle */
kbdev->hwcnt.state = KBASE_INSTR_STATE_IDLE;
kbdev->hwcnt.triggered = 1;
wake_up(&kbdev->hwcnt.wait);
spin_unlock_irqrestore(&kbdev->hwcnt.lock, flags);
mutex_unlock(&kbdev->cacheclean_lock);
}
/**
* @brief Dump complete interrupt received
*/
void kbase_instr_hwcnt_sample_done(struct kbase_device *kbdev)
{
unsigned long flags;
spin_lock_irqsave(&kbdev->hwcnt.lock, flags);
if (kbdev->hwcnt.state == KBASE_INSTR_STATE_FAULT) {
kbdev->hwcnt.triggered = 1;
wake_up(&kbdev->hwcnt.wait);
} else if (kbdev->hwcnt.state == KBASE_INSTR_STATE_DUMPING) {
int ret;
/* Always clean and invalidate the cache after a successful dump */
kbdev->hwcnt.state = KBASE_INSTR_STATE_REQUEST_CLEAN;
ret = queue_work(kbdev->hwcnt.cache_clean_wq, &kbdev->hwcnt.cache_clean_work);
KBASE_DEBUG_ASSERT(ret);
}
/* NOTE: In the state KBASE_INSTR_STATE_RESETTING, We're in a reset,
* and the instrumentation state hasn't been restored yet -
* kbasep_reset_timeout_worker() will do the rest of the work */
spin_unlock_irqrestore(&kbdev->hwcnt.lock, flags);
}
/**
* @brief Cache clean interrupt received
*/
void kbase_clean_caches_done(struct kbase_device *kbdev)
{
u32 irq_mask;
if (kbdev->hwcnt.state != KBASE_INSTR_STATE_DISABLED) {
unsigned long flags;
unsigned long pm_flags;
spin_lock_irqsave(&kbdev->hwcnt.lock, flags);
/* Disable interrupt */
spin_lock_irqsave(&kbdev->pm.power_change_lock, pm_flags);
irq_mask = kbase_reg_read(kbdev, GPU_CONTROL_REG(GPU_IRQ_MASK), NULL);
kbase_reg_write(kbdev, GPU_CONTROL_REG(GPU_IRQ_MASK), irq_mask & ~CLEAN_CACHES_COMPLETED, NULL);
spin_unlock_irqrestore(&kbdev->pm.power_change_lock, pm_flags);
/* Wakeup... */
if (kbdev->hwcnt.state == KBASE_INSTR_STATE_CLEANING) {
/* Only wake if we weren't resetting */
kbdev->hwcnt.state = KBASE_INSTR_STATE_CLEANED;
wake_up(&kbdev->hwcnt.cache_clean_wait);
}
/* NOTE: In the state KBASE_INSTR_STATE_RESETTING, We're in a reset,
* and the instrumentation state hasn't been restored yet -
* kbasep_reset_timeout_worker() will do the rest of the work */
spin_unlock_irqrestore(&kbdev->hwcnt.lock, flags);
}
}
/* Disable instrumentation and wait for any existing dump to complete
* It's assumed that there's only one privileged context
* Safe to do this without lock when doing an OS suspend, because it only
* changes in response to user-space IOCTLs */
void kbase_instr_hwcnt_suspend(struct kbase_device *kbdev)
{
struct kbase_context *kctx;
KBASE_DEBUG_ASSERT(kbdev);
KBASE_DEBUG_ASSERT(!kbdev->hwcnt.suspended_kctx);
kctx = kbdev->hwcnt.kctx;
kbdev->hwcnt.suspended_kctx = kctx;
/* Relevant state was saved into hwcnt.suspended_state when enabling the
* counters */
if (kctx) {
KBASE_DEBUG_ASSERT(kctx->jctx.sched_info.ctx.flags & KBASE_CTX_FLAG_PRIVILEGED);
kbase_instr_hwcnt_disable(kctx);
}
}
void kbase_instr_hwcnt_resume(struct kbase_device *kbdev)
{
struct kbase_context *kctx;
KBASE_DEBUG_ASSERT(kbdev);
kctx = kbdev->hwcnt.suspended_kctx;
kbdev->hwcnt.suspended_kctx = NULL;
if (kctx) {
mali_error err;
err = kbase_instr_hwcnt_enable_internal(kbdev, kctx, &kbdev->hwcnt.suspended_state);
WARN(err != MALI_ERROR_NONE,
"Failed to restore instrumented hardware counters on resume\n");
}
}
|
theithec/pagetools | pagetools/models.py | <gh_stars>0
"""Core models, managers and querysets for pagetools
"""
import warnings
from django.conf import settings
from django.db import models
from django.utils.translation import get_language
from django.utils.translation import gettext_lazy as _
from model_utils.choices import Choices
from model_utils.models import StatusModel, TimeStampedModel
from . import settings as ptsettings
class LangQueryset(models.QuerySet):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.use_lang = bool(getattr(settings, "LANGUAGES", False))
def lfilter(self, lang=False, **kwargs):
"""Uses keyword-argument or system-language to add 'lang' to filter-
arguments if settings.LANGUAGES compares not to null"""
if self.use_lang and not kwargs.pop("skip_lang", False):
if lang is False:
lang = get_language() or ""
kwargs.update(lang__in=(lang, lang.split("-")[0], ""))
return self.filter(**kwargs)
class LangManager(models.Manager):
"""
Manager for models with a lang-field
"""
def get_queryset(self):
return LangQueryset(self.model, using=self._db)
def lfilter(self, lang=False, **kwargs):
return self.get_queryset().lfilter(lang=lang, **kwargs)
class LangModel(models.Model):
"""
Model with a ``lang``-field.
Note:
To avoid `NOT NULL constraint failed` errors,
empty lang is saved as "".
"""
objects = models.Manager()
# public = LangManager()
lang = models.CharField(
max_length=20,
choices=settings.LANGUAGES,
blank=True,
verbose_name=_("language"),
)
def save(self, *args, **kwargs):
if self.lang is None:
self.lang = ""
super(LangModel, self).save(*args, **kwargs)
class Meta:
abstract = True
class PublishableQueryset(LangQueryset):
def lfilter(self, **kwargs):
"""
For non authenticated users returns only published content
"""
user = kwargs.pop("user", None)
if not user or not user.is_authenticated:
kwargs["status"] = ptsettings.STATUS_PUBLISHED
return LangQueryset.lfilter(self, **kwargs)
class PublishableLangQueryset(LangQueryset):
def lfilter(self, **kwargs):
"""
For non authenticated users returns only published content
and filters for language (if settings.LANGUAGES has entries)
See :class: `LangManager`
"""
user = kwargs.pop("user", None)
if not user or not user.is_authenticated:
kwargs["status"] = ptsettings.STATUS_PUBLISHED
return LangQueryset.lfilter(self, **kwargs)
class PublishableLangManager(LangManager):
"""
Manager that finds published content language filtered
"""
def get_queryset(self):
return PublishableLangQueryset(self.model, using=self._db)
class PublishableLangModel(LangModel, StatusModel):
"""
Model with a language and a status field and a ``PublishableLangManager``
"""
_translated_choices = [(slug, _(name)) for (slug, name) in ptsettings.STATUS_CHOICES]
STATUS = Choices(*_translated_choices)
public = PublishableLangManager()
def _enabled(self):
warnings.warn("Depricated. Bad naming. Use ``is_published``.")
return self.status == ptsettings.STATUS_PUBLISHED
_enabled.boolean = True # type: ignore
_enabled.admin_order_field = "status" # type: ignore
enabled = property(_enabled)
def _is_published(self):
return self.status == ptsettings.STATUS_PUBLISHED
_is_published.boolean = True # type: ignore
_is_published.admin_order_field = "status" # type: ignore
is_published = property(_is_published)
class Meta:
abstract = True
class PagelikeModel(TimeStampedModel, PublishableLangModel):
"""
This could be a base model for everything that inclines a detail_view
Args:
title (str)
slug (str)
description (Optional[str]): for metatag/seo
"""
title = models.CharField(_("Title"), max_length=255)
slug = models.SlugField(_("Slug"), max_length=255, allow_unicode=True)
description = models.CharField(
_("Description"),
max_length=156,
help_text="""Description (for searchengines)""",
blank=True,
)
def get_absolute_url(self) -> str:
"""Dummy"""
return f"/{self.slug}"
def __str__(self) -> str:
return str(self.title)
class Meta:
abstract = True
|
proglang/dts-generate-results | results/4_extract-code/code/changelog-parser/changelog-parser_1.js | var parseChangelog = require('changelog-parser')
|
tejpochiraju/onecourse-main | app/src/main/java/org/onebillion/onecourse/mainui/oc_countmore/OC_CountMore_S3.java | <reponame>tejpochiraju/onecourse-main<gh_stars>10-100
package org.onebillion.onecourse.mainui.oc_countmore;
import android.graphics.Color;
import android.graphics.PointF;
import android.graphics.RectF;
import android.view.View;
import org.onebillion.onecourse.controls.OBControl;
import org.onebillion.onecourse.controls.OBGroup;
import org.onebillion.onecourse.controls.OBLabel;
import org.onebillion.onecourse.mainui.OC_SectionController;
import org.onebillion.onecourse.utils.OBMisc;
import org.onebillion.onecourse.utils.OBUtils;
import org.onebillion.onecourse.utils.OB_Maths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* Created by michal on 20/02/2017.
*/
public class OC_CountMore_S3 extends OC_SectionController
{
List<OBGroup> numbers;
List<OBControl> sceneObjs;
int hilitecolour;
int correct;
public void prepare()
{
setStatus(STATUS_BUSY);
super.prepare();
loadFingers();
loadEvent("master");
loadNumbers();
sceneObjs = new ArrayList<>();
hilitecolour = OBUtils.colorFromRGBString(eventAttributes.get("colour_highlight"));
events = Arrays.asList(eventAttributes.get("scenes").split(","));
setSceneXX(currentEvent());
}
public void start()
{
OBUtils.runOnOtherThread(new OBUtils.RunLambda()
{
public void run() throws Exception
{
demo3a();
}
});
}
public void setSceneXX(String scene)
{
super.setSceneXX(scene);
correct = Integer.valueOf(eventAttributes.get("correct"));
if(eventAttributes.get("reload") != null)
{
for(OBControl con : sceneObjs) detachControl(con);
sceneObjs.clear();
String[] vals = eventAttributes.get("reload").split(",");
int val1 = Integer.valueOf(vals[0]);
int val2 = Integer.valueOf(vals[1]);
OBGroup obj = (OBGroup)objectDict.get("obj");
obj.show();
OBGroup group = new OBGroup(Arrays.asList(obj.copy()));
obj.hide();
group.highlight();
group.lowlight();
PointF rloc = OB_Maths.relativePointInRectForLocation(obj.position(), objectDict.get("workrect").frame());
float distance = (1.0f-(rloc.x*2.0f))/(val1-1);
for(int i=0;i<val2;i++)
{
OBGroup screenObj = (OBGroup)group.copy();
PointF objLoc = new PointF(rloc.x + (i%val1) *distance, rloc.y);
screenObj.setPosition ( OB_Maths.locationForRect(objLoc.x,objLoc.y,objectDict.get("workrect").frame()));
if(i>=val1)
{
screenObj.setTop (sceneObjs.get(0).bottom()+0.3f*screenObj.height());
}
attachControl(screenObj);
sceneObjs.add(screenObj);
}
}
for(int i=0;i<sceneObjs.size();i++)
sceneObjs.get(i).hide();
for(int i=0;i<correct;i++)
sceneObjs.get(i).show();
for(OBGroup con : numbers)
con.objectDict.get("box").setBackgroundColor(Color.WHITE);
}
public void doMainXX() throws Exception
{
startScene();
}
public void touchDownAtPoint(final PointF pt,View v)
{
if(status() == STATUS_AWAITING_CLICK)
{
final OBGroup box = (OBGroup)finger(-1,-1,(List<OBControl>)(Object)numbers, pt);
if(box != null)
{
setStatus(STATUS_BUSY);
OBUtils.runOnOtherThread(new OBUtils.RunLambda()
{
public void run() throws Exception
{
checkTarget(box);
}
});
}
}
}
public void checkTarget(OBGroup box) throws Exception
{
playAudio(null);
box.objectDict.get("box").setBackgroundColor(hilitecolour);
if((int)box.settings.get("num_val") == correct)
{
gotItRightBigTick(true);
waitForSecs(0.3f);
playAudioQueuedScene("FINAL",0.3f,true);
waitForSecs(0.5f);
nextScene();
}
else
{
gotItWrongWithSfx();
long time = setStatus(STATUS_AWAITING_CLICK);
waitSFX();
box.objectDict.get("box").setBackgroundColor(Color.WHITE);
if(time == statusTime)
playAudioQueuedScene("INCORRECT",0.3f,false);
}
}
public void startScene() throws Exception
{
demoCount();
OBMisc.doSceneAudio(4,setStatus(STATUS_AWAITING_CLICK),this);
}
public void loadNumbers()
{
numbers = new ArrayList<>();
OBControl numbox = objectDict.get("numbox");
float fontSize = 65.0f*numbox.height()/85.0f;
for(int i = 0;i<10;i++)
{
OBControl box = new OBControl();
box.setFrame(new RectF(0, 0, numbox.width()/10.0f, numbox.height()));
box.setBackgroundColor(Color.WHITE);
box.setBorderColor(Color.BLACK);
box.setBorderWidth(applyGraphicScale(2));
box.setPosition(OB_Maths.locationForRect(1/10.0f * i,0.5f,numbox.frame()));
box.setLeft(numbox.position().x - (5-i)*(box.width() - box.borderWidth));
OBLabel label = new OBLabel(String.format("%d",(i+1)*2),OBUtils.standardTypeFace(), fontSize);
label.setColour(Color.BLACK);
label.setPosition(box.position());
OBGroup group = new OBGroup(Arrays.asList(box,label));
group.objectDict.put("label",label);
group.objectDict.put("box",box);
attachControl(group);
group.setProperty("num_val",i+1);
numbers.add(group);
}
}
public void demoCount() throws Exception
{
playAudioQueuedScene("DEMO",0.3f,true);
waitForSecs(0.3f);
if(getAudioForScene(currentEvent(),"DEMO2") != null)
{
for(int i=0;i<correct;i++)
{
OBGroup cont = (OBGroup)sceneObjs.get(i);
cont.highlight();
playAudioScene("DEMO2",i,true);
waitForSecs(0.3f);
cont.lowlight();
}
waitForSecs(0.3f);
}
}
public void demo3a() throws Exception
{
loadPointer(POINTER_LEFT);
moveScenePointer(OB_Maths.locationForRect(0.5f,0.8f,this.bounds()),-20,0.5f,"DEMO",0,0.3f);
moveScenePointer(OB_Maths.locationForRect(0.3f,0.8f,this.bounds()),-30,0.5f,"DEMO",1,0.3f);
for(int i=0;i<5;i++)
{
OBGroup cont = (OBGroup)sceneObjs.get(i);
movePointerToPoint(OB_Maths.locationForRect(0.55f,1.05f,cont.frame()) ,-30+(i*4),0.5f,true);
cont.highlight();
playAudioScene("DEMO2",i,true);
waitForSecs(0.3f);
cont.lowlight();
}
OBGroup targetBox = numbers.get(4);
movePointerToPoint(OB_Maths.locationForRect(0.55f,1.05f,targetBox.frame()) ,-20,0.5f,true);
movePointerToPoint(OB_Maths.locationForRect(0.55f,0.7f,targetBox.frame()) ,-20,0.2f,true);
targetBox.objectDict.get("box").setBackgroundColor(hilitecolour);
playAudio("correct");
waitAudio();
movePointerToPoint(OB_Maths.locationForRect(0.55f,1.05f,targetBox.frame()) ,-20,0.2f,true);
moveScenePointer(OB_Maths.locationForRect(0.5f,0.8f,this.bounds()),-15,0.5f,"DEMO3",0,0.5f);
thePointer.hide();
waitForSecs(0.3f);
nextScene();
}
}
|
tharakamd/integration-studio | components/studio-platform/plugins/org.wso2.integrationstudio.webui.core/src/org/wso2/integrationstudio/webui/core/composite/WebComposite.java | <reponame>tharakamd/integration-studio<filename>components/studio-platform/plugins/org.wso2.integrationstudio.webui.core/src/org/wso2/integrationstudio/webui/core/composite/WebComposite.java
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wso2.integrationstudio.webui.core.composite;
import java.net.URL;
import org.eclipse.swt.SWT;
import org.eclipse.swt.browser.Browser;
import org.eclipse.swt.browser.ProgressEvent;
import org.eclipse.swt.browser.ProgressListener;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.wso2.integrationstudio.logging.core.IIntegrationStudioLog;
import org.wso2.integrationstudio.logging.core.Logger;
import org.wso2.integrationstudio.webui.core.WebUICorePlugin;
import org.wso2.integrationstudio.webui.core.composite.function.DisposeCompositeCallback;
import org.wso2.integrationstudio.webui.core.composite.function.ResizeCompositeCallback;
import org.wso2.integrationstudio.webui.core.exception.WebUIException;
import org.wso2.integrationstudio.webui.core.model.BrowserScript;
public abstract class WebComposite extends Composite {
protected Browser browser;
protected String appID;
protected String appContext;
protected URL appURL;
protected static IIntegrationStudioLog log = Logger
.getLog(WebUICorePlugin.PLUGIN_ID);
public WebComposite(String appID, Composite parent, int style)
throws WebUIException {
super(parent, style);
this.appID = appID;
setLayout(new FillLayout(SWT.HORIZONTAL));
init();
}
public WebComposite(String appID, String appContext, Composite parent,
int style) throws WebUIException {
super(parent, style);
this.appID = appID;
this.appContext = appContext;
setLayout(new FillLayout(SWT.HORIZONTAL));
init();
}
public WebComposite(URL appURL, Composite parent, int style)
throws WebUIException {
super(parent, style);
this.appURL = appURL;
setLayout(new FillLayout(SWT.HORIZONTAL));
init();
}
protected void onLoadComplete() {
}
protected abstract String getURL() throws WebUIException;
public void executeScript(BrowserScript script) throws WebUIException {
if (browser != null) {
boolean success = browser.execute(script.getScript());
if (!success) {
throw new WebUIException("Error executing Script:"
+ script.getScriptName()
+ " Browser returned execution failed status.");
}
} else {
throw new WebUIException("Error executing Script:"
+ script.getScriptName() + ". Browser instance not found.");
}
}
private void init() throws WebUIException {
browser = new Browser(this, SWT.NONE);
browser.setLayout(new FillLayout(SWT.HORIZONTAL));
browser.setUrl(getURL());
browser.addProgressListener(new ProgressListener() {
@Override
public void completed(ProgressEvent arg0) {
onLoadComplete();
}
@Override
public void changed(ProgressEvent arg0) {
// TODO Auto-generated method stub
}
});
browser.addListener(SWT.MenuDetect, new Listener() {
public void handleEvent(Event event) {
event.doit = false;
}
});
this.pack();
injectCallbacks();
}
private void injectCallbacks() {
new DisposeCompositeCallback(this);
new ResizeCompositeCallback(this);
}
public Browser getBrowser() {
return browser;
}
}
|
srini009/ascent | src/rover/rover.hpp | <filename>src/rover/rover.hpp
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// Copyright (c) Lawrence Livermore National Security, LLC and other Ascent
// Project developers. See top-level LICENSE AND COPYRIGHT files for dates and
// other details. No copyright assignment is required to contribute to Ascent.
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
#ifndef rover_h
#define rover_h
#include <image.hpp>
#include <rover_exports.h>
#include <rover_types.hpp>
#include <ray_generators/ray_generator.hpp>
// vtk-m includes
#include <vtkm_typedefs.hpp>
// std includes
#include <memory>
#include <conduit.hpp>
namespace rover {
class ROVER_API Rover
{
public:
Rover();
~Rover();
void set_mpi_comm_handle(int mpi_comm_id);
int get_mpi_comm_handle();
void finalize();
void add_data_set(vtkmDataSet &);
void set_render_settings(const RenderSettings render_settings);
void set_ray_generator(RayGenerator *);
void clear_data_sets();
void set_background(const std::vector<vtkm::Float32> &background);
void set_background(const std::vector<vtkm::Float64> &background);
void execute();
void about();
void save_png(const std::string &file_name);
void to_blueprint(conduit::Node &dataset);
void save_png(const std::string &file_name,
const float min_val,
const float max_val,
const bool log_scale);
void save_bov(const std::string &file_name);
void set_tracer_precision32();
void set_tracer_precision64();
void get_result(Image<vtkm::Float32> &image);
void get_result(Image<vtkm::Float64> &image);
private:
class InternalsType;
std::shared_ptr<InternalsType> m_internals;
};
}; // namespace rover
#endif
|
Hussam-Turjman/FLDServer | fldserver/base/time/time_to_iso8601.h | <reponame>Hussam-Turjman/FLDServer<gh_stars>1-10
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef BASE_TIME_TIME_TO_ISO8601_H_
#define BASE_TIME_TIME_TO_ISO8601_H_
#include "fldserver/fldserver_config.h"
#include <string>
namespace base
{
class Time;
CORE_EXPORT std::string
TimeToISO8601(const base::Time& t);
} // namespace base
#endif // BASE_TIME_TIME_TO_ISO8601_H_
|
kuo77122/serverless-survey-forms | web/portal/src/constants/DragTypes.js | /**
* @module DragTypes
* Drag constants
**/
// drag and drop Option
export const DRAG_OPTION = 'DRAG_OPTION';
// drag and drop Question
export const DRAG_QUESTION = 'DRAG_QUESTION';
// drag and drop Page
export const DRAG_PAGE = 'DRAG_PAGE';
|
ronaldomg/Valim_EFS_REDIS | src/static/hacervosmaisemprestados.js | <reponame>ronaldomg/Valim_EFS_REDIS
/**@preserve GeneXus Java 10_3_12-110051 on December 12, 2020 11:47:54.70
*/
gx.evt.autoSkip = false;
gx.define('hacervosmaisemprestados', false, function () {
this.ServerClass = "hacervosmaisemprestados" ;
this.PackageName = "" ;
this.setObjectType("web");
this.setOnAjaxSessionTimeout("Warn");
this.hasEnterEvent = true;
this.skipOnEnter = false;
this.addKeyListener("12", "'FECHAR'");
this.addKeyListener("5", "REFRESH");
this.addKeyListener("12", "CANCEL");
this.addKeyListener("1", "HELP");
this.SetStandaloneVars=function()
{
};
this.e11092_client=function()
{
this.executeServerEvent("'FECHAR'", false, null, false, false);
};
this.e13092_client=function()
{
this.executeServerEvent("ENTER", true, null, false, false);
};
this.e15092_client=function()
{
this.executeServerEvent("CANCEL", true, null, false, false);
};
this.GXValidFnc = [];
var GXValidFnc = this.GXValidFnc ;
this.GXCtrlIds=[2,5,8,11,13,16,18,20,28];
this.GXLastCtrlId =28;
GXValidFnc[2]={fld:"TABLE3",grid:0};
GXValidFnc[5]={fld:"TABLE5",grid:0};
GXValidFnc[8]={fld:"TABLE6",grid:0};
GXValidFnc[11]={fld:"TEXTBLOCK5", format:0,grid:0};
GXValidFnc[13]={fld:"TABLE8",grid:0};
GXValidFnc[16]={lvl:0,type:"date",len:10,dec:0,sign:false,ro:0,grid:0,gxgrid:null,fnc:null,isvalid:null,rgrid:[],fld:"vDATAINICIAL",gxz:"ZV13DataInicial",gxold:"OV13DataInicial",gxvar:"AV13DataInicial",dp:{f:0,st:false,wn:false,mf:false,pic:"99/99/9999",dec:0},ucs:[],op:[],ip:[],nacdep:[],ctrltype:"edit",v2v:function(Value){gx.O.AV13DataInicial=gx.fn.toDatetimeValue(Value)},v2z:function(Value){gx.O.ZV13DataInicial=gx.fn.toDatetimeValue(Value)},v2c:function(){gx.fn.setControlValue("vDATAINICIAL",gx.O.AV13DataInicial,0);if (typeof(this.dom_hdl) == 'function') this.dom_hdl.call(gx.O);},c2v:function(){gx.O.AV13DataInicial=gx.fn.toDatetimeValue(this.val())},val:function(){return gx.fn.getControlValue("vDATAINICIAL")},nac:gx.falseFn};
this.declareDomainHdlr( 16 , function() {
});
GXValidFnc[18]={fld:"TEXTBLOCK6", format:0,grid:0};
GXValidFnc[20]={lvl:0,type:"date",len:10,dec:0,sign:false,ro:0,grid:0,gxgrid:null,fnc:null,isvalid:null,rgrid:[],fld:"vDATAFINAL",gxz:"ZV14DataFinal",gxold:"OV14DataFinal",gxvar:"AV14DataFinal",dp:{f:0,st:false,wn:false,mf:false,pic:"99/99/9999",dec:0},ucs:[],op:[],ip:[],nacdep:[],ctrltype:"edit",v2v:function(Value){gx.O.AV14DataFinal=gx.fn.toDatetimeValue(Value)},v2z:function(Value){gx.O.ZV14DataFinal=gx.fn.toDatetimeValue(Value)},v2c:function(){gx.fn.setControlValue("vDATAFINAL",gx.O.AV14DataFinal,0);if (typeof(this.dom_hdl) == 'function') this.dom_hdl.call(gx.O);},c2v:function(){gx.O.AV14DataFinal=gx.fn.toDatetimeValue(this.val())},val:function(){return gx.fn.getControlValue("vDATAFINAL")},nac:gx.falseFn};
this.declareDomainHdlr( 20 , function() {
});
GXValidFnc[28]={fld:"JS", format:2,grid:0};
this.AV13DataInicial = gx.date.nullDate() ;
this.ZV13DataInicial = gx.date.nullDate() ;
this.OV13DataInicial = gx.date.nullDate() ;
this.AV14DataFinal = gx.date.nullDate() ;
this.ZV14DataFinal = gx.date.nullDate() ;
this.OV14DataFinal = gx.date.nullDate() ;
this.AV13DataInicial = gx.date.nullDate() ;
this.AV14DataFinal = gx.date.nullDate() ;
this.Events = {"e11092_client": ["'FECHAR'", true] ,"e13092_client": ["ENTER", true] ,"e15092_client": ["CANCEL", true]};
this.EvtParms["REFRESH"] = [[],[]];
this.EvtParms["'FECHAR'"] = [[],[]];
this.EvtParms["ENTER"] = [[{av:'AV13DataInicial',fld:'vDATAINICIAL'},{av:'AV14DataFinal',fld:'vDATAFINAL'},{av:'AV10Ordenacao',fld:'vORDENACAO'},{av:'AV40QtdPagGeradas',fld:'vQTDPAGGERADAS'},{av:'AV44Pgmdesc',fld:'vPGMDESC'}],[{av:'AV14DataFinal',fld:'vDATAFINAL'},{av:'AV13DataInicial',fld:'vDATAINICIAL'},{av:'AV11OrdenacaoDescricao',fld:'vORDENACAODESCRICAO'},{av:'AV16NomeRelativo',fld:'vNOMERELATIVO'},{av:'AV15NomeAbsoluto',fld:'vNOMEABSOLUTO'},{av:'AV40QtdPagGeradas',fld:'vQTDPAGGERADAS'}]];
this.EnterCtrl = ["BUTTON3"];
this.InitStandaloneVars( );
});
gx.setParentObj(new hacervosmaisemprestados());
|
ivanov/numpy | numpy/core/info.py | <reponame>ivanov/numpy
"""Defines a multi-dimensional array and useful procedures for Numerical computation.
Functions
- array - NumPy Array construction
- zeros - Return an array of all zeros
- empty - Return an unitialized array
- shape - Return shape of sequence or array
- rank - Return number of dimensions
- size - Return number of elements in entire array or a
certain dimension
- fromstring - Construct array from (byte) string
- take - Select sub-arrays using sequence of indices
- put - Set sub-arrays using sequence of 1-D indices
- putmask - Set portion of arrays using a mask
- reshape - Return array with new shape
- repeat - Repeat elements of array
- choose - Construct new array from indexed array tuple
- correlate - Correlate two 1-d arrays
- searchsorted - Search for element in 1-d array
- sum - Total sum over a specified dimension
- average - Average, possibly weighted, over axis or array.
- cumsum - Cumulative sum over a specified dimension
- product - Total product over a specified dimension
- cumproduct - Cumulative product over a specified dimension
- alltrue - Logical and over an entire axis
- sometrue - Logical or over an entire axis
- allclose - Tests if sequences are essentially equal
More Functions:
- arange - Return regularly spaced array
- asarray - Guarantee NumPy array
- convolve - Convolve two 1-d arrays
- swapaxes - Exchange axes
- concatenate - Join arrays together
- transpose - Permute axes
- sort - Sort elements of array
- argsort - Indices of sorted array
- argmax - Index of largest value
- argmin - Index of smallest value
- inner - Innerproduct of two arrays
- dot - Dot product (matrix multiplication)
- outer - Outerproduct of two arrays
- resize - Return array with arbitrary new shape
- indices - Tuple of indices
- fromfunction - Construct array from universal function
- diagonal - Return diagonal array
- trace - Trace of array
- dump - Dump array to file object (pickle)
- dumps - Return pickled string representing data
- load - Return array stored in file object
- loads - Return array from pickled string
- ravel - Return array as 1-D
- nonzero - Indices of nonzero elements for 1-D array
- shape - Shape of array
- where - Construct array from binary result
- compress - Elements of array where condition is true
- clip - Clip array between two values
- ones - Array of all ones
- identity - 2-D identity array (matrix)
(Universal) Math Functions
add logical_or exp
subtract logical_xor log
multiply logical_not log10
divide maximum sin
divide_safe minimum sinh
conjugate bitwise_and sqrt
power bitwise_or tan
absolute bitwise_xor tanh
negative invert ceil
greater left_shift fabs
greater_equal right_shift floor
less arccos arctan2
less_equal arcsin fmod
equal arctan hypot
not_equal cos around
logical_and cosh sign
arccosh arcsinh arctanh
"""
from __future__ import division, absolute_import
depends = ['testing']
global_symbols = ['*']
|
SmartDataProjects/ddm | lib/dataformat/fileop.py | <reponame>SmartDataProjects/ddm
class Operation(object):
"""
Defines the base class for a data operation (transfer or deletion).
"""
# slots need to be defined to allow for the object to be loaded more quickly
__slots__ = \
['rid', 'lfn', 'source', 'status', 'created', 'start', 'end', 'bid', 'size', 'ecode']
def __init__(self):
self.rid = 0
self.lfn = ""
self.source = ""
self.status = ""
self.created = ""
self.start = 0
self.end = 0
self.bid = 0
self.size = 0
self.ecode = 0
def __str__(self):
return " (id: %s) %s %d %s %d %d %s %d"%\
(self.rid,self.lfn,self.size,self.created,self.start,self.end,self.source,self.status)
def fill(self,rid,lfn,source,status,created,start,end,bid,size,ecode):
self.rid = rid
self.lfn = lfn
self.source = source
self.status = status
self.created = created
self.start = -1
if start is not None and type(start) is not int:
self.start = int(start.strftime("%s"))
self.end = -1
if end is not None and type(end) is not int:
self.end = int(end.strftime("%s"))
self.bid = bid
self.size = size
self.ecode = ecode
def from_row(self,row,sites):
if len(row) == 10:
self.fill(int(row[0]),row[1],sites.names[int(row[2])],int(row[3]),
row[4],row[5],row[6],
row[7],int(row[8]),int(row[9]))
else:
print " ERROR - row length (%d) not compatible: %s"%(len(row),row)
class Deletion(Operation):
"""
Defines the data operation deletion.
"""
__slots__ = []
def __init__(self):
Operation.__init__(self)
def __str__(self):
return Operation.__str__(self)
def fill(self,rid,lfn,source,status,created,start,end,bid,size,ecode):
Operation.fill(self,rid,lfn,source,status,created,start,end,bid,size,ecode)
def from_row(self,row,sites):
Operation.from_row(self,row,sites)
def show(self):
print self.__str__()
class Transfer(Operation):
__slots__ = [ 'target' ]
def __init__(self):
Operation.__init__(self)
self.target = ""
def __str__(self):
return Operation.__str__(self) + " to target: %s"%(self.target)
def fill(self,rid,lfn,source,target,status,created,start,end,bid,size,ecode):
Operation.fill(self,rid,lfn,source,status,created,start,end,bid,size,ecode)
self.target = target
def from_row(self,row,sites):
if len(row) == 11:
self.fill(int(row[0]),row[1],sites.names[int(row[2])],sites.names[int(row[3])],
int(row[4]),row[5],row[6],row[7],row[8],int(row[9]),int(row[10]))
else:
print " ERROR Transfer - row length (%d) not compatible: %s"%(len(row),row)
def show(self):
print self.__str__()
|
jaroslaw-wieczorek/Project_IP_Telephony_Python_Voip | JaroEliCall/gui/interaction_ui.py | <filename>JaroEliCall/gui/interaction_ui.py
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file '/home/afar/Dokumenty/Project_IP_Telephony_Python_Voip/JaroEliCall/gui/ui/interaction.ui'
#
# Created by: PyQt5 UI code generator 5.11.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_InteractionInterfaceDialog(object):
def setupUi(self, InteractionInterfaceDialog):
InteractionInterfaceDialog.setObjectName("InteractionInterfaceDialog")
InteractionInterfaceDialog.resize(417, 606)
self.verticalLayout = QtWidgets.QVBoxLayout(InteractionInterfaceDialog)
self.verticalLayout.setObjectName("verticalLayout")
spacerItem = QtWidgets.QSpacerItem(20, 20, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum)
self.verticalLayout.addItem(spacerItem)
self.horizontal_layout_1 = QtWidgets.QHBoxLayout()
self.horizontal_layout_1.setObjectName("horizontal_layout_1")
self.rich_text_user_call = QtWidgets.QLabel(InteractionInterfaceDialog)
font = QtGui.QFont()
font.setPointSize(15)
self.rich_text_user_call.setFont(font)
self.rich_text_user_call.setAlignment(QtCore.Qt.AlignCenter)
self.rich_text_user_call.setObjectName("rich_text_user_call")
self.horizontal_layout_1.addWidget(self.rich_text_user_call)
self.verticalLayout.addLayout(self.horizontal_layout_1)
spacerItem1 = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum)
self.verticalLayout.addItem(spacerItem1)
self.label_avatar = QtWidgets.QLabel(InteractionInterfaceDialog)
self.label_avatar.setMinimumSize(QtCore.QSize(150, 150))
self.label_avatar.setMaximumSize(QtCore.QSize(200, 200))
self.label_avatar.setAlignment(QtCore.Qt.AlignCenter)
self.label_avatar.setObjectName("label_avatar")
self.verticalLayout.addWidget(self.label_avatar, 0, QtCore.Qt.AlignHCenter)
spacerItem2 = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum)
self.verticalLayout.addItem(spacerItem2)
self.horizontal_layout_2 = QtWidgets.QHBoxLayout()
self.horizontal_layout_2.setObjectName("horizontal_layout_2")
spacerItem3 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
self.horizontal_layout_2.addItem(spacerItem3)
self.label_reject = QtWidgets.QLabel(InteractionInterfaceDialog)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.label_reject.sizePolicy().hasHeightForWidth())
self.label_reject.setSizePolicy(sizePolicy)
self.label_reject.setMinimumSize(QtCore.QSize(120, 120))
self.label_reject.setMaximumSize(QtCore.QSize(120, 120))
self.label_reject.setText("")
self.label_reject.setPixmap(QtGui.QPixmap(":/icon/low-signal-indicator.png"))
self.label_reject.setScaledContents(True)
self.label_reject.setAlignment(QtCore.Qt.AlignCenter)
self.label_reject.setObjectName("label_reject")
self.horizontal_layout_2.addWidget(self.label_reject)
spacerItem4 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
self.horizontal_layout_2.addItem(spacerItem4)
self.label_accept = QtWidgets.QLabel(InteractionInterfaceDialog)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.label_accept.sizePolicy().hasHeightForWidth())
self.label_accept.setSizePolicy(sizePolicy)
self.label_accept.setMinimumSize(QtCore.QSize(120, 120))
self.label_accept.setMaximumSize(QtCore.QSize(120, 120))
self.label_accept.setText("")
self.label_accept.setPixmap(QtGui.QPixmap(":/icon/add-button.png"))
self.label_accept.setScaledContents(True)
self.label_accept.setAlignment(QtCore.Qt.AlignCenter)
self.label_accept.setObjectName("label_accept")
self.horizontal_layout_2.addWidget(self.label_accept)
spacerItem5 = QtWidgets.QSpacerItem(38, 18, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
self.horizontal_layout_2.addItem(spacerItem5)
self.verticalLayout.addLayout(self.horizontal_layout_2)
spacerItem6 = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum)
self.verticalLayout.addItem(spacerItem6)
self.horizontal_layout_33 = QtWidgets.QHBoxLayout()
self.horizontal_layout_33.setSpacing(2)
self.horizontal_layout_33.setObjectName("horizontal_layout_33")
spacerItem7 = QtWidgets.QSpacerItem(20, 20, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum)
self.horizontal_layout_33.addItem(spacerItem7)
self.push_button_accept = QtWidgets.QPushButton(InteractionInterfaceDialog)
self.push_button_accept.setMinimumSize(QtCore.QSize(100, 70))
self.push_button_accept.setObjectName("push_button_accept")
self.horizontal_layout_33.addWidget(self.push_button_accept)
spacerItem8 = QtWidgets.QSpacerItem(20, 20, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum)
self.horizontal_layout_33.addItem(spacerItem8)
self.push_button_reject = QtWidgets.QPushButton(InteractionInterfaceDialog)
self.push_button_reject.setMinimumSize(QtCore.QSize(100, 70))
self.push_button_reject.setObjectName("push_button_reject")
self.horizontal_layout_33.addWidget(self.push_button_reject)
spacerItem9 = QtWidgets.QSpacerItem(20, 20, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum)
self.horizontal_layout_33.addItem(spacerItem9)
self.verticalLayout.addLayout(self.horizontal_layout_33)
spacerItem10 = QtWidgets.QSpacerItem(20, 20, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum)
self.verticalLayout.addItem(spacerItem10)
self.retranslateUi(InteractionInterfaceDialog)
QtCore.QMetaObject.connectSlotsByName(InteractionInterfaceDialog)
InteractionInterfaceDialog.setTabOrder(self.push_button_accept, self.push_button_reject)
def retranslateUi(self, InteractionInterfaceDialog):
_translate = QtCore.QCoreApplication.translate
InteractionInterfaceDialog.setWindowTitle(_translate("InteractionInterfaceDialog", "JaroEliCall - Rozmowa"))
self.rich_text_user_call.setText(_translate("InteractionInterfaceDialog", "<html><head/><body><p><span style=\" font-size:18pt; font-weight:600;\">Tomek dzwoni</span></p></body></html>"))
self.label_avatar.setText(_translate("InteractionInterfaceDialog", "Avatar"))
self.push_button_accept.setText(_translate("InteractionInterfaceDialog", "Odbierz"))
self.push_button_reject.setText(_translate("InteractionInterfaceDialog", "Odrzuć"))
|
mulanbay-face/mulanbay-face-server | mulanbay-api/src/main/java/cn/mulanbay/face/api/web/bean/response/chart/ChartPieSerieDetailData.java | package cn.mulanbay.face.api.web.bean.response.chart;
/**
* 饼图的数据明细
*
* @author fenghong
* @create 2017-07-10 21:44
*/
public class ChartPieSerieDetailData {
private String name;
private Object value;
public ChartPieSerieDetailData() {
}
public ChartPieSerieDetailData(String name, Object value) {
this.name = name;
this.value = value;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Object getValue() {
return value;
}
public void setValue(Object value) {
this.value = value;
}
}
|
zefciu/ralph_pricing | src/ralph_pricing/plugins/openstack.py | <reponame>zefciu/ralph_pricing<filename>src/ralph_pricing/plugins/openstack.py
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import datetime
import collections
import logging
from django.conf import settings
from ralph.util import plugin
from ralph_pricing.models import UsageType, Venture, DailyUsage
from ralph_pricing.openstack import OpenStack
logger = logging.getLogger(__name__)
def set_usages(venture_symbol, data, date):
try:
venture = Venture.objects.get(symbol=venture_symbol)
except Venture.DoesNotExist:
logger.error('Venture: %s does not exist' % venture_symbol)
return
def set_usage(name, key, venture, multiplier):
if key not in data:
return
usage_type, created = UsageType.objects.get_or_create(name=name)
usage, created = DailyUsage.objects.get_or_create(
date=date,
type=usage_type,
pricing_venture=venture,
)
usage.value = data[key] / multiplier
usage.save()
if venture:
set_usage(
'OpenStack 10000 Memory GiB Hours',
'total_memory_mb_usage',
venture,
1024,
)
set_usage(
'OpenStack 10000 CPU Hours',
'total_vcpus_usage',
venture,
1,
)
set_usage(
'OpenStack 10000 Disk GiB Hours',
'total_local_gb_usage',
venture,
1,
)
set_usage(
'OpenStack 10000 Volume GiB Hours',
'total_volume_gb_usage',
venture,
1,
)
set_usage(
'OpenStack 10000 Images GiB Hours',
'total_images_gb_usage',
venture,
1,
)
@plugin.register(chain='pricing', requires=['ventures'])
def openstack(**kwargs):
"""Updates OpenStack usage per Venture"""
if settings.OPENSTACK_URL is None:
return False, 'Not configured.', kwargs
tenants = collections.defaultdict(lambda: collections.defaultdict(dict))
date = kwargs['today']
end = date
start = end - datetime.timedelta(days=1)
ventures = {}
for region in getattr(settings, 'OPENSTACK_REGIONS', ['']):
stack = OpenStack(
settings.OPENSTACK_URL,
settings.OPENSTACK_USER,
settings.OPENSTACK_PASS,
region=region,
)
ventures.update(stack.get_ventures())
for data in stack.simple_tenant_usage(start, end):
tenants[data['tenant_id']][region].update(data)
for url, query in getattr(settings, 'OPENSTACK_EXTRA_QUERIES', []):
for data in stack.query(
query,
url=url,
start=start.strftime('%Y-%m-%dT%H:%M:%S'),
end=end.strftime('%Y-%m-%dT%H:%M:%S'),
):
tenants[data['tenant_id']][url].update(data)
for tenant_id, regions in tenants.iteritems():
for region, data in regions.iteritems():
venture_symbol = ventures.get(data['tenant_id'])
if venture_symbol:
set_usages(venture_symbol, data, date)
return True, 'Openstack usages were saved', kwargs
|
sarbull/components | packages/webcall-mobilon.js | {
"name": "webcall-mobilon.js",
"url": "https://github.com/antirek/webcall-mobilon.js.git"
}
|
wilebeast/FireFox-OS | B2G/gecko/intl/uconv/ucvcn/nsUCvCnCID.h | /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#ifndef nsUCvCnCID_h___
#define nsUCvCnCID_h___
#include "nsISupports.h"
// Class ID for our GB2312ToUnicode charset converter// {379C2774-EC77-11d2-8AAC-00600811A836}
#define NS_GB2312TOUNICODE_CID \
{ 0x379c2774, 0xec77, 0x11d2, {0x8a, 0xac, 0x0, 0x60, 0x8, 0x11, 0xa8, 0x36}}
// Class ID for our ISO2022CNToUnicode charset converter
// {BA615199-1DFA-11d3-B3BF-00805F8A6670}
#define NS_ISO2022CNTOUNICODE_CID \
{ 0xba615199, 0x1dfa, 0x11d3, {0xb3, 0xbf, 0x0, 0x80, 0x5f, 0x8a, 0x66, 0x70}}
// Class ID for our HZToUnicode charset converter
// {BA61519A-1DFA-11d3-B3BF-00805F8A6670}
#define NS_HZTOUNICODE_CID \
{ 0xba61519a, 0x1dfa, 0x11d3, {0xb3, 0xbf, 0x0, 0x80, 0x5f, 0x8a, 0x66, 0x70}}
// Class ID for our GBKToUnicode charset converter
// {BA61519E-1DFA-11d3-B3BF-00805F8A6670}
#define NS_GBKTOUNICODE_CID \
{ 0xba61519e, 0x1dfa, 0x11d3, {0xb3, 0xbf, 0x0, 0x80, 0x5f, 0x8a, 0x66, 0x70}}
// Class ID for our UnicodeToGB2312 charset converter
// {379C2777-EC77-11d2-8AAC-00600811A836}
#define NS_UNICODETOGB2312_CID \
{ 0x379c2777, 0xec77, 0x11d2, {0x8a, 0xac, 0x0, 0x60, 0x8, 0x11, 0xa8, 0x36}}
// Class ID for our UnicodeToGBK charset converter
// {BA61519B-1DFA-11d3-B3BF-00805F8A6670}
#define NS_UNICODETOGBK_CID \
{ 0xba61519b, 0x1dfa, 0x11d3, {0xb3, 0xbf, 0x0, 0x80, 0x5f, 0x8a, 0x66, 0x70}}
// Class ID for our UnicodeToISO2022CN charset converter
// {BA61519C-1DFA-11d3-B3BF-00805F8A6670}
#define NS_UNICODETOISO2022CN_CID \
{ 0xba61519c, 0x1dfa, 0x11d3, {0xb3, 0xbf, 0x0, 0x80, 0x5f, 0x8a, 0x66, 0x70}}
// Class ID for our UnicodeToHZ charset converter
// {BA61519D-1DFA-11d3-B3BF-00805F8A6670}
#define NS_UNICODETOHZ_CID \
{ 0xba61519d, 0x1dfa, 0x11d3, {0xb3, 0xbf, 0x0, 0x80, 0x5f, 0x8a, 0x66, 0x70}}
// Class ID for our UnicodeToGB18030 charset converter
// {A59DA932-4091-11d5-A145-005004832142}
#define NS_UNICODETOGB18030_CID \
{ 0xa59da932, 0x4091, 0x11d5, { 0xa1, 0x45, 0x0, 0x50, 0x4, 0x83, 0x21, 0x42 } }
// Class ID for our GBKToUnicode charset converter
// {A59DA935-4091-11d5-A145-005004832142}
#define NS_GB18030TOUNICODE_CID \
{ 0xa59da935, 0x4091, 0x11d5, { 0xa1, 0x45, 0x0, 0x50, 0x4, 0x83, 0x21, 0x42 } }
#endif /* nsUCvCnCID_h___ */
|
huangyunbin/sofa-ark | sofa-ark-parent/core/common/src/main/java/com/alipay/sofa/ark/common/thread/CommonThreadPool.java | <filename>sofa-ark-parent/core/common/src/main/java/com/alipay/sofa/ark/common/thread/CommonThreadPool.java<gh_stars>100-1000
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alipay.sofa.ark.common.thread;
import com.alipay.sofa.ark.common.util.ThreadPoolUtils;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* Execute tasks triggered by ark container and ark plugin.
*
* @author qilong.zql
* @since 0.4.0
*/
public class CommonThreadPool {
/**
* Core size of thread pool
*
* @see ThreadPoolExecutor#corePoolSize
*/
private int corePoolSize = 10;
/**
* Maximum size of thread pool
*
* @see ThreadPoolExecutor#corePoolSize
*/
private int maximumPoolSize = 100;
/**
* @see ThreadPoolExecutor#keepAliveTime
*/
private int keepAliveTime = 300000;
/**
* @see ThreadPoolExecutor#getQueue
*/
private int queueSize = 0;
/**
* @see ThreadPoolExecutor#threadFactory#threadPoolName
*/
private String threadPoolName = "CommonProcessor";
/**
* @see ThreadPoolExecutor#threadFactory#isDaemon
*/
private boolean isDaemon = false;
/**
* @see ThreadPoolExecutor#allowCoreThreadTimeOut
*/
private boolean allowCoreThreadTimeOut = false;
/**
* @see ThreadPoolExecutor#prestartAllCoreThreads
*/
private boolean prestartAllCoreThreads = false;
/**
* ThreadPoolExecutor
*/
transient volatile ThreadPoolExecutor executor;
private void init() {
executor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime,
TimeUnit.MILLISECONDS, ThreadPoolUtils.buildQueue(queueSize), new NamedThreadFactory(
threadPoolName, isDaemon));
if (allowCoreThreadTimeOut) {
executor.allowCoreThreadTimeOut(true);
}
if (prestartAllCoreThreads) {
executor.prestartAllCoreThreads();
}
}
public int getCorePoolSize() {
return corePoolSize;
}
public CommonThreadPool setCorePoolSize(int corePoolSize) {
this.corePoolSize = corePoolSize;
return this;
}
public int getMaximumPoolSize() {
return maximumPoolSize;
}
public CommonThreadPool setMaximumPoolSize(int maximumPoolSize) {
this.maximumPoolSize = maximumPoolSize;
return this;
}
public int getKeepAliveTime() {
return keepAliveTime;
}
public CommonThreadPool setKeepAliveTime(int keepAliveTime) {
this.keepAliveTime = keepAliveTime;
return this;
}
public int getQueueSize() {
return queueSize;
}
public CommonThreadPool setQueueSize(int queueSize) {
this.queueSize = queueSize;
return this;
}
public String getThreadPoolName() {
return threadPoolName;
}
public CommonThreadPool setThreadPoolName(String threadPoolName) {
this.threadPoolName = threadPoolName;
return this;
}
public boolean isDaemon() {
return isDaemon;
}
public CommonThreadPool setDaemon(boolean daemon) {
isDaemon = daemon;
return this;
}
public boolean isAllowCoreThreadTimeOut() {
return allowCoreThreadTimeOut;
}
public CommonThreadPool setAllowCoreThreadTimeOut(boolean allowCoreThreadTimeOut) {
this.allowCoreThreadTimeOut = allowCoreThreadTimeOut;
return this;
}
public boolean isPrestartAllCoreThreads() {
return prestartAllCoreThreads;
}
public CommonThreadPool setPrestartAllCoreThreads(boolean prestartAllCoreThreads) {
this.prestartAllCoreThreads = prestartAllCoreThreads;
return this;
}
/**
* Gets executor
*
* @return the executor
*/
public ThreadPoolExecutor getExecutor() {
if (executor == null) {
synchronized (this) {
if (executor == null) {
init();
}
}
}
return executor;
}
} |
coderZsq/coderZsq.practice.server | study-notes/j2ee-collection/architecture/07-设计模式/src/main/java/com/sq/dp/designpattern/visitor/Project.java | <gh_stars>1-10
package com.sq.dp.designpattern.visitor;
import java.util.ArrayList;
import java.util.List;
public class Project {
private List<Employee> emps = new ArrayList<>();
public void add(Employee emp) {
emps.add(emp);
}
public void remove(Employee emp) {
emps.remove(emp);
}
public void accept(Visitor visitor) {
System.out.println("管理员: " + visitor.getName() + " 开始检查各成员项目状态");
for (Employee emp : emps) {
emp.accept(visitor);
}
}
}
|
kleister/kleister-go | kleister/pack/permit_pack_team_responses.go | // Code generated by go-swagger; DO NOT EDIT.
package pack
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"fmt"
"io"
"github.com/go-openapi/runtime"
strfmt "github.com/go-openapi/strfmt"
models "github.com/kleister/kleister-go/models"
)
// PermitPackTeamReader is a Reader for the PermitPackTeam structure.
type PermitPackTeamReader struct {
formats strfmt.Registry
}
// ReadResponse reads a server response into the received o.
func (o *PermitPackTeamReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {
switch response.Code() {
case 200:
result := NewPermitPackTeamOK()
if err := result.readResponse(response, consumer, o.formats); err != nil {
return nil, err
}
return result, nil
case 403:
result := NewPermitPackTeamForbidden()
if err := result.readResponse(response, consumer, o.formats); err != nil {
return nil, err
}
return nil, result
case 412:
result := NewPermitPackTeamPreconditionFailed()
if err := result.readResponse(response, consumer, o.formats); err != nil {
return nil, err
}
return nil, result
case 422:
result := NewPermitPackTeamUnprocessableEntity()
if err := result.readResponse(response, consumer, o.formats); err != nil {
return nil, err
}
return nil, result
default:
result := NewPermitPackTeamDefault(response.Code())
if err := result.readResponse(response, consumer, o.formats); err != nil {
return nil, err
}
if response.Code()/100 == 2 {
return result, nil
}
return nil, result
}
}
// NewPermitPackTeamOK creates a PermitPackTeamOK with default headers values
func NewPermitPackTeamOK() *PermitPackTeamOK {
return &PermitPackTeamOK{}
}
/*PermitPackTeamOK handles this case with default header values.
Plain success message
*/
type PermitPackTeamOK struct {
Payload *models.GeneralError
}
func (o *PermitPackTeamOK) Error() string {
return fmt.Sprintf("[PUT /packs/{pack_id}/teams][%d] permitPackTeamOK %+v", 200, o.Payload)
}
func (o *PermitPackTeamOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {
o.Payload = new(models.GeneralError)
// response payload
if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF {
return err
}
return nil
}
// NewPermitPackTeamForbidden creates a PermitPackTeamForbidden with default headers values
func NewPermitPackTeamForbidden() *PermitPackTeamForbidden {
return &PermitPackTeamForbidden{}
}
/*PermitPackTeamForbidden handles this case with default header values.
User is not authorized
*/
type PermitPackTeamForbidden struct {
Payload *models.GeneralError
}
func (o *PermitPackTeamForbidden) Error() string {
return fmt.Sprintf("[PUT /packs/{pack_id}/teams][%d] permitPackTeamForbidden %+v", 403, o.Payload)
}
func (o *PermitPackTeamForbidden) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {
o.Payload = new(models.GeneralError)
// response payload
if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF {
return err
}
return nil
}
// NewPermitPackTeamPreconditionFailed creates a PermitPackTeamPreconditionFailed with default headers values
func NewPermitPackTeamPreconditionFailed() *PermitPackTeamPreconditionFailed {
return &PermitPackTeamPreconditionFailed{}
}
/*PermitPackTeamPreconditionFailed handles this case with default header values.
Failed to parse request body
*/
type PermitPackTeamPreconditionFailed struct {
Payload *models.GeneralError
}
func (o *PermitPackTeamPreconditionFailed) Error() string {
return fmt.Sprintf("[PUT /packs/{pack_id}/teams][%d] permitPackTeamPreconditionFailed %+v", 412, o.Payload)
}
func (o *PermitPackTeamPreconditionFailed) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {
o.Payload = new(models.GeneralError)
// response payload
if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF {
return err
}
return nil
}
// NewPermitPackTeamUnprocessableEntity creates a PermitPackTeamUnprocessableEntity with default headers values
func NewPermitPackTeamUnprocessableEntity() *PermitPackTeamUnprocessableEntity {
return &PermitPackTeamUnprocessableEntity{}
}
/*PermitPackTeamUnprocessableEntity handles this case with default header values.
Team is not assigned
*/
type PermitPackTeamUnprocessableEntity struct {
Payload *models.GeneralError
}
func (o *PermitPackTeamUnprocessableEntity) Error() string {
return fmt.Sprintf("[PUT /packs/{pack_id}/teams][%d] permitPackTeamUnprocessableEntity %+v", 422, o.Payload)
}
func (o *PermitPackTeamUnprocessableEntity) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {
o.Payload = new(models.GeneralError)
// response payload
if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF {
return err
}
return nil
}
// NewPermitPackTeamDefault creates a PermitPackTeamDefault with default headers values
func NewPermitPackTeamDefault(code int) *PermitPackTeamDefault {
return &PermitPackTeamDefault{
_statusCode: code,
}
}
/*PermitPackTeamDefault handles this case with default header values.
Some error unrelated to the handler
*/
type PermitPackTeamDefault struct {
_statusCode int
Payload *models.GeneralError
}
// Code gets the status code for the permit pack team default response
func (o *PermitPackTeamDefault) Code() int {
return o._statusCode
}
func (o *PermitPackTeamDefault) Error() string {
return fmt.Sprintf("[PUT /packs/{pack_id}/teams][%d] PermitPackTeam default %+v", o._statusCode, o.Payload)
}
func (o *PermitPackTeamDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {
o.Payload = new(models.GeneralError)
// response payload
if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF {
return err
}
return nil
}
|
oirad21/react_oirad | node_modules/@fortawesome/pro-light-svg-icons/faCameraRetro.js | 'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var prefix = 'fal';
var iconName = 'camera-retro';
var width = 512;
var height = 512;
var ligatures = [];
var unicode = 'f083';
var svgPathData = 'M32 58V38c0-3.3 2.7-6 6-6h116c3.3 0 6 2.7 6 6v20c0 3.3-2.7 6-6 6H38c-3.3 0-6-2.7-6-6zm344 230c0-66.2-53.8-120-120-120s-120 53.8-120 120 53.8 120 120 120 120-53.8 120-120zm-32 0c0 48.5-39.5 88-88 88s-88-39.5-88-88 39.5-88 88-88 88 39.5 88 88zm-120 0c0-17.6 14.4-32 32-32 8.8 0 16-7.2 16-16s-7.2-16-16-16c-35.3 0-64 28.7-64 64 0 8.8 7.2 16 16 16s16-7.2 16-16zM512 80v352c0 26.5-21.5 48-48 48H48c-26.5 0-48-21.5-48-48V144c0-26.5 21.5-48 48-48h136l33.6-44.8C226.7 39.1 240.9 32 256 32h208c26.5 0 48 21.5 48 48zM224 96h240c5.6 0 11 1 16 2.7V80c0-8.8-7.2-16-16-16H256c-5 0-9.8 2.4-12.8 6.4L224 96zm256 48c0-8.8-7.2-16-16-16H48c-8.8 0-16 7.2-16 16v288c0 8.8 7.2 16 16 16h416c8.8 0 16-7.2 16-16V144z';
exports.definition = {
prefix: prefix,
iconName: iconName,
icon: [
width,
height,
ligatures,
unicode,
svgPathData
]};
exports.faCameraRetro = exports.definition;
exports.prefix = prefix;
exports.iconName = iconName;
exports.width = width;
exports.height = height;
exports.ligatures = ligatures;
exports.unicode = unicode;
exports.svgPathData = svgPathData; |
Fyee/Ihome-react-native | js/pages/data/component/health/index.js | <filename>js/pages/data/component/health/index.js
import React, { Fragment } from 'react'
import { View, Text, Image, StyleSheet, } from 'react-native'
import { VictoryLine } from 'victory-native'
import LinearGradient from 'react-native-linear-gradient'
import { ListItem } from 'react-native-elements'
import { AnimatedCircularProgress } from 'react-native-circular-progress'
export default Health = (props) => {
return (
<View style={{ flex: 1 }}>
<LinearGradient style={{ backgroundColor: '#3D4957' }} colors={['#3B2860', '#211342', '#160B2E']} >
<VictoryLine
style={{
data: { stroke: "#FF3D68" },
parent: { border: "1px solid #ccc" },
}}
animate={{
duration: 2000,
onLoad: { duration: 1000 }
}}
data={[
{ x: -2, y: 12 },
{ x: -1, y: 12 },
{ x: 0, y: 12 },
{ x: 1, y: 12 },
{ x: 2, y: 8 },
{ x: 3, y: 19 },
{ x: 4, y: 11 },
{ x: 6, y: 16 },
{ x: 7, y: 9 },
{ x: 8, y: 17 },
{ x: 9, y: 9 },
{ x: 10, y: 19 },
{ x: 11, y: 12 },
{ x: 12, y: 12 },
{ x: 13, y: 12 },
]}
height={230}
/>
<ListItem
leftAvatar={
<Image style={{ width: 20, height: 20, tintColor: '#fff' }} source={require('../../../../assets/icon/pages/data/heart.png')} />
}
title='心率'
titleStyle={
{
color: '#fff', fontSize: 14, marginLeft: -10
}
}
containerStyle={{
height: 60, backgroundColor: 'transparent'
}}
rightElement={
<View style={{ flexDirection: "row", alignItems: 'center' }}>
<Text style={{ color: '#fff', fontSize: 32, fontWeight: '200', marginRight: 5 }}>82</Text>
<Text style={{ color: '#fff', fontSize: 10, }}>BPM</Text>
</View>
}
/>
</LinearGradient>
<View
style={{ flexDirection: 'row', flex: 1 }}
>
<LinearGradient style={styles.footerContainer} colors={['#331E5F', '#231540']}>
<AnimatedCircularProgress
rotation={0}
size={100}
width={5}
fill={40}
tintColor="#1DDAFA"
backgroundColor="#2A3D73" >
{
(fill) => (
<View style={{ alignItems: 'center', justifyContent: 'center' }}>
<Text style={styles.value}>
7005
</Text>
<Text style={styles.unit}>
Step
</Text>
</View>
)
}
</AnimatedCircularProgress>
<View style={styles.wrapper}>
<Image source={require('../../../../assets/icon/pages/data/working.png')} style={styles.icon} />
<Text style={styles.title}>运动</Text>
</View>
</LinearGradient>
<LinearGradient style={styles.footerContainer} colors={['#331E5C', '#2A174C']}>
<AnimatedCircularProgress
rotation={0}
size={100}
width={5}
fill={70}
tintColor="#A2FD58"
backgroundColor="#616f39" >
{
(fill) => (
<View style={{ alignItems: 'center', justifyContent: 'center' }}>
<Text style={styles.value}>
605
</Text>
<Text style={styles.unit}>
Calorie
</Text>
</View>
)
}
</AnimatedCircularProgress>
<View style={styles.wrapper}>
<Image source={require('../../../../assets/icon/pages/data/food.png')} style={styles.icon} />
<Text style={styles.title}>食物</Text>
</View>
</LinearGradient>
<LinearGradient style={styles.footerContainer} colors={['#331E5F', '#231540']}>
<AnimatedCircularProgress
rotation={0}
size={100}
width={5}
fill={80}
tintColor="#FF5035"
backgroundColor="#5D2144" >
{
(fill) => (
<View style={{ alignItems: 'center', justifyContent: 'center' }}>
<Text style={styles.value}>
7:30
</Text>
<Text style={styles.unit}>
Hour
</Text>
</View>
)
}
</AnimatedCircularProgress>
<View style={styles.wrapper}>
<Image source={require('../../../../assets/icon/pages/data/sleep.png')} style={styles.icon} />
<Text style={styles.title}>睡眠</Text>
</View>
</LinearGradient>
</View>
</View>
)
}
const styles = StyleSheet.create({
unit: {
fontSize: 10,
color: '#fff'
},
value: {
fontSize: 24,
color: '#fff',
marginTop: 10
},
footerContainer: {
flex: 1,
alignItems: "center",
justifyContent: 'center'
},
wrapper: {
alignItems: 'center',
justifyContent: 'center',
flexDirection: "row",
marginTop: 20
},
icon: {
width: 20,
height: 20,
tintColor: "#fff"
},
title: {
fontSize: 14,
color: '#fff',
fontWeight: '400',
marginLeft: 10
}
}) |
nfell2009/skript-parser | src/main/java/io/github/syst3ms/skriptparser/Skript.java | <gh_stars>0
package io.github.syst3ms.skriptparser;
import io.github.syst3ms.skriptparser.event.ScriptLoadContext;
import io.github.syst3ms.skriptparser.lang.Statement;
import io.github.syst3ms.skriptparser.lang.Trigger;
import io.github.syst3ms.skriptparser.registration.SkriptAddon;
import java.util.ArrayList;
import java.util.List;
public class Skript extends SkriptAddon {
private final String[] mainArgs;
private List<Trigger> mainTriggers = new ArrayList<>();
public Skript(String[] mainArgs) {
this.mainArgs = mainArgs;
}
@Override
public void handleTrigger(Trigger trigger) {
mainTriggers.add(trigger);
}
@Override
public void finishedLoading() {
for (Trigger trigger : mainTriggers) {
Statement.runAll(trigger, new ScriptLoadContext(mainArgs));
}
}
}
|
rodb70/RDMnet | include/rdmnet/cpp/controller.h | <filename>include/rdmnet/cpp/controller.h
/******************************************************************************
* Copyright 2020 ETC Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************
* This file is a part of RDMnet. For more information, go to:
* https://github.com/ETCLabs/RDMnet
*****************************************************************************/
/// @file rdmnet/cpp/controller.h
/// @brief C++ wrapper for the RDMnet Controller API
#ifndef RDMNET_CPP_CONTROLLER_H_
#define RDMNET_CPP_CONTROLLER_H_
#include <algorithm>
#include <string>
#include <vector>
#include "etcpal/common.h"
#include "etcpal/cpp/error.h"
#include "etcpal/cpp/inet.h"
#include "etcpal/cpp/uuid.h"
#include "etcpal/cpp/log.h"
#include "rdm/cpp/uid.h"
#include "rdm/cpp/message.h"
#include "rdmnet/cpp/client.h"
#include "rdmnet/cpp/common.h"
#include "rdmnet/cpp/message.h"
#include "rdmnet/controller.h"
namespace rdmnet
{
/// @defgroup rdmnet_controller_cpp Controller API
/// @ingroup rdmnet_cpp_api
/// @brief Implementation of RDMnet controller functionality; see @ref using_controller.
///
/// RDMnet controllers are clients which originate RDM commands and receive responses. Controllers
/// can participate in multiple scopes; the default scope string "default" must be configured as a
/// default setting. This API provides classes tailored to the usage concerns of an RDMnet
/// controller.
///
/// See @ref using_controller for details of how to use this API.
/// @ingroup rdmnet_controller_cpp
/// @brief An instance of RDMnet controller functionality.
///
/// See @ref using_controller for details of how to use this API.
class Controller
{
public:
/// A handle type used by the RDMnet library to identify controller instances.
using Handle = rdmnet_controller_t;
/// An invalid Handle value.
static constexpr Handle kInvalidHandle = RDMNET_CONTROLLER_INVALID;
/// @ingroup rdmnet_controller_cpp
/// @brief A base class for a class that receives notification callbacks from a controller.
///
/// See @ref using_controller for details of how to use this API.
class NotifyHandler
{
public:
virtual ~NotifyHandler() = default;
/// @brief A controller has successfully connected to a broker.
/// @param controller_handle Handle to controller instance which has connected.
/// @param scope_handle Handle to the scope on which the controller has connected.
/// @param info More information about the successful connection.
virtual void HandleConnectedToBroker(Handle controller_handle,
ScopeHandle scope_handle,
const ClientConnectedInfo& info) = 0;
/// @brief A connection attempt failed between a controller and a broker.
/// @param controller_handle Handle to controller instance which has failed to connect.
/// @param scope_handle Handle to the scope on which the connection failed.
/// @param info More information about the failed connection.
virtual void HandleBrokerConnectFailed(Handle controller_handle,
ScopeHandle scope_handle,
const ClientConnectFailedInfo& info) = 0;
/// @brief A controller which was previously connected to a broker has disconnected.
/// @param controller_handle Handle to controller instance which has disconnected.
/// @param scope_handle Handle to the scope on which the disconnect occurred.
/// @param info More information about the disconnect event.
virtual void HandleDisconnectedFromBroker(Handle controller_handle,
ScopeHandle scope_handle,
const ClientDisconnectedInfo& info) = 0;
/// @brief A client list update has been received from a broker.
/// @param controller_handle Handle to controller instance which has received the client list update.
/// @param scope_handle Handle to the scope on which the client list update was received.
/// @param list_action The way the updates in client_list should be applied to the controller's
/// cached list.
/// @param list The list of updates.
virtual void HandleClientListUpdate(Handle controller_handle,
ScopeHandle scope_handle,
client_list_action_t list_action,
const RptClientList& list) = 0;
/// @brief An RDM response has been received.
/// @param controller_handle Handle to controller instance which has received the RDM response.
/// @param scope_handle Handle to the scope on which the RDM response was received.
/// @param resp The RDM response data.
virtual void HandleRdmResponse(Handle controller_handle, ScopeHandle scope_handle, const RdmResponse& resp) = 0;
/// @brief An RPT status message has been received in response to a previously-sent RDM command.
/// @param controller_handle Handle to controller instance which has received the RPT status message.
/// @param scope_handle Handle to the scope on which the RPT status message was received.
/// @param status The RPT status data.
virtual void HandleRptStatus(Handle controller_handle, ScopeHandle scope_handle, const RptStatus& status) = 0;
/// @brief A set of previously-requested mappings of dynamic UIDs to responder IDs has been received.
///
/// This callback does not need to be implemented if the controller implementation never intends
/// to request responder IDs.
///
/// @param controller_handle Handle to controller instance which has received the responder IDs.
/// @param scope_handle Handle to the scope on which the responder IDs were received.
/// @param list The list of dynamic UID to responder ID mappings.
virtual void HandleResponderIdsReceived(Handle controller_handle,
ScopeHandle scope_handle,
const DynamicUidAssignmentList& list)
{
ETCPAL_UNUSED_ARG(controller_handle);
ETCPAL_UNUSED_ARG(scope_handle);
ETCPAL_UNUSED_ARG(list);
}
};
/// @ingroup rdmnet_controller_cpp
/// @brief A base class for a class that receives RDM commands addressed to a controller.
///
/// This is an optional portion of the controller API. See @ref using_controller for details.
class RdmCommandHandler
{
public:
/// @brief An RDM command has been received addressed to a controller.
/// @param controller_handle Handle to controller instance which has received the RDM command.
/// @param scope_handle Handle to the scope on which the RDM command was received.
/// @param cmd The RDM command data.
/// @return The action to take in response to this RDM command.
virtual RdmResponseAction HandleRdmCommand(Handle controller_handle,
ScopeHandle scope_handle,
const RdmCommand& cmd) = 0;
/// @brief An RDM command has been received over LLRP, addressed to a controller.
/// @param controller_handle Handle to controller instance which has received the RDM command.
/// @param cmd The RDM command data.
/// @return The action to take in response to this LLRP RDM command.
virtual RdmResponseAction HandleLlrpRdmCommand(Handle controller_handle, const llrp::RdmCommand& cmd)
{
ETCPAL_UNUSED_ARG(controller_handle);
ETCPAL_UNUSED_ARG(cmd);
return rdmnet::RdmResponseAction::SendNack(kRdmNRActionNotSupported);
}
};
/// @ingroup rdmnet_controller_cpp
/// @brief A set of configuration settings that a controller needs to initialize.
struct Settings
{
etcpal::Uuid cid; ///< The controller's Component Identifier (CID).
rdm::Uid uid; ///< The controller's RDM UID. For a dynamic UID, use rdm::Uid::DynamicUidRequest().
std::string search_domain; ///< (optional) The controller's search domain for discovering brokers.
/// (optional) Whether to create an LLRP target associated with this controller.
bool create_llrp_target{false};
/// (optional) A set of network interfaces to use for the LLRP target associated with this
/// controller. If empty, the set passed to rdmnet::Init() will be used, or all network
/// interfaces on the system if that was not provided.
std::vector<EtcPalMcastNetintId> llrp_netints;
/// Create an empty, invalid data structure by default.
Settings() = default;
Settings(const etcpal::Uuid& new_cid, const rdm::Uid& new_uid);
Settings(const etcpal::Uuid& new_cid, uint16_t manufacturer_id);
bool IsValid() const;
};
/// @ingroup rdmnet_controller_cpp
/// @brief A set of initial identifying RDM data to use for a controller.
struct RdmData
{
/// @brief A number representing the product model which implements the controller.
/// @details Should be unique per model for a given manufacturer.
uint16_t model_id{0};
/// @brief A number representing the version of the controller software.
/// @details Should be unique per version of a given controller's application.
uint32_t software_version_id{0};
/// @brief A number representing the product's primary function.
/// @details Valid values are defined in rdm/defs.h as E120_PRODUCT_CATEGORY_...
uint16_t product_category{E120_PRODUCT_CATEGORY_CONTROL_CONTROLLER};
std::string manufacturer_label; ///< The manufacturer name of the controller.
std::string device_model_description; ///< The name of the product model which implements the controller.
std::string software_version_label; ///< The software version of the controller as a string.
std::string device_label; ///< A user-settable name for this controller instance.
bool device_label_settable{false}; ///< Whether the library should allow device_label to be changed remotely.
/// Create an empty, invalid structure by default - must be filled in before passing to Controller::Startup().
RdmData() = default;
RdmData(uint16_t new_model_id,
uint32_t new_software_version_id,
const char* new_manufacturer_label,
const char* new_device_model_description,
const char* new_software_version_label,
const char* new_device_label);
RdmData(uint16_t new_model_id,
uint32_t new_software_version_id,
const std::string& new_manufacturer_label,
const std::string& new_device_model_description,
const std::string& new_software_version_label,
const std::string& new_device_label);
bool IsValid() const;
};
Controller() = default;
Controller(const Controller& other) = delete;
Controller& operator=(const Controller& other) = delete;
Controller(Controller&& other) = default; ///< Move a controller instance.
Controller& operator=(Controller&& other) = default; ///< Move a controller instance.
etcpal::Error Startup(NotifyHandler& notify_handler, const Settings& settings, const RdmData& rdm_data);
etcpal::Error Startup(NotifyHandler& notify_handler,
const Settings& settings,
RdmCommandHandler& rdm_handler,
uint8_t* rdm_response_buf = nullptr);
void Shutdown(rdmnet_disconnect_reason_t disconnect_reason = kRdmnetDisconnectShutdown);
etcpal::Expected<ScopeHandle> AddScope(const char* id,
const etcpal::SockAddr& static_broker_addr = etcpal::SockAddr{});
etcpal::Expected<ScopeHandle> AddScope(const std::string& id,
const etcpal::SockAddr& static_broker_addr = etcpal::SockAddr{});
etcpal::Expected<ScopeHandle> AddScope(const Scope& scope_config);
etcpal::Expected<ScopeHandle> AddDefaultScope(const etcpal::SockAddr& static_broker_addr = etcpal::SockAddr{});
etcpal::Error RemoveScope(ScopeHandle scope_handle, rdmnet_disconnect_reason_t disconnect_reason);
etcpal::Error ChangeScope(ScopeHandle scope_handle,
const char* new_scope_id_str,
rdmnet_disconnect_reason_t disconnect_reason,
const etcpal::SockAddr& new_static_broker_addr = etcpal::SockAddr{});
etcpal::Error ChangeScope(ScopeHandle scope_handle,
const Scope& new_scope_config,
rdmnet_disconnect_reason_t disconnect_reason);
etcpal::Error ChangeSearchDomain(const char* new_search_domain, rdmnet_disconnect_reason_t disconnect_reason);
etcpal::Expected<uint32_t> SendRdmCommand(ScopeHandle scope_handle,
const DestinationAddr& destination,
rdmnet_command_class_t command_class,
uint16_t param_id,
const uint8_t* data = nullptr,
uint8_t data_len = 0);
etcpal::Expected<uint32_t> SendGetCommand(ScopeHandle scope_handle,
const DestinationAddr& destination,
uint16_t param_id,
const uint8_t* data = nullptr,
uint8_t data_len = 0);
etcpal::Expected<uint32_t> SendSetCommand(ScopeHandle scope_handle,
const DestinationAddr& destination,
uint16_t param_id,
const uint8_t* data = nullptr,
uint8_t data_len = 0);
etcpal::Error RequestClientList(ScopeHandle scope_handle);
etcpal::Error RequestResponderIds(ScopeHandle scope_handle, const rdm::Uid* uids, size_t num_uids);
etcpal::Error RequestResponderIds(ScopeHandle scope_handle, const std::vector<rdm::Uid>& uids);
etcpal::Error SendRdmAck(ScopeHandle scope_handle,
const SavedRdmCommand& received_cmd,
const uint8_t* response_data = nullptr,
size_t response_data_len = 0);
etcpal::Error SendRdmNack(ScopeHandle scope_handle,
const SavedRdmCommand& received_cmd,
rdm_nack_reason_t nack_reason);
etcpal::Error SendRdmNack(ScopeHandle scope_handle, const SavedRdmCommand& received_cmd, uint16_t raw_nack_reason);
etcpal::Error SendRdmUpdate(ScopeHandle scope_handle,
uint16_t param_id,
const uint8_t* data = nullptr,
size_t data_len = 0);
etcpal::Error SendLlrpAck(const llrp::SavedRdmCommand& received_cmd,
const uint8_t* response_data = nullptr,
uint8_t response_data_len = 0);
etcpal::Error SendLlrpNack(const llrp::SavedRdmCommand& received_cmd, rdm_nack_reason_t nack_reason);
etcpal::Error SendLlrpNack(const llrp::SavedRdmCommand& received_cmd, uint16_t raw_nack_reason);
Handle handle() const;
const RdmData& rdm_data() const;
Controller::NotifyHandler* notify_handler() const;
Controller::RdmCommandHandler* rdm_command_handler() const;
etcpal::Expected<Scope> scope(ScopeHandle scope_handle) const;
void UpdateRdmData(const RdmData& new_data);
private:
Handle handle_{kInvalidHandle};
RdmData my_rdm_data_;
RdmCommandHandler* rdm_cmd_handler_{nullptr};
NotifyHandler* notify_{nullptr};
};
/// @cond controller_c_callbacks
/// Callbacks from underlying controller library to be forwarded
namespace internal
{
extern "C" inline void ControllerLibCbConnected(rdmnet_controller_t controller_handle,
rdmnet_client_scope_t scope_handle,
const RdmnetClientConnectedInfo* info,
void* context)
{
if (info && context)
{
static_cast<Controller::NotifyHandler*>(context)->HandleConnectedToBroker(controller_handle, scope_handle, *info);
}
}
extern "C" inline void ControllerLibCbConnectFailed(rdmnet_controller_t controller_handle,
rdmnet_client_scope_t scope_handle,
const RdmnetClientConnectFailedInfo* info,
void* context)
{
if (info && context)
{
static_cast<Controller::NotifyHandler*>(context)->HandleBrokerConnectFailed(controller_handle, scope_handle, *info);
}
}
extern "C" inline void ControllerLibCbDisconnected(rdmnet_controller_t controller_handle,
rdmnet_client_scope_t scope_handle,
const RdmnetClientDisconnectedInfo* info,
void* context)
{
if (info && context)
{
static_cast<Controller::NotifyHandler*>(context)->HandleDisconnectedFromBroker(controller_handle, scope_handle,
*info);
}
}
extern "C" inline void ControllerLibCbClientListUpdate(rdmnet_controller_t controller_handle,
rdmnet_client_scope_t scope_handle,
client_list_action_t list_action,
const RdmnetRptClientList* list,
void* context)
{
if (list && context)
{
static_cast<Controller::NotifyHandler*>(context)->HandleClientListUpdate(controller_handle, scope_handle,
list_action, *list);
}
}
extern "C" inline void ControllerLibCbRdmResponseReceived(rdmnet_controller_t controller_handle,
rdmnet_client_scope_t scope_handle,
const RdmnetRdmResponse* resp,
void* context)
{
if (resp && context)
{
static_cast<Controller::NotifyHandler*>(context)->HandleRdmResponse(controller_handle, scope_handle, *resp);
}
}
extern "C" inline void ControllerLibCbStatusReceived(rdmnet_controller_t controller_handle,
rdmnet_client_scope_t scope_handle,
const RdmnetRptStatus* status,
void* context)
{
if (status && context)
{
static_cast<Controller::NotifyHandler*>(context)->HandleRptStatus(controller_handle, scope_handle, *status);
}
}
extern "C" inline void ControllerLibCbResponderIdsReceived(rdmnet_controller_t controller_handle,
rdmnet_client_scope_t scope_handle,
const RdmnetDynamicUidAssignmentList* list,
void* context)
{
if (list && context)
{
static_cast<Controller::NotifyHandler*>(context)->HandleResponderIdsReceived(controller_handle, scope_handle,
*list);
}
}
extern "C" inline void ControllerLibCbRdmCommandReceived(rdmnet_controller_t controller_handle,
rdmnet_client_scope_t scope_handle,
const RdmnetRdmCommand* cmd,
RdmnetSyncRdmResponse* response,
void* context)
{
if (cmd && context)
{
*response = static_cast<Controller::RdmCommandHandler*>(context)
->HandleRdmCommand(controller_handle, scope_handle, *cmd)
.get();
}
}
extern "C" inline void ControllerLibCbLlrpRdmCommandReceived(rdmnet_controller_t controller_handle,
const LlrpRdmCommand* cmd,
RdmnetSyncRdmResponse* response,
void* context)
{
if (cmd && context)
{
*response =
static_cast<Controller::RdmCommandHandler*>(context)->HandleLlrpRdmCommand(controller_handle, *cmd).get();
}
}
}; // namespace internal
/// @endcond
/// @brief Create a controller Settings instance by passing the required members explicitly.
/// @details This version takes the fully-formed RDM UID that the controller will use.
inline Controller::Settings::Settings(const etcpal::Uuid& new_cid, const rdm::Uid& new_uid) : cid(new_cid), uid(new_uid)
{
}
/// @brief Create a controller Settings instance by passing the required members explicitly.
///
/// This version just takes the controller's ESTA manufacturer ID and uses it to generate
/// an RDMnet dynamic UID request.
inline Controller::Settings::Settings(const etcpal::Uuid& new_cid, uint16_t manufacturer_id)
: cid(new_cid), uid(rdm::Uid::DynamicUidRequest(manufacturer_id))
{
}
/// Determine whether a controller Settings instance contains valid data for RDMnet operation.
inline bool Controller::Settings::IsValid() const
{
return (!cid.IsNull() && (uid.IsStatic() || uid.IsDynamicUidRequest()));
}
/// Create a controller RdmData instance by passing all members which do not have a default value.
inline Controller::RdmData::RdmData(uint16_t new_model_id,
uint32_t new_software_version_id,
const char* new_manufacturer_label,
const char* new_device_model_description,
const char* new_software_version_label,
const char* new_device_label)
: model_id(new_model_id)
, software_version_id(new_software_version_id)
, manufacturer_label(new_manufacturer_label)
, device_model_description(new_device_model_description)
, software_version_label(new_software_version_label)
, device_label(new_device_label)
{
}
/// Create a controller RdmData instance by passing all members which do not have a default value.
inline Controller::RdmData::RdmData(uint16_t new_model_id,
uint32_t new_software_version_id,
const std::string& new_manufacturer_label,
const std::string& new_device_model_description,
const std::string& new_software_version_label,
const std::string& new_device_label)
: model_id(new_model_id)
, software_version_id(new_software_version_id)
, manufacturer_label(new_manufacturer_label)
, device_model_description(new_device_model_description)
, software_version_label(new_software_version_label)
, device_label(new_device_label)
{
}
/// Whether this data is valid (all string members are non-empty).
inline bool Controller::RdmData::IsValid() const
{
return ((!manufacturer_label.empty()) && (!device_model_description.empty()) && (!software_version_label.empty()) &&
(!device_label.empty()));
}
/// @brief Allocate resources and start up this controller with the given configuration.
///
/// This overload provides a set of RDM data to the library to use for the controller's RDM
/// responder. RDM commands addressed to the controller will be handled internally by the library.
///
/// @param notify_handler A class instance to handle callback notifications from this controller.
/// @param settings Configuration settings used by this controller.
/// @param rdm_data Data to identify this controller to other controllers on the network.
/// @return etcpal::Error::Ok(): Controller started successfully.
/// @return #kEtcPalErrInvalid: Invalid argument.
/// @return Errors forwarded from rdmnet_controller_create().
inline etcpal::Error Controller::Startup(NotifyHandler& notify_handler,
const Settings& settings,
const RdmData& rdm_data)
{
if (!settings.IsValid() || !rdm_data.IsValid())
return kEtcPalErrInvalid;
notify_ = ¬ify_handler;
my_rdm_data_ = rdm_data;
// clang-format off
RdmnetControllerConfig config = {
settings.cid.get(), // CID
{ // Callback shims
internal::ControllerLibCbConnected,
internal::ControllerLibCbConnectFailed,
internal::ControllerLibCbDisconnected,
internal::ControllerLibCbClientListUpdate,
internal::ControllerLibCbRdmResponseReceived,
internal::ControllerLibCbStatusReceived,
internal::ControllerLibCbResponderIdsReceived,
¬ify_handler // Context
},
{ // RDM command callback shims
nullptr, nullptr, nullptr, nullptr
},
{ // RDM data
rdm_data.model_id,
rdm_data.software_version_id,
rdm_data.manufacturer_label.c_str(),
rdm_data.device_model_description.c_str(),
rdm_data.software_version_label.c_str(),
rdm_data.device_label.c_str(),
rdm_data.product_category,
rdm_data.device_label_settable
},
settings.uid.get(), // UID
settings.search_domain.c_str(), // Search domain
settings.create_llrp_target, // Create LLRP target
nullptr,
0
};
// clang-format on
// LLRP network interfaces
if (!settings.llrp_netints.empty())
{
config.llrp_netints = settings.llrp_netints.data();
config.num_llrp_netints = settings.llrp_netints.size();
}
return rdmnet_controller_create(&config, &handle_);
}
/// @brief Allocate resources and start up this controller with the given configuration.
///
/// This overload provides a notification handler to respond to RDM commands addressed to the
/// controller. You must implement a core set of RDM commands - see @ref using_controller for more
/// information.
///
/// @param notify_handler A class instance to handle callback notifications from this controller.
/// @param settings Configuration settings used by this controller.
/// @param rdm_handler A class instance to handle RDM commands addressed to this controller.
/// @param rdm_response_buf (optional) A data buffer used to respond synchronously to RDM commands.
/// See @ref handling_rdm_commands for more information.
/// @return etcpal::Error::Ok(): Controller started successfully.
/// @return #kEtcPalErrInvalid: Invalid argument.
/// @return Errors forwarded from rdmnet_controller_create().
inline etcpal::Error Controller::Startup(NotifyHandler& notify_handler,
const Settings& settings,
RdmCommandHandler& rdm_handler,
uint8_t* rdm_response_buf)
{
if (!settings.IsValid())
return kEtcPalErrInvalid;
notify_ = ¬ify_handler;
rdm_cmd_handler_ = &rdm_handler;
// clang-format off
RdmnetControllerConfig config = {
settings.cid.get(), // CID
{ // Callback shims
internal::ControllerLibCbConnected,
internal::ControllerLibCbConnectFailed,
internal::ControllerLibCbDisconnected,
internal::ControllerLibCbClientListUpdate,
internal::ControllerLibCbRdmResponseReceived,
internal::ControllerLibCbStatusReceived,
internal::ControllerLibCbResponderIdsReceived,
¬ify_handler // Context
},
{ // RDM command callback shims
internal::ControllerLibCbRdmCommandReceived,
internal::ControllerLibCbLlrpRdmCommandReceived,
rdm_response_buf,
&rdm_handler // Context
},
RDMNET_CONTROLLER_RDM_DATA_DEFAULT_INIT, // RDM data
settings.uid.get(), // UID
settings.search_domain.c_str(), // Search domain
settings.create_llrp_target, // Create LLRP target
nullptr,
0
};
// clang-format on
// LLRP network interfaces
if (!settings.llrp_netints.empty())
{
config.llrp_netints = settings.llrp_netints.data();
config.num_llrp_netints = settings.llrp_netints.size();
}
return rdmnet_controller_create(&config, &handle_);
}
/// @brief Shut down this controller and deallocate resources.
///
/// Will disconnect all scopes to which this controller is currently connected, sending the
/// disconnect reason provided in the disconnect_reason parameter.
///
/// @param disconnect_reason Reason code for disconnecting from each scope.
inline void Controller::Shutdown(rdmnet_disconnect_reason_t disconnect_reason)
{
rdmnet_controller_destroy(handle_, disconnect_reason);
handle_ = kInvalidHandle;
}
/// @brief Add a new scope to this controller instance.
///
/// The library will attempt to discover and connect to a broker for the scope (or just connect if
/// a static broker address is given); the status of these attempts will be communicated via the
/// associated Controller::NotifyHandler.
///
/// @param id The scope ID string.
/// @param static_broker_addr [optional] A static IP address and port at which to connect to the
/// broker for this scope.
/// @return On success, a handle to the new scope, to be used with subsequent API calls.
/// @return On failure, error codes from rdmnet_controller_add_scope().
inline etcpal::Expected<ScopeHandle> Controller::AddScope(const char* id, const etcpal::SockAddr& static_broker_addr)
{
RdmnetScopeConfig scope_config = {id, static_broker_addr.get()};
rdmnet_client_scope_t scope_handle;
auto result = rdmnet_controller_add_scope(handle_, &scope_config, &scope_handle);
if (result == kEtcPalErrOk)
return scope_handle;
else
return result;
}
/// @brief Add a new scope to this controller instance.
///
/// The library will attempt to discover and connect to a broker for the scope (or just connect if
/// a static broker address is given); the status of these attempts will be communicated via the
/// associated Controller::NotifyHandler.
///
/// @param id The scope ID string.
/// @param static_broker_addr [optional] A static IP address and port at which to connect to the
/// broker for this scope.
/// @return On success, a handle to the new scope, to be used with subsequent API calls.
/// @return On failure, error codes from rdmnet_controller_add_scope().
inline etcpal::Expected<ScopeHandle> Controller::AddScope(const std::string& id,
const etcpal::SockAddr& static_broker_addr)
{
return AddScope(id.c_str(), static_broker_addr);
}
/// @brief Add a new scope to this controller instance.
///
/// The library will attempt to discover and connect to a broker for the scope (or just connect if
/// a static broker address is given); the status of these attempts will be communicated via the
/// associated Controller::NotifyHandler.
///
/// @param scope_config Configuration information for the new scope.
/// @return On success, a handle to the new scope, to be used with subsequent API calls.
/// @return On failure, error codes from rdmnet_controller_add_scope().
inline etcpal::Expected<ScopeHandle> Controller::AddScope(const Scope& scope_config)
{
return AddScope(scope_config.id_string().c_str(), scope_config.static_broker_addr());
}
/// @brief Shortcut to add the default RDMnet scope to a controller instance.
///
/// The library will attempt to discover and connect to a broker for the default scope (or just
/// connect if a static broker address is given); the status of these attempts will be communicated
/// via the associated Controller::NotifyHandler.
///
/// @param static_broker_addr [optional] A static broker address to configure for the default scope.
/// @return On success, a handle to the new scope, to be used with subsequent API calls.
/// @return On failure, error codes from rdmnet_controller_add_scope().
inline etcpal::Expected<ScopeHandle> Controller::AddDefaultScope(const etcpal::SockAddr& static_broker_addr)
{
return AddScope(E133_DEFAULT_SCOPE, static_broker_addr);
}
/// @brief Remove a previously-added scope from this controller instance.
///
/// After this call completes, scope_handle will no longer be valid.
///
/// @param scope_handle Handle to scope to remove.
/// @param disconnect_reason RDMnet protocol disconnect reason to send to the connected broker.
/// @return etcpal::Error::Ok(): Scope removed successfully.
/// @return Error codes from from rdmnet_controller_remove_scope().
inline etcpal::Error Controller::RemoveScope(ScopeHandle scope_handle, rdmnet_disconnect_reason_t disconnect_reason)
{
return rdmnet_controller_remove_scope(handle_, scope_handle, disconnect_reason);
}
/// @brief Change the configuration of a scope on a controller.
///
/// Will disconnect from any connected brokers and attempt connection again using the new
/// configuration given.
///
/// @param scope_handle Handle to the scope for which to change the configuration.
/// @param new_scope_id_str ID string to use for the new scope.
/// @param disconnect_reason RDMnet protocol disconnect reason to send to the connected broker.
/// @param new_static_broker_addr [optional] New static IP address and port at which to connect to
/// the broker for this scope.
/// @return etcpal::Error::Ok(): Scope changed successfully.
/// @return #kEtcPalErrInvalid: Invalid argument.
/// @return #kEtcPalErrNotInit: Module not initialized.
/// @return #kEtcPalErrNotFound: scope_handle is not associated with a valid scope instance.
/// @return #kEtcPalErrSys: An internal library or system call error occurred.
inline etcpal::Error Controller::ChangeScope(ScopeHandle scope_handle,
const char* new_scope_id_str,
rdmnet_disconnect_reason_t disconnect_reason,
const etcpal::SockAddr& new_static_broker_addr)
{
RdmnetScopeConfig new_scope_config = {new_scope_id_str, new_static_broker_addr.get()};
return rdmnet_controller_change_scope(handle_, scope_handle, &new_scope_config, disconnect_reason);
}
/// @brief Change the configuration of a scope on a controller.
///
/// Will disconnect from any connected brokers and attempt connection again using the new
/// configuration given.
///
/// @param scope_handle Handle to the scope for which to change the configuration.
/// @param new_scope_config New configuration parameters for the scope.
/// @param disconnect_reason RDMnet protocol disconnect reason to send to the connected broker.
/// @return etcpal::Error::Ok(): Scope changed successfully.
/// @return #kEtcPalErrInvalid: Invalid argument.
/// @return #kEtcPalErrNotInit: Module not initialized.
/// @return #kEtcPalErrNotFound: scope_handle is not associated with a valid scope instance.
/// @return #kEtcPalErrSys: An internal library or system call error occurred.
inline etcpal::Error Controller::ChangeScope(ScopeHandle scope_handle,
const Scope& new_scope_config,
rdmnet_disconnect_reason_t disconnect_reason)
{
return ChangeScope(scope_handle, new_scope_config.id_string().c_str(), disconnect_reason,
new_scope_config.static_broker_addr());
}
/// @brief Change the controller's DNS search domain.
///
/// Non-default search domains are considered advanced usage. Any added scopes which do not have a
/// static broker configuration will be disconnected, sending the disconnect reason provided in the
/// disconnect_reason parameter. Then discovery will be re-attempted on the new search domain.
///
/// @param new_search_domain New search domain to use for discovery.
/// @param disconnect_reason Disconnect reason to send to any connected brokers.
/// @return etcpal::Error::Ok(): Search domain changed successfully.
/// @return #kEtcPalErrInvalid: Invalid argument.
/// @return #kEtcPalErrNotInit: Module not initialized.
/// @return #kEtcPalErrSys: An internal library or system call error occurred.
inline etcpal::Error Controller::ChangeSearchDomain(const char* new_search_domain,
rdmnet_disconnect_reason_t disconnect_reason)
{
return rdmnet_controller_change_search_domain(handle_, new_search_domain, disconnect_reason);
}
/// @brief Send an RDM command from a controller on a scope.
///
/// The response will be delivered via the Controller::NotifyHandler::HandleRdmResponse() callback.
///
/// @param scope_handle Handle to the scope on which to send the RDM command.
/// @param destination The destination addressing information for the RDM command.
/// @param command_class The command's RDM command class (GET or SET).
/// @param param_id The command's RDM parameter ID.
/// @param data [optional] The command's RDM parameter data, if it has any.
/// @param data_len [optional] The length of the RDM parameter data (or 0 if data is nullptr).
/// @return On success, a sequence number which can be used to match the command with a response.
/// @return On failure, error codes from rdmnet_controller_send_rdm_command().
inline etcpal::Expected<uint32_t> Controller::SendRdmCommand(ScopeHandle scope_handle,
const DestinationAddr& destination,
rdmnet_command_class_t command_class,
uint16_t param_id,
const uint8_t* data,
uint8_t data_len)
{
uint32_t seq_num;
etcpal_error_t res = rdmnet_controller_send_rdm_command(handle_, scope_handle, &destination.get(), command_class,
param_id, data, data_len, &seq_num);
if (res == kEtcPalErrOk)
return seq_num;
else
return res;
}
/// @brief Send an RDM GET command from a controller on a scope.
///
/// The response will be delivered via the Controller::NotifyHandler::HandleRdmResponse() callback.
///
/// @param scope_handle Handle to the scope on which to send the RDM command.
/// @param destination The destination addressing information for the RDM command.
/// @param param_id The command's RDM parameter ID.
/// @param data [optional] The command's RDM parameter data, if it has any.
/// @param data_len [optional] The length of the RDM parameter data (or 0 if data is nullptr).
/// @return On success, a sequence number which can be used to match the command with a response.
/// @return On failure, error codes from rdmnet_controller_send_get_command().
inline etcpal::Expected<uint32_t> Controller::SendGetCommand(ScopeHandle scope_handle,
const DestinationAddr& destination,
uint16_t param_id,
const uint8_t* data,
uint8_t data_len)
{
uint32_t seq_num;
etcpal_error_t res =
rdmnet_controller_send_get_command(handle_, scope_handle, &destination.get(), param_id, data, data_len, &seq_num);
if (res == kEtcPalErrOk)
return seq_num;
else
return res;
}
/// @brief Send an RDM SET command from a controller on a scope.
///
/// The response will be delivered via the Controller::NotifyHandler::HandleRdmResponse() callback.
///
/// @param scope_handle Handle to the scope on which to send the RDM command.
/// @param destination The destination addressing information for the RDM command.
/// @param param_id The command's RDM parameter ID.
/// @param data [optional] The command's RDM parameter data, if it has any.
/// @param data_len [optional] The length of the RDM parameter data (or 0 if data is nullptr).
/// @return On success, a sequence number which can be used to match the command with a response.
/// @return On failure, error codes from rdmnet_controller_send_set_command().
inline etcpal::Expected<uint32_t> Controller::SendSetCommand(ScopeHandle scope_handle,
const DestinationAddr& destination,
uint16_t param_id,
const uint8_t* data,
uint8_t data_len)
{
uint32_t seq_num;
etcpal_error_t res =
rdmnet_controller_send_set_command(handle_, scope_handle, &destination.get(), param_id, data, data_len, &seq_num);
if (res == kEtcPalErrOk)
return seq_num;
else
return res;
}
/// @brief Request a client list from a broker.
///
/// The response will be delivered via the Controller::NotifyHandler::HandleClientListUpdate()
/// callback.
///
/// @param scope_handle Handle to the scope on which to request the client list.
/// @return etcpal::Error::Ok(): Request sent successfully.
/// @return Error codes from rdmnet_controller_request_client_list().
inline etcpal::Error Controller::RequestClientList(ScopeHandle scope_handle)
{
return rdmnet_controller_request_client_list(handle_, scope_handle);
}
/// @brief Request mappings from dynamic UIDs to Responder IDs (RIDs).
///
/// See @ref devices_and_gateways for more information. A RID is a UUID that permanently identifies
/// a virtual RDMnet responder.
///
/// @param scope_handle Handle to the scope on which to request the responder IDs.
/// @param uids List of dynamic UIDs for which to request the corresponding responder ID.
/// @param num_uids Size of the uids array.
/// @return etcpal::Error::Ok(): Request sent successfully.
/// @return Error codes from rdmnet_controller_request_responder_ids().
inline etcpal::Error Controller::RequestResponderIds(ScopeHandle scope_handle, const rdm::Uid* uids, size_t num_uids)
{
if (num_uids == 0)
return kEtcPalErrInvalid;
std::vector<RdmUid> c_uids;
c_uids.reserve(num_uids);
std::transform(uids, uids + num_uids, std::back_inserter(c_uids), [](const rdm::Uid& uid) { return uid.get(); });
return rdmnet_controller_request_responder_ids(handle_, scope_handle, c_uids.data(), c_uids.size());
}
/// @brief Request mappings from dynamic UIDs to Responder IDs (RIDs).
///
/// See @ref devices_and_gateways for more information. A RID is a UUID that permanently identifies
/// a virtual RDMnet responder.
///
/// @param scope_handle Handle to the scope on which to request the responder IDs.
/// @param uids List of dynamic UIDs for which to request the corresponding responder ID.
/// @return etcpal::Error::Ok(): Request sent successfully.
/// @return Error codes from rdmnet_controller_request_responder_ids().
inline etcpal::Error Controller::RequestResponderIds(ScopeHandle scope_handle, const std::vector<rdm::Uid>& uids)
{
return RequestResponderIds(scope_handle, uids.data(), uids.size());
}
/// @brief Send an acknowledge (ACK) response to an RDM command received by a controller.
///
/// This function should only be used if a Controller::RdmCommandHandler was supplied when starting
/// this controller.
///
/// @param scope_handle Handle to the scope on which the corresponding command was received.
/// @param received_cmd The command to which this ACK is a response.
/// @param response_data [optional] The response's RDM parameter data, if it has any.
/// @param response_data_len [optional] The length of the RDM parameter data (or 0 if data is nullptr).
/// @return etcpal::Error::Ok(): ACK sent successfully.
/// @return Error codes from rdmnet_controller_send_rdm_ack().
inline etcpal::Error Controller::SendRdmAck(ScopeHandle scope_handle,
const SavedRdmCommand& received_cmd,
const uint8_t* response_data,
size_t response_data_len)
{
return rdmnet_controller_send_rdm_ack(handle_, scope_handle, &received_cmd.get(), response_data, response_data_len);
}
/// @brief Send a negative acknowledge (NACK) response to an RDM command received by a controller.
///
/// This function should only be used if a Controller::RdmCommandHandler was supplied when starting
/// this controller.
///
/// @param scope_handle Handle to the scope on which the corresponding command was received.
/// @param received_cmd The command to which this NACK is a response.
/// @param nack_reason The RDM NACK reason to send with the NACK response.
/// @return etcpal::Error::Ok(): NACK sent successfully.
/// @return Error codes from rdmnet_controller_send_rdm_nack().
inline etcpal::Error Controller::SendRdmNack(ScopeHandle scope_handle,
const SavedRdmCommand& received_cmd,
rdm_nack_reason_t nack_reason)
{
return rdmnet_controller_send_rdm_nack(handle_, scope_handle, &received_cmd.get(), nack_reason);
}
/// @brief Send a negative acknowledge (NACK) response to an RDM command received by a controller.
///
/// This function should only be used if a Controller::RdmCommandHandler was supplied when starting
/// this controller.
///
/// @param scope_handle Handle to the scope on which the corresponding command was received.
/// @param received_cmd The command to which this NACK is a response.
/// @param raw_nack_reason The NACK reason (either standard or manufacturer-specific) to send with
/// the NACK response.
/// @return etcpal::Error::Ok(): NACK sent successfully.
/// @return Error codes from rdmnet_controller_send_rdm_nack().
inline etcpal::Error Controller::SendRdmNack(ScopeHandle scope_handle,
const SavedRdmCommand& received_cmd,
uint16_t raw_nack_reason)
{
return rdmnet_controller_send_rdm_nack(handle_, scope_handle, &received_cmd.get(),
static_cast<rdm_nack_reason_t>(raw_nack_reason));
}
/// @brief Send an asynchronous RDM GET response to update the value of a local parameter.
///
/// This function should only be used if a Controller::RdmCommandHandler was supplied when starting
/// this controller.
///
/// @param scope_handle Handle to the scope on which to send the RDM update.
/// @param param_id The RDM parameter ID that has been updated.
/// @param data The updated parameter data, if any.
/// @param data_len The length of the parameter data, if any.
/// @return etcpal::Error::Ok(): RDM update sent successfully.
/// @return Error codes from rdmnet_controller_send_rdm_update().
inline etcpal::Error Controller::SendRdmUpdate(ScopeHandle scope_handle,
uint16_t param_id,
const uint8_t* data,
size_t data_len)
{
return rdmnet_controller_send_rdm_update(handle_, scope_handle, 0, param_id, data, data_len);
}
/// @brief Send an acknowledge (ACK) response to an LLRP RDM command received by a controller.
///
/// This function should only be used if a Controller::RdmCommandHandler was supplied when starting
/// this controller.
///
/// @param received_cmd The command to which this ACK is a response.
/// @param response_data [optional] The response's RDM parameter data, if it has any.
/// @param response_data_len [optional] The length of the RDM parameter data (or 0 if data is nullptr).
/// @return etcpal::Error::Ok(): LLRP ACK sent successfully.
/// @return Error codes from rdmnet_controller_send_llrp_ack().
inline etcpal::Error Controller::SendLlrpAck(const llrp::SavedRdmCommand& received_cmd,
const uint8_t* response_data,
uint8_t response_data_len)
{
return rdmnet_controller_send_llrp_ack(handle_, &received_cmd.get(), response_data, response_data_len);
}
/// @brief Send a negative acknowledge (NACK) response to an LLRP RDM command received by a controller.
///
/// This function should only be used if a Controller::RdmCommandHandler was supplied when starting
/// this controller.
///
/// @param received_cmd The command to which this NACK is a response.
/// @param nack_reason The RDM NACK reason to send with the NACK response.
/// @return etcpal::Error::Ok(): NACK sent successfully.
/// @return Error codes from rdmnet_controller_send_llrp_nack().
inline etcpal::Error Controller::SendLlrpNack(const llrp::SavedRdmCommand& received_cmd, rdm_nack_reason_t nack_reason)
{
return rdmnet_controller_send_llrp_nack(handle_, &received_cmd.get(), nack_reason);
}
/// @brief Send a negative acknowledge (NACK) response to an LLRP RDM command received by a controller.
///
/// This function should only be used if a Controller::RdmCommandHandler was supplied when starting
/// this controller.
///
/// @param received_cmd The command to which this NACK is a response.
/// @param raw_nack_reason The NACK reason (either standard or manufacturer-specific) to send with
/// the NACK response.
/// @return etcpal::Error::Ok(): NACK sent successfully.
/// @return Error codes from rdmnet_controller_send_llrp_nack().
inline etcpal::Error Controller::SendLlrpNack(const llrp::SavedRdmCommand& received_cmd, uint16_t raw_nack_reason)
{
return rdmnet_controller_send_llrp_nack(handle_, &received_cmd.get(),
static_cast<rdm_nack_reason_t>(raw_nack_reason));
}
/// @brief Retrieve the handle of a controller instance.
inline Controller::Handle Controller::handle() const
{
return handle_;
}
/// @brief Retrieve the RDM data that this controller was configured with on startup.
/// @return The data, or an invalid RdmData instance if it was not provided.
inline const Controller::RdmData& Controller::rdm_data() const
{
return my_rdm_data_;
}
/// @brief Retrieve the Controller::NotifyHandler reference that this controller was configured with.
inline Controller::NotifyHandler* Controller::notify_handler() const
{
return notify_;
}
/// @brief Retrieve the Controller::RdmCommandHandler reference that this controller was configured with.
/// @return A pointer to the handler, or nullptr if it was not provided.
inline Controller::RdmCommandHandler* Controller::rdm_command_handler() const
{
return rdm_cmd_handler_;
}
/// @brief Retrieve the scope configuration associated with a given scope handle.
/// @return The scope configuration on success.
/// @return #kEtcPalErrNotInit: Module not initialized.
/// @return #kEtcPalErrNotFound: Controller not started, or scope handle not found.
inline etcpal::Expected<Scope> Controller::scope(ScopeHandle scope_handle) const
{
std::string scope_id(E133_SCOPE_STRING_PADDED_LENGTH, 0);
EtcPalSockAddr static_broker_addr;
etcpal_error_t res = rdmnet_controller_get_scope(handle_, scope_handle, &scope_id[0], &static_broker_addr);
if (res == kEtcPalErrOk)
return Scope(scope_id, static_broker_addr);
else
return res;
}
/// @brief Update the data used to identify this controller to other controllers.
inline void Controller::UpdateRdmData(const RdmData& new_data)
{
// TODO implement
ETCPAL_UNUSED_ARG(new_data);
}
}; // namespace rdmnet
#endif // RDMNET_CPP_CONTROLLER_H_
|
SerayaEryn/nodejs-sensor | src/metrics/optDependencies.js | <reponame>SerayaEryn/nodejs-sensor
'use strict';
exports.payloadPrefix = 'optDependencies';
exports.currentPayload = {
gcstats: isAvailable('gcstats.js'),
v8Profiler: isAvailable('v8-profiler-node8'),
eventLoopStats: isAvailable('event-loop-stats')
};
exports.activate = function() {};
exports.deactivate = function() {};
function isAvailable(mod) {
try {
require(mod);
return true;
} catch (e) {
return false;
}
}
|
Grosskopf/openoffice | main/sfx2/source/dialog/filtergrouping.cxx | <gh_stars>100-1000
/**************************************************************
*
* 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.
*
*************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sfx2.hxx"
#include "filtergrouping.hxx"
#include <sfx2/fcontnr.hxx>
#include <sfx2/filedlghelper.hxx>
#include <sfx2/sfx.hrc>
#include <sfx2/docfac.hxx>
#include "sfx2/sfxresid.hxx"
#include <osl/thread.h>
#include <com/sun/star/ui/dialogs/XFilterGroupManager.hpp>
#include <com/sun/star/beans/StringPair.hpp>
#include <com/sun/star/uno/Sequence.hxx>
#include <unotools/confignode.hxx>
#include <comphelper/processfactory.hxx>
#include <comphelper/sequenceashashmap.hxx>
#include <tools/wldcrd.hxx>
#include <tools/diagnose_ex.h>
#include <list>
#include <vector>
#include <map>
#include <algorithm>
//........................................................................
namespace sfx2
{
//........................................................................
//#define DISABLE_GROUPING_AND_CLASSIFYING
// not using the functionallity herein, yet
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::ui::dialogs;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::beans;
using namespace ::utl;
//====================================================================
/**
Some general words about what's going on here ....
<p>In our file open dialog, usually we display every filter we know. That's how it was before: every filter
lead to an own line in the filter list box, e.g. "StarWriter 5.0 Dokument" or "Microsoft Word 97".</p>
<p>But then the PM came. And everything changed ....</p>
<p>A basic idea are groups: Why simply listing all the single filters? Couldn't we draw nice separators
between the filters which logically belong together? I.e. all the filters which open a document in StarWriter:
couldn't we separate them from all the filters which open the document in StarCalc?<br/>
So spoke the PM, and engineering obeyed.</p>
<p>So we have groups. They're just a visual aspect: All the filters of a group are presented together, separated
by a line from other groups.</p>
<p>Let's be honest: How the concrete implementation of the file picker service separates the different groups
is a matter of this implementation. We only do this grouping and suggest it to the FilePicker service ...</p>
<p>Now for the second concept:<br/>
Thinking about it (and that's what the PM did), both "StarWriter 5.0 Dokument" and "Microsoft Word 97"
describe a text document. It's a text. It's of no interest for the user that one of the texts was saved in
MS' format, and one in our own format.<br/>
So in a first step, we want to have a filter entry "Text documents". This would cover both above-mentioned
filters, as well as any other filters for documents which are texts.</p>
<p>Such an entry as "Text documents" is - within the scope of this file - called "class" or "filter class".</p>
<p>In the file-open-dialog, such a class looks like an ordinary filter: it's simply a name in the filter
listbox. Selecting means that all the files matching one of the "sub-filters" are displayed (in the example above,
this would be "*.sdw", "*.doc" and so on).</p>
<p>Now there are two types of filter classes: global ones and local ones. "Text documents" is a global class. As
well as "Spreadsheets". Or "Web pages".<br/>
Let's have a look at a local class: The filters "MS Word 95" and "MS WinWord 6.0" together form the class
"Microsoft Word 6.0 / 95" (don't ask for the reasons. At least not me. Ask the PM). There are a lot of such
local classes ...</p>
<p>The difference between global and local classes is as follows: Global classes are presented in an own group.
There is one dedicated group at the top of the list, containing all the global groups - no local groups and no
single filters.</p>
<p>Ehm - it was a lie. Not really at the top. Before this group, there is this single "All files" entry. It forms
it's own group. But this is uninteresting here.</p>
<p>Local classes must consist of filters which - without the classification - would all belong to the same group.
Then, they're combined to one entry (in the example above: "Microsoft Word 6.0 / 95"), and this entry is inserted
into the file picker filter list, instead of the single filters which form the class.</p>
<p>This is an interesting difference between local and global classes: Filters which are part of a global class
are listed in there own group, too. Filters in local classes aren't listed a second time - neither directly (as
the filter itself) nor indirectly (as part of another local group).</p>
<p>The only exception are filters which are part of a global class <em>and</em> a local class. This is allowed.
Being cotained in two local classes isn't.</p>
<p>So that's all what you need to know: Understand the concept of "filter classes" (a filter class combines
different filters and acts as if it's a filter itself) and the concept of groups (a group just describes a
logical correlation of filters and usually is represented to the user by drawing group separators in the filter
list).</p>
<p>If you got it, go try understanding this file :).</p>
*/
//====================================================================
typedef StringPair FilterDescriptor; // a single filter or a filter class (display name and filter mask)
typedef ::std::list< FilterDescriptor > FilterGroup; // a list of single filter entries
typedef ::std::list< FilterGroup > GroupedFilterList; // a list of all filters, already grouped
/// the logical name of a filter
typedef ::rtl::OUString FilterName;
// a struct which holds references from a logical filter name to a filter group entry
// used for quick lookup of classes (means class entries - entries representing a class)
// which a given filter may belong to
typedef ::std::map< ::rtl::OUString, FilterGroup::iterator > FilterGroupEntryReferrer;
/// a descriptor for a filter class (which in the final dialog is represented by one filter entry)
typedef struct _tagFilterClass
{
::rtl::OUString sDisplayName; // the display name
Sequence< FilterName > aSubFilters; // the (logical) names of the filter which belong to the class
} FilterClass;
typedef ::std::list< FilterClass > FilterClassList;
typedef ::std::map< ::rtl::OUString, FilterClassList::iterator > FilterClassReferrer;
typedef ::std::vector< ::rtl::OUString > StringArray;
// =======================================================================
// = reading of configuration data
// =======================================================================
//--------------------------------------------------------------------
void lcl_ReadFilterClass( const OConfigurationNode& _rClassesNode, const ::rtl::OUString& _rLogicalClassName,
FilterClass& /* [out] */ _rClass )
{
static const ::rtl::OUString sDisplaNameNodeName( RTL_CONSTASCII_USTRINGPARAM( "DisplayName" ) );
static const ::rtl::OUString sSubFiltersNodeName( RTL_CONSTASCII_USTRINGPARAM( "Filters" ) );
// the description node for the current class
OConfigurationNode aClassDesc = _rClassesNode.openNode( _rLogicalClassName );
// the values
aClassDesc.getNodeValue( sDisplaNameNodeName ) >>= _rClass.sDisplayName;
aClassDesc.getNodeValue( sSubFiltersNodeName ) >>= _rClass.aSubFilters;
}
//--------------------------------------------------------------------
struct CreateEmptyClassRememberPos : public ::std::unary_function< FilterName, void >
{
protected:
FilterClassList& m_rClassList;
FilterClassReferrer& m_rClassesReferrer;
public:
CreateEmptyClassRememberPos( FilterClassList& _rClassList, FilterClassReferrer& _rClassesReferrer )
:m_rClassList ( _rClassList )
,m_rClassesReferrer ( _rClassesReferrer )
{
}
// operate on a single class name
void operator() ( const FilterName& _rLogicalFilterName )
{
// insert a new (empty) class
m_rClassList.push_back( FilterClass() );
// get the position of this new entry
FilterClassList::iterator aInsertPos = m_rClassList.end();
--aInsertPos;
// remember this position
m_rClassesReferrer.insert( FilterClassReferrer::value_type( _rLogicalFilterName, aInsertPos ) );
}
};
//--------------------------------------------------------------------
struct ReadGlobalFilter : public ::std::unary_function< FilterName, void >
{
protected:
OConfigurationNode m_aClassesNode;
FilterClassReferrer& m_aClassReferrer;
public:
ReadGlobalFilter( const OConfigurationNode& _rClassesNode, FilterClassReferrer& _rClassesReferrer )
:m_aClassesNode ( _rClassesNode )
,m_aClassReferrer ( _rClassesReferrer )
{
}
// operate on a single logical name
void operator() ( const FilterName& _rName )
{
FilterClassReferrer::iterator aClassRef = m_aClassReferrer.find( _rName );
if ( m_aClassReferrer.end() == aClassRef )
{
// we do not know this global class
DBG_ERROR( "ReadGlobalFilter::operator(): unknown filter name!" );
// TODO: perhaps we should be more tolerant - at the moment, the filter is dropped
// We could silently push_back it to the container ....
}
else
{
// read the data of this class into the node referred to by aClassRef
lcl_ReadFilterClass( m_aClassesNode, _rName, *aClassRef->second );
}
}
};
//--------------------------------------------------------------------
void lcl_ReadGlobalFilters( const OConfigurationNode& _rFilterClassification, FilterClassList& _rGlobalClasses, StringArray& _rGlobalClassNames )
{
_rGlobalClasses.clear();
_rGlobalClassNames.clear();
//================================================================
// get the list describing the order of all global classes
Sequence< ::rtl::OUString > aGlobalClasses;
_rFilterClassification.getNodeValue( DEFINE_CONST_OUSTRING( "GlobalFilters/Order" ) ) >>= aGlobalClasses;
const ::rtl::OUString* pNames = aGlobalClasses.getConstArray();
const ::rtl::OUString* pNamesEnd = pNames + aGlobalClasses.getLength();
// copy the logical names
_rGlobalClassNames.resize( aGlobalClasses.getLength() );
::std::copy( pNames, pNamesEnd, _rGlobalClassNames.begin() );
// Global classes are presented in an own group, so their order matters (while the order of the
// "local classes" doesn't).
// That's why we can't simply add the global classes to _rGlobalClasses using the order in which they
// are returned from the configuration - it is completely undefined, and we need a _defined_ order.
FilterClassReferrer aClassReferrer;
::std::for_each(
pNames,
pNamesEnd,
CreateEmptyClassRememberPos( _rGlobalClasses, aClassReferrer )
);
// now _rGlobalClasses contains a dummy entry for each global class,
// while aClassReferrer maps from the logical name of the class to the position within _rGlobalClasses where
// it's dummy entry resides
//================================================================
// go for all the single class entries
OConfigurationNode aFilterClassesNode =
_rFilterClassification.openNode( DEFINE_CONST_OUSTRING( "GlobalFilters/Classes" ) );
Sequence< ::rtl::OUString > aFilterClasses = aFilterClassesNode.getNodeNames();
::std::for_each(
aFilterClasses.getConstArray(),
aFilterClasses.getConstArray() + aFilterClasses.getLength(),
ReadGlobalFilter( aFilterClassesNode, aClassReferrer )
);
}
//--------------------------------------------------------------------
struct ReadLocalFilter : public ::std::unary_function< FilterName, void >
{
protected:
OConfigurationNode m_aClassesNode;
FilterClassList& m_rClasses;
public:
ReadLocalFilter( const OConfigurationNode& _rClassesNode, FilterClassList& _rClasses )
:m_aClassesNode ( _rClassesNode )
,m_rClasses ( _rClasses )
{
}
// operate on a single logical name
void operator() ( const FilterName& _rName )
{
// read the data for this class
FilterClass aClass;
lcl_ReadFilterClass( m_aClassesNode, _rName, aClass );
// insert the class descriptor
m_rClasses.push_back( aClass );
}
};
//--------------------------------------------------------------------
void lcl_ReadLocalFilters( const OConfigurationNode& _rFilterClassification, FilterClassList& _rLocalClasses )
{
_rLocalClasses.clear();
// the node for the local classes
OConfigurationNode aFilterClassesNode =
_rFilterClassification.openNode( DEFINE_CONST_OUSTRING( "LocalFilters/Classes" ) );
Sequence< ::rtl::OUString > aFilterClasses = aFilterClassesNode.getNodeNames();
::std::for_each(
aFilterClasses.getConstArray(),
aFilterClasses.getConstArray() + aFilterClasses.getLength(),
ReadLocalFilter( aFilterClassesNode, _rLocalClasses )
);
}
//--------------------------------------------------------------------
void lcl_ReadClassification( FilterClassList& _rGlobalClasses, StringArray& _rGlobalClassNames, FilterClassList& _rLocalClasses )
{
//================================================================
// open our config node
OConfigurationTreeRoot aFilterClassification = OConfigurationTreeRoot::createWithServiceFactory(
::comphelper::getProcessServiceFactory(),
DEFINE_CONST_OUSTRING( "org.openoffice.Office.UI/FilterClassification" ),
-1,
OConfigurationTreeRoot::CM_READONLY
);
//================================================================
// go for the global classes
lcl_ReadGlobalFilters( aFilterClassification, _rGlobalClasses, _rGlobalClassNames );
//================================================================
// fo for the local classes
lcl_ReadLocalFilters( aFilterClassification, _rLocalClasses );
}
// =======================================================================
// = grouping and classifying
// =======================================================================
//--------------------------------------------------------------------
// a struct which adds helps remembering a reference to a class entry
struct ReferToFilterEntry : public ::std::unary_function< FilterName, void >
{
protected:
FilterGroupEntryReferrer& m_rEntryReferrer;
FilterGroup::iterator m_aClassPos;
public:
ReferToFilterEntry( FilterGroupEntryReferrer& _rEntryReferrer, const FilterGroup::iterator& _rClassPos )
:m_rEntryReferrer( _rEntryReferrer )
,m_aClassPos( _rClassPos )
{
}
// operate on a single filter name
void operator() ( const FilterName& _rName )
{
#ifdef DBG_UTIL
::std::pair< FilterGroupEntryReferrer::iterator, bool > aInsertRes =
#endif
m_rEntryReferrer.insert( FilterGroupEntryReferrer::value_type( _rName, m_aClassPos ) );
DBG_ASSERT( aInsertRes.second, "ReferToFilterEntry::operator(): already have an element for this name!" );
}
};
//--------------------------------------------------------------------
struct FillClassGroup : public ::std::unary_function< FilterClass, void >
{
protected:
FilterGroup& m_rClassGroup;
FilterGroupEntryReferrer& m_rClassReferrer;
public:
FillClassGroup( FilterGroup& _rClassGroup, FilterGroupEntryReferrer& _rClassReferrer )
:m_rClassGroup ( _rClassGroup )
,m_rClassReferrer ( _rClassReferrer )
{
}
// operate on a single class
void operator() ( const FilterClass& _rClass )
{
// create an empty filter descriptor for the class
FilterDescriptor aClassEntry;
// set it's name (which is all we know by now)
aClassEntry.First = _rClass.sDisplayName;
// add it to the group
m_rClassGroup.push_back( aClassEntry );
// the position of the newly added class
FilterGroup::iterator aClassEntryPos = m_rClassGroup.end();
--aClassEntryPos;
// and for all the sub filters of the class, remember the class
// (respectively the position of the class it the group)
::std::for_each(
_rClass.aSubFilters.getConstArray(),
_rClass.aSubFilters.getConstArray() + _rClass.aSubFilters.getLength(),
ReferToFilterEntry( m_rClassReferrer, aClassEntryPos )
);
}
};
//--------------------------------------------------------------------
static const sal_Unicode s_cWildcardSeparator( ';' );
//====================================================================
const ::rtl::OUString& getSeparatorString()
{
static ::rtl::OUString s_sSeparatorString( &s_cWildcardSeparator, 1 );
return s_sSeparatorString;
}
//====================================================================
struct CheckAppendSingleWildcard : public ::std::unary_function< ::rtl::OUString, void >
{
::rtl::OUString& _rToBeExtended;
CheckAppendSingleWildcard( ::rtl::OUString& _rBase ) : _rToBeExtended( _rBase ) { }
void operator() ( const ::rtl::OUString& _rWC )
{
// check for double wildcards
sal_Int32 nExistentPos = _rToBeExtended.indexOf( _rWC );
if ( -1 < nExistentPos )
{ // found this wildcard (already part of _rToBeExtended)
const sal_Unicode* pBuffer = _rToBeExtended.getStr();
if ( ( 0 == nExistentPos )
|| ( s_cWildcardSeparator == pBuffer[ nExistentPos - 1 ] )
)
{ // the wildcard really starts at this position (it starts at pos 0 or the previous character is a separator
sal_Int32 nExistentWCEnd = nExistentPos + _rWC.getLength();
if ( ( _rToBeExtended.getLength() == nExistentWCEnd )
|| ( s_cWildcardSeparator == pBuffer[ nExistentWCEnd ] )
)
{ // it's really the complete wildcard we found
// (not something like _rWC being "*.t" and _rToBeExtended containing "*.txt")
// -> outta here
return;
}
}
}
if ( _rToBeExtended.getLength() )
_rToBeExtended += getSeparatorString();
_rToBeExtended += _rWC;
}
};
//====================================================================
// a helper struct which adds a fixed (Sfx-)filter to a filter group entry given by iterator
struct AppendWildcardToDescriptor : public ::std::unary_function< FilterGroupEntryReferrer::value_type, void >
{
protected:
::std::vector< ::rtl::OUString > aWildCards;
public:
AppendWildcardToDescriptor( const String& _rWildCard );
// operate on a single class entry
void operator() ( const FilterGroupEntryReferrer::value_type& _rClassReference )
{
// simply add our wildcards
::std::for_each(
aWildCards.begin(),
aWildCards.end(),
CheckAppendSingleWildcard( _rClassReference.second->Second )
);
}
};
//====================================================================
AppendWildcardToDescriptor::AppendWildcardToDescriptor( const String& _rWildCard )
{
DBG_ASSERT( _rWildCard.Len(),
"AppendWildcardToDescriptor::AppendWildcardToDescriptor: invalid wildcard!" );
DBG_ASSERT( _rWildCard.GetBuffer()[0] != s_cWildcardSeparator,
"AppendWildcardToDescriptor::AppendWildcardToDescriptor: wildcard already separated!" );
aWildCards.reserve( _rWildCard.GetTokenCount( s_cWildcardSeparator ) );
const sal_Unicode* pTokenLoop = _rWildCard.GetBuffer();
const sal_Unicode* pTokenLoopEnd = pTokenLoop + _rWildCard.Len();
const sal_Unicode* pTokenStart = pTokenLoop;
for ( ; pTokenLoop != pTokenLoopEnd; ++pTokenLoop )
{
if ( ( s_cWildcardSeparator == *pTokenLoop ) && ( pTokenLoop > pTokenStart ) )
{ // found a new token separator (and a non-empty token)
aWildCards.push_back( ::rtl::OUString( pTokenStart, pTokenLoop - pTokenStart ) );
// search the start of the next token
while ( ( pTokenStart != pTokenLoopEnd ) && ( *pTokenStart != s_cWildcardSeparator ) )
++pTokenStart;
if ( pTokenStart == pTokenLoopEnd )
// reached the end
break;
++pTokenStart;
pTokenLoop = pTokenStart;
}
}
if ( pTokenLoop > pTokenStart )
// the last one ....
aWildCards.push_back( ::rtl::OUString( pTokenStart, pTokenLoop - pTokenStart ) );
}
//--------------------------------------------------------------------
void lcl_InitGlobalClasses( GroupedFilterList& _rAllFilters, const FilterClassList& _rGlobalClasses, FilterGroupEntryReferrer& _rGlobalClassesRef )
{
// we need an extra group in our "all filters" container
_rAllFilters.push_front( FilterGroup() );
FilterGroup& rGlobalFilters = _rAllFilters.front();
// it's important to work on the reference: we want to access the members of this filter group
// by an iterator (FilterGroup::const_iterator)
// the referrer for the global classes
// initialize the group
::std::for_each(
_rGlobalClasses.begin(),
_rGlobalClasses.end(),
FillClassGroup( rGlobalFilters, _rGlobalClassesRef )
);
// now we have:
// in rGlobalFilters: a list of FilterDescriptor's, where each's discriptor's display name is set to the name of a class
// in aGlobalClassesRef: a mapping from logical filter names to positions within rGlobalFilters
// this way, if we encounter an arbitrary filter, we can easily (and efficient) check if it belongs to a global class
// and modify the descriptor for this class accordingly
}
//--------------------------------------------------------------------
typedef ::std::vector< ::std::pair< FilterGroupEntryReferrer::mapped_type, FilterGroup::iterator > >
MapGroupEntry2GroupEntry;
// this is not really a map - it's just called this way because it is used as a map
struct FindGroupEntry : public ::std::unary_function< MapGroupEntry2GroupEntry::value_type, sal_Bool >
{
FilterGroupEntryReferrer::mapped_type aLookingFor;
FindGroupEntry( FilterGroupEntryReferrer::mapped_type _rLookingFor ) : aLookingFor( _rLookingFor ) { }
sal_Bool operator() ( const MapGroupEntry2GroupEntry::value_type& _rMapEntry )
{
return _rMapEntry.first == aLookingFor ? sal_True : sal_False;
}
};
struct CopyGroupEntryContent : public ::std::unary_function< MapGroupEntry2GroupEntry::value_type, void >
{
void operator() ( const MapGroupEntry2GroupEntry::value_type& _rMapEntry )
{
#ifdef DBG_UTIL
FilterDescriptor aHaveALook = *_rMapEntry.first;
#endif
*_rMapEntry.second = *_rMapEntry.first;
}
};
//--------------------------------------------------------------------
struct CopyNonEmptyFilter : public ::std::unary_function< FilterDescriptor, void >
{
FilterGroup& rTarget;
CopyNonEmptyFilter( FilterGroup& _rTarget ) :rTarget( _rTarget ) { }
void operator() ( const FilterDescriptor& _rFilter )
{
if ( _rFilter.Second.getLength() )
rTarget.push_back( _rFilter );
}
};
//--------------------------------------------------------------------
void lcl_GroupAndClassify( TSortedFilterList& _rFilterMatcher, GroupedFilterList& _rAllFilters )
{
_rAllFilters.clear();
// ===============================================================
// read the classification of filters
FilterClassList aGlobalClasses, aLocalClasses;
StringArray aGlobalClassNames;
lcl_ReadClassification( aGlobalClasses, aGlobalClassNames, aLocalClasses );
// ===============================================================
// for the global filter classes
FilterGroupEntryReferrer aGlobalClassesRef;
lcl_InitGlobalClasses( _rAllFilters, aGlobalClasses, aGlobalClassesRef );
// insert as much placeholders (FilterGroup's) into _rAllFilter for groups as we have global classes
// (this assumes that both numbers are the same, which, speaking strictly, must not hold - but it does, as we know ...)
sal_Int32 nGlobalClasses = aGlobalClasses.size();
while ( nGlobalClasses-- )
_rAllFilters.push_back( FilterGroup() );
// ===============================================================
// for the local classes:
// if n filters belong to a local class, they do not appear in their respective group explicitly, instead
// and entry for the class is added to the group and the extensions of the filters are collected under
// this entry
FilterGroupEntryReferrer aLocalClassesRef;
FilterGroup aCollectedLocals;
::std::for_each(
aLocalClasses.begin(),
aLocalClasses.end(),
FillClassGroup( aCollectedLocals, aLocalClassesRef )
);
// to map from the position within aCollectedLocals to positions within the real groups
// (where they finally belong to)
MapGroupEntry2GroupEntry aLocalFinalPositions;
// ===============================================================
// now add the filters
// the group which we currently work with
GroupedFilterList::iterator aCurrentGroup = _rAllFilters.end(); // no current group
// the filter container of the current group - if this changes between two filters, a new group is reached
String aCurrentServiceName;
String sFilterWildcard;
::rtl::OUString sFilterName;
// loop through all the filters
for ( const SfxFilter* pFilter = _rFilterMatcher.First(); pFilter; pFilter = _rFilterMatcher.Next() )
{
sFilterName = pFilter->GetFilterName();
sFilterWildcard = pFilter->GetWildcard().GetWildCard();
AppendWildcardToDescriptor aExtendWildcard( sFilterWildcard );
DBG_ASSERT( sFilterWildcard.Len(), "sfx2::lcl_GroupAndClassify: invalid wildcard of this filter!" );
// ===========================================================
// check for a change in the group
String aServiceName = pFilter->GetServiceName();
if ( aServiceName != aCurrentServiceName )
{ // we reached a new group
::rtl::OUString sDocServName = aServiceName;
// look for the place in _rAllFilters where this ne group belongs - this is determined
// by the order of classes in aGlobalClassNames
GroupedFilterList::iterator aGroupPos = _rAllFilters.begin();
DBG_ASSERT( aGroupPos != _rAllFilters.end(),
"sfx2::lcl_GroupAndClassify: invalid all-filters array here!" );
// the loop below will work on invalid objects else ...
++aGroupPos;
StringArray::iterator aGlobalIter = aGlobalClassNames.begin();
while ( ( aGroupPos != _rAllFilters.end() )
&& ( aGlobalIter != aGlobalClassNames.end() )
&& ( *aGlobalIter != sDocServName )
)
{
++aGlobalIter;
++aGroupPos;
}
if ( aGroupPos != _rAllFilters.end() )
// we found a global class name which matchies the doc service name -> fill the filters of this
// group in the respective prepared group
aCurrentGroup = aGroupPos;
else
// insert a new entry in our overall-list
aCurrentGroup = _rAllFilters.insert( _rAllFilters.end(), FilterGroup() );
// remember the container to properly detect the next group
aCurrentServiceName = aServiceName;
}
DBG_ASSERT( aCurrentGroup != _rAllFilters.end(), "sfx2::lcl_GroupAndClassify: invalid current group!" );
// ===========================================================
// check if the filter is part of a global group
::std::pair< FilterGroupEntryReferrer::iterator, FilterGroupEntryReferrer::iterator >
aBelongsTo = aGlobalClassesRef.equal_range( sFilterName );
// add the filter to the entries for these classes
// (if they exist - if not, the range is empty and the for_each is a no-op)
::std::for_each(
aBelongsTo.first,
aBelongsTo.second,
aExtendWildcard
);
// ===========================================================
// add the filter to it's group
// for this, check if the filter is part of a local filter
FilterGroupEntryReferrer::iterator aBelongsToLocal = aLocalClassesRef.find( sFilterName );
if ( aLocalClassesRef.end() != aBelongsToLocal )
{
/*
#ifdef DBG_UTIL
const ::rtl::OUString& rLocalClassDisplayName = aBelongsToLocal->second->First;
const ::rtl::OUString& rLocalClassExtension = aBelongsToLocal->second->Second;
#endif
*/
// okay, there is a local class which the filter belongs to
// -> append the wildcard
aExtendWildcard( *aBelongsToLocal );
MapGroupEntry2GroupEntry::iterator aThisGroupFinalPos =
::std::find_if( aLocalFinalPositions.begin(), aLocalFinalPositions.end(), FindGroupEntry( aBelongsToLocal->second ) );
if ( aLocalFinalPositions.end() == aThisGroupFinalPos )
{ // the position within aCollectedLocals has not been mapped to a final position
// within the "real" group (aCollectedLocals is only temporary)
// -> do this now (as we just encountered the first filter belonging to this local class
// add a new entry which is the "real" group entry
aCurrentGroup->push_back( FilterDescriptor( aBelongsToLocal->second->First, String() ) );
// the position where we inserted the entry
FilterGroup::iterator aInsertPos = aCurrentGroup->end();
--aInsertPos;
// remember this pos
aLocalFinalPositions.push_back( MapGroupEntry2GroupEntry::value_type( aBelongsToLocal->second, aInsertPos ) );
}
}
else
aCurrentGroup->push_back( FilterDescriptor( pFilter->GetUIName(), sFilterWildcard ) );
}
// now just complete the infos for the local groups:
// During the above loop, they have been collected in aCollectedLocals, but this is only temporary
// They have to be copied into their final positions (which are stored in aLocalFinalPositions)
::std::for_each(
aLocalFinalPositions.begin(),
aLocalFinalPositions.end(),
CopyGroupEntryContent()
);
// and remove local groups which do not apply - e.g. have no entries due to the limited content of the
// current SfxFilterMatcherIter
FilterGroup& rGlobalFilters = _rAllFilters.front();
FilterGroup aNonEmptyGlobalFilters;
::std::for_each(
rGlobalFilters.begin(),
rGlobalFilters.end(),
CopyNonEmptyFilter( aNonEmptyGlobalFilters )
);
rGlobalFilters.swap( aNonEmptyGlobalFilters );
}
//--------------------------------------------------------------------
struct AppendFilter : public ::std::unary_function< FilterDescriptor, void >
{
protected:
Reference< XFilterManager > m_xFilterManager;
FileDialogHelper_Impl* m_pFileDlgImpl;
bool m_bAddExtension;
public:
AppendFilter( const Reference< XFilterManager >& _rxFilterManager,
FileDialogHelper_Impl* _pImpl, bool _bAddExtension ) :
m_xFilterManager( _rxFilterManager ),
m_pFileDlgImpl ( _pImpl ),
m_bAddExtension ( _bAddExtension )
{
DBG_ASSERT( m_xFilterManager.is(), "AppendFilter::AppendFilter: invalid filter manager!" );
DBG_ASSERT( m_pFileDlgImpl, "AppendFilter::AppendFilter: invalid filedlg impl!" );
}
// operate on a single filter
void operator() ( const FilterDescriptor& _rFilterEntry )
{
String sDisplayText = m_bAddExtension
? addExtension( _rFilterEntry.First, _rFilterEntry.Second, sal_True, *m_pFileDlgImpl )
: _rFilterEntry.First;
m_xFilterManager->appendFilter( sDisplayText, _rFilterEntry.Second );
}
};
// =======================================================================
// = handling for the "all files" entry
// =======================================================================
//--------------------------------------------------------------------
sal_Bool lcl_hasAllFilesFilter( TSortedFilterList& _rFilterMatcher, String& /* [out] */ _rAllFilterName )
{
::rtl::OUString sUIName;
sal_Bool bHasAll = sal_False;
_rAllFilterName = String( SfxResId( STR_SFX_FILTERNAME_ALL ) );
// ===============================================================
// check if there's already a filter <ALL>
for ( const SfxFilter* pFilter = _rFilterMatcher.First(); pFilter && !bHasAll; pFilter = _rFilterMatcher.Next() )
{
if ( pFilter->GetUIName() == _rAllFilterName )
bHasAll = sal_True;
}
return bHasAll;
}
//--------------------------------------------------------------------
void lcl_EnsureAllFilesEntry( TSortedFilterList& _rFilterMatcher, GroupedFilterList& _rFilters )
{
// ===============================================================
String sAllFilterName;
if ( !lcl_hasAllFilesFilter( _rFilterMatcher, sAllFilterName ) )
{
// get the first group of filters (by definition, this group contains the global classes)
DBG_ASSERT( !_rFilters.empty(), "lcl_EnsureAllFilesEntry: invalid filter list!" );
if ( !_rFilters.empty() )
{
FilterGroup& rGlobalClasses = *_rFilters.begin();
rGlobalClasses.push_front( FilterDescriptor( sAllFilterName, DEFINE_CONST_UNICODE( FILEDIALOG_FILTER_ALL ) ) );
}
}
}
#ifdef DISABLE_GROUPING_AND_CLASSIFYING
//--------------------------------------------------------------------
void lcl_EnsureAllFilesEntry( TSortedFilterList& _rFilterMatcher, const Reference< XFilterManager >& _rxFilterManager, ::rtl::OUString& _rFirstNonEmpty )
{
// ===============================================================
String sAllFilterName;
if ( !lcl_hasAllFilesFilter( _rFilterMatcher, sAllFilterName ) )
{
try
{
_rxFilterManager->appendFilter( sAllFilterName, DEFINE_CONST_UNICODE( FILEDIALOG_FILTER_ALL ) );
_rFirstNonEmpty = sAllFilterName;
}
catch( const IllegalArgumentException& )
{
#ifdef DBG_UTIL
ByteString aMsg( "sfx2::lcl_EnsureAllFilesEntry: could not append Filter" );
aMsg += ByteString( String( sAllFilterName ), RTL_TEXTENCODING_UTF8 );
DBG_ERROR( aMsg.GetBuffer() );
#endif
}
}
}
#endif
// =======================================================================
// = filling an XFilterManager
// =======================================================================
//--------------------------------------------------------------------
struct AppendFilterGroup : public ::std::unary_function< FilterGroup, void >
{
protected:
Reference< XFilterManager > m_xFilterManager;
Reference< XFilterGroupManager > m_xFilterGroupManager;
FileDialogHelper_Impl* m_pFileDlgImpl;
public:
AppendFilterGroup( const Reference< XFilterManager >& _rxFilterManager, FileDialogHelper_Impl* _pImpl )
:m_xFilterManager ( _rxFilterManager )
,m_xFilterGroupManager ( _rxFilterManager, UNO_QUERY )
,m_pFileDlgImpl ( _pImpl )
{
DBG_ASSERT( m_xFilterManager.is(), "AppendFilterGroup::AppendFilterGroup: invalid filter manager!" );
DBG_ASSERT( m_pFileDlgImpl, "AppendFilterGroup::AppendFilterGroup: invalid filedlg impl!" );
}
void appendGroup( const FilterGroup& _rGroup, bool _bAddExtension )
{
try
{
if ( m_xFilterGroupManager.is() )
{ // the file dialog implementation supports visual grouping of filters
// create a representation of the group which is understandable by the XFilterGroupManager
if ( _rGroup.size() )
{
Sequence< StringPair > aFilters( _rGroup.size() );
::std::copy(
_rGroup.begin(),
_rGroup.end(),
aFilters.getArray()
);
if ( _bAddExtension )
{
StringPair* pFilters = aFilters.getArray();
StringPair* pEnd = pFilters + aFilters.getLength();
for ( ; pFilters != pEnd; ++pFilters )
pFilters->First = addExtension( pFilters->First, pFilters->Second, sal_True, *m_pFileDlgImpl );
}
m_xFilterGroupManager->appendFilterGroup( ::rtl::OUString(), aFilters );
}
}
else
{
::std::for_each(
_rGroup.begin(),
_rGroup.end(),
AppendFilter( m_xFilterManager, m_pFileDlgImpl, _bAddExtension ) );
}
}
catch( const Exception& )
{
DBG_UNHANDLED_EXCEPTION();
}
}
// operate on a single filter group
void operator() ( const FilterGroup& _rGroup )
{
appendGroup( _rGroup, true );
}
};
//--------------------------------------------------------------------
TSortedFilterList::TSortedFilterList(const ::com::sun::star::uno::Reference< ::com::sun::star::container::XEnumeration >& xFilterList)
: m_nIterator(0)
{
if (!xFilterList.is())
return;
m_lFilters.clear();
while(xFilterList->hasMoreElements())
{
::comphelper::SequenceAsHashMap lFilterProps (xFilterList->nextElement());
::rtl::OUString sFilterName = lFilterProps.getUnpackedValueOrDefault(
::rtl::OUString::createFromAscii("Name"),
::rtl::OUString());
if (sFilterName.getLength())
m_lFilters.push_back(sFilterName);
}
}
//--------------------------------------------------------------------
const SfxFilter* TSortedFilterList::First()
{
m_nIterator = 0;
return impl_getFilter(m_nIterator);
}
//--------------------------------------------------------------------
const SfxFilter* TSortedFilterList::Next()
{
++m_nIterator;
return impl_getFilter(m_nIterator);
}
//--------------------------------------------------------------------
const SfxFilter* TSortedFilterList::impl_getFilter(sal_Int32 nIndex)
{
if (nIndex<0 || nIndex>=(sal_Int32)m_lFilters.size())
return 0;
const ::rtl::OUString& sFilterName = m_lFilters[nIndex];
if (!sFilterName.getLength())
return 0;
return SfxFilter::GetFilterByName(String(sFilterName));
}
//--------------------------------------------------------------------
void appendFiltersForSave( TSortedFilterList& _rFilterMatcher,
const Reference< XFilterManager >& _rxFilterManager,
::rtl::OUString& _rFirstNonEmpty, FileDialogHelper_Impl& _rFileDlgImpl,
const ::rtl::OUString& _rFactory )
{
DBG_ASSERT( _rxFilterManager.is(), "sfx2::appendFiltersForSave: invalid manager!" );
if ( !_rxFilterManager.is() )
return;
::rtl::OUString sUIName;
::rtl::OUString sExtension;
// retrieve the default filter for this application module.
// It must be set as first of the generated filter list.
const SfxFilter* pDefaultFilter = SfxFilterContainer::GetDefaultFilter_Impl(_rFactory);
// --> PB 2004-11-01 #i32434# only use one extension
// (and always the first if there are more than one)
sExtension = pDefaultFilter->GetWildcard().GetWildCard().GetToken( 0, ';' );
// <--
sUIName = addExtension( pDefaultFilter->GetUIName(), sExtension, sal_False, _rFileDlgImpl );
try
{
_rxFilterManager->appendFilter( sUIName, sExtension );
if ( !_rFirstNonEmpty.getLength() )
_rFirstNonEmpty = sUIName;
}
catch( IllegalArgumentException )
{
#ifdef DBG_UTIL
ByteString aMsg( "Could not append DefaultFilter" );
aMsg += ByteString( String( sUIName ), osl_getThreadTextEncoding() );
DBG_ERRORFILE( aMsg.GetBuffer() );
#endif
}
for ( const SfxFilter* pFilter = _rFilterMatcher.First(); pFilter; pFilter = _rFilterMatcher.Next() )
{
if (pFilter->GetName() == pDefaultFilter->GetName())
continue;
// --> PB 2004-09-21 #i32434# only use one extension
// (and always the first if there are more than one)
sExtension = pFilter->GetWildcard().GetWildCard().GetToken( 0, ';' );
// <--
sUIName = addExtension( pFilter->GetUIName(), sExtension, sal_False, _rFileDlgImpl );
try
{
_rxFilterManager->appendFilter( sUIName, sExtension );
if ( !_rFirstNonEmpty.getLength() )
_rFirstNonEmpty = sUIName;
}
catch( IllegalArgumentException )
{
#ifdef DBG_UTIL
ByteString aMsg( "Could not append Filter" );
aMsg += ByteString( String( sUIName ), osl_getThreadTextEncoding() );
DBG_ERRORFILE( aMsg.GetBuffer() );
#endif
}
}
}
struct ExportFilter
{
ExportFilter( const rtl::OUString& _aUIName, const rtl::OUString& _aWildcard ) :
aUIName( _aUIName ), aWildcard( _aWildcard ) {}
rtl::OUString aUIName;
rtl::OUString aWildcard;
};
//--------------------------------------------------------------------
void appendExportFilters( TSortedFilterList& _rFilterMatcher,
const Reference< XFilterManager >& _rxFilterManager,
::rtl::OUString& _rFirstNonEmpty, FileDialogHelper_Impl& _rFileDlgImpl )
{
DBG_ASSERT( _rxFilterManager.is(), "sfx2::appendExportFilters: invalid manager!" );
if ( !_rxFilterManager.is() )
return;
sal_Int32 nHTMLIndex = -1;
sal_Int32 nXHTMLIndex = -1;
sal_Int32 nPDFIndex = -1;
sal_Int32 nFlashIndex = -1;
::rtl::OUString sUIName;
::rtl::OUString sExtensions;
std::vector< ExportFilter > aImportantFilterGroup;
std::vector< ExportFilter > aFilterGroup;
Reference< XFilterGroupManager > xFilterGroupManager( _rxFilterManager, UNO_QUERY );
::rtl::OUString sTypeName;
const ::rtl::OUString sWriterHTMLType( DEFINE_CONST_OUSTRING("writer_web_HTML") );
const ::rtl::OUString sGraphicHTMLType( DEFINE_CONST_OUSTRING("graphic_HTML") );
const ::rtl::OUString sXHTMLType( DEFINE_CONST_OUSTRING("XHTML_File") );
const ::rtl::OUString sPDFType( DEFINE_CONST_OUSTRING("pdf_Portable_Document_Format") );
const ::rtl::OUString sFlashType( DEFINE_CONST_OUSTRING("graphic_SWF") );
for ( const SfxFilter* pFilter = _rFilterMatcher.First(); pFilter; pFilter = _rFilterMatcher.Next() )
{
sTypeName = pFilter->GetTypeName();
sUIName = pFilter->GetUIName();
sExtensions = pFilter->GetWildcard().GetWildCard();
ExportFilter aExportFilter( sUIName, sExtensions );
String aExt = sExtensions;
if ( nHTMLIndex == -1 &&
( sTypeName.equals( sWriterHTMLType ) || sTypeName.equals( sGraphicHTMLType ) ) )
{
aImportantFilterGroup.insert( aImportantFilterGroup.begin(), aExportFilter );
nHTMLIndex = 0;
}
else if ( nXHTMLIndex == -1 && sTypeName.equals( sXHTMLType ) )
{
std::vector< ExportFilter >::iterator aIter = aImportantFilterGroup.begin();
if ( nHTMLIndex == -1 )
aImportantFilterGroup.insert( aIter, aExportFilter );
else
aImportantFilterGroup.insert( ++aIter, aExportFilter );
nXHTMLIndex = 0;
}
else if ( nPDFIndex == -1 && sTypeName.equals( sPDFType ) )
{
std::vector< ExportFilter >::iterator aIter = aImportantFilterGroup.begin();
if ( nHTMLIndex != -1 )
aIter++;
if ( nXHTMLIndex != -1 )
aIter++;
aImportantFilterGroup.insert( aIter, aExportFilter );
nPDFIndex = 0;
}
else if ( nFlashIndex == -1 && sTypeName.equals( sFlashType ) )
{
std::vector< ExportFilter >::iterator aIter = aImportantFilterGroup.begin();
if ( nHTMLIndex != -1 )
aIter++;
if ( nXHTMLIndex != -1 )
aIter++;
if ( nPDFIndex != -1 )
aIter++;
aImportantFilterGroup.insert( aIter, aExportFilter );
nFlashIndex = 0;
}
else
aFilterGroup.push_back( aExportFilter );
}
if ( xFilterGroupManager.is() )
{
// Add both html/pdf filter as a filter group to get a separator between both groups
if ( aImportantFilterGroup.size() > 0 )
{
Sequence< StringPair > aFilters( aImportantFilterGroup.size() );
for ( sal_Int32 i = 0; i < (sal_Int32)aImportantFilterGroup.size(); i++ )
{
aFilters[i].First = addExtension( aImportantFilterGroup[i].aUIName,
aImportantFilterGroup[i].aWildcard,
sal_False, _rFileDlgImpl );
aFilters[i].Second = aImportantFilterGroup[i].aWildcard;
}
try
{
xFilterGroupManager->appendFilterGroup( ::rtl::OUString(), aFilters );
}
catch( IllegalArgumentException )
{
}
}
if ( aFilterGroup.size() > 0 )
{
Sequence< StringPair > aFilters( aFilterGroup.size() );
for ( sal_Int32 i = 0; i < (sal_Int32)aFilterGroup.size(); i++ )
{
aFilters[i].First = addExtension( aFilterGroup[i].aUIName,
aFilterGroup[i].aWildcard,
sal_False, _rFileDlgImpl );
aFilters[i].Second = aFilterGroup[i].aWildcard;
}
try
{
xFilterGroupManager->appendFilterGroup( ::rtl::OUString(), aFilters );
}
catch( IllegalArgumentException )
{
}
}
}
else
{
// Fallback solution just add both filter groups as single filters
sal_Int32 n;
for ( n = 0; n < (sal_Int32)aImportantFilterGroup.size(); n++ )
{
try
{
rtl::OUString aUIName = addExtension( aImportantFilterGroup[n].aUIName,
aImportantFilterGroup[n].aWildcard,
sal_False, _rFileDlgImpl );
_rxFilterManager->appendFilter( aUIName, aImportantFilterGroup[n].aWildcard );
if ( !_rFirstNonEmpty.getLength() )
_rFirstNonEmpty = sUIName;
}
catch( IllegalArgumentException )
{
#ifdef DBG_UTIL
ByteString aMsg( "Could not append Filter" );
aMsg += ByteString( String( sUIName ), osl_getThreadTextEncoding() );
DBG_ERRORFILE( aMsg.GetBuffer() );
#endif
}
}
for ( n = 0; n < (sal_Int32)aFilterGroup.size(); n++ )
{
try
{
rtl::OUString aUIName = addExtension( aFilterGroup[n].aUIName,
aFilterGroup[n].aWildcard,
sal_False, _rFileDlgImpl );
_rxFilterManager->appendFilter( aUIName, aFilterGroup[n].aWildcard );
if ( !_rFirstNonEmpty.getLength() )
_rFirstNonEmpty = sUIName;
}
catch( IllegalArgumentException )
{
#ifdef DBG_UTIL
ByteString aMsg( "Could not append Filter" );
aMsg += ByteString( String( sUIName ), osl_getThreadTextEncoding() );
DBG_ERRORFILE( aMsg.GetBuffer() );
#endif
}
}
}
}
//--------------------------------------------------------------------
void appendFiltersForOpen( TSortedFilterList& _rFilterMatcher,
const Reference< XFilterManager >& _rxFilterManager,
::rtl::OUString& _rFirstNonEmpty, FileDialogHelper_Impl& _rFileDlgImpl )
{
DBG_ASSERT( _rxFilterManager.is(), "sfx2::appendFiltersForOpen: invalid manager!" );
if ( !_rxFilterManager.is() )
return;
#ifdef DISABLE_GROUPING_AND_CLASSIFYING
// ===============================================================
// ensure that there's an entry "all" (with wildcard *.*)
lcl_EnsureAllFilesEntry( _rFilterMatcher, _rxFilterManager, _rFirstNonEmpty );
// ===============================================================
appendFilters( _rFilterMatcher, _rxFilterManager, _rFirstNonEmpty );
#else
// ===============================================================
// group and classify the filters
GroupedFilterList aAllFilters;
lcl_GroupAndClassify( _rFilterMatcher, aAllFilters );
// ===============================================================
// ensure that we have the one "all files" entry
lcl_EnsureAllFilesEntry( _rFilterMatcher, aAllFilters );
// ===============================================================
// the first non-empty string - which we assume is the first overall entry
if ( !aAllFilters.empty() )
{
const FilterGroup& rFirstGroup = *aAllFilters.begin(); // should be the global classes
if ( !rFirstGroup.empty() )
_rFirstNonEmpty = rFirstGroup.begin()->First;
// append first group, without extension
AppendFilterGroup aGroup( _rxFilterManager, &_rFileDlgImpl );
aGroup.appendGroup( rFirstGroup, false );
}
// ===============================================================
// append the filters to the manager
if ( !aAllFilters.empty() )
{
::std::list< FilterGroup >::iterator pIter = aAllFilters.begin();
++pIter;
::std::for_each(
pIter, // first filter group was handled separately, see above
aAllFilters.end(),
AppendFilterGroup( _rxFilterManager, &_rFileDlgImpl ) );
}
#endif
}
::rtl::OUString addExtension( const ::rtl::OUString& _rDisplayText,
const ::rtl::OUString& _rExtension,
sal_Bool _bForOpen, FileDialogHelper_Impl& _rFileDlgImpl )
{
static ::rtl::OUString sAllFilter( RTL_CONSTASCII_USTRINGPARAM( "(*.*)" ) );
static ::rtl::OUString sOpenBracket( RTL_CONSTASCII_USTRINGPARAM( " (" ) );
static ::rtl::OUString sCloseBracket( RTL_CONSTASCII_USTRINGPARAM( ")" ) );
::rtl::OUString sRet = _rDisplayText;
if ( sRet.indexOf( sAllFilter ) == -1 )
{
String sExt = _rExtension;
if ( !_bForOpen )
// show '*' in extensions only when opening a document
sExt.EraseAllChars( '*' );
sRet += sOpenBracket;
sRet += sExt;
sRet += sCloseBracket;
}
_rFileDlgImpl.addFilterPair( _rDisplayText, sRet );
return sRet;
}
//........................................................................
} // namespace sfx2
//........................................................................
|
wqw547243068/DS_Algorithm | CtCI/chapter20/20.11.cpp | <reponame>wqw547243068/DS_Algorithm
#include <iostream>
#include <cstdio>
using namespace std;
const int MAX_N = 100;
int matrix[MAX_N][MAX_N];
struct SubSquare{
int row, col, size;
};
inline int max(int a, int b){
return a > b ? a : b;
}
bool IsSquare(int row, int col, int size){
for(int i=0; i<size; ++i){
if(matrix[row][col+i] == 1)// 1代表白色,0代表黑色
return false;
if(matrix[row+size-1][col+i] == 1)
return false;
if(matrix[row+i][col] == 1)
return false;
if(matrix[row+i][col+size-1] == 1)
return false;
}
return true;
}
SubSquare FindSubSquare(int n){
int max_size = 0; //最大边长
int col = 0;
SubSquare sq;
while(n-col > max_size){
for(int row=0; row<n; ++row){
int size = n - max(row, col);
while(size > max_size){
if(IsSquare(row, col, size)){
max_size = size;
sq.row = row;
sq.col = col;
sq.size = size;
break;
}
--size;
}
}
++col;
}
return sq;
}
int main(){
freopen("20.11.in", "r", stdin);
int n;
cin>>n;
for(int i=0; i<n; ++i)
for(int j=0; j<n; ++j)
cin>>matrix[i][j];
SubSquare sq = FindSubSquare(n);
cout<<"top: "<<sq.row<<endl;
cout<<"bottom: "<<sq.row+sq.size-1<<endl;
cout<<"left: "<<sq.col<<endl;
cout<<"right: "<<sq.col+sq.size-1<<endl;
fclose(stdin);
return 0;
}
|
djamal2727/Main-Bearing-Analytical-Model | Validation/pyFrame3DD-master/gcc-master/gcc/testsuite/c-c++-common/pr95378.c | /* { dg-do compile } */
#define seq_cst __ATOMIC_SEQ_CST
extern int *i;
extern int *j;
extern const int *c;
extern volatile int *v;
extern const volatile int *cv;
void
load()
{
__atomic_load(c, i, seq_cst);
__atomic_load(cv, i, seq_cst);
__atomic_load(i, c, seq_cst);
/* { dg-error "argument 2 of '__atomic_load' must not be a pointer to a 'const' type" "" { target c++ } .-1 } */
/* { dg-warning "argument 2 of '__atomic_load' discards 'const' qualifier" "" { target c } .-2 } */
__atomic_load(i, v, seq_cst);
/* { dg-error "argument 2 of '__atomic_load' must not be a pointer to a 'volatile' type" "" { target c++ } .-1 } */
/* { dg-warning "argument 2 of '__atomic_load' discards 'volatile' qualifier" "" { target c } .-2 } */
__atomic_load(i, cv, seq_cst);
/* { dg-error "argument 2 of '__atomic_load' must not be a pointer to a 'const' type" "" { target c++ } .-1 } */
/* { dg-warning "argument 2 of '__atomic_load' discards 'const' qualifier" "" { target c } .-2 } */
/* { dg-warning "argument 2 of '__atomic_load' discards 'volatile' qualifier" "" { target c } .-3 } */
}
void
store()
{
__atomic_store(i, c, seq_cst);
__atomic_store(v, c, seq_cst);
__atomic_store(c, i, seq_cst);
/* { dg-error "argument 1 of '__atomic_store' must not be a pointer to a 'const' type" "" { target c++ } .-1 } */
/* { dg-warning "argument 1 of '__atomic_store' discards 'const' qualifier" "" { target c } .-2 } */
__atomic_store(cv, i, seq_cst);
/* { dg-error "argument 1 of '__atomic_store' must not be a pointer to a 'const' type" "" { target c++ } .-1 } */
/* { dg-warning "argument 1 of '__atomic_store' discards 'const' qualifier" "" { target c } .-2 } */
__atomic_store(i, v, seq_cst);
/* { dg-error "argument 2 of '__atomic_store' must not be a pointer to a 'volatile' type" "" { target c++ } .-1 } */
/* { dg-warning "argument 2 of '__atomic_store' discards 'volatile' qualifier" "" { target c } .-2 } */
}
void
exchange()
{
__atomic_exchange(i, c, j, seq_cst);
__atomic_exchange(v, i, j, seq_cst);
__atomic_exchange(v, c, j, seq_cst);
__atomic_exchange(c, i, j, seq_cst);
/* { dg-error "argument 1 of '__atomic_exchange' must not be a pointer to a 'const' type" "" { target c++ } .-1 } */
/* { dg-warning "argument 1 of '__atomic_exchange' discards 'const' qualifier" "" { target c } .-2 } */
__atomic_exchange(cv, i, j, seq_cst);
/* { dg-error "argument 1 of '__atomic_exchange' must not be a pointer to a 'const' type" "" { target c++ } .-1 } */
/* { dg-warning "argument 1 of '__atomic_exchange' discards 'const' qualifier" "" { target c } .-2 } */
__atomic_exchange(i, v, j, seq_cst);
/* { dg-error "argument 2 of '__atomic_exchange' must not be a pointer to a 'volatile' type" "" { target c++ } .-1 } */
/* { dg-warning "argument 2 of '__atomic_exchange' discards 'volatile' qualifier" "" { target c } .-2 } */
__atomic_exchange(i, cv, j, seq_cst);
/* { dg-error "argument 2 of '__atomic_exchange' must not be a pointer to a 'volatile' type" "" { target c++ } .-1 } */
/* { dg-warning "argument 2 of '__atomic_exchange' discards 'volatile' qualifier" "" { target c } .-2 } */
__atomic_exchange(i, j, c, seq_cst);
/* { dg-error "argument 3 of '__atomic_exchange' must not be a pointer to a 'const' type" "" { target c++ } .-1 } */
/* { dg-warning "argument 3 of '__atomic_exchange' discards 'const' qualifier" "" { target c } .-2 } */
__atomic_exchange(i, j, v, seq_cst);
/* { dg-error "argument 3 of '__atomic_exchange' must not be a pointer to a 'volatile' type" "" { target c++ } .-1 } */
/* { dg-warning "argument 3 of '__atomic_exchange' discards 'volatile' qualifier" "" { target c } .-2 } */
__atomic_exchange(i, j, cv, seq_cst);
/* { dg-error "argument 3 of '__atomic_exchange' must not be a pointer to a 'const' type" "" { target c++ } .-1 } */
/* { dg-warning "argument 3 of '__atomic_exchange' discards 'const' qualifier" "" { target c } .-2 } */
/* { dg-warning "argument 3 of '__atomic_exchange' discards 'volatile' qualifier" "" { target c } .-3 } */
}
void
compare_exchange()
{
__atomic_compare_exchange(i, j, c, 1, seq_cst, seq_cst);
__atomic_compare_exchange(v, i, j, 1, seq_cst, seq_cst);
__atomic_compare_exchange(v, i, c, 1, seq_cst, seq_cst);
__atomic_compare_exchange(c, i, j, 1, seq_cst, seq_cst);
/* { dg-error "argument 1 of '__atomic_compare_exchange' must not be a pointer to a 'const' type" "" { target c++ } .-1 } */
/* { dg-warning "argument 1 of '__atomic_compare_exchange' discards 'const' qualifier" "" { target c } .-2 } */
__atomic_compare_exchange(cv, i, j, 1, seq_cst, seq_cst);
/* { dg-error "argument 1 of '__atomic_compare_exchange' must not be a pointer to a 'const' type" "" { target c++ } .-1 } */
/* { dg-warning "argument 1 of '__atomic_compare_exchange' discards 'const' qualifier" "" { target c } .-2 } */
__atomic_compare_exchange(i, c, j, 1, seq_cst, seq_cst);
/* { dg-error "argument 2 of '__atomic_compare_exchange' must not be a pointer to a 'const' type" "" { target c++ } .-1 } */
/* { dg-warning "argument 2 of '__atomic_compare_exchange' discards 'const' qualifier" "" { target c } .-2 } */
__atomic_compare_exchange(i, v, j, 1, seq_cst, seq_cst);
/* { dg-error "argument 2 of '__atomic_compare_exchange' must not be a pointer to a 'volatile' type" "" { target c++ } .-1 } */
/* { dg-warning "argument 2 of '__atomic_compare_exchange' discards 'volatile' qualifier" "" { target c } .-2 } */
__atomic_compare_exchange(i, cv, j, 1, seq_cst, seq_cst);
/* { dg-error "argument 2 of '__atomic_compare_exchange' must not be a pointer to a 'const' type" "" { target c++ } .-1 } */
/* { dg-warning "argument 2 of '__atomic_compare_exchange' discards 'const" "" { target c } .-2 } */
/* { dg-warning "argument 2 of '__atomic_compare_exchange' discards 'volatile' qualifier" "" { target c } .-3 } */
__atomic_compare_exchange(i, j, v, 1, seq_cst, seq_cst);
/* { dg-error "argument 3 of '__atomic_compare_exchange' must not be a pointer to a 'volatile' type" "" { target c++ } .-1 } */
/* { dg-warning "argument 3 of '__atomic_compare_exchange' discards 'volatile' qualifier" "" { target c } .-2 } */
__atomic_compare_exchange(i, j, cv, 1, seq_cst, seq_cst);
/* { dg-error "argument 3 of '__atomic_compare_exchange' must not be a pointer to a 'volatile' type" "" { target c++ } .-1 } */
/* { dg-warning "argument 3 of '__atomic_compare_exchange' discards 'volatile' qualifier" "" { target c } .-2 } */
}
|
QuantEcon/sphinx-tojupyter | docs/_build/jupyter_execute/directives.py | #!/usr/bin/env python
# coding: utf-8
# (directives)=
# # Directives
#
# The following directives are provided by this extension:
#
# ```{contents}
# ---
# depth: 1
# local:
# ---
# ```
#
# ## Directive: exercise
#
# Exercise directives can be added to your text such as:
#
# ```{code-block} rst
# .. exercise::
#
# Contains the Exercise
# ```
#
# If you would like to `exclude` them from your documents you
# can set:
# In[1]:
exercise_include_exercises = False``
# in your `conf.py` file.
#
# ## Directive: exerciselist
#
# Collect exercises from the document and compile an exercise list where the directive is placed in the RST
#
# ```{code-block} rst
# .. exerciselist::
# ```
#
# Beneath each exercise in the list there is another link "(back to text)"
# that points back to the location where you originally authored/placed the exercise.
#
# ### Provided Options
#
# ```{code-block} rst
# .. exerciselist::
# :scope: SCOPE
# :from: FILE
# :force:
# ```
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
# |Option|Description|Values|
# |:-------------------------------:|:-------------------------------:|:-------------------------------:|
# |`|:from:|`|import exercise defined in a file|
# |`|:scope:|`|provide scope of exercises|`|file|`|, |`|section|`|, or |`|all|`|
# |`|:force:|`|force exercises to render where they are defined|True/False|
# |`|:title:|`|Specify title used for exercise block|
#
# #### `:scope:`
#
# `file` then only exercises defined in the same file as the exerciselist directive will be included
# `section` then all exercises defined in the same section will be included
# `all` then all exercises anywhere in the project will be included
#
# ### `:force:`
#
# By default, when the conf.py config setting exercise_inline_exercises is true, all
# exercises will render where they are defined and the exerciselist node will be removed
# from the doctree.
#
# ```{warning}
# However, if the :force: option is given the exerciselist will always be rendered
# and when exercise_inline_exercises is True, each problem will be rendered twice.
# ```
#
# ### Additional Info
#
# If an exercise is included in an exercise list, it is only removed from its original
# location if the exercise list is in the same file.
#
# For example, if I define an exercise in A.rst and in B.rst I both define an exercise
# and an exerciselist with :scope: section then the following will happen:
#
# - both exercises will render at the point of the exerciselist in B.rst
# - The exercise in B.rst will not be rendered where it was defined, but instead a link to the exercise list and number will be given
# - The exercise in A.rst will still be rendered in file A. This means its contents are rendered two times.
|
2019-2020-IUT/M213-Bases-de-la-programmation-oriente-objet | src/TD4/vehicule/Vehicule.java | package TD4.vehicule;
public class Vehicule {
protected String marque;
protected int dateAchat;
protected double prixAchat;
protected double prixCourant;
public Vehicule() {
marque = "";
dateAchat = 0;
prixAchat = 0;
prixCourant = 0;
}
public Vehicule(String s, int d, double pA) {
this.marque = s;
dateAchat = d;
prixAchat = pA;
prixCourant = 0;
}
public void calculPrix(int y) {
int previousY = this.dateAchat - y;
this.prixCourant = this.prixAchat - ((this.prixAchat/100) * previousY);
}
public void affiche() {
System.out.println(""+this.marque+" "+this.dateAchat+" "+this.prixAchat+" "+prixCourant);
}
}
|
weforward/weforward-parent | weforward-protocol/src/main/java/cn/weforward/protocol/client/ext/RequestInvokeObject.java | /**
* Copyright (c) 2019,2020 honintech
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
package cn.weforward.protocol.client.ext;
import java.util.Date;
import java.util.Enumeration;
import java.util.Iterator;
import cn.weforward.common.KvPair;
import cn.weforward.protocol.RequestConstants;
import cn.weforward.protocol.datatype.DtBase;
import cn.weforward.protocol.datatype.DtObject;
import cn.weforward.protocol.exception.ObjectMappingException;
import cn.weforward.protocol.ext.ObjectMapper;
import cn.weforward.protocol.ext.ObjectMapperSet;
import cn.weforward.protocol.support.datatype.SimpleDtList;
import cn.weforward.protocol.support.datatype.SimpleDtObject;
/**
* 调用请求的invoke信息封装
*
* @author zhangpengji
*
*/
public class RequestInvokeObject {// implements DtObject
SimpleDtObject m_Invoke;
SimpleDtObject m_Params;
ObjectMapperSet m_Mappers;
/**
* 构造
*
* @param method 方法名
*/
public RequestInvokeObject(String method) {
m_Invoke = new SimpleDtObject(false);
m_Invoke.put(RequestConstants.METHOD, method);
}
/**
* 根据另一个RequestInvokeObject构造,复制其内容
*
* @param other 另一个对象
*/
public RequestInvokeObject(RequestInvokeObject other) {
m_Invoke = other.m_Invoke;
m_Mappers = other.m_Mappers;
if (null != other.m_Params) {
Enumeration<KvPair<String, DtBase>> dtObjAtts = other.m_Params.getAttributes();
while (dtObjAtts.hasMoreElements()) {
KvPair<String, DtBase> att = dtObjAtts.nextElement();
putParam(att.getKey(), att.getValue());
}
}
}
public RequestInvokeObject(String method, ObjectMapperSet mappers) {
this(method);
setMappers(mappers);
}
public RequestInvokeObject(String method, RequestInvokeParam... params) {
this(method);
putParams(params);
}
public void setMappers(ObjectMapperSet mappers) {
m_Mappers = mappers;
}
public <E> ObjectMapper<E> getMapper(Class<E> clazz) {
if (null == m_Mappers) {
return null;
}
return m_Mappers.getObjectMapper(clazz);
}
protected SimpleDtObject getParams() {
if (null == m_Params) {
synchronized (this) {
// double check
if (null == m_Params) {
m_Params = new SimpleDtObject();
m_Invoke.put("params", m_Params);
}
}
}
return m_Params;
}
public void putParam(String name, DtBase value) {
getParams().put(name, value);
}
public void putParam(String name, String value) {
getParams().put(name, value);
}
public void putParam(String name, int value) {
getParams().put(name, value);
}
public void putParam(String name, long value) {
getParams().put(name, value);
}
public void putParam(String name, double value) {
getParams().put(name, value);
}
public void putParam(String name, Date value) {
getParams().put(name, value);
}
public void putParam(String name, boolean value) {
getParams().put(name, value);
}
public void putParamStringList(String name, Iterable<String> value) {
SimpleDtList list = SimpleDtList.stringOf(value);
getParams().put(name, list);
}
public void putParamDateList(String name, Iterable<Date> value) {
SimpleDtList list = SimpleDtList.dateOf(value);
getParams().put(name, list);
}
public void putParamNumberList(String name, Iterable<? extends Number> value) {
SimpleDtList list = SimpleDtList.numberOf(value);
getParams().put(name, list);
}
public void putParamBooleanList(String name, Iterable<Boolean> value) {
SimpleDtList list = SimpleDtList.booleanOf(value);
getParams().put(name, list);
}
public <E> void putParam(String name, E obj) {
DtBase dtObj = null;
if (null != obj) {
@SuppressWarnings("unchecked")
ObjectMapper<E> mapper = getMapper((Class<E>) obj.getClass());
if (null == mapper) {
throw new ObjectMappingException("不支持映射此对象:" + obj);
}
dtObj = mapper.toDtObject(obj);
}
getParams().put(name, dtObj);
}
@SuppressWarnings("unchecked")
public <E> void putParam(String name, Iterable<E> it) {
if (null == it) {
getParams().put(name, (DtBase) null);
return;
}
Iterator<E> iterator = it.iterator();
if (!iterator.hasNext()) {
getParams().put(name, SimpleDtList.empty());
return;
}
SimpleDtList dtList = new SimpleDtList();
ObjectMapper<E> mapper = null;
while (iterator.hasNext()) {
E obj = iterator.next();
if (null == mapper) {
mapper = getMapper((Class<E>) obj.getClass());
if (null == mapper) {
throw new ObjectMappingException("不支持映射此对象:" + obj);
}
}
DtObject hyObj = mapper.toDtObject(obj);
dtList.addItem(hyObj);
}
getParams().put(name, dtList);
}
public void putParams(RequestInvokeParam... params) {
if (null == params || 0 == params.length) {
return;
}
for (RequestInvokeParam p : params) {
putParam(p.name, p.value);
}
}
/**
* 将obj的所有属性做为参数
*
* @param obj
*/
public void asParams(Object obj) {
if (null == obj) {
return;
}
DtObject dtObj;
if (obj instanceof DtObject) {
dtObj = (DtObject) obj;
} else {
@SuppressWarnings("unchecked")
ObjectMapper<Object> mapper = getMapper((Class<Object>) obj.getClass());
if (null == mapper) {
throw new ObjectMappingException("不支持映射此对象:" + obj);
}
dtObj = mapper.toDtObject(obj);
}
getParams().putAll(dtObj);
}
public DtObject toDtObject() {
return m_Invoke;
}
}
|
kit-sdq/eagle | port/src/main/java/edu/kit/ipd/eagle/port/xplore/IPath.java | <gh_stars>1-10
package edu.kit.ipd.eagle.port.xplore;
import java.io.Serializable;
import edu.kit.ipd.eagle.port.xplore.layer.ILayerEntry;
/**
* This interface defines a path in the exploration tree of hypotheses.
*
* @author <NAME>
*
*/
public interface IPath extends Serializable {
/**
* Get a readable version of the path.
*
* @return a readable version
*/
String getPrettyString();
/**
* Get the path as array of layer entries starting at root.
*
* @return the path as layer entries
*/
ILayerEntry[] getPath();
/**
* Convert the path to {@link IExplorationResult}.
*
* @param text the text to use for {@link IExplorationResult#getId()}
* @return the {@link IExplorationResult} which only contains the path
*/
IExplorationResult toExplorationResult(String text);
}
|
nathan-menhorn/xilinx-embeddedw-sonarcloud | XilinxProcessorIPLib/drivers/rfdc/doc/html/api/xrfdc__clock_8c.js | var xrfdc__clock_8c =
[
[ "XRFdc_DynamicPLLConfig", "xrfdc__clock_8c.html#ga2390330eaf525d57a9500d298d712db1", null ],
[ "XRFdc_GetClkDistribution", "xrfdc__clock_8c.html#ga378a2d5a17b1eeac656ccccdb20d0a0a", null ],
[ "XRFdc_GetClockSource", "xrfdc__clock_8c.html#gadbda21c40278f6c95ce2a02f0d52c49c", null ],
[ "XRFdc_GetPLLConfig", "xrfdc__clock_8c.html#gaf806aa894bd65b6fffa3fa978546f41a", null ],
[ "XRFdc_GetPLLLockStatus", "xrfdc__clock_8c.html#gac141871e4c2350d88e8fc892771f3ae4", null ],
[ "XRFdc_SetClkDistribution", "xrfdc__clock_8c.html#gad56eb12fd1e1e9dad5c4b8c0f7cc87c1", null ]
]; |
halvardmadsen/fjell | src/components/RelatedProducts.js | import React, { useEffect, useState } from 'react';
import PropTypes from 'prop-types';
import Img from 'gatsby-image';
import { graphql, Link } from 'gatsby';
//const isIE = /*@cc_on!@*/ false || !!document.documentMode;
const RelatedProducts = ({ relatedproducts, title1 }) => {
const [isIE, setIsIE] = useState(false);
useEffect(() => {
setIsIE(/*@cc_on!@*/ false || !!document.documentMode);
}, []);
if (relatedproducts) {
if (
relatedproducts['relatedproduct1'] === null &&
relatedproducts['relatedproduct2'] === null &&
relatedproducts['relatedproduct3'] === null
) {
relatedproducts = null;
}
}
return (
<div className="project-related-products">
<p className="title has-text-centered" style={{ marginBottom: '3rem' }}>
{title1}
</p>
<div className={`columns ${!isIE && 'is-centered'}`}>
{relatedproducts ? (
Object.keys(relatedproducts).map((product, index) => {
if (relatedproducts[product]) {
return (
<div
key={index}
className="is-horizontal-align column"
style={{
flexDirection: 'column',
maxHeight: '350px',
maxWidth: '550px',
}}
>
{typeof relatedproducts[product].headerimage === 'string' ? (
<img
src={relatedproducts[product].headerimage}
style={{ width: '40%' }}
/>
) : (
<Link
to={'/product/' + relatedproducts[product]['slug']}
style={{ width: '94%' }}
className="related-product"
>
<Img
fluid={
relatedproducts[product].headerimage.childImageSharp
.fluid
}
alt={`featured image thumbnail for ${title1}`}
style={{
height: '270px',
width: '100%',
objectFit: 'cover',
}}
/>
</Link>
)}
<hr
style={{
backgroundColor: 'black',
width: '50%',
height: '1px',
padding: '0.5px',
}}
></hr>
<Link
className="title is-5 has-text-centered "
to={'/product/' + relatedproducts[product]['slug']}
>
{relatedproducts[product]['title']}
</Link>
</div>
);
}
})
) : (
<div style={{ textAlign: 'center', margin: '0 auto' }}>
- No related products found -
</div>
)}
</div>
</div>
);
};
RelatedProducts.propTypes = {
relatedproducts: PropTypes.object,
title1: PropTypes.string,
};
export default RelatedProducts;
|
gregsoares/gregsoares.com | client/src/Components/ProjectSection/WixLandingPage.js | import React from "react";
export const WixLandingPage = () => {
return (
<div className="mx-4 my-16 overflow-hidden border border-gray-700 rounded-md shadow-md sm:mx-auto lg:max-w-4xl md:max-w-2xl xs:max-w-lg sm:max-w-lg brand-lighterBlue">
<h3 className="my-6 text-2xl text-center text-gray-400 sm:text-3xl ">
Wix Landing Page
</h3>
<div className="flex flex-col items-center justify-center leading-normal tracking-wide text-center ">
<img
src="https://i.ibb.co/T4VSb21/Screenshot-from-2020-09-30-22-47-48.png"
alt="Wix Landing Page Screenshot"
className="object-cover max-w-4xl"
/>
</div>
<div className="flex-col py-8 mx-8 justify-evenly">
<p className="leading-relaxed tracking-wide text-justify sm:mx-2 md:mx-4">
<span className="pl-2">C</span>hanging gears from coding and having
the power to customize everything is difficult, on the other hand, it
is quite fun to be able to fall back to it anytime I need. As I start
my freelancing / consulting business, I realize that I must adapt and
continue to be versatile in what skills and services I can offer.
<br />
<span className="pl-2"></span>This Langing page is the beginning of it
all, forever under construction, it will contain my new portfolio from
my freelancing work
</p>
<div className="flex justify-around">
<ol className="my-3 list-disc list-inside ">
Web Platforms:
{/* <p className="my-2 font-medium text-gray-300">Tools Used:</p> */}
<li className="w-full my-1">Wordpress</li>
<li className="w-full my-1">Wix</li>
<li className="w-full my-1">Squarepace</li>
</ol>
<ol className="my-3 list-disc list-inside ">
Web Platforms:
{/* <p className="my-2 font-medium text-gray-300">Tools Used:</p> */}
<li className="w-full my-1">Shopify</li>
<li className="w-full my-1">Prestashop </li>
<li className="w-full my-1">ShipStation</li>
</ol>
</div>
<p className="my-3 leading-relaxed tracking-wide text-justify sm:mx-2 md:mx-4">
<span className="pl-2">I</span> love how these platforms bring
everything from setting up Hostname, Domains, Email, Search Engine
Optimization, all in one place. There's definetly much to do!
</p>
<p className="mt-5 leading-relaxed tracking-wide text-justify sm:mx-2 md:mx-4">
<span className="pl-2">C</span>heck out the Wix Landing Page, and my
<a
href="https://www.upwork.com/freelancers/~016e40a81aa39e3594"
target="_blank"
rel="noopener noreferrer"
>
{" "}
<span className="text-white underline">Upwork Profile</span>
</a>{" "}
if you're at all interested in Web Solutions.
</p>
</div>
{/* Footer section */}
<div className="mt-2 text-center text-grey-darker">
<h3 className="">
<a
className="block w-full py-4 mt-8 tracking-wide text-gray-300 border rounded shadow-md brand-blue-gradient hover:border-white hover:border-2 hover:text-white hover:shadow-lg"
href="https://gregasoares.wixsite.com/portfolio"
target="_blank"
rel="noopener noreferrer"
>
Go To Wix Landing Page
</a>
</h3>
</div>
</div>
);
};
|
ToxicJojo/github-issue-visualizer | app/js/filter/filter-date.js | // Filtes for issues that have been created between dateStart and dateEnd
const filterDate = (issues, dateStart, dateEnd) => {
return issues.filter((issue) => {
const issueDate = new Date(issue.created_at)
return (issueDate.getTime() > dateStart.getTime() && issueDate.getTime() < dateEnd.getTime())
})
}
export default {
filterDate,
} |
nodeca/nodeca.core | server/common/core/token_live.js | // - Create new token on client request
// - Inject token to runtime for http requests
// - Save token or update TLL
//
'use strict';
const createToken = require('nodeca.core/lib/app/random_token');
const MAX_LIVE_TOKEN_TTL = 1 * 60 * 60; // 1 hour
module.exports = function (N, apiPath) {
N.validate(apiPath, {});
// Create new token
//
N.wire.on(apiPath, function token_live_create(env) {
// If no session - skip
if (!env.session) return;
let token = createToken();
env.session.token_live = token;
env.res.token_live = token;
});
// Inject token to runtime for http requests
//
N.wire.after('server_chain:http:*', function token_live_inject(env) {
// If no token or no session - skip
if (!env.session || !env.session.token_live) return;
env.runtime.token_live = env.session.token_live;
});
// Save token or update TLL
//
N.wire.after('server_chain:*', { priority: 90, ensure: true }, async function token_live_save(env) {
// If no token or no session - skip
if (!env.session || !env.session.token_live) return;
let ttl = Math.min(MAX_LIVE_TOKEN_TTL, env.session_ttl);
// - save token here because we couldn't know session_id earlier
// - if same record already exists redis will only update TTL
await N.redis.setex('token_live:' + env.session.token_live, ttl, env.session_id);
});
};
|
xterminal86/nrogue | src/states/look-input-state.h | <gh_stars>1-10
#ifndef LOOKINPUTSTATE_H
#define LOOKINPUTSTATE_H
#include "gamestate.h"
#include "position.h"
class Player;
class GameObject;
class LookInputState : public GameState
{
public:
void Init() override;
void HandleInput() override;
void Update(bool forceUpdate = false) override;
void Prepare() override;
private:
void MoveCursor(int dx, int dy);
void DrawCursor();
void DisplayMonsterStats();
bool CheckPlayer();
GameObject* CheckActor();
const std::vector<GameObject*> CheckGameObjects();
#ifdef DEBUG_BUILD
void PrintDebugInfo();
#endif
Player* _playerRef;
Position _cursorPosition;
#ifdef DEBUG_BUILD
const StringsArray2D _debugInfo =
{
"'ENTER' - display actor stats",
"",
"'f' - player's potential field value here",
"'d' - destroy static object here",
"'D' - destroy updatable game object here"
};
std::string _distanceField;
#endif
};
#endif // LOOKINPUTSTATE_H
|
lunny/xcodis | Godeps/_workspace/src/github.com/bsm/redeo/request.go | package redeo
import (
"bufio"
"io"
"strconv"
"strings"
)
// Request contains a command, arguments, and client information
type Request struct {
Name string `json:"name"`
Args []string `json:"args,omitempty"`
Ctx interface{} `json:"ctx,omitempty"`
client *Client
}
// Client returns the client
func (r *Request) Client() *Client {
return r.client
}
// ParseRequest parses a new request from a buffered connection
func ParseRequest(rd *bufio.Reader) (*Request, error) {
line, err := rd.ReadString('\n')
if err != nil {
return nil, io.EOF
} else if len(line) < 3 {
return nil, io.EOF
}
// Truncate CRLF
line = line[:len(line)-2]
// Return if inline
if line[0] != binASTERISK {
return &Request{Name: strings.ToLower(line)}, nil
}
argc, err := strconv.Atoi(line[1:])
if err != nil {
return nil, ErrInvalidRequest
}
args := make([]string, argc)
for i := 0; i < argc; i++ {
if args[i], err = parseArgument(rd); err != nil {
return nil, err
}
}
return &Request{Name: strings.ToLower(args[0]), Args: args[1:]}, nil
}
func parseArgument(rd *bufio.Reader) (string, error) {
line, err := rd.ReadString('\n')
if err != nil {
return "", io.EOF
} else if len(line) < 3 {
return "", io.EOF
} else if line[0] != binDOLLAR {
return "", ErrInvalidRequest
}
blen, err := strconv.Atoi(line[1 : len(line)-2])
if err != nil {
return "", ErrInvalidRequest
}
buf := make([]byte, blen+2)
if _, err := io.ReadFull(rd, buf); err != nil {
return "", io.EOF
}
return string(buf[:blen]), nil
}
|
lkd062819/decision | decision-core/src/main/java/com/decision/core/plugin/constant/DecisionConstant.java | package com.decision.core.plugin.constant;
/**
* @Author KD
* @Date 2020/12/22 14:47
*/
public class DecisionConstant {
public static final String COMMON = "common";
public static final String DECISION_TRACE = "decision-trace";
public static final String DECISION_HEADER_VERSION = "decision.header.version";
public static final String DECISION_HEADER_ENV = "decision.header.env";
public static final String DECISION = "decision";
}
|
walterfan/snippets | python/decorator_test.py | registry = []
def register(func):
print("register function {}".format(func))
registry.append(func)
return func
@register
def hello():
print("hello")
@register
def world():
print("world")
if __name__ == '__main__':
hello()
world()
for func in registry:
print("there is a registered {}".format(func)) |
esmanda3w/tp | src/main/java/seedu/pivot/model/investigationcase/UniqueCaseList.java | package seedu.pivot.model.investigationcase;
import static java.util.Objects.requireNonNull;
import static seedu.pivot.commons.util.CollectionUtil.requireAllNonNull;
import java.util.Iterator;
import java.util.List;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import seedu.pivot.model.investigationcase.exceptions.CaseNotFoundException;
import seedu.pivot.model.investigationcase.exceptions.DuplicateCaseException;
/**
* A list of cases that enforces uniqueness between its elements and does not allow nulls.
* A case is considered unique by comparing using {@code Case#isSameCase(Case)}. As such, adding and updating of
* cases uses Case#isSameCase(Case) for equality so as to ensure that the case being added or updated is
* unique in terms of identity in the UniqueCaseList. However, the removal of a case uses Case#equals(Object) so
* as to ensure that the case with exactly the same fields will be removed.
*
* Supports a minimal set of list operations.
*
* @see Case#isSameCase(Case)
*/
public class UniqueCaseList implements Iterable<Case> {
private final ObservableList<Case> internalList = FXCollections.observableArrayList();
private final ObservableList<Case> internalUnmodifiableList =
FXCollections.unmodifiableObservableList(internalList);
/**
* Returns true if the list contains an equivalent case as the given argument.
*/
public boolean contains(Case toCheck) {
requireNonNull(toCheck);
return internalList.stream().anyMatch(toCheck::isSameCase);
}
/**
* Adds a case to the list.
* The case must not already exist in the list.
*/
public void add(Case toAdd) {
requireNonNull(toAdd);
if (contains(toAdd)) {
throw new DuplicateCaseException();
}
internalList.add(toAdd);
}
/**
* Replaces the case {@code target} in the list with {@code editedCase}.
* {@code target} must exist in the list.
* The case identity of {@code editedCase} must not be the same as another existing case in the list.
*/
public void setCase(Case target, Case editedCase) {
requireAllNonNull(target, editedCase);
int index = internalList.indexOf(target);
if (index == -1) {
throw new CaseNotFoundException();
}
if (!target.isSameCase(editedCase) && contains(editedCase)) {
throw new DuplicateCaseException();
}
internalList.set(index, editedCase);
}
/**
* Removes the equivalent case from the list.
* The case must exist in the list.
*/
public void remove(Case toRemove) {
requireNonNull(toRemove);
if (!internalList.remove(toRemove)) {
throw new CaseNotFoundException();
}
}
public void setCases(UniqueCaseList replacement) {
requireNonNull(replacement);
internalList.setAll(replacement.internalList);
}
/**
* Replaces the contents of this list with {@code cases}.
* {@code cases} must not contain duplicate cases.
*/
public void setCases(List<Case> cases) {
requireAllNonNull(cases);
if (!casesAreUnique(cases)) {
throw new DuplicateCaseException();
}
internalList.setAll(cases);
}
/**
* Returns the backing list as an unmodifiable {@code ObservableList}.
*/
public ObservableList<Case> asUnmodifiableObservableList() {
return internalUnmodifiableList;
}
@Override
public Iterator<Case> iterator() {
return internalList.iterator();
}
@Override
public boolean equals(Object other) {
return other == this // short circuit if same object
|| (other instanceof UniqueCaseList // instanceof handles nulls
&& internalList.equals(((UniqueCaseList) other).internalList));
}
@Override
public int hashCode() {
return internalList.hashCode();
}
/**
* Returns true if {@code cases} contains only unique cases.
*/
private boolean casesAreUnique(List<Case> cases) {
for (int i = 0; i < cases.size() - 1; i++) {
for (int j = i + 1; j < cases.size(); j++) {
if (cases.get(i).isSameCase(cases.get(j))) {
return false;
}
}
}
return true;
}
}
|
banwenmang/BBCamera | btime/src/main/java/com/shouyiren/btime/webser/identification/api/IdentificationSmsLog.java | package com.shouyiren.btime.webser.identification.api;
import java.io.Serializable;
import java.util.Date;
/**
* 作者:ZhouJianxing on 2017/7/1 10:51
* email:<EMAIL>
*/
public class IdentificationSmsLog
implements Serializable {
private static final long serialVersionUID = -6425455354358738376L;
private Date addTime;
private Long id;
private String phone;
private String secret;
public Date getAddTime() {
return this.addTime;
}
public Long getId() {
return this.id;
}
public String getPhone() {
return this.phone;
}
public String getSecret() {
return this.secret;
}
public void setAddTime(Date paramDate) {
this.addTime = paramDate;
}
public void setId(Long paramLong) {
this.id = paramLong;
}
public void setPhone(String paramString) {
this.phone = paramString;
}
public void setSecret(String paramString) {
this.secret = paramString;
}
}
|
Klaital/vitasa-web | db/migrate/20181126230622_add_active_to_sites.rb | class AddActiveToSites < ActiveRecord::Migration[5.0]
def change
change_table :sites do |t|
t.boolean :active, default: true
end
end
end
|
PRASAD-DANGARE/JAVA | Program207.java | ///////////////////////////////////////////////////////////
//
// Description : Accept String From User And Check It Is Anagram Or Not V1
// Input : Int, Str
// Output : Int, Str
// Author : <NAME>
// Date : 30 May 2021
//
///////////////////////////////////////////////////////////
/*
"abcde" "cebad"
"hello" "loleh"
"india" "iinda"
*/
import java.util.*;
class StringX
{
boolean CheckAnagram(String str1, String str2) // complexcity is 2N
{
int i = 0;
int count1[] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; // create array of 26 elements
int count2[] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
if(str1.length() != str2.length()) // filter
{
return false;
}
char arr[] = str1.toCharArray(); // convert into character array
char brr[] = str2.toCharArray();
for(i = 0; i < arr.length; i++)
{
count1[arr[i]-'a']++; // count1[98(b) - 97(a)]++ = count1[1]++ or count1[arr['a']-'a'] = [0] asel tar index ha ++ kar count1[0]++
} // its like hashtable
for(i = 0; i < brr.length; i++)
{
count2[brr[i]-'a']++; // count1, ani count2 madhe apan character count kale
}
for(i = 0; i < 26; i++)
{
if(count1[i] != count2[i]) // jar dogancha cha count ha same nasel tar break
{
break;
}
}
if(i == 26) // jar loop ha without break asel tar i he 26 parant janar or we check that i goes till 26 or not
{
return true;
}
else
{
return false;
}
}
}
class Program207
{
public static void main(String arg[])
{
Scanner sobj = new Scanner(System.in);
System.out.println("Please enter first string");
String str1 = sobj.nextLine();
System.out.println("Please enter second string");
String str2 = sobj.nextLine();
StringX obj = new StringX();
boolean bRet = obj.CheckAnagram(str1,str2);
if(bRet == true)
System.out.println("Strings are anagram");
else
System.out.println("Strings are not anagram");
}
} |
syntheticgio/fda-hive | vlib/ssci/math/nr/nr_pwt.cpp | /*
* ::718604!
*
* Copyright(C) November 20, 2014 U.S. Food and Drug Administration
* Authors: Dr. <NAME> (1), Dr. <NAME> (2), et al
* Affiliation: Food and Drug Administration (1), George Washington University (2)
*
* All rights Reserved.
*
* The MIT License (MIT)
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#include <ssci/math/nr/nrutil.h>
#include <math.h>
void sMathNR::pwt(real a[], udx n, idx isign)
{
real ai,ai1,*wksp;
udx i,ii,j,jf,jr,k,n1,ni,nj,nh,nmod;
if (n < 4) return;
wksp=sMathNRUtil::vector(1,n);
nmod=wfilt.ncof*n;
n1=n-1;
nh=n >> 1;
for (j=1;j<=n;j++) wksp[j]=0.0;
if (isign >= 0) {
for (ii=1,i=1;i<=n;i+=2,ii++) {
ni=i+nmod+wfilt.ioff;
nj=i+nmod+wfilt.joff;
for (k=1;k<=wfilt.ncof;k++) {
jf=n1 & (ni+k);
jr=n1 & (nj+k);
wksp[ii] += wfilt.cc[k]*a[jf+1];
wksp[ii+nh] += wfilt.cr[k]*a[jr+1];
}
}
} else {
for (ii=1,i=1;i<=n;i+=2,ii++) {
ai=a[ii];
ai1=a[ii+nh];
ni=i+nmod+wfilt.ioff;
nj=i+nmod+wfilt.joff;
for (k=1;k<=wfilt.ncof;k++) {
jf=(n1 & (ni+k))+1;
jr=(n1 & (nj+k))+1;
wksp[jf] += wfilt.cc[k]*ai;
wksp[jr] += wfilt.cr[k]*ai1;
}
}
}
for (j=1;j<=n;j++) a[j]=wksp[j];
sMathNRUtil::free_vector(wksp,1,n);
}
sMathNR::wavefilt sMathNR::wfilt;
void sMathNR::pwtset(idx n)
{
static idx prvN=-1;
if(prvN==n)return;
idx k;
real sig = -1.0;
static real c4[5]={0.0,0.4829629131445341,0.8365163037378079,
0.2241438680420134,-0.1294095225512604};
static real c12[13]={0.0,0.111540743350, 0.494623890398, 0.751133908021,
0.315250351709,-0.226264693965,-0.129766867567,
0.097501605587, 0.027522865530,-0.031582039318,
0.000553842201, 0.004777257511,-0.001077301085};
static real c20[21]={0.0,0.026670057901, 0.188176800078, 0.527201188932,
0.688459039454, 0.281172343661,-0.249846424327,
-0.195946274377, 0.127369340336, 0.093057364604,
-0.071394147166,-0.029457536822, 0.033212674059,
0.003606553567,-0.010733175483, 0.001395351747,
0.001992405295,-0.000685856695,-0.000116466855,
0.000093588670,-0.000013264203};
static real c4r[5],c12r[13],c20r[21];
wfilt.ncof=n;
if (n == 4) {
wfilt.cc=c4;
wfilt.cr=c4r;
}
else if (n == 12) {
wfilt.cc=c12;
wfilt.cr=c12r;
}
else if (n == 20) {
wfilt.cc=c20;
wfilt.cr=c20r;
}
else sMathNRUtil::nrerror("unimplemented value n in pwtset");
for (k=1;k<=n;k++) {
wfilt.cr[wfilt.ncof+1-k]=sig*wfilt.cc[k];
sig = -sig;
}
wfilt.ioff = wfilt.joff = -(n >> 1);
prvN=n;
}
|
hankaibo/myspringboot | src/main/java/cn/mypandora/springboot/core/exception/LowerCaseClassNameResolver.java | package cn.mypandora.springboot.core.exception;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.databind.jsontype.impl.TypeIdResolverBase;
/**
* LowerCaseClassNameResolver
*
* @author hankaibo
* @date 2020/3/29
*/
public class LowerCaseClassNameResolver extends TypeIdResolverBase {
@Override
public String idFromValue(Object o) {
return o.getClass().getSimpleName().toLowerCase();
}
@Override
public String idFromValueAndType(Object o, Class<?> aClass) {
return idFromValue(o);
}
@Override
public JsonTypeInfo.Id getMechanism() {
return JsonTypeInfo.Id.CUSTOM;
}
}
|
sadhna-rana/react_small_app | app/containers/WeatherForcaste/selectors.js | <filename>app/containers/WeatherForcaste/selectors.js
import { createSelector } from 'reselect';
/**
* Direct selector to the weatherForcaste state domain
*/
const selectWeatherForcasteDomain = (state) => state.get('weatherForcaste');
/**
* Other specific selectors
*/
/**
* Default selector used by WeatherForcaste
*/
const makeSelectWeatherForcaste = () => createSelector(
selectWeatherForcasteDomain,
(substate) => substate.toJS()
);
const makeSelectWeatherLocation = () => createSelector(
selectWeatherForcasteDomain,
(substate) => substate.get('city')
);
const makeSelectWeatherDetails = () => createSelector(
selectWeatherForcasteDomain,
(substate) => substate.get('weather_details')
);
const makeSelectWeatherApiError = () => createSelector(
selectWeatherForcasteDomain,
(substate) => substate.get('weather_api_error')
);
export default makeSelectWeatherForcaste;
export {
selectWeatherForcasteDomain,
makeSelectWeatherLocation,
makeSelectWeatherDetails,
makeSelectWeatherApiError,
};
|
banderous/nfdiv-case-api | src/main/java/uk/gov/hmcts/divorce/caseworker/event/page/AlternativeServicePaymentConfirmation.java | <filename>src/main/java/uk/gov/hmcts/divorce/caseworker/event/page/AlternativeServicePaymentConfirmation.java
package uk.gov.hmcts.divorce.caseworker.event.page;
import uk.gov.hmcts.divorce.common.ccd.CcdPageConfiguration;
import uk.gov.hmcts.divorce.common.ccd.PageBuilder;
import uk.gov.hmcts.divorce.divorcecase.model.AlternativeService;
import uk.gov.hmcts.divorce.divorcecase.model.CaseData;
public class AlternativeServicePaymentConfirmation implements CcdPageConfiguration {
@Override
public void addTo(PageBuilder pageBuilder) {
pageBuilder.page("alternativeServicePayment")
.pageLabel("Payment - service application payment")
.complex(CaseData::getAlternativeService)
.mandatory(AlternativeService::getPaymentMethod)
.mandatory(AlternativeService::getFeeAccountNumber, "paymentMethod = \"feePayByAccount\"")
.optional(AlternativeService::getFeeAccountReferenceNumber, "paymentMethod = \"feePayByAccount\"")
.mandatory(AlternativeService::getHelpWithFeesReferenceNumber, "paymentMethod = \"feePayByHelp\"")
.done();
}
}
|
Lorak-mmk/Kalafior | libecho/src/QTInitializer.cc | #include "QTInitializer.h"
QTInitializer::QTInitializer(int a_argc, char **a_argv) {
if (QCoreApplication::instance() == nullptr) {
app = new QCoreApplication(a_argc, a_argv);
}
qSetMessagePattern("[%{type}] %{function} Thread %{threadid} - %{message}");
}
QTInitializer::~QTInitializer() {
delete app;
}
|
HagenSR/byte_le_royale_2022 | game/test_suite/tests/objects/test_bullet.py | import unittest
from game.common.moving.damaging import bullet
from game.common.moving.damaging.bullet import Bullet
from game.common.stats import GameStats
from game.common.hitbox import Hitbox
class TestBullet(unittest.TestCase):
def setUp(self):
self.bltObj = Bullet((25, 25), False, range=5,
damage=5, heading=1, speed=1, health=5,
hitbox=Hitbox(5, 5, (5, 5)), collidable=True)
def test_set_get_termination_valid(self):
self.bltObj.termination = (10, 10)
self.assertEqual(self.bltObj.termination, (10, 10))
def test_set_get_termination_invalid_x_low(self):
self.assertRaises(Exception, self.setTermination, (-5, 10))
def test_set_get_termination_invalid_x_high(self):
self.assertRaises(Exception, self.setTermination, (501, 10))
def test_set_get_termination_invalid_y_low(self):
self.assertRaises(Exception, self.setTermination, (10, -5))
def test_set_get_termination_invalid_y_high(self):
self.assertRaises(Exception, self.setTermination, (10, 501))
def test_set_get_termination_boundary_low(self):
self.bltObj.termination = (0, 0)
self.assertEqual(
self.bltObj.termination, (0, 0))
def test_set_get_termination_boundary_high(self):
self.bltObj.termination = (
GameStats.game_board_width,
GameStats.game_board_height)
self.assertEqual(
self.bltObj.termination,
(GameStats.game_board_width, GameStats.game_board_height))
def test_bullet_obj_parent_params(self):
testBlt = Bullet(
termination=(10, 10),
object_hit=True,
range=10,
damage=10,
heading=1,
speed=10,
health=1,
hitbox=Hitbox(
10,
10,
(10,
10)),
collidable=True)
self.assertIsNotNone(testBlt.range)
self.assertIsNotNone(testBlt.damage)
self.assertIsNotNone(testBlt.heading)
self.assertIsNotNone(testBlt.speed)
self.assertIsNotNone(testBlt.hitbox.position)
self.assertIsNotNone(testBlt.hitbox)
self.assertIsNotNone(testBlt.collidable)
# newTerm set as xy tuple
def setTermination(self, newTerm):
self.bltObj.termination = newTerm
if __name__ == '__main__':
unittest.main
|
google-ar/chromium | third_party/WebKit/Source/modules/shapedetection/DetectedText.cpp | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "modules/shapedetection/DetectedText.h"
#include "core/dom/DOMRect.h"
namespace blink {
DetectedText* DetectedText::create() {
return new DetectedText(emptyString(), DOMRect::create());
}
DetectedText* DetectedText::create(String rawValue, DOMRect* boundingBox) {
return new DetectedText(rawValue, boundingBox);
}
const String& DetectedText::rawValue() const {
return m_rawValue;
}
DOMRect* DetectedText::boundingBox() const {
return m_boundingBox.get();
}
DetectedText::DetectedText(String rawValue, DOMRect* boundingBox)
: m_rawValue(rawValue), m_boundingBox(boundingBox) {}
DEFINE_TRACE(DetectedText) {
visitor->trace(m_boundingBox);
}
} // namespace blink
|
joel-rich/ShieldBattery | server/migrations/20200518014720-fixed-rename-race-enum-values.js | <filename>server/migrations/20200518014720-fixed-rename-race-enum-values.js
// We rename the `race` enum in this migration to be more in line with what we use in the rest of
// the app. Note that Postgres 10+ has better syntax for doing this but we unfortunately still
// support older versions.
exports.up = async function (db) {
await db.runSql(`
ALTER TABLE matchmaking_preferences ALTER COLUMN race TYPE varchar(64);
ALTER TABLE matchmaking_preferences ALTER COLUMN alternate_race TYPE varchar(64);
DROP TYPE race;
UPDATE matchmaking_preferences SET race = 'z' WHERE race = 'zerg';
UPDATE matchmaking_preferences SET race = 't' WHERE race = 'terran';
UPDATE matchmaking_preferences SET race = 'p' WHERE race = 'protoss';
UPDATE matchmaking_preferences SET race = 'r' WHERE race = 'random';
UPDATE matchmaking_preferences SET alternate_race = 'z' WHERE alternate_race = 'zerg';
UPDATE matchmaking_preferences SET alternate_race = 't' WHERE alternate_race = 'terran';
UPDATE matchmaking_preferences SET alternate_race = 'p' WHERE alternate_race = 'protoss';
UPDATE matchmaking_preferences SET alternate_race = 'r' WHERE alternate_race = 'random';
CREATE TYPE race AS ENUM('z', 't', 'p', 'r');
ALTER TABLE matchmaking_preferences ALTER COLUMN race TYPE race USING race::race;
ALTER TABLE matchmaking_preferences ALTER COLUMN alternate_race TYPE race
USING alternate_race::race;
`)
}
exports.down = async function (db) {
await db.runSql(`
ALTER TABLE matchmaking_preferences ALTER COLUMN race TYPE varchar(64);
ALTER TABLE matchmaking_preferences ALTER COLUMN alternate_race TYPE varchar(64);
DROP TYPE race;
UPDATE matchmaking_preferences SET race = 'zerg' WHERE race = 'z';
UPDATE matchmaking_preferences SET race = 'terran' WHERE race = 't';
UPDATE matchmaking_preferences SET race = 'protoss' WHERE race = 'p';
UPDATE matchmaking_preferences SET race = 'random' WHERE race = 'r';
UPDATE matchmaking_preferences SET alternate_race = 'zerg' WHERE alternate_race = 'z';
UPDATE matchmaking_preferences SET alternate_race = 'terran' WHERE alternate_race = 't';
UPDATE matchmaking_preferences SET alternate_race = 'protoss' WHERE alternate_race = 'p';
UPDATE matchmaking_preferences SET alternate_race = 'random' WHERE alternate_race = 'r';
CREATE TYPE race AS ENUM('zerg', 'terran', 'protoss', 'random');
ALTER TABLE matchmaking_preferences ALTER COLUMN race TYPE race USING race::race;
ALTER TABLE matchmaking_preferences ALTER COLUMN alternate_race TYPE race
USING alternate_race::race;
`)
}
exports._meta = {
version: 1,
}
|
immbudden/buddeen | node_modules/core-js-pure/features/map/key-by.js | 'use strict';
require('../../modules/es.map');
require('../../modules/esnext.map.key-by');
var Map = require('../../internals/path').Map;
var mapKeyBy = Map.keyBy;
module.exports = function keyBy(source, iterable, keyDerivative) {
return mapKeyBy.call(typeof this === 'function' ? this : Map, source, iterable, keyDerivative);
};
|
cxcorp/MemWrite | lacuna/lacuna-core/src/test/java/cx/corp/lacuna/core/windows/winapi/MockPsapi.java | package cx.corp.lacuna.core.windows.winapi;
import com.sun.jna.ptr.IntByReference;
public class MockPsapi implements Psapi {
private boolean enumProcessesReturnValue = true;
private int[] enumProcessesPids = new int[0];
private int enumProcessesBytesReturned = 0;
public void setEnumProcessesPids(int[] pids) {
this.enumProcessesPids = pids;
}
public void setEnumProcessesReturnValue(boolean val) {
this.enumProcessesReturnValue = val;
}
public void setEnumProcessesBytesReturned(int bytesReturned) {
this.enumProcessesBytesReturned = bytesReturned;
}
@Override
public boolean enumProcesses(int[] pids, int pidsLength, IntByReference bytesReturned) {
if (!enumProcessesReturnValue) {
return false;
}
int limit = Math.min(this.enumProcessesPids.length, pidsLength);
System.arraycopy(this.enumProcessesPids, 0, pids, 0, limit);
bytesReturned.setValue(enumProcessesBytesReturned);
return true;
}
@Override
public int getModuleFileNameExW(int hProcess, int hModule, char[] charBuf, int bufSize) {
throw new UnsupportedOperationException("Not implemented");
}
}
|
suomenriistakeskus/oma-riista-web | src/generated/java/fi/riista/sql/SQVesialue.java | <reponame>suomenriistakeskus/oma-riista-web
package fi.riista.sql;
import static com.querydsl.core.types.PathMetadataFactory.*;
import com.querydsl.core.types.dsl.*;
import com.querydsl.core.types.PathMetadata;
import javax.annotation.Generated;
import com.querydsl.core.types.Path;
import com.querydsl.sql.ColumnMetadata;
import java.sql.Types;
import com.querydsl.sql.spatial.RelationalPathSpatial;
import com.querydsl.spatial.*;
/**
* SQVesialue is a Querydsl query type for SQVesialue
*/
@Generated("com.querydsl.sql.codegen.MetaDataSerializer")
public class SQVesialue extends RelationalPathSpatial<SQVesialue> {
private static final long serialVersionUID = -566803821;
public static final SQVesialue vesialue = new SQVesialue("vesialue");
public final NumberPath<Double> ainlahde = createNumber("ainlahde", Double.class);
public final NumberPath<Double> aluejakoon = createNumber("aluejakoon", Double.class);
public final NumberPath<Double> attr2 = createNumber("attr2", Double.class);
public final NumberPath<Double> attr3 = createNumber("attr3", Double.class);
public final GeometryPath<org.geolatte.geom.Geometry> geom = createGeometry("geom", org.geolatte.geom.Geometry.class);
public final NumberPath<Integer> gid = createNumber("gid", Integer.class);
public final NumberPath<Double> kartoglk = createNumber("kartoglk", Double.class);
public final NumberPath<Double> kohdeoso = createNumber("kohdeoso", Double.class);
public final NumberPath<Double> korarv = createNumber("korarv", Double.class);
public final NumberPath<Double> korkeus = createNumber("korkeus", Double.class);
public final NumberPath<Double> kortar = createNumber("kortar", Double.class);
public final NumberPath<Double> kulkutapa = createNumber("kulkutapa", Double.class);
public final StringPath kuolhetki = createString("kuolhetki");
public final NumberPath<Double> luokka = createNumber("luokka", Double.class);
public final NumberPath<Double> ryhma = createNumber("ryhma", Double.class);
public final NumberPath<Double> siirtDx = createNumber("siirtDx", Double.class);
public final NumberPath<Double> siirtDy = createNumber("siirtDy", Double.class);
public final NumberPath<Double> suunta = createNumber("suunta", Double.class);
public final StringPath syntyhetki = createString("syntyhetki");
public final NumberPath<Double> tastar = createNumber("tastar", Double.class);
public final StringPath teksti = createString("teksti");
public final NumberPath<Double> versuh = createNumber("versuh", Double.class);
public final com.querydsl.sql.PrimaryKey<SQVesialue> vesialuePkey = createPrimaryKey(gid);
public SQVesialue(String variable) {
super(SQVesialue.class, forVariable(variable), "public", "vesialue");
addMetadata();
}
public SQVesialue(String variable, String schema, String table) {
super(SQVesialue.class, forVariable(variable), schema, table);
addMetadata();
}
public SQVesialue(String variable, String schema) {
super(SQVesialue.class, forVariable(variable), schema, "vesialue");
addMetadata();
}
public SQVesialue(Path<? extends SQVesialue> path) {
super(path.getType(), path.getMetadata(), "public", "vesialue");
addMetadata();
}
public SQVesialue(PathMetadata metadata) {
super(SQVesialue.class, metadata, "public", "vesialue");
addMetadata();
}
public void addMetadata() {
addMetadata(ainlahde, ColumnMetadata.named("ainlahde").withIndex(10).ofType(Types.DOUBLE).withSize(17).withDigits(17));
addMetadata(aluejakoon, ColumnMetadata.named("aluejakoon").withIndex(14).ofType(Types.DOUBLE).withSize(17).withDigits(17));
addMetadata(attr2, ColumnMetadata.named("attr2").withIndex(20).ofType(Types.DOUBLE).withSize(17).withDigits(17));
addMetadata(attr3, ColumnMetadata.named("attr3").withIndex(21).ofType(Types.DOUBLE).withSize(17).withDigits(17));
addMetadata(geom, ColumnMetadata.named("geom").withIndex(22).ofType(Types.OTHER).withSize(2147483647).notNull());
addMetadata(gid, ColumnMetadata.named("gid").withIndex(1).ofType(Types.INTEGER).withSize(10).notNull());
addMetadata(kartoglk, ColumnMetadata.named("kartoglk").withIndex(13).ofType(Types.DOUBLE).withSize(17).withDigits(17));
addMetadata(kohdeoso, ColumnMetadata.named("kohdeoso").withIndex(9).ofType(Types.DOUBLE).withSize(17).withDigits(17));
addMetadata(korarv, ColumnMetadata.named("korarv").withIndex(7).ofType(Types.DOUBLE).withSize(17).withDigits(17));
addMetadata(korkeus, ColumnMetadata.named("korkeus").withIndex(19).ofType(Types.DOUBLE).withSize(17).withDigits(17));
addMetadata(kortar, ColumnMetadata.named("kortar").withIndex(6).ofType(Types.DOUBLE).withSize(17).withDigits(17));
addMetadata(kulkutapa, ColumnMetadata.named("kulkutapa").withIndex(8).ofType(Types.DOUBLE).withSize(17).withDigits(17));
addMetadata(kuolhetki, ColumnMetadata.named("kuolhetki").withIndex(12).ofType(Types.VARCHAR).withSize(8));
addMetadata(luokka, ColumnMetadata.named("luokka").withIndex(4).ofType(Types.DOUBLE).withSize(17).withDigits(17));
addMetadata(ryhma, ColumnMetadata.named("ryhma").withIndex(3).ofType(Types.DOUBLE).withSize(17).withDigits(17));
addMetadata(siirtDx, ColumnMetadata.named("siirt_dx").withIndex(17).ofType(Types.DOUBLE).withSize(17).withDigits(17));
addMetadata(siirtDy, ColumnMetadata.named("siirt_dy").withIndex(18).ofType(Types.DOUBLE).withSize(17).withDigits(17));
addMetadata(suunta, ColumnMetadata.named("suunta").withIndex(16).ofType(Types.DOUBLE).withSize(17).withDigits(17));
addMetadata(syntyhetki, ColumnMetadata.named("syntyhetki").withIndex(11).ofType(Types.VARCHAR).withSize(8));
addMetadata(tastar, ColumnMetadata.named("tastar").withIndex(5).ofType(Types.DOUBLE).withSize(17).withDigits(17));
addMetadata(teksti, ColumnMetadata.named("teksti").withIndex(2).ofType(Types.VARCHAR).withSize(80));
addMetadata(versuh, ColumnMetadata.named("versuh").withIndex(15).ofType(Types.DOUBLE).withSize(17).withDigits(17));
}
}
|
isuhao/xylsxyls-xueyelingshuang | src/dtwsAccount/dtwsAccount/TaskLogin.h | <filename>src/dtwsAccount/dtwsAccount/TaskLogin.h<gh_stars>1-10
#pragma once
#include "CTask/CTaskAPI.h"
class TaskLogin : public CTask{
public:
string account;
string password;
string bigServerName;
string smallServerName;
public:
TaskLogin();
public:
int Run();
void SuspendRun();
}; |
if1live/kanae | exchanges/reports.go | <filename>exchanges/reports.go
package exchanges
import (
"sort"
"strings"
"github.com/deckarep/golang-set"
"github.com/if1live/kanae/kanaelib"
"github.com/thrasher-/gocryptotrader/exchanges/poloniex"
)
type Report struct {
Asset string
Currency string
Rows []Exchange
ticker poloniex.PoloniexTicker
}
func reverseExchanges(a []Exchange) {
for i := len(a)/2 - 1; i >= 0; i-- {
opp := len(a) - 1 - i
a[i], a[opp] = a[opp], a[i]
}
}
func NewReport(asset, currency string, ticker poloniex.PoloniexTicker, rows []Exchange) (closed, opened *Report) {
// input data : date desc
ascRows := append([]Exchange(nil), rows...)
reverseExchanges(ascRows)
var myAmountAccum float64
lastZeroSumIdx := -1
for i, r := range ascRows {
if r.Type == ExchangeBuy {
myAmountAccum += r.MyAmount()
} else {
myAmountAccum -= r.Amount
}
if myAmountAccum <= float64(0) {
lastZeroSumIdx = i
}
}
if lastZeroSumIdx == -1 {
// closed exchange not exists
closed = nil
opened = &Report{
Asset: asset,
Currency: currency,
Rows: rows,
ticker: ticker,
}
return
}
closedRows := ascRows[:lastZeroSumIdx+1]
reverseExchanges(closedRows)
openedRows := ascRows[lastZeroSumIdx+1:]
reverseExchanges(openedRows)
if len(closedRows) == 0 {
closed = nil
} else {
closed = &Report{
Asset: asset,
Currency: currency,
Rows: closedRows,
ticker: ticker,
}
}
if len(openedRows) == 0 {
opened = nil
} else {
opened = &Report{
Asset: asset,
Currency: currency,
Rows: openedRows,
ticker: ticker,
}
}
return
}
func NewReports(tickers *kanaelib.TickerCache, rows []Exchange) (closedList, openedList []*Report) {
// find all asset-currency pairs
currencyPairSet := mapset.NewSet()
for _, e := range rows {
currencyPairSet.Add(e.CurrencyPair())
}
// sort asset-currency pairs
currencyPairs := []string{}
it := currencyPairSet.Iterator()
for elem := range it.C {
s := elem.(string)
currencyPairs = append(currencyPairs, s)
}
sort.Strings(currencyPairs)
// generate reports
closedList = []*Report{}
openedList = []*Report{}
for _, currencyPair := range currencyPairs {
tokens := strings.Split(currencyPair, "_")
asset := tokens[0]
currency := tokens[1]
selected := []Exchange{}
for _, r := range rows {
if r.Asset == asset && r.Currency == currency {
selected = append(selected, r)
}
}
ticker, _ := tickers.Get(asset, currency)
closed, opened := NewReport(asset, currency, ticker, selected)
if closed != nil {
closedList = append(closedList, closed)
}
if opened != nil {
openedList = append(openedList, opened)
}
}
return
}
func (r *Report) CurrentAsset() float64 {
var total float64
total += r.TotalAssetBuys()
total -= r.TotalAssetSells()
if total < 0 {
total = 0
}
return total
}
func (r *Report) EquivalentCurrency() float64 {
asset := r.CurrentAsset()
rate := r.ticker.Last
return asset * rate
}
func (r *Report) ProfitLoss() float64 {
var total float64
for _, r := range r.Rows {
switch r.Type {
case ExchangeBuy:
total -= r.MyTotal()
case ExchangeSell:
total += r.MyTotal()
}
}
return total
}
func (r *Report) TotalAssetBuys() float64 {
var total float64
for _, r := range r.Rows {
if r.Type == ExchangeBuy {
total += r.MyAmount()
}
}
return total
}
func (r *Report) TotalAssetSells() float64 {
var total float64
for _, r := range r.Rows {
if r.Type == ExchangeSell {
total += r.Amount
}
}
return total
}
func (r *Report) TotalCurrencyBuys() float64 {
var total float64
for _, r := range r.Rows {
if r.Type == ExchangeBuy {
total += r.MyTotal()
}
}
return total
}
func (r *Report) EarningRate() float64 {
return r.ProfitLoss() / r.TotalCurrencyBuys() * 100
}
type ClosedSummaryReport struct {
reports []*Report
}
func NewClosedSummaryReport(rs []*Report) *ClosedSummaryReport {
return &ClosedSummaryReport{
reports: rs,
}
}
func (r *ClosedSummaryReport) ProfitLoss() float64 {
var total float64
for _, r := range r.reports {
total += r.ProfitLoss()
}
return total
}
|
nwy140/TheWYGameDevelopmentFramework | WyFramework/Docs/html/class_game_framework_1_1_input_1_1_components_1_1_on_mouse_click_or_tap_load_level.js | var class_game_framework_1_1_input_1_1_components_1_1_on_mouse_click_or_tap_load_level =
[
[ "RunMethod", "class_game_framework_1_1_input_1_1_components_1_1_on_mouse_click_or_tap_load_level.html#a77a798542de79f9b60794191e59b1c79", null ],
[ "SceneName", "class_game_framework_1_1_input_1_1_components_1_1_on_mouse_click_or_tap_load_level.html#ad1b2fcf4b984d51bc534e682124d7e45", null ]
]; |
codefacts/Elastic-Components | elasta-pipeline/src/main/java/elasta/pipeline/jsonwalker/JsonObjectTraverseFilter.java | <filename>elasta-pipeline/src/main/java/elasta/pipeline/jsonwalker/JsonObjectTraverseFilter.java<gh_stars>1-10
package elasta.pipeline.jsonwalker;
/**
* Created by sohan on 3/27/2017.
*/
public interface JsonObjectTraverseFilter {
boolean filter(JsonObjectTraverseFunction.Params params);
}
|
Vetch0710/hospital | src/main/java/com/ruoyi/project/system/controller/WebPatientController.java | <gh_stars>0
package com.ruoyi.project.system.controller;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.exception.user.CaptchaException;
import com.ruoyi.common.exception.user.CaptchaExpireException;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.framework.security.LoginBody;
import com.ruoyi.framework.security.LoginUser;
import com.ruoyi.framework.security.service.SysLoginService;
import com.ruoyi.framework.security.service.TokenService;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.system.domain.Account;
import com.ruoyi.project.system.domain.SysMenu;
import com.ruoyi.project.system.domain.WebPatient;
import com.ruoyi.project.system.domain.vo.QueryVo;
import com.ruoyi.project.system.service.ISysLoginAccountService;
import com.ruoyi.project.system.service.WebPatientService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.*;
/**
* 登录验证
*
* @author ruoyi
*/
@RestController
@RequestMapping("/web/patient")
public class WebPatientController extends BaseController {
@Autowired
private WebPatientService webPatientService;
@Autowired
private SysLoginService sysLoginService;
@Autowired
private TokenService tokenService;
@ApiOperation("获取员工列表")
@PreAuthorize("@ss.hasPermi('web:patientinfo:list')")
@GetMapping("/list")
public AjaxResult list() {
LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
Account user = loginUser.getUser();
Long userId = user.getUserId();
WebPatient webPatient = webPatientService.selectPatientByUserId(userId);
AjaxResult ajax = AjaxResult.success();
ajax.put("patient", webPatient);
return ajax;
}
/**
* 修改用户
*/
@ApiOperation("修改用户")
@PreAuthorize("@ss.hasPermi('web:patientinfo:edit')")
@PutMapping
public AjaxResult edit(@Validated @RequestBody WebPatient webPatient)throws Exception {
// LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
// Account account = loginUser.getUser();
// webPatient.setUserId(account.getUserId());
return toAjax(webPatientService.updatePatient(webPatient));
}
/**
* 修改用户
*/
@ApiOperation("查看用户状态")
@GetMapping("/status")
public AjaxResult getStatus()throws Exception {
LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
Account account = loginUser.getUser();
List<String> result = webPatientService.updatePatientStatus(account.getUserId());
AjaxResult ajaxResult = new AjaxResult();
ajaxResult.put("status",result.get(0));
ajaxResult.put("banTime",result.get(1));
return ajaxResult;
}
}
|
huwlloyd-mmu/LockdownEngine | LJ2/Engine/DebugPrint.h | <filename>LJ2/Engine/DebugPrint.h
#pragma once
#include <string>
#include <list>
#include <SFML/Graphics.hpp>
namespace LE
{
class DebugPrint
{
sf::Font font;
const int fontSize = 30;
const int lifetime = 2000;
struct ConsoleLine
{
int age;
std::string text;
ConsoleLine() {}
ConsoleLine(const std::string& text) : text(text), age(0) {}
};
std::list<ConsoleLine> console;
sf::RenderWindow* window;
public:
DebugPrint()
{
// load font here
//font.loadFromFile("data/monogram.ttf");
}
void SetWindow(sf::RenderWindow* w) { window = w; }
void AddLine(const std::string& line)
{
console.push_back(ConsoleLine(line));
}
void Draw()
{
//run through, calculating size
auto it = console.begin();
int lines = 0;
int maxWidth = 0;
while (it != console.end())
{
it->age++;
if (it->age > lifetime)
it = console.erase(it);
else
{
++lines;
if (it->text.size() > maxWidth)
maxWidth = it->text.size();
++it;
}
}
sf::Text t;
t.setFont(font);
t.setFillColor(sf::Color(255, 0, 0, 255));
t.setCharacterSize(fontSize);
it = console.begin();
int x = 10;
int y = 10;
while (it != console.end())
{
t.setString(it->text);
t.setPosition(sf::Vector2f(x, y));
window->draw(t);
y += fontSize;
++it;
}
}
};
} |
VladTheEvilCat/mcheli-port-1.12.2 | mcheli/mcheli/aircraft/MCH_ItemFuel.java | /* */ package mcheli.mcheli.aircraft;
/* */
/* */ import mcheli.wrapper.W_Item;
/* */ import net.minecraft.entity.player.EntityPlayer;
/* */ import net.minecraft.item.ItemStack;
/* */ import net.minecraft.world.World;
/* */
/* */
/* */
/* */
/* */ public class MCH_ItemFuel
/* */ extends W_Item
/* */ {
/* */ public MCH_ItemFuel(int itemID) {
/* 15 */ super(itemID);
/* 16 */ func_77656_e(600);
/* 17 */ func_77625_d(1);
/* 18 */ setNoRepair();
/* 19 */ func_77664_n();
/* */ }
/* */
/* */
/* */ public ItemStack func_77659_a(ItemStack stack, World world, EntityPlayer player) {
/* 24 */ int damage = stack.func_77960_j();
/* 25 */ if (!world.field_72995_K && stack.func_77951_h() && !player.field_71075_bZ.field_75098_d) {
/* */
/* */
/* 28 */ refuel(stack, player, 1);
/* 29 */ refuel(stack, player, 0);
/* */ }
/* 31 */ return stack;
/* */ }
/* */
/* */
/* */ private void refuel(ItemStack stack, EntityPlayer player, int coalType) {
/* 36 */ ItemStack[] list = player.field_71071_by.field_70462_a;
/* 37 */ for (int i = 0; i < list.length; i++) {
/* */
/* 39 */ ItemStack is = list[i];
/* 40 */ if (is != null && is.func_77973_b() instanceof net.minecraft.item.ItemCoal && is.func_77960_j() == coalType) {
/* */
/* 42 */ for (int j = 0; is.field_77994_a > 0 && stack.func_77951_h() && j < 64; j++) {
/* */
/* 44 */ int damage = stack.func_77960_j() - ((coalType == 1) ? 75 : 100);
/* 45 */ if (damage < 0) damage = 0;
/* 46 */ stack.func_77964_b(damage);
/* 47 */ is.field_77994_a--;
/* */ }
/* */
/* 50 */ if (is.field_77994_a <= 0) list[i] = null;
/* */ }
/* */ }
/* */ }
/* */ }
/* Location: C:\Users\danie\Desktop\Mod Porting Tools\MC1.7.10_mcheli_1.0.3.jar!\mcheli\mcheli\aircraft\MCH_ItemFuel.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/ |
mforoni/ruby-launch-plan | rspec/3.mocks/image_flipper/spec/image_flipper_spec.rb | # frozen_string_literal: true
require 'spec_helper'
require File.expand_path('../image_flipper', __dir__)
RSpec.describe 'ImageFlipper' do
it 'calls the flip method with the correct arguments' do
mock = double('mini_magick')
expect(mock).to receive(:flip).with('ruby.jpg')
img = ImageFlipper.new(mock)
img.flip('ruby.jpg')
end
end
|
all-of-us/raw-data-repository | rdr_service/model/bq_workbench_researcher.py | from rdr_service.model.bq_participant_summary import BQGenderSchema, BQRaceSchema
from rdr_service.model.bq_base import BQTable, BQSchema, BQView, BQField, BQFieldTypeEnum, BQFieldModeEnum, \
BQRecordField
class BQDegreeSchema(BQSchema):
degree = BQField('degree', BQFieldTypeEnum.STRING, BQFieldModeEnum.NULLABLE)
degree_id = BQField('degree_id', BQFieldTypeEnum.INTEGER, BQFieldModeEnum.NULLABLE)
class BQSexAtBirthSchema(BQSchema):
sex_at_birth = BQField('sex_at_birth', BQFieldTypeEnum.STRING, BQFieldModeEnum.NULLABLE)
sex_at_birth_id = BQField('sex_at_birth_id', BQFieldTypeEnum.INTEGER, BQFieldModeEnum.NULLABLE)
class BQRWBResearcherSchema(BQSchema):
id = BQField('id', BQFieldTypeEnum.INTEGER, BQFieldModeEnum.REQUIRED)
created = BQField('created', BQFieldTypeEnum.DATETIME, BQFieldModeEnum.REQUIRED)
modified = BQField('modified', BQFieldTypeEnum.DATETIME, BQFieldModeEnum.REQUIRED)
user_source_id = BQField('user_source_id', BQFieldTypeEnum.INTEGER, BQFieldModeEnum.REQUIRED)
modified_time = BQField('modified_time', BQFieldTypeEnum.DATETIME, BQFieldModeEnum.REQUIRED)
state = BQField('state', BQFieldTypeEnum.STRING, BQFieldModeEnum.NULLABLE)
zip_code = BQField('zip_code', BQFieldTypeEnum.STRING, BQFieldModeEnum.NULLABLE)
country = BQField('country', BQFieldTypeEnum.STRING, BQFieldModeEnum.NULLABLE)
ethnicity = BQField('ethnicity', BQFieldTypeEnum.STRING, BQFieldModeEnum.NULLABLE)
ethnicity_id = BQField('ethnicity_id', BQFieldTypeEnum.INTEGER, BQFieldModeEnum.NULLABLE)
genders = BQRecordField('genders', schema=BQGenderSchema)
races = BQRecordField('races', schema=BQRaceSchema)
sex_at_birth = BQRecordField('sex_at_birth', schema=BQSexAtBirthSchema)
identifies_as_lgbtq = BQField('identifies_as_lgbtq', BQFieldTypeEnum.INTEGER, BQFieldModeEnum.NULLABLE)
lgbtq_identity = BQField('lgbtq_identity', BQFieldTypeEnum.STRING, BQFieldModeEnum.NULLABLE)
education = BQField('education', BQFieldTypeEnum.STRING, BQFieldModeEnum.NULLABLE)
education_id = BQField('education_id', BQFieldTypeEnum.INTEGER, BQFieldModeEnum.NULLABLE)
degrees = BQRecordField('degrees', schema=BQDegreeSchema)
disability = BQField('disability', BQFieldTypeEnum.STRING, BQFieldModeEnum.NULLABLE)
disability_id = BQField('disability_id', BQFieldTypeEnum.INTEGER, BQFieldModeEnum.NULLABLE)
creation_time = BQField('creation_time', BQFieldTypeEnum.DATETIME, BQFieldModeEnum.NULLABLE)
class BQRWBResearcher(BQTable):
""" Code BigQuery Table """
__tablename__ = 'rwb_researcher'
__schema__ = BQRWBResearcherSchema
class BQRWBResearcherView(BQView):
__viewname__ = 'v_rwb_researcher'
__viewdescr__ = 'Research Workbench Researcher View'
__pk_id__ = 'user_source_id'
__table__ = BQRWBResearcher
# We need to build a SQL statement with all fields except sub-tables and remove duplicates.
__sql__ = """
SELECT
%%FIELD_LIST%%
FROM (
SELECT *,
ROW_NUMBER() OVER (PARTITION BY user_source_id ORDER BY modified desc) AS rn
FROM `{project}`.{dataset}.rwb_researcher
) t
WHERE t.rn = 1
""".replace('%%FIELD_LIST%%', BQRWBResearcherSchema.get_sql_field_names(
exclude_fields=[
'genders',
'races',
'sex_at_birth',
'degrees'
])
)
class BQRWBResearcherGenderView(BQView):
__viewname__ = 'v_rwb_researcher_gender'
__viewdescr__ = 'Research Workbench Researcher Gender View'
__pk_id__ = 'user_source_id'
__table__ = BQRWBResearcher
__sql__ = """
SELECT t.id, t.created, t.modified, t.user_source_id, nt.*
FROM (
SELECT *,
ROW_NUMBER() OVER (PARTITION BY user_source_id ORDER BY modified desc) AS rn
FROM `{project}`.{dataset}.rwb_researcher
) t cross join unnest(genders) as nt
WHERE t.rn = 1
"""
class BQRWBResearcherRaceView(BQView):
__viewname__ = 'v_rwb_researcher_race'
__viewdescr__ = 'Research Workbench Researcher Race View'
__pk_id__ = 'user_source_id'
__table__ = BQRWBResearcher
__sql__ = """
SELECT t.id, t.created, t.modified, t.user_source_id, nt.*
FROM (
SELECT *,
ROW_NUMBER() OVER (PARTITION BY user_source_id ORDER BY modified desc) AS rn
FROM `{project}`.{dataset}.rwb_researcher
) t cross join unnest(races) as nt
WHERE t.rn = 1
"""
class BQRWBResearcherSexAtBirthView(BQView):
__viewname__ = 'v_rwb_researcher_sex_at_birth'
__viewdescr__ = 'Research Workbench Researcher Sex at Birth View'
__pk_id__ = 'user_source_id'
__table__ = BQRWBResearcher
__sql__ = """
SELECT t.id, t.created, t.modified, t.user_source_id, nt.*
FROM (
SELECT *,
ROW_NUMBER() OVER (PARTITION BY user_source_id ORDER BY modified desc) AS rn
FROM `{project}`.{dataset}.rwb_researcher
) t cross join unnest(sex_at_birth) as nt
WHERE t.rn = 1
"""
class BQRWBResearcherDegreeView(BQView):
__viewname__ = 'v_rwb_researcher_degree'
__viewdescr__ = 'Research Workbench Researcher Degree View'
__pk_id__ = 'user_source_id'
__table__ = BQRWBResearcher
__sql__ = """
SELECT t.id, t.created, t.modified, t.user_source_id, nt.*
FROM (
SELECT *,
ROW_NUMBER() OVER (PARTITION BY user_source_id ORDER BY modified desc) AS rn
FROM `{project}`.{dataset}.rwb_researcher
) t cross join unnest(degrees) as nt
WHERE t.rn = 1
"""
class BQRWBInstitutionalAffiliationsSchema(BQSchema):
id = BQField('id', BQFieldTypeEnum.INTEGER, BQFieldModeEnum.REQUIRED)
created = BQField('created', BQFieldTypeEnum.DATETIME, BQFieldModeEnum.REQUIRED)
modified = BQField('modified', BQFieldTypeEnum.DATETIME, BQFieldModeEnum.REQUIRED)
researcher_id = BQField('researcher_id', BQFieldTypeEnum.INTEGER, BQFieldModeEnum.REQUIRED)
institution = BQField('institution', BQFieldTypeEnum.STRING, BQFieldModeEnum.NULLABLE)
role = BQField('role', BQFieldTypeEnum.STRING, BQFieldModeEnum.NULLABLE)
non_academic_affiliation = BQField('non_academic_affiliation', BQFieldTypeEnum.STRING, BQFieldModeEnum.NULLABLE)
non_academic_affiliation_id = BQField('non_academic_affiliation_id', BQFieldTypeEnum.INTEGER,
BQFieldModeEnum.NULLABLE)
is_verified = BQField('is_verified', BQFieldTypeEnum.INTEGER, BQFieldModeEnum.NULLABLE)
class BQRWBInstitutionalAffiliations(BQTable):
""" Research Workbench Institutional Affiliations BigQuery Table """
__tablename__ = 'rwb_institutional_affiliations'
__schema__ = BQRWBInstitutionalAffiliationsSchema
class BQRWBInstitutionalAffiliationsView(BQView):
__viewname__ = 'v_rwb_institutional_affiliations'
__viewdescr__ = 'Research Workbench Institutional Affiliations View'
__pk_id__ = 'id'
__table__ = BQRWBInstitutionalAffiliations
|
believe563/PostLeanredCodes | MultiUploadDemo/app/src/main/java/com/fengjianghui/com/multiuploaddemo/MainActivity.java | package com.fengjianghui.com.multiuploaddemo;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
private ArrayList<File> files;
private Map<String, String> params;
Handler mHandler=new Handler(){
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
switch (msg.what) {
case UploadService.UPLOAD_SUCCESS:
Toast.makeText(MainActivity.this, "上传成功", Toast.LENGTH_LONG).show();
break;
default:
Toast.makeText(MainActivity.this, "上传失败", Toast.LENGTH_LONG).show();
}
super.handleMessage(msg);
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
files=new ArrayList<File>();
params=new HashMap<String, String>();
Log.i("number","lujing"+ Environment.getExternalStorageDirectory());
}
public void upload(View v) {
files.clear();
params.clear();
File file=new File(Environment.getExternalStorageDirectory(),"a.jpg");
File file2=new File(Environment.getExternalStorageDirectory(),"b.jpg");
File file3=new File(Environment.getExternalStorageDirectory(),"c.jpg");
files.add(file);
files.add(file2);
files.add(file3);
Log.i("number","三个文件分别是:"+files);
StringBuffer sbFileTypes=new StringBuffer();
for (File tempFile:files) {
String fileName=tempFile.getName();
sbFileTypes.append(getFileType(fileName));
}
Log.i("number", "fileTypes:" + sbFileTypes.toString());
params.put("fileTypes",sbFileTypes.toString());
params.put("method", "upload");
UploadService uploadService=new UploadService(mHandler);
uploadService.uploadFileToServer(params, files);
}
/**
* 获取文件的类型
* @param fileName :文件名
* @return 文件类型
*/
private String getFileType(String fileName) {
// TODO Auto-generated method stub
return fileName.substring(fileName.lastIndexOf("."), fileName.length());
}
public void outputtoast(String string) {
Toast.makeText(MainActivity.this, string,Toast.LENGTH_SHORT).show();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.