repo_name
stringlengths 6
101
| path
stringlengths 4
300
| text
stringlengths 7
1.31M
|
|---|---|---|
sotaoverride/backup
|
openbmc/build/tmp/deploy/sdk/witherspoon-2019-08-08/sysroots/armv6-openbmc-linux-gnueabi/usr/src/debug/glib-2.0/1_2.60.3-r0/glib-2.60.3/gio/gfileiostream.h
|
<gh_stars>0
/* GIO - GLib Input, Io and Streaming Library
*
* Copyright (C) 2006-2007 Red Hat, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General
* Public License along with this library; if not, see
* <http://www.gnu.org/licenses/>.
*
* Author: <NAME> <<EMAIL>>
*/
#ifndef __G_FILE_IO_STREAM_H__
#define __G_FILE_IO_STREAM_H__
#if !defined(__GIO_GIO_H_INSIDE__) && !defined(GIO_COMPILATION)
#error "Only <gio/gio.h> can be included directly."
#endif
#include <gio/giostream.h>
G_BEGIN_DECLS
#define G_TYPE_FILE_IO_STREAM (g_file_io_stream_get_type())
#define G_FILE_IO_STREAM(o) \
(G_TYPE_CHECK_INSTANCE_CAST((o), G_TYPE_FILE_IO_STREAM, GFileIOStream))
#define G_FILE_IO_STREAM_CLASS(k) \
(G_TYPE_CHECK_CLASS_CAST((k), G_TYPE_FILE_IO_STREAM, GFileIOStreamClass))
#define G_IS_FILE_IO_STREAM(o) \
(G_TYPE_CHECK_INSTANCE_TYPE((o), G_TYPE_FILE_IO_STREAM))
#define G_IS_FILE_IO_STREAM_CLASS(k) \
(G_TYPE_CHECK_CLASS_TYPE((k), G_TYPE_FILE_IO_STREAM))
#define G_FILE_IO_STREAM_GET_CLASS(o) \
(G_TYPE_INSTANCE_GET_CLASS((o), G_TYPE_FILE_IO_STREAM, GFileIOStreamClass))
/**
* GFileIOStream:
*
* A subclass of GIOStream for opened files. This adds
* a few file-specific operations and seeking and truncating.
*
* #GFileIOStream implements GSeekable.
**/
typedef struct _GFileIOStreamClass GFileIOStreamClass;
typedef struct _GFileIOStreamPrivate GFileIOStreamPrivate;
struct _GFileIOStream
{
GIOStream parent_instance;
/*< private >*/
GFileIOStreamPrivate* priv;
};
struct _GFileIOStreamClass
{
GIOStreamClass parent_class;
goffset (*tell)(GFileIOStream* stream);
gboolean (*can_seek)(GFileIOStream* stream);
gboolean (*seek)(GFileIOStream* stream, goffset offset, GSeekType type,
GCancellable* cancellable, GError** error);
gboolean (*can_truncate)(GFileIOStream* stream);
gboolean (*truncate_fn)(GFileIOStream* stream, goffset size,
GCancellable* cancellable, GError** error);
GFileInfo* (*query_info)(GFileIOStream* stream, const char* attributes,
GCancellable* cancellable, GError** error);
void (*query_info_async)(GFileIOStream* stream, const char* attributes,
int io_priority, GCancellable* cancellable,
GAsyncReadyCallback callback, gpointer user_data);
GFileInfo* (*query_info_finish)(GFileIOStream* stream, GAsyncResult* result,
GError** error);
char* (*get_etag)(GFileIOStream* stream);
/* Padding for future expansion */
void (*_g_reserved1)(void);
void (*_g_reserved2)(void);
void (*_g_reserved3)(void);
void (*_g_reserved4)(void);
void (*_g_reserved5)(void);
};
GLIB_AVAILABLE_IN_ALL
GType g_file_io_stream_get_type(void) G_GNUC_CONST;
GLIB_AVAILABLE_IN_ALL
GFileInfo* g_file_io_stream_query_info(GFileIOStream* stream,
const char* attributes,
GCancellable* cancellable,
GError** error);
GLIB_AVAILABLE_IN_ALL
void g_file_io_stream_query_info_async(GFileIOStream* stream,
const char* attributes, int io_priority,
GCancellable* cancellable,
GAsyncReadyCallback callback,
gpointer user_data);
GLIB_AVAILABLE_IN_ALL
GFileInfo* g_file_io_stream_query_info_finish(GFileIOStream* stream,
GAsyncResult* result,
GError** error);
GLIB_AVAILABLE_IN_ALL
char* g_file_io_stream_get_etag(GFileIOStream* stream);
G_END_DECLS
#endif /* __G_FILE_FILE_IO_STREAM_H__ */
|
BearerPipelineTest/cucumber-ruby
|
lib/cucumber/formatter/duration.rb
|
# frozen_string_literal: true
module Cucumber
module Formatter
module Duration
# Helper method for formatters that need to
# format a duration in seconds to the UNIX
# <tt>time</tt> format.
def format_duration(seconds)
m, s = seconds.divmod(60)
"#{m}m#{format('%<seconds>.3f', seconds: s)}s"
end
end
end
end
|
hyajam/jabs
|
src/main/java/jabs/consensus/DAGsper.java
|
<reponame>hyajam/jabs<filename>src/main/java/jabs/consensus/DAGsper.java
package jabs.consensus;
import jabs.blockchain.LocalBlockTree;
import jabs.data.Block;
import jabs.data.BlockWithTx;
import jabs.data.Tx;
import jabs.data.Vote;
import jabs.data.dagsper.DAGsperVote;
import jabs.data.ethereum.EthereumBlock;
import jabs.message.Packet;
import jabs.message.VoteMessage;
import jabs.node.nodes.Node;
import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics;
import java.util.*;
public class DAGsper<B extends Block<B>, T extends Tx<T>> extends GhostProtocol<B, T>
implements VotingBasedConsensus<B, T>, DeterministicFinalityConsensus<B,T> {
private final int numOfStakeholders;
private final int checkpointSpace;
private final HashMap<Integer, HashMap<Node, B>> fVotesInHeight = new HashMap<>();
private final HashMap<Integer, HashMap<Node, B>> jVotesInHeight = new HashMap<>();
private final HashMap<B, HashSet<Node>> fVotesForBlock = new HashMap<>();
private final HashMap<B, HashSet<Node>> jVotesForBlock = new HashMap<>();
private final HashMap<Integer, HashSet<B>> fVotedBlocksInHeight = new HashMap<>();
private final HashMap<Integer, HashSet<B>> jVotedBlocksInHeight = new HashMap<>();
private final Set<Integer> unfinalizableHeights = new HashSet<>();
private final SortedSet<B> finalizedBlocks = new TreeSet<>();
private final SortedSet<B> justifiedBlocks = new TreeSet<>();
private final Set<B> indirectlyFinalizedBlocks = new HashSet<>();
private final Set<T> finalizedTxs = new HashSet<>();
private final HashMap<Integer, B> previousFVotes = new HashMap<>();
private final HashMap<Integer, B> previousJVotes = new HashMap<>();
private DescriptiveStatistics blockFinalizationTimes = null;
public DAGsper(LocalBlockTree<B> localBlockTree, int checkpointSpace, int numOfStakeholders) {
super(localBlockTree);
this.checkpointSpace = checkpointSpace;
this.numOfStakeholders = numOfStakeholders;
finalizedBlocks.add(localBlockTree.getGenesisBlock());
justifiedBlocks.add(localBlockTree.getGenesisBlock());
indirectlyFinalizedBlocks.add(localBlockTree.getGenesisBlock());
}
public void enableFinalizationTimeRecords(DescriptiveStatistics blockFinalizationTimes) {
this.blockFinalizationTimes = blockFinalizationTimes;
}
@Override
public void newIncomingVote(Vote vote) {
if (vote instanceof DAGsperVote) {
B toBeJustified = (B) ((DAGsperVote) vote).toBeJustified;
B latestFinalized = localBlockTree.getAncestorOfHeight(toBeJustified, ((DAGsperVote) vote).latestFinalizedHeight);
B toBeFinalized = localBlockTree.getAncestorOfHeight(toBeJustified, ((DAGsperVote) vote).toBeFinalizedHeight);
HashSet<Integer> unaffectedHeights = ((DAGsperVote) vote).unaffectedHeights;
List<B> toBeJustifiedPath = localBlockTree.getPathBetween(toBeJustified, toBeFinalized);
if (toBeJustifiedPath != null) {
toBeJustifiedPath.removeIf(i -> unaffectedHeights.contains(i.getHeight()));
this.addVote(toBeJustifiedPath, vote.getVoter(), jVotesInHeight, jVotesForBlock, fVotedBlocksInHeight);
}
List<B> toBeFinalizedPath = localBlockTree.getPathBetween(toBeFinalized, latestFinalized);
if (toBeFinalizedPath != null) {
toBeFinalizedPath.removeIf(i -> unaffectedHeights.contains(i.getHeight()));
this.addVote(toBeFinalizedPath, vote.getVoter(), fVotesInHeight, fVotesForBlock, jVotedBlocksInHeight);
}
}
}
public void addVote(List<B> blocks, Node voter, HashMap<Integer, HashMap<Node, B>> heightVotes,
HashMap<B, HashSet<Node>> blockVotes, HashMap<Integer, HashSet<B>> blocksInHeight) {
for (B block:blocks) {
if (!heightVotes.containsKey(block.getHeight())) { // first vote for this height
heightVotes.put(block.getHeight(), new HashMap<>());
}
if (!blockVotes.containsKey(block)) { // first vote for this block
blockVotes.put(block, new HashSet<>());
}
if (!blocksInHeight.containsKey(block.getHeight())) { // first block for this height
blocksInHeight.put(block.getHeight(), new HashSet<>());
}
if (heightVotes.get(block.getHeight()).containsKey(voter)) {
if (heightVotes.get(block.getHeight()).get(voter) != block) {
System.out.printf("Slashing condition for participant %s, on height %s\n", voter, block.getHeight());
}
} else {
heightVotes.get(block.getHeight()).put(voter, block);
blockVotes.get(block).add(voter);
blocksInHeight.get(block.getHeight()).add(block);
}
if (heightVotes == fVotesInHeight) { // if it is a finalization vote
int totalNumOfVotes = heightVotes.get(block.getHeight()).size();
int highestVote = 0;
for (B blockOfHeight:blocksInHeight.get(block.getHeight())) {
if (highestVote < blockVotes.get(blockOfHeight).size()) {
highestVote = blockVotes.get(blockOfHeight).size();
}
}
if ((numOfStakeholders - totalNumOfVotes) + highestVote < (((numOfStakeholders / 3) * 2) + 1)) {
// if the height is unfinalizable
unfinalizableHeights.add(block.getHeight());
}
// did block gain enough votes?
if (!finalizedBlocks.contains(block)) {
if (blockVotes.get(block).size() > (((numOfStakeholders / 3) * 2) + 1)) {
int finalizableHeight = block.getHeight() - 1;
while (unfinalizableHeights.contains(finalizableHeight)) {
finalizableHeight--;
}
if (finalizedBlocks.contains(localBlockTree.getAncestorOfHeight(block, finalizableHeight))) {
finalizedBlocks.add(block);
updateFinalizedBlocks(finalizedBlocks.last());
this.originOfGhost = finalizedBlocks.last();
}
}
}
} else { // it is a justification vote
// did block gain enough votes?
if (blockVotes.get(block).size() > (((numOfStakeholders / 3) * 2) + 1)) {
justifiedBlocks.add(block);
}
}
}
}
private void updateFinalizedBlocks(B newlyFinalizedBlock) {
if (!indirectlyFinalizedBlocks.contains(newlyFinalizedBlock)) {
indirectlyFinalizedBlocks.add(newlyFinalizedBlock);
if (blockFinalizationTimes != null) {
blockFinalizationTimes.addValue(blockchainNode.getSimulator().getCurrentTime() - newlyFinalizedBlock.getCreationTime());
}
}
Set<B> ancestors = new HashSet<>();
Set<B> nextAncestors = new HashSet<>();
ancestors.add(newlyFinalizedBlock);
while (ancestors.size() > 0) {
for (B block:ancestors) {
nextAncestors.add(block.getParent());
if (block instanceof EthereumBlock) {
nextAncestors.addAll((Collection<? extends B>) ((EthereumBlock) block).getUncles());
}
}
ancestors.clear();
for (B block:nextAncestors) {
if (localBlockTree.contains(block)) {
if (!indirectlyFinalizedBlocks.contains(block)) {
ancestors.add(block);
}
}
}
indirectlyFinalizedBlocks.addAll(ancestors);
for (B block:ancestors) {
if (blockFinalizationTimes != null) {
blockFinalizationTimes.addValue(blockchainNode.getSimulator().getCurrentTime() - block.getCreationTime());
}
if (block instanceof BlockWithTx) {
finalizedTxs.addAll(((BlockWithTx<T>) block).getTxs());
}
}
nextAncestors.clear();
}
}
@Override
protected void updateChain() {
acceptedBlocks = localBlockTree.getAllAncestors(currentMainChainHead);
if (currentMainChainHead.getHeight() > 0) {
if ((currentMainChainHead.getHeight() % checkpointSpace) == (blockchainNode.nodeID % checkpointSpace)) {
B latestConnectedJBlock = finalizedBlocks.last();
if (localBlockTree.areBlocksConnected(currentMainChainHead, justifiedBlocks.last())) {
latestConnectedJBlock = justifiedBlocks.last();
} else {
for (B jBlock:justifiedBlocks) {
if (localBlockTree.areBlocksConnected(currentMainChainHead, jBlock))
latestConnectedJBlock = jBlock;
}
}
HashSet<Integer> unaffectedHeights = new HashSet<>();
List<B> fPath = localBlockTree.getPathBetween(latestConnectedJBlock, finalizedBlocks.last());
removePreviouslyVotedHeights(unaffectedHeights, fPath, previousFVotes);
List<B> jPath = localBlockTree.getPathBetween(currentMainChainHead, latestConnectedJBlock);
removePreviouslyVotedHeights(unaffectedHeights, jPath, previousJVotes);
DAGsperVote<B> daGsperVote = new DAGsperVote<>(blockchainNode, finalizedBlocks.last().getHeight(),
latestConnectedJBlock.getHeight(), currentMainChainHead, unaffectedHeights);
VoteMessage voteMessage = new VoteMessage(daGsperVote);
Packet packet = new Packet(this.blockchainNode, this.blockchainNode, voteMessage);
this.blockchainNode.processIncomingPacket(packet);
}
}
}
private void removePreviouslyVotedHeights(HashSet<Integer> unaffectedHeights, List<B> path, HashMap<Integer, B> previousVotes) {
if (path != null) {
for (B jBlock:path) {
if (previousVotes.containsKey(jBlock.getHeight())) {
if (previousVotes.get(jBlock.getHeight()) != jBlock) {
unaffectedHeights.add(jBlock.getHeight());
}
} else {
previousVotes.put(jBlock.getHeight(), jBlock);
}
}
}
}
@Override
public boolean isBlockFinalized(B block) {
return this.indirectlyFinalizedBlocks.contains(block);
}
@Override
public boolean isTxFinalized(T tx) {
return this.finalizedTxs.contains(tx);
}
@Override
public int getNumOfFinalizedBlocks() {
return this.indirectlyFinalizedBlocks.size();
}
@Override
public int getNumOfFinalizedTxs() {
return this.finalizedTxs.size();
}
}
|
MrManiak/Squad-SDK
|
Cpp/SDK/W_Grid_ActionList_CO_classes.h
|
<gh_stars>1-10
#pragma once
// Name: S, Version: b
#ifdef _MSC_VER
#pragma pack(push, 0x01)
#endif
/*!!HELPER_DEF!!*/
/*!!DEFINE!!*/
namespace UFT
{
//---------------------------------------------------------------------------
// Classes
//---------------------------------------------------------------------------
// WidgetBlueprintGeneratedClass W_Grid_ActionList_CO.W_Grid_ActionList_CO_C
// 0x0018 (FullSize[0x02B0] - InheritedSize[0x0298])
class UW_Grid_ActionList_CO_C : public UW_Grid_ActionList_C
{
public:
struct FPointerToUberGraphFrame UberGraphFrame; // 0x0298(0x0008) (ZeroConstructor, Transient, DuplicateTransient)
TArray<class UClass*> SQCommandActions; // 0x02A0(0x0010) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance)
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("WidgetBlueprintGeneratedClass W_Grid_ActionList_CO.W_Grid_ActionList_CO_C");
return ptr;
}
void Get_Fireteam_ID(int* ID);
void Populate_List();
void ExecuteUbergraph_W_Grid_ActionList_CO(int EntryPoint);
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
|
cashbitecrypto/cashbite
|
external/rocksdb/table/block_based/reader_common.h
|
<reponame>cashbitecrypto/cashbite
// Copyright (c) 2011-present, Facebook, Inc. All rights reserved.
// This source code is licensed under both the GPLv2 (found in the
// COPYING file in the root directory) and Apache 2.0 License
// (found in the LICENSE.Apache file in the root directory).
//
// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.
#pragma once
#include "rocksdb/table.h"
namespace ROCKSDB_NAMESPACE {
// Release the cached entry and decrement its ref count.
extern void ForceReleaseCachedEntry(void* arg, void* h);
inline MemoryAllocator* GetMemoryAllocator(
const BlockBasedTableOptions& table_options) {
return table_options.block_cache.get()
? table_options.block_cache->memory_allocator()
: nullptr;
}
inline MemoryAllocator* GetMemoryAllocatorForCompressedBlock(
const BlockBasedTableOptions& table_options) {
return table_options.block_cache_compressed.get()
? table_options.block_cache_compressed->memory_allocator()
: nullptr;
}
extern Status VerifyChecksum(const ChecksumType type, const char* buf,
size_t len, uint32_t expected);
} // namespace ROCKSDB_NAMESPACE
|
gchan/advent-of-code-go
|
2016/day-07/day-07-part-2.go
|
<reponame>gchan/advent-of-code-go
package main
import (
"io/ioutil"
"regexp"
"strings"
)
func aba(text string) (result []string) {
for i := 0; i < len(text)-2; i++ {
str := text[i : i+3]
if str[0] == str[2] {
result = append(result, str)
}
}
return result
}
func bab(text string) (result []string) {
for _, str := range aba(text) {
bab := append([]byte(str[1:2]), str[0], str[1])
result = append(result, string(bab))
}
return result
}
func main() {
input, _ := ioutil.ReadFile("./day-07-input.txt")
lines := strings.Split(string(input), "\n")
sequenceRegexFirst := regexp.MustCompile("(\\w+)\\[")
sequenceRegexRest := regexp.MustCompile("\\](\\w+)")
hypernetRegex := regexp.MustCompile("\\[(\\w+)\\]")
var count int
var match bool
for _, line := range lines {
sequences := sequenceRegexFirst.FindAllStringSubmatch(line, -1)
sequences = append(sequences, sequenceRegexRest.FindAllStringSubmatch(line, -1)...)
hypernets := hypernetRegex.FindAllStringSubmatch(line, -1)
var abas []string
for _, sequence := range sequences {
abas = append(abas, aba(sequence[1])...)
}
var babs []string
for _, hypernet := range hypernets {
babs = append(babs, bab(hypernet[1])...)
}
match = false
for _, aba := range abas {
for _, bab := range babs {
if aba == bab {
match = true
}
}
}
if match {
count++
}
}
println(count)
}
|
jamesanto/scala
|
test/files/run/t11476b.scala
|
<filename>test/files/run/t11476b.scala
case class Foo(a: Int*) { def lengthCompare(i: Int) = 1 }
object FooExtractor {
def unapplySeq(x$0: Foo): Option[Seq[Int]] = if (x$0.==(null))
None
else
Some[Seq[Int]](x$0.a);
}
object Test {
def main(args: Array[String]): Unit = {
val x = Foo(1) match { case FooExtractor(a) => a }
}
}
|
jbdelcuv/openenclave
|
3rdparty/musl/libc-test/src/math/sanity/cosf.h
|
T(RN, -0x1.0223ap+3, -0x1.b0aabep-3, 0x1.eee272p-2, INEXACT)
T(RN, 0x1.161868p+2, -0x1.6f9238p-2, 0x1.5c33e2p-5, INEXACT)
T(RN, -0x1.0c34b4p+3, -0x1.01b4e2p-1, -0x1.1be494p-3, INEXACT)
T(RN, -0x1.a206fp+2, 0x1.f0462cp-1, 0x1.6df7bcp-3, INEXACT)
T(RN, 0x1.288bbcp+3, -0x1.f9a51ep-1, 0x1.1c971cp-3, INEXACT)
T(RN, 0x1.52efdp-1, 0x1.93da12p-1, 0x1.322268p-2, INEXACT)
T(RN, -0x1.a05cc8p-2, 0x1.d6419ap-1, 0x1.f0a754p-3, INEXACT)
T(RN, 0x1.1f9efap-1, 0x1.b150bap-1, -0x1.ec3366p-3, INEXACT)
T(RN, 0x1.8c5dbp-1, 0x1.6e164ep-1, -0x1.595b9cp-2, INEXACT)
T(RN, -0x1.5b86eap-1, 0x1.8e83d4p-1, 0x1.52f278p-3, INEXACT)
|
brandonkim-1301/TI-RSLK-Maze-Follower
|
documentation/navtreeindex5.js
|
var NAVTREEINDEX5 =
{
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gaabaad6846eae116f278af4c87d432b2f":[2,0,0,0,7,10],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gaabaad6846eae116f278af4c87d432b2f":[2,0,0,0,8,6],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gaadddd8d5c6a55cd7f76497ca2c8a8d4a":[2,0,0,0,9,101],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gaae81f66171c9443f458ba233953a34d6":[2,0,0,0,9,18],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gaaeab15ff61e3bf4171b5f519bf7dc560":[2,0,0,0,9,115],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gaaed728382237b0e62b3dd4a46da10dce":[2,0,0,0,21,38],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gaaed728382237b0e62b3dd4a46da10dce":[0,3,76],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gaaf00be9e69422a82831aa42631ba8899":[2,0,0,0,9,163],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gab098d2c7fda2965b1699ae13d2a8ffc8":[2,0,0,0,4,26],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gab098d2c7fda2965b1699ae13d2a8ffc8":[2,0,0,0,5,26],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gab098d2c7fda2965b1699ae13d2a8ffc8":[0,3,38],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gab0a3a07222ec43ae4ccabd44bf35f47d":[2,0,0,0,9,23],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gab21ca26b7df608549e5d1bd583e4d52a":[0,3,17],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gab21ca26b7df608549e5d1bd583e4d52a":[2,0,0,0,4,5],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gab21ca26b7df608549e5d1bd583e4d52a":[2,0,0,0,5,5],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gab2d62243fc52243237e257c184e0ff3f":[2,0,0,0,9,53],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gab32d9400291b2a4663f4b58a66e69987":[2,0,0,0,9,33],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gab4897d93fb8406c61d6bfab44de8c054":[2,0,0,0,8,5],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gab4897d93fb8406c61d6bfab44de8c054":[0,3,48],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gab4897d93fb8406c61d6bfab44de8c054":[2,0,0,0,7,9],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gab5e8c1235b48cba8f05cbf18c1f086c6":[2,0,0,0,21,16],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gab61c664178d7c5b228c042e3f9d76cf6":[2,0,0,0,9,66],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gab7dba610f920f63a03e84d80be2aa4db":[0,3,13],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gab7dba610f920f63a03e84d80be2aa4db":[2,0,0,0,4,1],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gab7dba610f920f63a03e84d80be2aa4db":[2,0,0,0,5,1],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gab901d7ff4cfb84e13576f813e84019ec":[2,0,0,0,9,72],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gab9ac3938b949b6200668a9f0b8701920":[2,0,0,0,9,50],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gab9de9a9619bf08de973aef003092da0f":[2,0,0,0,21,33],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gab9de9a9619bf08de973aef003092da0f":[0,3,71],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gaba8ceda5c666772bfd30d30b5307395a":[2,0,0,0,21,2],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gabab200d34d4e3982f583931419a95084":[2,0,0,0,9,166],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gabb7931fd88fddf1812cdac483a16cf88":[2,0,0,0,9,104],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gabc0895a5c1c847e18e33daf5cd69c1b6":[2,0,0,0,7,4],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gabc0895a5c1c847e18e33daf5cd69c1b6":[2,0,0,0,8,0],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gabc0895a5c1c847e18e33daf5cd69c1b6":[0,3,43],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gabc605b18893625684b0437db47363897":[2,0,0,0,9,108],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gabd2e2ad720f86ad0d9e6ece900b6628d":[2,0,0,0,9,73],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gabdb1f4947a1e2639326420a9fc7a2b12":[0,3,50],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gabdb1f4947a1e2639326420a9fc7a2b12":[2,0,0,0,7,11],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gabdb1f4947a1e2639326420a9fc7a2b12":[2,0,0,0,8,7],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gabe068b7f463f2d0792dfec9cf789356b":[2,0,0,0,9,129],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gabe646b483626271a96bcbd9d708e1dbb":[2,0,0,0,9,36],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gabfd26fc351558a45693119519e14ca7a":[2,0,0,0,9,49],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gabff6a5cd4e26a87de79a69a619348829":[2,0,0,0,21,8],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gac00bc4d1e75cfbc1c662a24203c025f3":[2,0,0,0,9,164],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gac0429a3a84f1583f30db47fe5b91b95c":[0,3,79],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gac0429a3a84f1583f30db47fe5b91b95c":[2,0,0,0,21,41],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gac04e274fd3110a712d57a83a66f56574":[2,0,0,0,9,85],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gac356fd2c804c2da853436e16201bb39e":[2,0,0,0,9,113],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gac37108690acb5072d5c19a0f4e677634":[2,0,0,0,4,7],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gac37108690acb5072d5c19a0f4e677634":[2,0,0,0,5,7],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gac37108690acb5072d5c19a0f4e677634":[0,3,19],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gac3b65c846fa1d826b2addbbef4292a9c":[2,0,0,0,7,7],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gac3b65c846fa1d826b2addbbef4292a9c":[2,0,0,0,8,3],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gac3b65c846fa1d826b2addbbef4292a9c":[0,3,46],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gac5cead9788329ba97addba76997de01e":[2,0,0,0,4,18],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gac5cead9788329ba97addba76997de01e":[2,0,0,0,5,18],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gac5cead9788329ba97addba76997de01e":[0,3,30],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gac62a25e704f97becd8244199611ff717":[2,0,0,0,9,99],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gac6d11bee70aafd12449413c0fce3f014":[2,0,0,0,4,9],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gac6d11bee70aafd12449413c0fce3f014":[0,3,21],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gac6d11bee70aafd12449413c0fce3f014":[2,0,0,0,5,9],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gac7886d152790cca4273e3647d08e6cef":[2,0,0,0,9,56],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gac79f5b0b52b9eee50e374245c4524161":[2,0,0,0,9,119],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gac896869fc163b39f9e92a972fbbd592b":[2,0,0,0,30,1],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gac896869fc163b39f9e92a972fbbd592b":[0,3,81],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gac8eb6d7fd78c6fbb64b1cd9ab6972797":[2,0,0,0,9,139],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gac980d0255f3e86bebed102696b46dc41":[2,0,0,0,9,27],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gacc67ab3ab69ac01c5103473f2fc5fbfd":[2,0,0,0,9,151],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gacccfd1c8b53cb8b154cbab377d9cd9e9":[0,3,63],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gacccfd1c8b53cb8b154cbab377d9cd9e9":[2,0,0,0,21,25],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gacd2aa09844a8a245cf7fdbb808e215e5":[2,0,0,0,9,179],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gacd2aa09844a8a245cf7fdbb808e215e5":[2,0,0,0,6,463],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gacec262689d340c2160a64008a669aa17":[2,0,0,0,9,37],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gacf4792d76eafc7607a097c79fcadb92a":[0,3,22],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gacf4792d76eafc7607a097c79fcadb92a":[2,0,0,0,4,10],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gacf4792d76eafc7607a097c79fcadb92a":[2,0,0,0,5,10],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gacfc902bb655b1d2e2e4256a5085e6064":[2,0,0,0,9,90],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gad0fc8ca82bf767772bf6de22435586f3":[2,0,0,0,9,140],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gad21b97d3d5a0a03e27b9850757932e88":[0,3,7,1],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gad3a219e5d9c74e681358cf94a643ecb5":[0,3,69],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gad3a219e5d9c74e681358cf94a643ecb5":[2,0,0,0,21,31],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gad48401100ea30b4fe0751f83d3596e57":[2,0,0,0,9,45],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gad4e1a7316da5f4ef680fc284dbb97f1d":[2,0,0,0,9,145],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gad53c0f1cab22067aaff73d0f172a9dbe":[0,3,55],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gad53c0f1cab22067aaff73d0f172a9dbe":[2,0,0,0,8,12],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gad53c0f1cab22067aaff73d0f172a9dbe":[2,0,0,0,7,16],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gad78650fb7726f4e99205406569ef403d":[2,0,0,0,9,171],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gad78650fb7726f4e99205406569ef403d":[2,0,0,0,6,455],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gad8906c0208cd948e4f5fe79a920a3b7d":[2,0,0,0,21,1],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gadb0f53226732ebf188d21abc690f7153":[2,0,0,0,9,69],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gadd32543d7b560e6e0c457ce5de5a5c86":[2,0,0,0,9,109],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gade03ff196c69db24827960ee95a1aecb":[2,0,0,0,9,28],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gadee930eb8e5ef947b87ee8c217780143":[2,0,0,0,8,1],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gadee930eb8e5ef947b87ee8c217780143":[2,0,0,0,7,5],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gadee930eb8e5ef947b87ee8c217780143":[0,3,44],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gadfdfb6f13d803880acf88a0c4d5a933a":[2,0,0,0,9,154],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gae0a1183431d86617670185119b1416fb":[2,0,0,0,21,17],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gae1f173b8b1e4ba2601016cc5fe8edc29":[2,0,0,0,4,15],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gae1f173b8b1e4ba2601016cc5fe8edc29":[2,0,0,0,5,15],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gae1f173b8b1e4ba2601016cc5fe8edc29":[0,3,27],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gae25146f0841521534b67f6fa5fa5218d":[2,0,0,0,9,127],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gae2a0b717765bc2ee40c0fb92d2f819d2":[2,0,0,0,4,17],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gae2a0b717765bc2ee40c0fb92d2f819d2":[2,0,0,0,5,17],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gae2a0b717765bc2ee40c0fb92d2f819d2":[0,3,29],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gae36796ee91096d08d9606752d23edb49":[2,0,0,0,9,142],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gae379d42737c29ce3bdf8a21fa4569364":[2,0,0,0,9,43],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gae41907b55a2922bb2ec57b3ff4c937be":[2,0,0,0,9,58],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gae42ffc1cb14641aace57f88405accfee":[2,0,0,0,9,130],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gae444e3a85c42d159494a3aaa009acf96":[2,0,0,0,9,148],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gae4930ced79355b8039ded668e72cf241":[2,0,0,0,9,41],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gae548739f4185fa7fef8cb718ec6bd91d":[2,0,0,0,4,4],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gae548739f4185fa7fef8cb718ec6bd91d":[2,0,0,0,5,4],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gae548739f4185fa7fef8cb718ec6bd91d":[0,3,16],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gae614cb044b4924a3e82543dfa1588c0a":[0,3,66],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gae614cb044b4924a3e82543dfa1588c0a":[2,0,0,0,21,28],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gae6300dc6c71a7b372853ac5e05c8e9fe":[2,0,0,0,21,19],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gae6300dc6c71a7b372853ac5e05c8e9fe":[0,3,57],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gae70c03de48f609fd7c0ce910ccc367c4":[2,0,0,0,9,88],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gae80db964b313a18fd830f0ba981f1b84":[2,0,0,0,9,156],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gae80f53d4692065b51a8df454404fdf05":[2,0,0,0,9,26],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gae849493d17f837c628f1c810bb67e2af":[0,3,78],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gae849493d17f837c628f1c810bb67e2af":[2,0,0,0,21,40],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gae8c04953d945f3b1d21d93ab6c4a1251":[0,3,58],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gae8c04953d945f3b1d21d93ab6c4a1251":[2,0,0,0,21,20],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gae8fd008b08b8a1fc1aadce8e9ebfc1e6":[2,0,0,0,5,23],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gae8fd008b08b8a1fc1aadce8e9ebfc1e6":[2,0,0,0,4,23],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gae8fd008b08b8a1fc1aadce8e9ebfc1e6":[0,3,35],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gaea226b4dde4c023c6ef6a99368a512a0":[2,0,0,0,9,146],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gaeac8b4bc79e2f9daac20ffd475a73e05":[2,0,0,0,9,114],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gaec2da85c333c50753ea44752763b0c4a":[2,0,0,0,9,22],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gaec6af2af456b44f31f53c69235028ed6":[2,0,0,0,9,112],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gaed0e6344c2920833260cc45848e8bd58":[0,3,75],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gaed0e6344c2920833260cc45848e8bd58":[2,0,0,0,21,37],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gaf14f592affbc3c378989438565e1021e":[2,0,0,0,9,149],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gaf17e24386a1b68a96878192a141cdf0d":[0,3,56],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gaf17e24386a1b68a96878192a141cdf0d":[2,0,0,0,21,18],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gaf1ac7d49fb8a2c294d9adf1c87231395":[2,0,0,0,21,4],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gaf43ab256292412c2da888afc50fe8614":[2,0,0,0,9,54],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gaf473dd93df57b0a43966fbb08c58f3fd":[2,0,0,0,9,70],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gaf48a3b129a2fc9a8dea057dd317a52bd":[2,0,0,0,9,4],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gaf52fa42e52cc3a250f028f86035974ee":[2,0,0,0,9,19],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gaf5681a5d7f7b26f5e84deb9e529e8b90":[0,3,72],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gaf5681a5d7f7b26f5e84deb9e529e8b90":[2,0,0,0,21,34],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gaf5a0a241dbf7482c2d4981d464c04674":[2,0,0,0,9,126],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gaf5e2f18c796516955708266a654224f0":[2,0,0,0,9,48],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gaf6800e431a1e315906bc9a8c9e172756":[2,0,0,0,9,81],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gaf9a909f6c1b3be1b33658b2f17632d35":[2,0,0,0,4,0],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gaf9a909f6c1b3be1b33658b2f17632d35":[2,0,0,0,5,0],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gaf9a909f6c1b3be1b33658b2f17632d35":[0,3,12],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gafb571f959248cb5c9c64a7dcf843fe27":[2,0,0,0,9,87],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gafbc97840719e10a8a79d1a4d5c75ad11":[2,0,0,0,9,143],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gafbd9773c2f5c5645d60231f0ba7e8626":[0,3,52],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gafbd9773c2f5c5645d60231f0ba7e8626":[2,0,0,0,7,13],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gafbd9773c2f5c5645d60231f0ba7e8626":[2,0,0,0,8,9],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gafc3d125572065655f5b45e44980d5df9":[0,3,7,2],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gafc6359bc656da3823dbbb0d67bf37c4b":[2,0,0,0,9,121],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gafda35398d4e1b971ea8801da17341120":[2,0,0,0,9,40],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gafda9fb86796f4c4b4e703f492ce216ed":[2,0,0,0,9,118],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gafe347f30221ea77ea52121b65f30f63a":[2,0,0,0,9,80],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gga479329e9f54743abfe872741fcce4ae9a519204c91f338db8c681885c191d0caa":[0,3,11,1],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gga479329e9f54743abfe872741fcce4ae9a519204c91f338db8c681885c191d0caa":[2,0,0,0,9,182,1],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gga479329e9f54743abfe872741fcce4ae9ad7bdf3f9fb3ede40544dff5ad13b06ee":[0,3,11,0],
"group___b_p-_b_a_s_s_e_n_s_o_r_s_m_k_i_i.html#gga479329e9f54743abfe872741fcce4ae9ad7bdf3f9fb3ede40544dff5ad13b06ee":[2,0,0,0,9,182,0],
"group___debug.html":[0,11],
"group___debug.html#ga1956a36415c3dcd2df5f68e5feb1c54d":[0,11,35],
"group___debug.html#ga1956a36415c3dcd2df5f68e5feb1c54d":[2,0,0,0,42,18],
"group___debug.html#ga278002f54056da03e4cae02baa70a9fd":[2,0,0,0,42,24],
"group___debug.html#ga278002f54056da03e4cae02baa70a9fd":[0,11,41],
"group___debug.html#ga27c5f2fb57ee49159cb8275847f2ab5b":[2,0,0,0,42,13],
"group___debug.html#ga27c5f2fb57ee49159cb8275847f2ab5b":[0,11,30],
"group___debug.html#ga32e8f15744b7c8b0428a99ef790c10c7":[2,0,0,0,42,7],
"group___debug.html#ga32e8f15744b7c8b0428a99ef790c10c7":[0,11,24],
"group___debug.html#ga343599a9b7727394c00c67924d601b41":[0,11,29],
"group___debug.html#ga343599a9b7727394c00c67924d601b41":[2,0,0,0,42,12],
"group___debug.html#ga37f6a72d74ec91d2fa2b5bf149c17392":[0,11,19],
"group___debug.html#ga37f6a72d74ec91d2fa2b5bf149c17392":[2,0,0,0,42,2],
"group___debug.html#ga38ed800557809cf9c85df5f440d469e5":[0,11,40],
"group___debug.html#ga38ed800557809cf9c85df5f440d469e5":[2,0,0,0,42,23],
"group___debug.html#ga3d31c706b90d3156910d6da229f15e5f":[0,11,26],
"group___debug.html#ga3d31c706b90d3156910d6da229f15e5f":[2,0,0,0,42,9],
"group___debug.html#ga46145d89ba6be5894bb7f29f1bbc65e4":[0,11,27],
"group___debug.html#ga46145d89ba6be5894bb7f29f1bbc65e4":[2,0,0,0,42,10],
"group___debug.html#ga49361f2461c5a25e966f904bf57919db":[2,0,0,0,42,4],
"group___debug.html#ga49361f2461c5a25e966f904bf57919db":[0,11,21],
"group___debug.html#ga557cdfa1e0d493cdfc7106a034c7e450":[0,11,18],
"group___debug.html#ga557cdfa1e0d493cdfc7106a034c7e450":[2,0,0,0,42,1],
"group___debug.html#ga5b64480daeb41b3755160fb21eb57f76":[2,0,0,0,42,5],
"group___debug.html#ga5b64480daeb41b3755160fb21eb57f76":[0,11,22],
"group___debug.html#ga5e88b13c91baf6c42b8a3022523a5b33":[0,11,0],
"group___debug.html#ga5e88b13c91baf6c42b8a3022523a5b33":[2,0,0,0,42,0],
"group___debug.html#ga8418143a137cbb6ff108d89820f96cb1":[0,11,23],
"group___debug.html#ga8418143a137cbb6ff108d89820f96cb1":[2,0,0,0,42,6],
"group___debug.html#gab2cb179efa5577e32813435376f7b8f1":[2,0,0,0,42,21],
"group___debug.html#gab2cb179efa5577e32813435376f7b8f1":[0,11,38],
"group___debug.html#gab59ea6d3077ab859dd41a37b40253f3e":[0,11,39],
"group___debug.html#gab59ea6d3077ab859dd41a37b40253f3e":[2,0,0,0,42,22],
"group___debug.html#gabe1a5cea692d6ddb6fddbc35f35926db":[2,0,0,0,42,16],
"group___debug.html#gabe1a5cea692d6ddb6fddbc35f35926db":[0,11,33],
"group___debug.html#gac527055bac7642610dec1081beb68317":[0,11,32],
"group___debug.html#gac527055bac7642610dec1081beb68317":[2,0,0,0,42,15],
"group___debug.html#gac5f5edc29f553eac7589c658d1c08ef5":[0,11,25],
"group___debug.html#gac5f5edc29f553eac7589c658d1c08ef5":[2,0,0,0,42,8],
"group___debug.html#gad15b5a7bad5415929e9ff92bb0c0f0de":[0,11,31],
"group___debug.html#gad15b5a7bad5415929e9ff92bb0c0f0de":[2,0,0,0,42,14],
"group___debug.html#gad2baf012e7fe32af2f2893400219946b":[0,11,28],
"group___debug.html#gad2baf012e7fe32af2f2893400219946b":[2,0,0,0,42,11],
"group___debug.html#gad625fa4120b4cf970a4545517f05481d":[2,0,0,0,42,19],
"group___debug.html#gad625fa4120b4cf970a4545517f05481d":[0,11,36],
"group___debug.html#gadeb7fccbbb1881b866ba3ad16712294c":[0,11,34],
"group___debug.html#gadeb7fccbbb1881b866ba3ad16712294c":[2,0,0,0,42,17],
"group___debug.html#gadec1e2ded8292c19e341ebf873d2d455":[0,11,37],
"group___debug.html#gadec1e2ded8292c19e341ebf873d2d455":[2,0,0,0,42,20],
"group___debug.html#gafda97ee912d530d3c0c5695869fc4955":[0,11,20],
"group___debug.html#gafda97ee912d530d3c0c5695869fc4955":[2,0,0,0,42,3],
"group___debug.html#gga5e88b13c91baf6c42b8a3022523a5b33a049e3d754b35c93415e923a0691adf2e":[0,11,0,5],
"group___debug.html#gga5e88b13c91baf6c42b8a3022523a5b33a049e3d754b35c93415e923a0691adf2e":[0,11,8],
"group___debug.html#gga5e88b13c91baf6c42b8a3022523a5b33a049e3d754b35c93415e923a0691adf2e":[2,0,0,0,42,0,5],
"group___debug.html#gga5e88b13c91baf6c42b8a3022523a5b33a14cf15bbefa6ddef4325a854bddc48c9":[2,0,0,0,42,0,8],
"group___debug.html#gga5e88b13c91baf6c42b8a3022523a5b33a14cf15bbefa6ddef4325a854bddc48c9":[0,11,14],
"group___debug.html#gga5e88b13c91baf6c42b8a3022523a5b33a14cf15bbefa6ddef4325a854bddc48c9":[0,11,0,8],
"group___debug.html#gga5e88b13c91baf6c42b8a3022523a5b33a16f233467935687078e64c8630648e05":[0,11,15],
"group___debug.html#gga5e88b13c91baf6c42b8a3022523a5b33a16f233467935687078e64c8630648e05":[2,0,0,0,42,0,9],
"group___debug.html#gga5e88b13c91baf6c42b8a3022523a5b33a16f233467935687078e64c8630648e05":[0,11,0,9],
"group___debug.html#gga5e88b13c91baf6c42b8a3022523a5b33a33fa471babbf301e6ddb8f67ada01fe2":[2,0,0,0,42,0,16],
"group___debug.html#gga5e88b13c91baf6c42b8a3022523a5b33a33fa471babbf301e6ddb8f67ada01fe2":[0,11,0,16],
"group___debug.html#gga5e88b13c91baf6c42b8a3022523a5b33a33fa471babbf301e6ddb8f67ada01fe2":[0,11,12],
"group___debug.html#gga5e88b13c91baf6c42b8a3022523a5b33a5846ea94f1cafa82ab2a929c64cf0c9a":[2,0,0,0,42,0,11],
"group___debug.html#gga5e88b13c91baf6c42b8a3022523a5b33a5846ea94f1cafa82ab2a929c64cf0c9a":[0,11,3],
"group___debug.html#gga5e88b13c91baf6c42b8a3022523a5b33a5846ea94f1cafa82ab2a929c64cf0c9a":[0,11,0,11],
"group___debug.html#gga5e88b13c91baf6c42b8a3022523a5b33a5909e21119b9785bcb19d921a7dad77d":[2,0,0,0,42,0,13],
"group___debug.html#gga5e88b13c91baf6c42b8a3022523a5b33a5909e21119b9785bcb19d921a7dad77d":[0,11,0,13],
"group___debug.html#gga5e88b13c91baf6c42b8a3022523a5b33a5909e21119b9785bcb19d921a7dad77d":[0,11,9],
"group___debug.html#gga5e88b13c91baf6c42b8a3022523a5b33a5c5be91c4c56f94911a6c849fc4135aa":[0,11,0,0],
"group___debug.html#gga5e88b13c91baf6c42b8a3022523a5b33a5c5be91c4c56f94911a6c849fc4135aa":[2,0,0,0,42,0,0],
"group___debug.html#gga5e88b13c91baf6c42b8a3022523a5b33a5c5be91c4c56f94911a6c849fc4135aa":[0,11,17],
"group___debug.html#gga5e88b13c91baf6c42b8a3022523a5b33a6b4e57be460a9808328c5842bdeac46e":[0,11,13],
"group___debug.html#gga5e88b13c91baf6c42b8a3022523a5b33a6b4e57be460a9808328c5842bdeac46e":[0,11,0,7],
"group___debug.html#gga5e88b13c91baf6c42b8a3022523a5b33a6b4e57be460a9808328c5842bdeac46e":[2,0,0,0,42,0,7],
"group___debug.html#gga5e88b13c91baf6c42b8a3022523a5b33a9ac7c5e3e4d7c4743d052d691276afb6":[0,11,0,3],
"group___debug.html#gga5e88b13c91baf6c42b8a3022523a5b33a9ac7c5e3e4d7c4743d052d691276afb6":[0,11,4],
"group___debug.html#gga5e88b13c91baf6c42b8a3022523a5b33a9ac7c5e3e4d7c4743d052d691276afb6":[2,0,0,0,42,0,3],
"group___debug.html#gga5e88b13c91baf6c42b8a3022523a5b33abcfde76f0dab0b4a060c1c3388f94431":[2,0,0,0,42,0,10],
"group___debug.html#gga5e88b13c91baf6c42b8a3022523a5b33abcfde76f0dab0b4a060c1c3388f94431":[0,11,0,10],
"group___debug.html#gga5e88b13c91baf6c42b8a3022523a5b33abcfde76f0dab0b4a060c1c3388f94431":[0,11,16],
"group___debug.html#gga5e88b13c91baf6c42b8a3022523a5b33abfabb00d2222f910e0a3a988c550a611":[0,11,0,2],
"group___debug.html#gga5e88b13c91baf6c42b8a3022523a5b33abfabb00d2222f910e0a3a988c550a611":[0,11,2],
"group___debug.html#gga5e88b13c91baf6c42b8a3022523a5b33abfabb00d2222f910e0a3a988c550a611":[2,0,0,0,42,0,2],
"group___debug.html#gga5e88b13c91baf6c42b8a3022523a5b33ac409d0afd51d6bca2d9de4cdf497b45c":[0,11,10],
"group___debug.html#gga5e88b13c91baf6c42b8a3022523a5b33ac409d0afd51d6bca2d9de4cdf497b45c":[2,0,0,0,42,0,12]
};
|
dmgerman/hadoop
|
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/security/token/delegation/ZKDelegationTokenSecretManager.java
|
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_comment
comment|/** * 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. */
end_comment
begin_package
DECL|package|org.apache.hadoop.security.token.delegation
package|package
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|security
operator|.
name|token
operator|.
name|delegation
package|;
end_package
begin_import
import|import
name|java
operator|.
name|io
operator|.
name|ByteArrayInputStream
import|;
end_import
begin_import
import|import
name|java
operator|.
name|io
operator|.
name|ByteArrayOutputStream
import|;
end_import
begin_import
import|import
name|java
operator|.
name|io
operator|.
name|DataInputStream
import|;
end_import
begin_import
import|import
name|java
operator|.
name|io
operator|.
name|DataOutputStream
import|;
end_import
begin_import
import|import
name|java
operator|.
name|io
operator|.
name|IOException
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|Collections
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|HashMap
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|List
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|Map
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|concurrent
operator|.
name|ExecutorService
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|concurrent
operator|.
name|Executors
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|concurrent
operator|.
name|TimeUnit
import|;
end_import
begin_import
import|import
name|javax
operator|.
name|security
operator|.
name|auth
operator|.
name|login
operator|.
name|AppConfigurationEntry
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|curator
operator|.
name|ensemble
operator|.
name|fixed
operator|.
name|FixedEnsembleProvider
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|curator
operator|.
name|framework
operator|.
name|CuratorFramework
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|curator
operator|.
name|framework
operator|.
name|CuratorFrameworkFactory
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|curator
operator|.
name|framework
operator|.
name|CuratorFrameworkFactory
operator|.
name|Builder
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|curator
operator|.
name|framework
operator|.
name|api
operator|.
name|ACLProvider
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|curator
operator|.
name|framework
operator|.
name|imps
operator|.
name|DefaultACLProvider
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|curator
operator|.
name|framework
operator|.
name|recipes
operator|.
name|cache
operator|.
name|ChildData
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|curator
operator|.
name|framework
operator|.
name|recipes
operator|.
name|cache
operator|.
name|PathChildrenCache
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|curator
operator|.
name|framework
operator|.
name|recipes
operator|.
name|cache
operator|.
name|PathChildrenCache
operator|.
name|StartMode
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|curator
operator|.
name|framework
operator|.
name|recipes
operator|.
name|cache
operator|.
name|PathChildrenCacheEvent
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|curator
operator|.
name|framework
operator|.
name|recipes
operator|.
name|cache
operator|.
name|PathChildrenCacheListener
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|curator
operator|.
name|framework
operator|.
name|recipes
operator|.
name|shared
operator|.
name|SharedCount
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|curator
operator|.
name|framework
operator|.
name|recipes
operator|.
name|shared
operator|.
name|VersionedValue
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|curator
operator|.
name|retry
operator|.
name|RetryNTimes
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|curator
operator|.
name|utils
operator|.
name|EnsurePath
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|classification
operator|.
name|InterfaceAudience
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|classification
operator|.
name|InterfaceAudience
operator|.
name|Private
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|classification
operator|.
name|InterfaceStability
operator|.
name|Unstable
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|conf
operator|.
name|Configuration
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|security
operator|.
name|SecurityUtil
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|security
operator|.
name|token
operator|.
name|Token
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|security
operator|.
name|token
operator|.
name|delegation
operator|.
name|web
operator|.
name|DelegationTokenManager
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|zookeeper
operator|.
name|CreateMode
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|zookeeper
operator|.
name|KeeperException
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|zookeeper
operator|.
name|KeeperException
operator|.
name|NoNodeException
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|zookeeper
operator|.
name|ZooDefs
operator|.
name|Perms
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|zookeeper
operator|.
name|client
operator|.
name|ZKClientConfig
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|zookeeper
operator|.
name|data
operator|.
name|ACL
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|zookeeper
operator|.
name|data
operator|.
name|Id
import|;
end_import
begin_import
import|import
name|org
operator|.
name|slf4j
operator|.
name|Logger
import|;
end_import
begin_import
import|import
name|org
operator|.
name|slf4j
operator|.
name|LoggerFactory
import|;
end_import
begin_import
import|import
name|com
operator|.
name|google
operator|.
name|common
operator|.
name|annotations
operator|.
name|VisibleForTesting
import|;
end_import
begin_import
import|import
name|com
operator|.
name|google
operator|.
name|common
operator|.
name|base
operator|.
name|Preconditions
import|;
end_import
begin_comment
comment|/** * An implementation of {@link AbstractDelegationTokenSecretManager} that * persists TokenIdentifiers and DelegationKeys in Zookeeper. This class can * be used by HA (Highly available) services that consists of multiple nodes. * This class ensures that Identifiers and Keys are replicated to all nodes of * the service. */
end_comment
begin_class
annotation|@
name|InterfaceAudience
operator|.
name|Private
DECL|class|ZKDelegationTokenSecretManager
specifier|public
specifier|abstract
class|class
name|ZKDelegationTokenSecretManager
parameter_list|<
name|TokenIdent
extends|extends
name|AbstractDelegationTokenIdentifier
parameter_list|>
extends|extends
name|AbstractDelegationTokenSecretManager
argument_list|<
name|TokenIdent
argument_list|>
block|{
DECL|field|ZK_CONF_PREFIX
specifier|private
specifier|static
specifier|final
name|String
name|ZK_CONF_PREFIX
init|=
literal|"zk-dt-secret-manager."
decl_stmt|;
DECL|field|ZK_DTSM_ZK_NUM_RETRIES
specifier|public
specifier|static
specifier|final
name|String
name|ZK_DTSM_ZK_NUM_RETRIES
init|=
name|ZK_CONF_PREFIX
operator|+
literal|"zkNumRetries"
decl_stmt|;
DECL|field|ZK_DTSM_ZK_SESSION_TIMEOUT
specifier|public
specifier|static
specifier|final
name|String
name|ZK_DTSM_ZK_SESSION_TIMEOUT
init|=
name|ZK_CONF_PREFIX
operator|+
literal|"zkSessionTimeout"
decl_stmt|;
DECL|field|ZK_DTSM_ZK_CONNECTION_TIMEOUT
specifier|public
specifier|static
specifier|final
name|String
name|ZK_DTSM_ZK_CONNECTION_TIMEOUT
init|=
name|ZK_CONF_PREFIX
operator|+
literal|"zkConnectionTimeout"
decl_stmt|;
DECL|field|ZK_DTSM_ZK_SHUTDOWN_TIMEOUT
specifier|public
specifier|static
specifier|final
name|String
name|ZK_DTSM_ZK_SHUTDOWN_TIMEOUT
init|=
name|ZK_CONF_PREFIX
operator|+
literal|"zkShutdownTimeout"
decl_stmt|;
DECL|field|ZK_DTSM_ZNODE_WORKING_PATH
specifier|public
specifier|static
specifier|final
name|String
name|ZK_DTSM_ZNODE_WORKING_PATH
init|=
name|ZK_CONF_PREFIX
operator|+
literal|"znodeWorkingPath"
decl_stmt|;
DECL|field|ZK_DTSM_ZK_AUTH_TYPE
specifier|public
specifier|static
specifier|final
name|String
name|ZK_DTSM_ZK_AUTH_TYPE
init|=
name|ZK_CONF_PREFIX
operator|+
literal|"zkAuthType"
decl_stmt|;
DECL|field|ZK_DTSM_ZK_CONNECTION_STRING
specifier|public
specifier|static
specifier|final
name|String
name|ZK_DTSM_ZK_CONNECTION_STRING
init|=
name|ZK_CONF_PREFIX
operator|+
literal|"zkConnectionString"
decl_stmt|;
DECL|field|ZK_DTSM_ZK_KERBEROS_KEYTAB
specifier|public
specifier|static
specifier|final
name|String
name|ZK_DTSM_ZK_KERBEROS_KEYTAB
init|=
name|ZK_CONF_PREFIX
operator|+
literal|"kerberos.keytab"
decl_stmt|;
DECL|field|ZK_DTSM_ZK_KERBEROS_PRINCIPAL
specifier|public
specifier|static
specifier|final
name|String
name|ZK_DTSM_ZK_KERBEROS_PRINCIPAL
init|=
name|ZK_CONF_PREFIX
operator|+
literal|"kerberos.principal"
decl_stmt|;
DECL|field|ZK_DTSM_ZK_NUM_RETRIES_DEFAULT
specifier|public
specifier|static
specifier|final
name|int
name|ZK_DTSM_ZK_NUM_RETRIES_DEFAULT
init|=
literal|3
decl_stmt|;
DECL|field|ZK_DTSM_ZK_SESSION_TIMEOUT_DEFAULT
specifier|public
specifier|static
specifier|final
name|int
name|ZK_DTSM_ZK_SESSION_TIMEOUT_DEFAULT
init|=
literal|10000
decl_stmt|;
DECL|field|ZK_DTSM_ZK_CONNECTION_TIMEOUT_DEFAULT
specifier|public
specifier|static
specifier|final
name|int
name|ZK_DTSM_ZK_CONNECTION_TIMEOUT_DEFAULT
init|=
literal|10000
decl_stmt|;
DECL|field|ZK_DTSM_ZK_SHUTDOWN_TIMEOUT_DEFAULT
specifier|public
specifier|static
specifier|final
name|int
name|ZK_DTSM_ZK_SHUTDOWN_TIMEOUT_DEFAULT
init|=
literal|10000
decl_stmt|;
DECL|field|ZK_DTSM_ZNODE_WORKING_PATH_DEAFULT
specifier|public
specifier|static
specifier|final
name|String
name|ZK_DTSM_ZNODE_WORKING_PATH_DEAFULT
init|=
literal|"zkdtsm"
decl_stmt|;
DECL|field|LOG
specifier|private
specifier|static
name|Logger
name|LOG
init|=
name|LoggerFactory
operator|.
name|getLogger
argument_list|(
name|ZKDelegationTokenSecretManager
operator|.
name|class
argument_list|)
decl_stmt|;
DECL|field|JAAS_LOGIN_ENTRY_NAME
specifier|private
specifier|static
specifier|final
name|String
name|JAAS_LOGIN_ENTRY_NAME
init|=
literal|"ZKDelegationTokenSecretManagerClient"
decl_stmt|;
DECL|field|ZK_DTSM_NAMESPACE
specifier|private
specifier|static
specifier|final
name|String
name|ZK_DTSM_NAMESPACE
init|=
literal|"ZKDTSMRoot"
decl_stmt|;
DECL|field|ZK_DTSM_SEQNUM_ROOT
specifier|private
specifier|static
specifier|final
name|String
name|ZK_DTSM_SEQNUM_ROOT
init|=
literal|"/ZKDTSMSeqNumRoot"
decl_stmt|;
DECL|field|ZK_DTSM_KEYID_ROOT
specifier|private
specifier|static
specifier|final
name|String
name|ZK_DTSM_KEYID_ROOT
init|=
literal|"/ZKDTSMKeyIdRoot"
decl_stmt|;
DECL|field|ZK_DTSM_TOKENS_ROOT
specifier|private
specifier|static
specifier|final
name|String
name|ZK_DTSM_TOKENS_ROOT
init|=
literal|"/ZKDTSMTokensRoot"
decl_stmt|;
DECL|field|ZK_DTSM_MASTER_KEY_ROOT
specifier|private
specifier|static
specifier|final
name|String
name|ZK_DTSM_MASTER_KEY_ROOT
init|=
literal|"/ZKDTSMMasterKeyRoot"
decl_stmt|;
DECL|field|DELEGATION_KEY_PREFIX
specifier|private
specifier|static
specifier|final
name|String
name|DELEGATION_KEY_PREFIX
init|=
literal|"DK_"
decl_stmt|;
DECL|field|DELEGATION_TOKEN_PREFIX
specifier|private
specifier|static
specifier|final
name|String
name|DELEGATION_TOKEN_PREFIX
init|=
literal|"DT_"
decl_stmt|;
DECL|field|CURATOR_TL
specifier|private
specifier|static
specifier|final
name|ThreadLocal
argument_list|<
name|CuratorFramework
argument_list|>
name|CURATOR_TL
init|=
operator|new
name|ThreadLocal
argument_list|<
name|CuratorFramework
argument_list|>
argument_list|()
decl_stmt|;
DECL|method|setCurator (CuratorFramework curator)
specifier|public
specifier|static
name|void
name|setCurator
parameter_list|(
name|CuratorFramework
name|curator
parameter_list|)
block|{
name|CURATOR_TL
operator|.
name|set
argument_list|(
name|curator
argument_list|)
expr_stmt|;
block|}
DECL|field|isExternalClient
specifier|private
specifier|final
name|boolean
name|isExternalClient
decl_stmt|;
DECL|field|zkClient
specifier|private
specifier|final
name|CuratorFramework
name|zkClient
decl_stmt|;
DECL|field|delTokSeqCounter
specifier|private
name|SharedCount
name|delTokSeqCounter
decl_stmt|;
DECL|field|keyIdSeqCounter
specifier|private
name|SharedCount
name|keyIdSeqCounter
decl_stmt|;
DECL|field|keyCache
specifier|private
name|PathChildrenCache
name|keyCache
decl_stmt|;
DECL|field|tokenCache
specifier|private
name|PathChildrenCache
name|tokenCache
decl_stmt|;
DECL|field|listenerThreadPool
specifier|private
name|ExecutorService
name|listenerThreadPool
decl_stmt|;
DECL|field|shutdownTimeout
specifier|private
specifier|final
name|long
name|shutdownTimeout
decl_stmt|;
DECL|method|ZKDelegationTokenSecretManager (Configuration conf)
specifier|public
name|ZKDelegationTokenSecretManager
parameter_list|(
name|Configuration
name|conf
parameter_list|)
block|{
name|super
argument_list|(
name|conf
operator|.
name|getLong
argument_list|(
name|DelegationTokenManager
operator|.
name|UPDATE_INTERVAL
argument_list|,
name|DelegationTokenManager
operator|.
name|UPDATE_INTERVAL_DEFAULT
argument_list|)
operator|*
literal|1000
argument_list|,
name|conf
operator|.
name|getLong
argument_list|(
name|DelegationTokenManager
operator|.
name|MAX_LIFETIME
argument_list|,
name|DelegationTokenManager
operator|.
name|MAX_LIFETIME_DEFAULT
argument_list|)
operator|*
literal|1000
argument_list|,
name|conf
operator|.
name|getLong
argument_list|(
name|DelegationTokenManager
operator|.
name|RENEW_INTERVAL
argument_list|,
name|DelegationTokenManager
operator|.
name|RENEW_INTERVAL_DEFAULT
argument_list|)
operator|*
literal|1000
argument_list|,
name|conf
operator|.
name|getLong
argument_list|(
name|DelegationTokenManager
operator|.
name|REMOVAL_SCAN_INTERVAL
argument_list|,
name|DelegationTokenManager
operator|.
name|REMOVAL_SCAN_INTERVAL_DEFAULT
argument_list|)
operator|*
literal|1000
argument_list|)
expr_stmt|;
name|shutdownTimeout
operator|=
name|conf
operator|.
name|getLong
argument_list|(
name|ZK_DTSM_ZK_SHUTDOWN_TIMEOUT
argument_list|,
name|ZK_DTSM_ZK_SHUTDOWN_TIMEOUT_DEFAULT
argument_list|)
expr_stmt|;
if|if
condition|(
name|CURATOR_TL
operator|.
name|get
argument_list|()
operator|!=
literal|null
condition|)
block|{
name|zkClient
operator|=
name|CURATOR_TL
operator|.
name|get
argument_list|()
operator|.
name|usingNamespace
argument_list|(
name|conf
operator|.
name|get
argument_list|(
name|ZK_DTSM_ZNODE_WORKING_PATH
argument_list|,
name|ZK_DTSM_ZNODE_WORKING_PATH_DEAFULT
argument_list|)
operator|+
literal|"/"
operator|+
name|ZK_DTSM_NAMESPACE
argument_list|)
expr_stmt|;
name|isExternalClient
operator|=
literal|true
expr_stmt|;
block|}
else|else
block|{
name|String
name|connString
init|=
name|conf
operator|.
name|get
argument_list|(
name|ZK_DTSM_ZK_CONNECTION_STRING
argument_list|)
decl_stmt|;
name|Preconditions
operator|.
name|checkNotNull
argument_list|(
name|connString
argument_list|,
literal|"Zookeeper connection string cannot be null"
argument_list|)
expr_stmt|;
name|String
name|authType
init|=
name|conf
operator|.
name|get
argument_list|(
name|ZK_DTSM_ZK_AUTH_TYPE
argument_list|)
decl_stmt|;
comment|// AuthType has to be explicitly set to 'none' or 'sasl'
name|Preconditions
operator|.
name|checkNotNull
argument_list|(
name|authType
argument_list|,
literal|"Zookeeper authType cannot be null !!"
argument_list|)
expr_stmt|;
name|Preconditions
operator|.
name|checkArgument
argument_list|(
name|authType
operator|.
name|equals
argument_list|(
literal|"sasl"
argument_list|)
operator|||
name|authType
operator|.
name|equals
argument_list|(
literal|"none"
argument_list|)
argument_list|,
literal|"Zookeeper authType must be one of [none, sasl]"
argument_list|)
expr_stmt|;
name|Builder
name|builder
init|=
literal|null
decl_stmt|;
try|try
block|{
name|ACLProvider
name|aclProvider
init|=
literal|null
decl_stmt|;
if|if
condition|(
name|authType
operator|.
name|equals
argument_list|(
literal|"sasl"
argument_list|)
condition|)
block|{
name|LOG
operator|.
name|info
argument_list|(
literal|"Connecting to ZooKeeper with SASL/Kerberos"
operator|+
literal|"and using 'sasl' ACLs"
argument_list|)
expr_stmt|;
name|String
name|principal
init|=
name|setJaasConfiguration
argument_list|(
name|conf
argument_list|)
decl_stmt|;
name|System
operator|.
name|setProperty
argument_list|(
name|ZKClientConfig
operator|.
name|LOGIN_CONTEXT_NAME_KEY
argument_list|,
name|JAAS_LOGIN_ENTRY_NAME
argument_list|)
expr_stmt|;
name|System
operator|.
name|setProperty
argument_list|(
literal|"zookeeper.authProvider.1"
argument_list|,
literal|"org.apache.zookeeper.server.auth.SASLAuthenticationProvider"
argument_list|)
expr_stmt|;
name|aclProvider
operator|=
operator|new
name|SASLOwnerACLProvider
argument_list|(
name|principal
argument_list|)
expr_stmt|;
block|}
else|else
block|{
comment|// "none"
name|LOG
operator|.
name|info
argument_list|(
literal|"Connecting to ZooKeeper without authentication"
argument_list|)
expr_stmt|;
name|aclProvider
operator|=
operator|new
name|DefaultACLProvider
argument_list|()
expr_stmt|;
comment|// open to everyone
block|}
name|int
name|sessionT
init|=
name|conf
operator|.
name|getInt
argument_list|(
name|ZK_DTSM_ZK_SESSION_TIMEOUT
argument_list|,
name|ZK_DTSM_ZK_SESSION_TIMEOUT_DEFAULT
argument_list|)
decl_stmt|;
name|int
name|numRetries
init|=
name|conf
operator|.
name|getInt
argument_list|(
name|ZK_DTSM_ZK_NUM_RETRIES
argument_list|,
name|ZK_DTSM_ZK_NUM_RETRIES_DEFAULT
argument_list|)
decl_stmt|;
name|builder
operator|=
name|CuratorFrameworkFactory
operator|.
name|builder
argument_list|()
operator|.
name|aclProvider
argument_list|(
name|aclProvider
argument_list|)
operator|.
name|namespace
argument_list|(
name|conf
operator|.
name|get
argument_list|(
name|ZK_DTSM_ZNODE_WORKING_PATH
argument_list|,
name|ZK_DTSM_ZNODE_WORKING_PATH_DEAFULT
argument_list|)
operator|+
literal|"/"
operator|+
name|ZK_DTSM_NAMESPACE
argument_list|)
operator|.
name|sessionTimeoutMs
argument_list|(
name|sessionT
argument_list|)
operator|.
name|connectionTimeoutMs
argument_list|(
name|conf
operator|.
name|getInt
argument_list|(
name|ZK_DTSM_ZK_CONNECTION_TIMEOUT
argument_list|,
name|ZK_DTSM_ZK_CONNECTION_TIMEOUT_DEFAULT
argument_list|)
argument_list|)
operator|.
name|retryPolicy
argument_list|(
operator|new
name|RetryNTimes
argument_list|(
name|numRetries
argument_list|,
name|sessionT
operator|/
name|numRetries
argument_list|)
argument_list|)
expr_stmt|;
block|}
catch|catch
parameter_list|(
name|Exception
name|ex
parameter_list|)
block|{
throw|throw
operator|new
name|RuntimeException
argument_list|(
literal|"Could not Load ZK acls or auth: "
operator|+
name|ex
argument_list|,
name|ex
argument_list|)
throw|;
block|}
name|zkClient
operator|=
name|builder
operator|.
name|ensembleProvider
argument_list|(
operator|new
name|FixedEnsembleProvider
argument_list|(
name|connString
argument_list|)
argument_list|)
operator|.
name|build
argument_list|()
expr_stmt|;
name|isExternalClient
operator|=
literal|false
expr_stmt|;
block|}
block|}
DECL|method|setJaasConfiguration (Configuration config)
specifier|private
name|String
name|setJaasConfiguration
parameter_list|(
name|Configuration
name|config
parameter_list|)
throws|throws
name|Exception
block|{
name|String
name|keytabFile
init|=
name|config
operator|.
name|get
argument_list|(
name|ZK_DTSM_ZK_KERBEROS_KEYTAB
argument_list|,
literal|""
argument_list|)
operator|.
name|trim
argument_list|()
decl_stmt|;
if|if
condition|(
name|keytabFile
operator|==
literal|null
operator|||
name|keytabFile
operator|.
name|length
argument_list|()
operator|==
literal|0
condition|)
block|{
throw|throw
operator|new
name|IllegalArgumentException
argument_list|(
name|ZK_DTSM_ZK_KERBEROS_KEYTAB
operator|+
literal|" must be specified"
argument_list|)
throw|;
block|}
name|String
name|principal
init|=
name|config
operator|.
name|get
argument_list|(
name|ZK_DTSM_ZK_KERBEROS_PRINCIPAL
argument_list|,
literal|""
argument_list|)
operator|.
name|trim
argument_list|()
decl_stmt|;
name|principal
operator|=
name|SecurityUtil
operator|.
name|getServerPrincipal
argument_list|(
name|principal
argument_list|,
literal|""
argument_list|)
expr_stmt|;
if|if
condition|(
name|principal
operator|==
literal|null
operator|||
name|principal
operator|.
name|length
argument_list|()
operator|==
literal|0
condition|)
block|{
throw|throw
operator|new
name|IllegalArgumentException
argument_list|(
name|ZK_DTSM_ZK_KERBEROS_PRINCIPAL
operator|+
literal|" must be specified"
argument_list|)
throw|;
block|}
name|JaasConfiguration
name|jConf
init|=
operator|new
name|JaasConfiguration
argument_list|(
name|JAAS_LOGIN_ENTRY_NAME
argument_list|,
name|principal
argument_list|,
name|keytabFile
argument_list|)
decl_stmt|;
name|javax
operator|.
name|security
operator|.
name|auth
operator|.
name|login
operator|.
name|Configuration
operator|.
name|setConfiguration
argument_list|(
name|jConf
argument_list|)
expr_stmt|;
return|return
name|principal
operator|.
name|split
argument_list|(
literal|"[/@]"
argument_list|)
index|[
literal|0
index|]
return|;
block|}
comment|/** * Creates a programmatic version of a jaas.conf file. This can be used * instead of writing a jaas.conf file and setting the system property, * "java.security.auth.login.config", to point to that file. It is meant to be * used for connecting to ZooKeeper. */
annotation|@
name|InterfaceAudience
operator|.
name|Private
DECL|class|JaasConfiguration
specifier|public
specifier|static
class|class
name|JaasConfiguration
extends|extends
name|javax
operator|.
name|security
operator|.
name|auth
operator|.
name|login
operator|.
name|Configuration
block|{
DECL|field|baseConfig
specifier|private
specifier|final
name|javax
operator|.
name|security
operator|.
name|auth
operator|.
name|login
operator|.
name|Configuration
name|baseConfig
init|=
name|javax
operator|.
name|security
operator|.
name|auth
operator|.
name|login
operator|.
name|Configuration
operator|.
name|getConfiguration
argument_list|()
decl_stmt|;
DECL|field|entry
specifier|private
specifier|static
name|AppConfigurationEntry
index|[]
name|entry
decl_stmt|;
DECL|field|entryName
specifier|private
name|String
name|entryName
decl_stmt|;
comment|/** * Add an entry to the jaas configuration with the passed in name, * principal, and keytab. The other necessary options will be set for you. * * @param entryName * The name of the entry (e.g. "Client") * @param principal * The principal of the user * @param keytab * The location of the keytab */
DECL|method|JaasConfiguration (String entryName, String principal, String keytab)
specifier|public
name|JaasConfiguration
parameter_list|(
name|String
name|entryName
parameter_list|,
name|String
name|principal
parameter_list|,
name|String
name|keytab
parameter_list|)
block|{
name|this
operator|.
name|entryName
operator|=
name|entryName
expr_stmt|;
name|Map
argument_list|<
name|String
argument_list|,
name|String
argument_list|>
name|options
init|=
operator|new
name|HashMap
argument_list|<
name|String
argument_list|,
name|String
argument_list|>
argument_list|()
decl_stmt|;
name|options
operator|.
name|put
argument_list|(
literal|"keyTab"
argument_list|,
name|keytab
argument_list|)
expr_stmt|;
name|options
operator|.
name|put
argument_list|(
literal|"principal"
argument_list|,
name|principal
argument_list|)
expr_stmt|;
name|options
operator|.
name|put
argument_list|(
literal|"useKeyTab"
argument_list|,
literal|"true"
argument_list|)
expr_stmt|;
name|options
operator|.
name|put
argument_list|(
literal|"storeKey"
argument_list|,
literal|"true"
argument_list|)
expr_stmt|;
name|options
operator|.
name|put
argument_list|(
literal|"useTicketCache"
argument_list|,
literal|"false"
argument_list|)
expr_stmt|;
name|options
operator|.
name|put
argument_list|(
literal|"refreshKrb5Config"
argument_list|,
literal|"true"
argument_list|)
expr_stmt|;
name|String
name|jaasEnvVar
init|=
name|System
operator|.
name|getenv
argument_list|(
literal|"HADOOP_JAAS_DEBUG"
argument_list|)
decl_stmt|;
if|if
condition|(
name|jaasEnvVar
operator|!=
literal|null
operator|&&
literal|"true"
operator|.
name|equalsIgnoreCase
argument_list|(
name|jaasEnvVar
argument_list|)
condition|)
block|{
name|options
operator|.
name|put
argument_list|(
literal|"debug"
argument_list|,
literal|"true"
argument_list|)
expr_stmt|;
block|}
name|entry
operator|=
operator|new
name|AppConfigurationEntry
index|[]
block|{
operator|new
name|AppConfigurationEntry
argument_list|(
name|getKrb5LoginModuleName
argument_list|()
argument_list|,
name|AppConfigurationEntry
operator|.
name|LoginModuleControlFlag
operator|.
name|REQUIRED
argument_list|,
name|options
argument_list|)
block|}
expr_stmt|;
block|}
annotation|@
name|Override
DECL|method|getAppConfigurationEntry (String name)
specifier|public
name|AppConfigurationEntry
index|[]
name|getAppConfigurationEntry
parameter_list|(
name|String
name|name
parameter_list|)
block|{
return|return
operator|(
name|entryName
operator|.
name|equals
argument_list|(
name|name
argument_list|)
operator|)
condition|?
name|entry
else|:
operator|(
operator|(
name|baseConfig
operator|!=
literal|null
operator|)
condition|?
name|baseConfig
operator|.
name|getAppConfigurationEntry
argument_list|(
name|name
argument_list|)
else|:
literal|null
operator|)
return|;
block|}
DECL|method|getKrb5LoginModuleName ()
specifier|private
name|String
name|getKrb5LoginModuleName
parameter_list|()
block|{
name|String
name|krb5LoginModuleName
decl_stmt|;
if|if
condition|(
name|System
operator|.
name|getProperty
argument_list|(
literal|"java.vendor"
argument_list|)
operator|.
name|contains
argument_list|(
literal|"IBM"
argument_list|)
condition|)
block|{
name|krb5LoginModuleName
operator|=
literal|"com.ibm.security.auth.module.Krb5LoginModule"
expr_stmt|;
block|}
else|else
block|{
name|krb5LoginModuleName
operator|=
literal|"com.sun.security.auth.module.Krb5LoginModule"
expr_stmt|;
block|}
return|return
name|krb5LoginModuleName
return|;
block|}
block|}
annotation|@
name|Override
DECL|method|startThreads ()
specifier|public
name|void
name|startThreads
parameter_list|()
throws|throws
name|IOException
block|{
if|if
condition|(
operator|!
name|isExternalClient
condition|)
block|{
try|try
block|{
name|zkClient
operator|.
name|start
argument_list|()
expr_stmt|;
block|}
catch|catch
parameter_list|(
name|Exception
name|e
parameter_list|)
block|{
throw|throw
operator|new
name|IOException
argument_list|(
literal|"Could not start Curator Framework"
argument_list|,
name|e
argument_list|)
throw|;
block|}
block|}
else|else
block|{
comment|// If namespace parents are implicitly created, they won't have ACLs.
comment|// So, let's explicitly create them.
name|CuratorFramework
name|nullNsFw
init|=
name|zkClient
operator|.
name|usingNamespace
argument_list|(
literal|null
argument_list|)
decl_stmt|;
name|EnsurePath
name|ensureNs
init|=
name|nullNsFw
operator|.
name|newNamespaceAwareEnsurePath
argument_list|(
literal|"/"
operator|+
name|zkClient
operator|.
name|getNamespace
argument_list|()
argument_list|)
decl_stmt|;
try|try
block|{
name|ensureNs
operator|.
name|ensure
argument_list|(
name|nullNsFw
operator|.
name|getZookeeperClient
argument_list|()
argument_list|)
expr_stmt|;
block|}
catch|catch
parameter_list|(
name|Exception
name|e
parameter_list|)
block|{
throw|throw
operator|new
name|IOException
argument_list|(
literal|"Could not create namespace"
argument_list|,
name|e
argument_list|)
throw|;
block|}
block|}
name|listenerThreadPool
operator|=
name|Executors
operator|.
name|newSingleThreadExecutor
argument_list|()
expr_stmt|;
try|try
block|{
name|delTokSeqCounter
operator|=
operator|new
name|SharedCount
argument_list|(
name|zkClient
argument_list|,
name|ZK_DTSM_SEQNUM_ROOT
argument_list|,
literal|0
argument_list|)
expr_stmt|;
if|if
condition|(
name|delTokSeqCounter
operator|!=
literal|null
condition|)
block|{
name|delTokSeqCounter
operator|.
name|start
argument_list|()
expr_stmt|;
block|}
block|}
catch|catch
parameter_list|(
name|Exception
name|e
parameter_list|)
block|{
throw|throw
operator|new
name|IOException
argument_list|(
literal|"Could not start Sequence Counter"
argument_list|,
name|e
argument_list|)
throw|;
block|}
try|try
block|{
name|keyIdSeqCounter
operator|=
operator|new
name|SharedCount
argument_list|(
name|zkClient
argument_list|,
name|ZK_DTSM_KEYID_ROOT
argument_list|,
literal|0
argument_list|)
expr_stmt|;
if|if
condition|(
name|keyIdSeqCounter
operator|!=
literal|null
condition|)
block|{
name|keyIdSeqCounter
operator|.
name|start
argument_list|()
expr_stmt|;
block|}
block|}
catch|catch
parameter_list|(
name|Exception
name|e
parameter_list|)
block|{
throw|throw
operator|new
name|IOException
argument_list|(
literal|"Could not start KeyId Counter"
argument_list|,
name|e
argument_list|)
throw|;
block|}
try|try
block|{
name|createPersistentNode
argument_list|(
name|ZK_DTSM_MASTER_KEY_ROOT
argument_list|)
expr_stmt|;
name|createPersistentNode
argument_list|(
name|ZK_DTSM_TOKENS_ROOT
argument_list|)
expr_stmt|;
block|}
catch|catch
parameter_list|(
name|Exception
name|e
parameter_list|)
block|{
throw|throw
operator|new
name|RuntimeException
argument_list|(
literal|"Could not create ZK paths"
argument_list|)
throw|;
block|}
try|try
block|{
name|keyCache
operator|=
operator|new
name|PathChildrenCache
argument_list|(
name|zkClient
argument_list|,
name|ZK_DTSM_MASTER_KEY_ROOT
argument_list|,
literal|true
argument_list|)
expr_stmt|;
if|if
condition|(
name|keyCache
operator|!=
literal|null
condition|)
block|{
name|keyCache
operator|.
name|start
argument_list|(
name|StartMode
operator|.
name|BUILD_INITIAL_CACHE
argument_list|)
expr_stmt|;
name|keyCache
operator|.
name|getListenable
argument_list|()
operator|.
name|addListener
argument_list|(
operator|new
name|PathChildrenCacheListener
argument_list|()
block|{
annotation|@
name|Override
specifier|public
name|void
name|childEvent
parameter_list|(
name|CuratorFramework
name|client
parameter_list|,
name|PathChildrenCacheEvent
name|event
parameter_list|)
throws|throws
name|Exception
block|{
switch|switch
condition|(
name|event
operator|.
name|getType
argument_list|()
condition|)
block|{
case|case
name|CHILD_ADDED
case|:
name|processKeyAddOrUpdate
argument_list|(
name|event
operator|.
name|getData
argument_list|()
operator|.
name|getData
argument_list|()
argument_list|)
expr_stmt|;
break|break;
case|case
name|CHILD_UPDATED
case|:
name|processKeyAddOrUpdate
argument_list|(
name|event
operator|.
name|getData
argument_list|()
operator|.
name|getData
argument_list|()
argument_list|)
expr_stmt|;
break|break;
case|case
name|CHILD_REMOVED
case|:
name|processKeyRemoved
argument_list|(
name|event
operator|.
name|getData
argument_list|()
operator|.
name|getPath
argument_list|()
argument_list|)
expr_stmt|;
break|break;
default|default:
break|break;
block|}
block|}
block|}
argument_list|,
name|listenerThreadPool
argument_list|)
expr_stmt|;
name|loadFromZKCache
argument_list|(
literal|false
argument_list|)
expr_stmt|;
block|}
block|}
catch|catch
parameter_list|(
name|Exception
name|e
parameter_list|)
block|{
throw|throw
operator|new
name|IOException
argument_list|(
literal|"Could not start PathChildrenCache for keys"
argument_list|,
name|e
argument_list|)
throw|;
block|}
try|try
block|{
name|tokenCache
operator|=
operator|new
name|PathChildrenCache
argument_list|(
name|zkClient
argument_list|,
name|ZK_DTSM_TOKENS_ROOT
argument_list|,
literal|true
argument_list|)
expr_stmt|;
if|if
condition|(
name|tokenCache
operator|!=
literal|null
condition|)
block|{
name|tokenCache
operator|.
name|start
argument_list|(
name|StartMode
operator|.
name|BUILD_INITIAL_CACHE
argument_list|)
expr_stmt|;
name|tokenCache
operator|.
name|getListenable
argument_list|()
operator|.
name|addListener
argument_list|(
operator|new
name|PathChildrenCacheListener
argument_list|()
block|{
annotation|@
name|Override
specifier|public
name|void
name|childEvent
parameter_list|(
name|CuratorFramework
name|client
parameter_list|,
name|PathChildrenCacheEvent
name|event
parameter_list|)
throws|throws
name|Exception
block|{
switch|switch
condition|(
name|event
operator|.
name|getType
argument_list|()
condition|)
block|{
case|case
name|CHILD_ADDED
case|:
name|processTokenAddOrUpdate
argument_list|(
name|event
operator|.
name|getData
argument_list|()
argument_list|)
expr_stmt|;
break|break;
case|case
name|CHILD_UPDATED
case|:
name|processTokenAddOrUpdate
argument_list|(
name|event
operator|.
name|getData
argument_list|()
argument_list|)
expr_stmt|;
break|break;
case|case
name|CHILD_REMOVED
case|:
name|processTokenRemoved
argument_list|(
name|event
operator|.
name|getData
argument_list|()
argument_list|)
expr_stmt|;
break|break;
default|default:
break|break;
block|}
block|}
block|}
argument_list|,
name|listenerThreadPool
argument_list|)
expr_stmt|;
name|loadFromZKCache
argument_list|(
literal|true
argument_list|)
expr_stmt|;
block|}
block|}
catch|catch
parameter_list|(
name|Exception
name|e
parameter_list|)
block|{
throw|throw
operator|new
name|IOException
argument_list|(
literal|"Could not start PathChildrenCache for tokens"
argument_list|,
name|e
argument_list|)
throw|;
block|}
name|super
operator|.
name|startThreads
argument_list|()
expr_stmt|;
block|}
comment|/** * Load the PathChildrenCache into the in-memory map. Possible caches to be * loaded are keyCache and tokenCache. * * @param isTokenCache true if loading tokenCache, false if loading keyCache. */
DECL|method|loadFromZKCache (final boolean isTokenCache)
specifier|private
name|void
name|loadFromZKCache
parameter_list|(
specifier|final
name|boolean
name|isTokenCache
parameter_list|)
block|{
specifier|final
name|String
name|cacheName
init|=
name|isTokenCache
condition|?
literal|"token"
else|:
literal|"key"
decl_stmt|;
name|LOG
operator|.
name|info
argument_list|(
literal|"Starting to load {} cache."
argument_list|,
name|cacheName
argument_list|)
expr_stmt|;
specifier|final
name|List
argument_list|<
name|ChildData
argument_list|>
name|children
decl_stmt|;
if|if
condition|(
name|isTokenCache
condition|)
block|{
name|children
operator|=
name|tokenCache
operator|.
name|getCurrentData
argument_list|()
expr_stmt|;
block|}
else|else
block|{
name|children
operator|=
name|keyCache
operator|.
name|getCurrentData
argument_list|()
expr_stmt|;
block|}
name|int
name|count
init|=
literal|0
decl_stmt|;
for|for
control|(
name|ChildData
name|child
range|:
name|children
control|)
block|{
try|try
block|{
if|if
condition|(
name|isTokenCache
condition|)
block|{
name|processTokenAddOrUpdate
argument_list|(
name|child
argument_list|)
expr_stmt|;
block|}
else|else
block|{
name|processKeyAddOrUpdate
argument_list|(
name|child
operator|.
name|getData
argument_list|()
argument_list|)
expr_stmt|;
block|}
block|}
catch|catch
parameter_list|(
name|Exception
name|e
parameter_list|)
block|{
name|LOG
operator|.
name|info
argument_list|(
literal|"Ignoring node {} because it failed to load."
argument_list|,
name|child
operator|.
name|getPath
argument_list|()
argument_list|)
expr_stmt|;
name|LOG
operator|.
name|debug
argument_list|(
literal|"Failure exception:"
argument_list|,
name|e
argument_list|)
expr_stmt|;
operator|++
name|count
expr_stmt|;
block|}
block|}
if|if
condition|(
name|count
operator|>
literal|0
condition|)
block|{
name|LOG
operator|.
name|warn
argument_list|(
literal|"Ignored {} nodes while loading {} cache."
argument_list|,
name|count
argument_list|,
name|cacheName
argument_list|)
expr_stmt|;
block|}
name|LOG
operator|.
name|info
argument_list|(
literal|"Loaded {} cache."
argument_list|,
name|cacheName
argument_list|)
expr_stmt|;
block|}
DECL|method|processKeyAddOrUpdate (byte[] data)
specifier|private
name|void
name|processKeyAddOrUpdate
parameter_list|(
name|byte
index|[]
name|data
parameter_list|)
throws|throws
name|IOException
block|{
name|ByteArrayInputStream
name|bin
init|=
operator|new
name|ByteArrayInputStream
argument_list|(
name|data
argument_list|)
decl_stmt|;
name|DataInputStream
name|din
init|=
operator|new
name|DataInputStream
argument_list|(
name|bin
argument_list|)
decl_stmt|;
name|DelegationKey
name|key
init|=
operator|new
name|DelegationKey
argument_list|()
decl_stmt|;
name|key
operator|.
name|readFields
argument_list|(
name|din
argument_list|)
expr_stmt|;
synchronized|synchronized
init|(
name|this
init|)
block|{
name|allKeys
operator|.
name|put
argument_list|(
name|key
operator|.
name|getKeyId
argument_list|()
argument_list|,
name|key
argument_list|)
expr_stmt|;
block|}
block|}
DECL|method|processKeyRemoved (String path)
specifier|private
name|void
name|processKeyRemoved
parameter_list|(
name|String
name|path
parameter_list|)
block|{
name|int
name|i
init|=
name|path
operator|.
name|lastIndexOf
argument_list|(
literal|'/'
argument_list|)
decl_stmt|;
if|if
condition|(
name|i
operator|>
literal|0
condition|)
block|{
name|String
name|tokSeg
init|=
name|path
operator|.
name|substring
argument_list|(
name|i
operator|+
literal|1
argument_list|)
decl_stmt|;
name|int
name|j
init|=
name|tokSeg
operator|.
name|indexOf
argument_list|(
literal|'_'
argument_list|)
decl_stmt|;
if|if
condition|(
name|j
operator|>
literal|0
condition|)
block|{
name|int
name|keyId
init|=
name|Integer
operator|.
name|parseInt
argument_list|(
name|tokSeg
operator|.
name|substring
argument_list|(
name|j
operator|+
literal|1
argument_list|)
argument_list|)
decl_stmt|;
synchronized|synchronized
init|(
name|this
init|)
block|{
name|allKeys
operator|.
name|remove
argument_list|(
name|keyId
argument_list|)
expr_stmt|;
block|}
block|}
block|}
block|}
DECL|method|processTokenAddOrUpdate (ChildData data)
specifier|private
name|void
name|processTokenAddOrUpdate
parameter_list|(
name|ChildData
name|data
parameter_list|)
throws|throws
name|IOException
block|{
name|ByteArrayInputStream
name|bin
init|=
operator|new
name|ByteArrayInputStream
argument_list|(
name|data
operator|.
name|getData
argument_list|()
argument_list|)
decl_stmt|;
name|DataInputStream
name|din
init|=
operator|new
name|DataInputStream
argument_list|(
name|bin
argument_list|)
decl_stmt|;
name|TokenIdent
name|ident
init|=
name|createIdentifier
argument_list|()
decl_stmt|;
name|ident
operator|.
name|readFields
argument_list|(
name|din
argument_list|)
expr_stmt|;
name|long
name|renewDate
init|=
name|din
operator|.
name|readLong
argument_list|()
decl_stmt|;
name|int
name|pwdLen
init|=
name|din
operator|.
name|readInt
argument_list|()
decl_stmt|;
name|byte
index|[]
name|password
init|=
operator|new
name|byte
index|[
name|pwdLen
index|]
decl_stmt|;
name|int
name|numRead
init|=
name|din
operator|.
name|read
argument_list|(
name|password
argument_list|,
literal|0
argument_list|,
name|pwdLen
argument_list|)
decl_stmt|;
if|if
condition|(
name|numRead
operator|>
operator|-
literal|1
condition|)
block|{
name|DelegationTokenInformation
name|tokenInfo
init|=
operator|new
name|DelegationTokenInformation
argument_list|(
name|renewDate
argument_list|,
name|password
argument_list|)
decl_stmt|;
synchronized|synchronized
init|(
name|this
init|)
block|{
name|currentTokens
operator|.
name|put
argument_list|(
name|ident
argument_list|,
name|tokenInfo
argument_list|)
expr_stmt|;
comment|// The cancel task might be waiting
name|notifyAll
argument_list|()
expr_stmt|;
block|}
block|}
block|}
DECL|method|processTokenRemoved (ChildData data)
specifier|private
name|void
name|processTokenRemoved
parameter_list|(
name|ChildData
name|data
parameter_list|)
throws|throws
name|IOException
block|{
name|ByteArrayInputStream
name|bin
init|=
operator|new
name|ByteArrayInputStream
argument_list|(
name|data
operator|.
name|getData
argument_list|()
argument_list|)
decl_stmt|;
name|DataInputStream
name|din
init|=
operator|new
name|DataInputStream
argument_list|(
name|bin
argument_list|)
decl_stmt|;
name|TokenIdent
name|ident
init|=
name|createIdentifier
argument_list|()
decl_stmt|;
name|ident
operator|.
name|readFields
argument_list|(
name|din
argument_list|)
expr_stmt|;
synchronized|synchronized
init|(
name|this
init|)
block|{
name|currentTokens
operator|.
name|remove
argument_list|(
name|ident
argument_list|)
expr_stmt|;
comment|// The cancel task might be waiting
name|notifyAll
argument_list|()
expr_stmt|;
block|}
block|}
annotation|@
name|Override
DECL|method|stopThreads ()
specifier|public
name|void
name|stopThreads
parameter_list|()
block|{
name|super
operator|.
name|stopThreads
argument_list|()
expr_stmt|;
try|try
block|{
if|if
condition|(
name|tokenCache
operator|!=
literal|null
condition|)
block|{
name|tokenCache
operator|.
name|close
argument_list|()
expr_stmt|;
block|}
block|}
catch|catch
parameter_list|(
name|Exception
name|e
parameter_list|)
block|{
name|LOG
operator|.
name|error
argument_list|(
literal|"Could not stop Delegation Token Cache"
argument_list|,
name|e
argument_list|)
expr_stmt|;
block|}
try|try
block|{
if|if
condition|(
name|delTokSeqCounter
operator|!=
literal|null
condition|)
block|{
name|delTokSeqCounter
operator|.
name|close
argument_list|()
expr_stmt|;
block|}
block|}
catch|catch
parameter_list|(
name|Exception
name|e
parameter_list|)
block|{
name|LOG
operator|.
name|error
argument_list|(
literal|"Could not stop Delegation Token Counter"
argument_list|,
name|e
argument_list|)
expr_stmt|;
block|}
try|try
block|{
if|if
condition|(
name|keyIdSeqCounter
operator|!=
literal|null
condition|)
block|{
name|keyIdSeqCounter
operator|.
name|close
argument_list|()
expr_stmt|;
block|}
block|}
catch|catch
parameter_list|(
name|Exception
name|e
parameter_list|)
block|{
name|LOG
operator|.
name|error
argument_list|(
literal|"Could not stop Key Id Counter"
argument_list|,
name|e
argument_list|)
expr_stmt|;
block|}
try|try
block|{
if|if
condition|(
name|keyCache
operator|!=
literal|null
condition|)
block|{
name|keyCache
operator|.
name|close
argument_list|()
expr_stmt|;
block|}
block|}
catch|catch
parameter_list|(
name|Exception
name|e
parameter_list|)
block|{
name|LOG
operator|.
name|error
argument_list|(
literal|"Could not stop KeyCache"
argument_list|,
name|e
argument_list|)
expr_stmt|;
block|}
try|try
block|{
if|if
condition|(
operator|!
name|isExternalClient
operator|&&
operator|(
name|zkClient
operator|!=
literal|null
operator|)
condition|)
block|{
name|zkClient
operator|.
name|close
argument_list|()
expr_stmt|;
block|}
block|}
catch|catch
parameter_list|(
name|Exception
name|e
parameter_list|)
block|{
name|LOG
operator|.
name|error
argument_list|(
literal|"Could not stop Curator Framework"
argument_list|,
name|e
argument_list|)
expr_stmt|;
block|}
if|if
condition|(
name|listenerThreadPool
operator|!=
literal|null
condition|)
block|{
name|listenerThreadPool
operator|.
name|shutdown
argument_list|()
expr_stmt|;
try|try
block|{
comment|// wait for existing tasks to terminate
if|if
condition|(
operator|!
name|listenerThreadPool
operator|.
name|awaitTermination
argument_list|(
name|shutdownTimeout
argument_list|,
name|TimeUnit
operator|.
name|MILLISECONDS
argument_list|)
condition|)
block|{
name|LOG
operator|.
name|error
argument_list|(
literal|"Forcing Listener threadPool to shutdown !!"
argument_list|)
expr_stmt|;
name|listenerThreadPool
operator|.
name|shutdownNow
argument_list|()
expr_stmt|;
block|}
block|}
catch|catch
parameter_list|(
name|InterruptedException
name|ie
parameter_list|)
block|{
name|listenerThreadPool
operator|.
name|shutdownNow
argument_list|()
expr_stmt|;
name|Thread
operator|.
name|currentThread
argument_list|()
operator|.
name|interrupt
argument_list|()
expr_stmt|;
block|}
block|}
block|}
DECL|method|createPersistentNode (String nodePath)
specifier|private
name|void
name|createPersistentNode
parameter_list|(
name|String
name|nodePath
parameter_list|)
throws|throws
name|Exception
block|{
try|try
block|{
name|zkClient
operator|.
name|create
argument_list|()
operator|.
name|withMode
argument_list|(
name|CreateMode
operator|.
name|PERSISTENT
argument_list|)
operator|.
name|forPath
argument_list|(
name|nodePath
argument_list|)
expr_stmt|;
block|}
catch|catch
parameter_list|(
name|KeeperException
operator|.
name|NodeExistsException
name|ne
parameter_list|)
block|{
name|LOG
operator|.
name|debug
argument_list|(
name|nodePath
operator|+
literal|" znode already exists !!"
argument_list|)
expr_stmt|;
block|}
catch|catch
parameter_list|(
name|Exception
name|e
parameter_list|)
block|{
throw|throw
operator|new
name|IOException
argument_list|(
name|nodePath
operator|+
literal|" znode could not be created !!"
argument_list|,
name|e
argument_list|)
throw|;
block|}
block|}
annotation|@
name|Override
DECL|method|getDelegationTokenSeqNum ()
specifier|protected
name|int
name|getDelegationTokenSeqNum
parameter_list|()
block|{
return|return
name|delTokSeqCounter
operator|.
name|getCount
argument_list|()
return|;
block|}
DECL|method|incrSharedCount (SharedCount sharedCount)
specifier|private
name|void
name|incrSharedCount
parameter_list|(
name|SharedCount
name|sharedCount
parameter_list|)
throws|throws
name|Exception
block|{
while|while
condition|(
literal|true
condition|)
block|{
comment|// Loop until we successfully increment the counter
name|VersionedValue
argument_list|<
name|Integer
argument_list|>
name|versionedValue
init|=
name|sharedCount
operator|.
name|getVersionedValue
argument_list|()
decl_stmt|;
if|if
condition|(
name|sharedCount
operator|.
name|trySetCount
argument_list|(
name|versionedValue
argument_list|,
name|versionedValue
operator|.
name|getValue
argument_list|()
operator|+
literal|1
argument_list|)
condition|)
block|{
break|break;
block|}
block|}
block|}
annotation|@
name|Override
DECL|method|incrementDelegationTokenSeqNum ()
specifier|protected
name|int
name|incrementDelegationTokenSeqNum
parameter_list|()
block|{
try|try
block|{
name|incrSharedCount
argument_list|(
name|delTokSeqCounter
argument_list|)
expr_stmt|;
block|}
catch|catch
parameter_list|(
name|InterruptedException
name|e
parameter_list|)
block|{
comment|// The ExpirationThread is just finishing.. so dont do anything..
name|LOG
operator|.
name|debug
argument_list|(
literal|"Thread interrupted while performing token counter increment"
argument_list|,
name|e
argument_list|)
expr_stmt|;
name|Thread
operator|.
name|currentThread
argument_list|()
operator|.
name|interrupt
argument_list|()
expr_stmt|;
block|}
catch|catch
parameter_list|(
name|Exception
name|e
parameter_list|)
block|{
throw|throw
operator|new
name|RuntimeException
argument_list|(
literal|"Could not increment shared counter !!"
argument_list|,
name|e
argument_list|)
throw|;
block|}
return|return
name|delTokSeqCounter
operator|.
name|getCount
argument_list|()
return|;
block|}
annotation|@
name|Override
DECL|method|setDelegationTokenSeqNum (int seqNum)
specifier|protected
name|void
name|setDelegationTokenSeqNum
parameter_list|(
name|int
name|seqNum
parameter_list|)
block|{
try|try
block|{
name|delTokSeqCounter
operator|.
name|setCount
argument_list|(
name|seqNum
argument_list|)
expr_stmt|;
block|}
catch|catch
parameter_list|(
name|Exception
name|e
parameter_list|)
block|{
throw|throw
operator|new
name|RuntimeException
argument_list|(
literal|"Could not set shared counter !!"
argument_list|,
name|e
argument_list|)
throw|;
block|}
block|}
annotation|@
name|Override
DECL|method|getCurrentKeyId ()
specifier|protected
name|int
name|getCurrentKeyId
parameter_list|()
block|{
return|return
name|keyIdSeqCounter
operator|.
name|getCount
argument_list|()
return|;
block|}
annotation|@
name|Override
DECL|method|incrementCurrentKeyId ()
specifier|protected
name|int
name|incrementCurrentKeyId
parameter_list|()
block|{
try|try
block|{
name|incrSharedCount
argument_list|(
name|keyIdSeqCounter
argument_list|)
expr_stmt|;
block|}
catch|catch
parameter_list|(
name|InterruptedException
name|e
parameter_list|)
block|{
comment|// The ExpirationThread is just finishing.. so dont do anything..
name|LOG
operator|.
name|debug
argument_list|(
literal|"Thread interrupted while performing keyId increment"
argument_list|,
name|e
argument_list|)
expr_stmt|;
name|Thread
operator|.
name|currentThread
argument_list|()
operator|.
name|interrupt
argument_list|()
expr_stmt|;
block|}
catch|catch
parameter_list|(
name|Exception
name|e
parameter_list|)
block|{
throw|throw
operator|new
name|RuntimeException
argument_list|(
literal|"Could not increment shared keyId counter !!"
argument_list|,
name|e
argument_list|)
throw|;
block|}
return|return
name|keyIdSeqCounter
operator|.
name|getCount
argument_list|()
return|;
block|}
annotation|@
name|Override
DECL|method|getDelegationKey (int keyId)
specifier|protected
name|DelegationKey
name|getDelegationKey
parameter_list|(
name|int
name|keyId
parameter_list|)
block|{
comment|// First check if its I already have this key
name|DelegationKey
name|key
init|=
name|allKeys
operator|.
name|get
argument_list|(
name|keyId
argument_list|)
decl_stmt|;
comment|// Then query ZK
if|if
condition|(
name|key
operator|==
literal|null
condition|)
block|{
try|try
block|{
name|key
operator|=
name|getKeyFromZK
argument_list|(
name|keyId
argument_list|)
expr_stmt|;
if|if
condition|(
name|key
operator|!=
literal|null
condition|)
block|{
name|allKeys
operator|.
name|put
argument_list|(
name|keyId
argument_list|,
name|key
argument_list|)
expr_stmt|;
block|}
block|}
catch|catch
parameter_list|(
name|IOException
name|e
parameter_list|)
block|{
name|LOG
operator|.
name|error
argument_list|(
literal|"Error retrieving key ["
operator|+
name|keyId
operator|+
literal|"] from ZK"
argument_list|,
name|e
argument_list|)
expr_stmt|;
block|}
block|}
return|return
name|key
return|;
block|}
DECL|method|getKeyFromZK (int keyId)
specifier|private
name|DelegationKey
name|getKeyFromZK
parameter_list|(
name|int
name|keyId
parameter_list|)
throws|throws
name|IOException
block|{
name|String
name|nodePath
init|=
name|getNodePath
argument_list|(
name|ZK_DTSM_MASTER_KEY_ROOT
argument_list|,
name|DELEGATION_KEY_PREFIX
operator|+
name|keyId
argument_list|)
decl_stmt|;
try|try
block|{
name|byte
index|[]
name|data
init|=
name|zkClient
operator|.
name|getData
argument_list|()
operator|.
name|forPath
argument_list|(
name|nodePath
argument_list|)
decl_stmt|;
if|if
condition|(
operator|(
name|data
operator|==
literal|null
operator|)
operator|||
operator|(
name|data
operator|.
name|length
operator|==
literal|0
operator|)
condition|)
block|{
return|return
literal|null
return|;
block|}
name|ByteArrayInputStream
name|bin
init|=
operator|new
name|ByteArrayInputStream
argument_list|(
name|data
argument_list|)
decl_stmt|;
name|DataInputStream
name|din
init|=
operator|new
name|DataInputStream
argument_list|(
name|bin
argument_list|)
decl_stmt|;
name|DelegationKey
name|key
init|=
operator|new
name|DelegationKey
argument_list|()
decl_stmt|;
name|key
operator|.
name|readFields
argument_list|(
name|din
argument_list|)
expr_stmt|;
return|return
name|key
return|;
block|}
catch|catch
parameter_list|(
name|KeeperException
operator|.
name|NoNodeException
name|e
parameter_list|)
block|{
name|LOG
operator|.
name|error
argument_list|(
literal|"No node in path ["
operator|+
name|nodePath
operator|+
literal|"]"
argument_list|)
expr_stmt|;
block|}
catch|catch
parameter_list|(
name|Exception
name|ex
parameter_list|)
block|{
throw|throw
operator|new
name|IOException
argument_list|(
name|ex
argument_list|)
throw|;
block|}
return|return
literal|null
return|;
block|}
annotation|@
name|Override
DECL|method|getTokenInfo (TokenIdent ident)
specifier|protected
name|DelegationTokenInformation
name|getTokenInfo
parameter_list|(
name|TokenIdent
name|ident
parameter_list|)
block|{
comment|// First check if I have this..
name|DelegationTokenInformation
name|tokenInfo
init|=
name|currentTokens
operator|.
name|get
argument_list|(
name|ident
argument_list|)
decl_stmt|;
comment|// Then query ZK
if|if
condition|(
name|tokenInfo
operator|==
literal|null
condition|)
block|{
try|try
block|{
name|tokenInfo
operator|=
name|getTokenInfoFromZK
argument_list|(
name|ident
argument_list|)
expr_stmt|;
if|if
condition|(
name|tokenInfo
operator|!=
literal|null
condition|)
block|{
name|currentTokens
operator|.
name|put
argument_list|(
name|ident
argument_list|,
name|tokenInfo
argument_list|)
expr_stmt|;
block|}
block|}
catch|catch
parameter_list|(
name|IOException
name|e
parameter_list|)
block|{
name|LOG
operator|.
name|error
argument_list|(
literal|"Error retrieving tokenInfo ["
operator|+
name|ident
operator|.
name|getSequenceNumber
argument_list|()
operator|+
literal|"] from ZK"
argument_list|,
name|e
argument_list|)
expr_stmt|;
block|}
block|}
return|return
name|tokenInfo
return|;
block|}
comment|/** * This method synchronizes the state of a delegation token information in * local cache with its actual value in Zookeeper. * * @param ident Identifier of the token */
DECL|method|syncLocalCacheWithZk (TokenIdent ident)
specifier|private
specifier|synchronized
name|void
name|syncLocalCacheWithZk
parameter_list|(
name|TokenIdent
name|ident
parameter_list|)
block|{
try|try
block|{
name|DelegationTokenInformation
name|tokenInfo
init|=
name|getTokenInfoFromZK
argument_list|(
name|ident
argument_list|)
decl_stmt|;
if|if
condition|(
name|tokenInfo
operator|!=
literal|null
operator|&&
operator|!
name|currentTokens
operator|.
name|containsKey
argument_list|(
name|ident
argument_list|)
condition|)
block|{
name|currentTokens
operator|.
name|put
argument_list|(
name|ident
argument_list|,
name|tokenInfo
argument_list|)
expr_stmt|;
block|}
elseif|else
if|if
condition|(
name|tokenInfo
operator|==
literal|null
operator|&&
name|currentTokens
operator|.
name|containsKey
argument_list|(
name|ident
argument_list|)
condition|)
block|{
name|currentTokens
operator|.
name|remove
argument_list|(
name|ident
argument_list|)
expr_stmt|;
block|}
block|}
catch|catch
parameter_list|(
name|IOException
name|e
parameter_list|)
block|{
name|LOG
operator|.
name|error
argument_list|(
literal|"Error retrieving tokenInfo ["
operator|+
name|ident
operator|.
name|getSequenceNumber
argument_list|()
operator|+
literal|"] from ZK"
argument_list|,
name|e
argument_list|)
expr_stmt|;
block|}
block|}
DECL|method|getTokenInfoFromZK (TokenIdent ident)
specifier|private
name|DelegationTokenInformation
name|getTokenInfoFromZK
parameter_list|(
name|TokenIdent
name|ident
parameter_list|)
throws|throws
name|IOException
block|{
return|return
name|getTokenInfoFromZK
argument_list|(
name|ident
argument_list|,
literal|false
argument_list|)
return|;
block|}
DECL|method|getTokenInfoFromZK (TokenIdent ident, boolean quiet)
specifier|private
name|DelegationTokenInformation
name|getTokenInfoFromZK
parameter_list|(
name|TokenIdent
name|ident
parameter_list|,
name|boolean
name|quiet
parameter_list|)
throws|throws
name|IOException
block|{
name|String
name|nodePath
init|=
name|getNodePath
argument_list|(
name|ZK_DTSM_TOKENS_ROOT
argument_list|,
name|DELEGATION_TOKEN_PREFIX
operator|+
name|ident
operator|.
name|getSequenceNumber
argument_list|()
argument_list|)
decl_stmt|;
try|try
block|{
name|byte
index|[]
name|data
init|=
name|zkClient
operator|.
name|getData
argument_list|()
operator|.
name|forPath
argument_list|(
name|nodePath
argument_list|)
decl_stmt|;
if|if
condition|(
operator|(
name|data
operator|==
literal|null
operator|)
operator|||
operator|(
name|data
operator|.
name|length
operator|==
literal|0
operator|)
condition|)
block|{
return|return
literal|null
return|;
block|}
name|ByteArrayInputStream
name|bin
init|=
operator|new
name|ByteArrayInputStream
argument_list|(
name|data
argument_list|)
decl_stmt|;
name|DataInputStream
name|din
init|=
operator|new
name|DataInputStream
argument_list|(
name|bin
argument_list|)
decl_stmt|;
name|createIdentifier
argument_list|()
operator|.
name|readFields
argument_list|(
name|din
argument_list|)
expr_stmt|;
name|long
name|renewDate
init|=
name|din
operator|.
name|readLong
argument_list|()
decl_stmt|;
name|int
name|pwdLen
init|=
name|din
operator|.
name|readInt
argument_list|()
decl_stmt|;
name|byte
index|[]
name|password
init|=
operator|new
name|byte
index|[
name|pwdLen
index|]
decl_stmt|;
name|int
name|numRead
init|=
name|din
operator|.
name|read
argument_list|(
name|password
argument_list|,
literal|0
argument_list|,
name|pwdLen
argument_list|)
decl_stmt|;
if|if
condition|(
name|numRead
operator|>
operator|-
literal|1
condition|)
block|{
name|DelegationTokenInformation
name|tokenInfo
init|=
operator|new
name|DelegationTokenInformation
argument_list|(
name|renewDate
argument_list|,
name|password
argument_list|)
decl_stmt|;
return|return
name|tokenInfo
return|;
block|}
block|}
catch|catch
parameter_list|(
name|KeeperException
operator|.
name|NoNodeException
name|e
parameter_list|)
block|{
if|if
condition|(
operator|!
name|quiet
condition|)
block|{
name|LOG
operator|.
name|error
argument_list|(
literal|"No node in path ["
operator|+
name|nodePath
operator|+
literal|"]"
argument_list|)
expr_stmt|;
block|}
block|}
catch|catch
parameter_list|(
name|Exception
name|ex
parameter_list|)
block|{
throw|throw
operator|new
name|IOException
argument_list|(
name|ex
argument_list|)
throw|;
block|}
return|return
literal|null
return|;
block|}
annotation|@
name|Override
DECL|method|storeDelegationKey (DelegationKey key)
specifier|protected
name|void
name|storeDelegationKey
parameter_list|(
name|DelegationKey
name|key
parameter_list|)
throws|throws
name|IOException
block|{
name|addOrUpdateDelegationKey
argument_list|(
name|key
argument_list|,
literal|false
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Override
DECL|method|updateDelegationKey (DelegationKey key)
specifier|protected
name|void
name|updateDelegationKey
parameter_list|(
name|DelegationKey
name|key
parameter_list|)
throws|throws
name|IOException
block|{
name|addOrUpdateDelegationKey
argument_list|(
name|key
argument_list|,
literal|true
argument_list|)
expr_stmt|;
block|}
DECL|method|addOrUpdateDelegationKey (DelegationKey key, boolean isUpdate)
specifier|private
name|void
name|addOrUpdateDelegationKey
parameter_list|(
name|DelegationKey
name|key
parameter_list|,
name|boolean
name|isUpdate
parameter_list|)
throws|throws
name|IOException
block|{
name|String
name|nodeCreatePath
init|=
name|getNodePath
argument_list|(
name|ZK_DTSM_MASTER_KEY_ROOT
argument_list|,
name|DELEGATION_KEY_PREFIX
operator|+
name|key
operator|.
name|getKeyId
argument_list|()
argument_list|)
decl_stmt|;
name|ByteArrayOutputStream
name|os
init|=
operator|new
name|ByteArrayOutputStream
argument_list|()
decl_stmt|;
name|DataOutputStream
name|fsOut
init|=
operator|new
name|DataOutputStream
argument_list|(
name|os
argument_list|)
decl_stmt|;
if|if
condition|(
name|LOG
operator|.
name|isDebugEnabled
argument_list|()
condition|)
block|{
name|LOG
operator|.
name|debug
argument_list|(
literal|"Storing ZKDTSMDelegationKey_"
operator|+
name|key
operator|.
name|getKeyId
argument_list|()
argument_list|)
expr_stmt|;
block|}
name|key
operator|.
name|write
argument_list|(
name|fsOut
argument_list|)
expr_stmt|;
try|try
block|{
if|if
condition|(
name|zkClient
operator|.
name|checkExists
argument_list|()
operator|.
name|forPath
argument_list|(
name|nodeCreatePath
argument_list|)
operator|!=
literal|null
condition|)
block|{
name|zkClient
operator|.
name|setData
argument_list|()
operator|.
name|forPath
argument_list|(
name|nodeCreatePath
argument_list|,
name|os
operator|.
name|toByteArray
argument_list|()
argument_list|)
operator|.
name|setVersion
argument_list|(
operator|-
literal|1
argument_list|)
expr_stmt|;
if|if
condition|(
operator|!
name|isUpdate
condition|)
block|{
name|LOG
operator|.
name|debug
argument_list|(
literal|"Key with path ["
operator|+
name|nodeCreatePath
operator|+
literal|"] already exists.. Updating !!"
argument_list|)
expr_stmt|;
block|}
block|}
else|else
block|{
name|zkClient
operator|.
name|create
argument_list|()
operator|.
name|withMode
argument_list|(
name|CreateMode
operator|.
name|PERSISTENT
argument_list|)
operator|.
name|forPath
argument_list|(
name|nodeCreatePath
argument_list|,
name|os
operator|.
name|toByteArray
argument_list|()
argument_list|)
expr_stmt|;
if|if
condition|(
name|isUpdate
condition|)
block|{
name|LOG
operator|.
name|debug
argument_list|(
literal|"Updating non existent Key path ["
operator|+
name|nodeCreatePath
operator|+
literal|"].. Adding new !!"
argument_list|)
expr_stmt|;
block|}
block|}
block|}
catch|catch
parameter_list|(
name|KeeperException
operator|.
name|NodeExistsException
name|ne
parameter_list|)
block|{
name|LOG
operator|.
name|debug
argument_list|(
name|nodeCreatePath
operator|+
literal|" znode already exists !!"
argument_list|)
expr_stmt|;
block|}
catch|catch
parameter_list|(
name|Exception
name|ex
parameter_list|)
block|{
throw|throw
operator|new
name|IOException
argument_list|(
name|ex
argument_list|)
throw|;
block|}
finally|finally
block|{
name|os
operator|.
name|close
argument_list|()
expr_stmt|;
block|}
block|}
annotation|@
name|Override
DECL|method|removeStoredMasterKey (DelegationKey key)
specifier|protected
name|void
name|removeStoredMasterKey
parameter_list|(
name|DelegationKey
name|key
parameter_list|)
block|{
name|String
name|nodeRemovePath
init|=
name|getNodePath
argument_list|(
name|ZK_DTSM_MASTER_KEY_ROOT
argument_list|,
name|DELEGATION_KEY_PREFIX
operator|+
name|key
operator|.
name|getKeyId
argument_list|()
argument_list|)
decl_stmt|;
if|if
condition|(
name|LOG
operator|.
name|isDebugEnabled
argument_list|()
condition|)
block|{
name|LOG
operator|.
name|debug
argument_list|(
literal|"Removing ZKDTSMDelegationKey_"
operator|+
name|key
operator|.
name|getKeyId
argument_list|()
argument_list|)
expr_stmt|;
block|}
try|try
block|{
if|if
condition|(
name|zkClient
operator|.
name|checkExists
argument_list|()
operator|.
name|forPath
argument_list|(
name|nodeRemovePath
argument_list|)
operator|!=
literal|null
condition|)
block|{
while|while
condition|(
name|zkClient
operator|.
name|checkExists
argument_list|()
operator|.
name|forPath
argument_list|(
name|nodeRemovePath
argument_list|)
operator|!=
literal|null
condition|)
block|{
try|try
block|{
name|zkClient
operator|.
name|delete
argument_list|()
operator|.
name|guaranteed
argument_list|()
operator|.
name|forPath
argument_list|(
name|nodeRemovePath
argument_list|)
expr_stmt|;
block|}
catch|catch
parameter_list|(
name|NoNodeException
name|nne
parameter_list|)
block|{
comment|// It is possible that the node might be deleted between the
comment|// check and the actual delete.. which might lead to an
comment|// exception that can bring down the daemon running this
comment|// SecretManager
name|LOG
operator|.
name|debug
argument_list|(
literal|"Node already deleted by peer "
operator|+
name|nodeRemovePath
argument_list|)
expr_stmt|;
block|}
block|}
block|}
else|else
block|{
name|LOG
operator|.
name|debug
argument_list|(
literal|"Attempted to delete a non-existing znode "
operator|+
name|nodeRemovePath
argument_list|)
expr_stmt|;
block|}
block|}
catch|catch
parameter_list|(
name|Exception
name|e
parameter_list|)
block|{
name|LOG
operator|.
name|debug
argument_list|(
name|nodeRemovePath
operator|+
literal|" znode could not be removed!!"
argument_list|)
expr_stmt|;
block|}
block|}
annotation|@
name|Override
DECL|method|storeToken (TokenIdent ident, DelegationTokenInformation tokenInfo)
specifier|protected
name|void
name|storeToken
parameter_list|(
name|TokenIdent
name|ident
parameter_list|,
name|DelegationTokenInformation
name|tokenInfo
parameter_list|)
throws|throws
name|IOException
block|{
try|try
block|{
name|addOrUpdateToken
argument_list|(
name|ident
argument_list|,
name|tokenInfo
argument_list|,
literal|false
argument_list|)
expr_stmt|;
block|}
catch|catch
parameter_list|(
name|Exception
name|e
parameter_list|)
block|{
throw|throw
operator|new
name|RuntimeException
argument_list|(
name|e
argument_list|)
throw|;
block|}
block|}
annotation|@
name|Override
DECL|method|updateToken (TokenIdent ident, DelegationTokenInformation tokenInfo)
specifier|protected
name|void
name|updateToken
parameter_list|(
name|TokenIdent
name|ident
parameter_list|,
name|DelegationTokenInformation
name|tokenInfo
parameter_list|)
throws|throws
name|IOException
block|{
name|String
name|nodeRemovePath
init|=
name|getNodePath
argument_list|(
name|ZK_DTSM_TOKENS_ROOT
argument_list|,
name|DELEGATION_TOKEN_PREFIX
operator|+
name|ident
operator|.
name|getSequenceNumber
argument_list|()
argument_list|)
decl_stmt|;
try|try
block|{
if|if
condition|(
name|zkClient
operator|.
name|checkExists
argument_list|()
operator|.
name|forPath
argument_list|(
name|nodeRemovePath
argument_list|)
operator|!=
literal|null
condition|)
block|{
name|addOrUpdateToken
argument_list|(
name|ident
argument_list|,
name|tokenInfo
argument_list|,
literal|true
argument_list|)
expr_stmt|;
block|}
else|else
block|{
name|addOrUpdateToken
argument_list|(
name|ident
argument_list|,
name|tokenInfo
argument_list|,
literal|false
argument_list|)
expr_stmt|;
name|LOG
operator|.
name|debug
argument_list|(
literal|"Attempted to update a non-existing znode "
operator|+
name|nodeRemovePath
argument_list|)
expr_stmt|;
block|}
block|}
catch|catch
parameter_list|(
name|Exception
name|e
parameter_list|)
block|{
throw|throw
operator|new
name|RuntimeException
argument_list|(
literal|"Could not update Stored Token ZKDTSMDelegationToken_"
operator|+
name|ident
operator|.
name|getSequenceNumber
argument_list|()
argument_list|,
name|e
argument_list|)
throw|;
block|}
block|}
annotation|@
name|Override
DECL|method|removeStoredToken (TokenIdent ident)
specifier|protected
name|void
name|removeStoredToken
parameter_list|(
name|TokenIdent
name|ident
parameter_list|)
throws|throws
name|IOException
block|{
name|String
name|nodeRemovePath
init|=
name|getNodePath
argument_list|(
name|ZK_DTSM_TOKENS_ROOT
argument_list|,
name|DELEGATION_TOKEN_PREFIX
operator|+
name|ident
operator|.
name|getSequenceNumber
argument_list|()
argument_list|)
decl_stmt|;
if|if
condition|(
name|LOG
operator|.
name|isDebugEnabled
argument_list|()
condition|)
block|{
name|LOG
operator|.
name|debug
argument_list|(
literal|"Removing ZKDTSMDelegationToken_"
operator|+
name|ident
operator|.
name|getSequenceNumber
argument_list|()
argument_list|)
expr_stmt|;
block|}
try|try
block|{
if|if
condition|(
name|zkClient
operator|.
name|checkExists
argument_list|()
operator|.
name|forPath
argument_list|(
name|nodeRemovePath
argument_list|)
operator|!=
literal|null
condition|)
block|{
while|while
condition|(
name|zkClient
operator|.
name|checkExists
argument_list|()
operator|.
name|forPath
argument_list|(
name|nodeRemovePath
argument_list|)
operator|!=
literal|null
condition|)
block|{
try|try
block|{
name|zkClient
operator|.
name|delete
argument_list|()
operator|.
name|guaranteed
argument_list|()
operator|.
name|forPath
argument_list|(
name|nodeRemovePath
argument_list|)
expr_stmt|;
block|}
catch|catch
parameter_list|(
name|NoNodeException
name|nne
parameter_list|)
block|{
comment|// It is possible that the node might be deleted between the
comment|// check and the actual delete.. which might lead to an
comment|// exception that can bring down the daemon running this
comment|// SecretManager
name|LOG
operator|.
name|debug
argument_list|(
literal|"Node already deleted by peer "
operator|+
name|nodeRemovePath
argument_list|)
expr_stmt|;
block|}
block|}
block|}
else|else
block|{
name|LOG
operator|.
name|debug
argument_list|(
literal|"Attempted to remove a non-existing znode "
operator|+
name|nodeRemovePath
argument_list|)
expr_stmt|;
block|}
block|}
catch|catch
parameter_list|(
name|Exception
name|e
parameter_list|)
block|{
throw|throw
operator|new
name|RuntimeException
argument_list|(
literal|"Could not remove Stored Token ZKDTSMDelegationToken_"
operator|+
name|ident
operator|.
name|getSequenceNumber
argument_list|()
argument_list|,
name|e
argument_list|)
throw|;
block|}
block|}
annotation|@
name|Override
DECL|method|cancelToken (Token<TokenIdent> token, String canceller)
specifier|public
specifier|synchronized
name|TokenIdent
name|cancelToken
parameter_list|(
name|Token
argument_list|<
name|TokenIdent
argument_list|>
name|token
parameter_list|,
name|String
name|canceller
parameter_list|)
throws|throws
name|IOException
block|{
name|ByteArrayInputStream
name|buf
init|=
operator|new
name|ByteArrayInputStream
argument_list|(
name|token
operator|.
name|getIdentifier
argument_list|()
argument_list|)
decl_stmt|;
name|DataInputStream
name|in
init|=
operator|new
name|DataInputStream
argument_list|(
name|buf
argument_list|)
decl_stmt|;
name|TokenIdent
name|id
init|=
name|createIdentifier
argument_list|()
decl_stmt|;
name|id
operator|.
name|readFields
argument_list|(
name|in
argument_list|)
expr_stmt|;
name|syncLocalCacheWithZk
argument_list|(
name|id
argument_list|)
expr_stmt|;
return|return
name|super
operator|.
name|cancelToken
argument_list|(
name|token
argument_list|,
name|canceller
argument_list|)
return|;
block|}
DECL|method|addOrUpdateToken (TokenIdent ident, DelegationTokenInformation info, boolean isUpdate)
specifier|private
name|void
name|addOrUpdateToken
parameter_list|(
name|TokenIdent
name|ident
parameter_list|,
name|DelegationTokenInformation
name|info
parameter_list|,
name|boolean
name|isUpdate
parameter_list|)
throws|throws
name|Exception
block|{
name|String
name|nodeCreatePath
init|=
name|getNodePath
argument_list|(
name|ZK_DTSM_TOKENS_ROOT
argument_list|,
name|DELEGATION_TOKEN_PREFIX
operator|+
name|ident
operator|.
name|getSequenceNumber
argument_list|()
argument_list|)
decl_stmt|;
try|try
init|(
name|ByteArrayOutputStream
name|tokenOs
init|=
operator|new
name|ByteArrayOutputStream
argument_list|()
init|;
name|DataOutputStream
name|tokenOut
operator|=
operator|new
name|DataOutputStream
argument_list|(
name|tokenOs
argument_list|)
init|)
block|{
name|ident
operator|.
name|write
argument_list|(
name|tokenOut
argument_list|)
expr_stmt|;
name|tokenOut
operator|.
name|writeLong
argument_list|(
name|info
operator|.
name|getRenewDate
argument_list|()
argument_list|)
expr_stmt|;
name|tokenOut
operator|.
name|writeInt
argument_list|(
name|info
operator|.
name|getPassword
argument_list|()
operator|.
name|length
argument_list|)
expr_stmt|;
name|tokenOut
operator|.
name|write
argument_list|(
name|info
operator|.
name|getPassword
argument_list|()
argument_list|)
expr_stmt|;
if|if
condition|(
name|LOG
operator|.
name|isDebugEnabled
argument_list|()
condition|)
block|{
name|LOG
operator|.
name|debug
argument_list|(
operator|(
name|isUpdate
condition|?
literal|"Updating "
else|:
literal|"Storing "
operator|)
operator|+
literal|"ZKDTSMDelegationToken_"
operator|+
name|ident
operator|.
name|getSequenceNumber
argument_list|()
argument_list|)
expr_stmt|;
block|}
if|if
condition|(
name|isUpdate
condition|)
block|{
name|zkClient
operator|.
name|setData
argument_list|()
operator|.
name|forPath
argument_list|(
name|nodeCreatePath
argument_list|,
name|tokenOs
operator|.
name|toByteArray
argument_list|()
argument_list|)
operator|.
name|setVersion
argument_list|(
operator|-
literal|1
argument_list|)
expr_stmt|;
block|}
else|else
block|{
name|zkClient
operator|.
name|create
argument_list|()
operator|.
name|withMode
argument_list|(
name|CreateMode
operator|.
name|PERSISTENT
argument_list|)
operator|.
name|forPath
argument_list|(
name|nodeCreatePath
argument_list|,
name|tokenOs
operator|.
name|toByteArray
argument_list|()
argument_list|)
expr_stmt|;
block|}
block|}
block|}
comment|/** * Simple implementation of an {@link ACLProvider} that simply returns an ACL * that gives all permissions only to a single principal. */
DECL|class|SASLOwnerACLProvider
specifier|private
specifier|static
class|class
name|SASLOwnerACLProvider
implements|implements
name|ACLProvider
block|{
DECL|field|saslACL
specifier|private
specifier|final
name|List
argument_list|<
name|ACL
argument_list|>
name|saslACL
decl_stmt|;
DECL|method|SASLOwnerACLProvider (String principal)
specifier|private
name|SASLOwnerACLProvider
parameter_list|(
name|String
name|principal
parameter_list|)
block|{
name|this
operator|.
name|saslACL
operator|=
name|Collections
operator|.
name|singletonList
argument_list|(
operator|new
name|ACL
argument_list|(
name|Perms
operator|.
name|ALL
argument_list|,
operator|new
name|Id
argument_list|(
literal|"sasl"
argument_list|,
name|principal
argument_list|)
argument_list|)
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Override
DECL|method|getDefaultAcl ()
specifier|public
name|List
argument_list|<
name|ACL
argument_list|>
name|getDefaultAcl
parameter_list|()
block|{
return|return
name|saslACL
return|;
block|}
annotation|@
name|Override
DECL|method|getAclForPath (String path)
specifier|public
name|List
argument_list|<
name|ACL
argument_list|>
name|getAclForPath
parameter_list|(
name|String
name|path
parameter_list|)
block|{
return|return
name|saslACL
return|;
block|}
block|}
annotation|@
name|VisibleForTesting
annotation|@
name|Private
annotation|@
name|Unstable
DECL|method|getNodePath (String root, String nodeName)
specifier|static
name|String
name|getNodePath
parameter_list|(
name|String
name|root
parameter_list|,
name|String
name|nodeName
parameter_list|)
block|{
return|return
operator|(
name|root
operator|+
literal|"/"
operator|+
name|nodeName
operator|)
return|;
block|}
annotation|@
name|VisibleForTesting
DECL|method|getListenerThreadPool ()
specifier|public
name|ExecutorService
name|getListenerThreadPool
parameter_list|()
block|{
return|return
name|listenerThreadPool
return|;
block|}
annotation|@
name|VisibleForTesting
DECL|method|getTokenInfoFromMemory (TokenIdent ident)
name|DelegationTokenInformation
name|getTokenInfoFromMemory
parameter_list|(
name|TokenIdent
name|ident
parameter_list|)
block|{
return|return
name|currentTokens
operator|.
name|get
argument_list|(
name|ident
argument_list|)
return|;
block|}
block|}
end_class
end_unit
|
SEALABQualityGroup/SEAA-replication-package
|
code/easier-logicalSpecification/LogicalSpecification/src/logicalSpecification/actions/AEmilia/util/AEmiliaSwitch.java
|
<filename>code/easier-logicalSpecification/LogicalSpecification/src/logicalSpecification/actions/AEmilia/util/AEmiliaSwitch.java<gh_stars>0
/**
*/
package logicalSpecification.actions.AEmilia.util;
import logicalSpecification.Action;
import logicalSpecification.AddAction;
import logicalSpecification.ChangeAction;
import logicalSpecification.DeleteAction;
import logicalSpecification.MoveAction;
import logicalSpecification.NamedElement;
import logicalSpecification.actions.AEmilia.*;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.util.Switch;
/**
* <!-- begin-user-doc -->
* The <b>Switch</b> for the model's inheritance hierarchy.
* It supports the call {@link #doSwitch(EObject) doSwitch(object)}
* to invoke the <code>caseXXX</code> method for each class of the model,
* starting with the actual class of the object
* and proceeding up the inheritance hierarchy
* until a non-null result is returned,
* which is the result of the switch.
* <!-- end-user-doc -->
* @see logicalSpecification.actions.AEmilia.AEmiliaPackage
* @generated
*/
public class AEmiliaSwitch<T> extends Switch<T> {
/**
* The cached model package
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected static AEmiliaPackage modelPackage;
/**
* Creates an instance of the switch.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public AEmiliaSwitch() {
if (modelPackage == null) {
modelPackage = AEmiliaPackage.eINSTANCE;
}
}
/**
* Checks whether this is a switch for the given package.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param ePackage the package in question.
* @return whether this is a switch for the given package.
* @generated
*/
@Override
protected boolean isSwitchFor(EPackage ePackage) {
return ePackage == modelPackage;
}
/**
* Calls <code>caseXXX</code> for each class of the model until one returns a non null result; it yields that result.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the first non-null result returned by a <code>caseXXX</code> call.
* @generated
*/
@Override
protected T doSwitch(int classifierID, EObject theEObject) {
switch (classifierID) {
case AEmiliaPackage.AEMILIA_ADD_ACTION: {
AEmiliaAddAction aEmiliaAddAction = (AEmiliaAddAction)theEObject;
T result = caseAEmiliaAddAction(aEmiliaAddAction);
if (result == null) result = caseAddAction(aEmiliaAddAction);
if (result == null) result = caseAction(aEmiliaAddAction);
if (result == null) result = caseNamedElement(aEmiliaAddAction);
if (result == null) result = defaultCase(theEObject);
return result;
}
case AEmiliaPackage.AEMILIA_DELETE_ACTION: {
AEmiliaDeleteAction aEmiliaDeleteAction = (AEmiliaDeleteAction)theEObject;
T result = caseAEmiliaDeleteAction(aEmiliaDeleteAction);
if (result == null) result = caseDeleteAction(aEmiliaDeleteAction);
if (result == null) result = caseAction(aEmiliaDeleteAction);
if (result == null) result = caseNamedElement(aEmiliaDeleteAction);
if (result == null) result = defaultCase(theEObject);
return result;
}
case AEmiliaPackage.AEMILIA_MOVE_ACTION: {
AEmiliaMoveAction aEmiliaMoveAction = (AEmiliaMoveAction)theEObject;
T result = caseAEmiliaMoveAction(aEmiliaMoveAction);
if (result == null) result = caseMoveAction(aEmiliaMoveAction);
if (result == null) result = caseAction(aEmiliaMoveAction);
if (result == null) result = caseNamedElement(aEmiliaMoveAction);
if (result == null) result = defaultCase(theEObject);
return result;
}
case AEmiliaPackage.AEMILIA_CLONE_AEI_ACTION: {
AEmiliaCloneAEIAction aEmiliaCloneAEIAction = (AEmiliaCloneAEIAction)theEObject;
T result = caseAEmiliaCloneAEIAction(aEmiliaCloneAEIAction);
if (result == null) result = caseAEmiliaAddAction(aEmiliaCloneAEIAction);
if (result == null) result = caseAddAction(aEmiliaCloneAEIAction);
if (result == null) result = caseAction(aEmiliaCloneAEIAction);
if (result == null) result = caseNamedElement(aEmiliaCloneAEIAction);
if (result == null) result = defaultCase(theEObject);
return result;
}
case AEmiliaPackage.AEMILIA_CONST_CHANGES_ACTION: {
AEmiliaConstChangesAction aEmiliaConstChangesAction = (AEmiliaConstChangesAction)theEObject;
T result = caseAEmiliaConstChangesAction(aEmiliaConstChangesAction);
if (result == null) result = caseAEmiliaChangeAction(aEmiliaConstChangesAction);
if (result == null) result = caseChangeAction(aEmiliaConstChangesAction);
if (result == null) result = caseAction(aEmiliaConstChangesAction);
if (result == null) result = caseNamedElement(aEmiliaConstChangesAction);
if (result == null) result = defaultCase(theEObject);
return result;
}
case AEmiliaPackage.AEMILIA_CHANGE_ACTION: {
AEmiliaChangeAction aEmiliaChangeAction = (AEmiliaChangeAction)theEObject;
T result = caseAEmiliaChangeAction(aEmiliaChangeAction);
if (result == null) result = caseChangeAction(aEmiliaChangeAction);
if (result == null) result = caseAction(aEmiliaChangeAction);
if (result == null) result = caseNamedElement(aEmiliaChangeAction);
if (result == null) result = defaultCase(theEObject);
return result;
}
case AEmiliaPackage.AEMILIA_REMOVE_CLONED_AEI_ACTION: {
AEmiliaRemoveClonedAEIAction aEmiliaRemoveClonedAEIAction = (AEmiliaRemoveClonedAEIAction)theEObject;
T result = caseAEmiliaRemoveClonedAEIAction(aEmiliaRemoveClonedAEIAction);
if (result == null) result = caseAEmiliaDeleteAction(aEmiliaRemoveClonedAEIAction);
if (result == null) result = caseDeleteAction(aEmiliaRemoveClonedAEIAction);
if (result == null) result = caseAction(aEmiliaRemoveClonedAEIAction);
if (result == null) result = caseNamedElement(aEmiliaRemoveClonedAEIAction);
if (result == null) result = defaultCase(theEObject);
return result;
}
default: return defaultCase(theEObject);
}
}
/**
* Returns the result of interpreting the object as an instance of '<em>Add Action</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>Add Action</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseAEmiliaAddAction(AEmiliaAddAction object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>Delete Action</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>Delete Action</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseAEmiliaDeleteAction(AEmiliaDeleteAction object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>Move Action</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>Move Action</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseAEmiliaMoveAction(AEmiliaMoveAction object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>Clone AEI Action</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>Clone AEI Action</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseAEmiliaCloneAEIAction(AEmiliaCloneAEIAction object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>Const Changes Action</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>Const Changes Action</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseAEmiliaConstChangesAction(AEmiliaConstChangesAction object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>Change Action</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>Change Action</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseAEmiliaChangeAction(AEmiliaChangeAction object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>Remove Cloned AEI Action</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>Remove Cloned AEI Action</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseAEmiliaRemoveClonedAEIAction(AEmiliaRemoveClonedAEIAction object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>Named Element</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>Named Element</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseNamedElement(NamedElement object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>Action</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>Action</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseAction(Action object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>Add Action</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>Add Action</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseAddAction(AddAction object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>Delete Action</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>Delete Action</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseDeleteAction(DeleteAction object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>Move Action</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>Move Action</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseMoveAction(MoveAction object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>Change Action</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>Change Action</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseChangeAction(ChangeAction object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>EObject</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch, but this is the last case anyway.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>EObject</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject)
* @generated
*/
@Override
public T defaultCase(EObject object) {
return null;
}
} //AEmiliaSwitch
|
ow2-chameleon/fuchsia
|
importers/zwave/src/main/java/org/ow2/chameleon/fuchsia/importer/zwave/internal/commandclass/ZWaveNoOperationCommandClass.java
|
<filename>importers/zwave/src/main/java/org/ow2/chameleon/fuchsia/importer/zwave/internal/commandclass/ZWaveNoOperationCommandClass.java
/*
* #%L
* OW2 Chameleon - Fuchsia Framework
* %%
* Copyright (C) 2009 - 2015 OW2 Chameleon
* %%
* 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.
* #L%
*/
/**
* openHAB, the open Home Automation Bus.
* Copyright (C) 2010-2012, openHAB.org <<EMAIL>>
*
* See the contributors.txt file in the distribution for a
* full listing of individual contributors.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see <http://www.gnu.org/licenses>.
*
* Additional permission under GNU GPL version 3 section 7
*
* If you modify this Program, or any covered work, by linking or
* combining it with Eclipse (or a modified version of that library),
* containing parts covered by the terms of the Eclipse Public License
* (EPL), the licensors of this Program grant you additional permission
* to convey the resulting work.
*/
package org.ow2.chameleon.fuchsia.importer.zwave.internal.commandclass;
import org.ow2.chameleon.fuchsia.importer.zwave.internal.protocol.SerialMessage;
import org.ow2.chameleon.fuchsia.importer.zwave.internal.protocol.ZWaveController;
import org.ow2.chameleon.fuchsia.importer.zwave.internal.protocol.ZWaveEndpoint;
import org.ow2.chameleon.fuchsia.importer.zwave.internal.protocol.ZWaveNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Handles the no operation command class. The No Operation command class is used
* to check if a node is reachable by sending a serial message without a command
* to the specified node. This can for instance be used to check that a node is
* non-responding.
*
* @author <NAME>
* @since 1.3.0
*/
public class ZWaveNoOperationCommandClass extends ZWaveCommandClass {
private static final Logger logger = LoggerFactory.getLogger(ZWaveNoOperationCommandClass.class);
/**
* Creates a new instance of the ZWaveNoOperationCommandClass class.
* @param node the node this command class belongs to
* @param controller the controller to use
* @param endpoint the endpoint this Command class belongs to
*/
public ZWaveNoOperationCommandClass(ZWaveNode node,
ZWaveController controller, ZWaveEndpoint endpoint) {
super(node, controller, endpoint);
}
/**
* {@inheritDoc}
*/
@Override
public CommandClass getCommandClass() {
return CommandClass.NO_OPERATION;
}
/**
* {@inheritDoc}
*/
@Override
public void handleApplicationCommandRequest(SerialMessage serialMessage,
int offset, int endpoint) {
logger.trace("Handle No Operation Request");
logger.debug(String.format("Received No Operation for Node ID = %d", this.getNode().getNodeId()));
// advance node stage.
this.getNode().advanceNodeStage();
}
/**
* Gets a SerialMessage with the No Operation command
* @return the serial message
*/
public SerialMessage getNoOperationMessage() {
logger.debug("Creating new message for application command No Operation for node {}", this.getNode().getNodeId());
SerialMessage result = new SerialMessage(this.getNode().getNodeId(), SerialMessage.SerialMessageClass.SendData, SerialMessage.SerialMessageType.Request, SerialMessage.SerialMessageClass.SendData, SerialMessage.SerialMessagePriority.Low);
byte[] newPayload = { (byte) this.getNode().getNodeId(),
1,
(byte) getCommandClass().getKey() };
result.setMessagePayload(newPayload);
return result;
}
}
|
silenc3502/MYSQL-Arch-Doc-Summary
|
mysql-server/plugin/x/src/operations_factory.cc
|
<reponame>silenc3502/MYSQL-Arch-Doc-Summary<filename>mysql-server/plugin/x/src/operations_factory.cc
/*
* Copyright (c) 2015, 2020, Oracle and/or its affiliates.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License, version 2.0,
* as published by the Free Software Foundation.
*
* This program is also distributed with certain software (including
* but not limited to OpenSSL) that is licensed under separate terms,
* as designated in a particular file or component or in included license
* documentation. The authors of MySQL hereby grant you an additional
* permission to link the program and your derivative works with the
* separately licensed software that they have included with MySQL.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License, version 2.0, for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "plugin/x/src/operations_factory.h"
#include <errno.h>
#include <fcntl.h>
#ifndef _WIN32
#include <netdb.h>
#endif
#include <cinttypes>
#include <cstdint>
#include <string>
#include "my_io.h" // NOLINT(build/include_subdir)
#include "my_systime.h" // NOLINT(build/include_subdir)
#ifdef HAVE_SYS_UN_H
#include <signal.h>
#include <sys/types.h>
#include <sys/un.h>
#endif
#include "plugin/x/src/config/config.h"
namespace xpl {
namespace details {
class Socket : public iface::Socket {
public:
explicit Socket(MYSQL_SOCKET mysql_socket) : m_mysql_socket(mysql_socket) {}
Socket(PSI_socket_key key MY_ATTRIBUTE((unused)), int domain, int type,
int protocol)
: m_mysql_socket(mysql_socket_socket(key, domain, type, protocol)) {}
~Socket() override { close(); }
int bind(const struct sockaddr *addr, socklen_t len) override {
return mysql_socket_bind(m_mysql_socket, addr, len);
}
MYSQL_SOCKET accept(PSI_socket_key key MY_ATTRIBUTE((unused)),
struct sockaddr *addr, socklen_t *addr_len) override {
return mysql_socket_accept(key, m_mysql_socket, addr, addr_len);
}
int listen(int backlog) override {
return mysql_socket_listen(m_mysql_socket, backlog);
}
my_socket get_socket_fd() override {
return mysql_socket_getfd(m_mysql_socket);
}
MYSQL_SOCKET get_socket_mysql() override { return m_mysql_socket; }
int set_socket_opt(int level, int optname, const SOCKBUF_T *optval,
socklen_t optlen) override {
return mysql_socket_setsockopt(m_mysql_socket, level, optname, optval,
optlen);
}
void close() override {
if (INVALID_SOCKET != get_socket_fd()) {
mysql_socket_close(m_mysql_socket);
m_mysql_socket = MYSQL_INVALID_SOCKET;
}
}
void set_socket_thread_owner() override {
mysql_socket_set_thread_owner(m_mysql_socket);
}
private:
MYSQL_SOCKET m_mysql_socket;
};
class File : public iface::File {
public:
File(const char *name, int access, int permission)
: m_file_descriptor(::open(name, access, permission)) {}
~File() override { close(); }
int close() override {
if (INVALID_FILE_DESCRIPTOR != m_file_descriptor) {
const int result = ::close(m_file_descriptor);
m_file_descriptor = INVALID_FILE_DESCRIPTOR;
return result;
}
return 0;
}
int read(void *buffer, int nbyte) override {
return ::read(m_file_descriptor, buffer, nbyte);
}
int write(void *buffer, int nbyte) override {
return ::write(m_file_descriptor, buffer, nbyte);
}
bool is_valid() override {
return INVALID_FILE_DESCRIPTOR != m_file_descriptor;
}
int fsync() override {
#if defined(HAVE_SYS_UN_H)
return ::fsync(m_file_descriptor);
#else
return 0;
#endif // defined(HAVE_SYS_UN_H)
}
private:
int m_file_descriptor;
static const int INVALID_FILE_DESCRIPTOR;
};
const int File::INVALID_FILE_DESCRIPTOR = -1;
class System : public iface::System {
int32_t unlink(const char *name) override {
return HAVE_UNIX_SOCKET(::unlink(name), 0);
}
int32_t get_errno() override { return errno; }
int32_t get_ppid() override { return HAVE_UNIX_SOCKET(::getppid(), 0); }
int32_t get_pid() override { return HAVE_UNIX_SOCKET(::getpid(), 0); }
int32_t kill(int32_t pid, int32_t signal) override {
return HAVE_UNIX_SOCKET(::kill(pid, signal), 0);
}
int32_t get_socket_errno() override { return socket_errno; }
void set_socket_errno(const int32_t err) override {
#if defined(_WIN32)
// socket_errno resolved on windows to WASGetLastError which can't be set.
WSASetLastError(err);
#else
socket_errno = err;
#endif // defined(_WIN32)
}
void get_socket_error_and_message(int32_t *out_err,
std::string *out_strerr) override {
*out_err = socket_errno;
#ifdef _WIN32
char *s = nullptr;
if (0 == FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
nullptr, *out_err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
reinterpret_cast<LPSTR>(&s), 0, nullptr)) {
char text[256];
snprintf(text, sizeof(text), "Error %" PRIi32, *out_err);
*out_strerr = text;
} else {
*out_strerr = s;
LocalFree(s);
}
#else
*out_strerr = strerror(*out_err);
#endif
}
void freeaddrinfo(addrinfo *ai) override { return ::freeaddrinfo(ai); }
int32_t getaddrinfo(const char *node, const char *service,
const addrinfo *hints, addrinfo **res) override {
return ::getaddrinfo(node, service, hints, res);
}
void sleep(uint32_t seconds) override { ::sleep(seconds); }
};
} // namespace details
std::shared_ptr<iface::Socket> Operations_factory::create_socket(
PSI_socket_key key, int domain, int type, int protocol) {
return std::make_shared<details::Socket>(key, domain, type, protocol);
}
std::shared_ptr<iface::Socket> Operations_factory::create_socket(
MYSQL_SOCKET mysql_socket) {
return std::make_shared<details::Socket>(mysql_socket);
}
std::shared_ptr<iface::File> Operations_factory::open_file(const char *name,
int access,
int permission) {
return std::make_shared<details::File>(name, access, permission);
}
std::shared_ptr<iface::System> Operations_factory::create_system_interface() {
return std::make_shared<details::System>();
}
} // namespace xpl
|
ravi-mosaicml/ravi-composer
|
composer/profiler/profiler_hparams.py
|
# Copyright 2021 MosaicML. All Rights Reserved.
"""Hyperparameter classes for the :mod:`~composer.profiler`.
Attributes:
trace_handler_registry (Dict[str, Type[TraceHandlerHparams]]): Trace handler registry.
profiler_scheduler_registry (Dict[str, Type[ProfileScheduleHparams]]): Profiler scheduler registry.
"""
from __future__ import annotations
import abc
import dataclasses
from typing import Callable, Optional
import yahp as hp
from composer.core.state import State
from composer.profiler.json_trace_handler import JSONTraceHandler
from composer.profiler.profiler_action import ProfilerAction
from composer.profiler.profiler_schedule import cyclic_schedule
from composer.profiler.trace_handler import TraceHandler
__all__ = [
"TraceHandlerHparams", "JSONTraceHparams", "trace_handler_registry", "ProfileScheduleHparams",
"CyclicProfilerScheduleHparams", "profiler_scheduler_registry"
]
@dataclasses.dataclass
class TraceHandlerHparams(hp.Hparams, abc.ABC):
"""Base class for the :class:`.TraceHandler` hparams."""
@abc.abstractmethod
def initialize_object(self) -> TraceHandler:
"""Constructs and returns an instance of a :class:`.TraceHandler`.
Returns:
TraceHandler: The trace handler.
"""
pass
@dataclasses.dataclass
class JSONTraceHparams(TraceHandlerHparams):
"""Hyperparameters for the :class:`.JSONTraceHandler`.
Args:
folder (str, optional): See :class:`.JSONTraceHandler`.
filename (str, optional): See :class:`.JSONTraceHandler`.
artifact_name (str, optional): See :class:`.JSONTraceHandler`.
merged_trace_filename (str, optional): See :class:`.JSONTraceHandler`.
merged_trace_artifact_name (str, optional): See :class:`.JSONTraceHandler`.
overwrite (bool, optional): See :class:`.JSONTraceHandler`.
num_traces_to_keep (int, optional): See :class:`.JSONTraceHandler`.
"""
folder: str = hp.optional("Folder format", default='{run_name}/traces')
filename: str = hp.optional("Filename format string for the profile trace.",
default='ep{epoch}-ba{batch}-rank{rank}.json')
artifact_name: Optional[str] = hp.optional("Artifact name format string for the profiler trace.",
default='{run_name}/traces/ep{epoch}-ba{batch}-rank{rank}.json')
merged_trace_filename: Optional[str] = hp.optional("Merged trace filename format", default='node{node_rank}.json')
merged_trace_artifact_name: Optional[str] = hp.optional("Merged trace file artifact name format",
default='{run_name}/traces/merged_trace.json')
overwrite: bool = hp.optional("Overwrite", default=False)
num_traces_to_keep: int = hp.optional("Num trace files to keep", default=-1)
def initialize_object(self) -> JSONTraceHandler:
return JSONTraceHandler(**dataclasses.asdict(self))
trace_handler_registry = {"json": JSONTraceHparams}
@dataclasses.dataclass
class ProfileScheduleHparams(hp.Hparams, abc.ABC):
"""Base class for Composer Profiler schedule hparams."""
@abc.abstractmethod
def initialize_object(self) -> Callable[[State], ProfilerAction]:
"""Constructs and returns a Composer Profiler scheduler.
The scheduler is used ``prof_schedule`` argument for the :class:`~composer.trainer.trainer.Trainer`.
Returns:
(state) -> ProfilerAction: The profiler scheduler.
"""
pass
@dataclasses.dataclass
class CyclicProfilerScheduleHparams(ProfileScheduleHparams):
"""Hyperparameters for the :func:`.cyclic_schedule`.
Args:
skip_first (int, optional): See :func:`.cyclic_schedule`.
wait (str, optional): See :func:`.cyclic_schedule`.
warmup (str, optional): See :func:`.cyclic_schedule`.
active (str, optional): See :func:`.cyclic_schedule`.
repeat (str, optional): See :func:`.cyclic_schedule`.
"""
skip_first: int = hp.optional("skip first", default=0)
wait: int = hp.optional("wait", default=0)
warmup: int = hp.optional("warmup", default=1)
active: int = hp.optional("active", default=4)
repeat: int = hp.optional("repeat", default=1)
def initialize_object(self) -> Callable[[State], ProfilerAction]:
return cyclic_schedule(**dataclasses.asdict(self))
profiler_scheduler_registry = {'cyclic': CyclicProfilerScheduleHparams}
|
websage-team/super
|
packages/koot/utils/get-dist-path.js
|
<filename>packages/koot/utils/get-dist-path.js
const fs = require('fs');
const path = require('path');
const getCwd = require('./get-cwd');
let p;
/**
* 获取打包结果路径
* @returns {String} 打包结果路径 (硬盘绝对路径)
*/
module.exports = () => {
// console.log('global.KOOT_DIST_DIR', global.KOOT_DIST_DIR)
if (typeof p !== 'string') {
p =
typeof global.KOOT_DIST_DIR === 'string'
? global.KOOT_DIST_DIR
: (() => {
let cwd = getCwd();
let parent = path.resolve(cwd, '..');
let result = path.resolve(cwd, process.env.KOOT_DIST_DIR);
while (!fs.existsSync(result) && cwd !== parent) {
cwd = parent;
parent = path.resolve(cwd, '..');
result = path.resolve(cwd, process.env.KOOT_DIST_DIR);
}
if (fs.existsSync(result)) return result;
return path.resolve(cwd, process.env.KOOT_DIST_DIR);
})();
}
return p;
};
|
peacetrue/peacetrue
|
peacetrue-result/peacetrue-result-web/src/main/java/com/github/peacetrue/result/SimpleExceptionPageResolver.java
|
package com.github.peacetrue.result;
import javax.servlet.http.HttpServletRequest;
/**
* return a uniquely determined page
*
* @author xiayx
*/
public class SimpleExceptionPageResolver implements ExceptionPageResolver {
private String exceptionPage;
@Override
public String resolve(HttpServletRequest request, Exception exception) {
return exceptionPage;
}
public void setExceptionPage(String exceptionPage) {
this.exceptionPage = exceptionPage;
}
}
|
KnIfER/pdfpdf
|
xfa/fde/css/cfde_csssyntaxparser.h
|
<filename>xfa/fde/css/cfde_csssyntaxparser.h<gh_stars>1-10
// Copyright 2017 PDFium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com
#ifndef XFA_FDE_CSS_CFDE_CSSSYNTAXPARSER_H_
#define XFA_FDE_CSS_CFDE_CSSSYNTAXPARSER_H_
#include <stack>
#include "core/fxcrt/fx_string.h"
#include "xfa/fde/css/cfde_cssexttextbuf.h"
#include "xfa/fde/css/cfde_csstextbuf.h"
#define FDE_CSSSYNTAXCHECK_AllowCharset 1
#define FDE_CSSSYNTAXCHECK_AllowImport 2
enum class FDE_CSSSyntaxMode {
RuleSet,
Comment,
UnknownRule,
Selector,
PropertyName,
PropertyValue,
};
enum class FDE_CSSSyntaxStatus : uint8_t {
Error,
EOS,
None,
StyleRule,
Selector,
DeclOpen,
DeclClose,
PropertyName,
PropertyValue,
};
class CFDE_CSSSyntaxParser {
public:
CFDE_CSSSyntaxParser(const wchar_t* pBuffer, int32_t iBufferSize);
CFDE_CSSSyntaxParser(const wchar_t* pBuffer,
int32_t iBufferSize,
int32_t iTextDatSize,
bool bOnlyDeclaration);
~CFDE_CSSSyntaxParser();
FDE_CSSSyntaxStatus DoSyntaxParse();
CFX_WideStringC GetCurrentString() const;
protected:
void SwitchMode(FDE_CSSSyntaxMode eMode);
int32_t SwitchToComment();
bool RestoreMode();
bool AppendChar(wchar_t wch);
int32_t SaveTextData();
bool IsCharsetEnabled() const {
return (m_dwCheck & FDE_CSSSYNTAXCHECK_AllowCharset) != 0;
}
void DisableCharset() { m_dwCheck = FDE_CSSSYNTAXCHECK_AllowImport; }
bool IsImportEnabled() const;
void DisableImport() { m_dwCheck = 0; }
CFDE_CSSTextBuf m_TextData;
CFDE_CSSExtTextBuf m_TextPlane;
int32_t m_iTextDataLen;
uint32_t m_dwCheck;
FDE_CSSSyntaxMode m_eMode;
FDE_CSSSyntaxStatus m_eStatus;
std::stack<FDE_CSSSyntaxMode> m_ModeStack;
};
#endif // XFA_FDE_CSS_CFDE_CSSSYNTAXPARSER_H_
|
v-ya/local
|
graph/support_pri.h
|
<gh_stars>1-10
#ifndef _graph_support_pri_h_
#define _graph_support_pri_h_
#include "support.h"
#include <vulkan/vulkan.h>
// success return NULL
const graph_layer_t* graph_layer_mapping_length(const graph_layer_t *restrict p, uint32_t *restrict length);
const graph_extension_t* graph_extension_mapping_length(const graph_extension_t *restrict p, uint32_t *restrict length);
// must success
const char** graph_layer_mapping_copy(const graph_layer_t *restrict p, const char* d[]);
const char** graph_extension_mapping_copy(const graph_extension_t *restrict p, const char* d[]);
#endif
|
BrainFlame/store
|
async/stub/com/treode/async/stubs/AsyncChecks.scala
|
<gh_stars>0
/*
* Copyright 2014 Treode, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.treode.async.stubs
import java.util.concurrent.Executors
import scala.util.Random
import com.treode.async.Scheduler
import org.scalatest.{Informing, Suite}
trait AsyncChecks {
this: Suite with Informing =>
/** The value of `TEST_INTENSITY` from the environment, or `std` if the environment has no
* setting for that.
*/
val intensity: String = {
val env = System.getenv ("TEST_INTENSITY")
if (env == null) "std" else env
}
/** The number of seeds tried in `forAllSeeds`. 1 when when `intensity` is `dev` and 100
* otherwise.
*/
val nseeds =
intensity match {
case "dev" => 1
case _ => 100
}
/** Run the test with a PRNG seeded by `seed`. */
def forSeed (seed: Long) (test: Random => Any) {
try {
val random = new Random (seed)
test (random)
} catch {
case t: Throwable =>
info (s"Test failed; seed = ${seed}L")
throw t
}}
/** Run the test many times, each time with a PRNG seeded differently. When developing, set
* the environment variable `TEST_INTENSITY` to `dev` to run the test only once. Let your
* continuous build spend the time running it over and over.
*/
def forAllSeeds (test: Random => Any) {
for (_ <- 0 until nseeds)
forSeed (Random.nextLong) (test)
}}
|
Florinacho/NEStalgia
|
Bomberman/Character.hpp
|
#ifndef __CHARACTER_H__
#define __CHARACTER_H__
#include "Image.h"
class TileRenderer;
enum PlayerStatus {
EPS_DEAD,
EPS_STATIC,
EPS_FALLING,
EPS_SWIMMING,
EPS_CLIMB,
};
enum Direction {
ECD_UP,
ECD_LEFT,
ECD_DOWN,
ECD_RIGHT
};
class Character {
public:
static const unsigned int ValueScaling = 1024;
ivec2 position;
ivec2 velocity;
ivec2 targetVelocity;
Direction direction;
bool canClimb[3]; // 0 - up, 1 - middle, 2 - bottom
unsigned int score;
unsigned char status;
Image *outputPtr;
unsigned char spriteIndex;
unsigned char paletteIndex;
ivec2 getCollisionResponse(const ivec2& currentPosition, const ivec2& newPosition);
void updateStatus();
Character();
void setPosition(const ivec2& value);
const ivec2 getPosition() const;
void update(int deltaTime);
void draw(Image* output, const unsigned long long currentTime);
void setDead();
};
#endif // __CHARACTER_H__
|
Kiep13/BookFund-v.2
|
apps/frontpages/src/app/components/bookfund-page/index.js
|
<filename>apps/frontpages/src/app/components/bookfund-page/index.js
import BookFundPage from "./bookfund-page";
export default BookFundPage;
|
scfinniss/jabref
|
src/main/java/org/jabref/gui/preferences/NameFormatterItemModel.java
|
<filename>src/main/java/org/jabref/gui/preferences/NameFormatterItemModel.java
package org.jabref.gui.preferences;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import org.jabref.logic.layout.format.NameFormatter;
public class NameFormatterItemModel {
private final StringProperty name = new SimpleStringProperty("");
private final StringProperty format = new SimpleStringProperty("");
NameFormatterItemModel() {
this("");
}
NameFormatterItemModel(String name) {
this(name, NameFormatter.DEFAULT_FORMAT);
}
NameFormatterItemModel(String name, String format) {
this.name.setValue(name);
this.format.setValue(format);
}
public void setName(String name) {
this.name.setValue(name);
}
public String getName() {
return name.getValue();
}
public StringProperty nameProperty() {
return name;
}
public void setFormat(String format) {
this.format.setValue(format);
}
public String getFormat() {
return format.getValue();
}
public StringProperty formatProperty() {
return format;
}
@Override
public String toString() {
return "[" + name.getValue() + "," + format.getValue() + "]";
}
}
|
gorkem0606/moderasyon-botlari
|
Moderator 11/src/Commands/Staff/rol-log.js
|
const conf = require("../../configs/config.json");
const ayar = require("../../configs/settings.json")
const emoji = require("../../configs/emoji.json")
const roles = require("../../Schemas/rol-log")
const moment = require("moment");
moment.locale("tr");
module.exports = {
conf: {
aliases: ["rol-log","rolbilgi"],
name: "rollog",
help: "rollog [Kullanıcı]"
},
run: async (client, message, args, embed) => {
if(![conf.Staff].some(role => message.member.roles.cache.get(role)) && !message.member.hasPermission('ADMINISTRATOR')) return message.react(emoji.CarpiID)
//return message.channel.send(embed.setDescription(`Bu komutu kullanmak için \`${message.guild.roles.cache.find(x => x.id === conf.Staff).name}\` yetkisine sahip olman lazım`))
const member = message.mentions.members.first() || message.guild.members.cache.get(args[0]);
if (!member) { return message.channel.send("Bir kullanıcı belirtmelisin!") }
let data = await roles.findOne({ guildID: message.guild.id, userID: member.user.id});
if (!data) { return message.channel.send(embed.setDescription(`${member} üyesinin rol geçmişi bulunmuyor!`)) }
data = data.roles.sort((a, b) => b.date - a.date).map((x) =>
`${x.type ? emoji.TikID + " Rol verildi" : emoji.CarpiID + " Rol alındı"}. Rol: <@&${x.role}> Yetkili: <@${x.staff}>
Tarih: \`${moment(x.date).format("LLL")}\` \`(${moment(x.date).fromNow()})\``).join("\n**────────────────────────**\n");
for (var i = 0; i < Math.floor(data.length / 2000); i++) {
message.channel.send(embed.setDescription(data.slice(0, 2000)));
data = data.slice(2000);
}
message.react(emoji.TikID)
if (data.length > 0) message.channel.send(embed.setDescription(data));
},
};
|
HelpGiveThanks/Library
|
scripts/tagMenu/lock.c
|
<filename>scripts/tagMenu/lock.c
January 21, 2018 11:49:18 Library.fmp12 - lock -1-
tagMenu: lock
If [ nodeLockTagGroupCreatorLock::orderOrLock = "lock" ]
Go to Field [ ]
Show Custom Dialog [ Message: "Type the following into the box below to unlock all content created by " &
nodeLockTagGroupCreatorLock::tag; Default Button: “OK”, Commit: “Yes”; Button 2: “Cancel”, Commit: “No” ]
Halt Script
End If
|
mayonghui9182/helloWorld
|
sourceCode/testMaven/src/main/java/com/ma/test/Class/annotation/TestAnnotation.java
|
package com.ma.test.Class.annotation;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
public class TestAnnotation {
@Test
/** 只能获取本类中中的注解,不能获取父类中的注解 by mayh*/
private void testAnnotations() {
Annotation[] annotations = AnnotationClass.class.getAnnotations();
for (int i = 0; i < annotations.length; i++) {
System.out.println(annotations[i].toString());
}
Method[] methods = AnnotationClass.class.getMethods();
Annotation[] annotations1 = methods[1].getAnnotations();
for (int i = 0; i < annotations1.length; i++) {
System.out.println(annotations1[i].toString());
}
Parameter[] parameters = methods[1].getParameters();
Annotation[] annotations2 = parameters[0].getAnnotations();
for (int i = 0; i < annotations2.length; i++) {
System.out.println(annotations2[i].toString());
}
}
@Test
/** 只能获取本类的接口,不能获取父类中的接口 by mayh*/
public void testGetInterfaces() {
Class<?>[] interfaces = AnnotationClass.class.getInterfaces();
for (int i = 0; i < interfaces.length; i++) {
Method[] declaredMethods = interfaces[i].getDeclaredMethods();
for (int j = 0; j< declaredMethods.length; j++) {
System.out.println(declaredMethods[j].toString());
}
}
}
/** 只返回本来的方法 by mayh*/
@Test
public void testGetMethod() {
Method[] declaredMethods = AnnotationClass.class.getDeclaredMethods();
for (int i = 0; i < declaredMethods.length; i++) {
System.out.println(declaredMethods[i].toString());
}
}
}
|
jriwanek/RaspberryPi
|
test-harness/include/bcm2708_chip/pcm.h
|
<reponame>jriwanek/RaspberryPi
// This file was generated by the create_regs script
#define PCM_BASE 0x7e203000
#define PCM_CS_A HW_REGISTER_RW( 0x7e203000 )
#define PCM_CS_A_MASK 0x03ffe3ff
#define PCM_CS_A_WIDTH 26
#define PCM_CS_A_RESET 0000000000
#define PCM_CS_A_STBY_BITS 25:25
#define PCM_CS_A_STBY_SET 0x02000000
#define PCM_CS_A_STBY_CLR 0xfdffffff
#define PCM_CS_A_STBY_MSB 25
#define PCM_CS_A_STBY_LSB 25
#define PCM_CS_A_SYNC_BITS 24:24
#define PCM_CS_A_SYNC_SET 0x01000000
#define PCM_CS_A_SYNC_CLR 0xfeffffff
#define PCM_CS_A_SYNC_MSB 24
#define PCM_CS_A_SYNC_LSB 24
#define PCM_CS_A_RXSEX_BITS 23:23
#define PCM_CS_A_RXSEX_SET 0x00800000
#define PCM_CS_A_RXSEX_CLR 0xff7fffff
#define PCM_CS_A_RXSEX_MSB 23
#define PCM_CS_A_RXSEX_LSB 23
#define PCM_CS_A_RXF_BITS 22:22
#define PCM_CS_A_RXF_SET 0x00400000
#define PCM_CS_A_RXF_CLR 0xffbfffff
#define PCM_CS_A_RXF_MSB 22
#define PCM_CS_A_RXF_LSB 22
#define PCM_CS_A_TXE_BITS 21:21
#define PCM_CS_A_TXE_SET 0x00200000
#define PCM_CS_A_TXE_CLR 0xffdfffff
#define PCM_CS_A_TXE_MSB 21
#define PCM_CS_A_TXE_LSB 21
#define PCM_CS_A_RXD_BITS 20:20
#define PCM_CS_A_RXD_SET 0x00100000
#define PCM_CS_A_RXD_CLR 0xffefffff
#define PCM_CS_A_RXD_MSB 20
#define PCM_CS_A_RXD_LSB 20
#define PCM_CS_A_TXD_BITS 19:19
#define PCM_CS_A_TXD_SET 0x00080000
#define PCM_CS_A_TXD_CLR 0xfff7ffff
#define PCM_CS_A_TXD_MSB 19
#define PCM_CS_A_TXD_LSB 19
#define PCM_CS_A_RXR_BITS 18:18
#define PCM_CS_A_RXR_SET 0x00040000
#define PCM_CS_A_RXR_CLR 0xfffbffff
#define PCM_CS_A_RXR_MSB 18
#define PCM_CS_A_RXR_LSB 18
#define PCM_CS_A_TXW_BITS 17:17
#define PCM_CS_A_TXW_SET 0x00020000
#define PCM_CS_A_TXW_CLR 0xfffdffff
#define PCM_CS_A_TXW_MSB 17
#define PCM_CS_A_TXW_LSB 17
#define PCM_CS_A_RXERR_BITS 16:16
#define PCM_CS_A_RXERR_SET 0x00010000
#define PCM_CS_A_RXERR_CLR 0xfffeffff
#define PCM_CS_A_RXERR_MSB 16
#define PCM_CS_A_RXERR_LSB 16
#define PCM_CS_A_TXERR_BITS 15:15
#define PCM_CS_A_TXERR_SET 0x00008000
#define PCM_CS_A_TXERR_CLR 0xffff7fff
#define PCM_CS_A_TXERR_MSB 15
#define PCM_CS_A_TXERR_LSB 15
#define PCM_CS_A_RXSYNC_BITS 14:14
#define PCM_CS_A_RXSYNC_SET 0x00004000
#define PCM_CS_A_RXSYNC_CLR 0xffffbfff
#define PCM_CS_A_RXSYNC_MSB 14
#define PCM_CS_A_RXSYNC_LSB 14
#define PCM_CS_A_TXSYNC_BITS 13:13
#define PCM_CS_A_TXSYNC_SET 0x00002000
#define PCM_CS_A_TXSYNC_CLR 0xffffdfff
#define PCM_CS_A_TXSYNC_MSB 13
#define PCM_CS_A_TXSYNC_LSB 13
#define PCM_CS_A_DMAEN_BITS 9:9
#define PCM_CS_A_DMAEN_SET 0x00000200
#define PCM_CS_A_DMAEN_CLR 0xfffffdff
#define PCM_CS_A_DMAEN_MSB 9
#define PCM_CS_A_DMAEN_LSB 9
#define PCM_CS_A_RXTHR_BITS 8:7
#define PCM_CS_A_RXTHR_SET 0x00000180
#define PCM_CS_A_RXTHR_CLR 0xfffffe7f
#define PCM_CS_A_RXTHR_MSB 8
#define PCM_CS_A_RXTHR_LSB 7
#define PCM_CS_A_TXTHR_BITS 6:5
#define PCM_CS_A_TXTHR_SET 0x00000060
#define PCM_CS_A_TXTHR_CLR 0xffffff9f
#define PCM_CS_A_TXTHR_MSB 6
#define PCM_CS_A_TXTHR_LSB 5
#define PCM_CS_A_RXCLR_BITS 4:4
#define PCM_CS_A_RXCLR_SET 0x00000010
#define PCM_CS_A_RXCLR_CLR 0xffffffef
#define PCM_CS_A_RXCLR_MSB 4
#define PCM_CS_A_RXCLR_LSB 4
#define PCM_CS_A_TXCLR_BITS 3:3
#define PCM_CS_A_TXCLR_SET 0x00000008
#define PCM_CS_A_TXCLR_CLR 0xfffffff7
#define PCM_CS_A_TXCLR_MSB 3
#define PCM_CS_A_TXCLR_LSB 3
#define PCM_CS_A_TXON_BITS 2:2
#define PCM_CS_A_TXON_SET 0x00000004
#define PCM_CS_A_TXON_CLR 0xfffffffb
#define PCM_CS_A_TXON_MSB 2
#define PCM_CS_A_TXON_LSB 2
#define PCM_CS_A_RXON_BITS 1:1
#define PCM_CS_A_RXON_SET 0x00000002
#define PCM_CS_A_RXON_CLR 0xfffffffd
#define PCM_CS_A_RXON_MSB 1
#define PCM_CS_A_RXON_LSB 1
#define PCM_CS_A_EN_BITS 0:0
#define PCM_CS_A_EN_SET 0x00000001
#define PCM_CS_A_EN_CLR 0xfffffffe
#define PCM_CS_A_EN_MSB 0
#define PCM_CS_A_EN_LSB 0
#define PCM_FIFO_A HW_REGISTER_RW( 0x7e203004 )
#define PCM_FIFO_A_MASK 0xffffffff
#define PCM_FIFO_A_WIDTH 32
#define PCM_MODE_A HW_REGISTER_RW( 0x7e203008 )
#define PCM_MODE_A_MASK 0x1fffffff
#define PCM_MODE_A_WIDTH 29
#define PCM_MODE_A_RESET 0000000000
#define PCM_MODE_A_CLK_DIS_BITS 28:28
#define PCM_MODE_A_CLK_DIS_SET 0x10000000
#define PCM_MODE_A_CLK_DIS_CLR 0xefffffff
#define PCM_MODE_A_CLK_DIS_MSB 28
#define PCM_MODE_A_CLK_DIS_LSB 28
#define PCM_MODE_A_PDMN_BITS 27:27
#define PCM_MODE_A_PDMN_SET 0x08000000
#define PCM_MODE_A_PDMN_CLR 0xf7ffffff
#define PCM_MODE_A_PDMN_MSB 27
#define PCM_MODE_A_PDMN_LSB 27
#define PCM_MODE_A_PDME_BITS 26:26
#define PCM_MODE_A_PDME_SET 0x04000000
#define PCM_MODE_A_PDME_CLR 0xfbffffff
#define PCM_MODE_A_PDME_MSB 26
#define PCM_MODE_A_PDME_LSB 26
#define PCM_MODE_A_FRXP_BITS 25:25
#define PCM_MODE_A_FRXP_SET 0x02000000
#define PCM_MODE_A_FRXP_CLR 0xfdffffff
#define PCM_MODE_A_FRXP_MSB 25
#define PCM_MODE_A_FRXP_LSB 25
#define PCM_MODE_A_FTXP_BITS 24:24
#define PCM_MODE_A_FTXP_SET 0x01000000
#define PCM_MODE_A_FTXP_CLR 0xfeffffff
#define PCM_MODE_A_FTXP_MSB 24
#define PCM_MODE_A_FTXP_LSB 24
#define PCM_MODE_A_CLKM_BITS 23:23
#define PCM_MODE_A_CLKM_SET 0x00800000
#define PCM_MODE_A_CLKM_CLR 0xff7fffff
#define PCM_MODE_A_CLKM_MSB 23
#define PCM_MODE_A_CLKM_LSB 23
#define PCM_MODE_A_CLKI_BITS 22:22
#define PCM_MODE_A_CLKI_SET 0x00400000
#define PCM_MODE_A_CLKI_CLR 0xffbfffff
#define PCM_MODE_A_CLKI_MSB 22
#define PCM_MODE_A_CLKI_LSB 22
#define PCM_MODE_A_FSM_BITS 21:21
#define PCM_MODE_A_FSM_SET 0x00200000
#define PCM_MODE_A_FSM_CLR 0xffdfffff
#define PCM_MODE_A_FSM_MSB 21
#define PCM_MODE_A_FSM_LSB 21
#define PCM_MODE_A_FSI_BITS 20:20
#define PCM_MODE_A_FSI_SET 0x00100000
#define PCM_MODE_A_FSI_CLR 0xffefffff
#define PCM_MODE_A_FSI_MSB 20
#define PCM_MODE_A_FSI_LSB 20
#define PCM_MODE_A_FLEN_BITS 19:10
#define PCM_MODE_A_FLEN_SET 0x000ffc00
#define PCM_MODE_A_FLEN_CLR 0xfff003ff
#define PCM_MODE_A_FLEN_MSB 19
#define PCM_MODE_A_FLEN_LSB 10
#define PCM_MODE_A_FSLEN_BITS 9:0
#define PCM_MODE_A_FSLEN_SET 0x000003ff
#define PCM_MODE_A_FSLEN_CLR 0xfffffc00
#define PCM_MODE_A_FSLEN_MSB 9
#define PCM_MODE_A_FSLEN_LSB 0
#define PCM_RXC_A HW_REGISTER_RW( 0x7e20300c )
#define PCM_RXC_A_MASK 0xffffffff
#define PCM_RXC_A_WIDTH 32
#define PCM_RXC_A_RESET 0000000000
#define PCM_RXC_A_CH1WEX_BITS 31:31
#define PCM_RXC_A_CH1WEX_SET 0x80000000
#define PCM_RXC_A_CH1WEX_CLR 0x7fffffff
#define PCM_RXC_A_CH1WEX_MSB 31
#define PCM_RXC_A_CH1WEX_LSB 31
#define PCM_RXC_A_CH1EN_BITS 30:30
#define PCM_RXC_A_CH1EN_SET 0x40000000
#define PCM_RXC_A_CH1EN_CLR 0xbfffffff
#define PCM_RXC_A_CH1EN_MSB 30
#define PCM_RXC_A_CH1EN_LSB 30
#define PCM_RXC_A_CH1POS_BITS 29:20
#define PCM_RXC_A_CH1POS_SET 0x3ff00000
#define PCM_RXC_A_CH1POS_CLR 0xc00fffff
#define PCM_RXC_A_CH1POS_MSB 29
#define PCM_RXC_A_CH1POS_LSB 20
#define PCM_RXC_A_CH1WID_BITS 19:16
#define PCM_RXC_A_CH1WID_SET 0x000f0000
#define PCM_RXC_A_CH1WID_CLR 0xfff0ffff
#define PCM_RXC_A_CH1WID_MSB 19
#define PCM_RXC_A_CH1WID_LSB 16
#define PCM_RXC_A_CH2WEX_BITS 15:15
#define PCM_RXC_A_CH2WEX_SET 0x00008000
#define PCM_RXC_A_CH2WEX_CLR 0xffff7fff
#define PCM_RXC_A_CH2WEX_MSB 15
#define PCM_RXC_A_CH2WEX_LSB 15
#define PCM_RXC_A_CH2EN_BITS 14:14
#define PCM_RXC_A_CH2EN_SET 0x00004000
#define PCM_RXC_A_CH2EN_CLR 0xffffbfff
#define PCM_RXC_A_CH2EN_MSB 14
#define PCM_RXC_A_CH2EN_LSB 14
#define PCM_RXC_A_CH2POS_BITS 13:4
#define PCM_RXC_A_CH2POS_SET 0x00003ff0
#define PCM_RXC_A_CH2POS_CLR 0xffffc00f
#define PCM_RXC_A_CH2POS_MSB 13
#define PCM_RXC_A_CH2POS_LSB 4
#define PCM_RXC_A_CH2WID_BITS 3:0
#define PCM_RXC_A_CH2WID_SET 0x0000000f
#define PCM_RXC_A_CH2WID_CLR 0xfffffff0
#define PCM_RXC_A_CH2WID_MSB 3
#define PCM_RXC_A_CH2WID_LSB 0
#define PCM_TXC_A HW_REGISTER_RW( 0x7e203010 )
#define PCM_TXC_A_MASK 0xffffffff
#define PCM_TXC_A_WIDTH 32
#define PCM_TXC_A_RESET 0000000000
#define PCM_TXC_A_CH1WEX_BITS 31:31
#define PCM_TXC_A_CH1WEX_SET 0x80000000
#define PCM_TXC_A_CH1WEX_CLR 0x7fffffff
#define PCM_TXC_A_CH1WEX_MSB 31
#define PCM_TXC_A_CH1WEX_LSB 31
#define PCM_TXC_A_CH1EN_BITS 30:30
#define PCM_TXC_A_CH1EN_SET 0x40000000
#define PCM_TXC_A_CH1EN_CLR 0xbfffffff
#define PCM_TXC_A_CH1EN_MSB 30
#define PCM_TXC_A_CH1EN_LSB 30
#define PCM_TXC_A_CH1POS_BITS 29:20
#define PCM_TXC_A_CH1POS_SET 0x3ff00000
#define PCM_TXC_A_CH1POS_CLR 0xc00fffff
#define PCM_TXC_A_CH1POS_MSB 29
#define PCM_TXC_A_CH1POS_LSB 20
#define PCM_TXC_A_CH1WID_BITS 19:16
#define PCM_TXC_A_CH1WID_SET 0x000f0000
#define PCM_TXC_A_CH1WID_CLR 0xfff0ffff
#define PCM_TXC_A_CH1WID_MSB 19
#define PCM_TXC_A_CH1WID_LSB 16
#define PCM_TXC_A_CH2WEX_BITS 15:15
#define PCM_TXC_A_CH2WEX_SET 0x00008000
#define PCM_TXC_A_CH2WEX_CLR 0xffff7fff
#define PCM_TXC_A_CH2WEX_MSB 15
#define PCM_TXC_A_CH2WEX_LSB 15
#define PCM_TXC_A_CH2EN_BITS 14:14
#define PCM_TXC_A_CH2EN_SET 0x00004000
#define PCM_TXC_A_CH2EN_CLR 0xffffbfff
#define PCM_TXC_A_CH2EN_MSB 14
#define PCM_TXC_A_CH2EN_LSB 14
#define PCM_TXC_A_CH2POS_BITS 13:4
#define PCM_TXC_A_CH2POS_SET 0x00003ff0
#define PCM_TXC_A_CH2POS_CLR 0xffffc00f
#define PCM_TXC_A_CH2POS_MSB 13
#define PCM_TXC_A_CH2POS_LSB 4
#define PCM_TXC_A_CH2WID_BITS 3:0
#define PCM_TXC_A_CH2WID_SET 0x0000000f
#define PCM_TXC_A_CH2WID_CLR 0xfffffff0
#define PCM_TXC_A_CH2WID_MSB 3
#define PCM_TXC_A_CH2WID_LSB 0
#define PCM_DREQ_A HW_REGISTER_RW( 0x7e203014 )
#define PCM_DREQ_A_MASK 0x7f7f7f7f
#define PCM_DREQ_A_WIDTH 31
#define PCM_DREQ_A_RESET 0x10303020
#define PCM_DREQ_A_TX_PANIC_BITS 30:24
#define PCM_DREQ_A_TX_PANIC_SET 0x7f000000
#define PCM_DREQ_A_TX_PANIC_CLR 0x80ffffff
#define PCM_DREQ_A_TX_PANIC_MSB 30
#define PCM_DREQ_A_TX_PANIC_LSB 24
#define PCM_DREQ_A_RX_PANIC_BITS 22:16
#define PCM_DREQ_A_RX_PANIC_SET 0x007f0000
#define PCM_DREQ_A_RX_PANIC_CLR 0xff80ffff
#define PCM_DREQ_A_RX_PANIC_MSB 22
#define PCM_DREQ_A_RX_PANIC_LSB 16
#define PCM_DREQ_A_TX_BITS 14:8
#define PCM_DREQ_A_TX_SET 0x00007f00
#define PCM_DREQ_A_TX_CLR 0xffff80ff
#define PCM_DREQ_A_TX_MSB 14
#define PCM_DREQ_A_TX_LSB 8
#define PCM_DREQ_A_RX_BITS 6:0
#define PCM_DREQ_A_RX_SET 0x0000007f
#define PCM_DREQ_A_RX_CLR 0xffffff80
#define PCM_DREQ_A_RX_MSB 6
#define PCM_DREQ_A_RX_LSB 0
#define PCM_INTEN_A HW_REGISTER_RW( 0x7e203018 )
#define PCM_INTEN_A_MASK 0x0000000f
#define PCM_INTEN_A_WIDTH 4
#define PCM_INTEN_A_RESET 0000000000
#define PCM_INTEN_A_RXERR_BITS 3:3
#define PCM_INTEN_A_RXERR_SET 0x00000008
#define PCM_INTEN_A_RXERR_CLR 0xfffffff7
#define PCM_INTEN_A_RXERR_MSB 3
#define PCM_INTEN_A_RXERR_LSB 3
#define PCM_INTEN_A_TXERR_BITS 2:2
#define PCM_INTEN_A_TXERR_SET 0x00000004
#define PCM_INTEN_A_TXERR_CLR 0xfffffffb
#define PCM_INTEN_A_TXERR_MSB 2
#define PCM_INTEN_A_TXERR_LSB 2
#define PCM_INTEN_A_RXR_BITS 1:1
#define PCM_INTEN_A_RXR_SET 0x00000002
#define PCM_INTEN_A_RXR_CLR 0xfffffffd
#define PCM_INTEN_A_RXR_MSB 1
#define PCM_INTEN_A_RXR_LSB 1
#define PCM_INTEN_A_TXW_BITS 0:0
#define PCM_INTEN_A_TXW_SET 0x00000001
#define PCM_INTEN_A_TXW_CLR 0xfffffffe
#define PCM_INTEN_A_TXW_MSB 0
#define PCM_INTEN_A_TXW_LSB 0
#define PCM_INTSTC_A HW_REGISTER_RW( 0x7e20301c )
#define PCM_INTSTC_A_MASK 0x0000000f
#define PCM_INTSTC_A_WIDTH 4
#define PCM_INTSTC_A_RESET 0000000000
#define PCM_INTSTC_A_RXERR_BITS 3:3
#define PCM_INTSTC_A_RXERR_SET 0x00000008
#define PCM_INTSTC_A_RXERR_CLR 0xfffffff7
#define PCM_INTSTC_A_RXERR_MSB 3
#define PCM_INTSTC_A_RXERR_LSB 3
#define PCM_INTSTC_A_TXERR_BITS 2:2
#define PCM_INTSTC_A_TXERR_SET 0x00000004
#define PCM_INTSTC_A_TXERR_CLR 0xfffffffb
#define PCM_INTSTC_A_TXERR_MSB 2
#define PCM_INTSTC_A_TXERR_LSB 2
#define PCM_INTSTC_A_RXR_BITS 1:1
#define PCM_INTSTC_A_RXR_SET 0x00000002
#define PCM_INTSTC_A_RXR_CLR 0xfffffffd
#define PCM_INTSTC_A_RXR_MSB 1
#define PCM_INTSTC_A_RXR_LSB 1
#define PCM_INTSTC_A_TXW_BITS 0:0
#define PCM_INTSTC_A_TXW_SET 0x00000001
#define PCM_INTSTC_A_TXW_CLR 0xfffffffe
#define PCM_INTSTC_A_TXW_MSB 0
#define PCM_INTSTC_A_TXW_LSB 0
#define PCM_GRAY HW_REGISTER_RW( 0x7e203020 )
#define PCM_GRAY_MASK 0x003ffff7
#define PCM_GRAY_WIDTH 22
#define PCM_GRAY_RESET 0000000000
#define PCM_GRAY_RXFIFOLEVEL_BITS 21:16
#define PCM_GRAY_RXFIFOLEVEL_SET 0x003f0000
#define PCM_GRAY_RXFIFOLEVEL_CLR 0xffc0ffff
#define PCM_GRAY_RXFIFOLEVEL_MSB 21
#define PCM_GRAY_RXFIFOLEVEL_LSB 16
#define PCM_GRAY_FLUSHED_BITS 15:10
#define PCM_GRAY_FLUSHED_SET 0x0000fc00
#define PCM_GRAY_FLUSHED_CLR 0xffff03ff
#define PCM_GRAY_FLUSHED_MSB 15
#define PCM_GRAY_FLUSHED_LSB 10
#define PCM_GRAY_RXLEVEL_BITS 9:4
#define PCM_GRAY_RXLEVEL_SET 0x000003f0
#define PCM_GRAY_RXLEVEL_CLR 0xfffffc0f
#define PCM_GRAY_RXLEVEL_MSB 9
#define PCM_GRAY_RXLEVEL_LSB 4
#define PCM_GRAY_FLUSH_BITS 2:2
#define PCM_GRAY_FLUSH_SET 0x00000004
#define PCM_GRAY_FLUSH_CLR 0xfffffffb
#define PCM_GRAY_FLUSH_MSB 2
#define PCM_GRAY_FLUSH_LSB 2
#define PCM_GRAY_CLR_BITS 1:1
#define PCM_GRAY_CLR_SET 0x00000002
#define PCM_GRAY_CLR_CLR 0xfffffffd
#define PCM_GRAY_CLR_MSB 1
#define PCM_GRAY_CLR_LSB 1
#define PCM_GRAY_EN_BITS 0:0
#define PCM_GRAY_EN_SET 0x00000001
#define PCM_GRAY_EN_CLR 0xfffffffe
#define PCM_GRAY_EN_MSB 0
#define PCM_GRAY_EN_LSB 0
|
dcompane/controlm_go
|
model_statistics_average_info.go
|
/*
* Control-M Services
*
* Provides access to BMC Control-M Services
*
* API version: 9.20.115
* Contact: <EMAIL>
* Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git)
*/
package controlm_go
type StatisticsAverageInfo struct {
// Average start time
StartTime string `json:"startTime,omitempty"`
// Average CPU time
CpuTime string `json:"cpuTime,omitempty"`
// Average time
RunTime string `json:"runTime,omitempty"`
}
|
aleksandra992/TelerikAcademy
|
JavaScript-DOMandUI/JQueryPlugins/tasks/task-1.js
|
<gh_stars>0
function solve() {
return function (selector) {
var $selectElement = $(selector).hide();
var $optionElements = $selectElement.find('option');
var $divDropDown = $('<div>')
.addClass("dropdown-list")
.append($selectElement);
var $current = $('<div>')
.addClass("current")
.attr("data-value", '')
.text("Select value");
var $divOptionsContainer = $('<div>')
.addClass("options-container").css({
'position': 'absolute',
'display': 'none'
});
for (var i = 0; i < $optionElements.length; i += 1) {
var $optionElement = $optionElements[i];
console.log($($optionElement).val());
var $newDivOption = $('<div>');
$newDivOption.addClass("dropdown-item").
attr("data-value", $($optionElement).val()).
attr("data-index", i).
text($($optionElement).text());
$divOptionsContainer.append($newDivOption);
}
$divDropDown.append($selectElement);
$divDropDown.append($current);
$divDropDown.append($divOptionsContainer);
$divDropDown.appendTo("body");
$current.on('click', function () {
$current.text('Select a value');
if ($divOptionsContainer.css('display') === 'block') {
$divOptionsContainer.css('display', 'none');
}
else {
$divOptionsContainer.css('display', 'block');
}
});
$divOptionsContainer.on('click', '.dropdown-item', function () {
$current.text($(this).html());
$current.val($(this).attr('data-value'));
$divOptionsContainer.css('display', 'none');
$selectElement.val($(this).attr('data-value'));
});
};
}
module.exports = solve;
|
lottie-c/spl_tests_new
|
src/java/cz/cuni/mff/spl/evaluator/r/RProjectCaller.java
|
<reponame>lottie-c/spl_tests_new
/*
* Copyright (c) 2012, <NAME>, <NAME>, <NAME>, <NAME>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the author nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
package cz.cuni.mff.spl.evaluator.r;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.LinkedList;
import java.util.List;
import java.util.StringTokenizer;
import org.jfree.data.xy.XYSeries;
import cz.cuni.mff.spl.InvokedExecutionConfiguration;
import cz.cuni.mff.spl.Run;
import cz.cuni.mff.spl.evaluator.graphs.GraphUtils;
import cz.cuni.mff.spl.utils.ConvertUtils;
import cz.cuni.mff.spl.utils.logging.SplLog;
import cz.cuni.mff.spl.utils.logging.SplLogger;
/**
* <p>
* Simple interface to call R scripts.
* <p>
* {@code Rscript} executable is expected to be either in PATH environment
* property or specified in SPL evaluation configuration.
*
* @author <NAME>
*
* @see http://www.r-project.org/
*/
public class RProjectCaller {
/** The logger. */
private static final SplLog logger = SplLogger.getLogger(RProjectCaller.class);
/** The Rsript executable command. */
private final String R_runtime_command;
/** The project R script processor. */
public static final String R_RUNTIME_DEFAULT = "Rscript";
/** The working directory. */
private final File workingDirectory;
/** The r script file. */
private File R_SCRIPT_FILE;
/** The r script x values. */
private File R_SCRIPT_XVALUES;
/** The r script y values file. */
private File R_SCRIPT_YVALUES;
/** The file number. */
private static volatile int fileNumber = 0;
/**
* Instantiates a new R project caller.
*
* @param rScriptCommand
* The Rscript command.
* @param workingDirectory
* The working directory.
*/
public RProjectCaller(String rScriptCommand, File workingDirectory) {
this.R_runtime_command = rScriptCommand;
this.workingDirectory = workingDirectory;
}
/**
* Gets the density series.
*
* @param data
* The data.
* @param seriesName
* The series name.
* @return The density series.
*/
public synchronized XYSeries getDensitySeries(double[] data, String seriesName) {
try {
int runFileNumber = ++fileNumber;
R_SCRIPT_FILE = new File(workingDirectory, String.format("spl-rscript-%d.r", runFileNumber));
R_SCRIPT_XVALUES = new File(workingDirectory, String.format("spl-rscript-x-%d.txt", runFileNumber));
R_SCRIPT_YVALUES = new File(workingDirectory, String.format("spl-rscript-y-%d.txt", runFileNumber));
R_SCRIPT_FILE.createNewFile();
R_SCRIPT_XVALUES.createNewFile();
R_SCRIPT_YVALUES.createNewFile();
} catch (IOException e) {
logger.error(e, "Unable to create temporary file.");
throw new IllegalStateException("Unable to create temporary file.", e);
}
return this.getDensitySeriesImpl(data, seriesName);
}
/**
* Gets the density series.
*
* @param data
* The data.
* @param seriesName
* The series name.
* @return The density series. When error in obtaining series occurs, than
* series with no points is returned.
*/
private XYSeries getDensitySeriesImpl(double[] data, String seriesName) {
try {
prepareDensityScriptFile(data);
InvokedExecutionConfiguration.checkIfExecutionAborted();
runProcess();
InvokedExecutionConfiguration.checkIfExecutionAborted();
return loadResult(seriesName);
} catch (IOException e) {
logger.error(e, "Unable to compute density function.");
} catch (InterruptedException e) {
logger.error(e, "Unable to compute density function.");
InvokedExecutionConfiguration.checkIfExecutionAborted();
// if executoin was not aborted, clear the interrupted flag
Thread.interrupted();
}
return new XYSeries(seriesName);
}
/**
* Run process.
*
* @throws IOException
* Signals that an I/O exception has occurred.
* @throws InterruptedException
* Thrown when execution was aborted when waiting for Rscript
* process to compute density, see
* {@link Run#runForInvocation(File, File, File, String, cz.cuni.mff.spl.utils.interactive.InteractiveInterface)}
* .
*/
private void runProcess() throws IOException, InterruptedException {
ProcessBuilder processBuilder = new ProcessBuilder(R_runtime_command, R_SCRIPT_FILE.getAbsolutePath());
logger.trace("Processing call to RSCRIPT...");
logger.trace(processBuilder.toString());
Process p = processBuilder.start();
// we need to be able to abort execution when invoked remotely
p.waitFor();
String line;
try (
BufferedReader bri = new BufferedReader(new InputStreamReader(
p.getInputStream()));
BufferedReader bre = new BufferedReader(new InputStreamReader(
p.getErrorStream()))) {
while ((line = bri.readLine()) != null) {
logger.trace("Rscript out: " + line);
InvokedExecutionConfiguration.checkIfExecutionAborted();
}
while ((line = bre.readLine()) != null) {
logger.error("Rscript err: " + line);
InvokedExecutionConfiguration.checkIfExecutionAborted();
}
}
logger.trace("Done.");
}
/**
* Load result.
*
* @param seriesName
* The series name.
* @return the xY series
*/
private XYSeries loadResult(String seriesName) {
double[] xValues = loadFile(R_SCRIPT_XVALUES);
double[] yValues = loadFile(R_SCRIPT_YVALUES);
return GraphUtils.createSeriesOfPoints(xValues, yValues, seriesName);
}
/**
* Load file.
*
* @param file
* The filename.
* @return the double[]
*/
private static double[] loadFile(File file) {
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
String line;
StringTokenizer tokenizer;
List<Double> data = new LinkedList<>();
while ((line = reader.readLine()) != null) {
tokenizer = new StringTokenizer(line, " ");
while (tokenizer.hasMoreElements()) {
String nextToken = tokenizer.nextToken();
data.add(Double.parseDouble(nextToken));
}
}
return ConvertUtils.convertDoublesToArray(data, new double[data.size()]);
} catch (IOException | NumberFormatException e) {
logger.error("Unable to read measured density function data from file [%s]", file.getPath());
}
return new double[0];
}
/**
* Prepares density script file.
*
* @param data
* The data.
*/
private void prepareDensityScriptFile(double[] data) {
if (data.length < 2) {
return;
}
try {
PrintWriter writer = new PrintWriter(new FileWriter(R_SCRIPT_FILE));
writer.println("# SPL Evaluator generated temporary file");
writer.println("density.adjust <- 1");
writer.println("data <- as.double(c(");
for (int i = 0; i < data.length; ++i) {
if (i != 0) {
writer.print(',');
}
writer.print(data[i]);
}
writer.println();
writer.println("))");
writer.println("dst <- density(data, adjust=density.adjust)");
writer.printf("write(dst$x, file=\"%s\")\n",
R_SCRIPT_XVALUES.getAbsolutePath().replace("\\", "\\\\"));
writer.printf("write(dst$y, file=\"%s\")\n",
R_SCRIPT_YVALUES.getAbsolutePath().replace("\\", "\\\\"));
writer.close();
} catch (IOException e) {
logger.error(e, "Unable to prepare density function R script to file [%s].", R_SCRIPT_FILE);
e.printStackTrace();
}
}
}
|
Sophia-Okito/codewars-handbook
|
kata/7-kyu/unusual-lex-order/test/SolutionTest.java
|
<filename>kata/7-kyu/unusual-lex-order/test/SolutionTest.java
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import org.junit.jupiter.api.Test;
class SolutionTest {
@Test
void sample() {
assertArrayEquals(new String[] {"a", "a", "b", "c", "d"}, new Solution().unusualLexOrder(new String[] {"a", "b", "a", "d", "c"}));
assertArrayEquals(new String[] {"ta", "nigeb", "gninnigeb", "eht"}, new Solution().unusualLexOrder(new String[] {"nigeb", "ta", "eht", "gninnigeb"}));
}
}
|
Mic-U/ecsher
|
ecs/service.go
|
<reponame>Mic-U/ecsher<filename>ecs/service.go<gh_stars>10-100
package ecs
import (
"context"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/ecs"
ecsTypes "github.com/aws/aws-sdk-go-v2/service/ecs/types"
)
type ECSServiceClient interface {
DescribeServices(context.Context, *ecs.DescribeServicesInput, ...func(*ecs.Options)) (*ecs.DescribeServicesOutput, error)
ListServices(context.Context, *ecs.ListServicesInput, ...func(*ecs.Options)) (*ecs.ListServicesOutput, error)
}
type ListServicesPager interface {
HasMorePages() bool
NextPage(context.Context, ...func(*ecs.Options)) (*ecs.ListServicesOutput, error)
}
// GetService returns Service list. If names is not specified, calls listServices API
func GetService(client ECSServiceClient, cluster string, names []string) ([]ecsTypes.Service, error) {
if len(names) == 0 {
paginator := ecs.NewListServicesPaginator(client, &ecs.ListServicesInput{
Cluster: aws.String(cluster),
})
serviceArns, err := ListAllServices(context.TODO(), paginator)
if err != nil {
return []ecsTypes.Service{}, err
}
if len(serviceArns) == 0 {
return []ecsTypes.Service{}, nil
}
return DescribeService(client, cluster, serviceArns)
}
return DescribeService(client, cluster, names)
}
func ListAllServices(ctx context.Context, paginator ListServicesPager) ([]string, error) {
serviceArns := []string{}
for paginator.HasMorePages() {
output, err := paginator.NextPage(ctx)
if err != nil {
return []string{}, err
}
serviceArns = append(serviceArns, output.ServiceArns...)
}
return serviceArns, nil
}
// DescribeService returns Service list. This requires specifying service name
func DescribeService(client ECSServiceClient, cluster string, names []string) ([]ecsTypes.Service, error) {
describeServicesOutput, err := client.DescribeServices(context.TODO(),
&ecs.DescribeServicesInput{
Cluster: aws.String(cluster),
Services: names,
},
)
if err != nil {
return []ecsTypes.Service{}, err
}
return describeServicesOutput.Services, err
}
|
ScalablyTyped/SlinkyTyped
|
r/react-native-firebase/src/main/scala/typingsSlinky/reactNativeFirebase/mod/PerfModule.scala
|
package typingsSlinky.reactNativeFirebase.mod
import typingsSlinky.reactNativeFirebase.mod.RNFirebase.perf.Perf
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
/* Inlined react-native-firebase.react-native-firebase.FirebaseModuleAndStatics<react-native-firebase.react-native-firebase.RNFirebase.perf.Perf, {}> */
@js.native
trait PerfModule extends StObject {
def apply(): Perf = js.native
var nativeModuleExists: Boolean = js.native
}
|
victorcabeceira/react-swapi
|
src/store/actions/species.js
|
<filename>src/store/actions/species.js
import * as actionTypes from './actionTypes';
export const fetchSpecies = (page) => {
return {
type: actionTypes.FETCH_SPECIES,
page
}
}
export const fetchSpeciesStart = () => {
return {
type: actionTypes.FETCH_SPECIES_START,
}
}
export const fetchSpeciesSuccess = (species) => {
return {
type: actionTypes.FETCH_SPECIES_SUCCESS,
species
}
}
export const fetchSpeciesFail = (error) => {
return {
type: actionTypes.FETCH_SPECIES_FAIL,
error
}
}
|
tamirsagi/flink
|
flink-runtime/src/main/java/org/apache/flink/runtime/io/network/partition/consumer/UnionInputGate.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.flink.runtime.io.network.partition.consumer;
import org.apache.flink.runtime.checkpoint.channel.InputChannelInfo;
import org.apache.flink.runtime.event.TaskEvent;
import org.apache.flink.runtime.io.network.api.EndOfPartitionEvent;
import org.apache.flink.runtime.io.network.partition.PrioritizedDeque;
import org.apache.flink.shaded.guava18.com.google.common.collect.Sets;
import java.io.IOException;
import java.util.Arrays;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
import static org.apache.flink.runtime.concurrent.FutureUtils.assertNoException;
import static org.apache.flink.util.Preconditions.checkArgument;
import static org.apache.flink.util.Preconditions.checkNotNull;
import static org.apache.flink.util.Preconditions.checkState;
/**
* Input gate wrapper to union the input from multiple input gates.
*
* <p>Each input gate has input channels attached from which it reads data. At each input gate, the
* input channels have unique IDs from 0 (inclusive) to the number of input channels (exclusive).
*
* <pre>
* +---+---+ +---+---+---+
* | 0 | 1 | | 0 | 1 | 2 |
* +--------------+--------------+
* | Input gate 0 | Input gate 1 |
* +--------------+--------------+
* </pre>
*
* <p>The union input gate maps these IDs from 0 to the *total* number of input channels across all
* unioned input gates, e.g. the channels of input gate 0 keep their original indexes and the
* channel indexes of input gate 1 are set off by 2 to 2--4.
*
* <pre>
* +---+---++---+---+---+
* | 0 | 1 || 2 | 3 | 4 |
* +--------------------+
* | Union input gate |
* +--------------------+
* </pre>
*
* <strong>It is NOT possible to recursively union union input gates.</strong>
*/
public class UnionInputGate extends InputGate {
/** The input gates to union. */
private final Map<Integer, InputGate> inputGatesByGateIndex;
private final Set<IndexedInputGate> inputGatesWithRemainingData;
/**
* Gates, which notified this input gate about available data. We are using it as a FIFO queue
* of {@link InputGate}s to avoid starvation and provide some basic fairness.
*/
private final PrioritizedDeque<IndexedInputGate> inputGatesWithData = new PrioritizedDeque<>();
private final int[] inputChannelToInputGateIndex;
/**
* A mapping from input gate index to (logical) channel index offset. Valid channel indexes go
* from 0 (inclusive) to the total number of input channels (exclusive).
*/
private final int[] inputGateChannelIndexOffsets;
public UnionInputGate(IndexedInputGate... inputGates) {
inputGatesByGateIndex =
Arrays.stream(inputGates)
.collect(Collectors.toMap(IndexedInputGate::getGateIndex, ig -> ig));
checkArgument(
inputGates.length > 1, "Union input gate should union at least two input gates.");
if (Arrays.stream(inputGates).map(IndexedInputGate::getGateIndex).distinct().count()
!= inputGates.length) {
throw new IllegalArgumentException(
"Union of two input gates with the same gate index. Given indices: "
+ Arrays.stream(inputGates)
.map(IndexedInputGate::getGateIndex)
.collect(Collectors.toList()));
}
this.inputGatesWithRemainingData = Sets.newHashSetWithExpectedSize(inputGates.length);
final int maxGateIndex =
Arrays.stream(inputGates).mapToInt(IndexedInputGate::getGateIndex).max().orElse(0);
int totalNumberOfInputChannels =
Arrays.stream(inputGates)
.mapToInt(IndexedInputGate::getNumberOfInputChannels)
.sum();
inputGateChannelIndexOffsets = new int[maxGateIndex + 1];
inputChannelToInputGateIndex = new int[totalNumberOfInputChannels];
int currentNumberOfInputChannels = 0;
for (final IndexedInputGate inputGate : inputGates) {
inputGateChannelIndexOffsets[inputGate.getGateIndex()] = currentNumberOfInputChannels;
int previousNumberOfInputChannels = currentNumberOfInputChannels;
currentNumberOfInputChannels += inputGate.getNumberOfInputChannels();
Arrays.fill(
inputChannelToInputGateIndex,
previousNumberOfInputChannels,
currentNumberOfInputChannels,
inputGate.getGateIndex());
}
synchronized (inputGatesWithData) {
for (IndexedInputGate inputGate : inputGates) {
inputGatesWithRemainingData.add(inputGate);
CompletableFuture<?> available = inputGate.getAvailableFuture();
if (available.isDone()) {
inputGatesWithData.add(inputGate);
} else {
assertNoException(available.thenRun(() -> queueInputGate(inputGate, false)));
}
assertNoException(
inputGate
.getPriorityEventAvailableFuture()
.thenRun(() -> handlePriorityEventAvailable(inputGate)));
}
if (!inputGatesWithData.isEmpty()) {
availabilityHelper.resetAvailable();
}
}
}
private void handlePriorityEventAvailable(IndexedInputGate inputGate) {
queueInputGate(inputGate, true);
}
/** Returns the total number of input channels across all unioned input gates. */
@Override
public int getNumberOfInputChannels() {
return inputChannelToInputGateIndex.length;
}
@Override
public InputChannel getChannel(int channelIndex) {
int gateIndex = inputChannelToInputGateIndex[channelIndex];
return inputGatesByGateIndex
.get(gateIndex)
.getChannel(channelIndex - inputGateChannelIndexOffsets[gateIndex]);
}
@Override
public boolean isFinished() {
return inputGatesWithRemainingData.isEmpty();
}
@Override
public Optional<BufferOrEvent> getNext() throws IOException, InterruptedException {
return getNextBufferOrEvent(true);
}
@Override
public Optional<BufferOrEvent> pollNext() throws IOException, InterruptedException {
return getNextBufferOrEvent(false);
}
private Optional<BufferOrEvent> getNextBufferOrEvent(boolean blocking)
throws IOException, InterruptedException {
if (inputGatesWithRemainingData.isEmpty()) {
return Optional.empty();
}
Optional<InputWithData<IndexedInputGate, BufferOrEvent>> next =
waitAndGetNextData(blocking);
if (!next.isPresent()) {
return Optional.empty();
}
InputWithData<IndexedInputGate, BufferOrEvent> inputWithData = next.get();
handleEndOfPartitionEvent(inputWithData.data, inputWithData.input);
if (!inputWithData.data.moreAvailable()) {
inputWithData.data.setMoreAvailable(inputWithData.moreAvailable);
}
return Optional.of(inputWithData.data);
}
private Optional<InputWithData<IndexedInputGate, BufferOrEvent>> waitAndGetNextData(
boolean blocking) throws IOException, InterruptedException {
while (true) {
synchronized (inputGatesWithData) {
Optional<IndexedInputGate> inputGateOpt = getInputGate(blocking);
if (!inputGateOpt.isPresent()) {
return Optional.empty();
}
final IndexedInputGate inputGate = inputGateOpt.get();
Optional<BufferOrEvent> nextOpt = inputGate.pollNext();
if (!nextOpt.isPresent()) {
assertNoException(
inputGate
.getAvailableFuture()
.thenRun(() -> queueInputGate(inputGate, false)));
continue;
}
return Optional.of(processBufferOrEvent(inputGate, nextOpt.get()));
}
}
}
private InputWithData<IndexedInputGate, BufferOrEvent> processBufferOrEvent(
IndexedInputGate inputGate, BufferOrEvent bufferOrEvent) {
assert Thread.holdsLock(inputGatesWithData);
if (bufferOrEvent.moreAvailable()) {
// enqueue the inputGate at the end to avoid starvation
inputGatesWithData.add(inputGate, bufferOrEvent.morePriorityEvents(), false);
} else if (!inputGate.isFinished()) {
assertNoException(
inputGate.getAvailableFuture().thenRun(() -> queueInputGate(inputGate, false)));
}
if (bufferOrEvent.hasPriority() && !bufferOrEvent.morePriorityEvents()) {
assertNoException(
inputGate
.getPriorityEventAvailableFuture()
.thenRun(() -> handlePriorityEventAvailable(inputGate)));
}
final boolean morePriorityEvents = inputGatesWithData.getNumPriorityElements() > 0;
if (bufferOrEvent.hasPriority() && !morePriorityEvents) {
priorityAvailabilityHelper.resetUnavailable();
}
return new InputWithData<>(
inputGate, bufferOrEvent, !inputGatesWithData.isEmpty(), morePriorityEvents);
}
private void handleEndOfPartitionEvent(BufferOrEvent bufferOrEvent, InputGate inputGate) {
if (bufferOrEvent.isEvent()
&& bufferOrEvent.getEvent().getClass() == EndOfPartitionEvent.class
&& inputGate.isFinished()) {
checkState(!bufferOrEvent.moreAvailable());
if (!inputGatesWithRemainingData.remove(inputGate)) {
throw new IllegalStateException(
"Couldn't find input gate in set of remaining " + "input gates.");
}
if (isFinished()) {
markAvailable();
}
}
}
private void markAvailable() {
CompletableFuture<?> toNotify;
synchronized (inputGatesWithData) {
toNotify = availabilityHelper.getUnavailableToResetAvailable();
}
toNotify.complete(null);
}
@Override
public void sendTaskEvent(TaskEvent event) throws IOException {
for (InputGate inputGate : inputGatesByGateIndex.values()) {
inputGate.sendTaskEvent(event);
}
}
@Override
public void resumeConsumption(InputChannelInfo channelInfo) throws IOException {
// BEWARE: consumption resumption only happens for streaming jobs in which all
// slots are allocated together so there should be no UnknownInputChannel. We
// will refactor the code to not rely on this assumption in the future.
inputGatesByGateIndex.get(channelInfo.getGateIdx()).resumeConsumption(channelInfo);
}
@Override
public void setup() {}
@Override
public CompletableFuture<Void> getStateConsumedFuture() {
return CompletableFuture.allOf(
inputGatesByGateIndex.values().stream()
.map(InputGate::getStateConsumedFuture)
.collect(Collectors.toList())
.toArray(new CompletableFuture[] {}));
}
@Override
public void requestPartitions() throws IOException {
for (InputGate inputGate : inputGatesByGateIndex.values()) {
inputGate.requestPartitions();
}
}
@Override
public void close() throws IOException {}
@Override
public String toString() {
return "UnionInputGate{" + "inputGates=" + inputGatesByGateIndex.values() + '}';
}
private void queueInputGate(IndexedInputGate inputGate, boolean priority) {
checkNotNull(inputGate);
try (GateNotificationHelper notification =
new GateNotificationHelper(this, inputGatesWithData)) {
synchronized (inputGatesWithData) {
final boolean alreadyEnqueued = inputGatesWithData.contains(inputGate);
if (alreadyEnqueued
&& (!priority || inputGatesWithData.containsPriorityElement(inputGate))) {
// already notified / prioritized (double notification), ignore
return;
}
if (priority && !inputGate.getPriorityEventAvailableFuture().isDone()) {
// Since notification is not atomic in respect to gate enqueuing, priority event
// may already be polled by
// task thread when netty enqueues the gate, so just ignore the notification.
return;
}
inputGatesWithData.add(inputGate, priority, alreadyEnqueued);
if (priority && inputGatesWithData.getNumPriorityElements() == 1) {
notification.notifyPriority();
}
if (inputGatesWithData.size() == 1) {
notification.notifyDataAvailable();
}
}
}
}
private Optional<IndexedInputGate> getInputGate(boolean blocking) throws InterruptedException {
assert Thread.holdsLock(inputGatesWithData);
while (inputGatesWithData.isEmpty()) {
if (blocking) {
inputGatesWithData.wait();
} else {
availabilityHelper.resetUnavailable();
return Optional.empty();
}
}
return Optional.of(inputGatesWithData.poll());
}
@Override
public void finishReadRecoveredState() throws IOException {
for (InputGate inputGate : inputGatesByGateIndex.values()) {
inputGate.finishReadRecoveredState();
}
}
}
|
askmohanty/metasfresh
|
backend/de.metas.handlingunits.base/src/main/java/de/metas/handlingunits/picking/PackToSpec.java
|
package de.metas.handlingunits.picking;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
import de.metas.common.util.CoalesceUtil;
import de.metas.handlingunits.HUPIItemProductId;
import de.metas.handlingunits.HuPackingInstructionsId;
import lombok.NonNull;
import lombok.Value;
import org.adempiere.exceptions.AdempiereException;
import javax.annotation.Nullable;
import java.util.Objects;
/**
* Specification for packing the picked products
*/
@Value
@JsonAutoDetect(fieldVisibility = Visibility.ANY, getterVisibility = Visibility.NONE, isGetterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE)
public class PackToSpec
{
public static final PackToSpec VIRTUAL = new PackToSpec(HuPackingInstructionsId.VIRTUAL, null);
@Nullable HuPackingInstructionsId genericPackingInstructionsId;
@Nullable HUPIItemProductId tuPackingInstructionsId;
public static PackToSpec ofTUPackingInstructionsId(@NonNull final HUPIItemProductId tuPackingInstructionsId)
{
if (tuPackingInstructionsId.isVirtualHU())
{
return VIRTUAL;
}
else
{
return new PackToSpec(null, tuPackingInstructionsId);
}
}
public static PackToSpec ofGenericPackingInstructionsId(@NonNull final HuPackingInstructionsId genericPackingInstructionsId)
{
if (genericPackingInstructionsId.isVirtual())
{
return VIRTUAL;
}
else
{
return new PackToSpec(genericPackingInstructionsId, null);
}
}
private PackToSpec(
@Nullable final HuPackingInstructionsId genericPackingInstructionsId,
@Nullable final HUPIItemProductId tuPackingInstructionsId)
{
if (CoalesceUtil.countNotNulls(genericPackingInstructionsId, tuPackingInstructionsId) != 1)
{
throw new AdempiereException("Only one of packingInstructionsId or huPIItemProductId shall be specified");
}
this.genericPackingInstructionsId = genericPackingInstructionsId;
this.tuPackingInstructionsId = tuPackingInstructionsId;
}
public boolean isVirtual()
{
if (tuPackingInstructionsId != null)
{
return tuPackingInstructionsId.isVirtualHU();
}
else
{
return genericPackingInstructionsId != null && genericPackingInstructionsId.isVirtual();
}
}
public interface CaseMapper<T>
{
T packToVirtualHU();
T packToTU(HUPIItemProductId tuPackingInstructionsId);
T packToGenericHU(HuPackingInstructionsId genericPackingInstructionsId);
}
public <T> T map(@NonNull final CaseMapper<T> mapper)
{
if (isVirtual())
{
return mapper.packToVirtualHU();
}
else if (tuPackingInstructionsId != null)
{
return mapper.packToTU(tuPackingInstructionsId);
}
else
{
return mapper.packToGenericHU(Objects.requireNonNull(genericPackingInstructionsId));
}
}
}
|
JJPowelly/u8glib
|
fntsrc/u8g_font_symb12r.c
|
<reponame>JJPowelly/u8glib<gh_stars>1000+
/*
Fontname: -Adobe-Symbol-Medium-R-Normal--17-120-100-100-P-95-Adobe-FontSpecific
Copyright: Copyright (c) 1984, 1987 Adobe Systems Incorporated. All Rights Reserved. Copyright (c) 1988, 1991 Digital Equipment Corporation. All Rights Reserved.
Capital A Height: 11, '1' Height: 12
Calculated Max Values w=13 h=17 x= 7 y=12 dx=14 dy= 0 ascent=13 len=26
Font Bounding box w=20 h=17 x=-3 y=-4
Calculated Min Values x=-1 y=-4 dx= 0 dy= 0
Pure Font ascent =11 descent=-4
X Font ascent =12 descent=-4
Max Font ascent =13 descent=-4
*/
#include "u8g.h"
const u8g_fntpgm_uint8_t u8g_font_symb12r[1985] U8G_FONT_SECTION("u8g_font_symb12r") = {
0,20,17,253,252,11,2,70,5,85,32,127,252,13,252,12,
252,0,0,0,4,0,1,3,11,11,5,1,0,64,224,224,
224,64,64,64,0,64,224,64,11,12,24,11,0,0,128,32,
128,32,64,64,64,64,63,128,32,128,17,0,17,0,10,0,
10,0,4,0,4,0,8,11,11,8,0,0,18,18,18,127,
36,36,36,254,72,72,72,7,12,12,9,0,0,254,2,2,
2,2,126,2,2,2,2,2,254,11,12,24,13,1,255,48,
64,111,128,201,0,201,0,154,0,148,192,101,160,11,32,11,
32,18,96,34,64,33,128,12,11,22,13,0,0,14,0,25,
0,17,0,26,0,12,240,56,64,76,128,198,128,131,0,197,
144,120,224,5,8,8,7,1,0,224,16,24,120,24,24,16,
224,4,14,14,5,0,254,16,32,64,64,128,128,128,128,128,
128,64,64,32,16,4,14,14,5,0,254,128,64,32,32,16,
16,16,16,16,16,32,32,64,128,5,5,5,8,1,3,32,
168,112,168,32,9,9,18,9,0,0,8,0,8,0,8,0,
8,0,255,128,8,0,8,0,8,0,8,0,3,5,5,4,
1,254,64,224,96,64,128,9,1,2,9,0,4,255,128,3,
3,3,4,1,0,64,224,64,5,11,11,5,255,0,8,8,
16,16,32,32,32,64,64,128,128,7,12,12,8,0,0,56,
108,68,198,130,130,130,130,198,68,108,56,5,12,12,8,1,
0,32,96,160,32,32,32,32,32,32,32,32,248,7,12,12,
8,0,0,56,76,134,2,2,4,4,8,16,34,126,252,6,
12,12,8,1,0,56,76,132,4,8,56,12,4,4,4,200,
112,7,12,12,8,0,0,4,4,12,20,20,36,68,68,254,
4,4,4,7,12,12,8,0,0,62,60,64,64,240,248,12,
4,4,4,200,240,6,12,12,8,1,0,12,48,96,64,248,
204,132,132,132,132,76,56,6,12,12,8,1,0,252,252,136,
8,8,16,16,16,16,32,32,32,6,12,12,8,1,0,48,
72,132,196,104,48,88,140,132,132,72,48,6,12,12,8,1,
0,112,200,132,132,132,132,204,124,8,24,48,192,3,8,8,
4,1,0,64,224,64,0,0,64,224,64,3,10,10,4,1,
254,64,224,64,0,0,64,224,96,64,128,8,9,9,9,0,
0,1,6,24,96,128,96,24,6,1,9,4,8,9,0,2,
255,128,0,0,0,0,255,128,8,9,9,9,0,0,128,96,
24,6,1,6,24,96,128,6,11,11,7,0,0,120,156,140,
12,24,16,32,0,32,112,32,8,8,8,9,0,0,113,142,
0,0,255,0,0,255,11,11,22,12,0,0,4,0,4,0,
14,0,14,0,19,0,19,0,33,128,63,128,65,192,64,192,
225,224,9,11,22,11,1,0,254,0,99,0,97,128,97,128,
99,0,126,0,99,0,97,128,97,128,99,0,254,0,10,11,
22,12,0,0,241,192,96,128,49,0,26,0,26,0,12,0,
22,0,19,0,35,0,65,128,227,192,10,11,22,10,0,0,
4,0,4,0,14,0,14,0,19,0,19,0,35,0,33,128,
65,128,64,192,255,192,8,11,11,10,1,0,255,97,96,96,
98,126,98,96,96,97,255,12,11,22,12,0,0,15,0,6,
0,63,192,102,96,198,48,198,48,198,48,102,96,63,192,6,
0,15,0,9,11,22,10,1,0,255,128,97,128,96,0,96,
0,96,0,96,0,96,0,96,0,96,0,96,0,240,0,11,
11,22,12,0,0,241,224,96,192,96,192,96,192,96,192,127,
192,96,192,96,192,96,192,96,192,241,224,4,11,11,6,1,
0,240,96,96,96,96,96,96,96,96,96,240,9,12,24,10,
0,0,12,0,18,0,17,0,9,0,69,0,163,0,33,128,
33,0,33,0,33,0,34,0,28,0,10,11,22,12,1,0,
243,192,97,0,98,0,100,0,104,0,120,0,108,0,102,0,
99,0,97,128,243,192,11,11,22,11,0,0,4,0,4,0,
14,0,14,0,19,0,19,0,33,128,33,128,64,192,64,192,
225,224,13,11,22,14,1,0,224,56,96,112,112,112,112,176,
88,176,89,48,77,48,78,48,70,48,68,48,224,120,10,11,
22,11,1,0,225,192,112,128,112,128,88,128,92,128,78,128,
70,128,67,128,67,128,65,128,224,128,11,11,22,12,0,0,
31,0,113,192,96,192,192,96,192,96,192,96,192,96,192,96,
96,192,113,192,31,0,11,11,22,12,1,0,255,224,96,192,
96,192,96,192,96,192,96,192,96,192,96,192,96,192,96,192,
241,224,11,11,22,12,0,0,31,0,113,192,96,192,192,96,
209,96,223,96,209,96,192,96,96,192,113,192,31,0,8,11,
11,9,1,0,252,102,99,99,102,124,96,96,96,96,240,9,
11,22,10,0,0,255,128,96,128,48,0,24,0,12,0,12,
0,8,0,16,128,32,128,127,128,255,128,10,11,22,10,0,
0,255,192,140,64,140,64,12,0,12,0,12,0,12,0,12,
0,12,0,12,0,30,0,10,11,22,11,1,0,241,192,96,
128,49,0,49,0,26,0,12,0,12,0,12,0,12,0,12,
0,30,0,7,12,12,8,0,252,60,76,128,128,128,128,124,
62,2,2,60,56,12,12,24,12,0,0,31,128,112,224,96,
96,192,48,192,48,192,48,192,48,96,96,48,192,137,16,249,
240,249,240,9,11,22,11,0,0,255,128,255,128,128,128,0,
0,34,0,62,0,34,0,0,0,128,128,255,128,255,128,12,
11,22,13,0,0,207,48,102,96,102,96,102,96,102,96,63,
192,6,0,6,0,6,0,6,0,15,0,8,11,11,10,1,
0,255,131,134,12,12,24,48,48,97,193,255,3,14,14,6,
1,254,224,128,128,128,128,128,128,128,128,128,128,128,128,224,
9,8,16,14,2,0,8,0,28,0,8,0,0,0,0,0,
65,0,227,128,65,0,3,14,14,5,0,254,224,32,32,32,
32,32,32,32,32,32,32,32,32,224,9,11,22,11,1,0,
8,0,8,0,8,0,8,0,8,0,8,0,8,0,8,0,
8,0,8,0,255,128,8,1,1,8,0,253,255,10,1,2,
8,7,12,255,192,10,9,18,11,0,0,57,128,101,128,195,
0,195,0,195,0,194,0,198,64,101,64,56,128,8,17,17,
9,0,252,60,70,66,66,70,92,70,67,67,65,65,99,94,
64,64,64,192,8,12,12,9,0,253,99,162,150,20,28,24,
24,56,40,105,69,198,7,12,12,8,0,0,120,140,64,48,
24,44,70,194,130,194,68,56,7,9,9,7,0,0,56,68,
192,192,120,192,192,66,60,7,14,14,9,1,253,16,16,56,
84,214,146,146,146,214,84,56,16,16,16,8,13,13,7,255,
252,97,161,146,18,20,20,8,8,16,16,48,48,48,9,12,
24,10,0,253,110,0,177,0,33,0,33,0,33,0,33,0,
33,0,33,0,33,0,1,0,1,0,1,128,6,9,9,5,
255,0,32,96,160,32,32,32,32,52,24,9,12,24,10,0,
253,39,0,73,128,201,128,136,128,136,128,136,128,201,128,73,
0,62,0,8,0,8,0,8,0,8,9,9,9,0,0,70,
206,80,80,120,76,76,70,79,9,13,26,9,0,0,96,0,
208,0,144,0,16,0,8,0,24,0,24,0,56,0,40,0,
36,0,100,128,68,128,195,0,8,13,13,9,1,252,132,132,
132,132,132,132,132,205,182,128,128,128,128,9,9,18,8,255,
0,225,128,33,128,49,0,51,0,18,0,26,0,12,0,12,
0,8,0,7,9,9,9,1,0,56,68,198,130,130,130,198,
68,56,8,9,9,9,0,0,127,255,164,36,36,36,37,103,
102,7,12,12,9,1,0,56,108,68,198,130,254,130,130,198,
68,108,56,7,13,13,9,1,252,56,76,134,134,130,130,198,
196,184,128,128,128,128,9,9,18,10,1,0,31,128,116,0,
194,0,195,0,129,0,193,0,65,0,99,0,30,0,7,9,
9,7,0,0,60,124,144,16,16,16,18,30,12,8,9,9,
9,1,0,68,226,161,33,33,33,33,50,28,10,10,20,11,
0,0,127,192,155,0,32,128,100,192,68,64,68,64,68,64,
68,64,100,192,59,128,9,9,18,11,1,0,54,0,65,0,
201,128,136,128,136,128,136,128,136,128,201,128,119,0,7,17,
17,8,0,252,64,88,48,64,92,60,64,128,128,128,128,124,
62,2,2,60,56,11,13,26,11,0,252,196,96,100,192,36,
128,36,128,36,128,36,128,36,128,53,128,31,0,4,0,4,
0,4,0,4,0,7,17,17,8,1,252,32,76,60,32,64,
64,128,128,128,128,128,124,62,2,2,60,56,5,14,14,8,
1,254,24,32,32,32,32,32,192,32,32,32,32,32,32,24,
1,14,14,3,1,253,128,128,128,128,128,128,128,128,128,128,
128,128,128,128,5,14,14,8,1,254,192,32,32,32,32,32,
24,32,32,32,32,32,32,192,8,2,2,9,0,3,113,142,
255};
|
alessandro-antonelli/ALL-2014
|
08-2 - Qsort su stringhe/QsortStringhe.c
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int Compare(const void* a, const void* b)
{
char* s1 = *((char**) a);
char* s2 = *((char**) b);
return (-1) * (strcmp(s1, s2));
}
int main()
{
int len;
scanf("%d", &len);
char** a = malloc(len * sizeof(char*));
int i;
for(i=0; i<len; i++)
{
a[i] = malloc(101 * sizeof(char));
scanf("%s", a[i]);
}
qsort(a, len, sizeof(char*), Compare);
for(i=0; i<len; i++)
{
printf("%s\n", a[i]);
free(a[i]);
}
free(a);
return 0;
}
|
sskbskdrin/AudioVideo
|
app/src/main/java/cn/sskbskdrin/record/camera/CameraActivity.java
|
<reponame>sskbskdrin/AudioVideo
package cn.sskbskdrin.record.camera;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.SurfaceTexture;
import android.os.Bundle;
import android.util.Log;
import android.view.SurfaceView;
import android.view.TextureView;
import android.view.View;
import android.view.Window;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.List;
import cn.sskbskdrin.base.BaseActivity;
import cn.sskbskdrin.lib.face.FaceDetector;
import cn.sskbskdrin.lib.face.FaceLandmarker;
import cn.sskbskdrin.lib.tflite.Recognition;
import cn.sskbskdrin.lib.tflite.TFLiteDetector;
import cn.sskbskdrin.lib.yuv.YUVCache;
import cn.sskbskdrin.lib.yuv.YUVLib;
import cn.sskbskdrin.record.R;
public class CameraActivity extends BaseActivity {
private static final String TAG = "MainActivity";
private CameraManager cameraManager;
private SurfaceView surfaceView;
private TextureView textureView;
private DrawSurface drawView;
private boolean v2;
private boolean front;
private boolean texture;
private boolean face = false;
private boolean mark = true;
private boolean tf = true;
YUVCache factory = new YUVCache();
FaceDetector detector;
FaceLandmarker landmarker;
int[] faceRect;
double[] points;
TFLiteDetector tfLiteDetector;
int[] recognitionRect;
Bitmap bitmap;
CameraManager.CameraFrameListener listener = new CameraManager.CameraFrameListener() {
@Override
public void onCameraFrame(byte[] bytes, byte[] uBytes, byte[] vBytes, int format, int width, int height,
boolean v2) {
Log.d(TAG, String.format("frame: bytes len=%d %dx%d format=%d", bytes.length, width, height, format));
int rotate = (cameraManager != null ? cameraManager.getOrientation() : 0) + (front ? 180 : 0);
int size = Math.min(width, height);
int[] clip = new int[]{0, 0, size, size};
if (v2) {
factory.transformRGBA(bytes, uBytes, vBytes, clip, width, height, rotate, front, true);
} else {
factory.transformRGBA(bytes, clip, width, height, format, rotate, front, true);
}
size = 300;
factory.scaleRGBA(size, size, 0);
drawView.setSrcFrame(size, size);
drawView.clean();
if (bitmap == null) {
bitmap = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
}
bitmap.copyPixelsFromBuffer(ByteBuffer.wrap(factory.getRGBA()));
// drawView.drawBitmap(bitmap);
factory.toggleAlpha(true);
if (face) {
if (detector == null) {
detector = new FaceDetector(CameraActivity.this);
faceRect = new int[40];
landmarker = new FaceLandmarker(CameraActivity.this);
points = new double[100];
}
Arrays.fill(points, -1);
int face = detector.detect(factory.getRGBA(), size, size, faceRect, 10);
drawView.drawRect(faceRect, 0xffe00000);
if (mark) {
if (face > 0) {
landmarker.mark(factory.getRGBA(), size, size, points, faceRect, face);
}
drawView.drawPoints(points, Color.GREEN);
}
}
if (tf) {
if (tfLiteDetector == null) {
try {
// tfLiteDetector = TFLiteDetector.create(getAssets(), "mnist.tflite",
// "label.txt");
tfLiteDetector = TFLiteDetector.create(getAssets(), "detect.tflite", "label.txt");
} catch (IOException e) {
e.printStackTrace();
}
}
if (recognitionRect == null) {
recognitionRect = new int[40];
}
Arrays.fill(recognitionRect, 0);
List<Recognition> list = tfLiteDetector.recognize(factory.getRGBA());
for (int i = 0; i < list.size(); i++) {
Recognition res = list.get(i);
res.scaleLocation(recognitionRect, i * 4, size);
drawView.drawText(res.title, recognitionRect[i * 4] + 2, recognitionRect[i * 4 + 1] + 2);
}
drawView.drawRect(recognitionRect, Color.CYAN);
for (Recognition res : list) {
Log.d(TAG, res.toString());
}
}
drawView.end();
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_camera);
YUVLib.init();
surfaceView = findViewById(R.id.camera_surface);
drawView = findViewById(R.id.draw_surface);
textureView = findViewById(R.id.camera_texture);
textureView.setSurfaceTextureListener(new TextureView.SurfaceTextureListener() {
@Override
public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
Log.i(TAG, "onSurfaceTextureAvailable: ");
// if (cameraManager == null) {
// cameraManager = new CameraManager();
// cameraManager.init(CameraActivity.this, surface, width, height, v2);
// cameraManager.setEnabled(true);
// }
}
@Override
public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {
Log.i(TAG, "onSurfaceTextureSizeChanged: ");
}
@Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
Log.i(TAG, "onSurfaceTextureDestroyed: ");
if (cameraManager != null) {
cameraManager.release();
}
cameraManager = null;
return false;
}
@Override
public void onSurfaceTextureUpdated(SurfaceTexture surface) {
Log.i(TAG, "onSurfaceTextureUpdated: ");
}
});
CompoundButton.OnCheckedChangeListener changeListener = new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (buttonView.getId() == R.id.camera_version) {
v2 = isChecked;
} else if (buttonView.getId() == R.id.camera_id) {
front = isChecked;
} else if (buttonView.getId() == R.id.camera_view_id) {
texture = isChecked;
} else if (buttonView.getId() == R.id.camera_draw) {
drawView.setVisibility(isChecked ? View.VISIBLE : View.GONE);
drawView.clean();
return;
}
if (cameraManager != null) {
cameraManager.release();
}
reset();
change();
}
};
((CheckBox) findViewById(R.id.camera_version)).setOnCheckedChangeListener(changeListener);
((CheckBox) findViewById(R.id.camera_id)).setOnCheckedChangeListener(changeListener);
((CheckBox) findViewById(R.id.camera_view_id)).setOnCheckedChangeListener(changeListener);
((CheckBox) findViewById(R.id.camera_draw)).setOnCheckedChangeListener(changeListener);
}
private void reset() {
surfaceView.getLayoutParams().width = -1;
surfaceView.getLayoutParams().height = 1440;
surfaceView.requestLayout();
textureView.getLayoutParams().width = -1;
textureView.getLayoutParams().height = -1;
textureView.requestLayout();
drawView.postDelayed(new Runnable() {
@Override
public void run() {
change();
}
}, 200);
}
private void change() {
if (cameraManager != null) {
cameraManager.release();
}
cameraManager = new CameraManager();
// cameraManager.init(this, view, v2);
if (texture) {
textureView.setVisibility(View.VISIBLE);
cameraManager.init(this, textureView, v2);
surfaceView.setVisibility(View.INVISIBLE);
} else {
surfaceView.setVisibility(View.VISIBLE);
cameraManager.init(this, surfaceView, v2);
textureView.setVisibility(View.INVISIBLE);
}
cameraManager.setMaxFrameSize(640, 480);
cameraManager.setCameraId(front ? CameraManager.CameraId.FRONT : CameraManager.CameraId.BACK);
cameraManager.setCameraFrameListener(listener);
cameraManager.setEnabled(true);
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
// texture = true;
// v2 = true;
reset();
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
if (cameraManager != null) {
cameraManager.release();
}
cameraManager = null;
}
}
|
Oriolac/cig-lib
|
src/test/java/cat/udl/cig/utils/discretelogarithm/LogarithmAlgorithmTest.java
|
package cat.udl.cig.utils.discretelogarithm;
import cat.udl.cig.structures.GroupElement;
import cat.udl.cig.structures.PrimeField;
import cat.udl.cig.structures.PrimeFieldElement;
import cat.udl.cig.structures.builder.PrimeFieldElementBuilder;
import cat.udl.cig.structures.ecc.EllipticCurve;
import cat.udl.cig.structures.ecc.EllipticCurvePoint;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
abstract class LogarithmAlgorithmTest {
ArrayList<LogarithmAlgorithm> logarithmAlgorithm;
ArrayList<GroupElement> generators;
ArrayList<GroupElement> betas;
ArrayList<BigInteger> expectedPowers;
@BeforeEach
void setUp() {
logarithmAlgorithm = returnAlgorithm();
generators = returnGenerator();
assertEquals(generators, logarithmAlgorithm.stream().map(LogarithmAlgorithm::getAlpha).collect(Collectors.toCollection(ArrayList::new)));
betas = returnBeta();
expectedPowers = returnExpectedPower();
}
protected abstract ArrayList<LogarithmAlgorithm> returnAlgorithm();
static protected ArrayList<GroupElement> returnGenerator() {
return new ArrayList<>(List.of(
new PrimeFieldGenerator().returnGenerator(),
new EllipticCurvePrimeFieldGenerator().returnGenerator()
));
}
static protected ArrayList<GroupElement> returnBeta() {
return new ArrayList<>(List.of(
new PrimeFieldGenerator().returnBeta(),
new EllipticCurvePrimeFieldGenerator().returnBeta()
));
}
static protected ArrayList<BigInteger> returnExpectedPower() {
return new ArrayList<>(List.of(
new PrimeFieldGenerator().returnExpectedPower(),
new EllipticCurvePrimeFieldGenerator().returnExpectedPower()
));
}
int getNumTries() {
return 100;
}
@Test
void testTrySomeManyPowers() {
for (int j = 0; j < expectedPowers.size(); j++) {
GroupElement generator = generators.get(j);
LogarithmAlgorithm logarithm = logarithmAlgorithm.get(j);
for (int i = 1; i < getNumTries(); i++) {
GroupElement beta = generator.pow(BigInteger.valueOf(i));
Optional<BigInteger> actual = logarithm.algorithm(beta);
assertTrue(actual.isPresent(), "It has failed at " + i);
assertEquals(BigInteger.valueOf(i), actual.get(), "It has failed at " + logarithm.getAlpha() + " ** " + i);
}
}
}
@Test
void testAlgorithm() {
for (int j = 0; j < expectedPowers.size(); j++) {
GroupElement beta = betas.get(j);
LogarithmAlgorithm logarithm = logarithmAlgorithm.get(j);
Optional<BigInteger> power = logarithm.algorithm(beta);
assertTrue(power.isPresent(), "Power not found");
assertEquals(expectedPowers.get(j), power.get(), "Failed at " + beta);
}
}
static interface FieldGenerator {
GroupElement returnGenerator();
GroupElement returnBeta();
BigInteger returnExpectedPower();
}
static class PrimeFieldGenerator implements FieldGenerator {
static BigInteger P = BigInteger.valueOf(101);
static PrimeField primeField = new PrimeField(P);
@Override
public PrimeFieldElement returnGenerator() {
return primeField.buildElement().setValue(7).build().orElseThrow();
}
@Override
public PrimeFieldElement returnBeta() {
return primeField.buildElement().setValue(85).build().orElseThrow();
}
@Override
public BigInteger returnExpectedPower() {
return BigInteger.valueOf(6);
}
}
static class EllipticCurvePrimeFieldGenerator implements FieldGenerator {
static PrimeField primeField = new PrimeField(BigInteger.valueOf(2213));
static PrimeFieldElementBuilder builder = primeField.buildElement();
static EllipticCurve curve = new EllipticCurve(
primeField,
builder.setValue(1).build().orElseThrow(),
builder.setValue(49).build().orElseThrow(),
BigInteger.valueOf(1093 * 2)
);
public EllipticCurvePoint returnGenerator() {
return new EllipticCurvePoint(curve, builder.setValue(1583).build().orElseThrow(), builder.setValue(1734).build().orElseThrow());
}
public EllipticCurvePoint returnBeta() {
return new EllipticCurvePoint(curve, builder.setValue(165).build().orElseThrow(), builder.setValue(917).build().orElseThrow());
}
public BigInteger returnExpectedPower() {
return BigInteger.valueOf(30);
}
}
}
|
Phoosha/neo4j-ogm
|
neo4j-ogm-tests/neo4j-ogm-integration-tests/src/test/java/org/neo4j/ogm/metadata/PrimitiveFieldsTest.java
|
/*
* Copyright (c) 2002-2021 "Neo4j,"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of Neo4j.
*
* 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.neo4j.ogm.metadata;
import org.junit.Test;
/**
* @author vince
*/
public class PrimitiveFieldsTest extends TestMetaDataTypeResolution {
@Test
public void testPrimitiveShortArray() {
checkField("pss", "short[]", short.class);
}
@Test
public void testPrimitiveCharArray() {
checkField("pcc", "char[]", char.class);
}
@Test
public void testPrimitiveByteArray() {
checkField("pbb", "byte[]", byte.class);
}
@Test
public void testPrimitiveLongArray() {
checkField("pll", "long[]", long.class);
}
@Test
public void testPrimitiveDoubleArray() {
checkField("pdd", "double[]", double.class);
}
@Test
public void testPrimitiveFloatArray() {
checkField("pff", "float[]", float.class);
}
@Test
public void testPrimitiveBooleanArray() {
checkField("pzz", "boolean[]", boolean.class);
}
@Test
public void testPrimitiveIntegerArray() {
checkField("pii", "int[]", int.class);
}
@Test
public void testPrimitiveShort() {
checkField("ps", "short", short.class);
}
@Test
public void testPrimitiveChar() {
checkField("pc", "char", char.class);
}
@Test
public void testPrimitiveByte() {
checkField("pb", "byte", byte.class);
}
@Test
public void testPrimitiveLong() {
checkField("pl", "long", long.class);
}
@Test
public void testPrimitiveDouble() {
checkField("pd", "double", double.class);
}
@Test
public void testPrimitiveFloat() {
checkField("pf", "float", float.class);
}
@Test
public void testPrimitiveBoolean() {
checkField("pz", "boolean", boolean.class);
}
@Test
public void testPrimitiveInteger() {
checkField("pi", "int", int.class);
}
}
|
geekinasuit/MOE
|
client/src/test/java/com/google/devtools/moe/client/TaskTest.java
|
/*
* Copyright (c) 2011 Google, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.devtools.moe.client;
import static com.google.common.truth.Truth.assertThat;
import com.google.devtools.moe.client.Ui.Task;
import java.io.ByteArrayOutputStream;
import java.util.ArrayDeque;
import java.util.Deque;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@RunWith(JUnit4.class)
public class TaskTest {
@Test
public void testTaskOnStack() throws Exception {
Deque<Task> tasks = new ArrayDeque<>();
Ui ui = new Ui(new ByteArrayOutputStream(), new SystemFileSystem(), false, tasks);
try (Task firstTask = ui.newTask("first", "first")) {
assertThat(tasks).containsExactly(firstTask);
try (Task secondTask = ui.newTask("second", "second")) {
assertThat(tasks).containsExactly(firstTask, secondTask);
}
}
assertThat(tasks).isEmpty();
}
@Test
public void taskTiming_withDebug() throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Ui ui = new Ui(baos, new SystemFileSystem(), true);
try (Task t = ui.newTask("foo", "bar")) {}
assertThat(baos.toString()).containsMatch("\\[[0-9]*ms\\]");
}
@Test
public void taskTiming_WithoutDebug() throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Ui ui = new Ui(baos, new SystemFileSystem(), false);
try (Task t = ui.newTask("foo", "bar")) {}
assertThat(baos.toString()).doesNotContainMatch("\\[[0-9]*ms\\]");
}
@Test
public void taskTiming_TraceOnly() throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Ui ui = new Ui(baos, new SystemFileSystem(), false);
try (Task t = ui.newTask("foo", true, "bar")) {
t.result().append("foo");
}
assertThat(baos.toString()).doesNotContainMatch("foo");
}
@Test
public void taskTiming_TryWithResources() throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Ui ui = new Ui(baos, new SystemFileSystem(), false);
try (Task t = ui.newTask("foo", "bar")) {}
assertThat(baos.toString()).containsMatch("Done");
}
}
|
artudev/cities
|
app/src/test/java/com/assignment/cities/model/sort/Text.java
|
package com.assignment.cities.model.sort;
/**
* Created by <NAME> on 02.05.2018.
*/
public class Text implements Mappable {
private String mText;
public Text(String text) {
mText = text;
}
public String getText() {
return mText;
}
public void setText(String text) {
mText = text;
}
@Override
public String getKey() {
return mText;
}
@Override
public String getUniqueKey() {
return getKey();
}
}
|
cndabai/micro_ros
|
src/rcl_interfaces/msg/floating_point_range.h
|
<gh_stars>1-10
// generated from rosidl_generator_c/resource/idl.h.em
// with input from rcl_interfaces:msg/FloatingPointRange.idl
// generated code does not contain a copyright notice
#ifndef RCL_INTERFACES__MSG__FLOATING_POINT_RANGE_H_
#define RCL_INTERFACES__MSG__FLOATING_POINT_RANGE_H_
#include "rcl_interfaces/msg/detail/floating_point_range__struct.h"
#include "rcl_interfaces/msg/detail/floating_point_range__functions.h"
#include "rcl_interfaces/msg/detail/floating_point_range__type_support.h"
#endif // RCL_INTERFACES__MSG__FLOATING_POINT_RANGE_H_
|
peterschrammel/jayhorn
|
soottocfg/src/main/java/soottocfg/ast/Absyn/CommaExp.java
|
package soottocfg.ast.Absyn; // Java Package generated by the BNF Converter.
public class CommaExp extends CommaExpList {
public final Exp exp_;
public CommaExp(Exp p1) { exp_ = p1; }
public <R,A> R accept(soottocfg.ast.Absyn.CommaExpList.Visitor<R,A> v, A arg) { return v.visit(this, arg); }
public boolean equals(Object o) {
if (this == o) return true;
if (o instanceof soottocfg.ast.Absyn.CommaExp) {
soottocfg.ast.Absyn.CommaExp x = (soottocfg.ast.Absyn.CommaExp)o;
return this.exp_.equals(x.exp_);
}
return false;
}
public int hashCode() {
return this.exp_.hashCode();
}
}
|
floatplane/homebrew-core
|
Formula/xaric.rb
|
class Xaric < Formula
desc "IRC client"
homepage "https://xaric.org/"
url "https://xaric.org/software/xaric/releases/xaric-0.13.7.tar.gz"
sha256 "fd8cd677e2403e44ff525eac7c239cd8d64b7448aaf56a1272d1b0c53df1140c"
license "GPL-2.0-or-later"
livecheck do
url "https://xaric.org/software/xaric/releases/"
regex(/href=.*?xaric[._-]v?(\d+(?:\.\d+)+)\.t/i)
end
bottle do
rebuild 3
sha256 big_sur: "d832ba1dd3908ef0d452fd2cf7af23e871d2bc93ce45bc3bee23417096724b6d"
sha256 catalina: "b1247cee2be64fbf7fe5c1c76e7dd009b2a05538fa6e3fea047a6887ef7cffe2"
sha256 mojave: "8157b44f1d6a36035ac047e976c64e56b1c98d15f2e883f36bd033b1e0335ec4"
end
depends_on "openssl@1.1"
uses_from_macos "ncurses"
def install
# Workaround https://github.com/laeos/xaric/pull/10
ENV.append "CFLAGS", "-Wno-implicit-function-declaration"
system "./configure", "--disable-dependency-tracking",
"--prefix=#{prefix}",
"--with-openssl=#{Formula["openssl@1.1"].opt_prefix}"
system "make", "install"
end
test do
assert_match(/Xaric #{version}/, shell_output("script -q /dev/null xaric -v"))
end
end
|
OpenIntelligence/PolicyAlpha
|
lib/custom_exception/user_banned.rb
|
<reponame>OpenIntelligence/PolicyAlpha
module CustomException
class UserBanned < StandardError
end
end
|
keybrl/xdu-coursework
|
projects/g3h1-java/Java2_CheckingAccount/src/BankSystem.java
|
import java.math.BigDecimal;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.ArrayList;
import java.util.Queue;
import java.util.LinkedList;
import java.util.Date;
/**
* 一个银行系统类
*
* @author 罗阳豪 16130120191
* @author <EMAIL>
*/
public class BankSystem {
/**
* 程序入口
* @param args
*/
public static void main(String[] args) {
// 初始化银行系统
BankSystem sys = new BankSystem();
// 添加账户
sys.create_account("罗阳豪", false, 0, "159284637asd", new BigDecimal("23.33"));
sys.create_account("罗阳豪1", true, 10000, "137asd", new BigDecimal("23.33"));
sys.create_account("罗阳豪2", false, 0, "159287asd", new BigDecimal("0.00"));
sys.create_account("罗阳豪3", false, 100, "159284637asd", new BigDecimal("0.00"));
sys.create_account("罗阳豪4", true, 100, "1284637asd", new BigDecimal("23.33"));
sys.create_account("罗阳豪5", false, 0, "1592637d", new BigDecimal("23.33"));
// 非法输入
sys.create_account("罗阳豪6", false, 0, "1592637d", new BigDecimal("-23.33"));
// 显示账户
sys.show_accounts();
// 存款
sys.deposit(sys.get_account_by_id("CREDIT-000000001"), new BigDecimal("100.23"), "137asd");
sys.deposit(sys.get_account_by_id("CASH-00000000004"), new BigDecimal("23300.56"), "1592637d");
// 非法输入
sys.deposit(sys.get_account_by_id("CASH-00000000003"), new BigDecimal("-233.56"), "159284637asd");
sys.show_accounts();
// 取钱
sys.withdraw(sys.get_account_by_id("CREDIT-000000001"), new BigDecimal("2000.00"), "137asd");
sys.withdraw(sys.get_account_by_id("CREDIT-000000002"), new BigDecimal("99.00"), "128463<PASSWORD>");
sys.withdraw(sys.get_account_by_id("CASH-00000000004"), new BigDecimal("12.23"), "1592637d");
// 非法输入
sys.withdraw(sys.get_account_by_id("CASH-00000000004"), new BigDecimal("1200000.23"), "1592637d");
sys.show_accounts();
}
// 内部类定义
/**
* 银行账号类,是CashAccount和CreditAccount的父类
* 实现了银行账号的注册、更名、设改验密码、存取钱等操作
* 依赖Transactions_List类记录交易流水
*/
private class BankAccount {
protected String account_id; // 卡号
protected String name; // 开户人姓名
protected BigDecimal balance; // 使用精度为2的定点数存储账户余额,避免浮点运算误差。
public Transactions_List recorder; // 交易流水记录器
private String password;
protected BankAccount(String account_id, BigDecimal balance) {
this.account_id = account_id;
this.name = "Undefined";
this.balance = balance;
this.recorder = new Transactions_List();
this.password = "123456";
if (this.balance.compareTo(BigDecimal.ZERO) < 0) {
this.balance = new BigDecimal("0.00");
throw new IllegalArgumentException("初始余额不能为负数,已将余额置为0.00");
}
else if (this.balance.scale() != 2) {
this.balance = new BigDecimal("0.00");
throw new IllegalArgumentException("初始余额精度不符合要求,应精确到小数点后两位,已将余额置为0.00");
}
}
protected BankAccount(String account_id, String name, BigDecimal balance) {
this.account_id = account_id;
this.name = name;
this.balance = balance;
this.recorder = new Transactions_List();
this.password = "<PASSWORD>";
if (this.balance.compareTo(BigDecimal.ZERO) < 0) {
this.balance = new BigDecimal("0.00");
throw new IllegalArgumentException("初始余额不能为负数,已将余额置为0.00");
}
else if (this.balance.scale() != 2) {
this.balance = new BigDecimal("0.00");
throw new IllegalArgumentException("初始余额精度不符合要求,应精确到小数点后两位,已将余额置为0.00");
}
}
public String get_id() {
return this.account_id;
}
public String get_name() {
return this.name;
}
public String set_name(String new_name) {
this.name = new_name;
return this.name;
}
public BigDecimal get_balance() {
return this.balance;
}
public boolean check_password(String password) {
return this.password.equals(password);
}
public boolean reset_password(String old_passwd, String new_passwd) {
if (check_password(old_passwd)) {
this.password = <PASSWORD>;
return true;
}
return false;
}
// 改变账户余额,要求参数为精度为2的定点数。
public BigDecimal deposit(BigDecimal amount) {
if (amount.scale() != 2) {
throw new IllegalArgumentException("金额精度不符合要求,应精确到小数点后两位");
}
else if (amount.compareTo(BigDecimal.ZERO) <= 0) {
throw new IllegalArgumentException("不能存入负数或0.00元");
}
else {
return this.change_balance(amount);
}
}
public BigDecimal withdraw(BigDecimal amount) {
if (amount.scale() != 2) {
throw new IllegalArgumentException("金额精度不符合要求,应精确到小数点后两位");
}
else if (amount.compareTo(BigDecimal.ZERO) <= 0) {
throw new IllegalArgumentException("不能取出负数或0.00元");
}
else {
return this.change_balance(amount.negate());
}
}
protected BigDecimal change_balance(BigDecimal difference) {
if (difference.compareTo(this.balance.negate()) >= 0) {
this.balance = this.balance.add(difference);
}
else {
throw new IllegalArgumentException("账户余额不能为负,操作不能进行");
}
return this.balance;
}
}
/**
* 现金账户类,继承BankAccount类
* 并且,对比BankAccount,除了换了个名字什么也没做,仅为了形式上统一而设立
*/
private class CashAccount extends BankAccount {
public CashAccount(String account_id, BigDecimal balance) {
super(account_id, balance);
}
public CashAccount(String account_id, String name, BigDecimal balance) {
super(account_id, name, balance);
}
}
/**
* 信用卡账户类,继承BankAccount类
* 对比BankAccount类,增加overdraft属性(可透支额度),并修改了change_balance方法的部分逻辑
*/
private class CreditAccount extends BankAccount {
private int overdraft;
public CreditAccount(String account_id, BigDecimal balance, int overdraft) {
super(account_id, balance);
if (overdraft < 0) {
overdraft = 0;
}
this.overdraft = overdraft;
}
public CreditAccount(String account_id, String name, BigDecimal balance, int overdraft) {
super(account_id, name, balance);
this.overdraft = overdraft;
if (this.overdraft < 0) {
this.overdraft = 0;
throw new IllegalArgumentException("可透支额不能是负数,已置为0元");
}
}
public int get_overdraft() {
return this.overdraft;
}
protected BigDecimal change_balance(BigDecimal difference) {
if (difference.compareTo(this.balance.add(new BigDecimal(this.overdraft)).negate()) >= 0) {
this.balance = this.balance.add(difference);
}
else {
throw new IllegalArgumentException("账户透支金额不能大于可透支额度,操作不能进行");
}
return this.balance;
}
}
/**
* 对BankAccount的账户创建、存取款操作以及异常处理做一个简单的封装
*/
private class CheckingAccount {
private BankAccount target;
CheckingAccount() {
this.target = null;
}
CheckingAccount(BankAccount account) {
this.target = account;
}
public boolean change_target(BankAccount new_account) {
this.target = new_account;
return true;
}
public BankAccount get_account() {
return target;
}
// 创建CashAccount
public BankAccount create_account(String account_id, BigDecimal balance) {
try {
this.target = new CashAccount(account_id, balance);
}
catch (IllegalArgumentException err) {
err.printStackTrace(System.out);
throw new IllegalArgumentException("创建账户失败");
}
return this.target;
}
public BankAccount create_account(String account_id, String name, BigDecimal balance) {
try {
this.target = new CashAccount(account_id, name, balance);
}
catch (IllegalArgumentException err) {
err.printStackTrace(System.out);
throw new IllegalArgumentException("创建账户失败");
}
return this.target;
}
// 创建CreditAccount
public BankAccount create_account(String account_id, BigDecimal balance, int overdraft) {
try {
this.target = new CreditAccount(account_id, balance, overdraft);
}
catch (IllegalArgumentException err) {
err.printStackTrace(System.out);
throw new IllegalArgumentException("创建账户失败");
}
return this.target;
}
public BankAccount create_account(String account_id, String name, BigDecimal balance, int overdraft) {
try {
this.target = new CreditAccount(account_id, name, balance, overdraft);
}
catch (IllegalArgumentException err) {
err.printStackTrace(System.out);
throw new IllegalArgumentException("创建账户失败");
}
return this.target;
}
// 存钱取钱
public BigDecimal deposit(BigDecimal amount) {
if (this.target == null) {
throw new IllegalStateException("没有绑定账户,不能进行操作");
}
try {
return target.deposit(amount);
}
catch (IllegalArgumentException err) {
err.printStackTrace(System.out);
}
return target.get_balance();
}
public BigDecimal withdraw(BigDecimal amount) {
if (this.target == null) {
throw new IllegalStateException("没有绑定账户,不能进行操作");
}
try {
return target.withdraw(amount);
}
catch (IllegalArgumentException err) {
err.printStackTrace(System.out);
}
return target.get_balance();
}
}
/**
* 交易流水队列类,保存近期一定数量的交易流水
* 依赖Transaction类
*/
private class Transactions_List {
private Queue<Transaction> transactions_list = new LinkedList<Transaction>();
private String date_format = "yyyy-MM-dd HH:mm:ss";
private int max_size = 6;
public Transactions_List() {}
public Transactions_List(Integer max_size, String date_format) {
if (max_size != null) {
this.max_size = max_size;
}
if (date_format != null) {
this.date_format = date_format;
}
}
public Transaction record(Transaction transaction) {
this.transactions_list.offer(transaction);
if (transactions_list.size() > max_size) {
return transactions_list.poll();
}
return null;
}
public void print() {
int table_height = this.transactions_list.size() + 1;
int table_width = 5;
String[][] table = new String[table_height][table_width];
table[0][0] = "交易日期时间";
table[0][1] = "摘要";
table[0][2] = "支出";
table[0][3] = "收入";
table[0][4] = "余额";
int row_num = 1;
for (Transaction transaction: transactions_list) {
table[row_num][0] = transaction.get_date(date_format);
table[row_num][1] = transaction.memo;
table[row_num][2] = transaction.withdrawal.toString();
table[row_num][3] = transaction.deposit.toString();
table[row_num++][4] = transaction.balance.toString();
}
print_table(table);
}
}
/**
* 交易流水类,记录单条交易
* 包括 日期时间、摘要、支出、收入、结余 五个字段
*/
private class Transaction {
public Date date; // 日期时间
public String memo; // 摘要
public BigDecimal withdrawal; // 支出
public BigDecimal deposit; // 收入
public BigDecimal balance; // 结余
public Transaction(Date date, String memo, BigDecimal withdrawal, BigDecimal deposit, BigDecimal balance) {
this.date = date;
this.memo = memo;
if (withdrawal.scale() == 2 && deposit.scale() == 2 && balance.scale() == 2) {
this.withdrawal = withdrawal;
this.deposit = deposit;
this.balance = balance;
}
else {
throw new IllegalArgumentException();
}
}
public String get_date(String format) {
return (new SimpleDateFormat(format)).format(this.date);
}
public void print() {
System.out.printf(
"| %s | %s | %s | %s | %s |\n",
get_date("yyyy-MM-dd HH:mm:ss"), this.memo, this.withdrawal, this.deposit, this.balance
);
}
}
// 常用工具方法定义
private static void print_repeat(char ch, int n) {
for (int i = 0; i < n; i++) {
System.out.print(ch);
}
}
private static void print_line(int[] fields_max_width) {
System.out.print('-');
for (int i: fields_max_width) {
print_repeat('-', i + 2);
System.out.print('-');
}
System.out.println();
}
private static void print_fields(String[] fields, int[] fields_max_width) {
System.out.print("| ");
int i = 0;
for (String field: fields) {
System.out.print(field);
print_repeat(' ', fields_max_width[i++] - get_str_width(field));
System.out.print(" | ");
}
System.out.println();
}
private static void print_table(String[][] table) {
int table_height = table.length;
int table_width = table[0].length;
// 初始化字段最长宽度数组
int[] fields_max_width = new int[table_width];
for (int i = 0; i < fields_max_width.length; i++) {
fields_max_width[i] = 0;
}
// 求各字段最大长度
for (String[] row: table) {
for (int col_num = 0; col_num < table_width; col_num++) {
fields_max_width[col_num] = get_str_width(row[col_num]) > fields_max_width[col_num] ?
get_str_width(row[col_num]) : fields_max_width[col_num];
}
}
// 打印
print_line(fields_max_width);
print_fields(table[0], fields_max_width);
print_line(fields_max_width);
for (int row_num = 1; row_num < table_height; row_num++) {
print_fields(table[row_num], fields_max_width);
}
print_line(fields_max_width);
}
private static int get_str_width(String str) {
return str.getBytes(Charset.forName("gbk")).length;
}
// ...
private List<BankAccount> accounts_list = new ArrayList<BankAccount>();
private int cash_account_num = 0;
private int credit_account_num = 0;
public boolean create_account(String name, boolean is_credit, int overdraft, String password, BigDecimal balance) {
if (password.equals("")) {
return false;
}
CheckingAccount checking_account = new CheckingAccount();
try {
if (is_credit) {
checking_account.create_account(String.format("CREDIT-%09d", (credit_account_num++) + 1), name, balance, overdraft);
}
else {
checking_account.create_account(String.format("CASH-%011d", (cash_account_num++) + 1), name, balance);
}
}
catch (Throwable err) {
err.printStackTrace(System.out);
return false;
}
checking_account.get_account().reset_password("<PASSWORD>", password);
return this.accounts_list.add(checking_account.get_account());
}
public boolean delete_account(String account_id) {
BankAccount account = get_account_by_id(account_id);
if (account != null) {
accounts_list.remove(account);
return true;
}
return false;
}
public BankAccount get_account_by_id(String account_id) {
for (BankAccount account: accounts_list) {
if (account.account_id.equals(account_id)) {
return account;
}
}
return null;
}
public BankAccount[] get_accounts_by_name(String name) {
List<BankAccount> res = new ArrayList<BankAccount>();
for (BankAccount account: accounts_list) {
if (account.get_name().equals(name)) {
res.add(account);
}
}
return (BankAccount[]) res.toArray(new BankAccount[res.size()]);
}
public void show_accounts() {
int table_height = accounts_list.size() + 1;
int table_width = 5;
String[][] table = new String[table_height][table_width];
table[0][0] = "卡号";
table[0][1] = "开户人姓名";
table[0][2] = "账户类型";
table[0][3] = "余额";
table[0][4] = "可透支额度";
int row_num = 1;
for (BankAccount account: accounts_list) {
table[row_num][0] = account.get_id();
table[row_num][1] = account.get_name();
table[row_num][2] = account instanceof CreditAccount ? "信用卡" : "储蓄卡";
table[row_num][3] = account.get_balance().toString();
table[row_num++][4] = account instanceof CreditAccount ?
String.valueOf(((CreditAccount) account).get_overdraft()) + ".00" : "----";
}
print_table(table);
System.out.printf("账户总数:%d\n", table_height - 1);
}
// 显示银行资产
public void show_capital() {
String[][] table = new String[3][2];
table[0][0] = "项目";
table[0][1] = "值";
table[1][0] = "现金总量";
table[2][0] = "用户贷款总量";
BigDecimal cash = new BigDecimal("0.00");
BigDecimal loan = new BigDecimal("0.00");
for (BankAccount account: accounts_list) {
cash = cash.add(account.balance);
loan = account.get_balance().compareTo(BigDecimal.ZERO) <= 0 ? loan.add(account.balance.negate()) : loan;
}
table[1][1] = cash.toString();
table[2][1] = loan.toString();
print_table(table);
}
// 存钱
public boolean deposit(BankAccount account, BigDecimal amount, String password) {
if (!this.accounts_list.contains(account)) {
return false;
}
if (account.check_password(password)) {
CheckingAccount checking_account = new CheckingAccount(account);
checking_account.deposit(amount);
Transaction transaction = new Transaction(
new Date(),
"现金存入",
new BigDecimal("0.00"),
new BigDecimal("0.00"),
account.get_balance()
);
account.recorder.record(transaction);
return true;
}
return false;
}
// 取钱
public boolean withdraw(BankAccount account, BigDecimal amount, String password) {
if (!this.accounts_list.contains(account)) {
return false;
}
if (account.check_password(password)) {
CheckingAccount checking_account = new CheckingAccount(account);
checking_account.withdraw(amount);
Transaction transaction = new Transaction(
new Date(),
"现金支取",
amount,
new BigDecimal("0.00"),
account.get_balance()
);
account.recorder.record(transaction);
return true;
}
return false;
}
}
|
AyiinXd/Ayiin-Userbot
|
AyiinXd/modules/other.py
|
# Copyright (c) 2021 Man-Userbot
# Created by mrismanaziz
# FROM <https://github.com/mrismanaziz/Man-Userbot>
# t.me/SharingUserbot & t.me/Lunatic0de
#
# Thanks To Ultroid <https://github.com/TeamUltroid/Ultroid>
# Thanks To Geez-UserBot <https://github.com/vckyou/Geez-UserBot>
import os
from telethon import events
from telethon.errors.rpcerrorlist import ChatAdminRequiredError, YouBlockedUserError
from telethon.tl.functions.contacts import UnblockRequest
from telethon.tl.functions.messages import ExportChatInviteRequest
from telethon.tl.types import ChannelParticipantsKicked
from AyiinXd import CMD_HANDLER as cmd
from AyiinXd import CMD_HELP, LOGS
from AyiinXd.ayiin import ayiin_cmd, eod, eor
from Stringyins import get_string
@ayiin_cmd(pattern="open(?: |$)(.*)")
async def _(event):
b = await event.client.download_media(await event.get_reply_message())
with open(b, "r") as a:
c = a.read()
await eor(event, get_string("opn_1"))
if len(c) > 4095:
await eor(
event, c, deflink=True, linktext=get_string("opn_1")
)
else:
await event.client.send_message(event.chat_id, f"`{c}`")
await event.delete()
os.remove(b)
@ayiin_cmd(pattern="sendbot (.*)")
async def _(event):
if event.fwd_from:
return
chat = str(event.pattern_match.group(1).split(" ", 1)[0])
link = str(event.pattern_match.group(1).split(" ", 1)[1])
if not link:
return await eor(event, get_string("sendbot_1"))
botid = await event.client.get_entity(chat)
xx = await eor(event, get_string("com_1"))
async with event.client.conversation(chat) as conv:
try:
response = conv.wait_event(
events.NewMessage(incoming=True, from_users=botid)
)
msg = await event.client.send_message(chat, link)
response = await response
await event.client.send_read_acknowledge(conv.chat_id)
except YouBlockedUserError:
await event.client(UnblockRequest(chat))
msg = await event.client.send_message(chat, link)
response = await response
await event.client.send_read_acknowledge(conv.chat_id)
except BaseException:
await eod(xx, get_string("sendbot_2"))
await xx.edit(get_string("sendbot_3").format(link, chat))
await event.client.send_message(event.chat_id, response.message)
await event.client.send_read_acknowledge(event.chat_id)
await event.client.delete_messages(conv.chat_id, [msg.id, response.id])
@ayiin_cmd(pattern="allunban$")
async def _(event):
xx = await eor(event, get_string("alunban_1"))
p = 0
title = (await event.get_chat()).title
async for i in event.client.iter_participants(
event.chat_id,
filter=ChannelParticipantsKicked,
aggressive=True,
):
try:
await event.client.edit_permissions(event.chat_id, i, view_messages=True)
p += 1
except ChatAdminRequiredError:
pass
except BaseException as er:
LOGS.exeption(er)
await xx.edit(get_string("alunban_2").format(p, title))
@ayiin_cmd(pattern="(?:dm)\\s?(.*)?")
async def _(event):
p = event.pattern_match.group(1)
m = p.split(" ")
chat_id = m[0]
try:
chat_id = int(chat_id)
except BaseException:
pass
mssg = await event.get_reply_message()
if event.reply_to_msg_id:
await event.client.send_message(chat_id, mssg)
await eor(event, get_string("dm_1"))
msg = "".join(f"{i} " for i in m[1:])
if not msg:
return
try:
await event.client.send_message(chat_id, msg)
await eor(event, get_string("dm_1"))
except BaseException:
await eod(event, get_string("error_1").format("**Gagal Mengirim Pesan.**"), time=10)
@ayiin_cmd(pattern="fwdreply ?(.*)")
async def _(e):
message = e.pattern_match.group(1)
if not e.reply_to_msg_id:
return await eor(e, get_string("gban_8"))
if not message:
return await eor(e, get_string("replymsg_1"))
msg = await e.get_reply_message()
fwd = await msg.forward_to(msg.sender_id)
await fwd.reply(message)
await eod(e, get_string("replymsg_2"), time=10)
@ayiin_cmd(pattern="getlink(?: |$)(.*)")
async def _(event):
xx = await eor(event, get_string("com_1"))
try:
e = await event.client(
ExportChatInviteRequest(event.chat_id),
)
await xx.edit(get_string("getlink_1").format(e.link))
except ChatAdminRequiredError:
return await xx.edit(get_string("no_admn"))
@ayiin_cmd(pattern="tmsg (.*)")
async def _(event):
k = await event.get_reply_message()
u = event.pattern_match.group(1)
if k:
a = await event.client.get_messages(event.chat_id, 0, from_user=k.sender_id)
return await event.edit(get_string("tmsg_1").format(a.total, u)
)
if not u:
u = "me"
a = await event.client.get_messages(event.chat_id, 0, from_user=u)
await eor(
event, get_string("tmsg").format(a.total, "**saya**")
)
@ayiin_cmd(pattern="limit(?: |$)(.*)")
async def _(event):
xx = await eor(event, get_string("com_1"))
async with event.client.conversation("@SpamBot") as conv:
try:
response = conv.wait_event(
events.NewMessage(incoming=True, from_users=178220800)
)
await conv.send_message("/start")
response = await response
await event.client.send_read_acknowledge(conv.chat_id)
except YouBlockedUserError:
await event.client(UnblockRequest("@SpamBot"))
await conv.send_message("/start")
response = await response
await event.client.send_read_acknowledge(conv.chat_id)
await xx.edit(f"~ {response.message.message}")
@ayiin_cmd(pattern="view")
async def _(event):
reply_message = await event.get_reply_message()
if not reply_message:
await eor(event, get_string("view_1"))
return
if not reply_message.text:
await eor(event, get_string("view_1"))
return
chat = "@chotamreaderbot"
xx = await eor(event, get_string("com_1"))
async with event.client.conversation(chat) as conv:
try:
response = conv.wait_event(
events.NewMessage(incoming=True, from_users=272572121)
)
await event.client.forward_messages(chat, reply_message)
response = await response
await event.client.send_read_acknowledge(conv.chat_id)
except YouBlockedUserError:
await event.client(UnblockRequest(chat))
await event.client.forward_messages(chat, reply_message)
response = await response
await event.client.send_read_acknowledge(conv.chat_id)
if response.text.startswith(""):
await xx.edit(get_string("view_2"))
else:
await xx.delete()
await event.client.send_message(event.chat_id, response.message)
CMD_HELP.update(
{
"view": f"**Plugin : **`view`\
\n\n » **Perintah :** `{cmd}view` <reply ke link>\
\n » **Kegunaan : **Untuk Melihat isi web dengan instan view telegraph.\
"
}
)
CMD_HELP.update(
{
"open": f"**Plugin : **`open`\
\n\n » **Perintah :** `{cmd}open` <reply ke file>\
\n » **Kegunaan : **Untuk Melihat isi File Menjadi Text yang dikirim menjadi pesan telegram.\
"
}
)
CMD_HELP.update(
{
"dm": f"**Plugin : **`dm`\
\n\n » **Perintah :** `{cmd}dm` <username> <text>\
\n » **Kegunaan : **Untuk mengirim chat dengan menggunakan userbot.\
\n\n » **Perintah :** `{cmd}fwdreply` <username> <text>\
\n » **Kegunaan : **Untuk meneruskan chat yang di reply dengan membalasnya ke pc.\
"
}
)
CMD_HELP.update(
{
"sendbot": f"**Plugin : **`sendbot`\
\n\n » **Perintah :** `{cmd}sendbot` <username bot> <text>\
\n » **Kegunaan : **Untuk mengirim ke bot dan mendapatkan respond chat dengan menggunakan userbot.\
"
}
)
CMD_HELP.update(
{
"tmsg": f"**Plugin : **`tmsg`\
\n\n » **Perintah :** `{cmd}tmsg` <username/me>\
\n » **Kegunaan : **Untuk Menghitung total jumlah chat yang sudah dikirim.\
"
}
)
CMD_HELP.update(
{
"getlink": f"**Plugin : **`getlink`\
\n\n » **Perintah :** `{cmd}getlink`\
\n » **Kegunaan : **Untuk Mendapatkan link invite grup chat.\
"
}
)
CMD_HELP.update(
{
"unbanall": f"**Plugin : **`unbanall`\
\n\n » **Perintah :** `{cmd}unbanall`\
\n » **Kegunaan : **Untuk Menghapus Semua Pengguna yang dibanned di Daftar Banned GC.\
"
}
)
CMD_HELP.update(
{
"limit": f"**Plugin : **`limit`\
\n\n » **Perintah :** `{cmd}limit`\
\n » **Kegunaan : **Untuk Mengecek akun anda sedang terkena limit atau tidak dengan menggunakan @spambot.\
"
}
)
|
SweetIceLolly/DragControlsIDE
|
GCC/include/docobj.h
|
#ifndef _DOCOBJ_H
#define _DOCOBJ_H
#if __GNUC__ >= 3
#pragma GCC system_header
#endif
#ifdef __cplusplus
extern "C" {
#endif
#define OLECMDERR_E_UNKNOWNGROUP (-2147221244)
#define OLECMDERR_E_DISABLED (-2147221247)
#define OLECMDERR_E_NOHELP (-2147221246)
#define OLECMDERR_E_CANCELED (-2147221245)
#define OLECMDERR_E_NOTSUPPORTED (-2147221248)
typedef enum {
OLECMDID_OPEN = 1,
OLECMDID_NEW = 2,
OLECMDID_SAVE = 3,
OLECMDID_SAVEAS = 4,
OLECMDID_SAVECOPYAS = 5,
OLECMDID_PRINT = 6,
OLECMDID_PRINTPREVIEW = 7,
OLECMDID_PAGESETUP = 8,
OLECMDID_SPELL = 9,
OLECMDID_PROPERTIES = 10,
OLECMDID_CUT = 11,
OLECMDID_COPY = 12,
OLECMDID_PASTE = 13,
OLECMDID_PASTESPECIAL = 14,
OLECMDID_UNDO = 15,
OLECMDID_REDO = 16,
OLECMDID_SELECTALL = 17,
OLECMDID_CLEARSELECTION = 18,
OLECMDID_ZOOM = 19,
OLECMDID_GETZOOMRANGE = 20,
OLECMDID_UPDATECOMMANDS = 21,
OLECMDID_REFRESH = 22,
OLECMDID_STOP = 23,
OLECMDID_HIDETOOLBARS = 24,
OLECMDID_SETPROGRESSMAX = 25,
OLECMDID_SETPROGRESSPOS = 26,
OLECMDID_SETPROGRESSTEXT = 27,
OLECMDID_SETTITLE = 28,
OLECMDID_SETDOWNLOADSTATE = 29,
OLECMDID_STOPDOWNLOAD = 30
} OLECMDID;
typedef enum {
OLECMDF_SUPPORTED = 1,
OLECMDF_ENABLED = 2,
OLECMDF_LATCHED = 4,
OLECMDF_NINCHED = 8
} OLECMDF;
typedef enum {
OLECMDEXECOPT_DODEFAULT = 0,
OLECMDEXECOPT_PROMPTUSER = 1,
OLECMDEXECOPT_DONTPROMPTUSER = 2,
OLECMDEXECOPT_SHOWHELP = 3
} OLECMDEXECOPT;
typedef struct _tagOLECMDTEXT {
DWORD cmdtextf;
ULONG cwActual;
ULONG cwBuf;
wchar_t rgwz[1];
} OLECMDTEXT;
typedef struct _tagOLECMD {
ULONG cmdID;
DWORD cmdf;
} OLECMD;
typedef interface IOleInPlaceSite *LPOLEINPLACESITE;
typedef interface IEnumOleDocumentViews *LPENUMOLEDOCUMENTVIEWS;
EXTERN_C const IID IID_IContinueCallback;
EXTERN_C const IID IID_IEnumOleDocumentViews;
EXTERN_C const IID IID_IPrint;
EXTERN_C const IID IID_IOleDocumentView;
#undef INTERFACE
#define INTERFACE IOleDocumentView
DECLARE_INTERFACE_(IOleDocumentView,IUnknown)
{
STDMETHOD(QueryInterface)(THIS_ REFIID,PVOID*) PURE;
STDMETHOD_(ULONG,AddRef)(THIS) PURE;
STDMETHOD_(ULONG,Release)(THIS) PURE;
STDMETHOD(SetInPlaceSite)(THIS_ LPOLEINPLACESITE) PURE;
STDMETHOD(GetInPlaceSite)(THIS_ LPOLEINPLACESITE*) PURE;
STDMETHOD(GetDocument)(THIS_ IUnknown*) PURE;
STDMETHOD(SetRect)(THIS_ LPRECT) PURE;
STDMETHOD(GetRect)(THIS_ LPRECT) PURE;
STDMETHOD(SetRectComplex)(THIS_ LPRECT,LPRECT,LPRECT,LPRECT) PURE;
STDMETHOD(Show)(THIS_ BOOL) PURE;
STDMETHOD(UIActivate)(THIS_ BOOL) PURE;
STDMETHOD(Open)(THIS) PURE;
STDMETHOD(Close)(THIS_ DWORD) PURE;
STDMETHOD(SaveViewState)(THIS_ IStream*) PURE;
STDMETHOD(ApplyViewState)(THIS_ IStream*) PURE;
STDMETHOD(Clone)(THIS_ LPOLEINPLACESITE,IOleDocumentView**) PURE;
};
DECLARE_ENUMERATOR_(IEnumOleDocumentViews,IOleDocumentView);
EXTERN_C const IID IID_IOleDocument;
#undef INTERFACE
#define INTERFACE IOleDocument
DECLARE_INTERFACE_(IOleDocument,IUnknown)
{
STDMETHOD(QueryInterface)(THIS_ REFIID,PVOID*) PURE;
STDMETHOD_(ULONG,AddRef)(THIS) PURE;
STDMETHOD_(ULONG,Release)(THIS) PURE;
STDMETHOD(CreateView)(THIS_ LPOLEINPLACESITE,IStream*,DWORD,IOleDocumentView**) PURE;
STDMETHOD(GetDocMiscStatus)(THIS_ DWORD*) PURE;
STDMETHOD(EnumViews)(THIS_ LPENUMOLEDOCUMENTVIEWS*,IOleDocumentView**) PURE;
};
EXTERN_C const IID IID_IOleCommandTarget;
#undef INTERFACE
#define INTERFACE IOleCommandTarget
DECLARE_INTERFACE_(IOleCommandTarget,IUnknown)
{
STDMETHOD(QueryInterface)(THIS_ REFIID,PVOID*) PURE;
STDMETHOD_(ULONG,AddRef)(THIS) PURE;
STDMETHOD_(ULONG,Release)(THIS) PURE;
STDMETHOD(QueryStatus)(THIS_ const GUID*,ULONG,OLECMD*,OLECMDTEXT*) PURE;
STDMETHOD(Exec)(THIS_ const GUID*,DWORD,DWORD,VARIANTARG*,VARIANTARG*) PURE;
};
EXTERN_C const IID IID_IOleDocumentSite;
#undef INTERFACE
#define INTERFACE IOleDocumentSite
DECLARE_INTERFACE_(IOleDocumentSite,IUnknown)
{
STDMETHOD(QueryInterface)(THIS_ REFIID,PVOID*) PURE;
STDMETHOD_(ULONG,AddRef)(THIS) PURE;
STDMETHOD_(ULONG,Release)(THIS) PURE;
STDMETHOD(ActivateMe)(THIS_ IOleDocumentView*) PURE;
};
#ifdef __cplusplus
}
#endif
#endif
|
BlackWatch13/clinic-a
|
Projecto/src/model/expediente.js
|
<reponame>BlackWatch13/clinic-a
import Sequelize from 'sequelize';
import {sequelize} from '../db/db';
const expediente = sequelize.define('expediente',{
idexpe:{
type: Sequelize.TEXT,
primaryKey: true
},
idpaciente:{
type: Sequelize.TEXT,
},
alergias:{
type: Sequelize.TEXT
},
enferpade:{
type: Sequelize.TEXT
}
},{
tableName: 'expediente',
timestamps: false
})
export default expediente;
|
portal-webstore/books
|
practical-dojo-projects/ch08/js/dojo/dijit/nls/it/common.js
|
<gh_stars>1-10
({"buttonCancel": "Annulla", "buttonSave": "Salva", "buttonOk": "OK"})
|
joningis/coredata-java-api
|
src/main/java/com/bangsapabbi/api/common/ApiDTO.java
|
<reponame>joningis/coredata-java-api<filename>src/main/java/com/bangsapabbi/api/common/ApiDTO.java<gh_stars>0
package com.bangsapabbi.api.common;
public interface ApiDTO {
void setUUID(String uuid);
}
|
masami256/dfly-3.0.2-bhyve
|
contrib/gcc-4.1/gcc/c-pch.c
|
<filename>contrib/gcc-4.1/gcc/c-pch.c
/* Precompiled header implementation for the C languages.
Copyright (C) 2000, 2002, 2003, 2004, 2005 Free Software Foundation, Inc.
This file is part of GCC.
GCC is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GCC is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with GCC; see the file COPYING. If not, write to
the Free Software Foundation, 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA. */
#include "config.h"
#include "system.h"
#include "coretypes.h"
#include "version.h"
#include "cpplib.h"
#include "tree.h"
#include "flags.h"
#include "c-common.h"
#include "output.h"
#include "toplev.h"
#include "debug.h"
#include "c-pragma.h"
#include "ggc.h"
#include "langhooks.h"
#include "hosthooks.h"
#include "target.h"
/* This is a list of flag variables that must match exactly, and their
names for the error message. The possible values for *flag_var must
fit in a 'signed char'. */
static const struct c_pch_matching
{
int *flag_var;
const char *flag_name;
} pch_matching[] = {
{ &flag_exceptions, "-fexceptions" },
{ &flag_unit_at_a_time, "-funit-at-a-time" }
};
enum {
MATCH_SIZE = ARRAY_SIZE (pch_matching)
};
/* The value of the checksum in the dummy compiler that is actually
checksummed. That compiler should never be run. */
static const char no_checksum[16] = { 0 };
/* Information about flags and suchlike that affect PCH validity.
Before this structure is read, both an initial 8-character identification
string, and a 16-byte checksum, have been read and validated. */
struct c_pch_validity
{
unsigned char debug_info_type;
signed char match[MATCH_SIZE];
void (*pch_init) (void);
size_t target_data_length;
};
struct c_pch_header
{
unsigned long asm_size;
};
#define IDENT_LENGTH 8
/* The file we'll be writing the PCH to. */
static FILE *pch_outfile;
/* The position in the assembler output file when pch_init was called. */
static long asm_file_startpos;
static const char *get_ident (void);
/* Compute an appropriate 8-byte magic number for the PCH file, so that
utilities like file(1) can identify it, and so that GCC can quickly
ignore non-PCH files and PCH files that are of a completely different
format. */
static const char *
get_ident (void)
{
static char result[IDENT_LENGTH];
static const char template[IDENT_LENGTH] = "gpch.013";
static const char c_language_chars[] = "Co+O";
memcpy (result, template, IDENT_LENGTH);
result[4] = c_language_chars[c_language];
return result;
}
/* Prepare to write a PCH file, if one is being written. This is
called at the start of compilation.
Also, print out the executable checksum if -fverbose-asm is in effect. */
void
pch_init (void)
{
FILE *f;
struct c_pch_validity v;
void *target_validity;
static const char partial_pch[IDENT_LENGTH] = "gpcWrite";
#ifdef ASM_COMMENT_START
if (flag_verbose_asm)
{
fprintf (asm_out_file, "%s ", ASM_COMMENT_START);
c_common_print_pch_checksum (asm_out_file);
fputc ('\n', asm_out_file);
}
#endif
if (!pch_file)
return;
f = fopen (pch_file, "w+b");
if (f == NULL)
fatal_error ("can%'t create precompiled header %s: %m", pch_file);
pch_outfile = f;
gcc_assert (memcmp (executable_checksum, no_checksum, 16) != 0);
v.debug_info_type = write_symbols;
{
size_t i;
for (i = 0; i < MATCH_SIZE; i++)
{
v.match[i] = *pch_matching[i].flag_var;
gcc_assert (v.match[i] == *pch_matching[i].flag_var);
}
}
v.pch_init = &pch_init;
target_validity = targetm.get_pch_validity (&v.target_data_length);
if (fwrite (partial_pch, IDENT_LENGTH, 1, f) != 1
|| fwrite (executable_checksum, 16, 1, f) != 1
|| fwrite (&v, sizeof (v), 1, f) != 1
|| fwrite (target_validity, v.target_data_length, 1, f) != 1)
fatal_error ("can%'t write to %s: %m", pch_file);
/* We need to be able to re-read the output. */
/* The driver always provides a valid -o option. */
if (asm_file_name == NULL
|| strcmp (asm_file_name, "-") == 0)
fatal_error ("%qs is not a valid output file", asm_file_name);
asm_file_startpos = ftell (asm_out_file);
/* Let the debugging format deal with the PCHness. */
(*debug_hooks->handle_pch) (0);
cpp_save_state (parse_in, f);
}
/* Write the PCH file. This is called at the end of a compilation which
will produce a PCH file. */
void
c_common_write_pch (void)
{
char *buf;
long asm_file_end;
long written;
struct c_pch_header h;
(*debug_hooks->handle_pch) (1);
cpp_write_pch_deps (parse_in, pch_outfile);
asm_file_end = ftell (asm_out_file);
h.asm_size = asm_file_end - asm_file_startpos;
if (fwrite (&h, sizeof (h), 1, pch_outfile) != 1)
fatal_error ("can%'t write %s: %m", pch_file);
buf = xmalloc (16384);
if (fseek (asm_out_file, asm_file_startpos, SEEK_SET) != 0)
fatal_error ("can%'t seek in %s: %m", asm_file_name);
for (written = asm_file_startpos; written < asm_file_end; )
{
long size = asm_file_end - written;
if (size > 16384)
size = 16384;
if (fread (buf, size, 1, asm_out_file) != 1)
fatal_error ("can%'t read %s: %m", asm_file_name);
if (fwrite (buf, size, 1, pch_outfile) != 1)
fatal_error ("can%'t write %s: %m", pch_file);
written += size;
}
free (buf);
/* asm_out_file can be written afterwards, so fseek to clear
_IOREAD flag. */
if (fseek (asm_out_file, 0, SEEK_END) != 0)
fatal_error ("can%'t seek in %s: %m", asm_file_name);
gt_pch_save (pch_outfile);
cpp_write_pch_state (parse_in, pch_outfile);
if (fseek (pch_outfile, 0, SEEK_SET) != 0
|| fwrite (get_ident (), IDENT_LENGTH, 1, pch_outfile) != 1)
fatal_error ("can%'t write %s: %m", pch_file);
fclose (pch_outfile);
}
/* Check the PCH file called NAME, open on FD, to see if it can be
used in this compilation. Return 1 if valid, 0 if the file can't
be used now but might be if it's seen later in the compilation, and
2 if this file could never be used in the compilation. */
int
c_common_valid_pch (cpp_reader *pfile, const char *name, int fd)
{
int sizeread;
int result;
char ident[IDENT_LENGTH + 16];
const char *pch_ident;
struct c_pch_validity v;
/* Perform a quick test of whether this is a valid
precompiled header for the current language. */
gcc_assert (memcmp (executable_checksum, no_checksum, 16) != 0);
sizeread = read (fd, ident, IDENT_LENGTH + 16);
if (sizeread == -1)
fatal_error ("can%'t read %s: %m", name);
else if (sizeread != IDENT_LENGTH + 16)
{
cpp_error (pfile, CPP_DL_WARNING, "%s: too short to be a PCH file",
name);
return 2;
}
pch_ident = get_ident();
if (memcmp (ident, pch_ident, IDENT_LENGTH) != 0)
{
if (cpp_get_options (pfile)->warn_invalid_pch)
{
if (memcmp (ident, pch_ident, 5) == 0)
/* It's a PCH, for the right language, but has the wrong version.
*/
cpp_error (pfile, CPP_DL_WARNING,
"%s: not compatible with this GCC version", name);
else if (memcmp (ident, pch_ident, 4) == 0)
/* It's a PCH for the wrong language. */
cpp_error (pfile, CPP_DL_WARNING, "%s: not for %s", name,
lang_hooks.name);
else
/* Not any kind of PCH. */
cpp_error (pfile, CPP_DL_WARNING, "%s: not a PCH file", name);
}
return 2;
}
if (memcmp (ident + IDENT_LENGTH, executable_checksum, 16) != 0)
{
if (cpp_get_options (pfile)->warn_invalid_pch)
cpp_error (pfile, CPP_DL_WARNING,
"%s: created by a different GCC executable", name);
return 2;
}
/* At this point, we know it's a PCH file created by this
executable, so it ought to be long enough that we can read a
c_pch_validity structure. */
if (read (fd, &v, sizeof (v)) != sizeof (v))
fatal_error ("can%'t read %s: %m", name);
/* The allowable debug info combinations are that either the PCH file
was built with the same as is being used now, or the PCH file was
built for some kind of debug info but now none is in use. */
if (v.debug_info_type != write_symbols
&& write_symbols != NO_DEBUG)
{
if (cpp_get_options (pfile)->warn_invalid_pch)
cpp_error (pfile, CPP_DL_WARNING,
"%s: created with -g%s, but used with -g%s", name,
debug_type_names[v.debug_info_type],
debug_type_names[write_symbols]);
return 2;
}
/* Check flags that must match exactly. */
{
size_t i;
for (i = 0; i < MATCH_SIZE; i++)
if (*pch_matching[i].flag_var != v.match[i])
{
if (cpp_get_options (pfile)->warn_invalid_pch)
cpp_error (pfile, CPP_DL_WARNING,
"%s: settings for %s do not match", name,
pch_matching[i].flag_name);
return 2;
}
}
/* If the text segment was not loaded at the same address as it was
when the PCH file was created, function pointers loaded from the
PCH will not be valid. We could in theory remap all the function
pointers, but no support for that exists at present.
Since we have the same executable, it should only be necessary to
check one function. */
if (v.pch_init != &pch_init)
{
if (cpp_get_options (pfile)->warn_invalid_pch)
cpp_error (pfile, CPP_DL_WARNING,
"%s: had text segment at different address", name);
return 2;
}
/* Check the target-specific validity data. */
{
void *this_file_data = xmalloc (v.target_data_length);
const char *msg;
if ((size_t) read (fd, this_file_data, v.target_data_length)
!= v.target_data_length)
fatal_error ("can%'t read %s: %m", name);
msg = targetm.pch_valid_p (this_file_data, v.target_data_length);
free (this_file_data);
if (msg != NULL)
{
if (cpp_get_options (pfile)->warn_invalid_pch)
cpp_error (pfile, CPP_DL_WARNING, "%s: %s", name, msg);
return 2;
}
}
/* Check the preprocessor macros are the same as when the PCH was
generated. */
result = cpp_valid_state (pfile, name, fd);
if (result == -1)
return 2;
else
return result == 0;
}
/* If non-NULL, this function is called after a precompile header file
is loaded. */
void (*lang_post_pch_load) (void);
/* Load in the PCH file NAME, open on FD. It was originally searched for
by ORIG_NAME. */
void
c_common_read_pch (cpp_reader *pfile, const char *name,
int fd, const char *orig_name ATTRIBUTE_UNUSED)
{
FILE *f;
struct c_pch_header h;
struct save_macro_data *smd;
f = fdopen (fd, "rb");
if (f == NULL)
{
cpp_errno (pfile, CPP_DL_ERROR, "calling fdopen");
return;
}
cpp_get_callbacks (parse_in)->valid_pch = NULL;
if (fread (&h, sizeof (h), 1, f) != 1)
{
cpp_errno (pfile, CPP_DL_ERROR, "reading");
return;
}
if (!flag_preprocess_only)
{
unsigned long written;
char * buf = xmalloc (16384);
for (written = 0; written < h.asm_size; )
{
long size = h.asm_size - written;
if (size > 16384)
size = 16384;
if (fread (buf, size, 1, f) != 1
|| fwrite (buf, size, 1, asm_out_file) != 1)
cpp_errno (pfile, CPP_DL_ERROR, "reading");
written += size;
}
free (buf);
}
else
{
/* If we're preprocessing, don't write to a NULL
asm_out_file. */
if (fseek (f, h.asm_size, SEEK_CUR) != 0)
cpp_errno (pfile, CPP_DL_ERROR, "seeking");
}
cpp_prepare_state (pfile, &smd);
gt_pch_restore (f);
if (cpp_read_state (pfile, name, f, smd) != 0)
return;
fclose (f);
/* Give the front end a chance to take action after a PCH file has
been loaded. */
if (lang_post_pch_load)
(*lang_post_pch_load) ();
}
/* Indicate that no more PCH files should be read. */
void
c_common_no_more_pch (void)
{
if (cpp_get_callbacks (parse_in)->valid_pch)
{
cpp_get_callbacks (parse_in)->valid_pch = NULL;
host_hooks.gt_pch_use_address (NULL, 0, -1, 0);
}
}
/* Handle #pragma GCC pch_preprocess, to load in the PCH file. */
#ifndef O_BINARY
# define O_BINARY 0
#endif
void
c_common_pch_pragma (cpp_reader *pfile)
{
tree name_t;
const char *name;
int fd;
if (c_lex (&name_t) != CPP_STRING)
{
error ("malformed #pragma GCC pch_preprocess, ignored");
return;
}
if (!cpp_get_options (pfile)->preprocessed)
{
error ("pch_preprocess pragma should only be used with -fpreprocessed");
inform ("use #include instead");
return;
}
name = TREE_STRING_POINTER (name_t);
fd = open (name, O_RDONLY | O_BINARY, 0666);
if (fd == -1)
fatal_error ("%s: couldn%'t open PCH file: %m", name);
if (c_common_valid_pch (pfile, name, fd) != 1)
{
if (!cpp_get_options (pfile)->warn_invalid_pch)
inform ("use -Winvalid-pch for more information");
fatal_error ("%s: PCH file was invalid", name);
}
c_common_read_pch (pfile, name, fd, name);
close (fd);
}
/* Print out executable_checksum[]. */
void
c_common_print_pch_checksum (FILE *f)
{
int i;
fputs ("Compiler executable checksum: ", f);
for (i = 0; i < 16; i++)
fprintf (f, "%02x", executable_checksum[i]);
putc ('\n', f);
}
|
Hexav/AJE
|
Kaiper-Runtime-Lib/src/main/java/xyz/avarel/kaiper/runtime/collections/Range.java
|
/*
* 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 xyz.avarel.kaiper.runtime.collections;
import xyz.avarel.kaiper.runtime.Null;
import xyz.avarel.kaiper.runtime.Obj;
import xyz.avarel.kaiper.runtime.functions.NativeFunc;
import xyz.avarel.kaiper.runtime.modules.Module;
import xyz.avarel.kaiper.runtime.modules.NativeModule;
import xyz.avarel.kaiper.runtime.numbers.Int;
import xyz.avarel.kaiper.runtime.types.Type;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class Range implements Obj, Iterable<Int> {
public static final Type<Range> TYPE = new Type<>("Range");
public static final Module MODULE = new NativeModule() {{
declare("TYPE", Range.TYPE);
declare("length", new NativeFunc("length", "range") {
@Override
protected Obj eval(List<Obj> arguments) {
return Int.of(((Range) arguments.get(0)).size());
}
});
declare("lastIndex", new NativeFunc("lastIndex", "range") {
@Override
protected Obj eval(List<Obj> arguments) {
return Int.of(((Range) arguments.get(0)).size() - 1);
}
});
}};
private final int start;
private final int end;
public Range(int start, int end) {
this.start = start;
this.end = end;
}
public int getStart() {
return start;
}
public int getEnd() {
return end;
}
@Override
public List<Integer> toJava() {
List<Integer> list = new ArrayList<>();
for (Int i : this) {
list.add(i.value());
}
return list;
}
@Override
public Type getType() {
return TYPE;
}
public Array toArray() {
Array array = new Array();
for (Int i : this) {
array.add(i);
}
return array;
}
@Override
public String toString() {
return start + ".." + end;
}
@Override
public Obj get(Obj key) {
if (key instanceof Int) {
return get((Int) key);
}
return Obj.super.get(key);
}
public Obj get(Int index) {
if (index.value() < size()) {
return Int.of(start + index.value());
}
return Null.VALUE;
}
@Override
public Iterator<Int> iterator() {
return new RangeIterator();
}
public int size() {
return end - start + 1;
}
@Override
public Obj getAttr(String name) {
switch (name) {
case "size":
return Int.of(size());
case "length":
return Int.of(size());
case "lastIndex":
return Int.of(size() - 1);
default:
return Obj.super.getAttr(name);
}
}
private final class RangeIterator implements Iterator<Int> {
private int cursor;
private RangeIterator() {
this.cursor = start;
}
@Override
public boolean hasNext() {
return cursor <= end;
}
@Override
public Int next() {
return Int.of(cursor++);
}
}
}
|
Fuud/rolling-metrics
|
src/main/java/com/github/rollingmetrics/top/impl/ResetByChunksTop.java
|
<reponame>Fuud/rolling-metrics
/*
*
* Copyright 2016 <NAME>
*
* 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.github.rollingmetrics.top.impl;
import com.github.rollingmetrics.histogram.util.Printer;
import com.github.rollingmetrics.top.Position;
import com.github.rollingmetrics.top.Top;
import com.github.rollingmetrics.top.impl.collector.PositionCollector;
import com.github.rollingmetrics.top.impl.recorder.PositionRecorder;
import com.github.rollingmetrics.top.impl.recorder.TwoPhasePositionRecorder;
import com.github.rollingmetrics.util.Clock;
import com.github.rollingmetrics.util.ResilientExecutionUtil;
import com.github.rollingmetrics.histogram.util.Printer;
import com.github.rollingmetrics.top.Position;
import com.github.rollingmetrics.top.Top;
import com.github.rollingmetrics.top.impl.collector.PositionCollector;
import com.github.rollingmetrics.top.impl.recorder.PositionRecorder;
import com.github.rollingmetrics.top.impl.recorder.TwoPhasePositionRecorder;
import com.github.rollingmetrics.util.Clock;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Supplier;
public class ResetByChunksTop implements Top {
private final Executor backgroundExecutor;
private final long intervalBetweenResettingMillis;
private final long creationTimestamp;
private final ArchivedTop[] archive;
private final boolean historySupported;
private final Clock clock;
private final PositionCollector temporarySnapshotCollector;
private final Phase left;
private final Phase right;
private final Phase[] phases;
private final AtomicReference<Phase> currentPhaseRef;
public ResetByChunksTop(int size, long latencyThresholdNanos, int maxDescriptionLength, long intervalBetweenResettingMillis, int numberHistoryChunks, Clock clock, Executor backgroundExecutor) {
this.intervalBetweenResettingMillis = intervalBetweenResettingMillis;
this.clock = clock;
this.creationTimestamp = clock.currentTimeMillis();
this.backgroundExecutor = backgroundExecutor;
Supplier<TwoPhasePositionRecorder> recorderSupplier = () -> new TwoPhasePositionRecorder(size, latencyThresholdNanos, maxDescriptionLength);
this.left = new Phase(recorderSupplier.get(), creationTimestamp + intervalBetweenResettingMillis);
this.right = new Phase(recorderSupplier.get(), Long.MAX_VALUE);
this.phases = new Phase[] {left, right};
this.currentPhaseRef = new AtomicReference<>(left);
Supplier<PositionCollector> collectorSupplier = () -> PositionCollector.createCollector(size);
this.historySupported = numberHistoryChunks > 0;
if (historySupported) {
this.archive = new ArchivedTop[numberHistoryChunks];
for (int i = 0; i < numberHistoryChunks; i++) {
this.archive[i] = new ArchivedTop(collectorSupplier.get(), Long.MIN_VALUE);
}
} else {
archive = null;
}
this.temporarySnapshotCollector = collectorSupplier.get();
}
@Override
public void update(long timestamp, long latencyTime, TimeUnit latencyUnit, Supplier<String> descriptionSupplier) {
long currentTimeMillis = clock.currentTimeMillis();
Phase currentPhase = currentPhaseRef.get();
if (currentTimeMillis < currentPhase.proposedInvalidationTimestamp) {
currentPhase.recorder.update(timestamp, latencyTime, latencyUnit, descriptionSupplier);
return;
}
Phase nextPhase = currentPhase == left ? right : left;
nextPhase.recorder.update(timestamp, latencyTime, latencyUnit, descriptionSupplier);
if (!currentPhaseRef.compareAndSet(currentPhase, nextPhase)) {
// another writer achieved progress and must submit rotation task to backgroundExecutor
return;
}
// Current thread is responsible to rotate phases.
Runnable phaseRotation = () -> rotate(currentTimeMillis, currentPhase, nextPhase);
ResilientExecutionUtil.getInstance().execute(backgroundExecutor, phaseRotation);
}
@Override
synchronized public List<Position> getPositionsInDescendingOrder() {
temporarySnapshotCollector.reset();
long currentTimeMillis = clock.currentTimeMillis();
for (Phase phase : phases) {
if (phase.isNeedToBeReportedToSnapshot(currentTimeMillis)) {
phase.intervalRecorder = phase.recorder.getIntervalRecorder(phase.intervalRecorder);
phase.intervalRecorder.addInto(phase.totalsCollector);
phase.totalsCollector.addInto(temporarySnapshotCollector);
}
}
if (historySupported) {
for (ArchivedTop archivedTop : archive) {
if (archivedTop.proposedInvalidationTimestamp > currentTimeMillis) {
archivedTop.collector.addInto(temporarySnapshotCollector);
}
}
}
return temporarySnapshotCollector.getPositionsInDescendingOrder();
}
@Override
public int getSize() {
return left.intervalRecorder.getSize();
}
private synchronized void rotate(long currentTimeMillis, Phase currentPhase, Phase nextPhase) {
try {
currentPhase.intervalRecorder = currentPhase.recorder.getIntervalRecorder(currentPhase.intervalRecorder);
currentPhase.intervalRecorder.addInto(currentPhase.totalsCollector);
if (historySupported) {
// move values from recorder to correspondent archived collector
long currentPhaseNumber = (currentPhase.proposedInvalidationTimestamp - creationTimestamp) / intervalBetweenResettingMillis;
int correspondentArchiveIndex = (int) (currentPhaseNumber - 1) % archive.length;
ArchivedTop correspondentArchivedTop = archive[correspondentArchiveIndex];
correspondentArchivedTop.collector.reset();
currentPhase.totalsCollector.addInto(correspondentArchivedTop.collector);
correspondentArchivedTop.proposedInvalidationTimestamp = currentPhase.proposedInvalidationTimestamp + archive.length * intervalBetweenResettingMillis;
}
currentPhase.totalsCollector.reset();
} finally {
long millisSinceCreation = currentTimeMillis - creationTimestamp;
long intervalsSinceCreation = millisSinceCreation / intervalBetweenResettingMillis;
currentPhase.proposedInvalidationTimestamp = Long.MAX_VALUE;
nextPhase.proposedInvalidationTimestamp = creationTimestamp + (intervalsSinceCreation + 1) * intervalBetweenResettingMillis;
}
}
private final class ArchivedTop {
private final PositionCollector collector;
private volatile long proposedInvalidationTimestamp;
public ArchivedTop(PositionCollector collector, long proposedInvalidationTimestamp) {
this.collector = collector;
this.proposedInvalidationTimestamp = proposedInvalidationTimestamp;
}
@Override
public String toString() {
return "ArchivedTop{" +
"\n, proposedInvalidationTimestamp=" + proposedInvalidationTimestamp +
"\n, collector=" + collector +
"\n}";
}
}
private final class Phase {
final TwoPhasePositionRecorder recorder;
final PositionCollector totalsCollector;
PositionRecorder intervalRecorder;
volatile long proposedInvalidationTimestamp;
Phase(TwoPhasePositionRecorder recorder, long proposedInvalidationTimestamp) {
this.recorder = recorder;
this.intervalRecorder = recorder.getIntervalRecorder();
this.totalsCollector = PositionCollector.createCollector(intervalRecorder.getSize());
this.proposedInvalidationTimestamp = proposedInvalidationTimestamp;
}
@Override
public String toString() {
return "Phase{" +
"\n, proposedInvalidationTimestamp=" + proposedInvalidationTimestamp +
"\n, totalsCollector=" + totalsCollector +
"\n, intervalRecorder=" + intervalRecorder +
"\n}";
}
boolean isNeedToBeReportedToSnapshot(long currentTimeMillis) {
long proposedInvalidationTimestampLocal = proposedInvalidationTimestamp;
if (proposedInvalidationTimestampLocal > currentTimeMillis) {
return true;
}
if (!historySupported) {
return false;
}
long correspondentChunkProposedInvalidationTimestamp = proposedInvalidationTimestampLocal + archive.length * intervalBetweenResettingMillis;
return correspondentChunkProposedInvalidationTimestamp > currentTimeMillis;
}
}
@Override
public String toString() {
return "ResetByChunksAccumulator{" +
"\nintervalBetweenResettingMillis=" + intervalBetweenResettingMillis +
",\n creationTimestamp=" + creationTimestamp +
(!historySupported ? "" : ",\n archive=" + Printer.printArray(archive, "chunk")) +
",\n clock=" + clock +
",\n left=" + left +
",\n right=" + right +
",\n currentPhase=" + (currentPhaseRef.get() == left? "left": "right") +
",\n temporarySnapshotCollector=" + temporarySnapshotCollector +
'}';
}
}
|
d-amien-b/simple-getwordpress
|
Collections-a-installer/community-general-2.4.0/tests/unit/plugins/lookup/test_tss.py
|
# -*- coding: utf-8 -*-
# (c) 2020, <NAME> <<EMAIL>>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# Make coding more python3-ish
from __future__ import absolute_import, division, print_function
__metaclass__ = type
from ansible_collections.community.general.tests.unit.compat.unittest import TestCase
from ansible_collections.community.general.tests.unit.compat.mock import (
patch,
MagicMock,
)
from ansible_collections.community.general.plugins.lookup import tss
from ansible.plugins.loader import lookup_loader
class MockSecretServer(MagicMock):
RESPONSE = '{"foo": "bar"}'
def get_secret_json(self, path):
return self.RESPONSE
class TestLookupModule(TestCase):
def setUp(self):
tss.sdk_is_missing = False
self.lookup = lookup_loader.get("community.general.tss")
@patch(
"ansible_collections.community.general.plugins.lookup.tss.LookupModule.Client",
MockSecretServer(),
)
def test_get_secret_json(self):
self.assertListEqual(
[MockSecretServer.RESPONSE],
self.lookup.run(
[1],
[],
**{"base_url": "dummy", "username": "dummy", "password": "<PASSWORD>", }
),
)
|
xxyzzzq/ct_common
|
src/ct_common/common/exp_a.h
|
// Copyright 2016 ct_common authors. See LICENSE file for details.
#ifndef CT_COMMON_COMMON_EXP_A_H_
#define CT_COMMON_COMMON_EXP_A_H_
#include <memory>
#include <string>
#include <vector>
#include "ct_common/base/optional.h"
#include "ct_common/base/utils.h"
#include "ct_common/common/assignment.h"
#include "ct_common/common/exp.h"
#include "ct_common/common/paramspec.h"
namespace ct_common {
// Arithmetic expression types
enum eEXP_A_TYPE {
EAT_INT, /**< Integer type */
EAT_DOUBLE, /**< Floating-point type */
};
// Utility macro for getting the resulting value of some arithmetic expression,
// which is converted into the given type.
#define GET_EXP_VAL(type, identifier, exp, param_specs, assignment) \
optional<type> identifier; \
switch (exp->get_type()) { \
case EAT_INT: \
identifier = cast_optional<type>( \
exp->EvaluateInt(param_specs, assignment)); \
break; \
case EAT_DOUBLE: \
identifier = cast_optional<type>( \
exp->EvaluateDouble(param_specs, assignment)); \
break; \
default: \
CT_EXCEPTION("unrecognized expression type when evaluating"); \
}
/**
* Base class of arithmetic expressions
*/
class DLL_EXPORT Exp_A : public Exp {
public:
Exp_A();
~Exp_A() override;
/** Evaluate the double value of the expression. Checks whether the expression
* is of double type. */
optional<double> EvaluateDouble(
const std::vector<std::shared_ptr<ParamSpec> >& param_specs,
const Assignment& assignment) const;
/** Evaluate the int value of the expression. Checks whether the expression is
* of int type. */
optional<int> EvaluateInt(
const std::vector<std::shared_ptr<ParamSpec> >& param_specs,
const Assignment& assignment) const;
eEXP_A_TYPE get_type() const { return type_; }
void set_type(eEXP_A_TYPE type) { type_ = type; }
protected:
eEXP_A_TYPE type_; /**< whether the expression is int or double */
private:
/** Inner evaluating the double value of the expression, no type checking
* here, just return the desired value. */
virtual optional<double> EvaluateDouble_Impl(
const std::vector<std::shared_ptr<ParamSpec> >& param_specs,
const Assignment& assignment) const = 0;
/** Inner evaluating the int value of the expression, no type checking here,
* just return the desired value. */
virtual optional<int> EvaluateInt_Impl(
const std::vector<std::shared_ptr<ParamSpec> >& param_specs,
const Assignment& assignment) const = 0;
DISALLOW_COPY_AND_ASSIGN(Exp_A);
};
} // namespace ct_common
#endif // CT_COMMON_COMMON_EXP_A_H_
|
bTest2018/Store
|
middleware-moshi/src/main/java/com/nytimes/android/external/store3/middleware/moshi/MoshiParserFactory.java
|
<gh_stars>1000+
package com.nytimes.android.external.store3.middleware.moshi;
import com.nytimes.android.external.store3.base.Parser;
import com.squareup.moshi.Moshi;
import java.lang.reflect.Type;
import javax.annotation.Nonnull;
import okio.BufferedSource;
/**
* Factory which returns various Moshi {@link Parser} implementations.
*/
public final class MoshiParserFactory {
private MoshiParserFactory() {
}
/**
* Returns a new Parser which parses from a String to the specified type, using
* the provided {@link Moshi} instance.
*/
@Nonnull
@SuppressWarnings("PMD.AvoidThrowingNullPointerException")
public static <T> Parser<String, T> createStringParser(@Nonnull Moshi moshi, @Nonnull Type type) {
if (moshi == null) {
throw new NullPointerException("moshi cannot be null.");
}
if (type == null) {
throw new NullPointerException("type cannot be null.");
}
return new MoshiStringParser<>(moshi, type);
}
/**
* Returns a new Parser which parses from a String to the specified type, using
* a new default {@link Moshi} instance.
*/
@Nonnull
public static <T> Parser<String, T> createStringParser(@Nonnull Class<T> type) {
return createStringParser(new Moshi.Builder().build(), type);
}
/**
* Returns a new Parser which parses from {@link BufferedSource} to the specified type, using
* the provided {@link Moshi} instance.
*/
@Nonnull
@SuppressWarnings("PMD.AvoidThrowingNullPointerException")
public static <T> Parser<BufferedSource, T> createSourceParser(@Nonnull Moshi moshi, @Nonnull Type type) {
if (moshi == null) {
throw new NullPointerException("moshi cannot be null.");
}
if (type == null) {
throw new NullPointerException("type cannot be null.");
}
return new MoshiSourceParser<>(moshi, type);
}
/**
* Returns a new Parser which parses from {@link BufferedSource} to the specified type, using
* a new default configured {@link Moshi} instance.
*/
@Nonnull
public static <T> Parser<BufferedSource, T> createSourceParser(@Nonnull Type type) {
return createSourceParser(new Moshi.Builder().build(), type);
}
}
|
Olibear/ArcRoutingLibrary
|
src/oarlib/improvements/impl/TwoInterchange.java
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2013-2015 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package oarlib.improvements.impl;
import gnu.trove.TIntArrayList;
import oarlib.core.Graph;
import oarlib.core.Problem;
import oarlib.core.Route;
import oarlib.graph.impl.WindyGraph;
import oarlib.improvements.ImprovementStrategy;
import oarlib.improvements.IntraRouteImprovementProcedure;
import oarlib.link.impl.WindyEdge;
import oarlib.problem.impl.ProblemAttributes;
import oarlib.route.impl.Tour;
import oarlib.route.util.RouteExpander;
import oarlib.vertex.impl.WindyVertex;
import java.util.ArrayList;
import java.util.Collection;
/**
* Improvement Procedure first given in Benavent et al. (2005) New Heuristic Algorithms
* for the Windy Rural Postman Problem. This IP operates over the compressed representation
* of a feasible solution, and tries to swap the positions of two required edges, and re-assess
* cost.
* <p/>
* Created by oliverlum on 11/16/14.
*/
public class TwoInterchange extends IntraRouteImprovementProcedure<WindyVertex, WindyEdge, WindyGraph> {
public TwoInterchange(Problem<WindyVertex, WindyEdge, WindyGraph> problem) {
super(problem);
}
public TwoInterchange(Problem<WindyVertex, WindyEdge, WindyGraph> problem, ImprovementStrategy.Type strat, Collection<Route<WindyVertex, WindyEdge>> initialSol) {
super(problem, strat, initialSol);
}
@Override
public ProblemAttributes getProblemAttributes() {
return new ProblemAttributes(Graph.Type.WINDY, null, null, ProblemAttributes.NumDepots.SINGLE_DEPOT, null);
}
@Override
public Route<WindyVertex, WindyEdge> improveRoute(Route<WindyVertex, WindyEdge> r) {
Route record = r;
int recordCost = r.getCost();
int temp, temp2, candidateCost;
Boolean tempForward, tempForward2;
RouteExpander wre = new RouteExpander(getGraph());
boolean foundImprovement = true;
Route newRecord = null;
while (foundImprovement) {
// defaults
foundImprovement = false;
TIntArrayList flattenedRoute = new TIntArrayList(record.getCompactRepresentation().toNativeArray());
ArrayList<Boolean> traversalDirection = new ArrayList<Boolean>(record.getCompactTraversalDirection());
int n = flattenedRoute.size();
Tour candidate;
//swap them and re expand, and re-assess cost
for (int i = 0; i < n; i++) {
for (int j = 0; j < i; j++) {
temp = flattenedRoute.get(i);
temp2 = flattenedRoute.get(j);
tempForward = traversalDirection.get(i);
tempForward2 = traversalDirection.get(j);
//swap
flattenedRoute.set(i, temp2);
flattenedRoute.set(j, temp);
traversalDirection.set(i, tempForward2);
traversalDirection.set(j, tempForward);
candidate = wre.unflattenRoute(flattenedRoute, traversalDirection);
candidateCost = candidate.getCost();
if (candidateCost < recordCost) {
recordCost = candidateCost;
newRecord = candidate;
foundImprovement = true;
if (mStrat == ImprovementStrategy.Type.FirstImprovement) {
return newRecord;
}
}
//undo the swap
flattenedRoute.set(i, temp);
flattenedRoute.set(j, temp2);
traversalDirection.set(i, tempForward);
traversalDirection.set(j, tempForward2);
}
}
if (foundImprovement) {
record = newRecord;
}
}
return record;
}
}
|
dvmarcilio/accumulo
|
core/src/main/java/org/apache/accumulo/core/client/ConditionalWriterConfig.java
|
<filename>core/src/main/java/org/apache/accumulo/core/client/ConditionalWriterConfig.java
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.accumulo.core.client;
import static com.google.common.base.Preconditions.checkArgument;
import static java.util.Objects.requireNonNull;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static org.apache.accumulo.core.conf.ClientProperty.CONDITIONAL_WRITER_THREADS_MAX;
import static org.apache.accumulo.core.conf.ClientProperty.CONDITIONAL_WRITER_TIMEOUT_MAX;
import java.util.concurrent.TimeUnit;
import org.apache.accumulo.core.conf.ConfigurationTypeHelper;
import org.apache.accumulo.core.security.Authorizations;
/**
* @since 1.6.0
*/
public class ConditionalWriterConfig {
private static final Long DEFAULT_TIMEOUT = getDefaultTimeout();
private static final Integer DEFAULT_MAX_WRITE_THREADS =
Integer.parseInt(CONDITIONAL_WRITER_THREADS_MAX.getDefaultValue());
private Long timeout = null;
private Integer maxWriteThreads = null;
private Authorizations auths = null;
private Durability durability = null;
private String classLoaderContext = null;
/**
* A set of authorization labels that will be checked against the column visibility of each key in
* order to filter data. The authorizations passed in must be a subset of the accumulo user's set
* of authorizations. If the accumulo user has authorizations (A1, A2) and authorizations (A2, A3)
* are passed, then an exception will be thrown.
*
* <p>
* Any condition that is not visible with this set of authorizations will fail.
*/
public ConditionalWriterConfig setAuthorizations(Authorizations auths) {
checkArgument(auths != null, "auths is null");
this.auths = auths;
return this;
}
/**
* Sets the maximum amount of time an unresponsive server will be re-tried. When this timeout is
* exceeded, the {@link ConditionalWriter} should return the mutation with an exception.<br>
* For no timeout, set to zero, or {@link Long#MAX_VALUE} with {@link TimeUnit#MILLISECONDS}.
*
* <p>
* {@link TimeUnit#MICROSECONDS} or {@link TimeUnit#NANOSECONDS} will be truncated to the nearest
* {@link TimeUnit#MILLISECONDS}.<br>
* If this truncation would result in making the value zero when it was specified as non-zero,
* then a minimum value of one {@link TimeUnit#MILLISECONDS} will be used.
*
* <p>
* <b>Default:</b> {@link Long#MAX_VALUE} (no timeout)
*
* @param timeout
* the timeout, in the unit specified by the value of {@code timeUnit}
* @param timeUnit
* determines how {@code timeout} will be interpreted
* @throws IllegalArgumentException
* if {@code timeout} is less than 0
* @return {@code this} to allow chaining of set methods
*/
public ConditionalWriterConfig setTimeout(long timeout, TimeUnit timeUnit) {
if (timeout < 0)
throw new IllegalArgumentException("Negative timeout not allowed " + timeout);
if (timeout == 0)
this.timeout = Long.MAX_VALUE;
else
// make small, positive values that truncate to 0 when converted use the minimum millis
// instead
this.timeout = Math.max(1, timeUnit.toMillis(timeout));
return this;
}
/**
* Sets the maximum number of threads to use for writing data to the tablet servers.
*
* <p>
* <b>Default:</b> 3
*
* @param maxWriteThreads
* the maximum threads to use
* @throws IllegalArgumentException
* if {@code maxWriteThreads} is non-positive
* @return {@code this} to allow chaining of set methods
*/
public ConditionalWriterConfig setMaxWriteThreads(int maxWriteThreads) {
if (maxWriteThreads <= 0)
throw new IllegalArgumentException("Max threads must be positive " + maxWriteThreads);
this.maxWriteThreads = maxWriteThreads;
return this;
}
/**
* Sets the Durability for the mutation, if applied.
* <p>
* <b>Default:</b> Durability.DEFAULT: use the table's durability configuration.
*
* @return {@code this} to allow chaining of set methods
* @since 1.7.0
*/
public ConditionalWriterConfig setDurability(Durability durability) {
this.durability = durability;
return this;
}
public Authorizations getAuthorizations() {
return auths != null ? auths : Authorizations.EMPTY;
}
public long getTimeout(TimeUnit timeUnit) {
return timeUnit.convert(timeout != null ? timeout : DEFAULT_TIMEOUT, MILLISECONDS);
}
public int getMaxWriteThreads() {
return maxWriteThreads != null ? maxWriteThreads : DEFAULT_MAX_WRITE_THREADS;
}
public Durability getDurability() {
return durability != null ? durability : Durability.DEFAULT;
}
private static long getDefaultTimeout() {
long defVal =
ConfigurationTypeHelper.getTimeInMillis(CONDITIONAL_WRITER_TIMEOUT_MAX.getDefaultValue());
return defVal != 0L ? defVal : Long.MAX_VALUE;
}
/**
* Sets the name of the classloader context on this scanner. See the administration chapter of the
* user manual for details on how to configure and use classloader contexts.
*
* @param classLoaderContext
* name of the classloader context
* @throws NullPointerException
* if context is null
* @since 1.8.0
*/
public void setClassLoaderContext(String classLoaderContext) {
requireNonNull(classLoaderContext, "context name cannot be null");
this.classLoaderContext = classLoaderContext;
}
/**
* Clears the current classloader context set on this scanner
*
* @since 1.8.0
*/
public void clearClassLoaderContext() {
this.classLoaderContext = null;
}
/**
* Returns the name of the current classloader context set on this scanner
*
* @return name of the current context
* @since 1.8.0
*/
public String getClassLoaderContext() {
return this.classLoaderContext;
}
private static <T> T merge(T o1, T o2) {
if (o1 != null)
return o1;
return o2;
}
/**
* Merge this ConditionalWriterConfig with another. If config is set in both, preference will be
* given to this config.
*
* @param other
* Another ConditionalWriterConfig
* @return Merged ConditionalWriterConfig
* @since 2.1.0
*/
public ConditionalWriterConfig merge(ConditionalWriterConfig other) {
ConditionalWriterConfig result = new ConditionalWriterConfig();
result.timeout = merge(this.timeout, other.timeout);
result.maxWriteThreads = merge(this.maxWriteThreads, other.maxWriteThreads);
result.durability = merge(this.durability, other.durability);
result.auths = merge(this.auths, other.auths);
return result;
}
}
|
SleepyAries/lugia-web
|
src/widgets/css/check-button.js
|
/**
* CheckButton 颜色公共值
* create by guorg
* @flow
*/
import colorsFunc from '../css/stateColor';
import styled, { css } from 'styled-components';
import CSSComponent, { StaticComponent } from '@lugia/theme-css-hoc';
import { px2remcss } from '../css/units';
import Icon from '../icon';
type CheckSize = 'default' | 'small' | 'large' | 'bigger';
type TypeSizeCSS = {
height: number,
lineHeight: number,
};
export type CheckProps = {
size?: CheckSize,
checked?: boolean,
disabled?: boolean,
select?: 'radio' | 'checkbox',
onChange?: Function,
value?: any,
children: any,
cancel?: boolean,
type: 'checkbox' | 'radio',
childrenIndex: number,
childrenCount: number,
};
type CSSProps = {
themes: Function,
clicked: boolean,
hasChecked: boolean,
hover: boolean,
};
type PropsType = CSSProps & CheckProps;
export type CheckState = {
hasChecked: boolean,
};
const em = px2remcss;
const {
themeColor,
borderColor,
borderDisableColor,
darkGreyColor,
lightGreyColor,
mediumGreyColor,
} = colorsFunc();
const SizeCSS: { [key: CheckSize]: TypeSizeCSS } = {
default: {
height: 32,
lineHeight: 30,
},
small: {
height: 28,
lineHeight: 26,
},
large: {
height: 38,
lineHeight: 36,
},
bigger: {
height: 42,
lineHeight: 40,
},
};
const getSizeCSS = (props: PropsType): string => {
const { size = 'default' } = props;
const { height, lineHeight } = SizeCSS[size];
return `
height: ${em(height)};
line-height: ${em(lineHeight)};
`;
};
const getDisplayCSS = (props: PropsType): string => {
const { hover = false } = props;
if (hover) {
return `padding: ${em(2)}`;
}
return 'z-index: -2';
};
const getCursor = (props: PropsType) => {
const { disabled, cancel = false, type = 'checkbox' } = props;
if (disabled) {
return 'cursor: not-allowed;';
}
if (cancel) {
return `
cursor: ${type === 'radio' ? 'not-allowed' : 'pointer'};
`;
}
return 'cursor: pointer';
};
const getHasCheckCSS = (props: PropsType) => {
const { hasChecked = false } = props;
if (hasChecked) {
return ` border: 1px solid ${themeColor};`;
}
};
export const LabelWrapper = StaticComponent({
tag: 'label',
className: 'CheckButtonLabelWrapper',
css: css`
position: relative;
display: ${props => (props.hasCancel ? 'none' : 'inline-block')};
outline: none;
transition: all 0.3s;
`,
});
export const CheckInput = StaticComponent({
tag: 'input',
className: 'CheckButtonCheckInput',
css: css`
opacity: 0;
outline: none;
position: absolute;
z-index: -1;
`,
});
const getPadding = (themeProps: Object): Object => {
if (!themeProps) {
return {};
}
const { themeConfig = {} } = themeProps;
const { normal = {} } = themeConfig;
const { padding } = normal;
if (!padding) {
return {};
}
return { padding };
};
export const CheckSpan = CSSComponent({
tag: 'span',
className: 'CheckButtonCheckSpan',
css: css`
display: inline-block;
box-sizing: border-box;
white-space: nowrap;
vertical-align: middle;
${getCursor};
${getHasCheckCSS};
text-align: center;
margin: 0;
transition: all 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);
border-left: 0;
user-select: none;
${getSizeCSS};
`,
normal: {
selectNames: [
['opacity'],
['border'],
['borderRadius'],
['background'],
['width'],
['height'],
['color'],
['font'],
['padding'],
],
defaultTheme: {
color: darkGreyColor,
border: {
top: { color: borderColor, width: 1, style: 'solid' },
right: { color: borderColor, width: 1, style: 'solid' },
bottom: { color: borderColor, width: 1, style: 'solid' },
},
background: { color: '#fff' },
fontSize: em(12),
padding: {
top: 0,
right: 10,
bottom: 0,
left: 10,
},
},
getThemeMeta(themeMeta: Object, themeProps: Object): Object {
return getPadding(themeProps);
},
},
hover: {
selectNames: [
['opacity'],
['border'],
['borderRadius'],
['background'],
['color'],
['font'],
['padding'],
],
getThemeMeta(themeMeta: Object, themeProps: Object): Object {
// console.log(themeMeta);
return getPadding(themeProps);
},
},
disabled: {
selectNames: [['opacity'], ['borderRadius'], ['border'], ['background'], ['color']],
defaultTheme: {
color: lightGreyColor,
opacity: 1,
border: {
top: { color: borderDisableColor, width: 1, style: 'solid' },
right: { color: borderDisableColor, width: 1, style: 'solid' },
bottom: { color: borderDisableColor, width: 1, style: 'solid' },
},
background: { color: '#fff' },
fontSize: em(12),
padding: {
top: 0,
right: 10,
bottom: 0,
left: 10,
},
},
getThemeMeta(themeMeta: Object, themeProps: Object): Object {
return getPadding(themeProps);
},
},
});
export const CancelSpan = StaticComponent({
tag: 'span',
className: 'CheckButtonCancelSpan',
css: css`
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
color: ${darkGreyColor};
background: ${lightGreyColor};
${getDisplayCSS};
`,
});
const getIconFont = (props: Object) => {
const { size = 'default' } = props;
if (size === 'default' || size === 'small') {
return `
font-size: ${em(16)}!important;
`;
}
return `
font-size: ${em(18)}!important;
`;
};
export const IconWrap: Object = styled(Icon)`
vertical-align: text-bottom !important;
${getIconFont}
color: ${mediumGreyColor};
`;
|
whtait/eggdash-iteration
|
server/models/User.js
|
const user = (sequelize, DataTypes) => {
const User = sequelize.define('User', {
firstName: {
type: DataTypes.STRING,
allowNull: false,
},
lastName: {
type: DataTypes.STRING,
allowNull: false,
},
email: {
type: DataTypes.STRING,
allowNull: false,
unique: true,
},
password: {
type: DataTypes.STRING,
allowNull: false,
},
addressStreet: {
type: DataTypes.STRING,
allowNull: false,
},
addressZip: {
type: DataTypes.STRING,
allowNull: false,
},
accountType: {
type: DataTypes.STRING, // "customer" or "merchant"
allowNull: false,
},
});
User.associate = (models) => {
User.hasMany(models.Order);
User.hasMany(models.Farm);
};
return User;
};
module.exports = user;
|
todorkrastev/softuni-software-engineering
|
Java/M01JavaProgrammingBasics/L03ConditionalStatementsAdvanced/Lab/E11FruitShop.java
|
<gh_stars>1-10
package bg.softuni.programming_basics.conditional_statements_advanced.lab;
import java.util.Scanner;
public class E11FruitShop {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String fruit = scanner.nextLine();
String day = scanner.nextLine();
double quantity = Double.parseDouble(scanner.nextLine());
String prPeriod;
double price = 0.0;
if (day.equals("Saturday") || day.equals("Sunday")) {
prPeriod = "weekend";
} else if (day.equals("Monday") || day.equals("Tuesday") || day.equals("Wednesday") || day.equals("Thursday") || day.equals("Friday")) {
prPeriod = "week";
} else {
prPeriod = "error";
}
switch (prPeriod) {
case "week":
switch (fruit) {
case "banana":
price += 2.5;
break;
case "apple":
price += 1.2;
break;
case "orange":
price += 0.85;
break;
case "grapefruit":
price += 1.45;
break;
case "kiwi":
price += 2.7;
break;
case "pineapple":
price += 5.5;
break;
case "grapes":
price += 3.85;
break;
default:
price = 0.0;
}
break;
case "weekend":
switch (fruit) {
case "banana":
price += 2.7;
break;
case "apple":
price += 1.25;
break;
case "orange":
price += 0.9;
break;
case "grapefruit":
price += 1.6;
break;
case "kiwi":
price += 3.0;
break;
case "pineapple":
price += 5.6;
break;
case "grapes":
price += 4.2;
break;
default:
price = 0.0;
}
break;
case "error":
price = 0.0;
break;
}
if (price > 0) {
System.out.printf("%.2f", price * quantity);
} else {
System.out.println("error");
}
}
}
|
leongold/ovirt-engine
|
backend/manager/modules/vdsbroker/src/main/java/org/ovirt/engine/core/vdsbroker/vdsbroker/VmStatsVdsBrokerCommand.java
|
package org.ovirt.engine.core.vdsbroker.vdsbroker;
import static org.ovirt.engine.core.vdsbroker.vdsbroker.VdsBrokerObjectsBuilder.buildInterfaceStatisticsData;
import static org.ovirt.engine.core.vdsbroker.vdsbroker.VdsBrokerObjectsBuilder.buildVMStatisticsData;
import static org.ovirt.engine.core.vdsbroker.vdsbroker.VdsBrokerObjectsBuilder.buildVmBalloonInfo;
import static org.ovirt.engine.core.vdsbroker.vdsbroker.VdsBrokerObjectsBuilder.buildVmDiskStatistics;
import static org.ovirt.engine.core.vdsbroker.vdsbroker.VdsBrokerObjectsBuilder.buildVmGuestAgentInterfacesData;
import static org.ovirt.engine.core.vdsbroker.vdsbroker.VdsBrokerObjectsBuilder.buildVmJobsData;
import static org.ovirt.engine.core.vdsbroker.vdsbroker.VdsBrokerObjectsBuilder.buildVmLunDisksData;
import static org.ovirt.engine.core.vdsbroker.vdsbroker.VdsBrokerObjectsBuilder.getVdsmCallTimestamp;
import static org.ovirt.engine.core.vdsbroker.vdsbroker.VdsBrokerObjectsBuilder.getVmDevicesHash;
import java.util.Map;
import org.ovirt.engine.core.common.businessentities.VmDynamic;
import org.ovirt.engine.core.common.vdscommands.VdsIdVDSCommandParametersBase;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.vdsbroker.monitoring.VdsmVm;
public abstract class VmStatsVdsBrokerCommand<P extends VdsIdVDSCommandParametersBase> extends VdsBrokerCommand<P> {
protected VMInfoListReturn vmListReturn;
protected VmStatsVdsBrokerCommand(P parameters) {
super(parameters);
}
@Override
protected Status getReturnStatus() {
return vmListReturn.status;
}
@Override
protected Object getReturnValueFromBroker() {
return vmListReturn;
}
protected VdsmVm createVdsmVm(Map<String, Object> struct) {
VmDynamic vmDynamic = new VmDynamic();
VdsBrokerObjectsBuilder.updateVMDynamicData(vmDynamic, struct, getVds());
Guid vmId = vmDynamic.getId();
return new VdsmVm(getVdsmCallTimestamp(struct))
.setVmDynamic(vmDynamic)
.setDevicesHash(getVmDevicesHash(struct))
.setVmStatistics(buildVMStatisticsData(struct))
.setVmJobs(buildVmJobsData(struct))
.setInterfaceStatistics(buildInterfaceStatisticsData(struct))
.setVmBalloonInfo(buildVmBalloonInfo(struct))
.setVmGuestAgentInterfaces(buildVmGuestAgentInterfacesData(vmId, struct))
.setLunsMap(buildVmLunDisksData(struct))
.setDiskStatistics(buildVmDiskStatistics(struct));
}
@Override
protected boolean shouldLogToAudit() {
return false;
}
}
|
DCNick3/esp-idf
|
components/esp_pm/pm_trace.c
|
// Copyright 2016-2017 Espressif Systems (Shanghai) PTE LTD
//
// 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 "esp_private/pm_trace.h"
#include "driver/gpio.h"
/* GPIOs to use for tracing of esp_pm events.
* Two entries in the array for each type, one for each CPU.
* Feel free to change when debugging.
*/
static const int DRAM_ATTR s_trace_io[] = {
BIT(4), BIT(5), // ESP_PM_TRACE_IDLE
BIT(16), BIT(17), // ESP_PM_TRACE_TICK
BIT(18), BIT(18), // ESP_PM_TRACE_FREQ_SWITCH
BIT(19), BIT(19), // ESP_PM_TRACE_CCOMPARE_UPDATE
BIT(25), BIT(26), // ESP_PM_TRACE_ISR_HOOK
BIT(27), BIT(27), // ESP_PM_TRACE_SLEEP
};
void esp_pm_trace_init(void)
{
for (size_t i = 0; i < sizeof(s_trace_io)/sizeof(s_trace_io[0]); ++i) {
int io = __builtin_ffs(s_trace_io[i]);
if (io == 0) {
continue;
}
gpio_set_direction(io - 1, GPIO_MODE_OUTPUT);
}
}
void IRAM_ATTR esp_pm_trace_enter(esp_pm_trace_event_t event, int core_id)
{
REG_WRITE(GPIO_OUT_W1TS_REG, s_trace_io[2 * event + core_id]);
}
void IRAM_ATTR esp_pm_trace_exit(esp_pm_trace_event_t event, int core_id)
{
REG_WRITE(GPIO_OUT_W1TC_REG, s_trace_io[2 * event + core_id]);
}
|
A-Ribeiro/OpenGLStarter
|
projects-lib/mini-gl-engine/shaders/AmbientLightPassShader.cpp
|
#include "AmbientLightPassShader.h"
using namespace aRibeiro;
namespace GLEngine {
void printV(vec3 v, const char* txt){
printf("%s -> %.11f %.11f %.11f\n",txt,v.x,v.y,v.z);
}
vec3 fakevec3topolar(vec3 i) {
vec3 result;
result.x = acos(i.z);
result.y = acos(i.x);
return result;
}
vec3 vec3topolar(vec3 i){
vec3 result;
result.x = acos(i.z);
result.y = atan2(i.y, i.x);
//result.x = fmod(result.x + 2.0f*PI, 2.0f*PI);
//result.y = fmod(result.y + 2.0f*PI, 2.0f*PI);
return result;
}
vec3 polartovec3(vec3 i){
vec3 result;
result.x = sin(i.x)*cos(i.y);
result.y = sin(i.x)*sin(i.y);
result.z = cos(i.x);
return result;
}
vec3 baricentricCoord(vec3 a, vec3 b, vec3 c, vec3 p){
vec3 bc = c-b;
vec3 ba = a-b;
vec3 N = cross(bc,ba);
vec3 Nnorm = normalize(N);
float areaTriangle = length(N);
vec3 bp = p-b;
vec3 uvw;
uvw.x = (dot(cross(bc,bp),Nnorm)) / areaTriangle;
uvw.z = (dot(cross(bp,ba),Nnorm)) / areaTriangle;
uvw.y = 1.0 - uvw.x - uvw.z;
return uvw;
}
AmbientLight_tex_cube_PassShader::AmbientLight_tex_cube_PassShader() {
format = model::CONTAINS_POS |
model::CONTAINS_UV0 |
model::CONTAINS_NORMAL |
model::CONTAINS_TANGENT;
const char vertexShaderCode[] = {
"attribute vec4 aPosition;"
"attribute vec3 aNormal;"
"attribute vec3 aTangent;"
"attribute vec3 aUV0;"
"uniform mat4 uMVP;"
"uniform mat4 uLocalToWorld;"
"uniform mat4 uLocalToWorld_it;"
"varying vec2 uv;"
"varying mat3 worldTBN;"
"void main() {"
" uv = aUV0.xy;"
" vec3 N = normalize( uLocalToWorld_it * vec4( aNormal, 0.0 ) ).xyz;"
" vec3 T = normalize( uLocalToWorld * vec4( aTangent, 0.0 ) ).xyz;"
// re-orthogonalize T with respect to N
" T = normalize(T - dot(T, N) * N);"
" vec3 B = cross(T, N);"
" worldTBN = mat3(T,B,N);"
" gl_Position = uMVP * aPosition;"
"}" };
const char fragmentShaderCode[] = {
"varying vec2 uv;"
"varying mat3 worldTBN;"
"uniform vec4 uColor;"
"uniform sampler2D uTexture;"
"uniform sampler2D uTextureNormal;"
"uniform samplerCube uTextureCubeEnvironment;"
/*
"vec3 gammaToLinear(vec3 gamma){"
" return pow(gamma, vec3(2.2));"
"}"
"vec3 linearToGamma(vec3 linear){"
" return pow( linear / (linear + vec3(1)) , vec3( 1.0 / 2.2 ) );"
"}"
*/
/*
"vec3 baricentricCoordVec3(vec3 a, vec3 b, vec3 c, vec3 p){"
" vec3 bc = c-b;"
" vec3 ba = a-b;"
" vec3 N = cross(bc,ba);"
" float Nlength = length(N);"
" vec3 Nnorm = N * vec3( 1.0 / Nlength );"
" float areaTriangle = Nlength;"
" vec3 bp = p-b;"
" vec3 uvw;"
" uvw.x = (dot(cross(bc,bp),Nnorm)) / areaTriangle;"
" uvw.z = (dot(cross(bp,ba),Nnorm)) / areaTriangle;"
" uvw.y = 1.0 - uvw.x - uvw.z;"
" return uvw;"
"}"
*/
"vec3 baricentricCoordVec2(vec2 a, vec2 b, vec2 c, vec2 p){"
" vec3 bc = vec3(c-b,0);"
" vec3 ba = vec3(a-b,0);"
" float areaTriangle_inv = 1.0/cross(bc,ba).z;"
" vec3 bp = vec3(p-b,0);"
" vec3 uvw;"
" uvw.x = cross(bc,bp).z;"
" uvw.z = cross(bp,ba).z;"
" uvw.xz = uvw.xz * areaTriangle_inv;"
" uvw.y = 1.0 - uvw.x - uvw.z;"
" return uvw;"
"}"
/*
"vec2 vec3topolar(vec3 i){"
" vec2 r = vec2( acos(i.z), atan(i.y, i.x) );"
" return r;"
"}"
"vec3 polartovec3(vec2 i){"
" float sinx = sin(i.x);"
" vec3 result;"
" result.x = sinx*cos(i.y);"
" result.y = sinx*sin(i.y);"
" result.z = cos(i.x);"
" return result;"
"}"
*/
// convert i to cossine space
"vec2 fake_vec3topolar(vec3 i){"
" return acos(i.zx);"
"}"
"vec3 sampleEnvironmentCubeBaryLerp(vec3 normal){"
" vec3 sign = sign(normal);"
" vec3 signX = vec3(sign.x,0,0);"
" vec3 signY = vec3(0,sign.y,0);"
" vec3 signZ = vec3(0,0,sign.z);"
" mat3 tex = mat3("
" textureCube(uTextureCubeEnvironment, signX).rgb,"
" textureCube(uTextureCubeEnvironment, signY).rgb,"
" textureCube(uTextureCubeEnvironment, signZ).rgb"
" );"
//" vec2 polarSignX = fake_vec3topolar(signX);"
//" vec2 polarSignY = fake_vec3topolar(signY);"
//" vec2 polarSignZ = fake_vec3topolar(signZ);"
// vec2(-0.5) >= sign.xz : step( sign.xz, vec2(-0.5) )
" vec2 signXxZz = step( sign.xz, vec2(-0.5) );"
// vec2( (signX.x <= -0.5), (signZ.z <= -0.5) );"
" signXxZz = signXxZz * 3.14159265359;"
" vec2 polarSignX = vec2(1.57079637051,signXxZz.x );"
" vec2 polarSignY = vec2(1.57079637051);"
" vec2 polarSignZ = vec2(signXxZz.y,1.57079637051);"
" vec2 polarNormal = fake_vec3topolar(normal);"
" vec3 bariCentricCoord = baricentricCoordVec2("
" polarSignX,polarSignY,polarSignZ,polarNormal"
" );"
" return tex * bariCentricCoord;"
"}"
/*
"vec3 sampleEnvironmentCube(vec3 normal){"
" vec3 sign = sign(normal);"
" vec3 signX = vec3(sign.x,0,0);"
" vec3 signY = vec3(0,sign.y,0);"
" vec3 signZ = vec3(0,0,sign.z);"
" mat3 tex = mat3("
" gammaToLinear(textureCube(uTextureCubeEnvironment, signX).rgb),"
" gammaToLinear(textureCube(uTextureCubeEnvironment, signY).rgb),"
" gammaToLinear(textureCube(uTextureCubeEnvironment, signZ).rgb)"
" );"
" vec3 dot_normal = vec3( "
" dot(normal,signX),"
" dot(normal,signY),"
" dot(normal,signZ) "
" );"
" dot_normal = max( vec3(0), dot_normal );"
//linearize the angle mix asin(dot_normal)/(PI/2)
" dot_normal = asin(dot_normal) * vec3(6.36619806290e-01);"
" return tex * dot_normal;"
"}"
*/
"vec3 readNormalMap(){"
" vec3 normal = texture2D(uTextureNormal, uv).xyz;"
" normal = normal * 2.0 - 1.0;"
" normal = worldTBN * normal;"
" return normalize(normal);"
"}"
"void main() {"
" vec4 texel = texture2D(uTexture, uv);"
" vec3 texelEnvironment = sampleEnvironmentCubeBaryLerp(readNormalMap());"
" texel.a *= uColor.a;"
" texel.rgb = texel.rgb * uColor.rgb * texelEnvironment;"
" gl_FragColor = texel;"
"}" };
//PI = 3.14159265358 //1/PI = 3.18309877326e-01
compile(vertexShaderCode, fragmentShaderCode, __FILE__, __LINE__);
DefaultEngineShader::setupAttribLocation();
link(__FILE__, __LINE__);
u_mvp = getUniformLocation("uMVP");
u_localToWorld = getUniformLocation("uLocalToWorld");
u_localToWorld_it = getUniformLocation("uLocalToWorld_it");
u_texture = getUniformLocation("uTexture");
u_textureNormal = getUniformLocation("uTextureNormal");
u_textureCubeEnvironment = getUniformLocation("uTextureCubeEnvironment");
u_color = getUniformLocation("uColor");
/*
{
printf("%.11f %.11f \n.",acos(1),acos(-1));
exit(-1);
}
*/
/*
{
vec3 _sign = vec3(1,1,1);
vec3 signX = vec3(_sign.x,0,0);
vec3 signY = vec3(0,_sign.y,0);
vec3 signZ = vec3(0,0,_sign.z);
vec3 polarSignX = fakevec3topolar(signX);
vec3 polarSignY = fakevec3topolar(signY);
vec3 polarSignZ = fakevec3topolar(signZ);
printV(polarSignX, "polarSignX");
printV(polarSignY, "polarSignY");
printV(polarSignZ, "polarSignZ");
exit(-1);
}
*/
/*
for(int i=0;i<100;i++){
vec3 sample = Random::getVec3Direction();
vec3 _sign = vec3( sign(sample.x), sign(sample.y), sign(sample.z) );
vec3 signX = vec3(_sign.x,0,0);
vec3 signY = vec3(0,_sign.y,0);
vec3 signZ = vec3(0,0,_sign.z);
vec3 polarSignX = vec3topolar(signX);
vec3 polarSignY = vec3topolar(signY);
vec3 polarSignZ = vec3topolar(signZ);
vec3 polarSample = vec3topolar(sample);
vec3 polarBary = baricentricCoord(polarSignX,polarSignY,polarSignZ,polarSample);
vec3 polarReconstruction = polarSignX * polarBary.x + polarSignY * polarBary.y + polarSignZ * polarBary.z;
printV(sample,"sample");
printV(polarSample,"polarSample");
printV(polarReconstruction,"polarReconstruction");
vec3 sampleReconstruction = polartovec3(polarReconstruction);
printV(sampleReconstruction,"sampleReconstruction");
if (distance(sample,sampleReconstruction) > EPSILON){
printf("Error...\n");
exit(-1);
}
}
*/
/*
for (int i=0;i<=10;i++){
float _cos = (float)i/10.0f;
float _acos = asin(_cos);
float _acosd = _acos / (3.141592653 / 2.0);
printf("cos=%f acos=%.11e _acosd=%f\n",_cos,1.0f/_acos,_acosd);
}
*/
//printf("%.11e\n",1.0/PI);
}
}
|
ravindraranwala/JavaGenericsAndCollections
|
GenericsAndCollections/src/main/java/org/oreilly/books/chapter13/PriorityTask.java
|
package org.oreilly.books.chapter13;
import org.oreilly.books.chapter12.Task;
public class PriorityTask implements Comparable<PriorityTask> {
private final Task task;
private final Priority priority;
public PriorityTask(Task task, Priority priority) {
this.task = task;
this.priority = priority;
}
public Task getTask() {
return task;
}
public Priority getPriority() {
return priority;
}
@Override
public int compareTo(PriorityTask pt) {
int c = priority.compareTo(pt.priority);
return c != 0 ? c : task.compareTo(pt.task);
}
@Override
public boolean equals(Object o) {
if (o instanceof PriorityTask) {
PriorityTask pt = (PriorityTask) o;
return task.equals(pt.task) && priority.equals(pt.priority);
} else
return false;
}
@Override
public int hashCode() {
return task.hashCode();
}
@Override
public String toString() {
return task + ": " + priority;
}
}
|
longztian/cpp
|
codility/14_MinMaxDivision.cpp
|
// you can use includes, for example:
// #include <algorithm>
// you can write to stdout for debugging purposes, e.g.
// cout << "this is a debug message" << endl;
#include <algorithm>
#include <limits>
int solution(int K, int M, vector<int> &A) {
// write your code in C++11 (g++ 4.8.2)
int N = A.size();
if (K >= N) return *max_element(A.begin(), A.end());
vector<int> sum;
sum.reserve(N+1);
sum.push_back(0);
int maxV = numeric_limits<int>::min();
for (int v : A) {
sum.push_back(sum.back() + v);
if (v > maxV) maxV = v;
}
int minSum = maxV;
if (minSum * K < sum.back()) {
minSum = sum.back() / K;
if (sum.back() % K != 0) minSum += 1;
}
int minNK = numeric_limits<int>::max();
for (int i = 0, j = N - K; j <= N; ++i, ++j) {
if (sum[j] - sum[i] < minNK) minNK = sum[j] - sum[i];
}
int maxSum = max(minSum, minNK);
// greedy
int i = minSum - 1, j = maxSum;
while (i < j - 1) {
// cout << i << j << endl;
bool dividable = true;
int m = i + (j - i) / 2;
int n = 0, b = 0, e = b + 1;
while (b < N) {
while (e <= N && sum[e] - sum[b] <= m) ++e;
n += 1;
b = e - 1;
if (n > K) {
dividable = false;
break;
}
}
if (dividable) {
j = m;
} else {
i = m;
}
// cout << i << j << endl;
}
return j;
}
|
Tirthbharatiya/c-examples
|
Practical/spiral_order.c
|
/* a program that reads an M x N matrix A and prints its elements in spiral order */
#include <stdio.h>
#include<conio.h>
void main()
{
int i, k = 0, l = 0,m,n,a[20][20];
clrscr();
printf("Enter the number of row:");
scanf("%d",&m);
printf("Enter the number of column:");
scanf("%d",&n);
/* k - starting row index
m - ending row index
l - starting column index
n - ending column index
i - iterator
*/
for(k=0;k<m;k++)
{
for(l=0;l<n;l++)
{
scanf("%d",&a[k][l]);
}
}
printf("\n\nspiral order is:\n")
k=0;
l=0;
while (k < m && l < n)
{
/* Print the first row from the remaining rows */
for (i = l; i < n; ++i)
{
printf("%3d ", a[k][i]);
}
k++;
/* Print the last column from the remaining columns */
for (i = k; i < m; ++i)
{
printf("%3d ", a[i][n-1]);
}
n--;
/* Print the last row from the remaining rows */
if ( k < m)
{
for (i = n-1; i >= l; --i)
{
printf("%3d ", a[m-1][i]);
}
m--;
}
/* Print the first column from the remaining columns */
if (l < n)
{
for (i = m-1; i >= k; --i)
{
printf("%3d ", a[i][l]);
}
l++;
}
}
printf("\n-<NAME>");
getch();
}
|
shadansari/onos-cu-cp
|
openair2/UTIL/OTG/otg_rx.h
|
/*
* Licensed to the OpenAirInterface (OAI) Software Alliance under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The OpenAirInterface Software Alliance licenses this file to You under
* the OAI Public License, Version 1.1 (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.openairinterface.org/?page_id=698
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*-------------------------------------------------------------------------------
* For more information about the OpenAirInterface (OAI) Software Alliance:
* <EMAIL>
*/
/*! \file otg_rx.h
* \brief Data structure and functions for OTG receiver
* \author <NAME>
* \date 2011
* \version 1.0
* \company Eurecom
* \email: <EMAIL>
* \note
* \warning
*/
#ifndef __OTG_RX_H__
# define __OTG_RX_H__
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "otg.h"
/*! \fn int otg_rx_pkt(const int dst_instanceP, const int ctime, const char * const buffer_tx, const unsigned int size);
* \brief check if the packet is well received and do measurements: one way delay, throughput,etc.
* \param[in] the destination
* \param[in] time of the emulation
* \param[in] The packet
* \param[in] Size of the packet
* \param[out] return NULL is the packet is well received, else the packet to forward
* \note
* @ingroup _otg
*/
int otg_rx_pkt(const int dst_instanceP, const int ctime, const char * const buffer_tx, const unsigned int size);
/*! \fn void owd_const_gen(int src,int dst);
*\brief compute the one way delay introduced in LTE/LTE-A network REF PAPER: "Latency for Real-Time Machine-to-Machine Communication in LTE-Based System Architecture"
*\param[in] the source
*\param[in] the destination
*\param[out] void
*\note
*@ingroup _otg
*/
void owd_const_gen(const int src, const int dst, const int flow_id, const unsigned int flag);
/*! \fn float owd_const_capillary();
*\brief compute the one way delay introduced in LTE/LTE-A network REF PAPER: "Latency for Real-Time Machine-to-Machine Communication in LTE-Based System Architecture"
*\param[out] float: capillary delay constant
*\note
*@ingroup _otg
*/
float owd_const_capillary(void);
/*! \fn float owd_const_mobile_core();
*\brief compute the one way delay introduced in LTE/LTE-A network REF PAPER: "Latency for Real-Time Machine-to-Machine Communication in LTE-Based System Architecture"
*\param[out] float: mobile core delay constant
*\note
*@ingroup _otg
*/
float owd_const_mobile_core(void);
/*! \fn float owd_const_IP_backbone();
*\brief compute the one way delay introduced in LTE/LTE-A network REF PAPER: "Latency for Real-Time Machine-to-Machine Communication in LTE-Based System Architecture"
*\param[out] float: IP backbone delay constant
*\note
*@ingroup _otg
*/
float owd_const_IP_backbone(void);
/*! \fn float owd_const_applicatione();
*\brief compute the one way delay introduced in LTE/LTE-A network REF PAPER: "Latency for Real-Time Machine-to-Machine Communication in LTE-Based System Architecture"
*\param[out] float: application delay constant
*\note
*@ingroup _otg
*/
float owd_const_application(void);
/*! \fn void rx_check_loss(const int src, const int dst, const unsigned int flag, const int seq_num, unsigned int * const seq_num_rx, unsigned int * const nb_loss_pkts);
*\brief check the number of loss packet/out of sequence
*\param[in] src
*\param[in] dst
*\param[in] flag: background or data
*\param[in] seq_num: packet sequence number
*\param[in] seq_num_rx:RX sequence number
*\param[in] nb_loss_pkts: number of lost packet
*\param[out] lost_packet: (0) no lost packets, (1) lost packets
*\note
*@ingroup _otg
*/
int rx_check_loss(
const int src,
const int dst,
const unsigned int flag,
const int seq_num,
unsigned int * const seq_num_rx,
unsigned int * const nb_loss_pkts);
#endif
|
wangaen/forum
|
forumServer/src/token/token.js
|
<filename>forumServer/src/token/token.js<gh_stars>1-10
let jwt = require('jsonwebtoken');
let jwtScrect = 'wyl_forum_token'; //签名
module.exports = {
//登录接口 生成token的方法
setToken: (nickname, _id) => {
return new Promise((resolve, reject) => {
//expiresln 设置token过期的时间
// jwt.sign()生成token
const token = jwt.sign({ nickname, _id }, jwtScrect, { expiresIn: '10h' });
resolve(token)
})
},
//各个接口需要验证token的方法
getToken: (token) => {
return new Promise((resolve, reject) => {
if (!token) {
reject({
error: 'token 为空'
})
}
else {
//jwt.verify()验证token
let info = jwt.verify(token.split(' ')[1], jwtScrect);
resolve(info); //解析返回的值(sign 传入的值)
}
})
}
}
|
thewtex/scikit-image
|
doc/examples/segmentation/plot_rag_merge.py
|
"""
===========
RAG Merging
===========
This example constructs a Region Adjacency Graph (RAG) and progressively merges
regions that are similar in color. Merging two adjacent regions produces
a new region with all the pixels from the merged regions. Regions are merged
until no highly similar region pairs remain.
"""
from skimage import data, io, segmentation, color
from skimage.future import graph
import numpy as np
def _weight_mean_color(graph, src, dst, n):
"""Callback to handle merging nodes by recomputing mean color.
The method expects that the mean color of `dst` is already computed.
Parameters
----------
graph : RAG
The graph under consideration.
src, dst : int
The vertices in `graph` to be merged.
n : int
A neighbor of `src` or `dst` or both.
Returns
-------
data : dict
A dictionary with the `"weight"` attribute set as the absolute
difference of the mean color between node `dst` and `n`.
"""
diff = graph.node[dst]['mean color'] - graph.node[n]['mean color']
diff = np.linalg.norm(diff)
return {'weight': diff}
def merge_mean_color(graph, src, dst):
"""Callback called before merging two nodes of a mean color distance graph.
This method computes the mean color of `dst`.
Parameters
----------
graph : RAG
The graph under consideration.
src, dst : int
The vertices in `graph` to be merged.
"""
graph.node[dst]['total color'] += graph.node[src]['total color']
graph.node[dst]['pixel count'] += graph.node[src]['pixel count']
graph.node[dst]['mean color'] = (graph.node[dst]['total color'] /
graph.node[dst]['pixel count'])
img = data.coffee()
labels = segmentation.slic(img, compactness=30, n_segments=400)
g = graph.rag_mean_color(img, labels)
labels2 = graph.merge_hierarchical(labels, g, thresh=35, rag_copy=False,
in_place_merge=True,
merge_func=merge_mean_color,
weight_func=_weight_mean_color)
out = color.label2rgb(labels2, img, kind='avg')
out = segmentation.mark_boundaries(out, labels2, (0, 0, 0))
io.imshow(out)
io.show()
|
reels-research/iOS-Private-Frameworks
|
NewsTransport.framework/NTPBEndpointConfig.h
|
/* Generated by RuntimeBrowser
Image: /System/Library/PrivateFrameworks/NewsTransport.framework/NewsTransport
*/
@interface NTPBEndpointConfig : PBCodable <NSCopying> {
NSString * _analyticsEndpointUrlsJson;
NSString * _analyticsEnvelopeContentTypePropJson;
NSString * _clientApiBaseUrl;
int _environment;
NSString * _eventRelayBaseUrl;
NSString * _eventRelayBatchBaseUrl;
NSString * _newsNotificationsBaseUrl;
NSString * _remoteDataSourceBaseUrl;
NSString * _staticAssetBaseUrl;
}
@property (nonatomic, retain) NSString *analyticsEndpointUrlsJson;
@property (nonatomic, retain) NSString *analyticsEnvelopeContentTypePropJson;
@property (nonatomic, retain) NSString *clientApiBaseUrl;
@property (nonatomic) int environment;
@property (nonatomic, retain) NSString *eventRelayBaseUrl;
@property (nonatomic, retain) NSString *eventRelayBatchBaseUrl;
@property (nonatomic, readonly) bool hasAnalyticsEndpointUrlsJson;
@property (nonatomic, readonly) bool hasAnalyticsEnvelopeContentTypePropJson;
@property (nonatomic, readonly) bool hasClientApiBaseUrl;
@property (nonatomic, readonly) bool hasEventRelayBaseUrl;
@property (nonatomic, readonly) bool hasEventRelayBatchBaseUrl;
@property (nonatomic, readonly) bool hasNewsNotificationsBaseUrl;
@property (nonatomic, readonly) bool hasRemoteDataSourceBaseUrl;
@property (nonatomic, readonly) bool hasStaticAssetBaseUrl;
@property (nonatomic, retain) NSString *newsNotificationsBaseUrl;
@property (nonatomic, retain) NSString *remoteDataSourceBaseUrl;
@property (nonatomic, retain) NSString *staticAssetBaseUrl;
- (void).cxx_destruct;
- (id)analyticsEndpointUrlsJson;
- (id)analyticsEnvelopeContentTypePropJson;
- (id)clientApiBaseUrl;
- (id)copyWithZone:(struct _NSZone { }*)arg1;
- (id)description;
- (id)dictionaryRepresentation;
- (int)environment;
- (id)eventRelayBaseUrl;
- (id)eventRelayBatchBaseUrl;
- (bool)hasAnalyticsEndpointUrlsJson;
- (bool)hasAnalyticsEnvelopeContentTypePropJson;
- (bool)hasClientApiBaseUrl;
- (bool)hasEventRelayBaseUrl;
- (bool)hasEventRelayBatchBaseUrl;
- (bool)hasNewsNotificationsBaseUrl;
- (bool)hasRemoteDataSourceBaseUrl;
- (bool)hasStaticAssetBaseUrl;
- (unsigned long long)hash;
- (bool)isEqual:(id)arg1;
- (void)mergeFrom:(id)arg1;
- (id)newsNotificationsBaseUrl;
- (bool)readFrom:(id)arg1;
- (id)remoteDataSourceBaseUrl;
- (void)setAnalyticsEndpointUrlsJson:(id)arg1;
- (void)setAnalyticsEnvelopeContentTypePropJson:(id)arg1;
- (void)setClientApiBaseUrl:(id)arg1;
- (void)setEnvironment:(int)arg1;
- (void)setEventRelayBaseUrl:(id)arg1;
- (void)setEventRelayBatchBaseUrl:(id)arg1;
- (void)setNewsNotificationsBaseUrl:(id)arg1;
- (void)setRemoteDataSourceBaseUrl:(id)arg1;
- (void)setStaticAssetBaseUrl:(id)arg1;
- (id)staticAssetBaseUrl;
- (void)writeTo:(id)arg1;
@end
|
pierredebelen/gs-collections
|
unit-tests/src/test/java/com/gs/collections/impl/list/mutable/ArrayListAdapterTest.java
|
/*
* Copyright 2014 <NAME>.
*
* 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.gs.collections.impl.list.mutable;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import com.gs.collections.api.list.MutableList;
import com.gs.collections.api.partition.list.PartitionMutableList;
import com.gs.collections.impl.block.factory.Predicates;
import com.gs.collections.impl.block.procedure.CollectionAddProcedure;
import com.gs.collections.impl.collection.mutable.AbstractCollectionTestCase;
import com.gs.collections.impl.factory.Lists;
import com.gs.collections.impl.lazy.ReverseIterable;
import com.gs.collections.impl.list.Interval;
import com.gs.collections.impl.list.fixed.ArrayAdapter;
import com.gs.collections.impl.test.SerializeTestHelper;
import com.gs.collections.impl.test.Verify;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static com.gs.collections.impl.factory.Iterables.*;
/**
* JUnit test for {@link ArrayListAdapter}.
*/
public class ArrayListAdapterTest extends AbstractCollectionTestCase
{
private static final Logger LOGGER = LoggerFactory.getLogger(ArrayListAdapterTest.class);
@Override
protected <T> ArrayListAdapter<T> newWith(T... littleElements)
{
return ArrayListAdapter.<T>newList().with(littleElements);
}
@Test
public void testAsSynchronized()
{
Verify.assertInstanceOf(SynchronizedMutableList.class, ArrayListAdapter.newList().asSynchronized());
}
@Test
public void testClone()
{
MutableList<Integer> list = this.newWith(1, 2, 3);
MutableList<Integer> list2 = list.clone();
Verify.assertListsEqual(list, list2);
}
@Test
public void testForEachFromTo()
{
MutableList<Integer> result = Lists.mutable.of();
MutableList<Integer> collection = ArrayListAdapter.<Integer>newList(4).with(1, 2, 3, 4);
collection.forEach(2, 3, CollectionAddProcedure.on(result));
Verify.assertSize(2, result);
Verify.assertContainsAll(result, 3, 4);
}
@Test
public void testNewListWithSize()
{
MutableList<Integer> objects = ArrayListAdapter.<Integer>newList(4).with(1, 2, 3);
Assert.assertEquals(1, objects.indexOf(2));
}
@Override
@Test
public void remove()
{
MutableList<Integer> objects = this.newWith(1, 2, 3, null);
objects.removeIf(Predicates.isNull());
Verify.assertSize(3, objects);
Verify.assertContainsAll(objects, 1, 2, 3);
}
@Override
@Test
public void asSynchronized()
{
Verify.assertInstanceOf(SynchronizedMutableList.class, this.newWith().asSynchronized());
}
@Override
@Test
public void asUnmodifiable()
{
Verify.assertInstanceOf(UnmodifiableMutableList.class, this.newWith().asUnmodifiable());
}
@Test
public void asReversed()
{
Verify.assertInstanceOf(ReverseIterable.class, this.newWith().asReversed());
}
@Test
public void testRemoveIndex()
{
MutableList<Integer> objects = this.newWith(1, 2, 3);
objects.remove(2);
Verify.assertSize(2, objects);
Verify.assertContainsAll(objects, 1, 2);
}
@Test
public void testIndexOf()
{
MutableList<Integer> objects = this.newWith(1, 2, 3);
Assert.assertEquals(1, objects.indexOf(2));
}
@Test
public void testLastIndexOf()
{
MutableList<Integer> objects = this.newWith(1, 2, 3);
Assert.assertEquals(1, objects.lastIndexOf(2));
}
@Test
public void testSet()
{
MutableList<Integer> objects = this.newWith(1, 2, 3);
Assert.assertEquals(Integer.valueOf(2), objects.set(1, 4));
Verify.assertItemAtIndex(4, 1, objects);
}
@Test
public void testAddAtIndex()
{
MutableList<Integer> objects = this.newWith(1, 2, 3);
objects.add(0, 0);
Verify.assertSize(4, objects);
Verify.assertItemAtIndex(0, 0, objects);
}
@Test
public void testAddAllAtIndex()
{
MutableList<Integer> objects = this.newWith(1, 2, 3);
objects.addAll(0, Lists.fixedSize.of(0));
Verify.assertSize(4, objects);
Verify.assertItemAtIndex(0, 0, objects);
}
@Test
public void testEqualsAndHashCode()
{
MutableList<Integer> list1 = this.newWith(1, 2, 3, 4);
MutableList<Integer> list2 = this.newWith(1, 2, 3, 4);
MutableList<Integer> list3 = this.newWith(2, 3, 4);
Assert.assertNotEquals(list1, null);
Verify.assertEqualsAndHashCode(list1, list1);
Verify.assertEqualsAndHashCode(list1, list2);
Assert.assertNotEquals(list2, list3);
Verify.assertEqualsAndHashCode(list1, new ArrayList<Integer>(list1));
Verify.assertEqualsAndHashCode(list1, new LinkedList<Integer>(list1));
Verify.assertEqualsAndHashCode(list1, ArrayAdapter.newArrayWith(1, 2, 3, 4));
Verify.assertEqualsAndHashCode(list1, FastList.newListWith(1, 2, 3, 4));
}
@Test
public void testSerialization()
{
MutableList<Integer> collection = this.newWith(1, 2, 3, 4, 5);
MutableList<Integer> deserializedCollection = SerializeTestHelper.serializeDeserialize(collection);
Verify.assertSize(5, deserializedCollection);
Verify.assertStartsWith(deserializedCollection, 1, 2, 3, 4, 5);
Verify.assertListsEqual(collection, deserializedCollection);
}
@Test
public void testBAOSSize()
{
MutableList<Integer> mutableArrayList = ArrayListAdapter.newList();
ByteArrayOutputStream stream1 = SerializeTestHelper.getByteArrayOutputStream(mutableArrayList);
LOGGER.info("ArrayListAdapter size: {}", stream1.size());
LOGGER.info("{}", stream1);
Assert.assertTrue(stream1.size() > 0);
List<Integer> arrayList = new ArrayList<Integer>();
ByteArrayOutputStream stream2 = SerializeTestHelper.getByteArrayOutputStream(arrayList);
LOGGER.info("ArrayList size: {}", stream2.size());
LOGGER.info("{}", stream2);
Assert.assertTrue(stream2.size() > 0);
}
@Test
public void testWithMethods()
{
Verify.assertContainsAll(ArrayListAdapter.newList().with(1), 1);
Verify.assertContainsAll(ArrayListAdapter.newList().with(1, 2), 1, 2);
Verify.assertContainsAll(ArrayListAdapter.newList().with(1, 2, 3), 1, 2, 3);
Verify.assertContainsAll(ArrayListAdapter.newList().with(1, 2, 3, 4), 1, 2, 3, 4);
}
@Test
public void sortThis_small()
{
MutableList<Integer> actual = this.newWith(1, 2, 3);
Collections.shuffle(actual);
MutableList<Integer> sorted = actual.sortThis();
Assert.assertSame(actual, sorted);
Assert.assertEquals(FastList.newListWith(1, 2, 3), actual);
}
@Test
public void sortThis()
{
MutableList<Integer> actual = this.newWith(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
Collections.shuffle(actual);
MutableList<Integer> sorted = actual.sortThis();
Assert.assertSame(actual, sorted);
Assert.assertEquals(FastList.newListWith(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), actual);
}
@Test
public void sortThis_large()
{
MutableList<Integer> actual = this.newWith(Interval.oneTo(1000).toArray());
Collections.shuffle(actual);
MutableList<Integer> sorted = actual.sortThis();
Assert.assertSame(actual, sorted);
Assert.assertEquals(Interval.oneTo(1000), actual);
}
@Test
public void sortThis_with_comparator_small()
{
MutableList<Integer> actual = this.newWith(1, 2, 3);
Collections.shuffle(actual);
MutableList<Integer> sorted = actual.sortThis(Collections.<Integer>reverseOrder());
Assert.assertSame(actual, sorted);
Assert.assertEquals(FastList.newListWith(3, 2, 1), actual);
}
@Test
public void sortThis_with_comparator()
{
MutableList<Integer> actual = this.newWith(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
Collections.shuffle(actual);
MutableList<Integer> sorted = actual.sortThis(Collections.<Integer>reverseOrder());
Assert.assertSame(actual, sorted);
Assert.assertEquals(FastList.newListWith(10, 9, 8, 7, 6, 5, 4, 3, 2, 1), actual);
}
@Test
public void sortThis_with_comparator_large()
{
MutableList<Integer> actual = this.newWith(Interval.oneTo(1000).toArray());
Collections.shuffle(actual);
MutableList<Integer> sorted = actual.sortThis(Collections.<Integer>reverseOrder());
Assert.assertSame(actual, sorted);
Assert.assertEquals(Interval.fromToBy(1000, 1, -1), actual);
}
@Test
public void sortThisBy()
{
MutableList<Integer> actual = this.newWith(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
Collections.shuffle(actual);
MutableList<Integer> sorted = actual.sortThisBy(String::valueOf);
Assert.assertSame(actual, sorted);
Assert.assertEquals(FastList.newListWith(1, 10, 2, 3, 4, 5, 6, 7, 8, 9), actual);
}
@Override
@Test
public void newEmpty()
{
Verify.assertInstanceOf(ArrayListAdapter.class, ArrayListAdapter.newList().newEmpty());
}
@Test
public void distinct()
{
ArrayListAdapter<Integer> arrayListAdapter = ArrayListAdapter.<Integer>newList().with(3, 2, 1, 1, 2, 3);
Verify.assertListsEqual(FastList.newListWith(3, 2, 1), arrayListAdapter.distinct());
}
@Test
public void testForEachWithFromTo()
{
MutableList<Integer> result1 = Lists.mutable.of();
this.newWith(1, 2, 3).forEach(1, 2, CollectionAddProcedure.on(result1));
Assert.assertEquals(FastList.newListWith(2, 3), result1);
}
@Test
public void testForEachWithIndexWithFromTo()
{
MutableList<Integer> result1 = Lists.mutable.of();
this.newWith(1, 2, 3).forEachWithIndex(1, 2, new AddToList(result1));
Assert.assertEquals(FastList.newListWith(2, 3), result1);
}
@Test
public void testForEachWithFromToWithCommandoPatternOptimization()
{
MutableList<Integer> result2 = Lists.mutable.of();
// Requires list of 100+ elements to engage commando pattern optimization
ArrayListAdapter.adapt(new ArrayList<Integer>(Interval.oneTo(200))).forEach(99, 199, CollectionAddProcedure.on(result2));
Verify.assertSize(101, result2);
}
@Test
public void testForEachWithIndexWithFromToWithCommandoPatternOptimization()
{
MutableList<Integer> result2 = Lists.mutable.of();
// Requires list of 100+ elements to engage commando pattern optimization
ArrayListAdapter.adapt(new ArrayList<Integer>(Interval.oneTo(200))).forEachWithIndex(99, 199, new AddToList(result2));
Verify.assertSize(101, result2);
}
@Test
public void takeWhile()
{
Assert.assertEquals(
iList(1, 2, 3),
this.newWith(1, 2, 3, 4, 5).takeWhile(Predicates.lessThan(4)));
}
@Test
public void dropWhile()
{
Assert.assertEquals(
iList(4, 5),
this.newWith(1, 2, 3, 4, 5).dropWhile(Predicates.lessThan(4)));
}
@Test
public void partitionWhile()
{
PartitionMutableList<Integer> partition = this.newWith(1, 2, 3, 4, 5).partitionWhile(Predicates.lessThan(4));
MutableList<Integer> selected = partition.getSelected();
MutableList<Integer> rejected = partition.getRejected();
Assert.assertEquals(iList(1, 2, 3), selected);
Assert.assertEquals(iList(4, 5), rejected);
}
@Test
public void reverseForEach()
{
MutableList<Integer> result = Lists.mutable.of();
MutableList<Integer> collection = this.newWith(1, 2, 3, 4);
collection.reverseForEach(CollectionAddProcedure.on(result));
Assert.assertEquals(FastList.newListWith(4, 3, 2, 1), result);
}
}
|
czs/lhjz
|
src/main/java/com/canzs/lhjz/component/AjaxJsonView.java
|
<filename>src/main/java/com/canzs/lhjz/component/AjaxJsonView.java
package com.canzs.lhjz.component;
import java.io.PrintWriter;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.view.AbstractView;
import com.canzs.lhjz.pojo.constant.SysConstant;
import com.canzs.lhjz.util.JsonUtil;
import com.canzs.lhjz.util.StringUtil;
@Component
public class AjaxJsonView extends AbstractView {
private static Logger logger = Logger.getLogger(AjaxJsonView.class);
@Override
protected void renderMergedOutputModel(Map<String, Object> map, HttpServletRequest request,
HttpServletResponse response) throws Exception {
response.setCharacterEncoding("utf-8");
response.setContentType("text/html; charset=UTF-8");
// Set standard HTTP/1.1 no-cache headers.
response.setHeader("Cache-Control", "no-store, max-age=0, no-cache, must-revalidate");
// Set IE extended HTTP/1.1 no-cache headers.
response.addHeader("Cache-Control", "post-check=0, pre-check=0");
// Set standard HTTP/1.0 no-cache header.
response.setHeader("Pragma", "no-cache");
Object modelObject = map.get(SysConstant.MODEL_NAME_AJAX_JSON);
String callback = request.getParameter("callback");
if (StringUtil.isEmpty(callback)) {
callback = StringUtil.toString(map.get(SysConstant.CALLBACK));
}
PrintWriter writer = response.getWriter();
String backString = null;
if (StringUtil.isNotEmpty(callback)) {
backString = StringUtil.replace("{?1}({?2})", callback, JsonUtil.toJson(modelObject));
} else {
backString = JsonUtil.toJson(modelObject);
}
logger.debug(backString);
writer.write(backString);
writer.flush();
// writer.close();
}
}
|
nimetozk/budgeting-app-frontend
|
src/components/Controls/SelectionCountryList.js
|
<filename>src/components/Controls/SelectionCountryList.js
/**
A component created using the react-select.js library
It is implemented to provde input control on country selections.
To understand the implementation of the library,I have used the
documentation provided on: https://react-select.com/home
*/
import react, { useEffect, useState } from "react";
import Select from "react-select";
import { countryList } from "../../utility";
const SelectionCountry = ({ value, onCountryChange }) => {
const [options, setOptions] = useState([]);
useEffect(() => {
const tempOptions = [];
countryList.forEach((country) => {
tempOptions.push({ value: country.code, label: country.name });
});
setOptions(tempOptions);
}, []);
return (
<Select value={value} onChange={onCountryChange} options={options}></Select>
);
};
export default SelectionCountry;
|
futureseadev/hgwxx7
|
python/language/performance/performance_pandas_stopwords_1.py
|
# import libraries
import re
import tkinter
import pandas as pd
from timeit import timeit
import matplotlib.pyplot as plt
df = pd.DataFrame(
{
"ID": [1, 2, 3, 4, 5],
"name": [
"Hello Kitty",
"Hello Puppy",
"It is an Helloexample",
"for stackoverflow",
"Hello World",
],
}
)
stopwords = ["Hello", "for", "an", "It"]
# function 1
def fun1(df):
return df['name'].str.replace('|'.join(stopwords), '')
# function 2
def fun2(df):
p = re.compile('|'.join(map(re.escape, stopwords)))
return [p.sub('', text) for text in df['name']]
# function 3
def fun3(df):
return df['name'].replace(stopwords, value='', regex=True)
# create a pandas dataframe
# index has the list of functions
# columns has the multiplication factor -
# to increase input list size (thereby complexity)
res = pd.DataFrame(
index=['fun1', 'fun2', 'fun3',],
columns=[1, 10, 25, 50, 100, 500, 1000, 5000,] # 10000, 50000, 100000,] # 1000000],
)
# each function to be looped over the mul.factors
# timeit is used and output to dataframe
for f in res.index:
for c in res.columns:
l = pd.concat([df] * c)
stmt = '{}(l)'.format(f) # f(l)
setp = 'from __main__ import l, {}'.format(f)
res.at[f, c] = timeit(stmt, setp, number=50)
# using matplotlib to plot
ax = res.div(res.min()).T.plot(loglog=True)
ax.set_xlabel("N")
ax.set_ylabel("time (relative)")
plt.show()
|
Amihozar/lp-components
|
src/forms/buttons/index.js
|
<reponame>Amihozar/lp-components
export Button from './button'
export ButtonArea from './button-area'
export SubmitButton from './submit-button'
|
bcgov/foi-flow
|
request-management-api/request_api/models/FOIRawRequests.py
|
from enum import unique
from flask.app import Flask
from sqlalchemy.sql.schema import ForeignKey, ForeignKeyConstraint
from sqlalchemy.sql.expression import distinct
from .db import db, ma
from sqlalchemy.dialects.postgresql import JSON, UUID
from .default_method_result import DefaultMethodResult
from datetime import datetime
from sqlalchemy.orm import relationship,backref
from sqlalchemy import insert, and_, text
from flask import jsonify
class FOIRawRequest(db.Model):
# Name of the table in our database
__tablename__ = 'FOIRawRequests'
# Defining the columns
requestid = db.Column(db.Integer, primary_key=True,autoincrement=True)
version = db.Column(db.Integer, primary_key=True,nullable=False)
requestrawdata = db.Column(JSON, unique=False, nullable=True)
status = db.Column(db.String(25), unique=False, nullable=True)
notes = db.Column(db.String(120), unique=False, nullable=True)
wfinstanceid = db.Column(UUID(as_uuid=True), unique=False, nullable=True)
assignedgroup = db.Column(db.String(250), unique=False, nullable=True)
assignedto = db.Column(db.String(120), unique=False, nullable=True)
created_at = db.Column(db.DateTime, default=datetime.now())
updated_at = db.Column(db.DateTime, nullable=True)
createdby = db.Column(db.String(120), unique=False, nullable=True)
updatedby = db.Column(db.String(120), unique=False, nullable=True)
sourceofsubmission = db.Column(db.String(120), nullable=True)
ispiiredacted = db.Column(db.Boolean, unique=False, nullable=False,default=False)
closedate = db.Column(db.DateTime, nullable=True)
requirespayment = db.Column(db.Boolean, unique=False, nullable=True, default=False)
closereasonid = db.Column(db.Integer,ForeignKey('CloseReasons.closereasonid'))
closereason = relationship("CloseReason", uselist=False)
@classmethod
def saverawrequest(cls,_requestrawdata,sourceofsubmission, ispiiredacted, userid, notes, requirespayment ,assigneegroup= None,assignee= None)->DefaultMethodResult:
createdat = datetime.now()
version = 1
newrawrequest = FOIRawRequest(requestrawdata=_requestrawdata, status='Unopened' if sourceofsubmission != "intake" else 'Intake in Progress',created_at=createdat,createdby=userid,version=version,sourceofsubmission=sourceofsubmission,assignedgroup=assigneegroup,assignedto=assignee,ispiiredacted=ispiiredacted,notes=notes, requirespayment=requirespayment)
db.session.add(newrawrequest)
db.session.commit()
return DefaultMethodResult(True,'Request added',newrawrequest.requestid)
@classmethod
def saverawrequest_foipayment(cls,_requestrawdata,notes, requirespayment, ispiiredacted)->DefaultMethodResult:
createdat = datetime.now()
version = 1
newrawrequest = FOIRawRequest(requestrawdata=_requestrawdata, status='Unopened',created_at=createdat,createdby=None,version=version,sourceofsubmission="onlineform",assignedgroup=None,assignedto=None,ispiiredacted=ispiiredacted,notes=notes, requirespayment= requirespayment)
db.session.add(newrawrequest)
db.session.commit()
return DefaultMethodResult(True,'Request added',newrawrequest.requestid)
@classmethod
def saverawrequestversion(cls,_requestrawdata,requestid, assigneegroup, assignee,status,ispiiredacted, userid)->DefaultMethodResult:
request = db.session.query(FOIRawRequest).filter_by(requestid=requestid).order_by(FOIRawRequest.version.desc()).first()
if request is not None:
closedate = _requestrawdata["closedate"] if 'closedate' in _requestrawdata else None
closereasonid = _requestrawdata["closereasonid"] if 'closereasonid' in _requestrawdata else None
_version = request.version+1
insertstmt =(
insert(FOIRawRequest).
values(
requestid=request.requestid,
requestrawdata=_requestrawdata,
version=_version,
updatedby=None,
updated_at=datetime.now(),
status=status,
assignedgroup=assigneegroup,
assignedto=assignee,
wfinstanceid=request.wfinstanceid,
sourceofsubmission=request.sourceofsubmission,
ispiiredacted=ispiiredacted,
createdby=userid,
closedate=closedate,
closereasonid=closereasonid,
)
)
db.session.execute(insertstmt)
db.session.commit()
return DefaultMethodResult(True,'Request versioned - {0}'.format(str(_version)),requestid,request.wfinstanceid,assignee)
else:
return DefaultMethodResult(True,'No request foound')
@classmethod
def updateworkflowinstance(cls,wfinstanceid,requestid, userid)->DefaultMethodResult:
updatedat = datetime.now()
dbquery = db.session.query(FOIRawRequest)
requestraqw = dbquery.filter_by(requestid=requestid,version = 1)
if(requestraqw.count() > 0) :
existingrequestswithwfid = dbquery.filter_by(wfinstanceid=wfinstanceid)
if(existingrequestswithwfid.count() == 0) :
requestraqw.update({FOIRawRequest.wfinstanceid:wfinstanceid, FOIRawRequest.updated_at:updatedat,FOIRawRequest.updatedby:userid, FOIRawRequest.notes:"WF Instance created"}, synchronize_session = False)
db.session.commit()
return DefaultMethodResult(True,'Request updated with WF Instance Id',requestid)
else:
return DefaultMethodResult(False,'WF instance already exists',requestid)
else:
return DefaultMethodResult(False,'Requestid not exists',-1)
@classmethod
def updateworkflowinstancewithstatus(cls,wfinstanceid,requestid,status,notes,userid)-> DefaultMethodResult:
updatedat = datetime.now()
dbquery = db.session.query(FOIRawRequest)
_requestraqw = dbquery.filter_by(requestid=requestid).order_by(FOIRawRequest.version.desc()).first()
requestraqw = dbquery.filter_by(requestid=requestid,version = _requestraqw.version)
if(requestraqw.count() > 0) :
request_schema = FOIRawRequestSchema()
request = request_schema.dump(_requestraqw)
if(request is not None and (request["status"] == "Redirect" or request["status"] == "Closed")):
status = request["status"]
requestraqw.update({FOIRawRequest.wfinstanceid:wfinstanceid, FOIRawRequest.updated_at:updatedat,FOIRawRequest.notes:notes,FOIRawRequest.status:status,FOIRawRequest.updatedby:userid}, synchronize_session = False)
db.session.commit()
return DefaultMethodResult(True,'Request updated',requestid)
else:
return DefaultMethodResult(False,'Requestid not exists',-1)
@classmethod
def getrequests(cls):
_session = db.session
_archivedrequestids = _session.query(distinct(FOIRawRequest.requestid)).filter(FOIRawRequest.status.in_(['Archived'])).all()
_requestids = _session.query(distinct(FOIRawRequest.requestid)).filter(FOIRawRequest.requestid.notin_(_archivedrequestids)).all()
requests = []
for _requestid in _requestids:
request = _session.query(FOIRawRequest).filter(FOIRawRequest.requestid == _requestid).order_by(FOIRawRequest.version.desc()).first()
requests.append(request)
return requests
@classmethod
def getDescriptionSummaryById(cls, requestid):
sql = """select CASE WHEN lower(status) <> 'unopened' then requestrawdata ->> 'description' ELSE requestrawdata -> 'descriptionTimeframe' ->> 'description' END as description ,
CASE WHEN lower(status) <> 'unopened' then requestrawdata ->> 'fromDate' ELSE requestrawdata -> 'descriptionTimeframe' ->> 'fromDate' END as fromdate,
CASE WHEN lower(status) <> 'unopened'then requestrawdata ->> 'toDate' ELSE requestrawdata -> 'descriptionTimeframe' ->> 'toDate' END as todate,
to_char(updated_at, 'YYYY-MM-DD HH24:MI:SS') as createdat, status, ispiiredacted,
CASE WHEN lower(status) <> 'unopened' then createdby else 'Online Form' END as createdby from "FOIRawRequests" fr
where requestid = :requestid order by version ;"""
rs = db.session.execute(text(sql), {'requestid': requestid})
requests = []
for row in rs:
requests.append(dict(row))
return requests
@classmethod
def get_request(cls,requestid):
request_schema = FOIRawRequestSchema()
request = db.session.query(FOIRawRequest).filter_by(requestid=requestid).order_by(FOIRawRequest.version.desc()).first()
return request_schema.dump(request)
@classmethod
def getLastStatusUpdateDate(cls,requestid,status):
sql = """select created_at from "FOIRawRequests"
where requestid = :requestid and status = :status
order by version desc limit 1;"""
rs = db.session.execute(text(sql), {'requestid': requestid, 'status': status})
return [row[0] for row in rs][0]
@classmethod
def getassignmenttransition(cls,requestid):
sql = """select version, assignedto, status from "FOIRawRequests"
where requestid = :requestid
order by version desc limit 2;"""
rs = db.session.execute(text(sql), {'requestid': requestid})
assignments = []
for row in rs:
assignments.append({"assignedto": row["assignedto"], "status": row["status"], "version": row["version"]})
return assignments
@classmethod
def getversionforrequest(cls,requestid):
return db.session.query(FOIRawRequest.version).filter_by(requestid=requestid).order_by(FOIRawRequest.version.desc()).first()
@classmethod
def getstatesummary(cls, requestid):
sql = """select status, version from (select distinct on (status) status, version from "FOIRawRequests"
where requestid=:requestid order by status, version asc) as fs3 order by version desc"""
rs = db.session.execute(text(sql), {'requestid': requestid})
transitions = []
for row in rs:
transitions.append({"status": row["status"], "version": row["version"]})
return transitions
@classmethod
def getstatenavigation(cls, requestid):
_session = db.session
_requeststates = _session.query(FOIRawRequest.status).filter(FOIRawRequest.requestid == requestid).order_by(FOIRawRequest.version.desc()).limit(2)
requeststates = []
for _requeststate in _requeststates:
requeststates.append(_requeststate[0])
return requeststates
class FOIRawRequestSchema(ma.Schema):
class Meta:
fields = ('requestid', 'requestrawdata', 'status','notes','created_at','wfinstanceid','version','updated_at','assignedgroup','assignedto','updatedby','createdby','sourceofsubmission','ispiiredacted')
|
SCV/enso
|
engine/runtime/src/test/scala/org/enso/compiler/test/pass/desugar/FunctionBindingTest.scala
|
<reponame>SCV/enso
package org.enso.compiler.test.pass.desugar
import org.enso.compiler.Passes
import org.enso.compiler.context.{InlineContext, ModuleContext}
import org.enso.compiler.core.IR
import org.enso.compiler.pass.desugar.FunctionBinding
import org.enso.compiler.pass.{IRPass, PassConfiguration, PassManager}
import org.enso.compiler.test.CompilerTest
class FunctionBindingTest extends CompilerTest {
// === Test Setup ===========================================================
val passes = new Passes
val precursorPasses: List[IRPass] = passes.getPrecursors(FunctionBinding).get
val passConfig: PassConfiguration = PassConfiguration()
implicit val passManager: PassManager =
new PassManager(precursorPasses, passConfig)
/** Adds an extension method to run method and function desugaring on an
* [[IR.Module]].
*
* @param ir the module to run desugaring on
*/
implicit class DesugarModule(ir: IR.Module) {
/** Runs desugaring on a module.
*
* @param moduleContext the module context in which desugaring is taking
* place
* @return [[ir]], with any sugared function and method definitions
* desugared
*/
def desugar(implicit moduleContext: ModuleContext): IR.Module = {
FunctionBinding.runModule(ir, moduleContext)
}
}
/** Adds an extension method to run function desugaring on an arbitrary
* expression.
*
* @param ir the expression to desugar
*/
implicit class DesugarExpression(ir: IR.Expression) {
/** Runs desgaring on an expression.
*
* @param inlineContext the inline context in which the desugaring is
* taking place
* @return [[ir]], with any sugared function definitions desugared
*/
def desugar(implicit inlineContext: InlineContext): IR.Expression = {
FunctionBinding.runExpression(ir, inlineContext)
}
}
/** Creates a defaulted module context.
*
* @return a defaulted module context
*/
def mkModuleContext: ModuleContext = {
ModuleContext()
}
/** Creates a defaulted inline context.
*
* @return a defaulted inline context
*/
def mkInlineContext: InlineContext = {
InlineContext()
}
// === The Tests ============================================================
"Sugared method definitions" should {
implicit val ctx: ModuleContext = mkModuleContext
val ir =
"""
|Unit.foo ~a _ (c = 1) = a + c
|""".stripMargin.preprocessModule.desugar
"desugar to standard method definitions" in {
ir.bindings.head shouldBe an[IR.Module.Scope.Definition.Method.Explicit]
}
val explicitMethod =
ir.bindings.head.asInstanceOf[IR.Module.Scope.Definition.Method.Explicit]
"have the function arguments in the body functions" in {
val lambda1 = explicitMethod.body.asInstanceOf[IR.Function.Lambda]
val lambda2 = lambda1.body.asInstanceOf[IR.Function.Lambda]
val lambda3 = lambda2.body.asInstanceOf[IR.Function.Lambda]
val cArg =
lambda3.arguments.head.asInstanceOf[IR.DefinitionArgument.Specified]
lambda1.arguments.head
.asInstanceOf[IR.DefinitionArgument.Specified]
.suspended shouldEqual true
lambda1.arguments.head.name.name shouldEqual "a"
lambda2.arguments.head
.asInstanceOf[IR.DefinitionArgument.Specified]
.name shouldBe an[IR.Name.Blank]
cArg.name.name shouldEqual "c"
cArg.defaultValue shouldBe defined
}
"desugar nested sugared functions" in {
val ir =
"""
|Foo.bar a =
| f b = b
| f 1
|""".stripMargin.preprocessModule.desugar
val body = ir.bindings.head
.asInstanceOf[IR.Module.Scope.Definition.Method.Explicit]
.body
.asInstanceOf[IR.Function.Lambda]
.body
.asInstanceOf[IR.Expression.Block]
body.expressions.head shouldBe an[IR.Expression.Binding]
val binding = body.expressions.head.asInstanceOf[IR.Expression.Binding]
binding.expression shouldBe an[IR.Function.Lambda]
}
"desugar module-level methods" in {
val ir =
"""
|foo x =
| y -> x + y
|""".stripMargin.preprocessModule.desugar
ir.bindings.head shouldBe an[IR.Module.Scope.Definition.Method.Explicit]
}
}
"Sugared function definitions" should {
implicit val ctx: InlineContext = mkInlineContext
val ir =
"""
|f ~a _ (c = 1) = a + b * c
|""".stripMargin.preprocessExpression.get.desugar
"desugar to a binding with a lambda" in {
ir shouldBe an[IR.Expression.Binding]
val binding = ir.asInstanceOf[IR.Expression.Binding]
binding.name.name shouldEqual "f"
binding.expression shouldBe an[IR.Function.Lambda]
}
"work properly for complex argument definition types" in {
val lambda1 = ir
.asInstanceOf[IR.Expression.Binding]
.expression
.asInstanceOf[IR.Function.Lambda]
val lambda2 = lambda1.body.asInstanceOf[IR.Function.Lambda]
val lambda3 = lambda2.body.asInstanceOf[IR.Function.Lambda]
val cArg =
lambda3.arguments.head.asInstanceOf[IR.DefinitionArgument.Specified]
lambda1.arguments.head
.asInstanceOf[IR.DefinitionArgument.Specified]
.suspended shouldEqual true
lambda2.arguments.head
.asInstanceOf[IR.DefinitionArgument.Specified]
.name shouldBe an[IR.Name.Blank]
cArg.name.name shouldEqual "c"
cArg.defaultValue shouldBe defined
}
"work recursively" in {
val ir =
"""
|f (a = (f a = a)) =
| g b = b
| g 1
|""".stripMargin.preprocessExpression.get.desugar
.asInstanceOf[IR.Expression.Binding]
val aArg = ir.expression
.asInstanceOf[IR.Function.Lambda]
.arguments
.head
.asInstanceOf[IR.DefinitionArgument.Specified]
aArg.name.name shouldEqual "a"
aArg.defaultValue.get
.asInstanceOf[IR.Expression.Binding]
.name
.name shouldEqual "f"
val body = ir.expression
.asInstanceOf[IR.Function.Lambda]
.body
.asInstanceOf[IR.Expression.Block]
body.expressions.head shouldBe an[IR.Expression.Binding]
val gBinding = body.expressions.head.asInstanceOf[IR.Expression.Binding]
gBinding.name.name shouldEqual "g"
gBinding.expression shouldBe an[IR.Function.Lambda]
}
}
}
|
maricaantonacci/alien4cloud
|
alien4cloud-ui/src/main/webapp/scripts/meta-props/controllers/meta_props_conf.js
|
<filename>alien4cloud-ui/src/main/webapp/scripts/meta-props/controllers/meta_props_conf.js
define(function (require) {
'use strict';
var modules = require('modules');
var states = require('states');
require('scripts/meta-props/services/meta_props_conf_services');
require('scripts/common/directives/generic_form');
require('scripts/common/services/formdescriptor_services');
var state = 'admin.metaprops.detail';
states.state(state, {
url: '/details/:id',
templateUrl: 'views/meta-props/meta_props_conf.html',
controller: 'MetaPropsConfCtrl'
});
modules.get('a4c-metas', ['a4c-common']).controller('MetaPropsConfCtrl',
['$scope', '$stateParams', '$state', 'metapropConfServices', 'formDescriptorServices',
function($scope, $stateParams, $state, metapropConfServices, formDescriptorServices) {
$scope.refreshDetails = function() {
metapropConfServices.get($stateParams.id).then(function(config) {
$scope.configuration = config;
$scope.formTitle = config.name;
});
};
$scope.refreshDetails();
formDescriptorServices.getTagConfigurationDescriptor.get({}, function(success) {
$scope.objectDefinition = success.data;
});
$scope.saveTagConfiguration = function(config) {
return metapropConfServices.save(config).then(function(response) {
return metapropConfServices.processValidationErrors(response.validationErrors);
});
};
$scope.removeTagConfiguration = function() {
metapropConfServices.remove($stateParams.id).then(function() {
$state.go('admin.metaprops.list');
});
};
$scope.cancelTagConfigurationCreation = function() {
$state.go('admin.metaprops.list');
};
}]);
return state;
});
|
kpgangat/quality-measure-and-cohort-service
|
cohort-evaluator/src/main/java/com/ibm/cohort/cql/evaluation/CqlDebug.java
|
/*
* (C) Copyright IBM Corp. 2021, 2021
*
* SPDX-License-Identifier: Apache-2.0
*/
package com.ibm.cohort.cql.evaluation;
public enum CqlDebug {
NONE, DEBUG, TRACE
}
|
C2Talon/kolmafia
|
src/net/sourceforge/kolmafia/request/CosmicRaysBazaarRequest.java
|
package net.sourceforge.kolmafia.request;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import net.java.dev.spellcast.utilities.LockableListModel;
import net.sourceforge.kolmafia.AdventureResult;
import net.sourceforge.kolmafia.AdventureResult.AdventureLongCountResult;
import net.sourceforge.kolmafia.CoinmasterData;
import net.sourceforge.kolmafia.KoLCharacter;
import net.sourceforge.kolmafia.objectpool.IntegerPool;
import net.sourceforge.kolmafia.objectpool.ItemPool;
import net.sourceforge.kolmafia.persistence.CoinmastersDatabase;
public class CosmicRaysBazaarRequest extends CoinMasterRequest {
public static final String master = "<NAME>";
private static final LockableListModel<AdventureResult> buyItems =
CoinmastersDatabase.getBuyItems(CosmicRaysBazaarRequest.master);
private static final Map<Integer, Integer> buyPrices = CoinmastersDatabase.getNewMap();
private static final Map<Integer, Integer> itemRows =
CoinmastersDatabase.getRows(CosmicRaysBazaarRequest.master);
public static final AdventureResult RARE_MEAT_ISOTOPE =
ItemPool.get(ItemPool.RARE_MEAT_ISOTOPE, 1);
public static final AdventureResult WHITE_PIXEL = ItemPool.get(ItemPool.WHITE_PIXEL, 1);
public static final AdventureResult FAT_LOOT_TOKEN = ItemPool.get(ItemPool.FAT_LOOT_TOKEN, 1);
public static final AdventureResult MEAT =
new AdventureLongCountResult(AdventureResult.MEAT, 1) {
@Override
public String toString() {
return this.getCount() + " Meat";
}
@Override
public String getPluralName(int price) {
return "Meat";
}
};
public static final CoinmasterData COSMIC_RAYS_BAZAAR =
new CoinmasterData(
CosmicRaysBazaarRequest.master,
"exploathing",
CosmicRaysBazaarRequest.class,
null,
null,
false,
null,
null,
null,
CosmicRaysBazaarRequest.itemRows,
"shop.php?whichshop=exploathing",
"buyitem",
CosmicRaysBazaarRequest.buyItems,
CosmicRaysBazaarRequest.buyPrices,
null,
null,
null,
null,
"whichrow",
GenericRequest.WHICHROW_PATTERN,
"quantity",
GenericRequest.QUANTITY_PATTERN,
null,
null,
true) {
@Override
public AdventureResult itemBuyPrice(final int itemId) {
return CosmicRaysBazaarRequest.buyCosts.get(IntegerPool.get(itemId));
}
};
// Since there are four different currencies, we need to have a map from
// itemId to item/count of currency; an AdventureResult.
private static final Map<Integer, AdventureResult> buyCosts =
new TreeMap<Integer, AdventureResult>();
// Manually set up the map and change the currency, as need
static {
for (Entry<Integer, Integer> entry :
CoinmastersDatabase.getBuyPrices(CosmicRaysBazaarRequest.master).entrySet()) {
int itemId = entry.getKey().intValue();
int price = entry.getValue().intValue();
AdventureResult cost = null;
switch (itemId) {
default:
cost = RARE_MEAT_ISOTOPE.getInstance(price);
break;
case ItemPool.DIGITAL_KEY:
cost = WHITE_PIXEL.getInstance(price);
break;
case ItemPool.BORIS_KEY:
case ItemPool.JARLSBERG_KEY:
case ItemPool.SNEAKY_PETE_KEY:
cost = FAT_LOOT_TOKEN.getInstance(price);
break;
case ItemPool.RARE_MEAT_ISOTOPE:
cost = MEAT.getInstance(price);
break;
}
buyCosts.put(itemId, cost);
}
}
public CosmicRaysBazaarRequest() {
super(CosmicRaysBazaarRequest.COSMIC_RAYS_BAZAAR);
}
public CosmicRaysBazaarRequest(final String action) {
super(CosmicRaysBazaarRequest.COSMIC_RAYS_BAZAAR, action);
}
public CosmicRaysBazaarRequest(final boolean buying, final AdventureResult[] attachments) {
super(CosmicRaysBazaarRequest.COSMIC_RAYS_BAZAAR, buying, attachments);
}
public CosmicRaysBazaarRequest(final boolean buying, final AdventureResult attachment) {
super(CosmicRaysBazaarRequest.COSMIC_RAYS_BAZAAR, buying, attachment);
}
public CosmicRaysBazaarRequest(final boolean buying, final int itemId, final int quantity) {
super(CosmicRaysBazaarRequest.COSMIC_RAYS_BAZAAR, buying, itemId, quantity);
}
@Override
public void run() {
if (this.action != null) {
this.addFormField("pwd");
}
super.run();
}
@Override
public void processResults() {
CosmicRaysBazaarRequest.parseResponse(this.getURLString(), this.responseText);
}
public static void parseResponse(final String location, final String responseText) {
if (!location.contains("whichshop=exploathing")) {
return;
}
CoinmasterData data = CosmicRaysBazaarRequest.COSMIC_RAYS_BAZAAR;
String action = GenericRequest.getAction(location);
if (action != null) {
CoinMasterRequest.parseResponse(data, location, responseText);
return;
}
// Parse current coin balances
CoinMasterRequest.parseBalance(data, responseText);
}
public static String accessible() {
if (!KoLCharacter.isKingdomOfExploathing()) {
return "The Kingdom is not Exploathing";
}
return null;
}
public static boolean registerRequest(final String urlString) {
if (!urlString.startsWith("shop.php") || !urlString.contains("whichshop=exploathing")) {
return false;
}
CoinmasterData data = CosmicRaysBazaarRequest.COSMIC_RAYS_BAZAAR;
return CoinMasterRequest.registerRequest(data, urlString, true);
}
}
|
cheremin/scalarization
|
lab/src/main/java/ru/cheremin/scalarization/lab/tricky/NewRunnableScenario.java
|
package ru.cheremin.scalarization.lab.tricky;
import java.util.*;
import java.util.concurrent.Callable;
import ru.cheremin.scalarization.AllocationScenario;
import ru.cheremin.scalarization.ScenarioRun;
import ru.cheremin.scalarization.infra.ScenarioRunArgs;
import ru.cheremin.scalarization.lab.Utils.Pool;
import static ru.cheremin.scalarization.lab.Utils.randomStringsPool;
/**
* In original paper (Choi99) there was a simplification which conservatively assumes
* any Runnable instance as escaping. I've checked, and currently this is not true:
* Runnable/Callable instances are scalarized as an ordinary objects.
*
* @author ruslan
* created 10/02/16 at 15:11
*/
public class NewRunnableScenario extends AllocationScenario {
private final Pool<String> generator = randomStringsPool( 1024 );
@Override
public long run() {
final ImplementsRunnable object = new ImplementsRunnable(
generator.next()
);
object.run();
return object.name.length();
}
@ScenarioRunArgs
public static List<ScenarioRun> parametersToRunWith() {
return ScenarioRun.withoutSpecificParameters();
}
public static class ImplementsRunnable implements Runnable {
public final String name;
public ImplementsRunnable( final String name ) {
this.name = name;
}
@Override
public void run() {
//nothing
}
}
public static class ImplementsCallable implements Callable<String> {
public final String name;
public ImplementsCallable( final String name ) {
this.name = name;
}
@Override
public String call() {
return null;
}
}
}
|
PengHuang0508/demo-reactjs-website
|
src/components/NavigationSidebar/NavigationSidebar.js
|
import React from "react";
import { stack as Menu } from "react-burger-menu";
import LanguageSwitcherMobile from "../LanguageSwitcherMobile";
class NavigationSidebar extends React.Component {
render() {
var styles = {
bmBurgerButton: {
height: "40px",
left: "25px",
position: "fixed",
top: "25px",
width: "46px",
},
bmBurgerBars: {
background: "#4287f5",
},
bmCrossButton: {
height: "30px",
width: "30px",
},
bmCross: {
height: "20px",
background: "rgb(0, 0, 0)",
},
bmMenu: {
background: "rgba(242, 245, 220, 0.95)",
fontSize: "1em",
height: "100vh",
overflow: "hidden",
padding: "1em 1em 0",
},
bmMorphShape: {
fill: "rgb(55, 60, 70)",
},
bmItemList: {
color: "rgb(185, 185, 175)",
padding: "0.8em",
},
bmOverlay: {
background: "rgba(0, 0, 0, 0.3)",
},
};
var itemStyle = {
color: "#373a47",
fontWeight: "bold",
letterSpacing: "0.5pt",
padding: "20px 0",
};
var iconStyle = {
width: "40px",
};
const items = [
<a key="0" href="/" style={itemStyle}>
<i className="fa fa-home" style={iconStyle} />
<span>Home</span>
</a>,
<a key="1" href="/about" style={itemStyle}>
<i className="fa fa-hospital" style={iconStyle} />
<span>About</span>
</a>,
<a key="2" href="/services" style={itemStyle}>
<i className="fa fa-paw" style={iconStyle} />
<span>Services</span>
</a>,
<a key="3" href="/resources" style={itemStyle}>
<i className="fa fa-file-alt" style={iconStyle} />
<span>Resources</span>
</a>,
<a key="4" href="/contact" style={itemStyle}>
<i className="fa fa-phone" style={iconStyle} />
<span>Contact</span>
</a>,
<a key="5" style={itemStyle}>
<i className="fa fa-language" style={iconStyle} />
<LanguageSwitcherMobile />
</a>,
];
return <Menu styles={styles}>{items}</Menu>;
}
}
export default NavigationSidebar;
|
wolfgangimig/joa
|
java/joa/src-gen/com/wilutions/mslib/outlook/_ColumnFormat.java
|
/* ** GENEREATED FILE - DO NOT MODIFY ** */
package com.wilutions.mslib.outlook;
import com.wilutions.com.*;
/**
* _ColumnFormat.
*
*/
@CoInterface(guid="{0006309E-0000-0000-C000-000000000046}")
public interface _ColumnFormat extends IDispatch {
static boolean __typelib__loaded = __TypeLib.load();
@DeclDISPID(61440) public _Application getApplication() throws ComException;
@DeclDISPID(61450) public OlObjectClass getClass_() throws ComException;
@DeclDISPID(61451) public _NameSpace getSession() throws ComException;
@DeclDISPID(61441) public IDispatch getParent() throws ComException;
@DeclDISPID(64030) public String getLabel() throws ComException;
@DeclDISPID(64030) public void setLabel(final String value) throws ComException;
@DeclDISPID(64396) public Integer getFieldFormat() throws ComException;
@DeclDISPID(64396) public void setFieldFormat(final Integer value) throws ComException;
@DeclDISPID(8471) public Integer getWidth() throws ComException;
@DeclDISPID(8471) public void setWidth(final Integer value) throws ComException;
@DeclDISPID(64034) public OlAlign getAlign() throws ComException;
@DeclDISPID(64034) public void setAlign(final OlAlign value) throws ComException;
@DeclDISPID(64398) public OlUserPropertyType getFieldType() throws ComException;
}
|
DhivakharVenkatachalam/snet-dapp
|
src/components/ServiceDetails/AboutService/ServiceDemo/Purchase/ExpiredSession/GeneralAccountWallet/PaymentPopup/Details/styles.js
|
<reponame>DhivakharVenkatachalam/snet-dapp
export const useStyles = theme => ({
deatilsTabDesc: {
marginTop: 32,
color: theme.palette.text.mediumShadeGray,
fontFamily: theme.typography.primary.main,
fontSize: 16,
lineHeight: "24px",
},
providerAndBalanceInfo: {
padding: 25,
display: "flex",
justifyContent: "space-between",
alignItems: "center",
"@media(max-width:480px)": {
flexDirection: "column",
alignItems: "flex-start",
},
},
providerDetails: {
display: "flex",
alignItems: "center",
"& div": {
marginRight: 10,
},
"@media(max-width:480px)": { marginBottom: 25 },
},
providerName: {
color: theme.palette.text.darkShadedGray,
fontFamily: theme.typography.primary.main,
fontSize: 21,
letterSpacing: 0.15,
},
noOfService: {
color: theme.palette.text.lightShadedGray,
fontFamily: theme.typography.primary.main,
fontSize: 16,
},
dropDownTextfield: {
padding: "20px 55px 30px",
"@media(max-width:480px)": { padding: "20px 0 30px" },
},
dropDownTitle: {
padding: "0 5px",
position: "absolute",
top: -11,
left: 10,
backgroundColor: theme.palette.text.white,
color: theme.palette.text.dialogTitle,
fontSize: 12,
letterSpacing: 0.4,
},
infoIconContainer: {
marginRight: 10,
alignSelf: "center",
color: theme.palette.text.lightShadedGray,
fontSize: 20,
},
paymentTypeDropDownContainer: {
display: "flex",
"& fieldset": { display: "none" },
},
paymentTypeDropDown: {
width: "100%",
padding: "0 10px",
borderWidth: 1,
borderStyle: "solid",
borderColor: "rgba(25,25,25,0.32)",
borderRadius: 4,
display: "flex",
alignItems: "center",
position: "relative",
"& .MuiFormControl-root": {
width: "100%",
padding: "8px 0",
"& .MuiOutlinedInput-input": { padding: "7px 0 !important" },
"& fieldset": { color: `${theme.palette.text.grayTitleText} !important`, border: "none" },
},
},
purchaseAmtTextfield: {
paddingLeft: 30,
paddingRight: 22,
"& > div": {
width: "100%",
marginTop: 25,
},
"& p": {
marginLeft: 15,
fontFamily: theme.typography.primary.main,
fontSize: 12,
color: "#444",
letterSpacing: 0.4,
lineHeight: "16px",
paddingTop: 5,
},
},
btnContainer: {
display: "flex",
justifyContent: "center",
},
});
|
chs6558/chs6558.github.io
|
node_modules/styled-icons/fa-solid/CircleNotch/CircleNotch.esm.js
|
<reponame>chs6558/chs6558.github.io
export * from '@styled-icons/fa-solid/CircleNotch';
|
fhornain/patternfly-react-seed_1
|
node_modules/@patternfly/react-icons/dist/js/icons/microchip-icon.d.js
|
"use strict";
//# sourceMappingURL=microchip-icon.d.js.map
|
kaituo/sedge
|
trunk/src-kaituo/edu/umass/cs/pig/Hide.java
|
<reponame>kaituo/sedge<filename>trunk/src-kaituo/edu/umass/cs/pig/Hide.java
package edu.umass.cs.pig;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
* Use this annotation to hide a MainConfig option
* from being printed.
*
* @author <EMAIL> (<NAME>)
*/
@Retention(RetentionPolicy.RUNTIME)
public @interface Hide {
// empty
}
|
GoatGirl98/cf
|
contest/1251/a/a.cpp
|
<gh_stars>0
#include<bits/stdc++.h>
using namespace std;
using LL = long long;
int main(){
//freopen("in", "r", stdin);
std::ios::sync_with_stdio(false);std::cin.tie(nullptr);
int cas;
cin>>cas;
while(cas--){
string a;
cin>>a;
int n = a.length();
bool v[26]={};
for(int i=0;i<n;++i){
if(i==n-1){
v[a[i]-'a'] = 1;
}else{
if(a[i]==a[i+1]) ++i;
else v[a[i]-'a'] = 1;
}
}
for(int i=0;i<26;++i){
if(v[i]) cout<<char('a'+i);
}
cout<<endl;
}
return 0;
}
|
tarunj116/GarageCustomer
|
node_modules/@rpldy/shared-ui/lib/esm/utils.js
|
import { useEffect, useState, useCallback } from "react";
import { isProduction } from "@rpldy/shared";
import { UPLOAD_OPTIONS_COMP } from "./consts";
import useUploadyContext from "./useUploadyContext";
const useEventEffect = (event, fn) => {
const context = useUploadyContext();
const {
on,
off
} = context;
useEffect(() => {
on(event, fn);
return () => {
off(event, fn);
};
}, [event, fn, on, off]);
};
const generateUploaderEventHookWithState = (event, stateCalculator) => (fn, id) => {
const [eventState, setEventState] = useState(null);
const eventCallback = useCallback((eventObj, ...args) => {
if (!id || eventObj.id === id) {
setEventState(stateCalculator(eventObj, ...args));
if (fn) {
fn(eventObj, ...args);
}
}
}, [fn, id]);
useEventEffect(event, eventCallback);
return eventState;
};
const generateUploaderEventHook = (event, canScope = true) => (fn, id) => {
const eventCallback = useCallback((eventObj, ...args) => {
return fn && (!canScope || !id || eventObj.id === id) ? fn(eventObj, ...args) : undefined;
}, [fn, id]);
useEventEffect(event, eventCallback);
};
const logWarning = (condition, msg) => {
if (!isProduction() && !condition) {
// eslint-disable-next-line no-console
console.warn(msg);
}
};
const markAsUploadOptionsComponent = Component => {
Component[UPLOAD_OPTIONS_COMP] = true;
};
const getIsUploadOptionsComponent = Component => {
var _Component$target, _Component$render;
return Component[UPLOAD_OPTIONS_COMP] === true || ((_Component$target = Component.target) === null || _Component$target === void 0 ? void 0 : _Component$target[UPLOAD_OPTIONS_COMP]) === true || ((_Component$render = Component.render) === null || _Component$render === void 0 ? void 0 : _Component$render[UPLOAD_OPTIONS_COMP]) === true;
};
export { generateUploaderEventHook, generateUploaderEventHookWithState, logWarning, markAsUploadOptionsComponent, getIsUploadOptionsComponent };
|
pavelerofeev/ontrack
|
ontrack-repository-impl/src/test/java/net/nemerosa/ontrack/repository/PropertyJdbcRepositoryIT.java
|
<reponame>pavelerofeev/ontrack
package net.nemerosa.ontrack.repository;
import com.fasterxml.jackson.core.JsonProcessingException;
import net.nemerosa.ontrack.json.JsonUtils;
import net.nemerosa.ontrack.model.structure.Project;
import net.nemerosa.ontrack.model.structure.ProjectEntityType;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import static net.nemerosa.ontrack.test.TestUtils.assertJsonEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
@Transactional
public class PropertyJdbcRepositoryIT extends AbstractRepositoryTestSupport {
@Autowired
private PropertyRepository repository;
private Project project;
private static final String PROPERTY_TYPE = "test";
@Before
public void create_project() {
project = do_create_project();
}
@Test
public void save_retrieve_delete_property() throws JsonProcessingException {
assertNull(repository.loadProperty(PROPERTY_TYPE, ProjectEntityType.PROJECT, project.getId()));
repository.saveProperty(PROPERTY_TYPE, ProjectEntityType.PROJECT, project.getId(), JsonUtils.object().with("value", 10).end());
TProperty t = repository.loadProperty(PROPERTY_TYPE, ProjectEntityType.PROJECT, project.getId());
assertNotNull(t);
assertJsonEquals(
JsonUtils.object().with("value", 10).end(),
t.getJson()
);
repository.deleteProperty(PROPERTY_TYPE, ProjectEntityType.PROJECT, project.getId());
assertNull(repository.loadProperty(PROPERTY_TYPE, ProjectEntityType.PROJECT, project.getId()));
}
@Test
public void save_update_data() throws JsonProcessingException {
assertNull(repository.loadProperty(PROPERTY_TYPE, ProjectEntityType.PROJECT, project.getId()));
repository.saveProperty(PROPERTY_TYPE, ProjectEntityType.PROJECT, project.getId(), JsonUtils.object().with("value", 10).end());
TProperty t = repository.loadProperty(PROPERTY_TYPE, ProjectEntityType.PROJECT, project.getId());
assertNotNull(t);
assertJsonEquals(
JsonUtils.object().with("value", 10).end(),
t.getJson()
);
repository.saveProperty(PROPERTY_TYPE, ProjectEntityType.PROJECT, project.getId(), JsonUtils.object().with("value", 12).end());
t = repository.loadProperty(PROPERTY_TYPE, ProjectEntityType.PROJECT, project.getId());
assertNotNull(t);
assertJsonEquals(
JsonUtils.object().with("value", 12).end(),
t.getJson()
);
}
}
|
want-fly/huaweicloud-sdk-go-v3
|
services/cdm/v1/model/model_cdm_query_cluster_details_repsonse_public_endpoint_status.go
|
package model
import (
"github.com/huaweicloud/huaweicloud-sdk-go-v3/core/utils"
"strings"
)
// EIP状态信息
type CdmQueryClusterDetailsRepsonsePublicEndpointStatus struct {
// 状态
Status *string `json:"status,omitempty"`
// 错误信息
ErrorMessage *string `json:"errorMessage,omitempty"`
}
func (o CdmQueryClusterDetailsRepsonsePublicEndpointStatus) String() string {
data, err := utils.Marshal(o)
if err != nil {
return "CdmQueryClusterDetailsRepsonsePublicEndpointStatus struct{}"
}
return strings.Join([]string{"CdmQueryClusterDetailsRepsonsePublicEndpointStatus", string(data)}, " ")
}
|
Virtual-Hex/virtual-hex-editor
|
editor-engine-api/src/main/java/com/virtual_hex/editor/PluginLoadCode.java
|
<reponame>Virtual-Hex/virtual-hex-editor
package com.virtual_hex.editor;
public enum PluginLoadCode {
JAR_FILE_IO_EXCEPTION("Jar File IO Exception"),
JAR_MANIFEST_IO_EXCEPTION("Jar Manifest IO Exception"),
NO_JAR_MANIFEST("Missing jar manifest"),
NO_JAR_MANIFEST_VALUE("Missing jar manifest value"),
CANNOT_FIND_CLASS_JAR_ENTRY("Cannot find class Jar Entry"),
MALFORMED_URL("Malformed URL"),
CANNOT_FIND_CLASS_EXCEPTION("Cannot find class Exception"),
CLASS_PLUGIN_INHERITANCE("Class does not inherit plugin"),
NO_TARGET("Plugin does not have a target"),
TARGET_MISS_MATCH("Targets do not match"),
ANNOTATION_METHOD_ILLEGAL_ACCESS_EXCEPTION("Annotation Method illegal access exception"),
ANNOTATION_METHOD_INVOCATION_TARGET_EXCEPTION("Annotation Method invocation target exception"),
MISSING_ANNOTATION("Missing annotation"),
MISSING_ANNOTATION_VALUE("Missing annotation value"),
CANNOT_PARSE_VERSION_STRING("Cannot parse Version String"),
CANNOT_PARSE_DEPENDENCIES_STRING("Cannot parse Dependencies String"),
PLUGIN_INSTANTIATION_EXCEPTION("Plugin Instantiation Exception"),
PLUGIN_ILLEGAL_ACCESS_EXCEPTION("Plugin Illegal Access Exception"),
PLUGIN_FILE_SIZE_IO_EXCEPTION("Plugin file size Io Exception"),
PLUGIN_DATA_DIRECTORY_CREATE_ERROR("This should not happen but could not create plugin data directory"),
PLUGIN_ON_ENABLE_EXCEPTION("This means an exception was thrown by the plugin Plugin.onEnable() code by the plugin" +
" developer"),
PLUGIN_ON_ENABLE_RETURNED_FALSE("Plugin.onEnable() returned false which means the plugin itself needs further" +
"configuration before being reloaded"),
SUCCESS_LOAD("Plugin was successfully loaded"),
SUCCESS_ON_ENABLE("Plugin was successfully enabled")
;
private final String string;
PluginLoadCode(String string) {
this.string = string;
}
}
|
FIWARE/CanisMajor
|
src/controller/helper-controller.js
|
import { getFromIPFS } from '../util/helper/ipfs';
import { getFromIOTA } from '../util/helper/iota';
import { verify } from '../util/helper/merkle';
import { StatusCodes } from 'http-status-codes';
import { trytesToAscii} from '@iota/converter';
import { composeAPI } from '@iota/core';
import { DLT_CONFIGURATION } from '../configuration/config';
class HelperController {
getDataFromIPFS(request, response) {
let hash = request.params.id;
if (hash == null || hash == '') {
let err = new Error();
err.status = StatusCodes.FORBIDDEN;
err.message = 'hash missing in param';
return response.status(StatusCodes.FORBIDDEN).jsonp(err);
}
getFromIPFS(hash).then((res) => {
return response.status(StatusCodes.OK).jsonp(res);
}).catch((err) => {
return response.status(StatusCodes.BAD_REQUEST).jsonp(err);
})
}
getDatafromIOTAMaM(request, response) {
let hash = request.params.id;
if (hash == null || hash == '') {
let err = new Error();
err.status = StatusCodes.FORBIDDEN;
err.message = 'hash missing in param';
return response.status(StatusCodes.FORBIDDEN).jsonp(err);
}
console.log('has' + hash);
getFromIOTA(hash).then((res) => {
return response.status(StatusCodes.OK).jsonp(res);
}).catch((err) => {
return response.status(StatusCodes.BAD_REQUEST).jsonp(err);
})
}
getDatafromIOTATx(request, response) {
const iota = composeAPI({
provider: DLT_CONFIGURATION.IOTA_CONFIG.endpoint
});
let hash = request.params.id;
if (hash == null || hash == '') {
let err = new Error();
err.status = StatusCodes.FORBIDDEN;
err.message = 'hash missing in param';
return response.status(StatusCodes.FORBIDDEN).jsonp(err);
}
iota.getBundle(hash).then((bundle) => {
console.log(bundle);
const sign = bundle[0].signatureMessageFragment;
console.log(sign);
const num = sign.match(/^(.*)99/);
console.log(num);
let data = Buffer.from(trytesToAscii(num[1].slice(0, -1)), 'base64').toString('utf-8');
console.log(data);
return response.status(StatusCodes.OK).jsonp(JSON.parse(data));
}).catch((err) => {
return response.status(StatusCodes.BAD_REQUEST).jsonp(err);
})
}
verifyMerkleTree(request, response) {
let hash = request.params.id;
let key = request.params.key;
if (hash == null || hash == '') {
let err = new Error();
err.status = StatusCodes.FORBIDDEN;
err.message = 'hash missing in param';
return response.status(StatusCodes.FORBIDDEN).jsonp(err);
}
if (key == null || key == '') {
let err = new Error();
err.status = StatusCodes.FORBIDDEN;
err.message = 'key missing in param';
return response.status(StatusCodes.FORBIDDEN).jsonp(err);
}
let body = request.body;
if (body == null || body == '') {
let err = new Error();
err.status = StatusCodes.FORBIDDEN;
err.message = 'body is empty';
return response.status(StatusCodes.FORBIDDEN).jsonp(err);
}
verify(body, key, hash).then((res) => {
return response.status(StatusCodes.OK).jsonp({ valid: res });
}).catch((err) => {
return response.status(StatusCodes.BAD_REQUEST).jsonp(err);
})
}
}
export default new HelperController();
|
manggoguy/parsec-modified
|
ext/splash2x/apps/water_nsquared/src/water.h
|
#line 233 "parmacs.pthreads.c.m4"
#line 1 "water.H"
/*************************************************************************/
/* */
/* Copyright (c) 1994 Stanford University */
/* */
/* All rights reserved. */
/* */
/* Permission is given to use, copy, and modify this software for any */
/* non-commercial purpose as long as this copyright notice is not */
/* removed. All other uses, including redistribution in whole or in */
/* part, are forbidden without prior written permission. */
/* */
/* This software is provided with absolutely no warranty and no */
/* support. */
/* */
/*************************************************************************/
/* some variable declarations and some macro definitions */
extern double OMAS,HMAS,WTMOL,ROH,ANGLE,FHM,FOM,ROHI,ROHI2;
extern long NATOMS;
#define max(a,b) ( (a) < (b) ) ? b : a
#define min(a,b) ( (a) > (b) ) ? b : a
#define ONE ((double) 1)
#define TWO ((double) 2)
#define FIVE ((double) 5)
|
Shubhrmcf07/Competitive-Coding-and-Interview-Problems
|
Leet Code/3sum.cpp
|
/* Leet Code */
/* Title - 3Sum */
// Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
// Note:
// The solution set must not contain duplicate triplets.
// Example:
// Given array nums = [-1, 0, 1, 2, -1, -4],
// A solution set is:
// [
// [-1, 0, 1],
// [-1, -1, 2]
// ]
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> v;
if(nums.size()<3)
return v;
int i,j,k;
sort(nums.begin(),nums.end());
for(i = 0;i<nums.size()-2;i++){
j=i+1;
k=nums.size()-1;
if(nums[i]>0)
break;
if(i>0 && nums[i]==nums[i-1])
continue;
while(j<k){
if(nums[j]+nums[i]>0)
break;
if(j>i+1 && nums[j]==nums[j-1])
{
j++;
continue;
}
if(nums[i]+nums[j]+nums[k]>0)
k--;
else if(nums[i]+nums[j]+nums[k]<0)
j++;
else{
v.push_back(vector<int>{nums[i],nums[j],nums[k]});
j++;
k--;
}
}
}
return v;
}
};
|
PuZhiweizuishuai/HomeworkEvaluation
|
evaluation/src/main/java/com/buguagaoshu/homework/evaluation/exception/UserDataFormatException.java
|
<filename>evaluation/src/main/java/com/buguagaoshu/homework/evaluation/exception/UserDataFormatException.java
package com.buguagaoshu.homework.evaluation.exception;
/**
* @author <NAME> {@literal <EMAIL>}
* create 2020-06-12 21:50
* 用户提交数据不符合规定异常
*/
public class UserDataFormatException extends RuntimeException {
public UserDataFormatException() {
}
public UserDataFormatException(String message) {
super(message);
}
public UserDataFormatException(String message, Throwable cause) {
super(message, cause);
}
public UserDataFormatException(Throwable cause) {
super(cause);
}
public UserDataFormatException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
|
HelloOO7/CTRMapStandardLibrary
|
src/ctrmap/stdlib/math/BlenLibMath.java
|
package ctrmap.stdlib.math;
import ctrmap.stdlib.math.vec.Matrix4;
import ctrmap.stdlib.math.vec.Vec3f;
import org.joml.Matrix3f;
/**
* Linear algebra from the Blender Library, available at:
* https://github.com/blender/blender/tree/master/source/blender/blenlib/intern
*/
public class BlenLibMath {
private static Matrix3f temp_mat3 = new Matrix3f();
public synchronized static Vec3f getRotation(Matrix4 matrix, Vec3f dest) {
float[] eul = new float[3];
float[] mfull = new float[9];
float[][] m = new float[3][3];
matrix.normalize3x3(temp_mat3);
temp_mat3.get(mfull);
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
m[i][j] = mfull[i + j * 3];
}
}
mat3_normalized_to_eulO(eul, m);
dest.set(eul);
return dest;
}
public static void mat3_normalized_to_eulO(float[] eul, float[][] m) {
float[] eul1 = new float[3];
float[] eul2 = new float[3];
float d1, d2;
mat3_normalized_to_eulo2(m, eul1, eul2);
d1 = Math.abs(eul1[0]) + Math.abs(eul1[1]) + Math.abs(eul1[2]);
d2 = Math.abs(eul2[0]) + Math.abs(eul2[1]) + Math.abs(eul2[2]);
/* return best, which is just the one with lowest values it in */
if (d1 > d2) {
copy_v3_v3(eul, eul2);
} else {
copy_v3_v3(eul, eul1);
}
}
public static void copy_v3_v3(float[] dst, float[] src) {
System.arraycopy(src, 0, dst, 0, 3);
}
public static void mat3_normalized_to_eulo2(float[][] mat,
float[] eul1,
float[] eul2) {
short i = 2, j = 1, k = 0;
float cy;
cy = (float) Math.hypot(mat[i][i], mat[i][j]);
if (cy > 16.0f * Float.MIN_VALUE) {
eul1[i] = (float) FAtan.atan2(mat[j][k], mat[k][k]);
eul1[j] = (float) FAtan.atan2(-mat[i][k], cy);
eul1[k] = (float) FAtan.atan2(mat[i][j], mat[i][i]);
eul2[i] = (float) FAtan.atan2(-mat[j][k], -mat[k][k]);
eul2[j] = (float) FAtan.atan2(-mat[i][k], -cy);
eul2[k] = (float) FAtan.atan2(-mat[i][j], -mat[i][i]);
} else {
eul1[i] = (float) FAtan.atan2(-mat[k][j], mat[j][j]);
eul1[j] = (float) FAtan.atan2(-mat[i][k], cy);
eul1[k] = 0;
copy_v3_v3(eul2, eul1);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.