repo_name stringlengths 6 101 | path stringlengths 4 300 | text stringlengths 7 1.31M |
|---|---|---|
chrisstaite/DMX_seven_segment | DMX Controller/seven_segment_array.h | <gh_stars>1-10
//
// seven_segment_array.h
// DMX Controller
//
// Created by <NAME> on 08/02/2017.
// Copyright © 2017 <NAME>. All rights reserved.
//
#ifndef SEVEN_SEGMENT_ARRAY_H_
#define SEVEN_SEGMENT_ARRAY_H_
#include "seven_segment.h"
namespace avr {
class Pin;
} // namespace avr
namespace led {
/// An encapsulation around a three digit 7-segment display
/// with common cathode, operating under the same stipulations
/// as set out in SevenSegment.
/// \see SevenSegment
class SevenSegmentArray
{
public:
/// The number of digits in the display
static constexpr unsigned int DIGITS = 3;
/// The nubmer of frames per second
static constexpr unsigned int FPS = 50;
/// The number of calls to displayStep per second
static constexpr unsigned int STEPS_PS = FPS * DIGITS * SevenSegment::SEQUENCE_STEPS;
/// Construct the encapsulation, setting the pins as outputs
///
/// \param digitSelectors The selectors for each of the three digits
/// \param digitPort The DDR for the 7-segment output
///
/// \see SevenSegment
template<typename Port>
SevenSegmentArray(avr::Pin (&digitSelectors)[DIGITS], Port digitPort);
SevenSegmentArray(const SevenSegmentArray&) = delete;
SevenSegmentArray& operator=(const SevenSegmentArray&) = delete;
~SevenSegmentArray();
/// Set the current value to display. A negative value
/// blanks the display.
///
/// The value is only actually displayed if displayStep
/// is called.
///
/// \param value The value to display
void setValue(int16_t value);
/// Set an individual display value, should be between
/// 0-9 or a value from SevenSegmentArray::Letters
///
/// \param index The index between 0 and DIGITS
/// \param value The value to display
void setValue(uint8_t index, uint8_t value);
/// Display the next bit, this wants to be performed roughly
/// 50fps for the DIGITS * SEQUENCE_STEPS long sequence. This
/// equates to about 600 times a second (STEPSPS).
void displayStep();
private:
/// The constructor, untemplated
void init();
avr::Pin (&m_digitSelectors)[DIGITS];
SevenSegment m_segment;
uint8_t m_currentValues[DIGITS];
uint8_t m_currentStep;
};
template<typename Port>
SevenSegmentArray::SevenSegmentArray(
avr::Pin (&digitSelectors)[DIGITS],
Port digitPort) :
m_digitSelectors{digitSelectors},
m_segment{digitPort},
m_currentValues{},
m_currentStep{0}
{
setValue(-1);
init();
}
} // namespace led
#endif // SEVEN_SEGMENT_ARRAY_H_
|
CDz1129/ZTuoExchange_framework | otc-core/src/main/java/cn/ztuo/bitrade/config/HttpSessionConfig.java | <filename>otc-core/src/main/java/cn/ztuo/bitrade/config/HttpSessionConfig.java
package cn.ztuo.bitrade.config;
import org.springframework.context.annotation.Bean;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;
import org.springframework.session.web.http.CookieHttpSessionStrategy;
import org.springframework.session.web.http.HeaderHttpSessionStrategy;
import org.springframework.session.web.http.HttpSessionStrategy;
import cn.ztuo.bitrade.ext.SmartHttpSessionStrategy;
@EnableRedisHttpSession
public class HttpSessionConfig {
@Bean
public HttpSessionStrategy httpSessionStrategy(){
HeaderHttpSessionStrategy headerSession = new HeaderHttpSessionStrategy();
CookieHttpSessionStrategy cookieSession = new CookieHttpSessionStrategy();
headerSession.setHeaderName("x-auth-token");
return new SmartHttpSessionStrategy(cookieSession,headerSession);
}
}
|
ruimo/store2 | app/models/ChangeItemMetadata.scala | package models
import java.sql.Connection
import play.api.db.Database
case class ChangeItemMetadataTable(
itemMetadatas: Seq[ChangeItemMetadata]
) {
def update(itemId: Long)(implicit conn: Connection) {
itemMetadatas.foreach {
_.update(itemId)
}
}
}
case class ChangeItemMetadata(
metadataType: Int, metadata: Long
) {
def update(itemId: Long)(implicit conn: Connection) {
ItemNumericMetadata.update(ItemId(itemId), ItemNumericMetadataType.byIndex(metadataType), metadata)
}
def add(itemId: Long)(implicit db: Database) {
ExceptionMapper.mapException {
db.withTransaction { implicit conn =>
ItemNumericMetadata.add(ItemId(itemId), ItemNumericMetadataType.byIndex(metadataType), metadata)
}
}
}
}
|
Soth1985/Thor | thor/code/Thor/Graphics/GraphicsRuntimeSharedComponent/ThGraphicsRuntimeSharedExport.h | <gh_stars>0
#pragma once
#include <Thor/Framework/Common.h>
#ifdef THOR_MS_WIN
#ifdef THOR_GRAPHICS_RUNTIME_SHARED_EXPORT
#define THOR_GRAPHICS_RUNTIME_SHARED_DLL __declspec(dllexport)
#elif defined THOR_GRAPHICS_RUNTIME_SHARED_IMPORT
#define THOR_GRAPHICS_RUNTIME_SHARED_DLL __declspec(dllimport)
#else
#define THOR_GRAPHICS_RUNTIME_SHARED_DLL
#endif
#else
#define THOR_GRAPHICS_RUNTIME_SHARED_DLL
#endif |
King0987654/windows2000 | private/inet/mshtml/src/site/display/dispinterior.hxx | <gh_stars>10-100
//+---------------------------------------------------------------------------
//
// Microsoft Internet Explorer
// Copyright (C) Microsoft Corporation, 1997-1998
//
// File: dispinterior.hxx
//
// Contents: Base class for interior (non-leaf) display nodes.
//
//----------------------------------------------------------------------------
#ifndef I_DISPINTERIOR_HXX_
#define I_DISPINTERIOR_HXX_
#pragma INCMSG("--- Beg 'dispinterior.hxx'")
#ifndef X_DISPNODE_HXX_
#define X_DISPNODE_HXX_
#include "dispnode.hxx"
#endif
class CDispContextStack;
class CDispBalanceNode;
// constants used to determine when tree balancing is necessary
#define MAX_CHILDREN_BEFORE_BALANCE 100 // don't balance nodes with less
// than this many children
#define MAX_CHILDREN_AFTER_BALANCE 50 // produce nodes with this many
// children after balancing
#define MIN_CHILDREN_BEFORE_BALANCE 5 // only group more than this
// many children during balancing
//+---------------------------------------------------------------------------
//
// Class: CDispInteriorNode
//
// Synopsis: Base class for interior (non-leaf) display nodes.
//
//----------------------------------------------------------------------------
class CDispInteriorNode :
public CDispNode
{
DECLARE_DISPNODE_ABSTRACT(CDispInteriorNode, CDispNode)
friend class CDispRoot;
friend class CDispNode;
friend class CDispLeafNode;
friend class CDispItemPlus;
friend class CDispContainer;
friend class CDispContainerPlus;
friend class CDispScroller;
friend class CDispScrollerPlus;
friend class CDispDrawContext;
friend class CDispContextStack;
protected:
CDispNode* _pFirstChildNode; // pointer to first child
CDispNode* _pLastChildNode; // pointer to last child
LONG _cChildren; // children count
// 48 bytes (12 bytes + 36 bytes for CDispNode base class)
protected:
// object can be created only by derived classes, and destructed only from
// special methods
CDispInteriorNode()
: CDispNode()
{SetFlag(CDispFlags::s_interiorNode);}
virtual ~CDispInteriorNode();
public:
CDispNode* GetFirstChildNode() const;
CDispNode* GetFirstChildNodeInLayer(DISPNODELAYER layer) const;
CDispNode* GetLastChildNode() const;
CDispNode* GetLastChildNodeInLayer(DISPNODELAYER layer) const;
CDispNode* GetChildInFlow(LONG index) const;
LONG CountChildren() const;
void InsertChildInFlow(CDispNode* pNewChild);
void InsertFirstChildInFlow(CDispNode* pNewChild);
void InsertChildInZLayer(CDispNode* pNewChild, LONG zOrder)
{if (zOrder < 0)
InsertChildInNegZ(pNewChild, zOrder);
else InsertChildInPosZ(pNewChild, zOrder);}
void TakeChildrenFrom(
CDispInteriorNode* pOldParent,
CDispNode* pFirstChildToTake = NULL,
CDispNode* pChildToInsertAfter = NULL);
virtual CDispScroller * HitScrollInset(CPoint *pptHit, DWORD *pdwScrollDir);
protected:
void InsertFirstChildNode(CDispNode* pNewChild);
void InsertLastChildNode(CDispNode* pNewChild);
void InsertChildInNegZ(CDispNode* pNewChild, LONG zOrder);
void InsertChildInPosZ(CDispNode* pNewChild, LONG zOrder);
void DestroyChildren();
void BalanceTree();
void CreateBalanceGroups(
CDispNode* pFirstChild,
CDispNode* pStopChild,
LONG cChildrenInEachGroup);
// Determine whether a node and its children are in-view or not.
BOOL CalculateInView();
void SetSubtreeFlags(const CDispFlags& flags);
void ClearSubtreeFlags(const CDispFlags& flags);
// CDispNode overrides
virtual BOOL PreDraw(CDispDrawContext* pContext);
virtual void DrawSelf(CDispDrawContext* pContext, CDispNode* pChild);
virtual BOOL HitTestPoint(CDispHitContext* pContext) const;
virtual void CalcDispInfo(
const CRect& rcClip,
CDispInfo* pdi) const;
// CDispInteriorNode virtuals
virtual void PushContext(
const CDispNode* pChild,
CDispContextStack* pContextStack,
CDispContext* pContext) const;
virtual BOOL ComputeVisibleBounds();
virtual BOOL SubtractOpaqueChildren(
CRegion* prgn,
CDispContext* pContext);
virtual BOOL CalculateInView(
CDispContext* pContext,
BOOL fPositionChanged,
BOOL fNoRedraw);
virtual void RecalcChildren(
BOOL fForceRecalc,
BOOL fSuppressInval,
CDispDrawContext* pContext);
void GetScrollableContentSize(
CSize* psize,
BOOL fAddBorder = FALSE) const;
BOOL PreDrawChild(
CDispNode* pChild,
CDispDrawContext* pContext,
const CDispContext& saveContext) const;
void InsertChildNode(
CDispNode* pChild,
CDispNode* pPreviousSibling,
CDispNode* pNextSibling);
void SetPositionHasChanged();
#if DBG==1
public:
virtual void VerifyTreeCorrectness() const;
protected:
virtual size_t GetMemorySize() const;
void VerifyChildrenCount() const;
void VerifyFlags(
const CDispFlags& mask,
const CDispFlags& value,
BOOL fEqual) const;
#endif
};
#pragma INCMSG("--- End 'dispinterior.hxx'")
#else
#pragma INCMSG("*** Dup 'dispinterior.hxx'")
#endif
|
DC-Melo/gradle_android_monkey_service | AndroidMonkeyRunningAdapter/src/main/java/com/github/monkey/runner/helper/SharedProperties.java | package com.github.monkey.runner.helper;
import java.util.ArrayList;
public class SharedProperties {
private static ArrayList<Object> properties = new ArrayList<Object>();
private static SharedProperties instance = new SharedProperties();
public static SharedProperties getInstance() {
return instance;
}
private SharedProperties() {
}
public void add(final Object property) {
synchronized (properties) {
properties.add(property);
}
}
public void clear() {
synchronized (properties) {
properties.clear();
}
}
public ArrayList<Object> getProperties() {
return properties;
}
}
|
south-coast-science/scs_philips_hue | src/scs_philips_hue/data/bridge/backup.py | """
Created on 28 Oct 2017
@author: <NAME> (<EMAIL>)
example:
{"status": "idle", "error_code": 0}
"""
from collections import OrderedDict
from scs_core.data.json import JSONable
# --------------------------------------------------------------------------------------------------------------------
class Backup(JSONable):
"""
classdocs
"""
# ----------------------------------------------------------------------------------------------------------------
@classmethod
def construct_from_jdict(cls, jdict):
if not jdict:
return None
status = jdict.get('status')
error_code = jdict.get('errorcode')
return Backup(status, error_code)
# ----------------------------------------------------------------------------------------------------------------
def __init__(self, status, error_code):
"""
Constructor
"""
self.__status = status # string
self.__error_code = int(error_code) # int
# ----------------------------------------------------------------------------------------------------------------
def as_json(self):
jdict = OrderedDict()
jdict['status'] = self.status
jdict['errorcode'] = self.error_code
return jdict
# ----------------------------------------------------------------------------------------------------------------
@property
def status(self):
return self.__status
@property
def error_code(self):
return self.__error_code
# ----------------------------------------------------------------------------------------------------------------
def __str__(self, *args, **kwargs):
return "Backup:{status:%s, error_code:%s}" % (self.status, self.error_code)
|
rkhmelichek/docker-maven-plugin | src/main/java/io/fabric8/maven/docker/config/CopyConfiguration.java | package io.fabric8.maven.docker.config;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import org.apache.maven.plugins.annotations.Parameter;
import io.fabric8.maven.docker.util.DeepCopy;
public class CopyConfiguration implements Serializable {
public static final String CONTAINER_PATH_PROPERTY = "containerPath";
public static final String HOST_DIRECTORY_PROPERTY = "hostDirectory";
public static class Entry implements Serializable {
/**
* Full path to container file or container directory which needs to copied.
*/
private String containerPath;
/**
* Path to a host directory where the files copied from container need to be placed. If relative path is
* provided then project base directory is considered as a base of that relative path. Can be <code>null</code>
* meaning the same as empty string. Note that if containerPath points to a directory, then a directory with the
* same name will be created in the hostDirectory, i.e. not just content of directory is copied, but the same
* name directory is created too.
*/
private String hostDirectory;
public Entry() {}
public Entry(String containerPath, String hostDirectory) {
this.containerPath = containerPath;
this.hostDirectory = hostDirectory;
}
public String getContainerPath() {
return containerPath;
}
public String getHostDirectory() {
return hostDirectory;
}
public void setContainerPath(String containerPath) {
this.containerPath = containerPath;
}
public void setHostDirectory(String hostDirectory) {
this.hostDirectory = hostDirectory;
}
}
/**
* Items to copy from container.
*/
@Parameter
private List<Entry> entries;
public List<Entry> getEntries() {
return entries;
}
public List<Properties> getEntriesAsListOfProperties() {
if (entries == null) {
return null;
}
final List<Properties> properties = new ArrayList<>(entries.size());
for (Entry entry : entries) {
final Properties entryProperties = new Properties();
entryProperties.put(CONTAINER_PATH_PROPERTY, entry.getContainerPath());
final String hostDirectory = entry.getHostDirectory();
if (hostDirectory != null) {
entryProperties.put(HOST_DIRECTORY_PROPERTY, hostDirectory);
}
properties.add(entryProperties);
}
return properties;
}
public static class Builder {
private final CopyConfiguration config;
public Builder() {
this(null);
}
public Builder(CopyConfiguration that) {
if (that == null) {
config = new CopyConfiguration();
} else {
config = DeepCopy.copy(that);
}
}
public Builder entries(List<Entry> entries) {
final List<Entry> entriesCopy = new ArrayList<>(entries.size());
for (Entry entry : entries) {
entriesCopy.add(new Entry(entry.getContainerPath(), entry.getHostDirectory()));
}
config.entries = entriesCopy;
return this;
}
public Builder entriesAsListOfProperties(List<Properties> entries) {
config.entries = getEntriesFromProperties(entries);
return this;
}
public CopyConfiguration build() {
return config;
}
private static List<Entry> getEntriesFromProperties(List<Properties> properties) {
if (properties == null) {
return null;
}
final List<Entry> entries = new ArrayList<>(properties.size());
int i = 0;
for (Properties entryProperties : properties) {
String containerPath = entryProperties.getProperty(CONTAINER_PATH_PROPERTY);
final String hostDirectory = entryProperties.getProperty(HOST_DIRECTORY_PROPERTY);
if (containerPath == null && hostDirectory == null) {
// Shortcut for the case when we need to define just containerPath of copy entry
containerPath = entryProperties.getProperty("");
}
if (containerPath == null) {
throw new IllegalArgumentException(
String.format("Mandatory property [%s] of entry [%d] is not defined",
CONTAINER_PATH_PROPERTY, i));
}
entries.add(new Entry(containerPath, hostDirectory));
++i;
}
return entries;
}
}
}
|
jmdisher/Cacophony | test/com/jeffdisher/cacophony/logic/TestGlobalPinCache.java | package com.jeffdisher.cacophony.logic;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import org.junit.Assert;
import org.junit.Test;
import com.jeffdisher.cacophony.data.local.v1.GlobalPinCache;
import com.jeffdisher.cacophony.types.IpfsFile;
public class TestGlobalPinCache
{
public static final IpfsFile M1 = IpfsFile.fromIpfsCid("QmTaodmZ3CBozbB9ikaQNQFGhxp9YWze8Q8N8XnryCCeKG");
public static final IpfsFile M2 = IpfsFile.fromIpfsCid("QmTaodmZ3CBozbB9ikaQNQFGhxp9YWze8Q8N8XnryCCeCG");
public static final IpfsFile M3 = IpfsFile.fromIpfsCid("QmTaodmZ3CBozbB9ikaQNQFGhxp9YWze8Q8N8XnryCCeCC");
@Test
public void testBasicUse()
{
GlobalPinCache index = GlobalPinCache.newCache();
Assert.assertFalse(index.isCached(M1));
index.hashWasAdded(M1);
Assert.assertTrue(index.isCached(M1));
Assert.assertTrue(index.shouldPinAfterAdding(M2));
Assert.assertFalse(index.shouldPinAfterAdding(M1));
Assert.assertFalse(index.shouldPinAfterAdding(M2));
Assert.assertFalse(index.shouldUnpinAfterRemoving(M1));
Assert.assertTrue(index.shouldUnpinAfterRemoving(M1));
Assert.assertFalse(index.isCached(M1));
}
@Test
public void testEmptySerializeDeserialize()
{
GlobalPinCache index = GlobalPinCache.newCache();
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
index.writeToStream(outStream);
ByteArrayInputStream inStream = new ByteArrayInputStream(outStream.toByteArray());
GlobalPinCache read = GlobalPinCache.fromStream(inStream);
Assert.assertNotNull(read);
Assert.assertFalse(read.isCached(M1));
}
@Test
public void testSerializeDeserialize()
{
GlobalPinCache index = GlobalPinCache.newCache();
index.hashWasAdded(M1);
Assert.assertTrue(index.shouldPinAfterAdding(M2));
Assert.assertFalse(index.shouldPinAfterAdding(M1));
Assert.assertFalse(index.shouldPinAfterAdding(M2));
Assert.assertTrue(index.shouldPinAfterAdding(M3));
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
index.writeToStream(outStream);
ByteArrayInputStream inStream = new ByteArrayInputStream(outStream.toByteArray());
GlobalPinCache read = GlobalPinCache.fromStream(inStream);
Assert.assertFalse(read.shouldPinAfterAdding(M2));
Assert.assertFalse(read.shouldUnpinAfterRemoving(M1));
Assert.assertTrue(read.shouldUnpinAfterRemoving(M1));
Assert.assertFalse(read.shouldUnpinAfterRemoving(M2));
Assert.assertFalse(read.shouldUnpinAfterRemoving(M2));
Assert.assertTrue(read.shouldUnpinAfterRemoving(M2));
Assert.assertTrue(read.shouldUnpinAfterRemoving(M3));
outStream = new ByteArrayOutputStream();
index.writeToStream(outStream);
inStream = new ByteArrayInputStream(outStream.toByteArray());
read = GlobalPinCache.fromStream(inStream);
Assert.assertNotNull(read);
}
}
|
lulugyf/inospeech | app/src/main/java/com/laog/test1/inoreader/InoApi.java | package com.laog.test1.inoreader;
import android.util.Log;
import com.laog.test1.db.FeedItem;
import com.laog.test1.db.FeedItemDao;
import com.laog.test1.db.MN;
import com.laog.test1.db.State;
import com.laog.test1.util.TextUtil;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URI;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import cz.msebera.android.httpclient.Consts;
import cz.msebera.android.httpclient.Header;
import cz.msebera.android.httpclient.HttpEntity;
import cz.msebera.android.httpclient.HttpHost;
import cz.msebera.android.httpclient.HttpResponse;
import cz.msebera.android.httpclient.NameValuePair;
import cz.msebera.android.httpclient.client.entity.UrlEncodedFormEntity;
import cz.msebera.android.httpclient.client.methods.CloseableHttpResponse;
import cz.msebera.android.httpclient.client.methods.HttpGet;
import cz.msebera.android.httpclient.client.methods.HttpPost;
import cz.msebera.android.httpclient.client.methods.HttpRequestBase;
import cz.msebera.android.httpclient.impl.client.CloseableHttpClient;
import cz.msebera.android.httpclient.impl.client.HttpClients;
import cz.msebera.android.httpclient.impl.conn.DefaultProxyRoutePlanner;
import cz.msebera.android.httpclient.message.BasicNameValuePair;
import cz.msebera.android.httpclient.util.EntityUtils;
public class InoApi {
private final static String base_url = "https://www.inore<EMAIL>";
private final static String api_url = "https://www.inoreader.com/reader/api/0/";
private String auth_file = null;
private CloseableHttpClient httpclient;
private volatile String rootDir;
private volatile String tmpDir;
private volatile FeedItemDao dao;
private String realPath(String p) {
if(p.charAt(0) == '/' || p.charAt(1) == ':')
return p;
return tmpDir + p;
}
public static void main(String[] args) throws Exception {
InoApi n = new InoApi("d:/tmp/ino", null, "127.0.0.1:8083");
String testOP = "list";
String recordFile = "D:/tmp/ino/record.dat";
String outDir = "D:/tmp/ino";
if("down".equals(testOP)) {
n.download2File(recordFile, outDir);
}else if("list".equals(testOP)) {
n.listRecords(recordFile, outDir);
}
// n.login();
// n.auth = "<PASSWORD>";
// n.content("user%2F-%2Fstate%2Fcom.google%2Freading-list?r=o&n=5&ot="+(System.currentTimeMillis()/1000-3600*24));
}
private void listRecords(String recordFile, String outDir) throws Exception {
InputStream fin = new FileInputStream(recordFile);
while(true) {
FeedItem fi = FeedItem.readRecord(fin);
if(fi == null)
break;
//fi.loadContent(outDir);
// fi.print();
if("tag:google.com,2005:reader/item/000000041fdba90d".equals(fi.getId())){
fi.loadContent(outDir);
fi.print();
for(String img: Article.parseImageLinks(fi.rawContent)){
System.out.println(" " + img);
String fname = img.substring(img.lastIndexOf('/')+1);
if(fname.indexOf('?') > 0)
fname = fname.substring(0, fname.indexOf('?'));
get(img, fname);
}
}
}
fin.close();
}
/**
* 下载数据, 并保存到文件中, 只是pc上的测试代码
* @return
* @throws Exception
*/
private int download2File(String recordFile, String outDir) throws Exception {
JsonUtil ju = new JsonUtil();
long maxTime = System.currentTimeMillis()/1000 - 24*3600; //往后推一天, 这个参数是feeds开始的时间, 单位是秒
int count = 0;
log("begin downloading, maxtime: "+maxTime);
String feed = "user%2F-%2Fstate%2Fcom.google%2Freading-list?r=o&n=50&ot="+maxTime;
OutputStream pw = new FileOutputStream(recordFile);
while(true) {
String url = api_url + "stream/contents/" + feed;
String content = get(url);
List<FeedItem> lst = ju.parseStream(content);
if(lst == null) {
System.out.println("--- not aticles found!");
break;
}
for(FeedItem fi: lst){
try {
fi.saveContent(outDir);
fi.saveRecord(pw);
}catch (Exception e){ Log.e("", "dulplicate item:"+fi.getId()); }
}
count += lst.size();
String c = ju.getC();
log("download "+c + " count:"+lst.size() + " " + lst.get(lst.size()-1).getS_published());
if(c == null)
break;
feed = "user%2F-%2Fstate%2Fcom.google%2Freading-list?r=o&n=50&ot="+maxTime+"&c="+c;
}
pw.close();
return count;
}
public InoApi(String rootdir, FeedItemDao dao, boolean useProxy) {
this.dao = dao;
if(rootdir != null) {
this.rootDir = rootdir;
tmpDir = rootDir + File.separator + "tmp" + File.separator;
File f = new File(tmpDir);
if (!f.exists()) f.mkdirs();
auth_file = tmpDir + File.separator + "auth_file";
f = new File(auth_file);
if (f.exists()) {
try {
auth = Utils.fileToString(auth_file).trim();
} catch (Exception e) {
e.printStackTrace();
}
}
}
if(useProxy){
HttpHost proxy = new HttpHost("172.22.0.23", 8989);
DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
httpclient = HttpClients.custom()
.setRoutePlanner(routePlanner)
.build();
}else
httpclient = HttpClients.createDefault();
}
public InoApi(String rootdir, FeedItemDao dao, String proxyaddr){
this(rootdir, dao, false);
if(proxyaddr != null){
int p=proxyaddr.lastIndexOf(':');
HttpHost proxy = new HttpHost(proxyaddr.substring(0, p), Integer.parseInt(proxyaddr.substring(p+1)));
DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
httpclient = HttpClients.custom().setRoutePlanner(routePlanner) .build();
}
}
/**
* 统计库中的记录信息和 文件的情况
* @throws Exception
*/
public String state() throws Exception{
StringBuilder sb = new StringBuilder();
if(dao != null){
sb.append("=========state in feeditems\n");
for(State st: dao.state()) {
sb.append(" "+st.getFeeday() + " " + st.getCt()).append('\n');
}
}
sb.append("==== files in "+tmpDir).append('\n');
File ft = new File(tmpDir);
for(File f: ft.listFiles()) {
if(f.isDirectory()) continue;
sb.append(" " + f.getName() + " len: "+f.length() + " lastmodify: "+Utils.timeToStr(f.lastModified())).append('\n');
}
return sb.toString();
}
/**
* 归档, 把上个月及以前的数据保存到sdcard上, 并删除当前数据中的这部分
* @param path
* @throws Exception
*/
public String archive(String path) throws Exception {
//Done 归档的实现
return removeOldContent();
}
public String backup(String path) throws Exception {
log("---path:" + path);
String fpath = path + File.separator + "backup";
File ft = new File(fpath);
if(!ft.exists())
ft.mkdirs();
ft = new File(tmpDir);
StringBuilder sb = new StringBuilder();
sb.append("=== backup from "+tmpDir +" to "+fpath).append('\n');
for(File f: ft.listFiles()) {
if(f.isDirectory())
continue;
Utils.copy(f.getAbsolutePath().toString(), fpath + File.separator + f.getName());
sb.append("backup file ").append(f.getName()).append('\n');
}
sb.append("==== backup database sqlite to file\n");
List<FeedItem> lst = dao.getAll();
File f1 = new File(fpath + File.separator + "feeditems."+System.currentTimeMillis());
OutputStream out = new FileOutputStream(f1);
for(FeedItem fi: lst) {
fi.saveRecord(out);
}
out.close();
sb.append(" record count:"+lst.size() +" file length:"+f1.length());
return sb.toString();
}
private long g_maxTime;
private int down_pagesize = 50;
public String[] download(String c) throws Exception {
if(dao == null) {
log("download failed: dao is null");
return null;
}
String feed = null;
if(c == null){
long maxTime = dao.findMaxTime();
if(maxTime > 0L)
maxTime -= 3600; //往后推一个小时, 这个参数是feeds开始的时间
else
maxTime = System.currentTimeMillis()/1000 - oneday;
g_maxTime = maxTime;
Log.d("", "load from "+Utils.timeToStr(maxTime));
feed = "user%2F-%2Fstate%2Fcom.google%2Freading-list?r=o&n="+down_pagesize+"&ot="+maxTime;
}else{
feed = "user%2F-%2Fstate%2Fcom.google%2Freading-list?r=o&n="+down_pagesize+"&ot="+g_maxTime+"&c="+c;
}
String url = api_url + "stream/contents/" + feed;
String content = get(url);
JsonUtil ju = new JsonUtil();
List<FeedItem> lst = ju.parseStream(content);
for(FeedItem fi: lst){
try {
dao.insert(fi); // 先插入记录, 如果有重复就略过了, 避免内容文件里有重复的, 但表中没有
fi.saveContent(tmpDir);
dao.updateItem(fi);
}catch (Exception e){ Log.e("", "dulplicate item:"+fi.getId()); }
}
Log.d("", "download:"+feed+" size:"+lst.size());
Log.d("", "download: max date:"+lst.get(lst.size()-1).getS_published());
c = ju.getC();
int lstsize = lst.size();
String prompt = String.valueOf(lstsize);
if(lstsize > 0) {
final String pt = "minTime: " + lst.get(0).getS_published() + " maxTime: " + lst.get(lstsize - 1).getS_published();
Log.d("", pt);
prompt = prompt + " " + pt;
}
return new String[]{c, prompt};
}
private int pagesize = 20;
private long mintime = 0L;
private long maxtime = 0L;
private long oneday = 24 * 3600;
public List<FeedItem> loadnew() throws Exception {
if(dao == null) {
Log.d("---", "loadnew failed, dao is null");
return null;
}
if(mintime <= 0L)
mintime = dao.findMaxTime() - oneday;
List<FeedItem> lst = null;
for(int i=0; i<6; i++) {
lst = dao.getPage(mintime, pagesize);
if(lst != null && lst.size() > 0)
break;
}
if(lst == null || lst.size() == 0)
return null;
for(FeedItem fi: lst) {
fi.loadContent(tmpDir);
}
mintime = lst.get(lst.size()-1).getPublished();
maxtime = lst.get(0).getPublished();
Log.d("", "loadnew mintime: "+mintime + " maxtime: "+maxtime);
return lst;
}
public List<FeedItem> loadold() throws Exception {
if(dao == null)
return null;
maxtime = mintime;
mintime = mintime - oneday;
Log.d("", "loadold begin: "+mintime + " "+maxtime);
List<FeedItem> lst = dao.getPage(mintime, maxtime, pagesize);
if(lst == null || lst.size() == 0) {
Log.w("", "load old failed lst is null:"+(lst== null));
return null;
}
for(FeedItem fi: lst) {
fi.loadContent(tmpDir);
}
mintime = lst.get(lst.size()-1).getPublished();
maxtime = lst.get(0).getPublished();
Log.d("", "loadold mintime: "+mintime + " maxtime: "+maxtime + " count: "+lst.size());
return lst;
}
public void content(String feed) throws Exception {
// https://www.inoreader.com/reader/api/0/stream/contents/user%2F-%2Fstate%2Fcom.google%2Fread
if(auth == null)
login();
String url = api_url + "stream/contents/" + feed;
String content = get(url);
if(content != null) {
JsonUtil ju = new JsonUtil();
List<FeedItem> lst = ju.parseStream(content);
}
}
/**
* 删除上个月及以前的内容, 包括文件和sqlite中的
*/
public String removeOldContent() {
long tm = TextUtil.getLastDayOfLastMonth();
List<MN> m = dao.getmn();
MN mn = m.get(0);
//Log.d("", "all rowcount:"+dao.getCount() + " tm:"+tm + " minp:"+mn.getMnp() + " mxp:"+mn.getMxp());
int deleteRows = dao.deleteByPubTime(tm);
Log.d("", "all rowcount:"+dao.getCount() + " delcount:"+deleteRows + " tm:"+tm + " minp:"+mn.getMnp() + " mxp:"+mn.getMxp());
String mon = null;
int deleteFiles = 0;
while(true) {
mon = TextUtil.getLastMonthStr(mon);
String fpath = realPath(mon);
File f = new File(fpath);
Log.d("", "delete file: "+f.getAbsolutePath() + " exists:"+f.exists());
if(!f.exists())
break;
f.delete();
deleteFiles += 1;
}
return "removeOldContent summury:\n deleteRows: " +deleteRows + " deleteFiles: "+deleteFiles;
}
public void login() throws Exception {
log("----login");
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
formparams.add(new BasicNameValuePair("Email", "<EMAIL>"));
formparams.add(new BasicNameValuePair("Passwd", "helloworld"));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);
URI uri = new URI(base_url + "/accounts/ClientLogin");
HttpPost post = new HttpPost(uri);
post.setEntity(entity);
addDefHeaders(post);
CloseableHttpResponse resp = httpclient.execute(post);
int statusCode = resp.getStatusLine().getStatusCode();
if(200 == statusCode) {
//printResp(resp);
String s = EntityUtils.toString(resp.getEntity());
auth = strMid(s, "Auth=", "\n");
Utils.stringToFile(auth_file, auth);
}else {
log("login failed");
}
}
private final String strMid(String s, String b, String e) {
if(s == null) return null;
int p = s.indexOf(b);
if(p < 0) return null;
p += b.length();
int p1 = s.indexOf(e, p);
if(p1 > 0) return s.substring(p, p1);
return s.substring(p);
}
private void printResp(HttpResponse resp) throws IOException{
log("==response: "+resp.getStatusLine());
for(Header h: resp.getAllHeaders()) {
log(" "+ h.getName() + ": " + h.getValue());
}
log(EntityUtils.toString(resp.getEntity()));
}
public void get(String url, String fname) throws Exception {
HttpGet get = new HttpGet(url);
addDefHeaders(get);
CloseableHttpResponse resp = httpclient.execute(get);
int length = -1;
if(resp.getFirstHeader("content-length") != null) {
length = Integer.parseInt(resp.getFirstHeader("content-length").getValue())/1024;
}
log("execute get "+url +" return "+resp.getStatusLine() + " length:"+length + " kb");
saveResp(resp, fname);
}
public String get(String url) throws Exception {
HttpGet get = new HttpGet(url);
addDefHeaders(get);
CloseableHttpResponse resp = httpclient.execute(get);
final int rcode = resp.getStatusLine().getStatusCode();
log("--get "+url + " return "+rcode + " rootDir="+rootDir);
if(200 == rcode) {
return EntityUtils.toString(resp.getEntity());
}else if(401 == rcode){
if(rootDir != null) {
login();
return get(url);
}
}else {
log("get failed:" + resp.getStatusLine());
}
return null;
}
private void saveResp(CloseableHttpResponse resp, String fname) throws Exception {
if(200 != resp.getStatusLine().getStatusCode()) {
log("saveResp failed, request failed with:"+resp.getStatusLine());
return;
}
fname = realPath(fname);
OutputStream fw = new FileOutputStream(fname);
String ctype = resp.getFirstHeader("Content-Type").getValue();
if(ctype.indexOf("application/json") > 0 && !fname.endsWith(".json"))
fname = fname + ".json";
else if(ctype.indexOf("text/html") > 0 && !fname.endsWith(".html"))
fname = fname + ".html";
else if(ctype.indexOf("application/javascript") > 0 && !fname.endsWith(".js"))
fname = fname + ".js";
try {
HttpEntity entity = resp.getEntity();
entity.writeTo(fw);
log("response save to "+fname);
} finally {
resp.close();
fw.close();
}
}
private static void log(Object msg) {
System.out.println(msg);
}
private String auth = null;
private void addDefHeaders(HttpRequestBase req) {
if(auth != null) // Authorization: GoogleLogin auth=
req.addHeader("Authorization", "GoogleLogin auth="+auth);
req.addHeader("AppId", "1000000383");
req.addHeader("AppKey", "<KEY>");
req.addHeader("accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
req.addHeader("accept-encoding", "gzip, deflate, br");
req.addHeader("accept-language", "zh-CN,zh;q=0.9,en;q=0.8");
req.addHeader("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36");
}
}
|
atveit/vespa | bundle-plugin/src/main/scala/com/yahoo/container/plugin/mojo/Artifacts.scala | // Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.container.plugin.mojo
import org.apache.maven.artifact.Artifact
import org.apache.maven.project.MavenProject
import scala.collection.JavaConverters._
/**
* @author tonytv
*/
object Artifacts {
def getArtifacts(project : MavenProject) = {
type artifactSet = java.util.Set[Artifact]
val artifacts = project.getArtifacts.asInstanceOf[artifactSet].asScala.groupBy(_.getScope)
def isTypeJar(artifact : Artifact) = artifact.getType == "jar"
def getByScope(scope: String) =
artifacts.getOrElse(scope, Iterable.empty).partition(isTypeJar)
val (jarArtifactsToInclude, nonJarArtifactsToInclude) = getByScope(Artifact.SCOPE_COMPILE)
val (jarArtifactsProvided, nonJarArtifactsProvided) = getByScope(Artifact.SCOPE_PROVIDED)
(jarArtifactsToInclude, jarArtifactsProvided, nonJarArtifactsToInclude ++ nonJarArtifactsProvided)
}
def getArtifactsToInclude(project: MavenProject) = getArtifacts(project)._1
}
|
neotracker/neotracker-wallet | src/wallet/shared/components/select/SelectCard.js | <filename>src/wallet/shared/components/select/SelectCard.js
/* @flow */
import { Link as RRLink } from 'react-router-dom';
import React from 'react';
import classNames from 'classnames';
import {
compose,
getContext,
pure,
withHandlers,
} from 'recompose';
import { connect } from 'react-redux';
import { createStyleSheet } from 'jss-theme-reactor';
import { graphql } from 'react-relay';
import { type AppStyleManager } from '~/src/shared/styles/createStyleManager';
import {
Button,
Card,
Collapse,
Typography,
} from '~/src/lib/components/shared/base';
import {
Link,
} from '~/src/lib/components/shared/link';
import {
AccountView,
} from '~/src/wallet/shared/components/account';
import {
Selector,
} from '~/src/lib/components/shared/selector';
import { Tooltip } from '~/src/lib/components/shared/tooltip';
import { type Wallet } from '~/src/wallet/shared/wallet';
import type { WalletContext } from '~/src/wallet/shared/WalletContext';
import * as routes from '~/src/wallet/shared/routes';
import {
deleteWallet,
selectWallet,
selectWallets,
} from '~/src/wallet/shared/redux';
import { fragmentContainer } from '~/src/lib/graphql/shared/relay';
import {
type SelectCard_address,
} from './__generated__/SelectCard_address.graphql';
import UnlockWallet from './UnlockWallet';
const styleSheet = createStyleSheet('SelectCard', theme => ({
[theme.breakpoints.down('sm')]: {
header: {
paddingLeft: theme.spacing.unit,
paddingTop: theme.spacing.unit,
},
content: {
padding: theme.spacing.unit,
},
},
[theme.breakpoints.up('sm')]: {
header: {
paddingLeft: theme.spacing.unit * 2,
paddingTop: theme.spacing.unit * 2,
paddingRight: theme.spacing.unit,
paddingBottom: theme.spacing.unit,
},
content: {
padding: theme.spacing.unit * 2,
},
},
content: {},
header: {
alignItems: 'center',
borderBottom: `1px solid ${theme.palette.text.lightDivider}`,
display: 'flex',
justifyContent: 'space-between',
flexWrap: 'wrap',
},
headerGroup: {
alignItems: 'center',
display: 'flex',
flexWrap: 'wrap',
},
selectorArea: {
alignItems: 'center',
display: 'flex',
flex: '0 1 auto',
marginBottom: theme.spacing.unit,
marginRight: theme.spacing.unit,
minWidth: 0,
},
buttonArea: {
alignItems: 'center',
display: 'flex',
flexWrap: 'wrap',
},
title: {
marginRight: theme.spacing.unit / 2,
},
selector: {
maxWidth: theme.spacing.unit * 50,
minWidth: 0,
},
buttonText: {
color: theme.custom.colors.common.white,
},
buttonMargin: {
marginBottom: theme.spacing.unit,
marginRight: theme.spacing.unit,
},
link: {
display: 'block',
textDecoration: 'none',
},
}));
type ExternalProps = {|
wallet: ?Wallet,
address?: any,
loading?: boolean,
error?: ?Error,
retry?: ?() => void,
forward?: boolean,
className?: string,
|};
// eslint-disable-next-line
type InternalProps = {|
address: SelectCard_address,
wallets: Array<Wallet>,
onSelect: (wallet: Object) => void,
onClickDeleteWallet: () => void,
styleManager: AppStyleManager,
walletContext: WalletContext,
|};
/* ::
type Props = {|
...ExternalProps,
...InternalProps,
|};
*/
function SelectCard({
wallet,
address,
loading,
error,
retry,
forward,
className,
wallets,
onSelect,
onClickDeleteWallet,
styleManager,
walletContext,
}: Props): React.Element<*> {
const classes = styleManager.render(styleSheet);
let selector;
if (wallets.length > 0) {
selector = (
<div className={classes.selectorArea}>
<Typography className={classes.title} type="title">
Wallet
</Typography>
<Selector
className={classes.selector}
id="select-wallet"
label="Select Wallet"
options={wallets.map(walletOption => ({
id: walletOption.address,
text: walletOption.name,
wallet: walletOption,
}))}
selectedID={
wallet == null
? null
: wallet.address
}
selectText="Select Wallet"
onSelect={onSelect}
/>
</div>
);
}
const makeButton = ({
path,
onClick,
text,
tooltip,
}: {
// eslint-disable-next-line
path?: string,
// eslint-disable-next-line
onClick?: () => void,
text: string,
tooltip: string,
}) => {
let button = (
<Button
className={classNames({
[classes.buttonMargin]: path == null,
})}
raised
color="primary"
onClick={onClick}
>
<Typography
className={classes.buttonText}
type="body1"
>
{text}
</Typography>
</Button>
);
if (path != null) {
button = (
<RRLink
className={classNames(
classes.link,
classes.buttonMargin,
)}
to={routes.makePath(walletContext, path)}
>
{button}
</RRLink>
);
}
return (
<Tooltip
title={tooltip}
position="bottom"
>
{button}
</Tooltip>
);
};
let deleteButton;
if (wallet != null) {
deleteButton = makeButton({
onClick: onClickDeleteWallet,
text: 'DELETE WALLET',
tooltip:
'Delete the currently selected wallet from local storage. This does ' +
'not delete the address or the funds at the address, it only ' +
'removes it from storage local to your computer.',
});
}
let content;
if (wallet == null) {
content = (
<Typography className={classes.content} type="body1">
Create a new wallet or open an existing one to view balance and claim GAS.
</Typography>
);
} else if (wallet.isLocked) {
content = <UnlockWallet wallet={wallet} forward={forward} />;
} else {
content = (
<AccountView
wallet={wallet}
address={address}
loading={loading}
error={error}
retry={retry}
forward={forward}
/>
);
}
return (
<Card className={className}>
<div className={classes.header}>
<div className={classes.headerGroup}>
{selector}
<div className={classes.buttonArea}>
{makeButton({
path: routes.NEW_WALLET,
text: 'NEW WALLET',
tooltip:
'Generate a new private key and address in order to interact ' +
'with the blockchain to receive NEO or GAS, claim GAS and more.',
})}
{makeButton({
path: routes.OPEN_WALLET,
text: 'OPEN WALLET',
tooltip:
'Open a wallet to interact with the blockchain in order to send ' +
'NEO or GAS, claim GAS and more.',
})}
{deleteButton}
</div>
</div>
<Link
className={classes.buttonMargin}
path={routes.makePath(walletContext, routes.WALLET_FAQ)}
title="FAQ"
type="subheading"
component="p"
/>
</div>
<Collapse
in={content != null}
transitionDuration="auto"
>
{content}
</Collapse>
</Card>
);
}
export default (compose(
getContext({
styleManager: () => null,
walletContext: () => null,
}),
connect(
(state, { walletContext }) => ({
wallets: selectWallets(walletContext, state),
}),
dispatch => ({
onSelect: (option: Object) => dispatch(selectWallet({
wallet: option.wallet,
})),
onDelete: (wallet: Wallet) => dispatch(deleteWallet({ wallet })),
}),
),
withHandlers({
onClickDeleteWallet: ({ onDelete, wallet }) => () => onDelete(wallet),
}),
fragmentContainer({
address: graphql`
fragment SelectCard_address on Address {
...AccountView_address
}
`
}),
pure,
)(SelectCard): Class<React.Component<void, ExternalProps, void>>);
|
WUttts/laboratory | src/main/java/com/mafei/laboratory/system/entity/SysUser.java | package com.mafei.laboratory.system.entity;
import lombok.Data;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;
/**
* 用户信息表
* @author wts
*/
@Entity
@Data
@Table(name = "sys_user")
public class SysUser implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 用户ID
*/
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "user_id", nullable = false)
private Long userId;
/**
* 部门ID
*/
@Column(name = "dept_id")
private Long deptId;
/**
* 登录账号
*/
@Column(name = "login_name", nullable = false)
private String loginName;
/**
* 用户昵称
*/
@Column(name = "user_name")
private String userName;
/**
* 用户类型(00系统用户 01注册用户)
*/
@Column(name = "user_type")
private String userType;
/**
* 用户邮箱
*/
@Column(name = "email")
private String email;
/**
* 手机号码
*/
@Column(name = "phonenumber")
private String phonenumber;
/**
* 用户性别(0男 1女 2未知)
*/
@Column(name = "sex")
private String sex;
/**
* 头像路径
*/
@Column(name = "avatar",columnDefinition = "VARCHAR(100) default https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png")
private String avatar;
/**
* 密码
*/
@Column(name = "password")
private String password;
/**
* 盐加密
*/
@Column(name = "salt")
private String salt;
/**
* 帐号状态(0正常 1停用)
*/
@Column(name = "status")
private String status;
/**
* 删除标志(0代表存在 2代表删除)
*/
@Column(name = "del_flag")
private String delFlag;
/**
* 最后登录IP
*/
@Column(name = "login_ip")
private String loginIp;
/**
* 最后登录时间
*/
@Column(name = "login_date")
private Date loginDate;
/**
* 密码最后更新时间
*/
@Column(name = "pwd_update_date")
private Date pwdUpdateDate;
/**
* 创建者
*/
@Column(name = "create_by")
private String createBy;
/**
* 创建时间
*/
@Column(name = "create_time")
private Date createTime;
/**
* 更新者
*/
@Column(name = "update_by")
private String updateBy;
/**
* 更新时间
*/
@Column(name = "update_time")
private Date updateTime;
/**
* 备注
*/
@Column(name = "remark")
private String remark;
}
|
wombats-writing-code/fbw-platform-common | reducers/Result/__tests__/result.unit-spec.js | <reponame>wombats-writing-code/fbw-platform-common
var _index=require('../index');var _index2=_interopRequireDefault(_index);
var _getResults=require('../getResults');
var _getStudentResult=require('../getStudentResult');
var _createMission=require('../../edit-mission/createMission');
var _deleteMission=require('../../edit-mission/deleteMission');function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{'default':obj};}var chai=require('chai');var should=require('should');chai.should();
describe('result reducer',function(){
it('should update results and progress in state upon RECEIVE_RESULTS results',function(){
var newState=(0,_index2['default'])({},{
type:_getResults.RECEIVE_RESULTS,
results:[
{name:'baz',mission:'1'},
{name:'foo',mission:'1'}]});
newState.resultsByMission['1'][0].name.should.be.eql('baz');
newState.resultsByMission['1'][1].name.should.be.eql('foo');
newState.isGetResultsInProgress.should.be.eql(false);
});
it('should update the current result state upon GET_STUDENT_RESULT',function(){
var newState=(0,_index2['default'])({},{
type:_getStudentResult.GET_STUDENT_RESULT_SUCCESS,
student:'batman',
mission:{displayName:'foo'},
questions:[1,2]});
newState.currentStudent.should.eql('batman');
newState.currentMission.displayName.should.eql('foo');
newState.currentMission.questions.should.eql([1,2]);
newState.isGetStudentResultInProgress.should.eql(false);
});
it('should update the dictionary of results state upon RECEIVE_DELETE_MISSION',function(){
var newState=(0,_index2['default'])({
resultsByMission:{
foo:['1','2','3'],
bar:['another','series','of','records']}},
{
type:_deleteMission.RECEIVE_DELETE_MISSION,
mission:{id:'foo'}});
should.not.exist(newState.resultsByMission['foo']);
newState.resultsByMission['bar'].should.eql(['another','series','of','records']);
});
}); |
deeptexas-ai/test | Common/script/src/csv_adapter.h | <gh_stars>1-10
/**
* \file csv_adapter.h
* \brief csv脚本适配器类头文件
*
* Copyright (c) 2019
* All rights reserved.
*
* \version 1.0
* \author jj
*/
#ifndef __CSV_ADAPTER_H__
#define __CSV_ADAPTER_H__
#include "csv_variant.h"
#include "csv_row.h"
#include <vector>
#include "fileloader.h"
#include "strutil.h"
using namespace dtutil;
namespace dtscript
{
//class FileLoader;
/**
* \brief csv脚本适配器
* \ingroup script_group
*/
class CsvAdapter : public ICsvIterator
{
enum
{
CSV_TITLE_ROW_COUNT = 3, ///< csv标题行数量,第一行为中文字段,第二行为英文字段,第三行为protobuf字段
};
public:
/**
* \brief 构造函数
*/
CsvAdapter(void);
/**
* \brief 析构函数
*/
virtual ~CsvAdapter(void);
public:
/**
* \brief 获得文档内容的行数
* \return 文档内容的行数
*/
virtual size_t Size();
/**
* \brief 根据指定行数获得数据
* \param nIndex 行数索引
* \return 指定行数据
*/
virtual CsvVariant & operator [] (size_t nIndex);
/**
* \brief 根据指定名称获得数据
* \param szName 指定名称
* \return 指定名称的数据
*/
virtual CsvVariant & operator [] (const char *szName);
public:
/**
* \brief 装载脚本
* \param szFileName 脚本文件
* \param bEncrypt 是否加密
* \return 装载成功返回true,否则返回false
*/
bool LoadScript(const char *szFileName, bool bEncrypt);
/**
* \brief 装载脚本数据
* \param pData 脚本数据
* \param nLen 数据大小
* \return 装载成功返回true,否则返回false
*/
bool LoadScript(LPCSTR pData, size_t nLen);
/**
* \brief 根据参数名称查找参数在第几列
* \param szName 列名称
* \return 参数所在列索引,非列表参数返回-1
*/
int32 FindPropName(const char *szName);
private:
/**
* \brief 装载csv脚本
* \param szFileName 脚本文件
* \return 装载成功返回true,否则返回false
*/
bool LoadScriptCsv(const char *szFileName);
/**
* \brief 装载cse脚本(加密csv脚本)
* \param szFileName 脚本文件
* \return 装载成功返回true,否则返回false
*/
bool LoadScriptCse(const char *szFileName);
/**
* \brief 装载脚本文件
* \param file 加载好的脚本文件
* \return 装载成功返回true,否则返回false
*/
bool LoadScriptFile(FileLoader *file);
/**
* \brief 根据指定行数获得数据
* \param nIndex 行数索引
* \return 指定行数据
*/
CsvVariant & GetData(size_t nIndex);
/**
* \brief 根据指定名称获得数据
* \param szName 指定名称
* \return 指定名称的数据
*/
CsvVariant & GetData(const char *szName);
private:
CsvRow m_Title[CSV_TITLE_ROW_COUNT]; ///< 标题,第一行为中文字段,第二行为英文字段,第三行为protobuf字段
std::vector<CsvVariant> m_RowTable; ///< 行数据列表,从第四行开始到文件尾
};
}
#endif // __CSV_ADAPTER_H__ |
vunamhung/codebases | bonobos.com/components/text_tag.js | <reponame>vunamhung/codebases
import React from "react"
import PropTypes from "prop-types"
import classNames from "classnames"
import styles from "highline/styles/components/text_tag.module.css"
class TextTag extends React.PureComponent {
static propTypes = {
checked: PropTypes.bool,
children: PropTypes.node.isRequired,
className: PropTypes.string,
disabled: PropTypes.bool,
readOnly: PropTypes.bool,
}
render() {
const { checked, children, className, disabled, readOnly, ...other } = this.props
return (
<div
className={ classNames(
"text-tag-component",
"component",
styles.component,
className,
) }
{ ...other }
>
<div
className={ classNames(
styles.container,
checked ? styles.checked : styles.unchecked,
disabled ? styles.disabled : null,
readOnly ? styles.readOnly : null,
) }
>
<span className={ styles.text }>{ children }</span>
</div>
</div>
)
}
}
export default TextTag
|
ricksjames/big-data-plugin | api/runtimeTest/src/test/java/org/pentaho/runtime/test/network/impl/GatewayConnectivityTestImplTest.java | /*******************************************************************************
*
* Pentaho Big Data
*
* Copyright (C) 2002-2017 by <NAME> : http://www.pentaho.com
*
*******************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
package org.pentaho.runtime.test.network.impl;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.HttpContext;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import org.pentaho.runtime.test.TestMessageGetterFactory;
import org.pentaho.runtime.test.i18n.MessageGetter;
import org.pentaho.runtime.test.i18n.MessageGetterFactory;
import org.pentaho.runtime.test.result.RuntimeTestEntrySeverity;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import java.io.IOException;
import java.net.URI;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import static org.mockito.Matchers.anyObject;
import static org.mockito.Mockito.*;
import static org.pentaho.runtime.test.RuntimeTestEntryUtil.verifyRuntimeTestResultEntry;
/**
* Created by dstepanov on 29/04/17.
*/
public class GatewayConnectivityTestImplTest {
public static final String HTTPS = "https://";
public static final String HTTP = "http://";
public static final String KETTLE_KNOX_IGNORE_SSL = "KETTLE_KNOX_IGNORE_SSL";
private String hostname;
private String port;
private RuntimeTestEntrySeverity severityOfFailures;
private ConnectivityTestImpl connectTest;
private MessageGetterFactory messageGetterFactory;
private MessageGetter messageGetter;
private URI uri;
private String path;
private String topology;
private String user;
private String password;
private HttpClient httpClient;
@Before
public void setup() throws IOException {
messageGetterFactory = new TestMessageGetterFactory();
messageGetter = messageGetterFactory.create( ConnectivityTestImpl.class );
hostname = "hostname";
port = "8443";
user = "user";
password = "password";
topology = "/gateway/default";
path = "/testPath";
uri = URI.create( HTTPS + hostname + ":" + port + topology );
severityOfFailures = RuntimeTestEntrySeverity.WARNING;
httpClient = mock( HttpClient.class, Mockito.CALLS_REAL_METHODS );
HttpResponse httpResponseMock = mock(HttpResponse.class);
StatusLine statusLineMock = mock(StatusLine.class);
doReturn( httpResponseMock ).when( httpClient ).execute( anyObject() );
doReturn( httpResponseMock ).when( httpClient ).execute( any( HttpUriRequest.class ), any( HttpContext.class) );
doReturn( statusLineMock ).when( httpResponseMock ).getStatusLine();
doReturn( 200 ).when( statusLineMock ).getStatusCode();
init();
System.setProperty( KETTLE_KNOX_IGNORE_SSL, "false" );
}
private void init() {
connectTest =
new GatewayConnectivityTestImpl( messageGetterFactory, uri, path, user, password, severityOfFailures ) {
@Override
HttpClient getHttpClient() {
return HttpClients.createDefault();
}
};
}
private void initMock() {
connectTest =
new GatewayConnectivityTestImpl( messageGetterFactory, uri, path, user, password, severityOfFailures ) {
@Override
HttpClient getHttpClient() {
return httpClient;
}
@Override
HttpClient getHttpClient( String user, String password ) {
return httpClient;
}
};
}
@Test
public void testHttp() throws IOException {
uri = URI.create( HTTP + hostname + ":" + port + topology );
initMock();
verifyRuntimeTestResultEntry( connectTest.runTest(), RuntimeTestEntrySeverity.INFO,
messageGetter.getMessage( GatewayConnectivityTestImpl.GATEWAY_CONNECT_TEST_CONNECT_SUCCESS_DESC ),
messageGetter.getMessage( GatewayConnectivityTestImpl.GATEWAY_CONNECT_TEST_CONNECT_SUCCESS_MESSAGE,
uri.toString() + path ) );
}
@Test
public void testBlankHostname() {
uri = URI.create( HTTPS + "" + ":" + port + topology );
initMock();
verifyRuntimeTestResultEntry( connectTest.runTest(), severityOfFailures,
messageGetter.getMessage( ConnectivityTestImpl.CONNECT_TEST_HOST_BLANK_DESC ), messageGetter.getMessage(
ConnectivityTestImpl.CONNECT_TEST_HOST_BLANK_MESSAGE ) );
}
@Test
public void testUnknownHostException() throws IOException {
verifyRuntimeTestResultEntry( connectTest.runTest(), severityOfFailures,
messageGetter.getMessage( ConnectivityTestImpl.CONNECT_TEST_UNKNOWN_HOSTNAME_DESC ), messageGetter.getMessage(
ConnectivityTestImpl.CONNECT_TEST_UNKNOWN_HOSTNAME_MESSAGE, hostname ), UnknownHostException.class );
}
@Test
public void testIOException() throws IOException {
doThrow( new IOException() ).when( httpClient )
.execute( any( HttpUriRequest.class ), any( HttpContext.class ) );
initMock();
verifyRuntimeTestResultEntry( connectTest.runTest(), severityOfFailures,
messageGetter.getMessage( GatewayConnectivityTestImpl.GATEWAY_CONNECT_EXECUTION_FAILED_DESC ),
messageGetter.getMessage(
GatewayConnectivityTestImpl.GATEWAY_CONNECT_EXECUTION_FAILED_MESSAGE, uri.toString() + path ),
IOException.class );
}
@Test
public void testSSLException() throws IOException {
doThrow( new SSLException( "errorMessage" ) ).when( httpClient )
.execute( any( HttpUriRequest.class ), any( HttpContext.class ) );
initMock();
verifyRuntimeTestResultEntry( connectTest.runTest(), severityOfFailures,
messageGetter.getMessage( GatewayConnectivityTestImpl.GATEWAY_CONNECT_SSLEXCEPTION_DESC ),
messageGetter.getMessage(
GatewayConnectivityTestImpl.GATEWAY_CONNECT_SSLEXCEPTION_MESSAGE, uri.toString() + path, "errorMessage" ),
SSLException.class );
}
@Test
public void testNoSuchAlgorithmException() {
System.setProperty( KETTLE_KNOX_IGNORE_SSL, "true" );
connectTest =
new GatewayConnectivityTestImpl( messageGetterFactory, uri, path, user, password, severityOfFailures ) {
@Override SSLContext getTlsContext() throws NoSuchAlgorithmException {
throw new NoSuchAlgorithmException();
}
};
verifyRuntimeTestResultEntry( connectTest.runTest(), RuntimeTestEntrySeverity.FATAL,
messageGetter.getMessage( GatewayConnectivityTestImpl.GATEWAY_CONNECT_TLSCONTEXT_DESC ),
messageGetter.getMessage( GatewayConnectivityTestImpl.GATEWAY_CONNECT_TLSCONTEXT_MESSAGE ),
NoSuchAlgorithmException.class );
}
@Test
public void testKeyManagementException() {
System.setProperty( KETTLE_KNOX_IGNORE_SSL, "true" );
connectTest =
new GatewayConnectivityTestImpl( messageGetterFactory, uri, path, user, password, severityOfFailures ) {
@Override void initContextWithTrustAll( SSLContext ctx ) throws KeyManagementException {
throw new KeyManagementException();
}
};
verifyRuntimeTestResultEntry( connectTest.runTest(), RuntimeTestEntrySeverity.FATAL,
messageGetter.getMessage( GatewayConnectivityTestImpl.GATEWAY_CONNECT_TLSCONTEXTINIT_DESC ),
messageGetter.getMessage( GatewayConnectivityTestImpl.GATEWAY_CONNECT_TLSCONTEXTINIT_MESSAGE ),
KeyManagementException.class );
}
@Test
public void testSuccess() throws IOException {
initMock();
verifyRuntimeTestResultEntry( connectTest.runTest(), RuntimeTestEntrySeverity.INFO,
messageGetter.getMessage( GatewayConnectivityTestImpl.GATEWAY_CONNECT_TEST_CONNECT_SUCCESS_DESC ),
messageGetter.getMessage( GatewayConnectivityTestImpl.GATEWAY_CONNECT_TEST_CONNECT_SUCCESS_MESSAGE,
uri.toString() + path ) );
}
@Test
public void test401() throws IOException {
HttpResponse httpResponseMock = mock(HttpResponse.class);
StatusLine statusLineMock = mock(StatusLine.class);
doReturn( httpResponseMock ).when( httpClient ).execute( any( HttpUriRequest.class ), any( HttpContext.class) );
doReturn( statusLineMock ).when( httpResponseMock ).getStatusLine();
doReturn( 401 ).when( statusLineMock ).getStatusCode();
initMock();
verifyRuntimeTestResultEntry( connectTest.runTest(), severityOfFailures,
messageGetter.getMessage( GatewayConnectivityTestImpl.GATEWAY_CONNECT_TEST_UNAUTHORIZED_DESC ),
messageGetter
.getMessage( GatewayConnectivityTestImpl.GATEWAY_CONNECT_TEST_UNAUTHORIZED_MESSAGE, uri.toString() + path,
user ) );
}
@Test
public void test403() throws IOException {
HttpResponse httpResponseMock = mock(HttpResponse.class);
StatusLine statusLineMock = mock(StatusLine.class);
doReturn( httpResponseMock ).when( httpClient ).execute( any( HttpUriRequest.class ), any( HttpContext.class) );
doReturn( statusLineMock ).when( httpResponseMock ).getStatusLine();
doReturn( 403 ).when( statusLineMock ).getStatusCode();
initMock();
verifyRuntimeTestResultEntry( connectTest.runTest(), severityOfFailures,
messageGetter.getMessage( GatewayConnectivityTestImpl.GATEWAY_CONNECT_TEST_FORBIDDEN_DESC ),
messageGetter.getMessage(
GatewayConnectivityTestImpl.GATEWAY_CONNECT_TEST_FORBIDDEN_MESSAGE, uri.toString() + path, user ) );
}
@Test
public void test404() throws IOException {
HttpResponse httpResponseMock = mock(HttpResponse.class);
StatusLine statusLineMock = mock(StatusLine.class);
doReturn( httpResponseMock ).when( httpClient ).execute( any( HttpUriRequest.class ), any( HttpContext.class) );
doReturn( statusLineMock ).when( httpResponseMock ).getStatusLine();
doReturn( 404 ).when( statusLineMock ).getStatusCode();
initMock();
verifyRuntimeTestResultEntry( connectTest.runTest(), severityOfFailures,
messageGetter.getMessage( GatewayConnectivityTestImpl.GATEWAY_CONNECT_TEST_SERVICE_NOT_FOUND_DESC ),
messageGetter.getMessage(
GatewayConnectivityTestImpl.GATEWAY_CONNECT_TEST_SERVICE_NOT_FOUND_MESSAGE, uri.toString() + path ) );
}
@Test
public void testUnknownCode() throws IOException {
Integer returnCode = 0;
HttpResponse httpResponseMock = mock(HttpResponse.class);
StatusLine statusLineMock = mock(StatusLine.class);
doReturn( httpResponseMock ).when( httpClient ).execute( any( HttpUriRequest.class ), any( HttpContext.class ) );
doReturn( statusLineMock ).when( httpResponseMock ).getStatusLine();
doReturn( returnCode ).when( statusLineMock ).getStatusCode();
initMock();
verifyRuntimeTestResultEntry( connectTest.runTest(), RuntimeTestEntrySeverity.WARNING,
messageGetter.getMessage( GatewayConnectivityTestImpl.GATEWAY_CONNECT_TEST_CONNECT_UNKNOWN_RETURN_CODE_DESC ),
messageGetter
.getMessage( GatewayConnectivityTestImpl.GATEWAY_CONNECT_TEST_CONNECT_UNKNOWN_RETURN_CODE_MESSAGE, user,
returnCode.toString(), uri.toString() + path ) );
}
} |
guillaume-plantevin/VeeSeeVSTRack | plugins/community/repos/TheXOR/src/attenuator.cpp | #include "common.hpp"
#include "attenuator.hpp"
namespace rack_plugin_TheXOR {
void Attenuator::step()
{
for(int k = 0; k < NUM_ATTENUATORS; k++)
{
if(outputs[OUT_1 + k].active)
outputs[OUT_1 + k].value = inputs[IN_1 + k].value * params[ATT_1 + k].value;
}
}
AttenuatorWidget::AttenuatorWidget(Attenuator *module) : ModuleWidget(module)
{
box.size = Vec(8 * RACK_GRID_WIDTH, RACK_GRID_HEIGHT);
{
SVGPanel *panel = new SVGPanel();
panel->box.size = box.size;
panel->setBackground(SVG::load(assetPlugin(plugin, "res/modules/attenuator.svg")));
addChild(panel);
}
addChild(Widget::create<ScrewBlack>(Vec(RACK_GRID_WIDTH, 0)));
addChild(Widget::create<ScrewBlack>(Vec(box.size.x - 2 * RACK_GRID_WIDTH, 0)));
addChild(Widget::create<ScrewBlack>(Vec(RACK_GRID_WIDTH, RACK_GRID_HEIGHT - RACK_GRID_WIDTH)));
addChild(Widget::create<ScrewBlack>(Vec(box.size.x - 2 * RACK_GRID_WIDTH, RACK_GRID_HEIGHT - RACK_GRID_WIDTH)));
float in_x = mm2px(2.490);
float pot_x = mm2px(16.320);
float out_x = mm2px(29.894);
float y = yncscape(107.460, 8.255);
float ypot = yncscape(107.588, 8.0);
float delta_y = mm2px(19.0);
for(int k = 0; k < NUM_ATTENUATORS; k++)
{
addInput(Port::create<PJ301GRPort>(Vec(in_x, y), Port::INPUT, module, Attenuator::IN_1 + k));
addParam(ParamWidget::create<Davies1900hFixWhiteKnobSmall>(Vec(pot_x, ypot), module, Attenuator::ATT_1+k, 0.0, 1.0, 1.0));
addOutput(Port::create<PJ301GPort>(Vec(out_x, y), Port::OUTPUT, module, Attenuator::OUT_1+k));
y += delta_y;
ypot += delta_y;
}
}
} // namespace rack_plugin_TheXOR
using namespace rack_plugin_TheXOR;
RACK_PLUGIN_MODEL_INIT(TheXOR, Attenuator) {
return Model::create<Attenuator, AttenuatorWidget>("TheXOR", "Attenuator", "Attenuator", ATTENUATOR_TAG);
}
|
WolfSmartRAML/raml-dotnet-parser-2 | source/Raml.Parser/node_modules/raml-1-0-parser/node_modules/webpack/test/js/devtool-eval/chunks/named-chunks/1.bundle.js | <filename>source/Raml.Parser/node_modules/raml-1-0-parser/node_modules/webpack/test/js/devtool-eval/chunks/named-chunks/1.bundle.js
exports.ids = [1];
exports.modules = [
/* 0 */,
/* 1 */
/*!****************************************!*\
!*** ./chunks/named-chunks/empty.js?a ***!
\****************************************/
/***/ function(module, exports, __webpack_require__) {
eval("\n\n/*****************\n ** WEBPACK FOOTER\n ** ./chunks/named-chunks/empty.js?a\n ** module id = 1\n ** module chunks = 1\n **/\n//# sourceURL=webpack:///./chunks/named-chunks/empty.js?");
/***/ },
/* 2 */
/*!****************************************!*\
!*** ./chunks/named-chunks/empty.js?b ***!
\****************************************/
/***/ function(module, exports, __webpack_require__) {
eval("\n\n/*****************\n ** WEBPACK FOOTER\n ** ./chunks/named-chunks/empty.js?b\n ** module id = 2\n ** module chunks = 1\n **/\n//# sourceURL=webpack:///./chunks/named-chunks/empty.js?");
/***/ },
/* 3 */
/*!****************************************!*\
!*** ./chunks/named-chunks/empty.js?c ***!
\****************************************/
/***/ function(module, exports, __webpack_require__) {
eval("\n\n/*****************\n ** WEBPACK FOOTER\n ** ./chunks/named-chunks/empty.js?c\n ** module id = 3\n ** module chunks = 1\n **/\n//# sourceURL=webpack:///./chunks/named-chunks/empty.js?");
/***/ },
/* 4 */
/*!****************************************!*\
!*** ./chunks/named-chunks/empty.js?d ***!
\****************************************/
/***/ function(module, exports, __webpack_require__) {
eval("\n\n/*****************\n ** WEBPACK FOOTER\n ** ./chunks/named-chunks/empty.js?d\n ** module id = 4\n ** module chunks = 1\n **/\n//# sourceURL=webpack:///./chunks/named-chunks/empty.js?");
/***/ }
]; |
kaebmoo/simple-server | app/models/admin_access_control.rb | <filename>app/models/admin_access_control.rb
class AdminAccessControl < ApplicationRecord
belongs_to :admin
belongs_to :access_controllable, polymorphic: true
ACCESS_CONTROLLABLE_TYPE_FOR_ROLE = {
analyst: 'FacilityGroup',
supervisor: 'FacilityGroup',
counsellor: 'FacilityGroup',
organization_owner: 'Organization'
}
validates :admin, presence: true
end
|
reels-research/iOS-Private-Frameworks | HomeKitDaemon.framework/HMDCloudLegacyHomeDataRecord.h | <filename>HomeKitDaemon.framework/HMDCloudLegacyHomeDataRecord.h
/* Generated by RuntimeBrowser
Image: /System/Library/PrivateFrameworks/HomeKitDaemon.framework/HomeKitDaemon
*/
@interface HMDCloudLegacyHomeDataRecord : HMDCloudRecord
@property (nonatomic, retain) NSData *dataVersion2;
+ (id)legacyModelWithHomeDataV0:(id)arg1 homeDataV2:(id)arg2;
- (void)clearData;
- (id)data;
- (id)dataVersion2;
- (bool)encodeObjectChange:(id)arg1;
- (id)extractObjectChange;
- (unsigned long long)objectEncoding;
- (id)recordType;
- (void)setData:(id)arg1;
- (void)setDataVersion2:(id)arg1;
@end
|
LetterN/Railcraft | src/main/java/mods/railcraft/world/item/CrowbarHandler.java | <filename>src/main/java/mods/railcraft/world/item/CrowbarHandler.java<gh_stars>1-10
package mods.railcraft.world.item;
import java.util.Map;
import com.google.common.collect.MapMaker;
import mods.railcraft.RailcraftConfig;
import mods.railcraft.advancements.criterion.RailcraftCriteriaTriggers;
import mods.railcraft.api.carts.ILinkableCart;
import mods.railcraft.api.item.Crowbar;
import mods.railcraft.season.Season;
import mods.railcraft.world.entity.cart.CartTools;
import mods.railcraft.world.entity.cart.IDirectionalCart;
import mods.railcraft.world.entity.cart.LinkageManagerImpl;
import mods.railcraft.world.entity.cart.SeasonalCart;
import mods.railcraft.world.entity.cart.TrackRemoverMinecartEntity;
import mods.railcraft.world.entity.cart.Train;
import mods.railcraft.world.entity.cart.TunnelBoreEntity;
import mods.railcraft.world.item.enchantment.RailcraftEnchantments;
import net.minecraft.enchantment.EnchantmentHelper;
import net.minecraft.entity.item.minecart.AbstractMinecartEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.ServerPlayerEntity;
import net.minecraft.item.ItemStack;
import net.minecraft.util.Hand;
import net.minecraft.util.text.TranslationTextComponent;
/**
* @author CovertJaguar (https://www.railcraft.info)
*/
public class CrowbarHandler {
public static final float SMACK_VELOCITY = 0.07f;
private static final Map<PlayerEntity, AbstractMinecartEntity> linkMap =
new MapMaker()
.weakKeys()
.weakValues()
.makeMap();
public boolean handleInteract(AbstractMinecartEntity cart, PlayerEntity player, Hand hand) {
boolean cancel = false;
ItemStack stack = player.getItemInHand(hand);
if (stack.getItem() instanceof Crowbar) {
cancel = true;
}
if (!stack.isEmpty() && stack.getItem() instanceof Crowbar) {
player.swing(hand);
cancel = true;
} else {
return cancel;
}
if (player.level.isClientSide()) {
return cancel;
}
Crowbar crowbar = (Crowbar) stack.getItem();
if ((stack.getItem() instanceof SeasonsCrowbarItem) && (cart instanceof SeasonalCart)
&& RailcraftConfig.common.enableSeasons.get()) {
Season season = SeasonsCrowbarItem.getSeason(stack);
((SeasonalCart) cart).setSeason(season);
RailcraftCriteriaTriggers.SEASON_SET.trigger((ServerPlayerEntity) player, cart, season);
return true;
}
if (crowbar.canLink(player, hand, stack, cart)) {
linkCart(player, hand, stack, cart, crowbar);
return true;
} else if (crowbar.canBoost(player, hand, stack, cart)) {
boostCart(player, hand, stack, cart, crowbar);
return true;
}
return cancel;
}
private void linkCart(PlayerEntity player, Hand hand, ItemStack stack,
AbstractMinecartEntity cart, Crowbar crowbar) {
boolean used = false;
boolean linkable = cart instanceof ILinkableCart;
if (!linkable || ((ILinkableCart) cart).isLinkable()) {
AbstractMinecartEntity last = linkMap.remove(player);
if (last != null && last.isAlive()) {
LinkageManagerImpl lm = LinkageManagerImpl.INSTANCE;
if (lm.areLinked(cart, last, false)) {
lm.breakLink(cart, last);
used = true;
player.displayClientMessage(new TranslationTextComponent("crowbar.link_broken"), true);
LinkageManagerImpl.printDebug("Reason For Broken Link: User removed link.");
} else {
used = lm.createLink(last, cart);
if (used) {
if (!player.level.isClientSide()) {
RailcraftCriteriaTriggers.CART_LINK.trigger((ServerPlayerEntity)player, last, cart);
}
player.displayClientMessage(new TranslationTextComponent("crowbar.link_created"), true);
}
}
if (!used) {
player.displayClientMessage(new TranslationTextComponent("crowbar.link_failed"), true);
}
} else {
linkMap.put(player, cart);
player.displayClientMessage(new TranslationTextComponent("crowbar.link_started"), true);
}
}
if (used) {
crowbar.onLink(player, hand, stack, cart);
}
}
private void boostCart(PlayerEntity player, Hand hand, ItemStack stack,
AbstractMinecartEntity cart, Crowbar crowbar) {
player.causeFoodExhaustion(.25F);
if (player.getVehicle() != null) {
// NOOP
} else if (cart instanceof TunnelBoreEntity) {
// NOOP
} else if (cart instanceof IDirectionalCart) {
((IDirectionalCart) cart).reverse();
} else if (cart instanceof TrackRemoverMinecartEntity) {
TrackRemoverMinecartEntity trackRemover = (TrackRemoverMinecartEntity) cart;
trackRemover.setMode(trackRemover.getMode().getNext());
} else {
int lvl = EnchantmentHelper.getItemEnchantmentLevel(RailcraftEnchantments.SMACK.get(), stack);
if (lvl == 0) {
CartTools.smackCart(cart, player, SMACK_VELOCITY);
}
Train.get(cart).ifPresent(train -> {
float smackVelocity = SMACK_VELOCITY * (float) Math.pow(1.7, lvl);
smackVelocity /= (float) Math.pow(train.size(), 1D / (1 + lvl));
for (AbstractMinecartEntity each : train) {
CartTools.smackCart(cart, each, player, smackVelocity);
}
});
}
crowbar.onBoost(player, hand, stack, cart);
}
}
|
JacobsonMT/Gemma | gemma-core/src/main/java/ubic/gemma/core/analysis/expression/coexpression/links/LinkAnalysisConfig.java | <filename>gemma-core/src/main/java/ubic/gemma/core/analysis/expression/coexpression/links/LinkAnalysisConfig.java
/*
* The Gemma project
*
* Copyright (c) 2007 Columbia University
*
* 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 ubic.gemma.core.analysis.expression.coexpression.links;
import ubic.gemma.model.analysis.expression.coexpression.CoexpressionAnalysis;
import ubic.gemma.model.common.protocol.Protocol;
import java.io.File;
import java.io.Serializable;
/**
* Holds parameters needed for LinkAnalysis. Note that many of these settings are not typically changed from the
* defaults; they are there for experimentation.
*
* @author Paul
*/
@SuppressWarnings({ "WeakerAccess", "unused" }) // Possible exernal use
public class LinkAnalysisConfig implements Serializable {
/**
* probes with more links than this are ignored. Zero means this doesn't do anything.
*/
@SuppressWarnings({ "unused", "WeakerAccess" }) // Possible external use
public static final Integer DEFAULT_PROBE_DEGREE_THRESHOLD = 0;
private static final long serialVersionUID = 1L;
private boolean absoluteValue = false;
private String arrayName = null;
/**
* what proportion of links to keep (possibly subject to FWE statistical significance threshold). 1.0 means keep
* everything. 0.01 means 1%.
*/
private double cdfCut = 0.01;
private boolean checkCorrelationDistribution = true;
/**
* only used for internal cache during calculations.
*/
private double correlationCacheThreshold = 0.8;
private boolean checkForBatchEffect = true;
private boolean checkForOutliers = true;
/**
* family-wise error rate threshold we use to select links
*/
private double fwe = 0.01;
private boolean lowerCdfCutUsed = false;
private double lowerTailCut = 0.01;
private boolean makeSampleCorrMatImages = true;
private String metric = "pearson"; // spearman
/**
* How many samples must be present in a correlation pair to keep the data, taking into account missing values.
*/
private int minNumPresent = AbstractMatrixRowPairAnalysis.HARD_LIMIT_MIN_NUM_USED;
private NormalizationMethod normalizationMethod = NormalizationMethod.none;
/**
* Remove negative correlated values at the end.
*/
private boolean omitNegLinks = false;
/**
* Only used if textOut = true; if null, just write to stdout.
*/
private File outputFile = null;
/**
* Probes with more than this many links are removed. Zero means no action is taken.
*/
private int probeDegreeThreshold = DEFAULT_PROBE_DEGREE_THRESHOLD;
private SingularThreshold singularThreshold = SingularThreshold.none; // fwe|cdfCut
private boolean subset = false;
private double subsetSize = 0.0;
private boolean subsetUsed = false;
private boolean textOut;
private boolean upperCdfCutUsed = false;
private double upperTailCut = 0.01;
private boolean useDb = true;
public boolean isCheckForBatchEffect() {
return checkForBatchEffect;
}
public void setCheckForBatchEffect( boolean rejectForBatchEffect ) {
this.checkForBatchEffect = rejectForBatchEffect;
}
public boolean isCheckForOutliers() {
return checkForOutliers;
}
public void setCheckForOutliers( boolean rejectForOutliers ) {
this.checkForOutliers = rejectForOutliers;
}
public String getArrayName() {
return arrayName;
}
public void setArrayName( String arrayName ) {
this.arrayName = arrayName;
}
public double getCdfCut() {
return cdfCut;
}
public void setCdfCut( double cdfCut ) {
this.cdfCut = cdfCut;
}
public double getCorrelationCacheThreshold() {
return correlationCacheThreshold;
}
public void setCorrelationCacheThreshold( double correlationCacheThreshold ) {
this.correlationCacheThreshold = correlationCacheThreshold;
}
public double getFwe() {
return fwe;
}
public void setFwe( double fwe ) {
this.fwe = fwe;
}
public double getLowerTailCut() {
return lowerTailCut;
}
public void setLowerTailCut( double lowerTailCut ) {
this.lowerTailCut = lowerTailCut;
}
public String getMetric() {
return metric;
}
public void setMetric( String metric ) {
checkValidMetric( metric );
this.metric = metric;
}
public int getMinNumPresent() {
return minNumPresent;
}
public void setMinNumPresent( int minNumPresent ) {
this.minNumPresent = minNumPresent;
}
/**
* @return the normalizationMethod
*/
public NormalizationMethod getNormalizationMethod() {
return normalizationMethod;
}
/**
* @param normalizationMethod the normalizationMethod to set
*/
public void setNormalizationMethod( NormalizationMethod normalizationMethod ) {
this.normalizationMethod = normalizationMethod;
}
public File getOutputFile() {
return outputFile;
}
public void setOutputFile( File outputFile ) {
this.outputFile = outputFile;
}
public Integer getProbeDegreeThreshold() {
return this.probeDegreeThreshold;
}
/**
* Probe degree threshold: Probes with more than this number of links are ignored. If set to <= 0, this setting is
* ignored.
*
* @param probeDegreeThreshold the probeDegreeThreshold to set
*/
public void setProbeDegreeThreshold( int probeDegreeThreshold ) {
this.probeDegreeThreshold = probeDegreeThreshold;
}
/**
* @return the singularThreshold
*/
public SingularThreshold getSingularThreshold() {
return singularThreshold;
}
/**
* Set to modify threshold behaviour: enforce the choice of only one of the two standard thresholds.
*
* @param singularThreshold the singularThreshold to set. Default is 'none'.
*/
public void setSingularThreshold( SingularThreshold singularThreshold ) {
this.singularThreshold = singularThreshold;
}
public double getSubsetSize() {
return subsetSize;
}
public void setSubsetSize( double subsetSize ) {
this.subsetSize = subsetSize;
}
public double getUpperTailCut() {
return upperTailCut;
}
public void setUpperTailCut( double upperTailCut ) {
this.upperTailCut = upperTailCut;
}
public boolean isAbsoluteValue() {
return absoluteValue;
}
public void setAbsoluteValue( boolean absoluteValue ) {
this.absoluteValue = absoluteValue;
}
public boolean isCheckCorrelationDistribution() {
return this.checkCorrelationDistribution;
}
public void setCheckCorrelationDistribution( boolean checkCorrelationDistribution ) {
this.checkCorrelationDistribution = checkCorrelationDistribution;
}
/**
* @return the lowerCdfCutUsed
*/
public boolean isLowerCdfCutUsed() {
return lowerCdfCutUsed;
}
/**
* @param lowerCdfCutUsed the lowerCdfCutUsed to set
*/
public void setLowerCdfCutUsed( boolean lowerCdfCutUsed ) {
this.lowerCdfCutUsed = lowerCdfCutUsed;
}
public boolean isMakeSampleCorrMatImages() {
return makeSampleCorrMatImages;
}
public void setMakeSampleCorrMatImages( boolean makeSampleCorrMatImages ) {
this.makeSampleCorrMatImages = makeSampleCorrMatImages;
}
/**
* @return the omitNegLinks
*/
public boolean isOmitNegLinks() {
return omitNegLinks;
}
/**
* @param omitNegLinks the omitNegLinks to set
*/
public void setOmitNegLinks( boolean omitNegLinks ) {
this.omitNegLinks = omitNegLinks;
}
public boolean isSubset() {
return subset;
}
public void setSubset( boolean subset ) {
this.subset = subset;
}
public boolean isSubsetUsed() {
return subsetUsed;
}
public void setSubsetUsed( boolean subsetUsed ) {
this.subsetUsed = subsetUsed;
}
public boolean isTextOut() {
return textOut;
}
public void setTextOut( boolean b ) {
this.textOut = b;
}
/**
* @return the upperCdfCutUsed
*/
public boolean isUpperCdfCutUsed() {
return upperCdfCutUsed;
}
/**
* @param upperCdfCutUsed the upperCdfCutUsed to set
*/
public void setUpperCdfCutUsed( boolean upperCdfCutUsed ) {
this.upperCdfCutUsed = upperCdfCutUsed;
}
public boolean isUseDb() {
return useDb;
}
public void setUseDb( boolean useDb ) {
this.useDb = useDb;
}
/**
* @return representation of this analysis (not completely filled in - only the basic parameters)
*/
public CoexpressionAnalysis toAnalysis() {
CoexpressionAnalysis analysis = CoexpressionAnalysis.Factory.newInstance();
Protocol protocol = Protocol.Factory.newInstance();
protocol.setName( "Link analysis settings" );
protocol.setDescription( this.toString() );
analysis.setProtocol( protocol );
return analysis;
}
@Override
public String toString() {
StringBuilder buf = new StringBuilder();
buf.append( "# absoluteValue:" ).append( this.isAbsoluteValue() ).append( "\n" );
buf.append( "# metric:" ).append( this.getMetric() ).append( "\n" );
buf.append( "# cdfCut:" ).append( this.getCdfCut() ).append( "\n" );
buf.append( "# cacheCut:" ).append( this.getCorrelationCacheThreshold() ).append( "\n" );
buf.append( "# fwe:" ).append( this.getFwe() ).append( "\n" );
buf.append( "# uppercut:" ).append( this.getUpperTailCut() ).append( "\n" );
buf.append( "# lowercut:" ).append( this.getLowerTailCut() ).append( "\n" );
buf.append( "# useDB:" ).append( this.isUseDb() ).append( "\n" );
buf.append( "# normalizationMethod:" ).append( this.getNormalizationMethod() ).append( "\n" );
buf.append( "# omitNegLinks:" ).append( this.isOmitNegLinks() ).append( "\n" );
buf.append( "# probeDegreeThreshold:" ).append( this.getProbeDegreeThreshold() ).append( "\n" );
/*
* if ( this.isSubsetUsed() ) { buf.append( "# subset:" + this.subsetSize + "\n" ); }
*/
if ( this.isUpperCdfCutUsed() ) {
buf.append( "# upperCutUsed:cdfCut\n" );
} else {
buf.append( "# upperCutUsed:fwe\n" );
}
if ( this.isLowerCdfCutUsed() ) {
buf.append( "# lowerCutUsed:cdfCut\n" );
} else {
buf.append( "# lowerCutUsed:fwe\n" );
}
buf.append( "# singularThreshold:" ).append( this.getSingularThreshold() ).append( "\n" );
return buf.toString();
}
private void checkValidMetric( String m ) {
if ( m.equalsIgnoreCase( "pearson" ) )
return;
if ( m.equalsIgnoreCase( "spearman" ) )
return;
throw new IllegalArgumentException(
"Unrecognized metric: " + m + ", valid options are 'pearson' and 'spearman'" );
}
public enum NormalizationMethod {
BALANCE, none, SPELL, SVD
}
/**
* Configures whether only one of the two thresholds should be used. Set to 'none' to use the standard
* dual-threshold, or choose 'fwe' or 'cdfcut' to use only one of those.
*/
public enum SingularThreshold {
cdfcut, fwe, none
}
}
|
Mindtribe/MTBuild | lib/mtbuild/toolchains/arm_none_eabi_gcc.rb | <reponame>Mindtribe/MTBuild
module MTBuild
require 'mtbuild/toolchains/gcc'
Toolchain.register_toolchain(:arm_none_eabi_gcc, 'MTBuild::ToolchainArmNoneEabiGcc')
# This ToolchainGcc subclass can build using arm-non-eabi-gcc
class ToolchainArmNoneEabiGcc < ToolchainGcc
def initialize(parent_configuration, toolchain_configuration)
super
end
# Create Rake tasks for linking
def create_application_tasks(objects, executable_name)
elf_file = File.join(@output_folder, "#{executable_name}#{@output_decorator}.elf")
bin_file = File.join(@output_folder, "#{executable_name}#{@output_decorator}.bin")
hex_file = File.join(@output_folder, "#{executable_name}#{@output_decorator}.hex")
map_file = File.join(@output_folder, "#{executable_name}#{@output_decorator}.map")
executable_folder = @output_folder
unless @tracked_folders.include?executable_folder
@tracked_folders << executable_folder
directory executable_folder
@parent_configuration.parent_project.add_files_to_clean(executable_folder)
end
@parent_configuration.parent_project.add_files_to_clean(elf_file, bin_file, hex_file, map_file)
all_objects = objects+get_include_objects
file elf_file => all_objects do |t|
command_line = construct_link_command(all_objects, t.name, get_include_paths, get_library_paths, map_file)
sh command_line
end
file map_file => elf_file
file bin_file => elf_file do |t|
command_line = construct_objcopy_command(elf_file, t.name, ' -Obinary')
sh command_line
end
file hex_file => elf_file do |t|
command_line = construct_objcopy_command(elf_file, t.name, ' -Oihex')
sh command_line
end
return [elf_file, bin_file, hex_file], [map_file], [executable_folder]
end
private
def construct_objcopy_command(input_name, output_name, objcopyflags)
return "\"#{objcopy}\"#{objcopyflags} \"#{input_name}\" \"#{output_name}\""
end
def assembler
return 'arm-none-eabi-gcc'
end
def compiler_c
return 'arm-none-eabi-gcc'
end
def compiler_cpp
return 'arm-none-eabi-g++'
end
def archiver
return 'arm-none-eabi-ar'
end
def linker_c
return 'arm-none-eabi-gcc'
end
def linker_cpp
return 'arm-none-eabi-g++'
end
def objcopy
return 'arm-none-eabi-objcopy'
end
end
end
|
ParikhKadam/NeMo | tests/unit/core/neural_module/test_module_configuration_import.py | <gh_stars>1-10
# ! /usr/bin/python
# -*- coding: utf-8 -*-
# =============================================================================
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# =============================================================================
import pytest
from nemo.core import NeuralModule
@pytest.mark.usefixtures("neural_factory")
class TestNeuralModuleImport:
"""
Class testing Neural Module configuration export.
"""
class FirstSimpleModule(NeuralModule):
"""
Mockup component class.
"""
def __init__(self, a, b, c, d):
super().__init__()
class SecondSimpleModule(NeuralModule):
"""
Mockup component class.
"""
def __init__(self, x, y):
super().__init__()
def setup_method(self, method):
"""
Setup_method is invoked for every test method of a class.
Mocks up the classes.
"""
# Mockup abstract methods.
TestNeuralModuleImport.FirstSimpleModule.__abstractmethods__ = set()
TestNeuralModuleImport.SecondSimpleModule.__abstractmethods__ = set()
@pytest.mark.unit
def test_simple_import_root_neural_module(self, tmpdir):
"""
Tests whether the Neural Module can instantiate a simple module by loading a configuration file.
Args:
tmpdir: Fixture which will provide a temporary directory.
"""
# params = {"int": 123, "float": 12.4, "string": "ala ma kota", "bool": True}
orig_module = TestNeuralModuleImport.FirstSimpleModule(123, 12.4, "ala ma kota", True)
# Generate filename in the temporary directory.
tmp_file_name = str(tmpdir.mkdir("export").join("simple_import_root.yml"))
# Export.
orig_module.export_to_config(tmp_file_name)
# Import and create the new object.
new_module = NeuralModule.import_from_config(tmp_file_name)
# Compare class types.
assert type(orig_module).__name__ == type(new_module).__name__
# Compare objects - by its all params.
param_keys = orig_module.init_params.keys()
for key in param_keys:
assert orig_module.init_params[key] == new_module.init_params[key]
@pytest.mark.unit
def test_simple_import_leaf_module(self, tmpdir):
"""
Tests whether a particular module can instantiate another
instance (a copy) by loading a configuration file.
Args:
tmpdir: Fixture which will provide a temporary directory.
"""
# params = {"int": 123, "float": 12.4, "string": "ala ma kota", "bool": True}
orig_module = TestNeuralModuleImport.FirstSimpleModule(123, 12.4, "ala ma kota", True)
# Generate filename in the temporary directory.
tmp_file_name = str(tmpdir.mkdir("export").join("simple_import_leaf.yml"))
# Export.
orig_module.export_to_config(tmp_file_name)
# Import and create the new object.
new_module = TestNeuralModuleImport.FirstSimpleModule.import_from_config(tmp_file_name)
# Compare class types.
assert type(orig_module).__name__ == type(new_module).__name__
# Compare objects - by its all params.
param_keys = orig_module.init_params.keys()
for key in param_keys:
assert orig_module.init_params[key] == new_module.init_params[key]
@pytest.mark.unit
def test_incompatible_import_leaf_module(self, tmpdir):
"""
Tests whether a particular module can instantiate another
instance (a copy) by loading a configuration file.
Args:
tmpdir: Fixture which will provide a temporary directory.
"""
# params = {"int": 123, "float": 12.4, "string": "ala ma kota", "bool": True}
orig_module = TestNeuralModuleImport.SecondSimpleModule(["No", "way", "dude!"], None)
# Generate filename in the temporary directory.
tmp_file_name = str(tmpdir.mkdir("export").join("incompatible_import_leaf.yml"))
# Export.
orig_module.export_to_config(tmp_file_name)
# This will actuall create an instance of SecondSimpleModule - OK.
new_module = NeuralModule.import_from_config(tmp_file_name)
# Compare class types.
assert type(orig_module).__name__ == type(new_module).__name__
# This will create an instance of SecondSimpleModule, not FirstSimpleModule - SO NOT OK!!
with pytest.raises(ImportError):
_ = TestNeuralModuleImport.FirstSimpleModule.import_from_config(tmp_file_name)
|
ScalablyTyped/SlinkyTyped | a/angular-loading-bar/src/main/scala/typingsSlinky/angularLoadingBar/mod.scala | <gh_stars>10-100
package typingsSlinky.angularLoadingBar
import org.scalablytyped.runtime.Shortcut
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
object mod extends Shortcut {
@JSImport("angular-loading-bar", JSImport.Namespace)
@js.native
val ^ : String = js.native
type _To = String
/* This means you don't have to write `^`, but can instead just say `mod.foo` */
override def _to: String = ^
/* augmented module */
object angularAugmentingMod {
@js.native
trait IRequestShortcutConfig extends StObject {
/**
* Indicates that the loading bar should be hidden.
*/
var ignoreLoadingBar: js.UndefOr[Boolean] = js.native
}
object IRequestShortcutConfig {
@scala.inline
def apply(): IRequestShortcutConfig = {
val __obj = js.Dynamic.literal()
__obj.asInstanceOf[IRequestShortcutConfig]
}
@scala.inline
implicit class IRequestShortcutConfigMutableBuilder[Self <: IRequestShortcutConfig] (val x: Self) extends AnyVal {
@scala.inline
def setIgnoreLoadingBar(value: Boolean): Self = StObject.set(x, "ignoreLoadingBar", value.asInstanceOf[js.Any])
@scala.inline
def setIgnoreLoadingBarUndefined: Self = StObject.set(x, "ignoreLoadingBar", js.undefined)
}
}
object loadingBar {
@js.native
trait ILoadingBarProvider extends StObject {
/**
* Give illusion that there's always progress
*/
var autoIncrement: js.UndefOr[Boolean] = js.native
/**
* Complete the loading bar
*/
def complete(): Unit = js.native
/**
* Increment the loading bar
*/
def inc(): Unit = js.native
/**
* Turn the loading bar on or off
*/
var includeBar: js.UndefOr[Boolean] = js.native
/**
* Turn the spinner on or off
*/
var includeSpinner: js.UndefOr[Boolean] = js.native
/**
* Latency Threshold
*/
var latencyThreshold: js.UndefOr[Double] = js.native
/**
* Loading bar template
*/
var loadingBarTemplate: js.UndefOr[String] = js.native
/**
* HTML element selector of parent
*/
var parentSelector: js.UndefOr[String] = js.native
/**
* Set the percentage completed
* @param {number} n - number between 0 and 1
*/
def set(n: Double): Unit = js.native
/**
* HTML template
*/
var spinnerTemplate: js.UndefOr[String] = js.native
/**
* Broadcast the start event
*/
def start(): Unit = js.native
/**
* Starting size
*/
var startSize: js.UndefOr[Double] = js.native
/**
* Get the percentage completed
* @returns {number}
*/
def status(): Double = js.native
}
object ILoadingBarProvider {
@scala.inline
def apply(
complete: () => Unit,
inc: () => Unit,
set: Double => Unit,
start: () => Unit,
status: () => Double
): ILoadingBarProvider = {
val __obj = js.Dynamic.literal(complete = js.Any.fromFunction0(complete), inc = js.Any.fromFunction0(inc), set = js.Any.fromFunction1(set), start = js.Any.fromFunction0(start), status = js.Any.fromFunction0(status))
__obj.asInstanceOf[ILoadingBarProvider]
}
@scala.inline
implicit class ILoadingBarProviderMutableBuilder[Self <: ILoadingBarProvider] (val x: Self) extends AnyVal {
@scala.inline
def setAutoIncrement(value: Boolean): Self = StObject.set(x, "autoIncrement", value.asInstanceOf[js.Any])
@scala.inline
def setAutoIncrementUndefined: Self = StObject.set(x, "autoIncrement", js.undefined)
@scala.inline
def setComplete(value: () => Unit): Self = StObject.set(x, "complete", js.Any.fromFunction0(value))
@scala.inline
def setInc(value: () => Unit): Self = StObject.set(x, "inc", js.Any.fromFunction0(value))
@scala.inline
def setIncludeBar(value: Boolean): Self = StObject.set(x, "includeBar", value.asInstanceOf[js.Any])
@scala.inline
def setIncludeBarUndefined: Self = StObject.set(x, "includeBar", js.undefined)
@scala.inline
def setIncludeSpinner(value: Boolean): Self = StObject.set(x, "includeSpinner", value.asInstanceOf[js.Any])
@scala.inline
def setIncludeSpinnerUndefined: Self = StObject.set(x, "includeSpinner", js.undefined)
@scala.inline
def setLatencyThreshold(value: Double): Self = StObject.set(x, "latencyThreshold", value.asInstanceOf[js.Any])
@scala.inline
def setLatencyThresholdUndefined: Self = StObject.set(x, "latencyThreshold", js.undefined)
@scala.inline
def setLoadingBarTemplate(value: String): Self = StObject.set(x, "loadingBarTemplate", value.asInstanceOf[js.Any])
@scala.inline
def setLoadingBarTemplateUndefined: Self = StObject.set(x, "loadingBarTemplate", js.undefined)
@scala.inline
def setParentSelector(value: String): Self = StObject.set(x, "parentSelector", value.asInstanceOf[js.Any])
@scala.inline
def setParentSelectorUndefined: Self = StObject.set(x, "parentSelector", js.undefined)
@scala.inline
def setSet(value: Double => Unit): Self = StObject.set(x, "set", js.Any.fromFunction1(value))
@scala.inline
def setSpinnerTemplate(value: String): Self = StObject.set(x, "spinnerTemplate", value.asInstanceOf[js.Any])
@scala.inline
def setSpinnerTemplateUndefined: Self = StObject.set(x, "spinnerTemplate", js.undefined)
@scala.inline
def setStart(value: () => Unit): Self = StObject.set(x, "start", js.Any.fromFunction0(value))
@scala.inline
def setStartSize(value: Double): Self = StObject.set(x, "startSize", value.asInstanceOf[js.Any])
@scala.inline
def setStartSizeUndefined: Self = StObject.set(x, "startSize", js.undefined)
@scala.inline
def setStatus(value: () => Double): Self = StObject.set(x, "status", js.Any.fromFunction0(value))
}
}
}
}
}
|
waslm/spring-boot-blog | src/main/java/cn/njiuyag/springboot/blog/service/UserService.java | <reponame>waslm/spring-boot-blog<filename>src/main/java/cn/njiuyag/springboot/blog/service/UserService.java
package cn.njiuyag.springboot.blog.service;
import cn.njiuyag.springboot.blog.dto.input.UserInfoUpdateInputDTO;
import cn.njiuyag.springboot.blog.framework.ErrorCode;
import cn.njiuyag.springboot.blog.framework.Result;
import cn.njiuyag.springboot.blog.generate.mapper.AdminUserMapper;
import cn.njiuyag.springboot.blog.generate.model.AdminUser;
import cn.njiuyag.springboot.blog.generate.model.AdminUserExample;
import com.sun.org.apache.regexp.internal.RE;
import org.springframework.stereotype.Service;
/**
* @author hjx
* @date 2020/12/25
*/
@Service
public class UserService {
private final AdminUserMapper adminUserMapper;
public UserService(AdminUserMapper adminUserMapper) {
this.adminUserMapper = adminUserMapper;
}
public Result<?> updateUserInfo(Integer userId, UserInfoUpdateInputDTO inputDTO) {
AdminUser adminUser = adminUserMapper.selectByPrimaryKey(userId);
if (adminUser == null) {
return Result.fail(ErrorCode.USER_INFO_NOT_FOUND, "用户信息不存在");
}
if (!adminUser.getLoginUserName().equals(inputDTO.getLoginUserName())) {
// 判断登录名是否已使用
AdminUserExample adminUserExample = new AdminUserExample();
adminUserExample.createCriteria().andLoginUserNameEqualTo(inputDTO.getLoginUserName());
long count = adminUserMapper.countByExample(adminUserExample);
if (count > 0) {
return Result.fail(ErrorCode.USER_PASSWORD_ERROR, "用户名已存在");
}
}
// 执行更新操作
AdminUser updateUser = new AdminUser();
updateUser.setAdminUserId(adminUser.getAdminUserId());
updateUser.setLoginUserName(inputDTO.getLoginUserName());
updateUser.setNickName(inputDTO.getNickName());
int result = adminUserMapper.updateByPrimaryKeySelective(updateUser);
if (result <= 0) {
return Result.fail(ErrorCode.USER_DATABASE_OPERATION_ERROR, "更新用户名称信息失败");
}
return Result.success(null);
}
}
|
shuwenjin/dcwlt | dcwlt-common/dcwlt-common-pay/src/main/java/com/dcits/dcwlt/pay/api/domain/dcep/login/LoginReqDTO.java | package com.dcits.dcwlt.pay.api.domain.dcep.login;
import com.alibaba.fastjson.annotation.JSONField;
import com.dcits.dcwlt.pay.api.domain.dcep.DCEPReqBody;
import com.dcits.dcwlt.pay.api.domain.ecny.ECNYReqBody;
/**
*
* @Time 2021/01/08
* @Version 1.0
* Description:登录/退出请求报文
*/
public class LoginReqDTO extends ECNYReqBody {
//DCEPReqBody
/**
* 登录退出报文体
*/
private LoginReq loginReq;
@JSONField(name = "LoginReq")
public LoginReq getLoginReq() {
return loginReq;
}
public void setLoginReq(LoginReq loginReq) {
this.loginReq = loginReq;
}
@Override
public String toString() {
return "LoginReqDTO{" +
"loginReq=" + loginReq +
'}';
}
}
|
kef/hieos | src/xutil/src/com/vangent/hieos/xutil/metadata/structure/SQCodeOr.java | /*
* This code is subject to the HIEOS License, Version 1.0
*
* Copyright(c) 2008-2009 Vangent, Inc. All rights reserved.
*
* 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.vangent.hieos.xutil.metadata.structure;
import com.vangent.hieos.xutil.exception.XdsInternalException;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author NIST (Adapated by <NAME>).
*/
public class SQCodeOr extends SQCodedTerm {
public class CodeLet {
public String code;
public String scheme;
public CodeLet(String value) throws XdsInternalException {
String[] a = value.split("\\^");
if (a.length != 3 || a[0] == null || a[0].equals("") || a[2] == null || a[2].equals("")) {
throw new XdsInternalException("CodeLet: code value " + value + " is not in CE format (code^^scheme)");
}
code = a[0];
scheme = a[2];
}
public String toString() {
return code + "^^" + scheme;
}
}
String varname;
int index; // used to make varname unique
public List<CodeLet> values;
public String classification; // uuid
/**
*
* @param varname
* @param classification
*/
public SQCodeOr(String varname, String classification) {
this.varname = varname;
this.classification = classification;
index = 0; // means no index
values = new ArrayList<CodeLet>();
}
/**
*
* @return
*/
public String toString() {
return "SQCodeOr: [\n" +
"varname=" + varname + "\n" +
"index=" + index + "\n" +
"values=" + values + "\n" +
"classification=" + classification + "\n" +
"]\n";
}
/**
*
* @param i
*/
public void setIndex(int i) { // so unique names can be generated
index = i;
}
/**
*
* @param value
* @throws XdsInternalException
*/
public void addValue(String value) throws XdsInternalException {
values.add(new CodeLet(value));
}
/**
*
* @param values
* @throws XdsInternalException
*/
public void addValues(List<String> values) throws XdsInternalException {
for (String value : values) {
addValue(value);
}
}
/**
*
* @return
*/
public List<String> getCodes() {
List<String> a = new ArrayList<String>();
for (CodeLet cl : values) {
a.add(cl.code);
}
return a;
}
/**
*
* @return
*/
public List<String> getSchemes() {
List<String> a = new ArrayList<String>();
for (CodeLet cl : values) {
a.add(cl.scheme);
}
return a;
}
/**
*
* @return
*/
public String getCodeVarName() {
if (index == 0) {
return codeVarName(varname) + "_code";
}
return codeVarName(varname) + "_code_" + index;
}
/**
*
* @return
*/
public String getSchemeVarName() {
if (index == 0) {
return codeVarName(varname) + "_scheme";
}
return codeVarName(varname) + "_scheme_" + index;
}
/**
*
* @return
*/
public boolean isEmpty() {
return values.size() == 0;
}
}
|
gknowles/dimapp | libs/net/httpmsg.cpp | <filename>libs/net/httpmsg.cpp
// Copyright <NAME> 2016 - 2021.
// Distributed under the Boost Software License, Version 1.0.
//
// httpmsg.cpp - dim http
#include "pch.h"
#pragma hdrstop
using namespace std;
using namespace Dim;
/****************************************************************************
*
* Tuning parameters
*
***/
/****************************************************************************
*
* Declarations
*
***/
/****************************************************************************
*
* Private
*
***/
namespace {
const TokenTable::Token s_hdrNames[] = {
{kHttpInvalid, "INVALID"},
{kHttp_Authority, ":authority"},
{kHttp_Method, ":method"},
{kHttp_Path, ":path"},
{kHttp_Scheme, ":scheme"},
{kHttp_Status, ":status"},
{kHttpAccept, "accept"},
{kHttpAcceptCharset, "accept-charset"},
{kHttpAcceptEncoding, "accept-encoding"},
{kHttpAcceptLanguage, "accept-language"},
{kHttpAcceptRanges, "accept-ranges"},
{kHttpAccessControlAllowOrigin, "access-control-allow-origin"},
{kHttpAge, "age"},
{kHttpAllow, "allow"},
{kHttpAuthorization, "authorization"},
{kHttpCacheControl, "cache-control"},
{kHttpConnection, "connection"},
{kHttpContentDisposition, "content-disposition"},
{kHttpContentEncoding, "content-encoding"},
{kHttpContentLanguage, "content-language"},
{kHttpContentLength, "content-length"},
{kHttpContentLocation, "content-location"},
{kHttpContentRange, "content-range"},
{kHttpContentType, "content-type"},
{kHttpCookie, "cookie"},
{kHttpDate, "date"},
{kHttpETag, "etag"},
{kHttpExpect, "expect"},
{kHttpExpires, "expires"},
{kHttpForwardedFor, "forwarded-for"},
{kHttpFrom, "from"},
{kHttpHost, "host"},
{kHttpIfMatch, "if-match"},
{kHttpIfModifiedSince, "if-modified-since"},
{kHttpIfNoneMatch, "if-none-match"},
{kHttpIfRange, "if-range"},
{kHttpIfUnmodifiedSince, "if-unmodified-since"},
{kHttpLastModified, "last-modified"},
{kHttpLink, "link"},
{kHttpLocation, "location"},
{kHttpMaxForwards, "max-forwards"},
{kHttpProxyAuthenticate, "proxy-authenticate"},
{kHttpProxyAuthorization, "proxy-authorization"},
{kHttpRange, "range"},
{kHttpReferer, "referer"},
{kHttpRefresh, "refresh"},
{kHttpRetryAfter, "retry-after"},
{kHttpServer, "server"},
{kHttpSetCookie, "set-cookie"},
{kHttpStrictTransportSecurity, "strict-transport-security"},
{kHttpTransferEncoding, "transfer-encoding"},
{kHttpUserAgent, "user-agent"},
{kHttpVary, "vary"},
{kHttpVia, "via"},
{kHttpWwwAuthenticate, "www-authenticate"},
};
static_assert(size(s_hdrNames) == kHttps);
const TokenTable s_hdrNameTbl(s_hdrNames);
const TokenTable::Token s_methodNames[] = {
{fHttpMethodConnect, "CONNECT"},
{fHttpMethodDelete, "DELETE"},
{fHttpMethodGet, "GET"},
{fHttpMethodHead, "HEAD"},
{fHttpMethodOptions, "OPTIONS"},
{fHttpMethodPost, "POST"},
{fHttpMethodPut, "PUT"},
{fHttpMethodTrace, "TRACE"},
};
static_assert(size(s_methodNames) == kHttpMethods);
const TokenTable s_methodNameTbl(s_methodNames);
} // namespace
/****************************************************************************
*
* HttpMsg::HdrList
*
***/
//===========================================================================
auto HttpMsg::HdrList::begin() -> ForwardListIterator<HdrName> {
return ForwardListIterator<HdrName>{m_firstHeader};
}
//===========================================================================
auto HttpMsg::HdrList::end() -> ForwardListIterator<HdrName> {
return ForwardListIterator<HdrName>{nullptr};
}
//===========================================================================
auto HttpMsg::HdrList::begin() const -> ForwardListIterator<HdrName const> {
return ForwardListIterator<HdrName const>{m_firstHeader};
}
//===========================================================================
auto HttpMsg::HdrList::end() const -> ForwardListIterator<HdrName const> {
return ForwardListIterator<HdrName const>{nullptr};
}
/****************************************************************************
*
* HttpMsg::HdrName
*
***/
//===========================================================================
auto HttpMsg::HdrName::begin() -> ForwardListIterator<HdrValue> {
return ForwardListIterator<HdrValue>(&m_value);
}
//===========================================================================
auto HttpMsg::HdrName::end() -> ForwardListIterator<HdrValue> {
return ForwardListIterator<HdrValue>(nullptr);
}
//===========================================================================
auto HttpMsg::HdrName::begin() const -> ForwardListIterator<HdrValue const> {
return ForwardListIterator<HdrValue const>(&m_value);
}
//===========================================================================
auto HttpMsg::HdrName::end() const -> ForwardListIterator<HdrValue const> {
return ForwardListIterator<HdrValue const>(nullptr);
}
/****************************************************************************
*
* HttpMsg
*
***/
//===========================================================================
void HttpMsg::clear() {
m_flags = {};
m_data.clear();
m_heap.clear();
m_firstHeader = nullptr;
m_stream = 0;
}
//===========================================================================
void HttpMsg::swap(HttpMsg & other) {
// You can't swap a request with a response. They different data and,
// consequently, different memory layouts.
assert(isRequest() == other.isRequest());
::swap(m_flags, other.m_flags);
m_data.swap(other.m_data);
m_heap.swap(other.m_heap);
::swap(m_firstHeader, other.m_firstHeader);
::swap(m_stream, other.m_stream);
}
//===========================================================================
void HttpMsg::addHeader(HttpHdr id, const char value[]) {
addHeaderRef(id, m_heap.strDup(value));
}
//===========================================================================
void HttpMsg::addHeader(HttpHdr id, string_view value) {
addHeaderRef(id, m_heap.strDup(value));
}
//===========================================================================
void HttpMsg::addHeader(const char name[], const char value[]) {
addHeader(name, string_view(value));
}
//===========================================================================
void HttpMsg::addHeader(const char name[], string_view value) {
if (auto id = httpHdrFromString(name))
return addHeader(id, value);
addHeaderRef(kHttpInvalid, m_heap.strDup(name), m_heap.strDup(value));
}
//===========================================================================
void HttpMsg::addHeader(HttpHdr id, TimePoint time) {
auto hv = addRef(time);
if (!hv)
logMsgFatal() << "addHeader(" << id << "): invalid time";
if (auto hv = addRef(time))
addHeaderRef(id, hv);
}
//===========================================================================
void HttpMsg::addHeader(const char name[], TimePoint time) {
auto hv = addRef(time);
if (!hv)
logMsgFatal() << "addHeader(" << name << "): invalid time";
if (auto id = httpHdrFromString(name)) {
addHeaderRef(id, hv);
} else {
addHeaderRef(id, m_heap.strDup(name), hv);
}
}
//===========================================================================
HttpMsg::Flags HttpMsg::toHasFlag(HttpHdr id) const {
switch (id) {
case kHttp_Status: return fFlagHasStatus;
case kHttp_Method: return fFlagHasMethod;
case kHttp_Scheme: return fFlagHasScheme;
case kHttp_Authority: return fFlagHasAuthority;
case kHttp_Path: return fFlagHasPath;
default:
return {};
}
}
//===========================================================================
void HttpMsg::addHeaderRef(HttpHdr id, const char name[], const char value[]) {
auto ni = m_firstHeader;
auto prev = (HdrName *) nullptr;
auto pseudo = name[0] == ':';
for (;;) {
if (!ni) {
ni = m_heap.emplace<HdrName>();
if (pseudo)
m_flags |= toHasFlag(id);
break;
}
if (pseudo && ni->m_name[0] != ':') {
auto next = ni;
ni = m_heap.emplace<HdrName>();
ni->m_next = next;
m_flags |= toHasFlag(id);
break;
}
if (ni->m_id == id && (id || strcmp(ni->m_name, name) == 0))
goto ADD_VALUE;
prev = ni;
ni = ni->m_next;
}
// update new header name info
if (!prev) {
// only header goes to front of list
m_firstHeader = ni;
} else {
// add regular headers to the back
prev->m_next = ni;
}
ni->m_id = id;
ni->m_name = name;
ADD_VALUE:
auto vi = ni->m_value.m_prev;
if (!vi) {
vi = &ni->m_value;
} else {
vi = m_heap.emplace<HdrValue>();
vi->m_next = &ni->m_value;
if (auto pv = ni->m_value.m_prev) {
vi->m_prev = pv;
pv->m_next = vi;
}
vi->m_next->m_prev = vi;
}
vi->m_value = value;
}
//===========================================================================
void HttpMsg::addHeaderRef(HttpHdr id, const char value[]) {
const char * name = tokenTableGetName(s_hdrNameTbl, id);
addHeaderRef(id, name, value);
}
//===========================================================================
void HttpMsg::addHeaderRef(const char name[], const char value[]) {
HttpHdr id = tokenTableGetEnum(s_hdrNameTbl, name, kHttpInvalid);
addHeaderRef(id, name, value);
}
//===========================================================================
const char * HttpMsg::addRef(TimePoint time) {
const unsigned kHttpDateLen = 30;
tm tm;
if (!timeToDesc(&tm, time))
return nullptr;
char * tmp = heap().alloc<char>(kHttpDateLen);
strftime(tmp, kHttpDateLen, "%a, %d %b %Y %T GMT", &tm);
return tmp;
}
//===========================================================================
HttpMsg::HdrList HttpMsg::headers() {
HdrList hl;
hl.m_firstHeader = m_firstHeader;
return hl;
}
//===========================================================================
const HttpMsg::HdrList HttpMsg::headers() const {
HdrList hl;
hl.m_firstHeader = m_firstHeader;
return hl;
}
//===========================================================================
HttpMsg::HdrName HttpMsg::headers(HttpHdr header) {
for (auto && hdr : headers()) {
if (hdr.m_id == header)
return hdr;
}
return {};
}
//===========================================================================
const HttpMsg::HdrName HttpMsg::headers(HttpHdr header) const {
return const_cast<HttpMsg *>(this)->headers(header);
}
//===========================================================================
HttpMsg::HdrName HttpMsg::headers(const char name[]) {
HttpHdr id = tokenTableGetEnum(s_hdrNameTbl, name, kHttpInvalid);
return headers(id);
}
//===========================================================================
const HttpMsg::HdrName HttpMsg::headers(const char name[]) const {
return const_cast<HttpMsg *>(this)->headers(name);
}
//===========================================================================
bool HttpMsg::hasHeader(HttpHdr header) const {
return headers(header).m_id;
}
//===========================================================================
bool HttpMsg::hasHeader(const char name[]) const {
return headers(name).m_id;
}
//===========================================================================
CharBuf & HttpMsg::body() {
return m_data;
}
//===========================================================================
const CharBuf & HttpMsg::body() const {
return m_data;
}
//===========================================================================
ITempHeap & HttpMsg::heap() {
return m_heap;
}
/****************************************************************************
*
* HttpRequest
*
***/
//===========================================================================
void HttpRequest::swap(HttpMsg & other) {
HttpMsg::swap(other);
::swap(m_query, static_cast<HttpRequest &>(other).m_query);
}
//===========================================================================
const char * HttpRequest::method() const {
return headers(kHttp_Method).begin()->m_value;
}
//===========================================================================
const char * HttpRequest::scheme() const {
return headers(kHttp_Scheme).begin()->m_value;
}
//===========================================================================
const char * HttpRequest::authority() const {
return headers(kHttp_Authority).begin()->m_value;
}
//===========================================================================
const char * HttpRequest::pathRaw() const {
return headers(kHttp_Path).begin()->m_value;
}
//===========================================================================
const HttpQuery & HttpRequest::query() const {
if (!m_query) {
auto self = const_cast<HttpRequest *>(this);
self->m_query = urlParseHttpPath(pathRaw(), self->heap());
if (!body().empty()) {
auto hdr = headers(kHttpContentType);
if (auto val = hdr.m_value.m_value;
strcmp(val, "application/x-www-form-urlencoded") == 0
) {
urlAddQueryString(self->m_query, body().c_str(), self->heap());
}
}
}
return *m_query;
}
//===========================================================================
bool HttpRequest::checkPseudoHeaders() const {
const Flags must = fFlagHasMethod | fFlagHasScheme | fFlagHasPath;
const Flags mustNot = fFlagHasStatus;
return (m_flags & must) == must && (~m_flags & mustNot);
}
/****************************************************************************
*
* HttpResponse
*
***/
//===========================================================================
HttpResponse::HttpResponse(
HttpStatus status,
string_view contentType
) {
auto str = StrFrom{status};
addHeader(kHttp_Status, str.view());
if (!contentType.empty())
addHeader(kHttpContentType, contentType);
}
//===========================================================================
int HttpResponse::status() const {
auto val = headers(kHttp_Status).begin()->m_value;
return strToInt(val);
}
//===========================================================================
bool HttpResponse::checkPseudoHeaders() const {
const Flags must = fFlagHasStatus;
const Flags mustNot = fFlagHasMethod | fFlagHasScheme | fFlagHasAuthority
| fFlagHasPath;
return (m_flags & must) == must && (~m_flags & mustNot);
}
/****************************************************************************
*
* Public API
*
***/
//===========================================================================
const char * Dim::toString(HttpHdr id) {
return tokenTableGetName(s_hdrNameTbl, id);
}
//===========================================================================
HttpHdr Dim::httpHdrFromString(string_view name, HttpHdr def) {
return tokenTableGetEnum(s_hdrNameTbl, name, def);
}
//===========================================================================
const char * Dim::toString(HttpMethod id) {
return tokenTableGetName(s_methodNameTbl, id);
}
//===========================================================================
vector<string_view> Dim::to_views(HttpMethod methods) {
return tokenTableGetFlagNames(s_methodNameTbl, methods);
}
//===========================================================================
HttpMethod Dim::httpMethodFromString(string_view name, HttpMethod def) {
return tokenTableGetEnum(s_methodNameTbl, name, def);
}
//===========================================================================
bool httpParse(TimePoint * time, std::string_view val) {
assert(!"httpTimeFromChar not implemented");
*time = {};
return false;
}
|
centresource/aws-sdk-for-ruby | lib/aws/ec2/client/xml.rb | # Copyright 2011 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file 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.
module AWS
class EC2
class Client < Core::Client
module XML
include Core::ConfiguredXmlGrammars
BaseError = Core::XmlGrammar.customize do
element "Errors" do
ignore
element("Error") { ignore }
end
end
define_configured_grammars
CustomizedDescribeSecurityGroups = DescribeSecurityGroups.customize do
element "securityGroupInfo" do
element "item" do
index(:security_group_index) { |i| i.group_id }
element "ipPermissions" do
list "item"
element "item" do
element("ipProtocol") { symbol_value }
element("fromPort") { integer_value }
element("toPort") { integer_value }
element("groups") { list "item" }
element("ipRanges") { list "item" }
end
end
end
end
end
CustomizedDescribeInstances = DescribeInstances.customize do
element "reservationSet" do
element "item" do
index :reservation_index do |r|
r.instances_set.map { |i| i.instance_id }
end
element "instancesSet" do
element "item" do
index(:instance_index) { |i| i.instance_id }
end
end
end
end
end
CustomizedDescribeImages = DescribeImages.customize do
element "imagesSet" do
element "item" do
index(:image_index) { |i| i.image_id }
end
end
end
CustomizedDescribeVolumes = DescribeVolumes.customize do
element "volumeSet" do
element "item" do
index(:volume_index) { |v| v.volume_id }
end
end
end
CustomizedDescribeSnapshots = DescribeSnapshots.customize do
element "snapshotSet" do
element "item" do
index(:snapshot_index) { |s| s.snapshot_id }
end
end
end
CustomizedDescribeAddresses = DescribeAddresses.customize do
element "addressesSet" do
element "item" do
index(:address_index) { |a| a.public_ip }
element "instanceId" do
force
end
end
end
end
CustomizedDescribeKeyPairs = DescribeKeyPairs.customize do
element "keySet" do
element "item" do
index(:key_index) { |k| k.key_name }
end
end
end
CustomizedDescribeTags = DescribeTags.customize do
element "tagSet" do
element "item" do
element("resourceType") { force }
element("resourceId") { force }
element("key") { force }
index(:tag_index) do |t|
"#{t.resource_type}:#{t.resource_id}:#{t.key}"
end
end
end
end
end
end
end
end
|
yourtion/LeetCode | java/src/test/java/com/yourtion/leetcode/daily/m10/d06/SolutionTest.java | <filename>java/src/test/java/com/yourtion/leetcode/daily/m10/d06/SolutionTest.java
package com.yourtion.leetcode.daily.m10.d06;
import com.yourtion.leetcode.TestUtils;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import java.util.stream.Stream;
import static org.junit.jupiter.params.provider.Arguments.arguments;
@DisplayName("每日一题 - 20201006")
class SolutionTest {
static Stream<Arguments> testDataProvider() {
return Stream.of(
arguments(6, "[[0,1],[0,2],[2,3],[2,4],[2,5]]", "[8, 12, 6, 10, 10, 10]")
);
}
@ParameterizedTest()
@MethodSource("testDataProvider")
void sumOfDistancesInTree(int n, String source, String res) {
System.out.printf("runTest: %d %s , res: %s", n, source, res);
int[][] ss = TestUtils.stringToInt2dArray(source);
int[] ret = new Solution().sumOfDistancesInTree(n, ss);
Assertions.assertEquals(res, TestUtils.integerArrayToString(ret));
}
} |
cflowe/ACE | TAO/tao/ImR_Client/ImR_Client.h | <reponame>cflowe/ACE
// -*- C++ -*-
//=============================================================================
/**
* @file ImR_Client.h
*
* $Id: ImR_Client.h 96760 2013-02-05 21:11:03Z stanleyk $
*
* @author <NAME> <<EMAIL>>
*/
//=============================================================================
#ifndef TAO_IMR_CLIENT_ADAPTER_IMPL_H
#define TAO_IMR_CLIENT_ADAPTER_IMPL_H
#include /**/ "ace/pre.h"
#include "tao/ImR_Client/imr_client_export.h"
#if !defined (ACE_LACKS_PRAGMA_ONCE)
# pragma once
#endif /* ACE_LACKS_PRAGMA_ONCE */
#include "tao/PortableServer/ImR_Client_Adapter.h"
#include "ace/Service_Config.h"
TAO_BEGIN_VERSIONED_NAMESPACE_DECL
class ServerObject_i;
namespace TAO
{
namespace ImR_Client
{
/**
* @class IFR_Client_Adapter_Impl
*
* @brief IFR_Client_Adapter_Impl.
*
* Class that adapts various functions in the PortableServer library
* which use the Implementation Repository. This is the derived class
* that contains the actual implementations.
*/
class TAO_IMR_Client_Export ImR_Client_Adapter_Impl
: public ::TAO::Portable_Server::ImR_Client_Adapter
{
public:
/// Constructor.
ImR_Client_Adapter_Impl (void);
/// Used to force the initialization of the PortableServer code.
static int Initializer (void);
/// ImplRepo helper method, notify the ImplRepo on startup
virtual void imr_notify_startup (TAO_Root_POA* poa);
/// ImplRepo helper method, notify the ImplRepo on shutdown
virtual void imr_notify_shutdown (TAO_Root_POA* poa);
/// ImplRepo helper method, create an IMR-ified object for a
/// key with a given type
virtual CORBA::Object_ptr imr_key_to_object(TAO_Root_POA* poa,
const TAO::ObjectKey &key,
const char *type_id) const;
private:
/// Implementation Repository Server Object
ServerObject_i *server_object_;
};
static int
TAO_Requires_ImR_Client_Initializer =
TAO::ImR_Client::ImR_Client_Adapter_Impl::Initializer ();
}
}
ACE_STATIC_SVC_DECLARE (ImR_Client_Adapter_Impl)
ACE_FACTORY_DECLARE (TAO_IMR_Client, ImR_Client_Adapter_Impl)
TAO_END_VERSIONED_NAMESPACE_DECL
#include /**/ "ace/post.h"
#endif /* TAO_IMR_CLIENT_ADAPTER_IMPL_H */
|
acidicMercury8/xray-1.6 | src/utils/xrLC_Light/lc_net_global_data.h | #ifndef _NET_LC_GLOBAL_DATA_H_
#define _NET_LC_GLOBAL_DATA_H_
#include "net_global_data.h"
namespace lc_net
{
template<>
class net_global_data_impl<gl_cl_data>
{
public:
void init() { data_init( ); }
protected:
void create_data_file (LPCSTR path);
bool create_data (LPCSTR path);
void destroy_data ( ){};
LPCSTR file_name ( ){ return "gl_cl_data"; }
virtual void data_init ( )=0 {};
virtual void data_cleanup ( )=0 {};
};
template<> struct global_add_global<gl_cl_data, gl_base_cl_data>{};
}
#endif |
ZottelvonUrvieh/TobyboT | src/extensions/core/timeFormated.js | <filename>src/extensions/core/timeFormated.js
module.exports = {
msToTimeDifferenceString: function (ms) {
let d, h, m, s;
s = Math.floor(ms / 1000);
m = Math.floor(s / 60);
s = s % 60;
h = Math.floor(m / 60);
m = m % 60;
d = Math.floor(h / 24);
h = h % 24;
let timeleft_array = [];
d = d === 0 ? null : d === 1 ? timeleft_array.push('1 day') : timeleft_array.push(`${d} days`);
h = h === 0 ? null : h === 1 ? timeleft_array.push('1 hour') : timeleft_array.push(`${h} hours`);
m = m === 0 ? null : m === 1 ? timeleft_array.push('1 minute') : timeleft_array.push(`${m} minutes`);
s = s === 0 ? null : s === 1 ? timeleft_array.push('1 second') : timeleft_array.push(`${s} seconds`);
return timeleft_array.join(', ');
}
};
|
DRK3/orb | pkg/protocolversion/versions/v1_0/client/client.go | /*
Copyright SecureKey Technologies Inc. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package client
import (
"github.com/trustbloc/sidetree-core-go/pkg/compression"
"github.com/trustbloc/sidetree-core-go/pkg/versions/1_0/operationparser"
"github.com/trustbloc/sidetree-core-go/pkg/versions/1_0/txnprovider"
"github.com/trustbloc/orb/pkg/context/common"
vcommon "github.com/trustbloc/orb/pkg/protocolversion/versions/common"
protocolcfg "github.com/trustbloc/orb/pkg/protocolversion/versions/v1_0/config"
"github.com/trustbloc/orb/pkg/versions/1_0/operationparser/validators/anchortime"
)
// Factory implements version 0.1 of the client factory.
type Factory struct{}
// New returns a version 1.0 implementation of the Sidetree protocol.
func New() *Factory {
return &Factory{}
}
// Create returns a 1.0 client version.
func (v *Factory) Create(version string, casClient common.CASReader) (common.ClientVersion, error) {
p := protocolcfg.GetProtocolConfig()
opParser := operationparser.New(p, operationparser.WithAnchorTimeValidator(anchortime.New(p.MaxOperationTimeDelta)))
cp := compression.New(compression.WithDefaultAlgorithms())
op := txnprovider.NewOperationProvider(p, opParser, casClient, cp)
return &vcommon.ClientVersion{
VersionStr: version,
P: p,
OpProvider: op,
}, nil
}
|
avesus/OpenFPGA | openfpga/src/utils/circuit_library_utils.h | /********************************************************************
* Header file for circuit_library_utils.cpp
*******************************************************************/
#ifndef CIRCUIT_LIBRARY_UTILS_H
#define CIRCUIT_LIBRARY_UTILS_H
/********************************************************************
* Include header files that are required by function declaration
*******************************************************************/
#include <vector>
#include "circuit_types.h"
#include "circuit_library.h"
/********************************************************************
* Function declaration
*******************************************************************/
/* begin namespace openfpga */
namespace openfpga {
std::vector<CircuitModelId> find_circuit_sram_models(const CircuitLibrary& circuit_lib,
const CircuitModelId& circuit_model);
std::vector<CircuitPortId> find_circuit_regular_sram_ports(const CircuitLibrary& circuit_lib,
const CircuitModelId& circuit_model);
std::vector<CircuitPortId> find_circuit_mode_select_sram_ports(const CircuitLibrary& circuit_lib,
const CircuitModelId& circuit_model);
size_t find_circuit_num_shared_config_bits(const CircuitLibrary& circuit_lib,
const CircuitModelId& circuit_model,
const e_config_protocol_type& sram_orgz_type);
size_t find_circuit_num_config_bits(const e_config_protocol_type& config_protocol_type,
const CircuitLibrary& circuit_lib,
const CircuitModelId& circuit_model);
std::vector<CircuitPortId> find_circuit_library_global_ports(const CircuitLibrary& circuit_lib);
std::vector<std::string> find_circuit_library_unique_verilog_netlists(const CircuitLibrary& circuit_lib);
std::vector<std::string> find_circuit_library_unique_spice_netlists(const CircuitLibrary& circuit_lib);
bool check_configurable_memory_circuit_model(const e_config_protocol_type& config_protocol_type,
const CircuitLibrary& circuit_lib,
const CircuitModelId& config_mem_circuit_model);
CircuitPortId find_circuit_model_power_gate_en_port(const CircuitLibrary& circuit_lib,
const CircuitModelId& circuit_model);
CircuitPortId find_circuit_model_power_gate_enb_port(const CircuitLibrary& circuit_lib,
const CircuitModelId& circuit_model);
std::vector<CircuitPortId> find_lut_circuit_model_input_port(const CircuitLibrary& circuit_lib,
const CircuitModelId& circuit_model,
const bool& include_harden_port,
const bool& include_global_port = true);
std::vector<CircuitPortId> find_lut_circuit_model_output_port(const CircuitLibrary& circuit_lib,
const CircuitModelId& circuit_model,
const bool& include_harden_port,
const bool& include_global_port = true);
} /* end namespace openfpga */
#endif
|
faraz891/gitlabhq | app/services/auth/dependency_proxy_authentication_service.rb | <gh_stars>1-10
# frozen_string_literal: true
module Auth
class DependencyProxyAuthenticationService < BaseService
AUDIENCE = 'dependency_proxy'
HMAC_KEY = 'gitlab-dependency-proxy'
DEFAULT_EXPIRE_TIME = 1.minute
def execute(authentication_abilities:)
return error('dependency proxy not enabled', 404) unless ::Gitlab.config.dependency_proxy.enabled
# Because app/controllers/concerns/dependency_proxy/auth.rb consumes this
# JWT only as `User.find`, we currently only allow User (not DeployToken, etc)
return error('access forbidden', 403) unless current_user.is_a?(User)
{ token: authorized_token.encoded }
end
class << self
include ::Gitlab::Utils::StrongMemoize
def secret
strong_memoize(:secret) do
OpenSSL::HMAC.hexdigest(
'sha256',
::Settings.attr_encrypted_db_key_base,
HMAC_KEY
)
end
end
def token_expire_at
Time.current + Gitlab::CurrentSettings.container_registry_token_expire_delay.minutes
end
end
private
def authorized_token
JSONWebToken::HMACToken.new(self.class.secret).tap do |token|
token['user_id'] = current_user.id
token.expire_time = self.class.token_expire_at
end
end
end
end
|
ducklingcloud/dct | src/main/java/cn/vlabs/duckling/vwb/service/emailnotifier/dao/EmailSubscriberProviderImpl.java | /*
* Copyright (c) 2008-2016 Computer Network Information Center (CNIC), Chinese Academy of Sciences.
*
* This file is part of Duckling project.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package cn.vlabs.duckling.vwb.service.emailnotifier.dao;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.PreparedStatementSetter;
import cn.vlabs.duckling.util.ContainerBaseDAO;
import cn.vlabs.duckling.vwb.service.emailnotifier.EmailSubscriber;
import cn.vlabs.duckling.vwb.service.emailnotifier.impl.EmailSubscriberProvider;
/**
* Introduction Here.
*
* @date Mar 1, 2010
* @author wkm(<EMAIL>)
*/
public class EmailSubscriberProviderImpl extends ContainerBaseDAO implements
EmailSubscriberProvider {
protected static final Logger log = Logger
.getLogger(EmailSubscriberProviderImpl.class);
private Map<Integer, EmailSubscriber> EmailSubscriberCache = new HashMap<Integer, EmailSubscriber>();
@Override
public void createEmailSubscriber(final int siteId,
List<EmailSubscriber> subscribers) {
final String sql = "insert into vwb_email_notify (subscriber,receiver,rec_time,siteId,resourceId) values(?,?,?,?,?)";
final List<EmailSubscriber> tsubscribers = subscribers;
getJdbcTemplate().batchUpdate(sql,
new BatchPreparedStatementSetter() {
public int getBatchSize() {
return tsubscribers.size();
}
public void setValues(PreparedStatement ps, int count)
throws SQLException {
EmailSubscriber email = (EmailSubscriber) tsubscribers
.get(count);
int i = 0;
ps.setString(++i, email.getNotify_creator());
ps.setString(++i, email.getReceiver());
ps.setInt(++i, email.getRec_time());
ps.setInt(++i, siteId);
ps.setString(++i, email.getresourceId());
}
});
}
@Override
public void delete(int id) {
getJdbcTemplate().update(
"delete from vwb_email_notify where id=" + id);
EmailSubscriberCache.remove(id);
}
@Override
public List<EmailSubscriber> findEmailSubscribers(int siteId,
String receiver, String pageName, int rec_time) {
ArrayList<String> conditions = new ArrayList<String>();
if (!StringUtils.isBlank(receiver)) {
conditions.add(" receiver like'%" + receiver + "%' ");
}
if (!StringUtils.isBlank(pageName)) {
if (!pageName.equals("*")) {
conditions.add(" title like'%" + pageName + "%' ");
}
}
if (rec_time != -1) {
conditions.add(" rec_time='" + rec_time + "' ");
}
String wherestr = "";
boolean first = true;
for (String cond : conditions) {
if (first) {
wherestr = " where " + cond;
first = false;
} else {
wherestr = wherestr + " and " + cond;
}
}
String sql = "select a.*, b.title from vwb_email_notify as a LEFT JOIN vwb_resource_info as b on a.resourceId=b.id and a.siteId=? and b.siteId=? "
+ wherestr;
return (List<EmailSubscriber>) getJdbcTemplate().query(sql,
new Object[] { siteId, siteId }, new EmailSubscriberMapper());
}
@Override
public List<EmailSubscriber> getAllEmailSubscribers(int siteId) {
String sql = "select a.*, b.title from vwb_email_notify a, vwb_resource_info b where a.resourceId=b.id and a.siteId=? and b.siteId=?";
return (List<EmailSubscriber>) getJdbcTemplate().query(sql,
new Object[] { siteId, siteId }, new EmailSubscriberMapper());
}
@Override
public EmailSubscriber getEmailSubscriberById(int siteId, int id) {
EmailSubscriber eSubscriber = null;
String sql = "select a.*, b.title" +
" from vwb_email_notify as a LEFT JOIN vwb_resource_info as b on a.resourceId=b.id and a.siteId=? and b.siteId=?" +
" where a.id=?";
eSubscriber = (EmailSubscriber) getJdbcTemplate().queryForObject(
sql, new Object[] { siteId, siteId, id },
new EmailSubscriberMapper());
return eSubscriber;
}
@Override
public void removeEmailSubscribers(int id) {
String sql = "delete from vwb_email_notify where id =?";
getJdbcTemplate().update(sql, new Object[] { id });
}
@Override
public void updateEmailSubscriber(final int siteId,
EmailSubscriber eSubscriber) {
final EmailSubscriber tempeSubscriber = eSubscriber;
getJdbcTemplate()
.update("update vwb_email_notify set subscriber=?,receiver=?,rec_time=?,resourceId=?,siteId=? where id=?",
new PreparedStatementSetter() {
public void setValues(PreparedStatement ps)
throws SQLException {
int i = 0;
ps.setString(++i,
tempeSubscriber.getNotify_creator());
ps.setString(++i, tempeSubscriber.getReceiver());
ps.setInt(++i, tempeSubscriber.getRec_time());
ps.setString(++i,
tempeSubscriber.getresourceId());
ps.setInt(++i, siteId);
ps.setInt(++i, tempeSubscriber.getId());
}
});
}
private static final String existSql = "select count(*) from vwb_email_notify where receiver=? and rec_time=? and siteId=? and resourceId=?";
@Override
public boolean isSubscribeExist(int siteId,EmailSubscriber sub) {
int count = getJdbcTemplate().queryForInt(
existSql,
new Object[] { sub.getReceiver(), sub.getRec_time(),siteId,
sub.getresourceId() });
return count != 0;
}
private static final String querySubscribeByTime = "select a.*, b.title "
+ "from vwb_email_notify as a LEFT JOIN vwb_resource_info as b on a.resourceId=b.id and a.siteId=? and b.siteId=? "
+ "where rec_time=?";
@Override
public List<EmailSubscriber> findReceiveAt(int siteId, int receiveTime) {
String sql = querySubscribeByTime;
List<EmailSubscriber> eSubscribers = (List<EmailSubscriber>) getJdbcTemplate()
.query(sql, new Object[] { siteId, siteId,receiveTime },
new EmailSubscriberMapper());
return eSubscribers;
}
private static final String querySubscribeByResourceId = "select a.*, b.title "
+ "from vwb_email_notify as a LEFT JOIN vwb_resource_info as b on a.resourceId=b.id and a.siteId=? and b.siteId=? "
+ "where resourceid=? or resourceid='*'";
@Override
public List<EmailSubscriber> findPageSubscribes(int siteId, int resourceId) {
String sql = querySubscribeByResourceId;
List<EmailSubscriber> eSubscribers = (List<EmailSubscriber>) getJdbcTemplate()
.query(sql, new Object[] {siteId, siteId, resourceId },
new EmailSubscriberMapper());
return eSubscribers;
}
private static final String querySubscribeByReceiver = "select a.*, b.title "
+ "from vwb_email_notify as a LEFT JOIN vwb_resource_info as b on a.resourceId=b.id and a.siteId=? and b.siteId=? "
+ "where receiver=?";
@Override
public List<EmailSubscriber> findUserSubScribe(int siteId,String username) {
String sql = querySubscribeByReceiver;
List<EmailSubscriber> eSubscribers = (List<EmailSubscriber>) getJdbcTemplate()
.query(sql, new Object[] {siteId, siteId, username },
new EmailSubscriberMapper());
return eSubscribers;
}
}
|
abohomol/gifky | app/src/main/java/com/abohomol/gifky/repository/retrofit/GifResponse.java | package com.abohomol.gifky.repository.retrofit;
class GifResponse {
private GifResponseItem[] data;
public GifResponseItem[] getData() {
return data;
}
static class GifResponseItem {
private String source_tld;
private ImageList images;
public String getSource() {
return source_tld;
}
public String getUrl() {
return images.fixed_height.url;
}
}
private static class ImageList {
private Gif fixed_height;
}
private static class Gif {
private String url;
}
}
|
gitchander/miscellaneous | sort_algo/gnome.go | <reponame>gitchander/miscellaneous<filename>sort_algo/gnome.go
package sort_algo
import "sort"
// Gnome sort
// Гномья сортировка
func GnomeSort(data sort.Interface) {
n := data.Len()
for i := 1; i < n; {
if (i == 0) || !data.Less(i, i-1) { // [i-1] <= [i]
i++
} else {
data.Swap(i, i-1)
i--
}
}
}
|
keerbin/cloudbreak | cloud-reactor-api/src/main/java/com/sequenceiq/cloudbreak/cloud/event/platform/GetPlatformNetworksResult.java | package com.sequenceiq.cloudbreak.cloud.event.platform;
import com.sequenceiq.cloudbreak.cloud.event.CloudPlatformRequest;
import com.sequenceiq.cloudbreak.cloud.event.CloudPlatformResult;
import com.sequenceiq.cloudbreak.cloud.model.CloudNetworks;
public class GetPlatformNetworksResult extends CloudPlatformResult<CloudPlatformRequest> {
private CloudNetworks cloudNetworks;
public GetPlatformNetworksResult(CloudPlatformRequest<?> request, CloudNetworks cloudNetworks) {
super(request);
this.cloudNetworks = cloudNetworks;
}
public GetPlatformNetworksResult(String statusReason, Exception errorDetails, CloudPlatformRequest<?> request) {
super(statusReason, errorDetails, request);
}
public CloudNetworks getCloudNetworks() {
return cloudNetworks;
}
}
|
EuroPython/djep | pyconde/sponsorship/urls.py | from django.conf.urls import url, patterns
urlpatterns = patterns('pyconde.sponsorship.views',
url(r'^$',
'list_sponsors',
name='sponsorship_list'),
url(r'^job_offers/$',
'job_offers_list_view',
name='sponsorship_job_offers'),
url(r'^send_job_offer/$',
'send_job_offer_view',
name='sponsorship_send_job_offer')
)
|
kyoujuro/istio | security/pkg/nodeagent/plugin/providers/google/stsclient/stsclient_test.go | <gh_stars>1-10
// Copyright Istio Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package stsclient
import (
"context"
"testing"
"istio.io/istio/security/pkg/stsservice/tokenmanager/google/mock"
)
func TestGetFederatedToken(t *testing.T) {
GKEClusterURL = mock.FakeGKEClusterURL
r := NewPlugin()
ms, err := mock.StartNewServer(t, mock.Config{Port: 0})
if err != nil {
t.Fatalf("failed to start a mock server: %v", err)
}
SecureTokenEndpoint = ms.URL + "/v1/identitybindingtoken"
defer func() {
if err := ms.Stop(); err != nil {
t.Logf("failed to stop mock server: %v", err)
}
SecureTokenEndpoint = "https://securetoken.googleapis.com/v1/identitybindingtoken"
}()
token, _, _, err := r.ExchangeToken(context.Background(), nil, mock.FakeTrustDomain, mock.FakeSubjectToken)
if err != nil {
t.Fatalf("failed to call exchange token %v", err)
}
if token != mock.FakeFederatedToken {
t.Errorf("Access token got %q, expected %q", token, mock.FakeFederatedToken)
}
}
|
obj-QED/Tailwind_Sass_Webpack | src/components/Nav.js | import React, { Component } from "react";
import { NavLink, Link } from "react-router-dom";
export default class Nav extends React.Component {
constructor(props) {
super(props);
this.state = {};
}
render() {
return (
<div className="navigation hidden">
<div className="logo">
<Link to={{
pathname: "/"
}}>
<p>Logo</p>
</Link>
</div>
<nav className="nav">
<ul className="nav-list">
<NavLink className="item" to="/">
<Link to="/404">
404 Error
</Link>
</NavLink>
</ul>
</nav>
</div>
);
}
} |
lcsm29/project-euler | py/py_0393_migrating_ants.py | # Solution of;
# Project Euler Problem 393: Migrating ants
# https://projecteuler.net/problem=393
#
# An n×n grid of squares contains n2 ants, one ant per square. All ants decide
# to move simultaneously to an adjacent square (usually 4 possibilities,
# except for ants on the edge of the grid or at the corners). We define f(n)
# to be the number of ways this can happen without any ants ending on the same
# square and without any two ants crossing the same edge between two squares.
# You are given that f(4) = 88. Find f(10).
#
# by lcsm29 http://github.com/lcsm29/project-euler
import timed
def dummy(n):
pass
if __name__ == '__main__':
n = 1000
i = 10000
prob_id = 393
timed.caller(dummy, n, i, prob_id)
|
ycj123/Research-Project | proFL-plugin-2.0.3/edu/emory/mathcs/backport/java/util/concurrent/locks/Lock.java | //
// Decompiled by Procyon v0.5.36
//
package edu.emory.mathcs.backport.java.util.concurrent.locks;
import edu.emory.mathcs.backport.java.util.concurrent.TimeUnit;
public interface Lock
{
void lock();
void lockInterruptibly() throws InterruptedException;
boolean tryLock();
boolean tryLock(final long p0, final TimeUnit p1) throws InterruptedException;
void unlock();
Condition newCondition();
}
|
honza-kasik/creaper | commands/src/main/java/org/wildfly/extras/creaper/commands/foundation/online/CliFile.java | package org.wildfly.extras.creaper.commands.foundation.online;
import com.google.common.base.Charsets;
import com.google.common.base.Predicates;
import com.google.common.collect.Iterables;
import com.google.common.io.ByteSource;
import org.wildfly.extras.creaper.core.CommandFailedException;
import org.wildfly.extras.creaper.core.online.CliException;
import org.wildfly.extras.creaper.core.online.OnlineCommand;
import org.wildfly.extras.creaper.core.online.OnlineCommandContext;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* <p>Apply a list of CLI operations (a CLI script) read from a file. The file is treated as UTF-8 text.</p>
*
* <p>The {@code connect} operations in the script are handled specially: bare {@code connect} operations without
* arguments are simply ignored, as we are already connected, and {@code connect host:port} operations (with an argument
* that specifies the host and port to connect to) are considered a failure. The script is scanned for the forbidden
* {@code connect} operations <i>before</i> is it executed, so if this error happens, no operation from the script
* has been performed yet.</p>
*/
public final class CliFile implements OnlineCommand {
// exactly one is always null and the other is always non-null
private final File file;
private final Class clazz;
/**
* Apply a CLI script from the filesystem ({@code file}).
* @param file an existing file on the filesystem
* @throws IllegalArgumentException if {@code file} is {@code null} or the file doesn't exist
*/
public CliFile(File file) {
if (file == null) {
throw new IllegalArgumentException("File must be set");
}
if (!file.exists()) {
throw new IllegalArgumentException("File doesn't exist: " + file);
}
this.file = file;
this.clazz = null;
}
/**
* Apply a CLI script from the classpath. The script must be stored in a file with the same name as
* the {@code clazz} and have the {@code .cli} extension. On the classpath, the script file must live along
* the class file.
* @param clazz the class that will be used for loading the script and also for discovering its name
* @throws IllegalArgumentException if the {@code clazz} is {@code null}
*/
public CliFile(Class clazz) {
if (clazz == null) {
throw new IllegalArgumentException("Class must be set");
}
this.file = null;
this.clazz = clazz;
}
@Override
public void apply(OnlineCommandContext ctx) throws IOException, CliException, CommandFailedException {
Iterable<String> lines = new CliFileByteSource().asCharSource(Charsets.UTF_8).readLines();
lines = Iterables.filter(lines, Predicates.not(Predicates.containsPattern("^\\s*connect\\s*$")));
if (Iterables.any(lines, Predicates.containsPattern("^\\s*connect"))) {
throw new CommandFailedException("The script contains an unsupported 'connect' operation: "
+ (file != null ? file : (clazz.getSimpleName() + ".cli")));
}
for (String line : lines) {
ctx.client.executeCli(line.trim());
}
}
@Override
public String toString() {
return "CliFile " + (file != null ? file : (clazz.getSimpleName() + ".cli"));
}
// ---
private final class CliFileByteSource extends ByteSource {
@Override
public InputStream openStream() throws IOException {
if (file != null) {
return new FileInputStream(file);
} else {
return clazz.getResourceAsStream(clazz.getSimpleName() + ".cli");
}
}
}
}
|
HadrienCools/blog_gatsby | node_modules/react-md/es/Dividers/index.js | import Divider from './Divider';
export default Divider;
import _Divider from './Divider';
export { _Divider as Divider }; |
malbouis/cmssw | RecoTracker/TkMSParametrization/interface/PixelRecoUtilities.h | #ifndef PixelRecoUtilities_H
#define PixelRecoUtilities_H
#include "DataFormats/GeometryVector/interface/GlobalVector.h"
#include "MagneticField/Engine/interface/MagneticField.h"
/** \namespace PixelRecoUtilities
* Small utility funcions used during seed generation
*/
namespace PixelRecoUtilities {
/** gives bending radius in magnetic field,
* pT in GeV, magnetic field taken at (0,0,0)
*/
template <typename T>
T bendingRadius(T pt, const MagneticField& field) {
return pt * field.inverseBzAtOriginInGeV();
}
/** gives transverse curvature (=1/radius of curvature) in magnetic field,
* pT in GeV, magnetic field taken at (0,0,0)
*/
template <typename T>
T curvature(T InversePt, const MagneticField& field) {
return InversePt / field.inverseBzAtOriginInGeV();
}
/** inverse pt from curvature **/
template <typename T>
T inversePt(T curvature, const MagneticField& field) {
return curvature * field.inverseBzAtOriginInGeV();
}
/** distance between stright line propagation and helix
* r_stright_line = radius+longitudinalBendingCorrection(radius,pt)
*/
inline double longitudinalBendingCorrection(double radius, double pt, const MagneticField& field) {
double invCurv = bendingRadius(pt, field);
if (invCurv == 0.)
return 0.;
return radius / 6. * radius * radius / (2. * invCurv * 2. * invCurv);
}
} // namespace PixelRecoUtilities
#endif
|
redroseio/collect | collect_app/src/test/java/org/odk/collect/android/support/FakeLifecycleOwner.java | package com.redrosecps.collect.android.support;
import androidx.annotation.NonNull;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.LifecycleRegistry;
public class FakeLifecycleOwner implements LifecycleOwner {
private final LifecycleRegistry lifecycle = new LifecycleRegistry(this);
public FakeLifecycleOwner() {
lifecycle.handleLifecycleEvent(Lifecycle.Event.ON_RESUME);
}
public void destroy() {
lifecycle.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY);
}
@NonNull
@Override
public Lifecycle getLifecycle() {
return lifecycle;
}
}
|
ak-jena/webpack | node_modules/@spectrum-web-components/icons-ui/src/custom-tag.js | <reponame>ak-jena/webpack
/*
Copyright 2020 Adobe. All rights reserved.
This file is licensed 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 REPRESENTATIONS
OF ANY KIND, either express or implied. See the License for the specific language
governing permissions and limitations under the License.
*/
import { TemplateResult } from '@spectrum-web-components/base';
export { TemplateResult };
let customTemplateLiteralTag;
export const tag = function (strings, ...values) {
if (customTemplateLiteralTag) {
return customTemplateLiteralTag(strings, ...values);
}
return values.reduce((acc, v, idx) => acc + v + strings[idx + 1], strings[0]);
};
export const setCustomTemplateLiteralTag = (tag) => {
customTemplateLiteralTag = tag;
};
//# sourceMappingURL=custom-tag.js.map |
JohnnRen/will-power | back_end/src/services/equipments/equipments.service.js | // Initializes the `equipments` service on path `/equipments`
const createService = require('feathers-nedb');
const createModel = require('../../models/equipments.model');
const _patchDelta = require('../../utils/_patchDelta');
const makePatchAction = require('../../utils/makePatchAction');
const joinFind = require('../../utils/joinFind');
const findFromGets = require('../../utils/findFromGets');
const hooks = require('./equipments.hooks');
module.exports = function(app) {
const Model = createModel(app);
const paginate = app.get('paginate');
const options = {
Model,
paginate
};
const CREATE_COST = 100;
let service = createService(options);
service.get = async function(id, params) {
let equipment = await this._get(id, params);
if (!equipment) {
return {};
}
var equipmentDetail;
if (equipment.cat === 'weapon') {
equipmentDetail = await app
.service('equipments/weapon-types')
.get(equipment.typeId);
equipmentDetail.damage = Math.round(
equipmentDetail.damage * Math.pow(1.5, equipment.tier - 1)
);
equipmentDetail.wpConsumption = Math.round(
equipmentDetail.wpConsumption * Math.pow(1.1, equipment.tier - 1)
);
}
if (equipment.cat === 'offHand') {
equipmentDetail = await app
.service('equipments/off-hand-types')
.get(equipment.typeId);
equipmentDetail.maxHp = Math.round(
equipmentDetail.maxHp * Math.pow(1.3, equipment.tier - 1)
);
equipmentDetail.maxWp = Math.round(
equipmentDetail.maxWp * Math.pow(1.3, equipment.tier - 1)
);
}
return Object.assign(equipmentDetail, equipment);
};
service.find = findFromGets;
service.create = async function(data) {
let payResult = await app.service('knights')._patchDelta(data.userId, {
field: 'willGem',
delta: -CREATE_COST,
min: 0,
stayOriginal: true,
notify: true
});
if (!payResult) {
return {};
}
let rarity = 1;
let random = Math.random();
if (random >= 0.97) {
rarity = 5;
} else if (random >= 0.9) {
rarity = 4;
} else if (random >= 0.8) {
rarity = 3;
} else if (random >= 0.5) {
rarity = 2;
} else {
rarity = 1;
}
let { data: types } = await joinFind(
[
app.service('equipments/weapon-types'),
app.service('equipments/off-hand-types')
],
{ query: { rarity: rarity } }
);
let resultTypeIndex = Math.floor(Math.random() * types.length);
let resultType = types[resultTypeIndex];
let tier;
random = Math.random();
if (random >= 0.93) {
tier = 3;
} else if (random >= 0.85) {
tier = 2;
} else {
tier = 1;
}
let createResult = await this._create({
userId: data.userId,
equipped: false,
typeId: resultType._id,
tier: tier,
acuiredTime: new Date().getTime(),
cat: resultType.cat
});
let result = Object.assign(resultType, createResult);
app.service('messages').create({
title: 'New Equipment',
message: `You forge a tier ${result.tier} ${result.name}`,
button: 'Great!'
});
return result;
};
service.patch = makePatchAction({
async equip(original) {
var { data: prevEquipped } = await this._find({
query: { equipped: true, cat: original.cat }
});
for (let prev of prevEquipped) {
let patchResult = await this._patch(prev._id, { equipped: false }, {});
this.emit('patched', patchResult);
}
return await this._patch(original._id, { equipped: true }, {});
},
async unequip(original) {
return await this._patch(original._id, { equipped: false }, {});
},
async advance(original) {
var { data: sameEquipment } = await this._find({
query: { typeId: original.typeId, tier: original.tier }
});
sameEquipment = sameEquipment.filter(e => e._id !== original._id);
if (sameEquipment.length >= 1) {
let consume = sameEquipment[0];
this._remove(consume._id, {});
this.emit('removed', { _id: consume._id });
let result = await this._patchDelta(original._id, {
field: 'tier',
delta: 1,
usePrivate: true
});
result = await this.get(original._id);
app.service('messages').create({
userId: original.userId,
title: 'Advance Succeed',
message: `Your ${result.name} is now Tier ${result.tier}.`,
button: 'Great!'
});
return result;
} else {
app.service('messages').create({
userId: original.userId,
title: 'Advance Fail',
message: 'You need 2 identical equipments to advance.',
button: 'I understand'
});
return original;
}
}
});
service._patchDelta = _patchDelta;
service.remove = async function(id, params) {
let equipment = await this.get(id);
await app.service('knights')._patchDelta(equipment.userId, {
field: 'willGem',
delta:
equipment.rarity *
equipment.rarity *
15 *
Math.pow(2, equipment.tier - 1),
notify: true
});
return await this._remove(id, params);
};
// Initialize our service with any options it requires
app.use('/equipments', service);
// Get our initialized service so that we can register hooks
service = app.service('equipments');
service.hooks(hooks);
};
|
kayahr/wlandsuite | src/main/java/de/ailis/wlandsuite/game/parts/Answer.java | <gh_stars>1-10
/*
* $Id$
* Copyright (C) 2006 <NAME> <<EMAIL>>
*
* 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 de.ailis.wlandsuite.game.parts;
import de.ailis.wlandsuite.utils.StringUtils;
import de.ailis.wlandsuite.utils.XmlUtils;
import org.dom4j.Element;
/**
* A dialogue item used in the Dialogue Action
*
* @author <NAME> (<EMAIL>)
* @version $Revision$
*/
public class Answer
{
/** The answer message */
private int message;
/** The new action class to set when this answer is selected */
private int newActionClass;
/** The new action to set when this answer is selected */
private int newAction;
/**
* Constructor
*
* @param answer
* The answer
* @param newActionClass
* The new action class
* @param newAction
* The new action
*/
public Answer(int answer, int newActionClass, int newAction)
{
this.message = answer;
this.newActionClass = newActionClass;
this.newAction = newAction;
}
/**
* Constructor
*/
public Answer()
{
super();
}
/**
* Returns the check data as XML.
*
* @return The check data as XML
*/
public Element toXml()
{
Element element;
element = XmlUtils.createElement("answer");
element.addAttribute("message", Integer.toString(this.message));
element.addAttribute("newActionClass", StringUtils.toHex(this.newActionClass));
element.addAttribute("newAction", StringUtils.toHex(this.newAction));
return element;
}
/**
* Creates and returns a new Check object by reading its data from XML.
*
* @param element
* The XML element
* @return The check data
*/
public static Answer read(Element element)
{
int message, newActionClass, newAction;
message = StringUtils.toInt(element.attributeValue("message"));
newActionClass = StringUtils.toInt(element.attributeValue("newActionClass"));
newAction = StringUtils.toInt(element.attributeValue("newAction"));
return new Answer(message, newActionClass, newAction);
}
/**
* Sets the message.
*
* @param message
* The message to set
*/
public void setMessage(int message)
{
this.message = message;
}
/**
* Sets the newAction.
*
* @param newAction
* The newAction to set
*/
public void setNewAction(int newAction)
{
this.newAction = newAction;
}
/**
* Sets the newActionClass.
*
* @param newActionClass
* The newActionClass to set
*/
public void setNewActionClass(int newActionClass)
{
this.newActionClass = newActionClass;
}
/**
* Returns the message.
*
* @return The message
*/
public int getMessage()
{
return this.message;
}
/**
* Returns the newAction.
*
* @return The newAction
*/
public int getNewAction()
{
return this.newAction;
}
/**
* Returns the newActionClass.
*
* @return The newActionClass
*/
public int getNewActionClass()
{
return this.newActionClass;
}
}
|
AlexKoukoulas2074245K/Genesis | source/engine/resources/ShaderLoader.h | ///------------------------------------------------------------------------------------------------
/// ShaderLoader.h
/// Genesis
///
/// Created by <NAME> on 20/11/2019.
///------------------------------------------------------------------------------------------------
#ifndef ShaderLoader_h
#define ShaderLoader_h
///------------------------------------------------------------------------------------------------
#include "IResourceLoader.h"
#include "../common/utils/StringUtils.h"
#include <memory>
#include <string>
#include <tsl/robin_map.h>
///------------------------------------------------------------------------------------------------
namespace genesis
{
///------------------------------------------------------------------------------------------------
namespace resources
{
///------------------------------------------------------------------------------------------------
using GLuint = unsigned int;
///------------------------------------------------------------------------------------------------
class ShaderLoader final : public IResourceLoader
{
friend class ResourceLoadingService;
public:
void VInitialize() override;
std::unique_ptr<IResource> VCreateAndLoadResource(const std::string& path) const override;
private:
static const std::string VERTEX_SHADER_FILE_EXTENSION;
static const std::string FRAGMENT_SHADER_FILE_EXTENSION;
ShaderLoader() = default;
std::string ReadFileContents(const std::string& filePath) const;
tsl::robin_map<StringId, GLuint, StringIdHasher> GetUniformNamesToLocationsMap
(
const GLuint programId,
const std::string& vertexShaderFileContents,
const std::string& fragmentShaderFileContents
) const;
};
///------------------------------------------------------------------------------------------------
}
}
///------------------------------------------------------------------------------------------------
#endif /* ShaderLoader_h */
|
BipronathSaha/immudb | cmd/immutest/command/cmd.go | <filename>cmd/immutest/command/cmd.go<gh_stars>0
/*
Copyright 2019-2020 vChain, 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 immutest
import (
c "github.com/codenotary/immudb/cmd/helper"
"github.com/codenotary/immudb/cmd/version"
"github.com/spf13/cobra"
)
var o = c.Options{}
func init() {
cobra.OnInitialize(func() { o.InitConfig("immutest") })
}
func NewCmd() *cobra.Command {
cmd := &cobra.Command{}
Init(cmd, &o)
cmd.AddCommand(version.VersionCmd())
return cmd
}
|
uwsampl/libposit | src/cjd/impl.h | <filename>src/cjd/impl.h
// SPDX-License-Identifier: MIT OR BSD-3-Clause
#include "posit.h"
// CAUTION: This header file is included in weird ways, DO NOT define any function
// signatures or types here. This file should only contain the implementation name
// and registration macros and should only include posit.h and implement_posit.h.
#define posit_IMPLEMENTATION cjd
#include "implement_posit.h"
// This is not recommended, but if you must register a function with a different name
// than posit<X>_<op>_<yourimpl>, you can redirect the name this way
posit8_equals_REGISTER_NAMED(posit8_equals_cjd_differentlynamed)
posit16_equals_REGISTER
posit32_equals_REGISTER
posit64_equals_REGISTER
posit8_cmp_REGISTER
posit16_cmp_REGISTER
posit32_cmp_REGISTER
posit64_cmp_REGISTER
posit8_cmpabs_REGISTER
posit16_cmpabs_REGISTER
posit32_cmpabs_REGISTER
posit64_cmpabs_REGISTER
|
dhenisdj/deep-object-reid | torchreid/engine/__init__.py | <reponame>dhenisdj/deep-object-reid<filename>torchreid/engine/__init__.py<gh_stars>1-10
from __future__ import print_function, absolute_import
from .engine import Engine
from .image import ImageSoftmaxEngine, ImageAMSoftmaxEngine, ImageTripletEngine
from .video import VideoSoftmaxEngine, VideoTripletEngine
from .builder import build_engine
|
cc616/cuke-ui | components/pagination/__tests__/index.test.js | import Select from "../../select";
import React from "react";
import { render, shallow } from "enzyme";
import assert from "power-assert";
import toJson from "enzyme-to-json";
import Pagination from "../index";
import Button from "../../button";
import { ArrowLeftIcon, ArrowRightIcon, SuccessIcon } from "../../icon";
import NumberInput from "../../number-input";
describe("<Pagination/>", () => {
it("should render Pagination", () => {
const wrapper = render(
<div>
<Pagination current={1} total={50} />
<Pagination
current={1}
total={50}
locale={{ prevText: "后退", nextText: "前进" }}
/>
<Pagination current={1} total={50} showQuickJumper />
<Pagination current={1} total={50} showSizeChanger />
</div>
);
expect(toJson(wrapper)).toMatchSnapshot();
});
it("should render simple Pagination", () => {
const wrapper = render(
<Pagination current={1} total={10} simple separator="|" />
);
expect(toJson(wrapper)).toMatchSnapshot();
});
it("should render sizes", () => {
const wrapper = render(
<div>
<Pagination current={1} total={50} size="small" showSizeChanger />
<Pagination current={1} total={50} size="default" showSizeChanger />
<Pagination current={1} total={50} size="large" showSizeChanger />
</div>
);
expect(toJson(wrapper)).toMatchSnapshot();
});
it("should render custom separator", () => {
const wrapper = shallow(
<Pagination current={1} total={10} simple separator={<SuccessIcon />} />
);
expect(wrapper.find(SuccessIcon)).toHaveLength(1);
});
it("should find cuke-pagination classnames", () => {
const wrapper = shallow(<Pagination current={1} total={10} />);
assert(wrapper.find(".cuke-pagination").length === 1);
expect(toJson(wrapper)).toMatchSnapshot();
});
it("should find cuke-pagination-simple classnames when is simple mode", () => {
const wrapper = shallow(<Pagination current={1} total={10} simple />);
assert(wrapper.find(".cuke-pagination-simple").length === 1);
expect(toJson(wrapper)).toMatchSnapshot();
});
it("should find custom locale text", () => {
const wrapper = render(
<Pagination
current={1}
total={10}
locale={{ prevText: "后退", nextText: "前进" }}
/>
);
expect(wrapper.text()).toContain("后退");
expect(wrapper.text()).toContain("前进");
expect(toJson(wrapper)).toMatchSnapshot();
});
it("should find default locale text", () => {
const wrapper = shallow(<Pagination current={1} total={10} />);
assert(wrapper.find(ArrowLeftIcon).length === 1);
assert(wrapper.find(ArrowRightIcon).length === 1);
});
it("should emit onChange events", () => {
const onChange = jest.fn();
const wrapper = shallow(
<Pagination onChange={onChange} current={2} total={50} />
);
wrapper.find(".cuke-pagination-prev").simulate("click");
expect(onChange).toHaveBeenCalled();
expect(wrapper.state().current).toBe(1);
wrapper.find(".cuke-pagination-next").simulate("click");
expect(onChange).toHaveBeenCalled();
expect(wrapper.state().current).toBe(2);
});
it("should emit onChange events with simple mode", () => {
const onChange = jest.fn();
const wrapper = shallow(
<Pagination simple onChange={onChange} current={1} total={10} />
);
wrapper
.find(Button)
.at(1)
.simulate("click");
expect(onChange).toHaveBeenCalled();
});
it("should emit on click events with simple", () => {
const onChange = jest.fn();
const wrapper = shallow(
<Pagination simple onChange={onChange} current={1} total={10} />
);
wrapper
.find(Button)
.at(1)
.simulate("click");
expect(wrapper.state().current).toBe(2);
});
it("should emit onChange events", () => {
const onChange = jest.fn();
const wrapper = shallow(
<Pagination onChange={onChange} current={2} total={50} />
);
wrapper.find(".cuke-pagination-prev").simulate("click");
expect(onChange).toHaveBeenCalled();
expect(wrapper.state().current).toBe(1);
wrapper.find(".cuke-pagination-next").simulate("click");
expect(onChange).toHaveBeenCalled();
expect(wrapper.state().current).toBe(2);
});
it("should render 10 page button when pageSize is 5", () => {
const wrapper = shallow(<Pagination pageSize={5} total={50} />);
const prevAndNext = 2;
expect(wrapper.find(".cuke-pagination-item")).toHaveLength(
10 + prevAndNext
);
});
it("should render 10 page button when pageSize is 5", () => {
const wrapper = shallow(<Pagination pageSize={5} total={49} />);
const prevAndNext = 2;
expect(wrapper.find(".cuke-pagination-item")).toHaveLength(
10 + prevAndNext
);
});
it("should render show size changer selector", () => {
const wrapper = shallow(
<Pagination pageSize={5} total={49} showSizeChanger />
);
expect(wrapper.find(Select)).toHaveLength(1);
});
it("should render custom total", () => {
const wrapper = shallow(
<Pagination
pageSize={5}
total={49}
showTotal={total => `共${total}条数据`}
/>
);
expect(wrapper.text()).toContain("共49条数据");
});
it("should trigger onChange", () => {
const onChange = jest.fn();
const wrapper = shallow(
<Pagination pageSize={5} total={49} onChange={onChange} />
);
wrapper
.find(".cuke-pagination-item")
.at(2)
.simulate("click");
expect(onChange).toHaveBeenCalled();
});
it("should find quick jumper", () => {
const wrapper = shallow(
<Pagination pageSize={5} total={49} showQuickJumper />
);
expect(wrapper.find(NumberInput)).toHaveLength(1);
});
});
|
edgar615/api-gateway | dispatch/src/main/java/com/github/edgar615/gateway/filter/ResponseReplaceFilter.java | package com.github.edgar615.gateway.filter;
import com.google.common.collect.Multimap;
import com.github.edgar615.gateway.core.dispatch.ApiContext;
import com.github.edgar615.gateway.core.dispatch.Filter;
import com.github.edgar615.gateway.core.dispatch.Result;
import io.vertx.core.Future;
import io.vertx.core.json.JsonObject;
/**
* 将Result中的请求头,请求参数,请求体按照ResponseTransformerPlugin中的配置处理.
* 目前body只考虑JsonObject类型的result修改,对JsonArray暂不支持.
* Created by edgar on 16-9-20.
*/
public class ResponseReplaceFilter extends AbstractReplaceFilter implements Filter {
ResponseReplaceFilter() {
}
@Override
public String type() {
return POST;
}
@Override
public int order() {
return Integer.MAX_VALUE - 1000;
}
@Override
public boolean shouldFilter(ApiContext apiContext) {
return true;
}
@Override
public void doFilter(ApiContext apiContext, Future<ApiContext> completeFuture) {
Result result = apiContext.result();
//如果body的JsonObject直接添加,如果是JsonArray,不支持body的修改
boolean isArray = result.isArray();
//body目前仅考虑JsonObject的替换
Multimap<String, String> header =
replaceHeader(apiContext, result.headers());
if (!isArray) {
JsonObject body = replaceBody(apiContext, result.responseObject());
apiContext.setResult(Result.createJsonObject(result.statusCode(),
body, header));
} else {
apiContext.setResult(Result.createJsonArray(result.statusCode(),
result.responseArray(), header));
}
completeFuture.complete(apiContext);
}
} |
dranawhite/study-java | study-tomcat/src/main/java/com/study/tomcat/lifecycle/Lifecycle.java | package com.study.tomcat.lifecycle;
/**
*
* @author dranawhite
* @version $Id: Lifecycle.java, v 0.1 2019-03-09 13:59 dranawhite Exp $$
*/
public interface Lifecycle {
void start();
void stop();
}
|
alect/Puzzledice | Tools/PuzzleMapEditor/src/puzzledice/PropertyChangePuzzleBlock.java | package puzzledice;
import gui.PuzzleEditPanel;
import gui.WindowMain;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.swing.BoxLayout;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import com.mxgraph.view.mxGraph;
public class PropertyChangePuzzleBlock extends PuzzleBlock {
private PuzzleBlock _changerBlock, _changeeBlock;
private static int nextIndex = 0;
public static void reset() {
nextIndex = 0;
}
private JComboBox _changerSelect, _changeeSelect;
private JCheckBox _useProperty;
private JPanel _propertyNamePanel, _propertyValuePanel;
private JTextField _propertyNameSelect, _propertyValueSelect;
private String _changerName, _changeeName, _propertyName, _propertyValue;
public void setChangerName(String value) {
_changerName = value;
}
public void setChangeeName(String value) {
_changeeName = value;
}
public void setPropertyName(String value) {
_propertyName = value;
}
public void setPropertyValue(String value) {
_propertyValue = value;
}
public PropertyChangePuzzleBlock()
{
_name = "Property-Change-" + ++nextIndex;
_type = "Property Change Puzzle";
JPanel editPanel = new JPanel();
editPanel.setLayout(new BoxLayout(editPanel, BoxLayout.Y_AXIS));
// Changer ComboBox Panel
JPanel changerPanel = new JPanel();
changerPanel.setLayout(new BoxLayout(changerPanel, BoxLayout.X_AXIS));
JLabel changerLabel = new JLabel("Changer:");
changerPanel.add(changerLabel);
_changerSelect = new JComboBox();
_changerSelect.setMaximumSize(new Dimension(Integer.MAX_VALUE, _changerSelect.getPreferredSize().height));
changerPanel.add(_changerSelect);
editPanel.add(changerPanel);
// Changee ComboBox Panel
JPanel changeePanel = new JPanel();
changeePanel.setLayout(new BoxLayout(changeePanel, BoxLayout.X_AXIS));
JLabel changeeLabel = new JLabel("Changee:");
changeePanel.add(changeeLabel);
_changeeSelect = new JComboBox();
_changeeSelect.setMaximumSize(new Dimension(Integer.MAX_VALUE, _changeeSelect.getPreferredSize().height));
changeePanel.add(_changeeSelect);
editPanel.add(changeePanel);
// Panel for asking to change a specific property
JPanel propertyPanel = new JPanel();
propertyPanel.setLayout(new BoxLayout(propertyPanel, BoxLayout.X_AXIS));
JLabel propertyLabel = new JLabel("Use Specific Property");
propertyPanel.add(propertyLabel);
_useProperty = new JCheckBox();
propertyPanel.add(_useProperty);
editPanel.add(propertyPanel);
// Panel for changing the specific property name
_propertyNamePanel = new JPanel();
_propertyNamePanel.setLayout(new BoxLayout(_propertyNamePanel, BoxLayout.X_AXIS));
JLabel propertyNameLabel = new JLabel("Desired Property Name:");
_propertyNamePanel.add(propertyNameLabel);
_propertyNameSelect = new JTextField();
_propertyNameSelect.setMaximumSize(new Dimension(Integer.MAX_VALUE, _propertyNameSelect.getPreferredSize().height));
_propertyNameSelect.setText("None");
_propertyNamePanel.add(_propertyNameSelect);
_propertyNameSelect.setColumns(10);
_propertyNamePanel.setVisible(false);
editPanel.add(_propertyNamePanel);
// Panel for changing the specific property value
_propertyValuePanel = new JPanel();
_propertyValuePanel.setLayout(new BoxLayout(_propertyValuePanel, BoxLayout.X_AXIS));
JLabel propertyValueLabel = new JLabel("Desired Property Value:");
_propertyValuePanel.add(propertyValueLabel);
_propertyValueSelect = new JTextField();
_propertyValueSelect.setMaximumSize(new Dimension(Integer.MAX_VALUE, _propertyValueSelect.getPreferredSize().height));
_propertyValueSelect.setText("None");
_propertyValuePanel.add(_propertyValueSelect);
_propertyValueSelect.setColumns(10);
_propertyValuePanel.setVisible(false);
editPanel.add(_propertyValuePanel);
_editUI = editPanel;
_changerSelect.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if(_changerBlock == _changerSelect.getSelectedItem() || _changerBlock == null && _changerSelect.getSelectedItem().equals("None"))
return;
mxGraph puzzleGraph = WindowMain.getPuzzleGraph();
// Before anything, check for a cycle
if (_changerSelect.getSelectedItem() != null && !_changerSelect.getSelectedItem().equals("None")) {
PuzzleBlock block = (PuzzleBlock)_changerSelect.getSelectedItem();
if (block.canReachBlockBackwards(PropertyChangePuzzleBlock.this)) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JOptionPane.showMessageDialog(null, "Error: Cannot add cycle to puzzle graph.");
}
});
if (_changerBlock != null)
_changerSelect.setSelectedItem(_changerBlock);
else
_changerSelect.setSelectedIndex(0);
return;
}
}
// first, see if we need to remove a previous edge
if(_changerBlock != null)
{
puzzleGraph.getModel().beginUpdate();
try { puzzleGraph.removeCells(puzzleGraph.getEdgesBetween(_changerBlock.getGraphCell(), _graphCell, false)); }
finally { puzzleGraph.getModel().endUpdate(); }
}
if (_changerSelect.getSelectedItem() == null)
_changerSelect.setSelectedIndex(0);
if(_changerSelect.getSelectedItem().equals("None"))
_changerBlock = null;
else
{
_changerBlock = (PuzzleBlock)_changerSelect.getSelectedItem();
// update the graph with a new edge
puzzleGraph.getModel().beginUpdate();
try { puzzleGraph.insertEdge(puzzleGraph.getDefaultParent(), null, null, _changerBlock.getGraphCell(), _graphCell);}
finally { puzzleGraph.getModel().endUpdate();}
}
_changeeSelect.setModel(new DefaultComboBoxModel(makeChangeeComboBox()));
if (_changeeBlock == null)
_changeeSelect.setSelectedIndex(0);
else
_changeeSelect.setSelectedItem(_changeeBlock);
PuzzleEditPanel.resetTextualDescription();
WindowMain.updatePuzzleGraph();
}
});
_changeeSelect.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if(_changeeBlock == _changeeSelect.getSelectedItem() || _changeeBlock == null && _changeeSelect.getSelectedItem().equals("None"))
return;
mxGraph puzzleGraph = WindowMain.getPuzzleGraph();
// Before anything, check for a cycle
if (_changeeSelect.getSelectedItem() != null && !_changeeSelect.getSelectedItem().equals("None")) {
PuzzleBlock block = (PuzzleBlock)_changeeSelect.getSelectedItem();
if (block.canReachBlockBackwards(PropertyChangePuzzleBlock.this)) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JOptionPane.showMessageDialog(null, "Error: Cannot add cycle to puzzle graph.");
}
});
if (_changeeBlock != null)
_changeeSelect.setSelectedItem(_changeeBlock);
else
_changeeSelect.setSelectedIndex(0);
return;
}
}
// first, see if we need to remove a previous edge
if(_changeeBlock != null)
{
puzzleGraph.getModel().beginUpdate();
try { puzzleGraph.removeCells(puzzleGraph.getEdgesBetween(_changeeBlock.getGraphCell(), _graphCell, false)); }
finally { puzzleGraph.getModel().endUpdate(); }
}
if (_changeeSelect.getSelectedItem() == null)
_changeeSelect.setSelectedIndex(0);
if(_changeeSelect.getSelectedItem().equals("None"))
_changeeBlock = null;
else
{
_changeeBlock = (PuzzleBlock)_changeeSelect.getSelectedItem();
// update the graph with a new edge
puzzleGraph.getModel().beginUpdate();
try { puzzleGraph.insertEdge(puzzleGraph.getDefaultParent(), null, null, _changeeBlock.getGraphCell(), _graphCell);}
finally { puzzleGraph.getModel().endUpdate();}
}
_changerSelect.setModel(new DefaultComboBoxModel(makeChangerComboBox()));
if (_changerBlock == null)
_changerSelect.setSelectedIndex(0);
else
_changerSelect.setSelectedItem(_changerBlock);
PuzzleEditPanel.resetTextualDescription();
WindowMain.updatePuzzleGraph();
}
});
_useProperty.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
// Set the visibility of certain elements
_propertyNamePanel.setVisible(_useProperty.isSelected());
_propertyValuePanel.setVisible(_useProperty.isSelected());
PuzzleEditPanel.resetTextualDescription();
}
});
_propertyNameSelect.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void changedUpdate(DocumentEvent evt) {
PuzzleEditPanel.resetTextualDescription();
}
@Override
public void insertUpdate(DocumentEvent evt) {
PuzzleEditPanel.resetTextualDescription();
}
@Override
public void removeUpdate(DocumentEvent evt) {
PuzzleEditPanel.resetTextualDescription();
}
});
_propertyValueSelect.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void changedUpdate(DocumentEvent evt) {
PuzzleEditPanel.resetTextualDescription();
}
@Override
public void insertUpdate(DocumentEvent evt) {
PuzzleEditPanel.resetTextualDescription();
}
@Override
public void removeUpdate(DocumentEvent evt) {
PuzzleEditPanel.resetTextualDescription();
}
});
}
@Override
public void update() {
_changerSelect.setModel(new DefaultComboBoxModel(makeChangerComboBox()));
if (_changerBlock == null)
_changerSelect.setSelectedIndex(0);
else
_changerSelect.setSelectedItem(_changerBlock);
_changeeSelect.setModel(new DefaultComboBoxModel(makeChangeeComboBox()));
if (_changeeBlock == null)
_changeeSelect.setSelectedIndex(0);
else
_changeeSelect.setSelectedItem(_changeeBlock);
}
private Object[] makeChangerComboBox()
{
List<Object> retVal = new ArrayList<Object>();
PuzzleBlock[] blockList = PuzzleEditPanel.getBlockList();
retVal.add("None");
for(PuzzleBlock p : blockList) {
if(!p.equals(_changeeSelect.getSelectedItem()) && !p.equals(this))
retVal.add(p);
}
return retVal.toArray();
}
private Object[] makeChangeeComboBox()
{
List<Object> retVal = new ArrayList<Object>();
PuzzleBlock[] blockList = PuzzleEditPanel.getBlockList();
retVal.add("None");
for(PuzzleBlock p : blockList) {
if(!p.equals(_changerSelect.getSelectedItem()) && !p.equals(this))
retVal.add(p);
}
return retVal.toArray();
}
@Override
public void maybeRemoveRef(PuzzleBlock block)
{
if(block.equals(_changerBlock)) {
_changerBlock = null;
_changerSelect.setSelectedIndex(0);
}
if(block.equals(_changeeBlock)) {
_changeeBlock = null;
_changeeSelect.setSelectedIndex(0);
}
}
@Override
public String getTextualDescription()
{
String retVal = "";
if (_changerBlock != null)
retVal += _changerBlock.getTextualDescription();
if (_changeeBlock != null)
retVal += _changeeBlock.getTextualDescription();
_outputTempName = (_changeeBlock == null) ? "SOMETHING" : _changeeBlock.getOutputTempName();
String changer = (_changerBlock == null) ? "SOMETHING" : _changerBlock.getOutputTempName();
String propertyName, propertyValue;
if(_useProperty.isSelected())
{
propertyName = "the " + _propertyNameSelect.getText() + " property";
propertyValue = "the value: " + _propertyValueSelect.getText();
}
else
{
propertyName = "some property";
propertyValue = "some value";
}
retVal += "The player uses " + changer + " to change " + propertyName + " of " + _outputTempName + " to " + propertyValue + ". ";
_outputTempName += " (with " + propertyName + " set to " + propertyValue + ")";
return retVal;
}
@Override
public void attachBlocksToName(Map<String, AreaBlock> areas, Map<String, PuzzleBlock> puzzles)
{
mxGraph puzzleGraph = WindowMain.getPuzzleGraph();
if (_changerName != null) {
_changerBlock = puzzles.get(_changerName);
puzzleGraph.getModel().beginUpdate();
try { puzzleGraph.insertEdge(puzzleGraph.getDefaultParent(), null, null, _changerBlock.getGraphCell(), _graphCell);}
finally { puzzleGraph.getModel().endUpdate();}
}
if (_changeeName != null) {
_changeeBlock = puzzles.get(_changeeName);
puzzleGraph.getModel().beginUpdate();
try { puzzleGraph.insertEdge(puzzleGraph.getDefaultParent(), null, null, _changeeBlock.getGraphCell(), _graphCell);}
finally { puzzleGraph.getModel().endUpdate();}
}
if (_propertyName != null) {
_propertyNameSelect.setText(_propertyName);
_useProperty.setSelected(true);
}
if (_propertyValue != null) {
_propertyValueSelect.setText(_propertyValue);
_useProperty.setSelected(true);
}
_propertyNamePanel.setVisible(_useProperty.isSelected());
_propertyValuePanel.setVisible(_useProperty.isSelected());
this.update();
}
@Override
public PuzzleBlock[] getPuzzleInputs()
{
if (_changerBlock != null && _changeeBlock != null)
return new PuzzleBlock[] { _changerBlock, _changeeBlock };
else if (_changerBlock != null)
return new PuzzleBlock[] { _changerBlock };
else if (_changeeBlock != null)
return new PuzzleBlock[] { _changeeBlock };
return new PuzzleBlock[0];
}
@Override
public String toXML()
{
String xml = "<PropertyChangePuzzle name=\"" + _name + "\" ";
if (_changerBlock != null)
xml += "changer=\"" + _changerBlock.getName() + "\" ";
if (_changeeBlock != null)
xml += "changee=\"" + _changeeBlock.getName() + "\" ";
if (_useProperty.isSelected()) {
if (_propertyNameSelect.getText() != null && !_propertyNameSelect.getText().equals("") && !_propertyNameSelect.getText().equals("None"))
xml += "propertyName=\"" + _propertyNameSelect.getText() + "\" ";
if (_propertyValueSelect.getText() != null && !_propertyValueSelect.getText().equals("") && !_propertyValueSelect.getText().equals("None"))
xml += "propertyValue=\"" + _propertyValueSelect.getText() + "\" ";
}
xml += "/>";
return xml;
}
}
|
hugeblank/Bagels_Baking | src/main/java/dev/elexi/hugeblank/bagels_baking/block/BasicCandleCakeBlock.java | <reponame>hugeblank/Bagels_Baking
package dev.elexi.hugeblank.bagels_baking.block;
import net.minecraft.block.Block;
import net.minecraft.block.BlockState;
import net.minecraft.block.CandleBlock;
import net.minecraft.block.CandleCakeBlock;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.ItemStack;
import net.minecraft.item.Items;
import net.minecraft.util.ActionResult;
import net.minecraft.util.Hand;
import net.minecraft.util.hit.BlockHitResult;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.BlockView;
import net.minecraft.world.World;
import java.util.HashMap;
import java.util.Map;
public class BasicCandleCakeBlock extends CandleCakeBlock {
private final BasicCakeBlock cake;
private static final Map<BasicCakeBlock, Map<CandleBlock, BasicCandleCakeBlock>> COMBINER = new HashMap<>();
public BasicCandleCakeBlock(Block candle, BasicCakeBlock cake, Settings settings) {
super(candle, settings);
this.cake = cake;
if (COMBINER.containsKey(cake)) {
COMBINER.get(cake).put((CandleBlock) candle, this);
} else {
Map<CandleBlock, BasicCandleCakeBlock> candleCakeBlockMap = new HashMap<>();
candleCakeBlockMap.put((CandleBlock) candle, this);
COMBINER.put(cake, candleCakeBlockMap);
}
}
public static BlockState getCandleCakeFromCandle(BasicCakeBlock cake, CandleBlock candle) {
return COMBINER.get(cake).get(candle).getDefaultState();
}
@Override
public ActionResult onUse(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockHitResult hit) {
ItemStack itemStack = player.getStackInHand(hand);
if (!itemStack.isOf(Items.FLINT_AND_STEEL) && !itemStack.isOf(Items.FIRE_CHARGE)) {
if (isHittingCandle(hit) && player.getStackInHand(hand).isEmpty() && state.get(LIT)) {
extinguish(player, state, world, pos);
return ActionResult.success(world.isClient);
} else {
ActionResult actionResult = BasicCakeBlock.tryEat(world, pos, cake.getDefaultState(), player);
if (actionResult.isAccepted()) {
dropStacks(state, world, pos);
}
return actionResult;
}
} else {
return ActionResult.PASS;
}
}
@Override
public ItemStack getPickStack(BlockView world, BlockPos pos, BlockState state) {
return new ItemStack(cake);
}
protected static boolean isHittingCandle(BlockHitResult hitResult) {
return hitResult.getPos().y - (double)hitResult.getBlockPos().getY() > 0.5D;
}
}
|
nattangwiwat/Mayan-EDMS-recitation | mayan/apps/duplicates/migrations/0009_auto_20210124_0738.py | <gh_stars>100-1000
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('duplicates', '0008_auto_20201130_0847'),
]
operations = [
migrations.RemoveField(
model_name='duplicatebackendentry',
name='datetime_added',
),
migrations.AlterField(
model_name='storedduplicatebackend',
name='backend_data',
field=models.TextField(
blank=True, help_text='JSON encoded data for the backend '
'class.', verbose_name='Backend data'
),
),
]
|
QlcChainOrg/winq-ios | Qlink/Main/Topup/GroupBuy/Cell/OngoingGroupCell.h | <gh_stars>1-10
//
// OngoingGroupCell.h
// Qlink
//
// Created by <NAME> on 2020/1/13.
// Copyright © 2020 pan. All rights reserved.
//
#import "QBaseTableCell.h"
NS_ASSUME_NONNULL_BEGIN
@class GroupBuyListModel;
static NSString *OngoingGroupCell_Reuse = @"OngoingGroupCell";
#define OngoingGroupCell_Height 60
typedef void(^OngoingGroupJoinBlock)(GroupBuyListModel *joinM);
@interface OngoingGroupCell : QBaseTableCell
- (void)config:(GroupBuyListModel *)model joinB:(OngoingGroupJoinBlock)joinB;
@end
NS_ASSUME_NONNULL_END
|
PhantomPowered/Proxy | proxy-api/src/main/java/com/github/phantompowered/proxy/api/location/Vector.java | /*
* This class has been taken from the Bukkit API
*/
package com.github.phantompowered.proxy.api.location;
import com.github.phantompowered.proxy.api.math.MathHelper;
import org.jetbrains.annotations.NotNull;
import java.io.Serializable;
/**
* Represents a mutable vector. Because the components of Vectors are mutable,
* storing Vectors long term may be dangerous if passing code modifies the
* Vector later. If you want to keep around a Vector, it may be wise to call
* <code>clone()</code> in order to get a copy.
*/
public class Vector implements Cloneable, Serializable {
private static final long serialVersionUID = -2657651106777219169L;
private static final double EPSILON = 0.000001;
protected double x;
protected double y;
protected double z;
public Vector() {
this.x = 0;
this.y = 0;
this.z = 0;
}
public Vector(int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
}
public Vector(double x, double y, double z) {
this.x = x;
this.y = y;
this.z = z;
}
public Vector(float x, float y, float z) {
this.x = x;
this.y = y;
this.z = z;
}
public static double getEpsilon() {
return EPSILON;
}
@NotNull
public Vector add(double x, double y, double z) {
this.x += x;
this.y += y;
this.z += z;
return this;
}
@NotNull
public Vector add(@NotNull Vector vec) {
return this.add(vec.x, vec.y, vec.z);
}
@NotNull
public Vector subtract(@NotNull Vector vec) {
x -= vec.x;
y -= vec.y;
z -= vec.z;
return this;
}
@NotNull
public Vector multiply(@NotNull Vector vec) {
x *= vec.x;
y *= vec.y;
z *= vec.z;
return this;
}
@NotNull
public Vector divide(@NotNull Vector vec) {
x /= vec.x;
y /= vec.y;
z /= vec.z;
return this;
}
@NotNull
public Vector copy(@NotNull Vector vec) {
x = vec.x;
y = vec.y;
z = vec.z;
return this;
}
public double length() {
return Math.sqrt(MathHelper.square(x) + MathHelper.square(y) + MathHelper.square(z));
}
public double lengthSquared() {
return MathHelper.square(x) + MathHelper.square(y) + MathHelper.square(z);
}
public double distance(@NotNull Vector o) {
return Math.sqrt(MathHelper.square(x - o.x) + MathHelper.square(y - o.y) + MathHelper.square(z - o.z));
}
public double distanceSquared(@NotNull Vector o) {
return MathHelper.square(x - o.x) + MathHelper.square(y - o.y) + MathHelper.square(z - o.z);
}
public float angle(@NotNull Vector other) {
double dot = MathHelper.clamp(dot(other) / (length() * other.length()), -1, 1);
return (float) Math.acos(dot);
}
@NotNull
public Vector midpoint(@NotNull Vector other) {
x = (x + other.x) / 2;
y = (y + other.y) / 2;
z = (z + other.z) / 2;
return this;
}
@NotNull
public Vector getMidpoint(@NotNull Vector other) {
double x = (this.x + other.x) / 2;
double y = (this.y + other.y) / 2;
double z = (this.z + other.z) / 2;
return new Vector(x, y, z);
}
@NotNull
public Vector multiply(int m) {
x *= m;
y *= m;
z *= m;
return this;
}
@NotNull
public Vector multiply(double m) {
x *= m;
y *= m;
z *= m;
return this;
}
@NotNull
public Vector multiply(float m) {
x *= m;
y *= m;
z *= m;
return this;
}
public double dot(@NotNull Vector other) {
return x * other.x + y * other.y + z * other.z;
}
@NotNull
public Vector crossProduct(@NotNull Vector o) {
double newX = y * o.z - o.y * z;
double newY = z * o.x - o.z * x;
double newZ = x * o.y - o.x * y;
x = newX;
y = newY;
z = newZ;
return this;
}
@NotNull
public Vector getCrossProduct(@NotNull Vector o) {
double x = this.y * o.z - o.y * this.z;
double y = this.z * o.x - o.z * this.x;
double z = this.x * o.y - o.x * this.y;
return new Vector(x, y, z);
}
@NotNull
public Vector normalize() {
double length = length();
x /= length;
y /= length;
z /= length;
return this;
}
public boolean isInAABB(@NotNull Vector min, @NotNull Vector max) {
return x >= min.x && x <= max.x && y >= min.y && y <= max.y && z >= min.z && z <= max.z;
}
public boolean isInSphere(@NotNull Vector origin, double radius) {
return (MathHelper.square(origin.x - x) + MathHelper.square(origin.y - y) + MathHelper.square(origin.z - z)) <= MathHelper.square(radius);
}
public boolean isNormalized() {
return Math.abs(this.lengthSquared() - 1) < getEpsilon();
}
@NotNull
public Vector rotateAroundX(double angle) {
double angleCos = Math.cos(angle);
double angleSin = Math.sin(angle);
double y = angleCos * getY() - angleSin * getZ();
double z = angleSin * getY() + angleCos * getZ();
return setY(y).setZ(z);
}
@NotNull
public Vector rotateAroundY(double angle) {
double angleCos = Math.cos(angle);
double angleSin = Math.sin(angle);
double x = angleCos * getX() + angleSin * getZ();
double z = -angleSin * getX() + angleCos * getZ();
return setX(x).setZ(z);
}
@NotNull
public Vector rotateAroundZ(double angle) {
double angleCos = Math.cos(angle);
double angleSin = Math.sin(angle);
double x = angleCos * getX() - angleSin * getY();
double y = angleSin * getX() + angleCos * getY();
return setX(x).setY(y);
}
@NotNull
public Vector rotateAroundAxis(@NotNull Vector axis, double angle) throws IllegalArgumentException {
return rotateAroundNonUnitAxis(axis.isNormalized() ? axis : axis.clone().normalize(), angle);
}
@NotNull
public Vector rotateAroundNonUnitAxis(@NotNull Vector axis, double angle) throws IllegalArgumentException {
double x = getX();
double y = getY();
double z = getZ();
double x2 = axis.getX();
double y2 = axis.getY();
double z2 = axis.getZ();
double cosTheta = Math.cos(angle);
double sinTheta = Math.sin(angle);
double dotProduct = this.dot(axis);
double xPrime = x2 * dotProduct * (1d - cosTheta) + x * cosTheta + (-z2 * y + y2 * z) * sinTheta;
double yPrime = y2 * dotProduct * (1d - cosTheta) + y * cosTheta + (z2 * x - x2 * z) * sinTheta;
double zPrime = z2 * dotProduct * (1d - cosTheta) + z * cosTheta + (-y2 * x + x2 * y) * sinTheta;
return setX(xPrime).setY(yPrime).setZ(zPrime);
}
public double getX() {
return x;
}
@NotNull
public Vector setX(int x) {
this.x = x;
return this;
}
@NotNull
public Vector setX(double x) {
this.x = x;
return this;
}
@NotNull
public Vector setX(float x) {
this.x = x;
return this;
}
public int getBlockX() {
return MathHelper.floor(x);
}
public double getY() {
return y;
}
@NotNull
public Vector setY(int y) {
this.y = y;
return this;
}
@NotNull
public Vector setY(double y) {
this.y = y;
return this;
}
@NotNull
public Vector setY(float y) {
this.y = y;
return this;
}
public int getBlockY() {
return MathHelper.floor(y);
}
public double getZ() {
return z;
}
@NotNull
public Vector setZ(int z) {
this.z = z;
return this;
}
@NotNull
public Vector setZ(double z) {
this.z = z;
return this;
}
@NotNull
public Vector setZ(float z) {
this.z = z;
return this;
}
public int getBlockZ() {
return MathHelper.floor(z);
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Vector)) {
return false;
}
Vector other = (Vector) obj;
return Math.abs(x - other.x) < EPSILON && Math.abs(y - other.y) < EPSILON && Math.abs(z - other.z) < EPSILON && (this.getClass().equals(obj.getClass()));
}
@Override
public int hashCode() {
int hash = 7;
hash = 79 * hash + (int) (Double.doubleToLongBits(this.x) ^ (Double.doubleToLongBits(this.x) >>> 32));
hash = 79 * hash + (int) (Double.doubleToLongBits(this.y) ^ (Double.doubleToLongBits(this.y) >>> 32));
hash = 79 * hash + (int) (Double.doubleToLongBits(this.z) ^ (Double.doubleToLongBits(this.z) >>> 32));
return hash;
}
@NotNull
@Override
public Vector clone() {
try {
return (Vector) super.clone();
} catch (CloneNotSupportedException e) {
return new Vector(this.x, this.y, this.z); // pail
}
}
@Override
public String toString() {
return x + "," + y + "," + z;
}
@NotNull
public Location toLocation(float yaw, float pitch) {
return new Location(x, y, z, yaw, pitch);
}
}
|
sknebel/microformat-shiv | test/module-tests/text-test.js | /*
Unit test for text
*/
assert = chai.assert;
// Tests the private Modules.text object
// Modules.text is unit tested as it has an interface access by other modules
describe('Modules.text', function() {
it('parse', function(){
var html = '\n <a href="http://glennjones.net">Glenn\<NAME> \n</a> \n',
node = document.createElement('div');
node.innerHTML = html;
assert.equal( Modules.text.parse( document, node, 'whitespacetrimmed' ), '<NAME>' );
assert.equal( Modules.text.parse( document, node, 'whitespace' ), '\n Glenn\<NAME> \n \n' );
assert.equal( Modules.text.parse( document, node, 'normalised' ), '<NAME>' );
// exclude tags
node.innerHTML = '<script>test</script>text';
assert.equal( Modules.text.parse( document, node, 'normalised' ), 'text' );
// block level
node.innerHTML = '<p>test</p>text';
//assert.equal( Modules.text.parse( document, node, 'normalised' ), 'test text' );
// node with no text data
node = document.createComment('test comment');
assert.equal( Modules.text.parse( document, node, 'normalised' ), '' );
});
it('parseText', function(){
var text = '\n <a href="http://glennjones.net"><NAME> \n</a> \n';
// create DOM context first
Modules.domUtils.getDOMContext( {} );
assert.equal( Modules.text.parseText( document, text, 'whitespacetrimmed' ), '<NAME>' );
assert.equal( Modules.text.parseText( document, text, 'whitespace' ), '\n Glenn\<NAME> \n \n' );
assert.equal( Modules.text.parseText( document, text, 'normalised' ), 'Glenn Jones' );
});
it('formatText', function(){
assert.equal( Modules.text.formatText( document, null, 'whitespacetrimmed' ), '' );
});
}); |
immutabl3/store | src/utils/indexOfCompare.js | <reponame>immutabl3/store<gh_stars>1-10
import compare from './compare.js';
export default (arr, item) => {
let idx = 0;
const len = arr.length;
for (; idx < len; idx++) {
if (compare(arr[idx], item)) return idx;
}
return -1;
}; |
FuShaoLei/NewsProject | project-server/src/main/java/com/fushaolei/server/controller/CommentController.java | package com.fushaolei.server.controller;
import com.alibaba.fastjson.JSON;
import com.fushaolei.server.bean.BaseResponse;
import com.fushaolei.server.bean.Comment;
import com.fushaolei.server.bean.InsertComment;
import com.fushaolei.server.constant.HttpConstant;
import com.fushaolei.server.dao.CommentsDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* 评论controller
*/
@RestController
@RequestMapping("/comments")
public class CommentController {
@Autowired
CommentsDao commentsDao;
/**
* 根据新闻id来获取评论信息
*/
@GetMapping("/{id}")
public String getComments(@PathVariable(name = "id") int id) {
BaseResponse<List<Comment>> baseResponse = new BaseResponse<>();
List<Comment> comments = commentsDao.getList(id);
if (comments != null && comments.size() > 0) {
baseResponse.setCode(HttpConstant.SUCCESS_CODE);
baseResponse.setData(comments);
}
return JSON.toJSONString(baseResponse);
}
/**
* 插入评论
*/
@PostMapping("/")
public String insertComment(@RequestBody InsertComment insertComment) {
BaseResponse<Integer> baseResponse = new BaseResponse<>();
int i = commentsDao.insertComment(insertComment);
if (i != 0) {
baseResponse.setCode(HttpConstant.SUCCESS_CODE);
baseResponse.setData(insertComment.getId());
}
return JSON.toJSONString(baseResponse);
}
}
|
iamzken/aliyun-openapi-cpp-sdk | vs/src/model/BatchForbidVsStreamResult.cc | <reponame>iamzken/aliyun-openapi-cpp-sdk<filename>vs/src/model/BatchForbidVsStreamResult.cc<gh_stars>10-100
/*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/vs/model/BatchForbidVsStreamResult.h>
#include <json/json.h>
using namespace AlibabaCloud::Vs;
using namespace AlibabaCloud::Vs::Model;
BatchForbidVsStreamResult::BatchForbidVsStreamResult() :
ServiceResult()
{}
BatchForbidVsStreamResult::BatchForbidVsStreamResult(const std::string &payload) :
ServiceResult()
{
parse(payload);
}
BatchForbidVsStreamResult::~BatchForbidVsStreamResult()
{}
void BatchForbidVsStreamResult::parse(const std::string &payload)
{
Json::Reader reader;
Json::Value value;
reader.parse(payload, value);
setRequestId(value["RequestId"].asString());
auto allForbidResultNode = value["ForbidResult"]["ForbidResultInfo"];
for (auto valueForbidResultForbidResultInfo : allForbidResultNode)
{
ForbidResultInfo forbidResultObject;
if(!valueForbidResultForbidResultInfo["Result"].isNull())
forbidResultObject.result = valueForbidResultForbidResultInfo["Result"].asString();
if(!valueForbidResultForbidResultInfo["Detail"].isNull())
forbidResultObject.detail = valueForbidResultForbidResultInfo["Detail"].asString();
if(!valueForbidResultForbidResultInfo["Count"].isNull())
forbidResultObject.count = std::stoi(valueForbidResultForbidResultInfo["Count"].asString());
auto allChannels = value["Channels"]["Channel"];
for (auto value : allChannels)
forbidResultObject.channels.push_back(value.asString());
forbidResult_.push_back(forbidResultObject);
}
}
std::vector<BatchForbidVsStreamResult::ForbidResultInfo> BatchForbidVsStreamResult::getForbidResult()const
{
return forbidResult_;
}
|
top/octopus | core/service/model/response/response.go | package response
import (
"net/http"
"octopus/core/global"
"github.com/gin-gonic/gin"
)
type Response struct {
Code int `json:"code"`
Data interface{} `json:"data,omitempty"`
Msg string `json:"msg"`
}
func Result(code int, data interface{}, msg string, c *gin.Context) {
c.JSON(http.StatusOK, Response{Code: code, Data: data, Msg: msg})
}
func OK(c *gin.Context) {
Result(global.SUCCESS_CODE, nil, global.SUCCESS_MESSAGE, c)
}
func OKMessage(msg string, c *gin.Context) {
Result(global.SUCCESS_CODE, nil, msg, c)
}
func OKData(data interface{}, c *gin.Context) {
Result(global.SUCCESS_CODE, data, global.SUCCESS_MESSAGE, c)
}
func OKResult(data interface{}, msg string, c *gin.Context) {
Result(global.SUCCESS_CODE, data, msg, c)
}
func Fail(code int, c *gin.Context) {
Result(code, nil, global.FAIL_MESSAGE, c)
}
func FailMessage(code int, msg string, c *gin.Context) {
Result(code, nil, msg, c)
}
func FailDetail(code int, data interface{}, msg string, c *gin.Context) {
Result(code, data, msg, c)
}
|
nick-nack-attack/utahexpungements.org | frontend/app/forms/special-bci/special-bci.pdf.component.js | <filename>frontend/app/forms/special-bci/special-bci.pdf.component.js
import React from "react";
import RenderPage from "../render-page.component";
import PositionedString from "../pdf-rendering/positioned-string.component";
import PositionedCheckmark from "../pdf-rendering/positioned-checkmark.component";
import {
getCounty,
getJudicialDistrict
} from "../form-common-options/form-common-options";
const farLeft = "11.28%";
const petitionerCheckboxLeft = "20.75%";
const attorneyTop = "33.00%";
const courtTypeTop = "36.4%";
const courtDistrictTop = "39.30%";
const caseInformationLeft = "54.00%";
export default function SpecialBci_Pdf({ data, renderData }) {
const firstPageUrl =
"/static/forms/special-bci/01_Petition_to_Expunge_Records_Criminal-special_certificate-1.png";
const secondPageUrl =
"/static/forms/special-bci/01_Petition_to_Expunge_Records_Criminal-special_certificate-2.png";
const thirdPageUrl =
"/static/forms/special-bci/01_Petition_to_Expunge_Records_Criminal-special_certificate-3.png";
return (
<>
<RenderPage url={firstPageUrl}>
{/* Personal Information */}
<PositionedString debugKey="fullName" left={farLeft} top="14.06%">
{`${renderData("person.firstName")} ${renderData(
"person.middleName"
)} ${renderData("person.lastName")}`}
</PositionedString>
<PositionedString
dataKey="person.addressStreet"
left={farLeft}
top="17.46%"
/>
<PositionedString
debugKey="addressStreetCityZip"
left={farLeft}
top="20.86%"
>
{`${renderData("person.addressCity")}, ${renderData(
"person.addressState"
)} ${renderData("person.addressZip")}`}
</PositionedString>
<PositionedString
dataKey="person.homePhone"
left={farLeft}
top="24.26%"
/>
<PositionedString dataKey="person.email" left={farLeft} top="28.16%" />
{/* Petitioner information */}
<PositionedCheckmark
debugKey="petitionerRepresentation"
left={petitionerCheckboxLeft}
top="31.50%"
shouldShow={data.person.petitionerRepresentative === "petitioner"}
/>
<PositionedCheckmark
debugKey="attorneyRepresentation"
left={petitionerCheckboxLeft}
top={attorneyTop}
shouldShow={data.person.petitionerRepresentative === "attorney"}
/>
<PositionedString
dataKey="person.petitionerBarNumber"
left="62.00%"
top={attorneyTop}
/>
{/* Case information */}
<PositionedCheckmark
debugKey="districtCourtType"
left="37.65%"
top={courtTypeTop}
shouldShow={data.case.courtType === "District"}
/>
<PositionedCheckmark
debugKey="justiceCourtType"
left="47.8%"
top={courtTypeTop}
shouldShow={data.case.courtType === "Justice"}
/>
<PositionedString
debugKey="courtDistrict"
left="25.9%"
top={courtDistrictTop}
>
{data.case.courtAddress &&
getJudicialDistrict(data.case.courtAddress, data.case.courtType)}
</PositionedString>
<PositionedString
debugKey="courtCounty"
left="52.00%"
top={courtDistrictTop}
>
{data.case.courtAddress &&
getCounty(data.case.courtAddress, data.case.courtType)}
</PositionedString>
<PositionedString
dataKey="case.courtAddress"
left="27.8%"
top="42.50%"
/>
<PositionedString
debugKey="petitionerFullName"
left="12.8%"
top="51.5%"
>
{`${renderData("person.firstName")} ${renderData(
"person.middleName"
)} ${renderData("person.lastName")}`}
</PositionedString>
<PositionedString
dataKey="case.caseNumber"
left={caseInformationLeft}
top="51.5%"
/>
<PositionedString
dataKey="case.judgeName"
left={caseInformationLeft}
top="56.5%"
/>
{/* Records of crimes without conviction */}
<PositionedCheckmark
debugKey="hasNoConviction"
left="18%"
top="68.6%"
shouldShow={data.case.hasConviction === "No"}
/>
{data.case.hasConviction === "No" && (
<>
<PositionedString
dataKey="case.arrestedDate"
left="39.5%"
top="70.8%"
/>
<PositionedString
dataKey="case.leaName"
left="19.0%"
top="73.6%"
shouldShow={data.case.hasConviction === "No"}
/>
<PositionedString
dataKey="case.leaFileNumber"
left="50%"
top="76%"
shouldShow={data.case.hasConviction === "No"}
/>
</>
)}
<PositionedCheckmark
debugKey="wasFiled"
left="23.8%"
top="83%"
shouldShow={
data.case.wasFiled === "Yes" && data.case.hasConviction === "No"
}
/>
{data.case.wasFiled === "Yes" && data.case.hasConviction === "No" && (
<PositionedString
dataKey="case.caseNumber"
left="23.8%"
top="85.4%"
/>
)}
</RenderPage>
<RenderPage url={secondPageUrl}>
{/* Records of crimes without conviction continued */}
<PositionedCheckmark
debugKey="wasNotFiled"
left="23.8%"
top="13.5%"
shouldShow={
data.case.wasFiled === "No" && data.case.hasConviction === "No"
}
/>
<PositionedCheckmark
debugKey="hasNoConviction"
left="23.8%"
top="20.7%"
shouldShow={data.case.hasConviction === "No"}
/>
<PositionedCheckmark
dataKey="case.thirtyDaysPassed"
left="23.8%"
top="23.2%"
shouldShow={data.case.hasConviction === "No"}
/>
<PositionedCheckmark
dataKey="case.noArrestsSinceLast"
left="23.8%"
top="25.7%"
shouldShow={data.case.hasConviction === "No"}
/>
<PositionedCheckmark
debugKey="oneOfTheFollowingOccurred"
left="23.8%"
top="28.2%"
// if any of the options of the radio button are checked, this checkmark should show
shouldShow={
Boolean(data.case.chargeResolution) &&
data.case.hasConviction === "No"
}
/>
<PositionedCheckmark
debugKey="noChargeFiled"
left="29.7%"
top="30.7%"
shouldShow={
data.case.chargeResolution === "noChargeFiled" &&
data.case.hasConviction === "No"
}
/>
<PositionedCheckmark
debugKey="withPrejudice"
left="29.7%"
top="33.2%"
shouldShow={
data.case.chargeResolution === "withPrejudice" &&
data.case.hasConviction === "No"
}
/>
<PositionedCheckmark
debugKey="atTrial"
left="29.7%"
top="37.5%"
shouldShow={
data.case.chargeResolution === "atTrial" &&
data.case.hasConviction === "No"
}
/>
{/* Records of crime with conviction */}
<PositionedCheckmark
debugKey="hasConviction"
left="18.0%"
top="41.5%"
shouldShow={data.case.hasConviction === "Yes"}
/>
{/* Check with Tucker that this is the same case number */}
{data.case.hasConviction === "Yes" && (
<>
<PositionedString
dataKey="case.caseNumber"
left="70%"
top="44.7%"
/>
<PositionedCheckmark
dataKey="case.wasNotSevereCrime"
left="23.8%"
top="49.7%"
/>
<PositionedCheckmark
dataKey="case.noCriminalCasePending"
left="23.8%"
top="62.3%"
/>
<PositionedCheckmark
dataKey="case.notConvictedOfCriminalEpisodes"
left="23.8%"
top="67.2%"
/>
<PositionedCheckmark
dataKey="case.hasPaidFines"
left="23.8%"
top="79.8%"
/>
<PositionedCheckmark
dataKey="case.timePeriodsHaveElapsed"
left="23.8%"
top="83.1%"
/>
</>
)}
</RenderPage>
<RenderPage url={thirdPageUrl}>
{/* BCI Certificate */}
<PositionedString
dataKey="case.bciEligibilityCause"
left="18.28%"
top="32.4%"
style={{
width: "71%",
overflowWrap: "anywhere",
lineHeight: "29px"
}}
/>
{/* Public Interest Cause */}
<PositionedString
dataKey="case.publicInterestCause"
left="18.28%"
top="48%"
style={{
width: "71%",
overflowWrap: "anywhere",
lineHeight: "29px"
}}
/>
</RenderPage>
</>
);
}
|
acidicMercury8/xray-1.0 | sdk/boost_1_30_0/libs/math/special_functions/sinhc_test.hpp | <filename>sdk/boost_1_30_0/libs/math/special_functions/sinhc_test.hpp
// unit test file sinhc.hpp for the special functions test suite
// (C) Copyright <NAME> 2003. Permission to copy, use, modify, sell and
// distribute this software is granted provided this copyright notice appears
// in all copies. This software is provided "as is" without express or implied
// warranty, and with no claim as to its suitability for any purpose.
#include <functional>
#include <iomanip>
#include <iostream>
#include <complex>
#include <boost/math/special_functions/sinhc.hpp>
#include <boost/test/unit_test.hpp>
template<typename T>
void sinhc_pi_test(const char * more_blurb)
{
using ::std::abs;
using ::std::numeric_limits;
using ::boost::math::sinhc_pi;
BOOST_MESSAGE("Testing sinhc_pi in the real domain for "
<< more_blurb << ".");
BOOST_CHECK_PREDICATE(::std::less_equal<T>(), 2,
(
abs(sinhc_pi<T>(static_cast<T>(0))-static_cast<T>(1)),
numeric_limits<T>::epsilon()
));
}
template<typename T>
void sinhc_pi_complex_test(const char * more_blurb)
{
using ::std::abs;
using ::std::sin;
using ::std::numeric_limits;
using ::boost::math::sinhc_pi;
BOOST_MESSAGE("Testing sinhc_pi in the complex domain for "
<< more_blurb << ".");
BOOST_CHECK_PREDICATE(::std::less_equal<T>(), 2,
(
abs(sinhc_pi<T>(::std::complex<T>(0, 1))-
::std::complex<T>(sin(static_cast<T>(1)))),
numeric_limits<T>::epsilon()
));
}
void sinhc_pi_manual_check()
{
using ::boost::math::sinhc_pi;
BOOST_MESSAGE("sinc_pi");
for (int i = 0; i <= 100; i++)
{
BOOST_MESSAGE( ::std::setw(15)
<< sinhc_pi<float>(static_cast<float>(i-50)/
static_cast<float>(50))
<< ::std::setw(15)
<< sinhc_pi<double>(static_cast<double>(i-50)/
static_cast<double>(50))
<< ::std::setw(15)
<< sinhc_pi<long double>(static_cast<long double>(i-50)/
static_cast<long double>(50)));
}
BOOST_MESSAGE(" ");
}
|
vaginessa/irma | common/tests/__init__.py | import sys
import os
pardir = os.path.abspath(os.path.join(__file__, os.path.pardir))
sys.path.append(os.path.dirname(pardir))
|
sufrin/ThreadCSO | src/io/threadcso/lock/AndBarrier.scala | package io.threadcso.lock
/** A `CombiningBarrier` with `e=true` and `op=_&&_` */
class AndBarrier(n: Int, name: String="AndBarrier") extends CombiningBarrier[Boolean](n, true, _ && _, name)
|
trngaje/mame-2003-plus-kaze | src/libretro-common/audio/dsp_filters/echo.c | /* Copyright (C) 2010-2020 The RetroArch team
*
* ---------------------------------------------------------------------------------------
* The following license statement only applies to this file (echo.c).
* ---------------------------------------------------------------------------------------
*
* Permission is hereby granted, free of charge,
* to any person obtaining a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <stdlib.h>
#include <retro_miscellaneous.h>
#include <libretro_dspfilter.h>
struct echo_channel
{
float *buffer;
unsigned ptr;
unsigned frames;
float feedback;
};
struct echo_data
{
struct echo_channel *channels;
unsigned num_channels;
float amp;
};
static void echo_free(void *data)
{
unsigned i;
struct echo_data *echo = (struct echo_data*)data;
for (i = 0; i < echo->num_channels; i++)
free(echo->channels[i].buffer);
free(echo->channels);
free(echo);
}
static void echo_process(void *data, struct dspfilter_output *output,
const struct dspfilter_input *input)
{
unsigned i, c;
float *out = NULL;
struct echo_data *echo = (struct echo_data*)data;
output->samples = input->samples;
output->frames = input->frames;
out = output->samples;
for (i = 0; i < input->frames; i++, out += 2)
{
float left, right;
float echo_left = 0.0f;
float echo_right = 0.0f;
for (c = 0; c < echo->num_channels; c++)
{
echo_left += echo->channels[c].buffer[(echo->channels[c].ptr << 1) + 0];
echo_right += echo->channels[c].buffer[(echo->channels[c].ptr << 1) + 1];
}
echo_left *= echo->amp;
echo_right *= echo->amp;
left = out[0] + echo_left;
right = out[1] + echo_right;
for (c = 0; c < echo->num_channels; c++)
{
float feedback_left = out[0] + echo->channels[c].feedback * echo_left;
float feedback_right = out[1] + echo->channels[c].feedback * echo_right;
echo->channels[c].buffer[(echo->channels[c].ptr << 1) + 0] = feedback_left;
echo->channels[c].buffer[(echo->channels[c].ptr << 1) + 1] = feedback_right;
echo->channels[c].ptr = (echo->channels[c].ptr + 1) % echo->channels[c].frames;
}
out[0] = left;
out[1] = right;
}
}
static void *echo_init(const struct dspfilter_info *info,
const struct dspfilter_config *config, void *userdata)
{
unsigned i, channels;
struct echo_channel *echo_channels = NULL;
float *delay = NULL;
float *feedback = NULL;
unsigned num_delay = 0;
unsigned num_feedback = 0;
static const float default_delay[] = { 200.0f };
static const float default_feedback[] = { 0.5f };
struct echo_data *echo = (struct echo_data*)
calloc(1, sizeof(*echo));
if (!echo)
return NULL;
config->get_float_array(userdata, "delay", &delay,
&num_delay, default_delay, 1);
config->get_float_array(userdata, "feedback", &feedback,
&num_feedback, default_feedback, 1);
config->get_float(userdata, "amp", &echo->amp, 0.2f);
channels = num_feedback = num_delay = MIN(num_delay, num_feedback);
echo_channels = (struct echo_channel*)calloc(channels,
sizeof(*echo_channels));
if (!echo_channels)
goto error;
echo->channels = echo_channels;
echo->num_channels = channels;
for (i = 0; i < channels; i++)
{
unsigned frames = (unsigned)(delay[i] * info->input_rate / 1000.0f + 0.5f);
if (!frames)
goto error;
echo->channels[i].buffer = (float*)calloc(frames, 2 * sizeof(float));
if (!echo->channels[i].buffer)
goto error;
echo->channels[i].frames = frames;
echo->channels[i].feedback = feedback[i];
}
config->free(delay);
config->free(feedback);
return echo;
error:
config->free(delay);
config->free(feedback);
echo_free(echo);
return NULL;
}
static const struct dspfilter_implementation echo_plug = {
echo_init,
echo_process,
echo_free,
DSPFILTER_API_VERSION,
"Multi-Echo",
"echo",
};
#ifdef HAVE_FILTERS_BUILTIN
#define dspfilter_get_implementation echo_dspfilter_get_implementation
#endif
const struct dspfilter_implementation *dspfilter_get_implementation(dspfilter_simd_mask_t mask)
{
(void)mask;
return &echo_plug;
}
#undef dspfilter_get_implementation
|
tyekx/netcode | NetcodeAssetEditor/BonesPage.h | <filename>NetcodeAssetEditor/BonesPage.h<gh_stars>0
#pragma once
#include "BonesPage.g.h"
#include "DepthToMarginConverter.h"
namespace winrt::NetcodeAssetEditor::implementation
{
struct BonesPage : BonesPageT<BonesPage>
{
bool firstNavigation;
BonesPage();
void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const & e);
void bonesList_SelectionChanged(winrt::Windows::Foundation::IInspectable const & sender, winrt::Windows::UI::Xaml::Controls::SelectionChangedEventArgs const & e);
};
}
namespace winrt::NetcodeAssetEditor::factory_implementation
{
struct BonesPage : BonesPageT<BonesPage, implementation::BonesPage>
{
};
}
|
IlyaKozlov/dedoc | dedoc/data_structures/annotation.py | <reponame>IlyaKozlov/dedoc
from collections import OrderedDict
from flask_restx import Api, Model, fields
from dedoc.data_structures.serializable import Serializable
class Annotation(Serializable):
def __init__(self, start: int, end: int, name: str, value: str) -> None:
"""
Some kind of text information about symbols between start and end.
For example Annotation(1, 13, "italic", "True")
says that text between 1st and 13st symbol was writen in italic
:param start: annotated text start
:param end: annotated text end
:param name: annotation's name
:param value: information about annotated text
"""
self.start = start
self.end = end
self.name = name
self.value = value
def __eq__(self, o: object) -> bool:
if not isinstance(o, Annotation):
return False
return self.name == o.name and self.value == o.value and self.start == o.start and self.end == o.end
def __str__(self) -> str:
return "{name}({start}:{end}, {value})".format(name=self.name.capitalize(),
start=self.start,
end=self.end,
value=self.value)
def __repr__(self) -> str:
return "{name}(...)".format(name=self.name.capitalize())
def to_dict(self, old_version: bool) -> dict:
res = OrderedDict()
res["start"] = self.start
res["end"] = self.end
if old_version:
res["value"] = self.name + ":" + self.value
else:
res["name"] = self.name
res["value"] = self.value
return res
@staticmethod
def get_api_dict(api: Api) -> Model:
names = ["style", "bold", "italic", "underlined", "size", "indentation", "alignment", "table",
"attachment", "spacing", "strike", "subscript", "superscript"]
return api.model('Annotation', {
'start': fields.Integer(description='annotation start index', required=True, example=0),
'end': fields.Integer(description='annotation end index', required=True, example=4),
'name': fields.String(description='annotation name', required=True, example='bold',
enum=names),
'value': fields.String(description='annotation value. For example, it may be font size value for size type '
'or type of alignment for alignment type',
required=True,
example="left")
})
|
s3valkov/JavaBasic | 05.SimpleLoops/src/LeftRightSum.java | <reponame>s3valkov/JavaBasic<filename>05.SimpleLoops/src/LeftRightSum.java
import java.util.Scanner;
public class LeftRightSum {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = Integer.parseInt(scanner.nextLine());
int leftSum = 0 ;
int rightSum = 0;
for (int i = 0; i < n ; i++) {
int leftNums = Integer.parseInt(scanner.nextLine());
leftSum += leftNums ;
}
for (int k = 0; k < n ; k++) {
int rightNums = Integer.parseInt(scanner.nextLine());
rightSum += rightNums;
}
if (leftSum == rightSum) {
System.out.println("Yes, sum = " +leftSum);
}
else {
int diff = Math.max(leftSum,rightSum) - Math.min(leftSum,rightSum);
System.out.println("No, diff = " +diff);
}
}
}
|
girishcx/one | src/fireedge/src/client/features/One/host/services.js | /* ------------------------------------------------------------------------- *
* Copyright 2002-2021, OpenNebula Project, OpenNebula Systems *
* *
* 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. *
* ------------------------------------------------------------------------- */
import { Actions, Commands } from 'server/utils/constants/commands/host'
import { httpCodes } from 'server/utils/constants'
import { requestConfig, RestClient } from 'client/utils'
export const hostService = {
/**
* Retrieves information for the host.
*
* @param {object} data - Request parameters
* @param {string} data.id - Host id
* @returns {object} Get host identified by id
* @throws Fails when response isn't code 200
*/
getHost: async ({ id }) => {
const name = Actions.HOST_INFO
const command = { name, ...Commands[name] }
const config = requestConfig({ id }, command)
const res = await RestClient.request(config)
if (!res?.id || res?.id !== httpCodes.ok.id) throw res
return res?.data?.HOST ?? {}
},
/**
* Retrieves information for all the hosts in the pool.
*
* @returns {object} Get list of hosts
* @throws Fails when response isn't code 200
*/
getHosts: async () => {
const name = Actions.HOST_POOL_INFO
const command = { name, ...Commands[name] }
const config = requestConfig(undefined, command)
const res = await RestClient.request(config)
if (!res?.id || res?.id !== httpCodes.ok.id) throw res
return [res?.data?.HOST_POOL?.HOST ?? []].flat()
},
/**
* Allocates a new host in OpenNebula.
*
* @param {object} params - Request params
* @param {string} params.hostname - Hostname of the machine we want to add
* @param {string} params.imMad
* - The name of the information manager (im_mad_name),
* this values are taken from the oned.conf with the tag name IM_MAD (name)
* @param {string} params.vmmMad
* - The name of the virtual machine manager mad name (vmm_mad_name),
* this values are taken from the oned.conf with the tag name VM_MAD (name)
* @param {string|number} [params.cluster] - The cluster ID
* @returns {number} Host id
* @throws Fails when response isn't code 200
*/
allocate: async (params) => {
const name = Actions.HOST_ALLOCATE
const command = { name, ...Commands[name] }
const config = requestConfig(params, command)
const res = await RestClient.request(config)
if (!res?.id || res?.id !== httpCodes.ok.id) throw res
return res?.data
},
/**
* Deletes the given host from the pool.
*
* @param {object} params - Request params
* @param {number|string} params.id - Host id
* @returns {number} Host id
* @throws Fails when response isn't code 200
*/
delete: async (params) => {
const name = Actions.HOST_DELETE
const command = { name, ...Commands[name] }
const config = requestConfig(params, command)
const res = await RestClient.request(config)
if (!res?.id || res?.id !== httpCodes.ok.id) throw res
return res?.data
},
/**
* Sets the status of the host to enabled.
*
* @param {object} params - Request params
* @param {number|string} params.id - Host id
* @returns {number} Host id
* @throws Fails when response isn't code 200
*/
enable: async (params) => {
const name = Actions.HOST_STATUS
const command = { name, ...Commands[name] }
const config = requestConfig({ ...params, status: 0 }, command)
const res = await RestClient.request(config)
if (!res?.id || res?.id !== httpCodes.ok.id) throw res
return res?.data
},
/**
* Sets the status of the host to disabled.
*
* @param {object} params - Request params
* @param {number|string} params.id - Host id
* @returns {number} Host id
* @throws Fails when response isn't code 200
*/
disable: async (params) => {
const name = Actions.HOST_STATUS
const command = { name, ...Commands[name] }
const config = requestConfig({ ...params, status: 1 }, command)
const res = await RestClient.request(config)
if (!res?.id || res?.id !== httpCodes.ok.id) throw res
return res?.data
},
/**
* Sets the status of the host to offline.
*
* @param {object} params - Request params
* @param {number|string} params.id - Host id
* @returns {number} Host id
* @throws Fails when response isn't code 200
*/
offline: async (params) => {
const name = Actions.HOST_STATUS
const command = { name, ...Commands[name] }
const config = requestConfig({ ...params, status: 2 }, command)
const res = await RestClient.request(config)
if (!res?.id || res?.id !== httpCodes.ok.id) throw res
return res?.data
},
/**
* Replaces the host’s template contents..
*
* @param {object} params - Request params
* @param {number|string} params.id - Host id
* @param {string} params.template - The new template contents
* @param {0|1} params.replace
* - Update type:
* ``0``: Replace the whole template.
* ``1``: Merge new template with the existing one.
* @returns {number} Host id
* @throws Fails when response isn't code 200
*/
update: async (params) => {
const name = Actions.HOST_UPDATE
const command = { name, ...Commands[name] }
const config = requestConfig(params, command)
const res = await RestClient.request(config)
if (!res?.id || res?.id !== httpCodes.ok.id) throw res
return res?.data
},
/**
* Renames a host.
*
* @param {object} params - Request parameters
* @param {string|number} params.id - Host id
* @param {string} params.name - New name
* @returns {number} Host id
* @throws Fails when response isn't code 200
*/
rename: async (params) => {
const name = Actions.HOST_RENAME
const command = { name, ...Commands[name] }
const config = requestConfig(params, command)
const res = await RestClient.request(config)
if (!res?.id || res?.id !== httpCodes.ok.id) throw res?.data
return res?.data
},
/**
* Returns the host monitoring records.
*
* @param {object} params - Request parameters
* @param {string|number} params.id - Host id
* @returns {string} The monitoring information string / The error string
* @throws Fails when response isn't code 200
*/
monitoring: async (params) => {
const name = Actions.HOST_MONITORING
const command = { name, ...Commands[name] }
const config = requestConfig(params, command)
const res = await RestClient.request(config)
if (!res?.id || res?.id !== httpCodes.ok.id) throw res?.data
return res?.data
},
/**
* Returns all the host monitoring records.
*
* @param {object} params - Request parameters
* @param {string|number} [params.seconds]
* - Retrieve monitor records in the last num seconds.
* ``0``: Only the last record.
* ``-1``: All records.
* @returns {string} The monitoring information string / The error string
* @throws Fails when response isn't code 200
*/
monitoringPool: async (params) => {
const name = Actions.HOST_POOL_MONITORING
const command = { name, ...Commands[name] }
const config = requestConfig(params, command)
const res = await RestClient.request(config)
if (!res?.id || res?.id !== httpCodes.ok.id) throw res?.data
return res?.data
},
}
|
Anbang713/mini-mall | mall-sales/mall-sales-provider/src/main/java/com/autumn/mall/sales/controller/PaymentTypeController.java | <reponame>Anbang713/mini-mall<filename>mall-sales/mall-sales-provider/src/main/java/com/autumn/mall/sales/controller/PaymentTypeController.java
/**
* 版权所有 (C), 2019-2020, XXX有限公司
* 项目名:com.autumn.mall.sales.controller
* 文件名: PaymentTypeController
* 日期: 2020/3/15 16:50
* 说明:
*/
package com.autumn.mall.sales.controller;
import com.autumn.mall.commons.controller.AbstractSupportStateController;
import com.autumn.mall.commons.model.UsingState;
import com.autumn.mall.commons.service.CrudService;
import com.autumn.mall.commons.service.SupportStateService;
import com.autumn.mall.sales.client.PaymentTypeApi;
import com.autumn.mall.sales.model.PaymentType;
import com.autumn.mall.sales.service.PaymentTypeService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Arrays;
import java.util.List;
/**
* @author Anbang713
* @create 2020/3/15
*/
@Api(value = "付款方式管理")
@RestController
@RequestMapping("/paymenttype")
public class PaymentTypeController extends AbstractSupportStateController<PaymentType, UsingState> implements PaymentTypeApi {
@Autowired
private PaymentTypeService paymentTypeService;
@Override
public SupportStateService<UsingState> getSupportStateService() {
return paymentTypeService;
}
@Override
public CrudService<PaymentType> getCrudService() {
return paymentTypeService;
}
@Override
public List<String> getSummaryFields() {
return Arrays.asList(UsingState.using.name(), UsingState.disabled.name());
}
} |
Junhua91/tornesol | algo-study/src/main/java/com/junhua/algorithm/leetcode/datastructure/bit/PowerOfTwo.java | <filename>algo-study/src/main/java/com/junhua/algorithm/leetcode/datastructure/bit/PowerOfTwo.java<gh_stars>1-10
package com.junhua.algorithm.leetcode.datastructure.bit;
/**
* leetCode 231
*/
public class PowerOfTwo {
public static void main(String[] args) {
System.out.println(isPowerOf2(4));
System.out.println(isPowerOf2(5));
System.out.println(isPowerOf2(8));
System.out.println(isPowerOf2(17));
}
/**
* 2=> 0010
* 4=> 0100
* 8=> 1000
* ... 所有2的平方数,都只有一个1,于是去除一个1,看剩下的数是否为0
*
* @param n
* @return
*/
public static boolean isPowerOf2(int n) {
return n > 0 && ((n & (n - 1)) == 0);
}
}
|
PedroPadilhaPortella/Curso_Desenvolvimento_Web_JavaScript | JavaScript/Funções/ParametrosPadrão.js | <filename>JavaScript/Funções/ParametrosPadrão.js<gh_stars>1-10
//Primeio Método para gerar um valor padrão
function product01(a, b, c){
a = a || 1;
b = b || 1;
c = c || 1;
return a * b * c
}
console.log(product01(), product01(3), product01(2, 3, 4), product01(0, 0, 0))
//Métodos usando operadores ternários ou IF-ELSE
function product02 (a, b, c){
a = a !== undefined ? a : 1
b = 1 in arguments ? b : 1
c = isNaN(c) ? 1 : c //método mais seguro dentre estes
return a * b * c
}
console.log(product02(), product02(3), product02(2, 3, 4), product02(0, 0, 0))
//Parametro Padrão ES06
function product03 (a = 1, b = 1, c = 1){
return a * b * c
}
console.log(product03(), product03(3), product03(2, 3, 4), product03(0, 0, 0)) |
naxadeve/MNE-Android | collect_app/src/main/java/org/odk/collect/android/mne/forms/PraticalActionForm.java | package org.odk.collect.android.mne.forms;
import android.arch.persistence.room.Entity;
import android.arch.persistence.room.PrimaryKey;
@Entity(tableName = "practical_action_forms")
public class PraticalActionForm {
private String beneficiaryId;
private String activityId;
private String instanceId;
public PraticalActionForm(String beneficiaryId, String activityId, String instanceId) {
this.beneficiaryId = beneficiaryId;
this.activityId = activityId;
this.instanceId = instanceId;
}
@PrimaryKey(autoGenerate = true)
private int id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getBeneficiaryId() {
return beneficiaryId;
}
public String getActivityId() {
return activityId;
}
public String getInstanceId() {
return instanceId;
}
}
|
qinFamily/freeVM | enhanced/archive/classlib/java6/modules/awt/src/main/java/common/org/apache/harmony/awt/gl/image/ImageDecoder.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.
*/
/**
* @author <NAME>
* @version $Revision$
*/
/*
* Created on 18.01.2005
*/
package org.apache.harmony.awt.gl.image;
import java.awt.image.ColorModel;
import java.awt.image.ImageConsumer;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.ConcurrentModificationException;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
/**
* This class contains common functionality for all image decoders.
*/
abstract class ImageDecoder {
private static final int MAX_BYTES_IN_SIGNATURE = 8;
List<ImageConsumer> consumers;
InputStream inputStream;
DecodingImageSource src;
boolean terminated;
/**
* Chooses appropriate image decoder by looking into input stream and checking
* the image signature.
* @param src - image producer, required for passing data to it from the
* created decoder via callbacks
* @param is - stream
* @return decoder
*/
static ImageDecoder createDecoder(DecodingImageSource src, InputStream is) {
InputStream markable;
if (!is.markSupported()) {
markable = new BufferedInputStream(is);
} else {
markable = is;
}
// Read the signature from the stream and then reset it back
try {
markable.mark(MAX_BYTES_IN_SIGNATURE);
byte[] signature = new byte[MAX_BYTES_IN_SIGNATURE];
markable.read(signature, 0, MAX_BYTES_IN_SIGNATURE);
markable.reset();
if ((signature[0] & 0xFF) == 0xFF &&
(signature[1] & 0xFF) == 0xD8 &&
(signature[2] & 0xFF) == 0xFF) { // JPEG
return new JpegDecoder(src, is);
} else if ((signature[0] & 0xFF) == 0x47 && // G
(signature[1] & 0xFF) == 0x49 && // I
(signature[2] & 0xFF) == 0x46) { // F
return new GifDecoder(src, is);
} else if ((signature[0] & 0xFF) == 137 && // PNG signature: 137 80 78 71 13 10 26 10
(signature[1] & 0xFF) == 80 &&
(signature[2] & 0xFF) == 78 &&
(signature[3] & 0xFF) == 71 &&
(signature[4] & 0xFF) == 13 &&
(signature[5] & 0xFF) == 10 &&
(signature[6] & 0xFF) == 26 &&
(signature[7] & 0xFF) == 10) {
return new PngDecoder(src, is);
}
} catch (IOException e) { // Silently
}
return null;
}
ImageDecoder(DecodingImageSource _src, InputStream is) {
src = _src;
consumers = src.consumers;
inputStream = is;
}
public abstract void decodeImage() throws IOException;
public synchronized void closeStream() {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
}
}
}
/**
* Stops the decoding by interrupting the current decoding thread.
* Used when all consumers are removed and there's no more need to
* run the decoder.
*/
public void terminate() {
src.lockDecoder(this);
closeStream();
AccessController.doPrivileged(
new PrivilegedAction<Void>() {
public Void run() {
Thread.currentThread().interrupt();
return null;
}
}
);
terminated = true;
}
protected void setDimensions(int w, int h) {
if (terminated) {
return;
}
for (ImageConsumer ic : consumers) {
ic.setDimensions(w, h);
}
}
protected void setProperties(Hashtable<?, ?> props) {
if (terminated) {
return;
}
for (ImageConsumer ic : consumers) {
ic.setProperties(props);
}
}
protected void setColorModel(ColorModel cm) {
if (terminated) {
return;
}
for (ImageConsumer ic : consumers) {
ic.setColorModel(cm);
}
}
protected void setHints(int hints) {
if (terminated) {
return;
}
for (ImageConsumer ic : consumers) {
ic.setHints(hints);
}
}
protected void setPixels(
int x, int y,
int w, int h,
ColorModel model,
byte pix[],
int off, int scansize
) {
if (terminated) {
return;
}
src.lockDecoder(this);
for (ImageConsumer ic : consumers) {
ic.setPixels(x, y, w, h, model, pix, off, scansize);
}
}
protected void setPixels(
int x, int y,
int w, int h,
ColorModel model,
int pix[],
int off, int scansize
) {
if (terminated) {
return;
}
src.lockDecoder(this);
for (ImageConsumer ic : consumers) {
ic.setPixels(x, y, w, h, model, pix, off, scansize);
}
}
protected void imageComplete(int status) {
if (terminated) {
return;
}
src.lockDecoder(this);
ImageConsumer ic = null;
for (Iterator<ImageConsumer> i = consumers.iterator(); i.hasNext();) {
try {
ic = i.next();
} catch (ConcurrentModificationException e) {
i = consumers.iterator();
continue;
}
ic.imageComplete(status);
}
}
}
|
didindinn/database-as-a-service | dbaas/physical/forms/disk_offerring.py | <reponame>didindinn/database-as-a-service
from django import forms
from django.core.validators import MinValueValidator
from ..models import DiskOffering
class DiskOfferingForm(forms.ModelForm):
size_gb = forms.FloatField(
label='Size GB', validators=[MinValueValidator(0.1)]
)
class Meta:
model = DiskOffering
fields = ("name", "size_gb")
def __init__(self, *args, **kwargs):
super(DiskOfferingForm, self).__init__(*args, **kwargs)
self.initial['size_gb'] = self.instance.size_gb()
|
joshiejack/Mirror-Mirror | src/main/java/joshie/mirror/api/elements/Band.java | package joshie.mirror.api.elements;
import joshie.mirror.api.Ability;
import joshie.mirror.api.Element;
import net.minecraft.util.ResourceLocation;
import java.util.HashMap;
import java.util.Map;
public class Band extends Element<Band> {
public static final Map<ResourceLocation, Band> BANDS = new HashMap<>();
private boolean hasOrnaments = true;
public Band(ResourceLocation name, Ability ability) {
super(name, ability);
}
public String getPrefix() {
return "band";
}
public Map<ResourceLocation, Band> getMap() {
return BANDS;
}
public Band setNoOrnaments() {
hasOrnaments = false;
return this;
}
public boolean hasOrnaments() {
return hasOrnaments;
}
}
|
wangrollin/leetcode-java | src/main/java/com/wangrollin/leetcode/n0_normal/p200/p210/problem217/Solution2.java | <reponame>wangrollin/leetcode-java<gh_stars>0
package com.wangrollin.leetcode.n0_normal.p200.p210.problem217;
import java.util.*;
/**
* 存在重复元素
*
* 给定一个整数数组,判断是否存在重复元素。
* 如果任何值在数组中出现至少两次,函数返回 true。如果数组中每个元素都不相同,则返回 false。
*
* 示例 1:
* 输入: [1,2,3,1]
* 输出: true
*
* 示例 2:
* 输入: [1,2,3,4]
* 输出: false
*
* 示例3:
* 输入: [1,1,1,3,3,4,3,2,4,2]
* 输出: true
*
* 来源:力扣(LeetCode)
* 链接:https://leetcode-cn.com/problems/contains-duplicate
*
* Solution2
* stream
*/
public class Solution2 {
public boolean containsDuplicate(int[] nums) {
return Arrays.stream(nums).distinct().toArray().length != nums.length;
}
}
|
shaojiankui/iOS10-Runtime-Headers | PrivateFrameworks/StoreKitUI.framework/SKUILibraryItemState.h | /* Generated by RuntimeBrowser
Image: /System/Library/PrivateFrameworks/StoreKitUI.framework/StoreKitUI
*/
@interface SKUILibraryItemState : NSObject <NSCopying> {
unsigned long long _avTypes;
long long _availability;
NSString * _bundleIdentifier;
NSString * _bundleVersion;
bool _highDefinition;
bool _preview;
bool _rental;
NSNumber * _storeAccountIdentifier;
NSString * _storeFlavorIdentifier;
NSString * _storePlatformKind;
NSNumber * _storeVersionIdentifier;
}
@property (nonatomic) unsigned long long AVTypes;
@property (nonatomic) long long availability;
@property (nonatomic, copy) NSString *bundleIdentifier;
@property (nonatomic, copy) NSString *bundleVersion;
@property (getter=isHighDefinition, nonatomic) bool highDefinition;
@property (nonatomic, readonly) NSString *itemStateVariantIdentifier;
@property (getter=isPreview, nonatomic) bool preview;
@property (getter=isRental, nonatomic) bool rental;
@property (nonatomic, copy) NSNumber *storeAccountIdentifier;
@property (nonatomic, copy) NSString *storeFlavorIdentifier;
@property (nonatomic, copy) NSString *storePlatformKind;
@property (nonatomic, copy) NSNumber *storeVersionIdentifier;
- (void).cxx_destruct;
- (unsigned long long)AVTypes;
- (long long)availability;
- (id)bundleIdentifier;
- (id)bundleVersion;
- (id)copyWithZone:(struct _NSZone { }*)arg1;
- (id)initWithApplication:(id)arg1;
- (bool)isHighDefinition;
- (bool)isPreview;
- (bool)isRental;
- (id)itemStateVariantIdentifier;
- (id)newJavaScriptRepresentation;
- (void)setAVTypes:(unsigned long long)arg1;
- (void)setAvailability:(long long)arg1;
- (void)setBundleIdentifier:(id)arg1;
- (void)setBundleVersion:(id)arg1;
- (void)setHighDefinition:(bool)arg1;
- (void)setPreview:(bool)arg1;
- (void)setRental:(bool)arg1;
- (void)setStoreAccountIdentifier:(id)arg1;
- (void)setStoreFlavorIdentifier:(id)arg1;
- (void)setStorePlatformKind:(id)arg1;
- (void)setStoreVersionIdentifier:(id)arg1;
- (id)storeAccountIdentifier;
- (id)storeFlavorIdentifier;
- (id)storePlatformKind;
- (id)storeVersionIdentifier;
@end
|
Schwarz-Hexe/YAMMS | skse/PapyrusCell.h | #pragma once
class TESObjectCELL;
class TESObjectREFR;
class VMClassRegistry;
namespace papyrusCell
{
void RegisterFuncs(VMClassRegistry* registry);
UInt32 GetNumRefs(TESObjectCELL* thisCell, UInt32 formType);
TESObjectREFR* GetNthRef(TESObjectCELL* thisCell, UInt32 index, UInt32 formType);
}
|
jydata/MCP | mcp-server/src/main/java/com/jiuye/mcp/server/controller/home/HomePageController.java | package com.jiuye.mcp.server.controller.home;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.jiuye.mcp.param.constants.SystemConstant;
import com.jiuye.mcp.response.Response;
import com.jiuye.mcp.server.controller.BaseController;
import com.jiuye.mcp.server.dao.meta.MetaDatarouteMapper;
import com.jiuye.mcp.server.model.home.*;
import com.jiuye.mcp.server.model.meta.MetaDatarouteEntity;
import com.jiuye.mcp.server.service.home.IHomePageService;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.time.FastDateFormat;
import org.redisson.api.RList;
import org.redisson.api.RListMultimap;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.*;
/**
* 首页面板
* @author zp
* @date 2018/12/11
*/
@RestController
@RequestMapping(value = "/home", produces = {"application/json;charset=UTF-8"})
public class HomePageController extends BaseController {
private static final Logger logger = LoggerFactory.getLogger(HomePageController.class.getName());
@Autowired
private IHomePageService homePageService;
@Autowired
private MetaDatarouteMapper metaDatarouteMapper;
@Autowired
RedissonClient redissonClient;
/**
* 1.查询作业状态图
* 1)init : 初始
* 2)wait : 等待执行
* 3)running : 运行中
* 4)success : 成功
* 5)fail : 失败
*
* @return
*/
@ApiOperation(value = "查询作业状态图", notes = "查询作业状态图", httpMethod = "GET")
@RequestMapping(value = "/jobs", method = RequestMethod.GET)
public Response<List<HomeCommonEntity>> queryHomeJobsPage() {
List<HomeCommonEntity> homeCommonEntities = homePageService.queryJobs();
Response<List<HomeCommonEntity>> response = Response.createResponse(homeCommonEntities);
response.setCode(SystemConstant.RESPONSE_CODE_SUCCESS);
return response;
}
/**
* 2.同步数据折线图
*
* @return
*/
@ApiOperation(value = "同步数据折线图", notes = "同步数据折线图", httpMethod = "GET")
@RequestMapping(value = "/sync_data", method = RequestMethod.GET)
public Response<List<HomeSyncTimeEnity>> queryHomeSyncDataPage() {
RListMultimap<String, String> map = redissonClient.getListMultimap("monitorRecord");
int mapSize = 500;
long currentTime = System.currentTimeMillis();
//截取时间格式当前时间的秒数
int val = Long.valueOf(FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss").format(currentTime).substring(17, 19)).intValue();
long endTime = currentTime;
//用于计算当前之前最近的取值时间
int flag = (val + 3) % 3;
switch (flag) {
case 0:
endTime = currentTime;
break;
case 1:
endTime = currentTime - 1000;
break;
case 2:
endTime = currentTime - 2000;
break;
}
//构建一个包含取值时间的List,用于后续map的取值
List<String> valTimeList = new ArrayList<>();
FastDateFormat format = FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss");
String timeFormat;
for (int i = 0; i < mapSize; i++) {
timeFormat = format.format(endTime);
valTimeList.add(timeFormat);
endTime -= 3000;
}
List<MetaDatarouteEntity> routeIdList = metaDatarouteMapper.queryRouteId();
Map<Long, String> routeNameMap = new HashMap<>();
if (routeIdList != null && routeIdList.size() > 0) {
for (MetaDatarouteEntity valRoute : routeIdList) {
routeNameMap.put(valRoute.getRouteId(), valRoute.getRouteName());
}
}
List<HomeSyncTimeEnity> timeList = new ArrayList<>();
HomeSyncRecordEntity entity;
HomeSyncRouteEntity routeEntityInfo;
HomeSyncTimeEnity timeEnityInfo;
for (String time : valTimeList) {
Map<Long, Long> routeMap = new Hashtable<>();
RList<String> valList = map.get(time);
String subTime = time.substring(11, 19);
//计算map中同一个key下,route对应的Record sum值
for (String homeSyncRecord : valList) {
entity = JSON.parseObject(homeSyncRecord, HomeSyncRecordEntity.class);
long routeId = entity.getRouteid();
if (routeNameMap.containsKey(routeId)) {
if (routeMap.containsKey(routeId)) {
Long routeSum = routeMap.get(routeId);
long record = entity.getRecord();
routeMap.put(routeId, (routeSum + record));
} else {
routeMap.put(routeId, entity.getRecord());
}
}
}
List<HomeSyncRouteEntity> routeList = new ArrayList<>();
timeEnityInfo = new HomeSyncTimeEnity();
timeEnityInfo.setTime(subTime);
for (Map.Entry<Long, Long> mapEntry : routeMap.entrySet()) {
routeEntityInfo = new HomeSyncRouteEntity();
Long routeId = mapEntry.getKey();
routeEntityInfo.setRouteId(routeId);
routeEntityInfo.setRouteName(routeNameMap.get(routeId));
routeEntityInfo.setRecordSum(mapEntry.getValue());
routeList.add(routeEntityInfo);
}
timeEnityInfo.setRouteList(routeList);
timeList.add(timeEnityInfo);
}
List<HomeSyncTimeEnity> list = Lists.reverse(timeList);
Response<List<HomeSyncTimeEnity>> response = Response.createResponse(list);
response.setCode(SystemConstant.RESPONSE_CODE_SUCCESS);
return response;
}
/**
* 3.技术元数据柱状图
* 1)源端链接个数
* 2)终端链接个数
* 3)路由数量(有效的)
* 4)agent个数(截止时间点)
*
* @return
*/
@ApiOperation(value = "技术元数据柱状图", notes = "技术元数据柱状图", httpMethod = "GET")
@RequestMapping(value = "/tech_metadata", method = RequestMethod.GET)
public Response<List<HomeCommonEntity>> queryHomeTechMetadataPage() {
List<HomeCommonEntity> homeCommonEntities = homePageService.queryTechDatas();
Response<List<HomeCommonEntity>> response = Response.createResponse(homeCommonEntities);
response.setCode(SystemConstant.RESPONSE_CODE_SUCCESS);
return response;
}
@ApiOperation(value = "数据量统计对比", notes = "数据量统计对比", httpMethod = "GET")
@RequestMapping(value = "/table_counts", method = RequestMethod.GET)
public Response<List<HomeFinenessStatisticEntity>> queryHomeTableCountPage() {
List<HomeFinenessStatisticEntity> homeTableCountEntities = homePageService.queryTableCounts();
Response<List<HomeFinenessStatisticEntity>> response = Response.createResponse(homeTableCountEntities);
response.setCode(SystemConstant.RESPONSE_CODE_SUCCESS);
return response;
}
@ApiOperation(value = "Agent Error Sql统计", notes = "Agent Error Sql统计", httpMethod = "GET")
@RequestMapping(value = "/error_sql_counts", method = RequestMethod.GET)
public Response<List<HomeSyncAgentErrorLogEntity>> queryHomeAgentErrorSqlCountsPage() {
List<HomeSyncAgentErrorLogEntity> errorCounts = homePageService.queryAgentErrorSqlCounts();
Response<List<HomeSyncAgentErrorLogEntity>> response = Response.createResponse(errorCounts);
response.setCode(SystemConstant.RESPONSE_CODE_SUCCESS);
return response;
}
/**
* 同步job数据折线图
*
* @return
*/
@ApiOperation(value = "同步Job数据折线图", notes = "同步Job数据折线图", httpMethod = "GET")
@RequestMapping(value = "/sync_job_data", method = RequestMethod.GET)
public Response<List<HomeSyncTimeEnity>> queryHomeSyncJobDataPage() {
List<HomeSyncTimeEnity> homeSyncTimeEnities = homePageService.querySyncJobData();
Response<List<HomeSyncTimeEnity>> response = Response.createResponse(homeSyncTimeEnities);
response.setCode(SystemConstant.RESPONSE_CODE_SUCCESS);
return response;
}
/**
* 同步agent数据折线图
* @return
*/
@ApiOperation(value = "同步Agent数据折线图", notes = "同步Agent数据折线图", httpMethod = "GET")
@RequestMapping(value = "/sync_agent_data", method = RequestMethod.GET)
public Response<List<HomeSyncTimeEnity>> queryHomeSyncAgentDataPage(){
List<HomeSyncTimeEnity> homeSyncTimeEnities = homePageService.querySyncAgentData();
Response<List<HomeSyncTimeEnity>> response = Response.createResponse(homeSyncTimeEnities);
response.setCode(SystemConstant.RESPONSE_CODE_SUCCESS);
return response;
}
@ApiOperation(value = "热度表", notes = "热度表", httpMethod = "GET")
@RequestMapping(value = "/hot_tables", method = RequestMethod.GET)
public Response<List<HomeTableCountEntity>> queryHomeHotTablesWeekTwoPage(@ApiParam(value = "粒度", required = true, defaultValue = "day") @RequestParam(value = "fineness") String fineness) {
List<HomeTableCountEntity> homeHotTablesCountEnities = homePageService.queryHotTables(fineness);
Response<List<HomeTableCountEntity>> response = Response.createResponse(homeHotTablesCountEnities);
response.setCode(SystemConstant.RESPONSE_CODE_SUCCESS);
return response;
}
}
|
unlimitedggames/gdxjam-ugg | core/src/com/ugg/gdxjam/model/ai/fsm/TripleEnemyState.java | package com.ugg.gdxjam.model.ai.fsm;
import com.badlogic.gdx.ai.fsm.State;
import com.badlogic.gdx.ai.msg.Telegram;
import com.badlogic.gdx.ai.steer.Steerable;
import com.badlogic.gdx.ai.steer.behaviors.Pursue;
import com.badlogic.gdx.ai.steer.behaviors.Wander;
import com.badlogic.gdx.math.Vector2;
import com.ugg.gdxjam.model.GameEntity;
import com.ugg.gdxjam.model.Logger;
import com.ugg.gdxjam.model.Mappers;
import com.ugg.gdxjam.model.SteerLocation;
import com.ugg.gdxjam.model.components.*;
import com.ugg.gdxjam.model.configs.Configs;
/**
* Created by <NAME> on 10/01/2016.
*/
public enum TripleEnemyState implements State<GameEntity> {
Watch() {
@Override
public void enter(GameEntity gameEntity) {
WeaponsComponent weaponC = Mappers.weapon.get(gameEntity.entity);
weaponC.enabled = false;
SteerableComponent steerableC = Mappers.steerable.get(gameEntity.entity);
SteeringBehaviorComponent steeringBC = Mappers.steeringBehavior.get(gameEntity.entity);
Wander wander = (Wander) gameEntity.getBehavior(Wander.class);
if(wander == null) {
wander = new Wander(steerableC);
}
wander.setOwner(steerableC);
gameEntity.cacheBehavior(steeringBC.behavior);
steeringBC.behavior = wander;
Configs.watcher.applyConfigs(steeringBC);
}
@Override
public void update(GameEntity gameEntity) {
if(Mappers.lockOn.has(gameEntity.entity))
gameEntity.changeState(TripleEnemyState.Attack);
}
@Override
public void exit(GameEntity gameEntity) {
}
},
Attack(){
@Override
public void enter(GameEntity gameEntity) {
WeaponsComponent weaponC = Mappers.weapon.get(gameEntity.entity);
weaponC.enabled = true;
}
@Override
public void update(GameEntity gameEntity) {
LockOnComponent lockOnComponent = Mappers.lockOn.get(gameEntity.entity);
if(lockOnComponent == null){
gameEntity.changeState(TripleEnemyState.Watch);
return;
}
if(lockOnComponent.target.isDead()){
gameEntity.changeState(TripleEnemyState.Watch);
}
}
@Override
public void exit(GameEntity gameEntity) {
WeaponsComponent weaponC = Mappers.weapon.get(gameEntity.entity);
weaponC.enabled = false;
gameEntity.entity.remove(LockOnComponent.class);
}
};
@Override
public boolean onMessage(GameEntity gameEntity, Telegram telegram) {
return false;
}
}
|
cleverrchen77/LeetCode | src/FirstBadVersion.java | <reponame>cleverrchen77/LeetCode
/**
* 第一个错误的版本
* @author Administrator
*
*/
/**
* The isBadVersion API is defined in the parent class VersionControl.
* boolean isBadVersion(int version);
*/
public class FirstBadVersion {
public int firstBadVersion(int n) {
int low=1;
int high= n;
int mid=0;
while(low<=high)
{
mid=low+(high-low)/2;
if(isBadVersion(mid))
{
high=mid-1;
}
else
{
low=mid+1;
}
}
return low;
}
} |
sidhu177/pythonprog | Breadth-First-Search.py | # -*- coding: utf-8 -*-
"""
Created on Sun Dec 2 01:51:49 2018
Taken from Data Structures and Algorithms using Python text book...
"""
def BFS(g,s,discovered):
level = [s]
while len(level)>0:
next_level = []
for u in level:
for e in g.incident_edges(u):
v = e.opposite(u)
if v not in discovered:
discovered[v] = e
next_level.append(v)
level = next_level
|
nattyco/fermatold | fermat-api/src/main/java/com/bitdubai/fermat_api/layer/dmp_transaction/incoming_device_user/IncomingDeviceUserManager.java | package com.bitdubai.fermat_api.layer.dmp_transaction.incoming_device_user;
//import com.bitdubai.fermat_api.layer.crypto_module.actor_address_book.exceptions.ExampleException;
/**
* Created by loui on 22/02/15.
*/
public interface IncomingDeviceUserManager {
// public void exampleMethod() throws ExampleException;
}
|
Jasonandy/alpaca | alpaca-common/src/main/java/cn/ucaner/alpaca/framework/utils/tools/system/JvmInfo.java | <reponame>Jasonandy/alpaca
/**
* <html>
* <body>
* <P> Copyright 1994 JsonInternational</p>
* <p> All rights reserved.</p>
* <p> Created on 19941115</p>
* <p> Created by Jason</p>
* </body>
* </html>
*/
package cn.ucaner.alpaca.framework.utils.tools.system;
/**
* @Package:cn.ucaner.alpaca.framework.utils.tools.system
* @ClassName:JvmInfo
* @Description: <p> Java Virtual Machine Implementation的信息。</p>
* @Author: -
* @CreatTime:2018年5月25日 上午10:05:12
* @Modify By:
* @ModifyTime: 2018年5月25日
* @Modify marker:
* @version V1.0
*/
public class JvmInfo {
private final String JAVA_VM_NAME = SystemUtil.get("java.vm.name", false);
private final String JAVA_VM_VERSION = SystemUtil.get("java.vm.version", false);
private final String JAVA_VM_VENDOR = SystemUtil.get("java.vm.vendor", false);
private final String JAVA_VM_INFO = SystemUtil.get("java.vm.info", false);
/**
* 取得当前JVM impl.的名称(取自系统属性:<code>java.vm.name</code>)。
*
* <p>
* 例如Sun JDK 1.4.2:<code>"Java HotSpot(TM) Client VM"</code>
* </p>
*
* @return 属性值,如果不能取得(因为Java安全限制)或值不存在,则返回<code>null</code>。
*
*/
public final String getName() {
return JAVA_VM_NAME;
}
/**
* 取得当前JVM impl.的版本(取自系统属性:<code>java.vm.version</code>)。
*
* <p>
* 例如Sun JDK 1.4.2:<code>"1.4.2-b28"</code>
* </p>
*
* @return 属性值,如果不能取得(因为Java安全限制)或值不存在,则返回<code>null</code>。
*
*/
public final String getVersion() {
return JAVA_VM_VERSION;
}
/**
* 取得当前JVM impl.的厂商(取自系统属性:<code>java.vm.vendor</code>)。
*
* <p>
* 例如Sun JDK 1.4.2:<code>"Sun Microsystems Inc."</code>
* </p>
*
* @return 属性值,如果不能取得(因为Java安全限制)或值不存在,则返回<code>null</code>。
*
*/
public final String getVendor() {
return JAVA_VM_VENDOR;
}
/**
* 取得当前JVM impl.的信息(取自系统属性:<code>java.vm.info</code>)。
*
* <p>
* 例如Sun JDK 1.4.2:<code>"mixed mode"</code>
* </p>
*
* @return 属性值,如果不能取得(因为Java安全限制)或值不存在,则返回<code>null</code>。
*
*/
public final String getInfo() {
return JAVA_VM_INFO;
}
/**
* 将Java Virutal Machine Implementation的信息转换成字符串。
*
* @return JVM impl.的字符串表示
*/
@Override
public final String toString() {
StringBuilder builder = new StringBuilder();
SystemUtil.append(builder, "JavaVM Name: ", getName());
SystemUtil.append(builder, "JavaVM Version: ", getVersion());
SystemUtil.append(builder, "JavaVM Vendor: ", getVendor());
SystemUtil.append(builder, "JavaVM Info: ", getInfo());
return builder.toString();
}
}
|
DonAnthonyLee/LBPanel_LBKit | src/libs/lbk/LBApplication.cpp | <filename>src/libs/lbk/LBApplication.cpp<gh_stars>1-10
/* --------------------------------------------------------------------------
*
* Little Board Application Kit
* Copyright (C) 2018, <NAME>, All Rights Reserved
*
* This software is a freeware; it may be used and distributed according to
* the terms of The MIT License.
*
* 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.
*
* File: LBApplication.cpp
* Description:
*
* --------------------------------------------------------------------------*/
#include <stdio.h>
#include <unistd.h>
#include <sys/select.h>
#include <lbk/LBKConfig.h>
#include <lbk/LBApplication.h>
#include <lbk/add-ons/LBPanelDevice.h>
#include <lbk/add-ons/LBPanelCombiner.h>
//#define LBK_APP_DEBUG
#ifdef LBK_APP_DEBUG
#define DBGOUT(msg...) do { printf(msg); } while (0)
#else
#define DBGOUT(msg...) do {} while (0)
#endif
#ifdef LBK_APP_IPC_BY_FIFO // defined in "<lbk/LBKConfig.h>"
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
typedef struct
{
BString path;
int fd;
} LBKAppIPC;
#endif // LBK_APP_IPC_BY_FIFO
typedef enum
{
LBK_ADD_ON_NONE = 0,
LBK_ADD_ON_PANEL_DEVICE,
LBK_ADD_ON_PANEL_MODULE,
} LBAddOnType;
// use ETK++'s functions for no implementation in Lite BeAPI
#ifdef ETK_MAJOR_VERSION
#define B_SYMBOL_TYPE_TEXT 0x02
typedef void* image_id;
#define load_add_on(path) etk_load_addon(path)
#define unload_add_on(image) etk_unload_addon(image)
#define get_image_symbol(image, name, sclass, ptr) etk_get_image_symbol(image, name, ptr)
#define IMAGE_IS_VALID(image) (image != NULL)
#else
#define IMAGE_IS_VALID(image) (image > 0)
#endif
typedef struct
{
uint8 keyState;
bigtime_t keyTimestamps[8];
uint8 keyClicks[8];
BList *leftPageViews;
BList *rightPageViews;
BHandler *preferHandler;
bool valid;
} LBPanelDeviceAddOnData;
typedef struct
{
const char *desc;
const lbk_icon **icons;
int icons_count;
LBView *view;
} LBPanelModuleData;
typedef struct
{
BString name;
LBAddOnType type;
void *dev;
image_id image;
void *data;
} LBAddOnData;
static LBAddOnData* lbk_app_load_panel_device_addon(const BPath &pth, const char *opt)
{
LBPanelDeviceAddOnData *devData = (LBPanelDeviceAddOnData*)malloc(sizeof(LBPanelDeviceAddOnData));
if(devData == NULL) return NULL;
image_id image = (image_id)0;
LBPanelDevice *dev = NULL;
if(pth.Path() != NULL)
{
image = load_add_on(pth.Path());
if(IMAGE_IS_VALID(image))
{
LBPanelDevice* (*instantiate_func)() = NULL;
if(get_image_symbol(image, "instantiate_panel_device",
B_SYMBOL_TYPE_TEXT,
(void**)&instantiate_func) == B_OK)
dev = (*instantiate_func)();
}
}
else // combiner
{
dev = new LBPanelCombiner();
}
if(dev == NULL || dev->InitCheck(opt) != B_OK)
{
if(dev != NULL) delete dev;
if(IMAGE_IS_VALID(image)) unload_add_on(image);
free(devData);
return NULL;
}
LBAddOnData *data = new LBAddOnData;
data->name.SetTo(pth.Leaf());
data->type = LBK_ADD_ON_PANEL_DEVICE;
data->dev = reinterpret_cast<void*>(dev);
data->image = image;
bzero(devData, sizeof(LBPanelDeviceAddOnData));
devData->leftPageViews = new BList();
devData->rightPageViews = new BList();
devData->valid = true;
data->data = devData;
return data;
}
static void lbk_app_unload_panel_device_addon(LBAddOnData *data)
{
if(data == NULL || data->type != LBK_ADD_ON_PANEL_DEVICE) return;
if(data->dev == NULL || data->data == NULL) return;
LBPanelDevice *dev = reinterpret_cast<LBPanelDevice*>(data->dev);
delete dev;
LBPanelDeviceAddOnData *devData = (LBPanelDeviceAddOnData*)data->data;
delete devData->leftPageViews;
delete devData->rightPageViews;
free(devData);
}
static LBPanelDevice* lbk_app_get_panel_device(const BList &addOnsList, int32 index)
{
if(index < 0 || index >= addOnsList.CountItems()) return NULL;
for(int32 k = 0; k < addOnsList.CountItems(); k++)
{
LBAddOnData *data = (LBAddOnData*)addOnsList.ItemAt(k);
if(data->type == LBK_ADD_ON_PANEL_DEVICE)
{
if(index-- == 0)
return(reinterpret_cast<LBPanelDevice*>(data->dev));
}
}
return NULL;
}
static LBPanelDeviceAddOnData* lbk_app_get_panel_device_data(const BList &addOnsList, int32 index)
{
if(index < 0 || index >= addOnsList.CountItems()) return NULL;
for(int32 k = 0; k < addOnsList.CountItems(); k++)
{
LBAddOnData *data = (LBAddOnData*)addOnsList.ItemAt(k);
if(data->type == LBK_ADD_ON_PANEL_DEVICE)
{
if(index-- == 0)
return((LBPanelDeviceAddOnData*)data->data);
}
}
return NULL;
}
static LBAddOnData* lbk_app_load_panel_module(const BPath &pth, const char *opt)
{
LBPanelModuleData *devData = (LBPanelModuleData*)malloc(sizeof(LBPanelModuleData));
if(devData == NULL) return NULL;
devData->view = NULL;
image_id image = load_add_on(pth.Path());
if(IMAGE_IS_VALID(image))
{
LBView* (*instantiate_func)(const char*, const char*, const char**, const lbk_icon***, int*) = NULL;
if(get_image_symbol(image, "instantiate_panel_module",
B_SYMBOL_TYPE_TEXT,
(void**)&instantiate_func) == B_OK)
{
devData->desc = NULL;
devData->icons = NULL;
devData->icons_count = 0;
devData->view = (*instantiate_func)(pth.Path(), opt, &devData->desc, &devData->icons, &devData->icons_count);
}
}
if(devData->view == NULL)
{
if(IMAGE_IS_VALID(image)) unload_add_on(image);
free(devData);
return NULL;
}
LBAddOnData *data = new LBAddOnData;
data->name.SetTo(pth.Leaf());
data->type = LBK_ADD_ON_PANEL_MODULE;
data->dev = NULL;
data->image = image;
data->data = devData;
return data;
}
static void lbk_app_unload_panel_module(LBAddOnData *data)
{
if(data == NULL || data->type != LBK_ADD_ON_PANEL_MODULE) return;
if(data->data == NULL) return;
LBPanelModuleData *devData = (LBPanelModuleData*)data->data;
delete devData->view;
free(devData);
}
static LBPanelModuleData* lbk_app_get_panel_module_data(const BList &addOnsList, int32 index)
{
if(index < 0 || index >= addOnsList.CountItems()) return NULL;
for(int32 k = 0; k < addOnsList.CountItems(); k++)
{
LBAddOnData *data = (LBAddOnData*)addOnsList.ItemAt(k);
if(data->type == LBK_ADD_ON_PANEL_MODULE)
{
if(index-- == 0)
return((LBPanelModuleData*)data->data);
}
}
return NULL;
}
LBApplication::LBApplication(const LBAppSettings *settings, bool use_lbk_default_settings)
: BLooper(NULL, B_URGENT_DISPLAY_PRIORITY),
fQuitLooper(false),
fPulseRate(0),
fPanelDevicesCount(0),
fPanelModulesCount(0),
fIPC(NULL),
fKeyInterval(LBK_KEY_INTERVAL_DEFAULT)
{
fPipes[0] = fPipes[1] = -1;
if(use_lbk_default_settings)
{
BFile f("/etc/LBK.conf", B_READ_ONLY);
fSettings.AddItems(&f);
}
if(settings != NULL)
fSettings.AddItems(*settings);
for(int32 k = 0; k < fSettings.CountItems(); k++)
{
BString name, value, options;
if(fSettings.GetItemAt(k, &name, &value, &options) != B_OK) continue;
if(name.FindFirst("::") >= 0) continue; // sub-settings
if(name == "PanelDeviceAddon")
{
BPath pth(value.String(), NULL, true);
if(pth.Path() == NULL && value != "combiner") continue;
LBAddOnData *data = lbk_app_load_panel_device_addon(pth, options.String());
if(data == NULL)
{
fprintf(stderr,
"[LBApplication]: %s --- Failed to load add-on (%s) !\n",
__func__, (pth.Path() == NULL) ? "combiner" : pth.Path());
continue;
}
fPanelDevicesCount++;
fAddOnsList.AddItem(data);
}
else if(name == "PanelModule")
{
BPath pth(value.String(), NULL, true);
if(pth.Path() == NULL) continue;
LBAddOnData *data = lbk_app_load_panel_module(pth, options.String());
if(data == NULL)
{
fprintf(stderr,
"[LBApplication]: %s --- Failed to load add-on (%s) !\n",
__func__, pth.Path());
continue;
}
fPanelModulesCount++;
fAddOnsList.AddItem(data);
}
else if(name == "IPC" && fIPC == NULL)
{
#ifdef LBK_APP_IPC_BY_FIFO
int fd;
BPath pth;
BString str;
str << "/tmp/lbk_ipc_" << getuid();
BEntry entry(str.String());
entry.GetPath(&pth);
if(!(entry.Exists() && entry.IsDirectory()))
{
if(mkdir(pth.Path(), 0700) != 0)
{
fprintf(stderr, "[LBApplication]: %s --- Failed to initialize IPC !\n", __func__);
continue;
}
}
entry.SetTo(pth.Path(), value.String());
entry.GetPath(&pth);
unlink(pth.Path());
if(mkfifo(pth.Path(), 0600) == -1 ||
chmod(pth.Path(), 0600) == -1 ||
(fd = open(pth.Path(), O_NONBLOCK | O_RDWR)) < 0) {
fprintf(stderr,
"[LBApplication]: %s --- Failed to create fifo (%s) !\n",
__func__, pth.Path());
continue;
}
LBKAppIPC *ipc = new LBKAppIPC;
ipc->path.SetTo(pth.Path());
ipc->fd = fd;
fIPC = (void*)ipc;
#else
// TODO: other way
#endif
}
else if(name == "KeyInterval")
{
int v = atoi(value.String());
if(v >= 100 && v <= LBK_KEY_INTERVAL_MAX)
fKeyInterval = (bigtime_t)v;
}
// TODO: others
}
}
LBApplication::~LBApplication()
{
for(int32 k = 0; k < CountPanels(); k++)
{
LBPanelDeviceAddOnData *dev = lbk_app_get_panel_device_data(fAddOnsList, k);
LBView *view;
while((view = (LBView*)dev->leftPageViews->RemoveItem((int32)0)) != NULL) delete view;
while((view = (LBView*)dev->rightPageViews->RemoveItem((int32)0)) != NULL) delete view;
}
if(fPipes[0] >= 0)
{
close(fPipes[0]);
close(fPipes[1]);
}
for(int32 k = 0; k < fAddOnsList.CountItems(); k++)
{
LBAddOnData *data = (LBAddOnData*)fAddOnsList.ItemAt(k);
switch(data->type)
{
case LBK_ADD_ON_PANEL_DEVICE:
lbk_app_unload_panel_device_addon(data);
break;
case LBK_ADD_ON_PANEL_MODULE:
lbk_app_unload_panel_module(data);
break;
default:
break;
}
if(IMAGE_IS_VALID(data->image))
unload_add_on(data->image);
delete data;
}
if(fIPC != NULL)
{
LBKAppIPC *ipc = (LBKAppIPC*)fIPC;
#ifdef LBK_APP_IPC_BY_FIFO
unlink(ipc->path.String());
close(ipc->fd);
#else
// TODO: other way
#endif
delete ipc;
}
}
bool
LBApplication::AddPageView(LBView *view, bool left_side, int32 panel_index)
{
LBPanelDeviceAddOnData *dev = lbk_app_get_panel_device_data(fAddOnsList, panel_index);
if(dev == NULL || dev->valid == false || view == NULL) return false;
if(view->fDev != NULL || view->Looper() != NULL || view->MasterView() != NULL) return false;
if((left_side ? dev->leftPageViews->AddItem(view) : dev->rightPageViews->AddItem(view)) == false) return false;
AddHandler(view);
view->fActivated = false;
view->fDev = PanelAt(panel_index);
view->Attached();
return true;
}
bool
LBApplication::RemovePageView(LBView *view)
{
if(view == NULL || view->fDev == NULL || view->Looper() != this || view->MasterView() != NULL) return false;
LBPanelDeviceAddOnData *dev = lbk_app_get_panel_device_data(fAddOnsList, view->fDev->Index());
view->Detached();
RemoveHandler(view);
if(dev->leftPageViews->RemoveItem(view) == false)
dev->rightPageViews->RemoveItem(view);
if(view == dev->preferHandler)
dev->preferHandler = NULL;
view->fActivated = false;
view->fDev = NULL;
return true;
}
LBView*
LBApplication::RemovePageView(int32 index, bool left_side, int32 panel_index)
{
LBView *view = PageViewAt(index, left_side, panel_index);
return(RemovePageView(view) ? view : NULL);
}
LBView*
LBApplication::PageViewAt(int32 index, bool left_side, int32 panel_index) const
{
LBPanelDeviceAddOnData *dev = lbk_app_get_panel_device_data(fAddOnsList, panel_index);
if(dev == NULL) return NULL;
return(left_side ? (LBView*)dev->leftPageViews->ItemAt(index) : (LBView*)dev->rightPageViews->ItemAt(index));
}
int32
LBApplication::CountPageViews(bool left_side, int32 panel_index) const
{
LBPanelDeviceAddOnData *dev = lbk_app_get_panel_device_data(fAddOnsList, panel_index);
if(dev == NULL) return 0;
return(left_side ? dev->leftPageViews->CountItems() : dev->rightPageViews->CountItems());
}
void
LBApplication::ActivatePageView(int32 index, bool left_side, int32 panel_index)
{
LBPanelDeviceAddOnData *dev = lbk_app_get_panel_device_data(fAddOnsList, panel_index);
if(dev == NULL || dev->valid == false) return;
LBView *newView = PageViewAt(index, left_side, panel_index);
LBView *oldView = GetActivatedPageView(panel_index);
if(oldView == newView || newView == NULL) return;
if(oldView)
oldView->SetActivated(false);
dev->preferHandler = newView;
newView->SetActivated(true);
}
LBView*
LBApplication::GetActivatedPageView(int32 panel_index) const
{
LBPanelDeviceAddOnData *dev = lbk_app_get_panel_device_data(fAddOnsList, panel_index);
if(dev == NULL) return NULL;
return e_cast_as(dev->preferHandler, LBView);
}
bool
LBApplication::QuitRequested()
{
fQuitLooper = true;
if(fPipes[1] >= 0)
{
uint8 byte = 0xff;
while(write(fPipes[1], &byte, 1) != 1) snooze(100000);
}
// The looper will be deleted automatically if this return "true".
return false;
}
void
LBApplication::Go()
{
#ifdef ETK_MAJOR_VERSION
if(IsRunning())
#else
if(Thread() > 0)
#endif
{
fprintf(stderr, "[LBApplication]: It's forbidden to run Go() more than ONE time !\n");
return;
}
if(CountPanels() == 0)
{
fprintf(stderr, "[LBApplication]: No panels !\n");
return;
}
if(pipe(fPipes) < 0)
{
perror("[LBApplication]: Unable to create pipe");
return;
}
Lock();
Run();
for(int32 k = 0; k < CountPanels(); k++)
{
LBPanelDevice* dev = PanelAt(k);
dev->Init(k, BMessenger(this, this));
ActivatePageView(0, false, k);
}
LBKAppIPC *ipc = (LBKAppIPC*)fIPC;
Unlock();
fd_set rset;
struct timeval timeout;
uint32 count = 0;
bigtime_t pulse_sent_time[2] = {0, 0};
bigtime_t pulse_rate = PulseRate();
timeout.tv_sec = 0;
#ifdef ETK_MAJOR_VERSION
while(IsRunning() && fQuitLooper == false)
#else
while(Thread() > 0 && fQuitLooper == false)
#endif
{
timeout.tv_usec = (pulse_rate > 0 && pulse_rate < (bigtime_t)500000) ? pulse_rate : 500000;
if(count > 0 && timeout.tv_usec > fKeyInterval / 3)
timeout.tv_usec = fKeyInterval / 3;
int fdMax = fPipes[0];
FD_ZERO(&rset);
FD_SET(fPipes[0], &rset);
if(ipc != NULL)
{
#ifdef LBK_APP_IPC_BY_FIFO
FD_SET(ipc->fd, &rset);
if(ipc->fd > fdMax) fdMax = ipc->fd;
#else
// TODO: other way
#endif
}
int status = select(fdMax + 1, &rset, NULL, NULL, &timeout);
if(status < 0)
{
perror("[LBApplication]: Unable to get event from input device");
break;
}
if(status > 0 && FD_ISSET(fPipes[0], &rset))
{
uint8 byte = 0x00;
if(read(fPipes[0], &byte, 1) == 1)
{
switch(byte)
{
case 0xab:
count++;
break;
default:
pulse_rate = PulseRate();
}
}
}
if(count > 0 && system_time() - pulse_sent_time[0] >= (bigtime_t)(fKeyInterval / 2))
{
count--;
PostMessage(LBK_EVENT_PENDING, this);
pulse_sent_time[0] = system_time();
}
if(pulse_rate > 0 && system_time() - pulse_sent_time[1] >= pulse_rate)
{
PostMessage(B_PULSE, this);
pulse_sent_time[1] = system_time();
}
if(ipc != NULL)
{
#ifdef LBK_APP_IPC_BY_FIFO
if(status > 0 && FD_ISSET(ipc->fd, &rset))
{
uint8 byte = 0x00;
if(read(ipc->fd, &byte, 1) == 1)
{
#ifdef LBK_APP_DEBUG
if(byte <= 0x04)
{
Lock();
LBPanelDeviceAddOnData *dev = lbk_app_get_panel_device_data(fAddOnsList, (int32)byte);
if(dev != NULL)
{
printf("--- Key state of device (id = %u) ---\n", byte);
printf("Current time = %lld\n", system_time());
printf("keyState = 0x%02x\n", dev->keyState);
for(int k = 0; k < 8; k++)
{
printf("keyClicks[%d] = %u\n", k, dev->keyClicks[k]);
printf("keyTimestamps[%d] = %lld\n", k, dev->keyTimestamps[k]);
}
printf("----------------------------------\n");
}
Unlock();
}
else if(byte <= 0x09)
{
Lock();
LBPanelDevice *dev = lbk_app_get_panel_device(fAddOnsList, (int32)(byte - 0x05));
if(dev != NULL)
dev->SetLogLevel(dev->LogLevel() == 0 ? 1 : 0);
Unlock();
}
else
#endif // LBK_APP_DEBUG
switch(byte)
{
case 0xfe:
PostMessage(LBK_APP_SETTINGS_UPDATED, this);
break;
default:
// TODO
break;
}
}
}
#else
// TODO: other way
#endif
}
}
PostMessage(B_QUIT_REQUESTED, this);
}
void
LBApplication::MessageReceived(BMessage *msg)
{
int32 id = -1;
LBPanelDeviceAddOnData *dev = NULL;
bigtime_t when;
uint8 key = 0;
bool stopRunner;
switch(msg->what)
{
case LBK_DEVICE_DETACHED:
if(msg->FindInt32("panel_id", &id) == B_OK)
{
dev = lbk_app_get_panel_device_data(fAddOnsList, id);
if(dev == NULL || dev->valid == false) break;
LBView *view;
while((view = (LBView*)dev->leftPageViews->RemoveItem((int32)0)) != NULL) delete view;
while((view = (LBView*)dev->rightPageViews->RemoveItem((int32)0)) != NULL) delete view;
dev->preferHandler = NULL;
dev->valid = false;
bool noValidPanels = true;
for(id = 0; id < CountPanels(); id++)
{
dev = lbk_app_get_panel_device_data(fAddOnsList, id);
if(dev->valid)
{
noValidPanels = false;
break;
}
}
if(noValidPanels)
PostMessage(B_QUIT_REQUESTED, this);
}
break;
case LBK_QUIT_REQUESTED:
PostMessage(B_QUIT_REQUESTED, this);
break;
case B_KEY_DOWN:
case B_KEY_UP:
if(msg->FindInt32("panel_id", &id) != B_OK) break;
if((dev = lbk_app_get_panel_device_data(fAddOnsList, id)) == NULL) break;
if(dev->preferHandler == NULL) break;
if(msg->FindInt64("when", &when) != B_OK) break;
if(when > system_time()) // should never happen, just in case
when = system_time();
if(msg->HasInt16("key")) // flexiable keys
{
uint16 keyID;
uint8 clicks;
if(msg->FindInt8("clicks", (int8*)&clicks) != B_OK || clicks == 0) break;
msg->FindInt16("key", (int16*)&keyID);
BMessage aMsg(msg->what);
aMsg.AddInt16("key", *((int16*)&keyID));
aMsg.AddInt8("clicks", *((int8*)&clicks));
aMsg.AddInt64("when", when);
PostMessage(&aMsg, dev->preferHandler);
break;
}
if(msg->FindInt8("key", (int8*)&key) != B_OK || key >= 8) break;
if(msg->what == B_KEY_DOWN)
{
if((dev->keyState & (0x01 << key)) != 0) // already DOWN
{
// auto-repeat (event.value = 2) event
if(when < dev->keyTimestamps[key]) break;
if(dev->keyClicks[key] == 0xff)
{
dev->keyTimestamps[key] = when;
break;
}
if(when - dev->keyTimestamps[key] < (bigtime_t)LBK_KEY_INTERVAL_MAX) break;
dev->keyClicks[key] = 0xff; // long press
}
else
{
if(dev->keyClicks[key] > 0 && when < dev->keyTimestamps[key]) break;
if(dev->keyClicks[key] < 0xff) dev->keyClicks[key]++;
if(dev->keyClicks[key] == 0x01) // first
{
uint8 byte = 0xab;
if(write(fPipes[1], &byte, 1) <= 0)
{
DBGOUT("[LBApplication]: Failed to notify the main thread. (line=%d)\n", __LINE__);
dev->keyClicks[key] = 0;
break;
}
}
}
dev->keyTimestamps[key] = when;
BMessage aMsg(B_KEY_DOWN);
aMsg.AddInt8("key", *((int8*)&key));
aMsg.AddInt8("clicks", *((int8*)&dev->keyClicks[key]));
aMsg.AddInt64("when", when);
PostMessage(&aMsg, dev->preferHandler);
dev->keyState |= (0x1 << key);
}
else
{
if((dev->keyState & (0x01 << key)) == 0) break; // already UP
if(when < dev->keyTimestamps[key]) break;
dev->keyState &= ~(0x01 << key);
dev->keyTimestamps[key] = when;
}
break;
case B_PULSE:
for(id = 0; id < CountPanels(); id++)
{
dev = lbk_app_get_panel_device_data(fAddOnsList, id);
if(dev->preferHandler != NULL)
PostMessage(B_PULSE, dev->preferHandler);
}
break;
case LBK_EVENT_PENDING:
stopRunner = true;
when = system_time();
for(id = 0; id < CountPanels(); id++)
{
dev = lbk_app_get_panel_device_data(fAddOnsList, id);
uint8 nKeys = CountPanelKeys(id);
for(uint8 k = 0; k < nKeys; k++)
{
if(when < dev->keyTimestamps[k]) continue; // should never happen
if((dev->keyState & (0x01 << k)) != 0) // already DOWN
{
// in case that no B_KEY_UP event received any more
if(when - dev->keyTimestamps[k] < (bigtime_t)(2 * LBK_KEY_INTERVAL_MAX))
{
stopRunner = false;
continue;
}
DBGOUT("[LBApplication]: B_KEY_DOWN over time.");
}
else
{
if(dev->keyClicks[k] == 0 || dev->keyTimestamps[k] == 0) continue; // no UP before
if(when - dev->keyTimestamps[k] < (bigtime_t)fKeyInterval)
{
stopRunner = false;
continue;
}
}
if(dev->preferHandler != NULL)
{
BMessage aMsg(B_KEY_UP);
aMsg.AddInt8("key", *((int8*)&k));
aMsg.AddInt8("clicks", *((int8*)&dev->keyClicks[k]));
aMsg.AddInt64("when", dev->keyTimestamps[k]);
PostMessage(&aMsg, dev->preferHandler);
}
dev->keyState &= ~(0x01 << k);
dev->keyClicks[k] = 0;
dev->keyTimestamps[k] = 0;
}
}
if(stopRunner == false)
{
uint8 byte = 0xab;
if(write(fPipes[1], &byte, 1) <= 0)
{
DBGOUT("[LBApplication]: Failed to notify the main thread. (line=%d)\n", __LINE__);
PostMessage(LBK_EVENT_PENDING, this); // try again
}
}
break;
case LBK_APP_SETTINGS_UPDATED: // derived class should read the settings then pass it to LBApplication.
if(msg->HasMessage("settings") == false) break;
// TODO: read default config if needed
for(id = 0; id < CountPanels(); id++)
{
dev = lbk_app_get_panel_device_data(fAddOnsList, id);
if(dev == NULL || dev->valid == false) continue;
for(int32 k = 0; k < dev->leftPageViews->CountItems(); k++)
{
LBView *view = (LBView*)dev->leftPageViews->ItemAt(k);
PostMessage(msg, view);
}
for(int32 k = 0; k < dev->rightPageViews->CountItems(); k++)
{
LBView *view = (LBView*)dev->rightPageViews->ItemAt(k);
PostMessage(msg, view);
}
}
break;
default:
BLooper::MessageReceived(msg);
}
}
bigtime_t
LBApplication::PulseRate() const
{
return fPulseRate;
}
void
LBApplication::SetPulseRate(bigtime_t rate)
{
if(rate != 0 && rate < (bigtime_t)50000)
rate = (bigtime_t)50000;
else if(rate > (bigtime_t)10000000)
rate = (bigtime_t)10000000;
if(fPulseRate != rate)
{
fPulseRate = rate;
if(fPipes[1] >= 0)
{
uint8 byte = 0x01;
write(fPipes[1], &byte, 1);
}
}
}
LBPanelDevice*
LBApplication::PanelAt(int32 index) const
{
return lbk_app_get_panel_device(fAddOnsList, index);
}
uint8
LBApplication::CountPanelKeys(int32 index) const
{
uint8 n = 0;
LBPanelDevice *dev = PanelAt(index);
if(dev != NULL)
dev->GetCountOfKeys(n);
return n;
}
int32
LBApplication::CountPanels() const
{
return fPanelDevicesCount;
}
const LBAppSettings*
LBApplication::Settings() const
{
return &fSettings;
}
void
LBApplication::SetSettings(const LBAppSettings* settings)
{
fSettings.MakeEmpty();
if(settings != NULL)
fSettings.AddItems(*settings);
}
int32
LBApplication::CountModules() const
{
return fPanelModulesCount;
}
const lbk_icon*
LBApplication::GetModuleIcon(int32 module_index, int32 icon_index) const
{
LBPanelModuleData *data = lbk_app_get_panel_module_data(fAddOnsList, module_index);
if(data == NULL || icon_index >= (int32)data->icons_count) return NULL;
return(data->icons[icon_index]);
}
const char*
LBApplication::GetModuleDescription(int32 index) const
{
LBPanelModuleData *data = lbk_app_get_panel_module_data(fAddOnsList, index);
return((data != NULL) ? data->desc : NULL);
}
LBView*
LBApplication::GetModuleView(int32 index) const
{
LBPanelModuleData *data = lbk_app_get_panel_module_data(fAddOnsList, index);
return((data != NULL) ? data->view : NULL);
}
|
matthewlai93/KafkaSentinel | KafkaApp/node_modules/csv-parse/samples/fs_read.js |
var fs = require('fs');
var parse = require('..');
var parser = parse({delimiter: ';'}, function(err, data){
console.log(data);
});
fs.createReadStream(__dirname+'/fs_read.csv').pipe(parser);
|
inesmarca/2TP_SO | Kernel/exceptions.c | // This is a personal academic project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++, C#, and Java: http://www.viva64.com
#include <consoleManager.h>
#include <stdint.h>
#include <lib.h>
#include <exception.h>
#include <time.h>
#define ZERO_EXCEPTION_ID 0
#define INVALID_OPCODE_EXCEPTION_ID 6
static void zero_division();
static void invalid_opcode();
void _hlt();
void _sti();
// valores de retorno de la excepcion
uint64_t * ipReturn;
uint64_t * rspReturn;
static char * regs[] = {
"R15: ", "R14: ", "R13: ", "R12: ", "R11: ",
"R10: ", "R9: ", "R8: ", "RSI: ", "RDI: ",
"RBP: ", "RDX: ", "RCX: ", "RBX: ", "RAX: ",
"RIP: ", "CS: ", "FLAGS: ", "RSP: "
};
// imprime los registros y despliega un timer para el reinicio de la pantalla
void printRegs(uint64_t * stackFrame) {
char buffer[9];
for (int i = 0; i < 19; i++) {
print(regs[i], 19);
uintToBase(stackFrame[i], buffer, 16);
baseToHexa(buffer);
print(buffer, 9);
if (i % 2 == 0) {
newLine(BACKGROUND_COLOR);
} else {
print(" ", 12);
}
}
// habilita de vuelta las interrupciones
_sti();
print("La pantalla se reiniciara en ", 30);
char buff[3] = {0};
// espera a una interrupcion
_hlt();
int init_time = seconds_elapsed();
int aux = 10;
int i = 10;
uintToBase(i, buff, 10);
changeColor(0xFB781F, BACKGROUND_COLOR);
print(buff, 9);
while (i > 0) {
_hlt();
aux = 10 - (seconds_elapsed() - init_time);
if (i != aux) {
delete(BACKGROUND_COLOR);
if (i == 10) {
delete(BACKGROUND_COLOR);
}
i = aux;
uintToBase(i, buff, 10);
changeColor(0xFB781F, BACKGROUND_COLOR);
print(buff, 3);
}
}
newLine(BACKGROUND_COLOR);
}
// setea los registros de retorno
void setAddresses(uint64_t * ip, uint64_t * rsp) {
ipReturn = ip;
rspReturn = rsp;
}
// resetea la pantalla
void resetScreen(uint64_t * stackFrame) {
stackFrame[15] = (uint64_t)ipReturn;
stackFrame[18] = (uint64_t)rspReturn;
clear(1);
clear(2);
}
void exceptionDispatcher(int exception, uint64_t * stackFrame) {
if (exception == ZERO_EXCEPTION_ID)
zero_division(stackFrame);
else if (exception == INVALID_OPCODE_EXCEPTION_ID)
invalid_opcode(stackFrame);
}
// handler de la excepcion 0
static void zero_division(uint64_t * stackFrame) {
changeColor(0xFF0000, BACKGROUND_COLOR);
print("Exception 0: division by 0\n", 28);
printRegs(stackFrame);
resetScreen(stackFrame);
}
// handler de la excepcion 6
static void invalid_opcode(uint64_t * stackFrame) {
changeColor(0xFF0000, BACKGROUND_COLOR);
print("Exception 6: invalid opcode\n", 29);
printRegs(stackFrame);
resetScreen(stackFrame);
} |
BrunoCersozimo/Fundamentos-Javascript | fundamentos/numerosAlgunsCuidados.js | console.log(7 / 0.0001)//Qualquer número divido por 0 não gera um erro gera um infinity
console.log("10" / 2)//javascript divide o 10 apesar dele estar entre aspas, ou seja, ser uma string
console.log('3' + 2) // Diferente do exemplo acima, aqui o + vai concatenar o 3 e o 2. Exibindo o resultado 32
console.log("Show!" * 2)// Algumas linguagens repetem o "Show!" duas vezes o javascript não. Gera um NaN
console.log(0.7 + 0.1)// O resultado não é 0.8 por haver uma especificação IEEE, portanto gera um resultado impreciso
//console.log(10.toString())//Não consigo chamar um número literal.Uma função
console.log((10.345).toFixed(2))// Aqui é possível apenas colocando o número em parenteses
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.