answer stringlengths 15 1.25M |
|---|
<!DOCTYPE HTML PUBLIC "-
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_151) on Tue Jan 16 16:57:26 CET 2018 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Package org.openbase.jul.visual.javafx.iface (JUL 1.5-SNAPSHOT API)</title>
<meta name="date" content="2018-01-16">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Package org.openbase.jul.visual.javafx.iface (JUL 1.5-SNAPSHOT API)";
}
}
catch(err) {
}
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<div class="topNav"><a name="navbar.top">
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li>Class</li>
<li class="navBarCell1Rev">Use</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?org/openbase/jul/visual/javafx/iface/package-use.html" target="_top">Frames</a></li>
<li><a href="package-use.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="<API key>">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!
allClassesLink = document.getElementById("<API key>");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
</script>
</div>
<a name="skip.navbar.top">
</a></div>
<div class="header">
<h1 title="Uses of Package org.openbase.jul.visual.javafx.iface" class="title">Uses of Package<br>org.openbase.jul.visual.javafx.iface</h1>
</div>
<div class="contentContainer">
<ul class="blockList">
<li class="blockList">
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../../../org/openbase/jul/visual/javafx/iface/package-summary.html">org.openbase.jul.visual.javafx.iface</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#org.openbase.jul.visual.javafx.iface">org.openbase.jul.visual.javafx.iface</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="org.openbase.jul.visual.javafx.iface">
</a>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation">
<caption><span>Classes in <a href="../../../../../../org/openbase/jul/visual/javafx/iface/package-summary.html">org.openbase.jul.visual.javafx.iface</a> used by <a href="../../../../../../org/openbase/jul/visual/javafx/iface/package-summary.html">org.openbase.jul.visual.javafx.iface</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Class and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colOne"><a href="../../../../../../org/openbase/jul/visual/javafx/iface/class-use/StaticPane.html#org.openbase.jul.visual.javafx.iface">StaticPane</a> </td>
</tr>
</tbody>
</table>
</li>
</ul>
</div>
<div class="bottomNav"><a name="navbar.bottom">
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li>Class</li>
<li class="navBarCell1Rev">Use</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?org/openbase/jul/visual/javafx/iface/package-use.html" target="_top">Frames</a></li>
<li><a href="package-use.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="<API key>">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!
allClassesLink = document.getElementById("<API key>");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
</script>
</div>
<a name="skip.navbar.bottom">
</a></div>
<p class="legalCopy"><small>Copyright &
</body>
</html> |
// Created file "Lib\src\gpmuuid\gpmgmt_i"
typedef struct _GUID
{
unsigned long Data1;
unsigned short Data2;
unsigned short Data3;
unsigned char Data4[8];
} GUID;
#define DEFINE_GUID(name, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) \
extern const GUID name = { l, w1, w2, { b1, b2, b3, b4, b5, b6, b7, b8 } }
DEFINE_GUID(LIBID_GPMGMTLib, 0xc2f48cc2, 0x305b, 0x4672, 0xba, 0xa7, 0x76, 0xa5, 0x77, 0x38, 0xf4, 0x8a); |
// Created file "Lib\src\Uuid\guids"
typedef struct _GUID
{
unsigned long Data1;
unsigned short Data2;
unsigned short Data3;
unsigned char Data4[8];
} GUID;
#define DEFINE_GUID(name, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) \
extern const GUID name = { l, w1, w2, { b1, b2, b3, b4, b5, b6, b7, b8 } }
DEFINE_GUID(<API key>, 0x58c571ec, 0x1bcb, 0x42a7, 0x8a, 0xc5, 0xbb, 0x29, 0x15, 0x73, 0xa2, 0x60); |
// <auto-generated>
// This code was generated by a tool.
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
namespace Serial_Test {
using System;
<summary>
A strongly-typed resource class, for looking up localized strings, etc.
</summary>
// This class was auto-generated by the <API key>
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.<API key>("System.Resources.Tools.<API key>", "4.0.0.0")]
[global::System.Diagnostics.<API key>()]
[global::System.Runtime.CompilerServices.<API key>()]
internal class Resource1 {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.<API key>("Microsoft.Performance", "CA1811:<API key>")]
internal Resource1() {
}
<summary>
Returns the cached ResourceManager instance used by this class.
</summary>
[global::System.ComponentModel.<API key>(global::System.ComponentModel.<API key>.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Serial_Test.Resource1", typeof(Resource1).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
<summary>
Overrides the current thread's CurrentUICulture property for all
resource lookups using this strongly typed resource class.
</summary>
[global::System.ComponentModel.<API key>(global::System.ComponentModel.<API key>.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
<summary>
Looks up a localized string similar to <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title></title>
</head>
<body>
<table>
<tr>
<td align="center">
&nbsp;
</td>
<td align="center">
<a href="/forward">Forward</a>
</td>
<td align="center">
&nbsp;
</td>
</tr>
<tr>
<td align="center">
<a href="/left">Left</a>
</td>
<td align="center">
<a href="/stop">Stop</a>
</td>
<td alig [rest of string was truncated]";.
</summary>
internal static string mainMenu {
get {
return ResourceManager.GetString("mainMenu", resourceCulture);
}
}
}
} |
<?php
use CyrilPerrin\Spine\Route\Literal;
/**
* Literal route test
*/
class LiteralTest extends \<API key>
{
/**
* ParseUrl() test
*/
public function testParseUrl()
{
// Build route
$route = new Literal('/user', 'User', 'index', array('test' => 'test'));
// Parse unvalid URLs
$this->assertNull($route->parseUrl(''));
$this->assertNull($route->parseUrl('something'));
$this->assertNull($route->parseUrl('/something'));
// Parse valid URLs
$request = $route->parseUrl('/user');
$this->assertEquals('User', $request->getControllerName());
$this->assertEquals('index', $request->getActionName());
$this->assertEquals(array('test' => 'test'), $request->getParameters());
}
/**
* BuildUrl() test
*/
public function testBuildUrl()
{
// Build route
$route = new Literal('/user', 'User', 'index', array('test' => 'test'));
// Build URL with invalid parameters
$url = $route->buildUrl('Something', 'something');
$this->assertNull($url);
$url = $route->buildUrl('User', 'something');
$this->assertNull($url);
$url = $route->buildUrl('Something', 'index');
$this->assertNull($url);
$url = $route->buildUrl('User', 'index');
$this->assertNull($url);
$url = $route->buildUrl('User', 'index', array('something' => 'something'));
$this->assertNull($url);
$url = $route->buildUrl('User', 'index', array('something' => 'something','test' => 'test'));
$this->assertNull($url);
// Build URLs with valid parameters
$url = $route->buildUrl('User', 'index', array('test' => 'test'));
$this->assertEquals('/user', $url);
}
} |
package com.professortea.view;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ScrollView;
import com.professortea.utils.LogUtil;
/**
* BorderScrollView
* <ul>
* <li>onTop and onBottom response ScrollView</li>
* <li>you can {@link #setOnBorderListener(OnBorderListener)} to set your top and bottom response</li>
* </ul>
*
* @author trinea@trinea.cn 2013-5-21
*/
public class BorderScrollView extends ScrollView {
private OnBorderListener onBorderListener;
private View contentView;
private boolean hasMore = true;
public boolean isOneTime() {
return oneTime;
}
public void setOneTime(boolean oneTime) {
this.oneTime = oneTime;
}
private boolean oneTime = true;
public boolean isHasMore() {
return hasMore;
}
public void setHasMore(boolean hasMore) {
this.hasMore = hasMore;
}
public BorderScrollView(Context context) {
super(context);
}
public BorderScrollView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public BorderScrollView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void onScrollChanged(int x, int y, int oldx, int oldy) {
super.onScrollChanged(x, y, oldx, oldy);
if(oneTime){
doOnBorderListener();
}
}
public void setOnBorderListener(final OnBorderListener onBorderListener) {
this.onBorderListener = onBorderListener;
if (onBorderListener == null) {
return;
}
if (contentView == null) {
contentView = getChildAt(0);
}
}
public static interface OnBorderListener {
/**
* Called when scroll to bottom
*/
public void onBottom();
/**
* Called when scroll to top
*/
public void onTop();
}
private void doOnBorderListener() {
if (contentView != null && contentView.getMeasuredHeight() <= getScrollY() + getHeight()) {
if (onBorderListener != null && hasMore && oneTime) {
LogUtil.d("TeaFragment", "OnLoadMore .... ");
onBorderListener.onBottom();
}
} else if (getScrollY() == 0) {
if (onBorderListener != null) {
onBorderListener.onTop();
}
}
}
} |
#include "mcp_can.h"
#define spi_readwrite SPI.transfer
#define spi_read() spi_readwrite(0x00)
#define SPI_BEGIN() SPI.beginTransaction(SPISettings(10000000, MSBFIRST, SPI_MODE0))
#define SPI_END() SPI.endTransaction()
void MCP_CAN::mcp2515_reset(void)
{
#ifdef SPI_HAS_TRANSACTION
SPI_BEGIN();
#endif
MCP2515_SELECT();
spi_readwrite(MCP_RESET);
MCP2515_UNSELECT();
#ifdef SPI_HAS_TRANSACTION
SPI_END();
#endif
delay(10);
}
INT8U MCP_CAN::<API key>(const INT8U address)
{
INT8U ret;
#ifdef SPI_HAS_TRANSACTION
SPI_BEGIN();
#endif
MCP2515_SELECT();
spi_readwrite(MCP_READ);
spi_readwrite(address);
ret = spi_read();
MCP2515_UNSELECT();
#ifdef SPI_HAS_TRANSACTION
SPI_END();
#endif
return ret;
}
void MCP_CAN::<API key>(const INT8U address, INT8U values[], const INT8U n)
{
INT8U i;
#ifdef SPI_HAS_TRANSACTION
SPI_BEGIN();
#endif
MCP2515_SELECT();
spi_readwrite(MCP_READ);
spi_readwrite(address);
// mcp2515 has auto-increment of address-pointer
for (i=0; i<n && i<<API key>; i++) {
values[i] = spi_read();
}
MCP2515_UNSELECT();
#ifdef SPI_HAS_TRANSACTION
SPI_END();
#endif
}
void MCP_CAN::mcp2515_setRegister(const INT8U address, const INT8U value)
{
#ifdef SPI_HAS_TRANSACTION
SPI_BEGIN();
#endif
MCP2515_SELECT();
spi_readwrite(MCP_WRITE);
spi_readwrite(address);
spi_readwrite(value);
MCP2515_UNSELECT();
#ifdef SPI_HAS_TRANSACTION
SPI_END();
#endif
}
void MCP_CAN::<API key>(const INT8U address, const INT8U values[], const INT8U n)
{
INT8U i;
#ifdef SPI_HAS_TRANSACTION
SPI_BEGIN();
#endif
MCP2515_SELECT();
spi_readwrite(MCP_WRITE);
spi_readwrite(address);
for (i=0; i<n; i++)
{
spi_readwrite(values[i]);
}
MCP2515_UNSELECT();
#ifdef SPI_HAS_TRANSACTION
SPI_END();
#endif
}
void MCP_CAN::<API key>(const INT8U address, const INT8U mask, const INT8U data)
{
#ifdef SPI_HAS_TRANSACTION
SPI_BEGIN();
#endif
MCP2515_SELECT();
spi_readwrite(MCP_BITMOD);
spi_readwrite(address);
spi_readwrite(mask);
spi_readwrite(data);
MCP2515_UNSELECT();
#ifdef SPI_HAS_TRANSACTION
SPI_END();
#endif
}
INT8U MCP_CAN::mcp2515_readStatus(void)
{
INT8U i;
#ifdef SPI_HAS_TRANSACTION
SPI_BEGIN();
#endif
MCP2515_SELECT();
spi_readwrite(MCP_READ_STATUS);
i = spi_read();
MCP2515_UNSELECT();
#ifdef SPI_HAS_TRANSACTION
SPI_END();
#endif
return i;
}
INT8U MCP_CAN::<API key>(const INT8U newmode)
{
INT8U i;
<API key>(MCP_CANCTRL, MODE_MASK, newmode);
i = <API key>(MCP_CANCTRL);
i &= MODE_MASK;
if ( i == newmode )
{
return MCP2515_OK;
}
return MCP2515_FAIL;
}
INT8U MCP_CAN::mcp2515_configRate(const INT8U canSpeed)
{
INT8U set, cfg1, cfg2, cfg3;
set = 1;
switch (canSpeed)
{
case (CAN_5KBPS):
cfg1 = <API key>;
cfg2 = <API key>;
cfg3 = <API key>;
break;
case (CAN_10KBPS):
cfg1 = <API key>;
cfg2 = <API key>;
cfg3 = <API key>;
break;
case (CAN_20KBPS):
cfg1 = <API key>;
cfg2 = <API key>;
cfg3 = <API key>;
break;
case (CAN_25KBPS):
cfg1 = <API key>;
cfg2 = <API key>;
cfg3 = <API key>;
break;
case (CAN_31K25BPS):
cfg1 = <API key>;
cfg2 = <API key>;
cfg3 = <API key>;
break;
case (CAN_33KBPS):
cfg1 = <API key>;
cfg2 = <API key>;
cfg3 = <API key>;
break;
case (CAN_40KBPS):
cfg1 = <API key>;
cfg2 = <API key>;
cfg3 = <API key>;
break;
case (CAN_50KBPS):
cfg1 = <API key>;
cfg2 = <API key>;
cfg3 = <API key>;
break;
case (CAN_80KBPS):
cfg1 = <API key>;
cfg2 = <API key>;
cfg3 = <API key>;
break;
case (CAN_83K3BPS):
cfg1 = <API key>;
cfg2 = <API key>;
cfg3 = <API key>;
break;
case (CAN_95KBPS):
cfg1 = <API key>;
cfg2 = <API key>;
cfg3 = <API key>;
break;
case (CAN_100KBPS): /* 100KBPS */
cfg1 = <API key>;
cfg2 = <API key>;
cfg3 = <API key>;
break;
case (CAN_125KBPS):
cfg1 = <API key>;
cfg2 = <API key>;
cfg3 = <API key>;
break;
case (CAN_200KBPS):
cfg1 = <API key>;
cfg2 = <API key>;
cfg3 = <API key>;
break;
case (CAN_250KBPS):
cfg1 = <API key>;
cfg2 = <API key>;
cfg3 = <API key>;
break;
case (CAN_500KBPS):
cfg1 = <API key>;
cfg2 = <API key>;
cfg3 = <API key>;
break;
case (CAN_666KBPS):
cfg1 = <API key>;
cfg2 = <API key>;
cfg3 = <API key>;
break;
case (CAN_1000KBPS):
cfg1 = <API key>;
cfg2 = <API key>;
cfg3 = <API key>;
break;
default:
set = 0;
break;
}
if (set) {
mcp2515_setRegister(MCP_CNF1, cfg1);
mcp2515_setRegister(MCP_CNF2, cfg2);
mcp2515_setRegister(MCP_CNF3, cfg3);
return MCP2515_OK;
}
else {
return MCP2515_FAIL;
}
}
void MCP_CAN::<API key>(void)
{
INT8U i, a1, a2, a3;
a1 = MCP_TXB0CTRL;
a2 = MCP_TXB1CTRL;
a3 = MCP_TXB2CTRL;
for (i = 0; i < 14; i++) { /* in-buffer loop */
mcp2515_setRegister(a1, 0);
mcp2515_setRegister(a2, 0);
mcp2515_setRegister(a3, 0);
a1++;
a2++;
a3++;
}
mcp2515_setRegister(MCP_RXB0CTRL, 0);
mcp2515_setRegister(MCP_RXB1CTRL, 0);
}
INT8U MCP_CAN::mcp2515_init(const INT8U canSpeed) /* mcp2515init */
{
INT8U res;
mcp2515_reset();
res = <API key>(MODE_CONFIG);
if(res > 0)
{
#if DEBUG_MODE
Serial.print("Enter setting mode fall\r\n");
#else
delay(10);
#endif
return res;
}
#if DEBUG_MODE
Serial.print("Enter setting mode success \r\n");
#else
delay(10);
#endif
/* set boadrate */
if(mcp2515_configRate(canSpeed))
{
#if DEBUG_MODE
Serial.print("set rate fall!!\r\n");
#else
delay(10);
#endif
return res;
}
#if DEBUG_MODE
Serial.print("set rate success!!\r\n");
#else
delay(10);
#endif
if ( res == MCP2515_OK ) {
/* init canbuffers */
<API key>();
/* interrupt mode */
mcp2515_setRegister(MCP_CANINTE, MCP_RX0IF | MCP_RX1IF);
#if (DEBUG_RXANY==1)
/* enable both receive-buffers */
/* to receive any message */
/* and enable rollover */
<API key>(MCP_RXB0CTRL,
MCP_RXB_RX_MASK | MCP_RXB_BUKT_MASK,
MCP_RXB_RX_ANY | MCP_RXB_BUKT_MASK);
<API key>(MCP_RXB1CTRL, MCP_RXB_RX_MASK,
MCP_RXB_RX_ANY);
#else
/* enable both receive-buffers */
/* to receive messages */
/* with std. and ext. identifie */
/* and enable rollover */
<API key>(MCP_RXB0CTRL,
MCP_RXB_RX_MASK | MCP_RXB_BUKT_MASK,
MCP_RXB_RX_STDEXT | MCP_RXB_BUKT_MASK );
<API key>(MCP_RXB1CTRL, MCP_RXB_RX_MASK,
MCP_RXB_RX_STDEXT);
#endif
/* enter normal mode */
res = <API key>(MODE_NORMAL);
if(res)
{
#if DEBUG_MODE
Serial.print("Enter Normal Mode Fall!!\r\n");
#else
delay(10);
#endif
return res;
}
#if DEBUG_MODE
Serial.print("Enter Normal Mode Success!!\r\n");
#else
delay(10);
#endif
}
return res;
}
void MCP_CAN::mcp2515_write_id( const INT8U mcp_addr, const INT8U ext, const INT32U id )
{
uint16_t canid;
INT8U tbufdata[4];
canid = (uint16_t)(id & 0x0FFFF);
if ( ext == 1)
{
tbufdata[MCP_EID0] = (INT8U) (canid & 0xFF);
tbufdata[MCP_EID8] = (INT8U) (canid >> 8);
canid = (uint16_t)(id >> 16);
tbufdata[MCP_SIDL] = (INT8U) (canid & 0x03);
tbufdata[MCP_SIDL] += (INT8U) ((canid & 0x1C) << 3);
tbufdata[MCP_SIDL] |= MCP_TXB_EXIDE_M;
tbufdata[MCP_SIDH] = (INT8U) (canid >> 5 );
}
else
{
tbufdata[MCP_SIDH] = (INT8U) (canid >> 3 );
tbufdata[MCP_SIDL] = (INT8U) ((canid & 0x07 ) << 5);
tbufdata[MCP_EID0] = 0;
tbufdata[MCP_EID8] = 0;
}
<API key>( mcp_addr, tbufdata, 4 );
}
void MCP_CAN::mcp2515_read_id( const INT8U mcp_addr, INT8U* ext, INT32U* id )
{
INT8U tbufdata[4];
*ext = 0;
*id = 0;
<API key>( mcp_addr, tbufdata, 4 );
*id = (tbufdata[MCP_SIDH]<<3) + (tbufdata[MCP_SIDL]>>5);
if ( (tbufdata[MCP_SIDL] & MCP_TXB_EXIDE_M) == MCP_TXB_EXIDE_M )
{
/* extended id */
*id = (*id<<2) + (tbufdata[MCP_SIDL] & 0x03);
*id = (*id<<8) + tbufdata[MCP_EID8];
*id = (*id<<8) + tbufdata[MCP_EID0];
*ext = 1;
}
}
void MCP_CAN::<API key>( const INT8U buffer_sidh_addr)
{
INT8U mcp_addr;
mcp_addr = buffer_sidh_addr;
<API key>(mcp_addr+5, m_nDta, m_nDlc ); /* write data bytes */
if ( m_nRtr == 1) /* if RTR set bit in byte */
{
m_nDlc |= MCP_RTR_MASK;
}
mcp2515_setRegister((mcp_addr+4), m_nDlc ); /* write the RTR and DLC */
mcp2515_write_id(mcp_addr, m_nExtFlg, m_nID ); /* write CAN id */
}
void MCP_CAN::mcp2515_read_canMsg( const INT8U buffer_sidh_addr) /* read can msg */
{
INT8U mcp_addr, ctrl;
mcp_addr = buffer_sidh_addr;
mcp2515_read_id( mcp_addr, &m_nExtFlg,&m_nID );
ctrl = <API key>( mcp_addr-1 );
m_nDlc = <API key>( mcp_addr+4 );
if ((ctrl & 0x08)) {
m_nRtr = 1;
}
else {
m_nRtr = 0;
}
m_nDlc &= MCP_DLC_MASK;
<API key>( mcp_addr+5, &(m_nDta[0]), m_nDlc );
}
void MCP_CAN::<API key>(const INT8U mcp_addr) /* start transmit */
{
<API key>( mcp_addr-1 , MCP_TXB_TXREQ_M, MCP_TXB_TXREQ_M );
}
INT8U MCP_CAN::<API key>(INT8U *txbuf_n) /* get Next free txbuf */
{
INT8U res, i, ctrlval;
INT8U ctrlregs[MCP_N_TXBUFFERS] = { MCP_TXB0CTRL, MCP_TXB1CTRL, MCP_TXB2CTRL };
res = MCP_ALLTXBUSY;
*txbuf_n = 0x00;
/* check all 3 TX-Buffers */
for (i=0; i<MCP_N_TXBUFFERS; i++) {
ctrlval = <API key>( ctrlregs[i] );
if ( (ctrlval & MCP_TXB_TXREQ_M) == 0 ) {
*txbuf_n = ctrlregs[i]+1; /* return SIDH-address of Buffe */
res = MCP2515_OK;
return res; /* ! function exit */
}
}
return res;
}
MCP_CAN::MCP_CAN(INT8U _CS)
{
SPICS = _CS;
pinMode(SPICS, OUTPUT);
MCP2515_UNSELECT();
}
INT8U MCP_CAN::begin(INT8U speedset)
{
INT8U res;
SPI.begin();
res = mcp2515_init(speedset);
if (res == MCP2515_OK) return CAN_OK;
else return CAN_FAILINIT;
}
INT8U MCP_CAN::init_Mask(INT8U num, INT8U ext, INT32U ulData)
{
INT8U res = MCP2515_OK;
#if DEBUG_MODE
Serial.print("Begin to set Mask!!\r\n");
#else
delay(10);
#endif
res = <API key>(MODE_CONFIG);
if(res > 0){
#if DEBUG_MODE
Serial.print("Enter setting mode fall\r\n");
#else
delay(10);
#endif
return res;
}
if (num == 0){
mcp2515_write_id(MCP_RXM0SIDH, ext, ulData);
}
else if(num == 1){
mcp2515_write_id(MCP_RXM1SIDH, ext, ulData);
}
else res = MCP2515_FAIL;
res = <API key>(MODE_NORMAL);
if(res > 0){
#if DEBUG_MODE
Serial.print("Enter normal mode fall\r\n");
#else
delay(10);
#endif
return res;
}
#if DEBUG_MODE
Serial.print("set Mask success!!\r\n");
#else
delay(10);
#endif
return res;
}
INT8U MCP_CAN::init_Filt(INT8U num, INT8U ext, INT32U ulData)
{
INT8U res = MCP2515_OK;
#if DEBUG_MODE
Serial.print("Begin to set Filter!!\r\n");
#else
delay(10);
#endif
res = <API key>(MODE_CONFIG);
if(res > 0)
{
#if DEBUG_MODE
Serial.print("Enter setting mode fall\r\n");
#else
delay(10);
#endif
return res;
}
switch( num )
{
case 0:
mcp2515_write_id(MCP_RXF0SIDH, ext, ulData);
break;
case 1:
mcp2515_write_id(MCP_RXF1SIDH, ext, ulData);
break;
case 2:
mcp2515_write_id(MCP_RXF2SIDH, ext, ulData);
break;
case 3:
mcp2515_write_id(MCP_RXF3SIDH, ext, ulData);
break;
case 4:
mcp2515_write_id(MCP_RXF4SIDH, ext, ulData);
break;
case 5:
mcp2515_write_id(MCP_RXF5SIDH, ext, ulData);
break;
default:
res = MCP2515_FAIL;
}
res = <API key>(MODE_NORMAL);
if(res > 0)
{
#if DEBUG_MODE
Serial.print("Enter normal mode fall\r\nSet filter fail!!\r\n");
#else
delay(10);
#endif
return res;
}
#if DEBUG_MODE
Serial.print("set Filter success!!\r\n");
#else
delay(10);
#endif
return res;
}
INT8U MCP_CAN::setMsg(INT32U id, INT8U ext, INT8U len, INT8U rtr, INT8U *pData)
{
m_nExtFlg = ext;
m_nID = id;
m_nDlc = min( len, MAX_CHAR_IN_MESSAGE );
m_nRtr = rtr;
for(int i = 0; i<m_nDlc; i++)
{
m_nDta[i] = *(pData+i);
}
return MCP2515_OK;
}
INT8U MCP_CAN::setMsg(INT32U id, INT8U ext, INT8U len, INT8U *pData)
{
return setMsg( id, ext, len, 0, pData );
}
INT8U MCP_CAN::clearMsg()
{
m_nID = 0;
m_nDlc = 0;
m_nExtFlg = 0;
m_nRtr = 0;
m_nfilhit = 0;
for(int i = 0; i<m_nDlc; i++ )
m_nDta[i] = 0x00;
return MCP2515_OK;
}
INT8U MCP_CAN::sendMsg()
{
INT8U res, res1, txbuf_n;
uint16_t uiTimeOut = 0;
do {
res = <API key>(&txbuf_n); /* info = addr. */
uiTimeOut++;
} while (res == MCP_ALLTXBUSY && (uiTimeOut < TIMEOUTVALUE));
if(uiTimeOut == TIMEOUTVALUE)
{
return CAN_GETTXBFTIMEOUT; /* get tx buff time out */
}
uiTimeOut = 0;
<API key>( txbuf_n);
<API key>( txbuf_n );
do
{
uiTimeOut++;
res1= <API key>(txbuf_n-1 /* the ctrl reg is located at txbuf_n-1 */); /* read send buff ctrl reg */
res1 = res1 & 0x08;
}while(res1 && (uiTimeOut < TIMEOUTVALUE));
if(uiTimeOut == TIMEOUTVALUE) /* send msg timeout */
{
return CAN_SENDMSGTIMEOUT;
}
return CAN_OK;
}
INT8U MCP_CAN::sendMsgBuf(INT32U id, INT8U ext, INT8U rtr, INT8U len, INT8U *buf)
{
setMsg(id, ext, len, rtr, buf);
return sendMsg();
}
INT8U MCP_CAN::sendMsgBuf(INT32U id, INT8U ext, INT8U len, INT8U *buf)
{
setMsg(id, ext, len, buf);
return sendMsg();
}
INT8U MCP_CAN::sendMsgBuf(const CanMessage &message)
{
setMsg(message.id(), message.frameType(), message.length(), message.message());
return sendMsg();
}
INT8U MCP_CAN::readMsg()
{
INT8U stat, res;
stat = mcp2515_readStatus();
if ( stat & MCP_STAT_RX0IF ) /* Msg in Buffer 0 */
{
mcp2515_read_canMsg( MCP_RXBUF_0);
<API key>(MCP_CANINTF, MCP_RX0IF, 0);
res = CAN_OK;
}
else if ( stat & MCP_STAT_RX1IF ) /* Msg in Buffer 1 */
{
mcp2515_read_canMsg( MCP_RXBUF_1);
<API key>(MCP_CANINTF, MCP_RX1IF, 0);
res = CAN_OK;
}
else
{
res = CAN_NOMSG;
}
return res;
}
INT8U MCP_CAN::readMsgBuf(INT8U *len, INT8U buf[])
{
INT8U rc;
rc = readMsg();
if (rc == CAN_OK) {
*len = m_nDlc;
#if DEBUG_MODE
Serial.println("rc == CAN_OK");
#endif
for(int i = 0; i<m_nDlc; i++) {
buf[i] = m_nDta[i];
}
} else {
#if DEBUG_MODE
Serial.println("rc != CAN_OK!");
#endif
*len = 0;
}
return rc;
}
INT8U MCP_CAN::readMsgBufID(INT32U *ID, INT8U *len, INT8U buf[])
{
INT8U rc;
rc = readMsg();
if (rc == CAN_OK) {
*len = m_nDlc;
*ID = m_nID;
#if DEBUG_MODE
Serial.println("rc == CAN_OK");
#endif
for(int i = 0; i<m_nDlc && i < MAX_CHAR_IN_MESSAGE; i++) {
buf[i] = m_nDta[i];
}
} else {
#if DEBUG_MODE
Serial.println("rc != CAN_OK!");
#endif
*len = 0;
}
return rc;
}
CanMessage MCP_CAN::readMsg(INT8U *readStatus)
{
INT32U id{0};
INT8U messageLength{0};
INT8U messageBuffer[MAX_CHAR_IN_MESSAGE];
INT8U rc{readMsg()};
if (rc == CAN_OK) {
messageLength = m_nDlc;
id = m_nID;
#if DEBUG_MODE
Serial.println("rc == CAN_OK");
#endif
for(int i = 0; i < m_nDlc && i < MAX_CHAR_IN_MESSAGE; i++) {
messageBuffer[i] = m_nDta[i];
}
} else {
#if DEBUG_MODE
Serial.println("rc != CAN_OK!");
#endif
messageLength = 0;
}
if (readStatus) {
*readStatus = rc;
}
return CanMessage{id, FrameType::Normal, messageLength, messageBuffer);
}
INT8U MCP_CAN::checkReceive(void)
{
INT8U res;
res = mcp2515_readStatus(); /* RXnIF in Bit 1 and 0 */
if ( res & MCP_STAT_RXIF_MASK )
{
#if DEBUG_MODE
Serial.println("res & MCP_STAT_RXIF_MAX == CAN_MSGAVAIL");
#endif
return CAN_MSGAVAIL;
}
else
{
#if DEBUG_MODE
Serial.println("res & MCP_STAT_RXIF_MAX == CAN_NOMSG!");
#endif
return CAN_NOMSG;
}
}
INT8U MCP_CAN::checkError(void)
{
INT8U eflg = <API key>(MCP_EFLG);
if ( eflg & MCP_EFLG_ERRORMASK )
{
return CAN_CTRLERROR;
}
else
{
return CAN_OK;
}
}
INT32U MCP_CAN::getCanId(void)
{
return m_nID;
}
INT8U MCP_CAN::isRemoteRequest(void)
{
return m_nRtr;
}
INT8U MCP_CAN::isExtendedFrame(void)
{
return m_nExtFlg;
} |
// ax5.ui.calendar
(function () {
var UI = ax5.ui;
var U = ax5.util;
UI.addClass({
className: "calendar",
version: "0.8.9"
}, (function () {
/**
* @class ax5calendar
* @classdesc
* @author tom@axisj.com
* @logs
* 2014-06-21 tom :
* @example
* ```
* var my_pad = new ax5.ui.calendar();
* ```
*/
var ax5calendar = function () {
var
self = this,
cfg,
selectableCount = 1
;
this.instanceId = ax5.getGuid();
this.target = null;
this.selection = [];
this.selectionMap = {};
this.selectableMap = {};
this.markerMap = {};
this.printedDay = {
start: "", end: ""
};
this.config = {
clickEventName: "click",
theme: 'default',
mode: 'day', // day|month|year,
dateFormat: 'yyyy-MM-dd',
displayDate: (new Date()),
animateTime: 250,
dimensions: {
controlHeight: '40',
controlButtonWidth: '40',
colHeadHeight: '30',
itemPadding: 2
},
lang: {
yearHeading: "Choose the year",
monthHeading: "Choose the month",
yearTmpl: "%s",
months: ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC'],
dayTmpl: "%s"
},
multipleSelect: false,
selectMode: 'day',
defaultMarkerTheme: 'holiday',
defaultPeriodTheme: 'period'
};
cfg = this.config;
var
onStateChanged = function (opts, that) {
if (opts && opts.onStateChanged) {
opts.onStateChanged.call(that, that);
}
else if (this.onStateChanged) {
this.onStateChanged.call(that, that);
}
that = null;
},
getFrameTmpl = function () {
return `
<div class="ax5-ui-calendar {{theme}}" data-calendar-els="root" onselectstart="return false;">
{{#control}}
<div class="calendar-control" data-calendar-els="control" style="{{controlCSS}}">
<a class="date-move-left" data-calendar-move="left" style="{{controlButtonCSS}}">{{{left}}}</a>
<div class="date-display" data-calendar-els="control-display" style="{{controlCSS}}"></div>
<a class="date-move-right" data-calendar-move="right" style="{{controlButtonCSS}}">{{{right}}}</a>
</div>
{{/control}}
<div class="calendar-body" data-calendar-els="body"></div>
</div>
`;
},
getFrame = function () {
var
data = jQuery.extend(true, {}, cfg, {
controlCSS: {},
controlButtonCSS: {}
}),
tmpl = getFrameTmpl();
data.controlButtonCSS["height"] = data.controlCSS["height"] = U.cssNumber(cfg.dimensions.controlHeight);
data.controlButtonCSS["line-height"] = data.controlCSS["line-height"] = U.cssNumber(cfg.dimensions.controlHeight);
data.controlButtonCSS["width"] = U.cssNumber(cfg.dimensions.controlHeight);
data.controlCSS = U.css(data.controlCSS);
data.controlButtonCSS = U.css(data.controlButtonCSS);
try {
return ax5.mustache.render(tmpl, data);
}
finally {
data = null;
tmpl = null;
}
},
getDayTmpl = function () {
return `
<table data-calendar-table="day" cellpadding="0" cellspacing="0" style="width:100%;">
<thead>
<tr>
{{#weekNames}}
<td class="calendar-col-{{col}}" style="height: {{colHeadHeight}}">
{{label}}
</td>
{{/weekNames}}
</tr>
</thead>
<tbody>
<tr>
{{#list}}
{{#isStartOfWeek}}
{{^@first}}
</tr>
<tr>
{{/@first}}
{{/isStartOfWeek}}
<td class="calendar-col-{{col}}" style="{{itemStyles}}">
<a class="calendar-item-day {{addClass}}" <API key>="{{thisDate}}">
<span class="addon addon-header"></span>
{{thisDataLabel}}
<span class="addon addon-footer"></span>
</a>
</td>
{{/list}}
</tr>
</tbody>
</table>
`;
},
getMonthTmpl = function () {
return `
<table data-calendar-table="month" cellpadding="0" cellspacing="0" style="width:100%;">
<thead>
<tr>
<td class="calendar-col-0" colspan="3" style="height: {{colHeadHeight}}">
{{colHeadLabel}}
</td>
</tr>
</thead>
<tbody>
<tr>
{{#list}}
{{#isStartOfRow}}
{{^@first}}
</tr>
<tr>
{{/@first}}
{{/isStartOfRow}}
<td class="calendar-col-{{col}}" style="{{itemStyles}}">
<a class="calendar-item-month {{addClass}}" <API key>="{{thisMonth}}">
<span class="addon"></span>
{{thisMonthLabel}}
<span class="lunar"></span>
</a>
</td>
{{/list}}
</tr>
</tbody>
</table>
`;
},
getYearTmpl = function () {
return `
<table data-calendar-table="year" cellpadding="0" cellspacing="0" style="width:100%;">
<thead>
<tr>
<td class="calendar-col-0" colspan="4" style="height: {{colHeadHeight}}">
{{colHeadLabel}}
</td>
</tr>
</thead>
<tbody>
<tr>
{{#list}}
{{#isStartOfRow}}
{{^@first}}
</tr>
<tr>
{{/@first}}
{{/isStartOfRow}}
<td class="calendar-col-{{col}}" style="{{itemStyles}}">
<a class="calendar-item-year {{addClass}}" <API key>="{{thisYear}}">
<span class="addon"></span>
{{thisYearLabel}}
<span class="lunar"></span>
</a>
</td>
{{/list}}
</tr>
</tbody>
</table>
`;
},
setDisplay = function () {
var
myDate = U.date(cfg.displayDate),
yy = "",
mm = "",
yy1, yy2;
if (cfg.control) {
if (cfg.mode == "day" || cfg.mode == "d") {
yy = (cfg.control.yearTmpl) ? cfg.control.yearTmpl.replace('%s', myDate.getFullYear()) : myDate.getFullYear();
mm = (cfg.control.monthTmpl) ? cfg.control.monthTmpl.replace('%s', cfg.lang.months[myDate.getMonth()]) : cfg.lang.months[myDate.getMonth()];
this.$["control-display"].html((function () {
if (cfg.control.yearFirst) {
return '<span <API key>="year">' + yy + '</span>' +
'<span <API key>="month">' + mm + '</span>';
}
else {
return '<span <API key>="month">' + mm + '</span>' +
'<span <API key>="year">' + yy + '</span>';
}
})());
}
else if (cfg.mode == "month" || cfg.mode == "m") {
yy = (cfg.control.yearTmpl) ? cfg.control.yearTmpl.replace('%s', myDate.getFullYear()) : myDate.getFullYear();
this.$["control-display"].html('<span <API key>="year">' + yy + '</span>');
}
else if (cfg.mode == "year" || cfg.mode == "y") {
yy1 = (cfg.control.yearTmpl) ? cfg.control.yearTmpl.replace('%s', myDate.getFullYear() - 10) : myDate.getFullYear() - 10;
yy2 = (cfg.control.yearTmpl) ? cfg.control.yearTmpl.replace('%s', Number(myDate.getFullYear()) + 9) : Number(myDate.getFullYear()) + 9;
this.$["control-display"].html(yy1 + ' ~ ' + yy2);
}
this.$["control-display"].find('[<API key>]').on(cfg.clickEventName, (function (e) {
var target = U.findParentNode(e.target, function (target) {
if (target.getAttribute("<API key>")) {
return true;
}
}), mode;
if (target) {
mode = target.getAttribute("<API key>");
this.changeMode(mode);
}
target = null;
mode = null;
}).bind(this));
}
myDate = null;
yy = null;
mm = null;
yy1 = null;
yy2 = null;
return this;
},
printDay = function (nowDate) {
var
dotDate = U.date(nowDate),
monthStratDate = new Date(dotDate.getFullYear(), dotDate.getMonth(), 1, 12),
_today = cfg.displayDate,
tableStartDate = (function () {
var day = monthStratDate.getDay();
if (day == 0) day = 7;
try {
return U.date(monthStratDate, {add: {d: -day}});
}
finally {
day = null;
}
})(),
loopDate,
thisMonth = dotDate.getMonth(),
itemStyles = {},
i,
k,
frameWidth = this.$["body"].width(),
frameHeight = Math.floor(frameWidth * (6 / 7)), // 1week = 7days, 1month = 6weeks
data,
tmpl = getDayTmpl()
;
if (cfg.dimensions.height) {
frameHeight = U.number(cfg.dimensions.height) - U.number(cfg.dimensions.colHeadHeight);
}
itemStyles['height'] = Math.floor(frameHeight / 6) - U.number(cfg.dimensions.itemPadding) * 2 + 'px';
itemStyles['line-height'] = itemStyles['height'];
itemStyles['padding'] = U.cssNumber(cfg.dimensions.itemPadding);
data = {
weekNames: [].concat(ax5.info.weekNames),
list: []
};
data.weekNames.forEach(function (n) {
n.colHeadHeight = U.cssNumber(cfg.dimensions.colHeadHeight);
});
loopDate = tableStartDate;
i = 0;
while (i < 6) {
k = 0;
while (k < 7) {
var
thisDate = '' + U.date(loopDate, {"return": cfg.dateFormat}),
_date = {
'row': i,
'col': k,
isStartOfWeek: (k == 0),
thisDate: '' + thisDate,
thisDataLabel: cfg.lang.dayTmpl.replace('%s', loopDate.getDate()),
itemStyles: U.css(itemStyles),
addClass: (function () {
if (cfg.selectable) {
if (self.selectableMap[thisDate]) {
return ( loopDate.getMonth() == thisMonth ) ? "live" : "";
}
else {
return "disable";
}
}
else {
return ( loopDate.getMonth() == thisMonth ) ? ( thisDate == U.date(_today, {"return": "yyyyMMdd"}) ) ? "focus" : "live" : "";
}
})()
+ ' '
+ (function () {
return (self.markerMap[thisDate]) ? self.markerMap[thisDate].theme || cfg.defaultMarkerTheme : '';
})()
+ ' '
+ (function () {
return (self.selectionMap[thisDate]) ? "selected-day" : '';
})()
};
data.list.push(_date);
k++;
loopDate = U.date(loopDate, {add: {d: 1}});
thisDate = null;
_date = null;
}
i++;
}
this.$["body"].html(ax5.mustache.render(tmpl, data));
this.$["body"].find('[<API key>]').on(cfg.clickEventName, function (e) {
e = e || window.event;
onclick.call(self, e, 'date');
U.stopEvent(e);
});
this.printedDay = {
start: tableStartDate, end: loopDate
};
onStateChanged.call(this, null, {
self: this,
action: "printDay",
printedDay: this.printedDay
});
setDisplay.call(this);
dotDate = null;
monthStratDate = null;
_today = null;
tableStartDate = null;
loopDate = null;
thisMonth = null;
itemStyles = null;
i = null;
k = null;
frameWidth = null;
frameHeight = null;
data = null;
tmpl = null;
},
printMonth = function (nowDate) {
var
dotDate = U.date(nowDate),
nMonth = dotDate.getMonth(),
itemStyles = {},
i,
k,
m,
tableStartMonth,
frameWidth = this.$["body"].width(),
frameHeight = Math.floor(frameWidth * (6 / 7)),
data,
tmpl = getMonthTmpl()
;
if (cfg.dimensions.height) {
frameHeight = U.number(cfg.dimensions.height) - U.number(cfg.dimensions.colHeadHeight);
}
itemStyles['height'] = Math.floor(frameHeight / 4) - U.number(cfg.dimensions.itemPadding) * 2 + 'px';
itemStyles['line-height'] = itemStyles['height'];
itemStyles['padding'] = U.cssNumber(cfg.dimensions.itemPadding);
data = {
colHeadHeight: U.cssNumber(cfg.dimensions.colHeadHeight),
colHeadLabel: cfg.lang.monthHeading,
list: []
};
tableStartMonth = 0;
m = 0;
i = 0;
while (i < 4) {
k = 0;
while (k < 3) {
var
_month = {
row: i,
col: k,
isStartOfRow: (k == 0),
thisMonth: dotDate.getFullYear() + '-' + U.setDigit(m + 1, 2) + '-' + U.setDigit(dotDate.getDate(), 2),
thisMonthLabel: cfg.lang.months[m],
itemStyles: U.css(itemStyles),
addClass: (function () {
if (cfg.selectable) {
return (self.selectableMap[m]) ? 'live' : 'disable';
}
else {
return 'live';
}
})()
+ ' '
+ (function () {
return ( m == nMonth ) ? "focus" : "";
})()
+ ' '
+ (function () {
return (self.markerMap[m]) ? self.markerMap[m].theme || cfg.defaultMarkerTheme : '';
})()
};
data.list.push(_month);
m++;
k++;
_month = null;
}
i++;
}
this.$["body"].html(ax5.mustache.render(tmpl, data));
this.$["body"].find('[<API key>]').on(cfg.clickEventName, function (e) {
e = e || window.event;
onclick.call(self, e, 'month');
U.stopEvent(e);
});
this.printedDay = {
start: dotDate.getFullYear() + '-' + U.setDigit(tableStartMonth + 1, 2),
end: dotDate.getFullYear() + '-' + U.setDigit(m, 2)
};
onStateChanged.call(this, null, {
self: this,
action: "printMonth",
printedDay: this.printedDay
});
setDisplay.call(this);
dotDate = null;
nMonth = null;
itemStyles = null;
i = null;
k = null;
m = null;
tableStartMonth = null;
frameWidth = null;
frameHeight = null;
data = null;
tmpl = null;
},
printYear = function (nowDate) {
var
dotDate = U.date(nowDate),
nYear = dotDate.getFullYear(),
itemStyles = {},
i,
k,
y,
tableStartYear,
frameWidth = this.$["body"].width(),
frameHeight = Math.floor(frameWidth * (6 / 7)),
data,
tmpl = getYearTmpl()
;
if (cfg.dimensions.height) {
frameHeight = U.number(cfg.dimensions.height) - U.number(cfg.dimensions.colHeadHeight);
}
itemStyles['height'] = Math.floor(frameHeight / 5) - U.number(cfg.dimensions.itemPadding) * 2 + 'px';
itemStyles['line-height'] = itemStyles['height'];
itemStyles['padding'] = U.cssNumber(cfg.dimensions.itemPadding);
data = {
colHeadHeight: U.cssNumber(cfg.dimensions.colHeadHeight),
colHeadLabel: cfg.lang.yearHeading,
list: []
};
tableStartYear = nYear - 10;
y = nYear - 10;
i = 0;
while (i < 5) {
k = 0;
while (k < 4) {
var
_year = {
row: i,
col: k,
isStartOfRow: (k == 0),
thisYear: y + '-' + U.setDigit(dotDate.getMonth() + 1, 2) + '-' + U.setDigit(dotDate.getDate(), 2),
thisYearLabel: cfg.lang.yearTmpl.replace('%s', (y)),
itemStyles: U.css(itemStyles),
addClass: (function () {
if (cfg.selectable) {
return (self.selectableMap[y]) ? 'live' : 'disable';
}
else {
return 'live';
}
})()
+ ' '
+ (function () {
return ( y == nYear ) ? "focus" : "";
})()
+ ' '
+ (function () {
return (self.selectableMap[y]) ? self.selectableMap[y].theme || cfg.defaultMarkerTheme : '';
})()
};
data.list.push(_year);
y++;
k++;
_year = null;
}
i++;
}
this.$["body"].html(ax5.mustache.render(tmpl, data));
this.$["body"].find('[<API key>]').on(cfg.clickEventName, function (e) {
e = (e || window.event);
onclick.call(this, e, 'year');
U.stopEvent(e);
});
this.printedDay = {
start: tableStartYear, end: y - 1
};
onStateChanged.call(this, null, {
self: this,
action: "printYear",
printedDay: this.printedDay
});
setDisplay.call(this);
dotDate = null;
nYear = null;
itemStyles = null;
i = null;
k = null;
y = null;
tableStartYear = null;
frameWidth = null;
frameHeight = null;
data = null;
tmpl = null;
},
onclick = function (e, mode, target, value) {
var
removed,
dt,
selectable;
mode = mode || "date";
target = U.findParentNode(e.target, function (target) {
if (target.getAttribute("data-calendar-item-" + mode)) {
return true;
}
});
if (target) {
value = target.getAttribute("data-calendar-item-" + mode);
dt = U.date(value, {"return": cfg.dateFormat});
selectable = true;
selectableCount = (cfg.multipleSelect) ? (U.isNumber(cfg.multipleSelect)) ? cfg.multipleSelect : 2 : 1;
if (cfg.selectable) {
if (!self.selectableMap[dt]) selectable = false;
}
if (mode == "date") {
if (selectable) {
if (self.selection.length >= selectableCount) {
removed = self.selection.splice(0, self.selection.length - (selectableCount - 1));
removed.forEach(function (d) {
self.$["body"].find('[<API key>="' + U.date(d, {"return": cfg.dateFormat}) + '"]').removeClass("selected-day");
});
}
jQuery(target).addClass("selected-day");
self.selection.push(value);
if (self.onClick) {
self.onClick.call({
self: this, date: value, target: this.target, dateElement: target
});
}
}
}
else if (mode == "month") {
if (cfg.selectMode == "month") {
if (selectable) {
if (self.selection.length >= selectableCount) {
removed = self.selection.splice(0, self.selection.length - (selectableCount - 1));
removed.forEach(function (d) {
self.$["body"].find('[<API key>="' + U.date(d, {"return": 'yyyy-MM-dd'}) + '"]').removeClass("selected-month");
});
}
jQuery(target).addClass("selected-month");
self.selection.push(value);
if (self.onClick) {
self.onClick.call({
self: this, date: value, target: this.target, dateElement: target
});
}
}
}
else {
self.changeMode("day", value);
}
}
else if (mode == "year") {
if (cfg.selectMode == "year") {
if (selectable) {
if (self.selection.length >= selectableCount) {
removed = self.selection.splice(0, self.selection.length - (selectableCount - 1));
removed.forEach(function (d) {
self.$["body"].find('[<API key>="' + U.date(d, {"return": 'yyyy-MM-dd'}) + '"]').removeClass("selected-year");
});
}
jQuery(target).addClass("selected-year");
self.selection.push(value);
if (self.onClick) {
self.onClick.call({
self: this, date: value, target: this.target, dateElement: target
});
}
}
}
else {
self.changeMode("month", value);
}
}
}
mode = null;
target = null;
value = null;
removed = null;
dt = null;
selectable = null;
},
move = function (e, target, value) {
target = U.findParentNode(e.target, function (target) {
if (target.getAttribute("data-calendar-move")) {
return true;
}
});
if (target) {
value = target.getAttribute("data-calendar-move");
if (cfg.mode == "day") {
if (value == "left") {
cfg.displayDate = U.date(cfg.displayDate, {add: {m: -1}});
}
else {
cfg.displayDate = U.date(cfg.displayDate, {add: {m: 1}});
}
printDay.call(this, cfg.displayDate);
}
else if (cfg.mode == "month") {
if (value == "left") {
cfg.displayDate = U.date(cfg.displayDate, {add: {y: -1}});
}
else {
cfg.displayDate = U.date(cfg.displayDate, {add: {y: 1}});
}
printMonth.call(this, cfg.displayDate);
}
else if (cfg.mode == "year") {
if (value == "left") {
cfg.displayDate = U.date(cfg.displayDate, {add: {y: -10}});
}
else {
cfg.displayDate = U.date(cfg.displayDate, {add: {y: 10}});
}
printYear.call(this, cfg.displayDate);
}
}
target = null;
value = null;
},
applyMarkerMap = function () {
setTimeout((function () {
if (cfg.mode === "day" || cfg.mode === "d") {
for (var k in this.markerMap) {
this.$["body"].find('[<API key>="' + k + '"]').addClass(this.markerMap[k].theme || cfg.defaultMarkerTheme);
}
}
}).bind(this));
},
applySelectionMap = function () {
setTimeout((function () {
for (var k in this.selectionMap) {
this.$["body"].find('[<API key>="' + k + '"]').addClass("selected-day");
}
}).bind(this));
},
applyPeriodMap = function () {
setTimeout((function () {
if (cfg.mode === "day" || cfg.mode === "d") {
for (var k in this.periodMap) {
if (this.periodMap[k].label) {
this.$["body"].find('[<API key>="' + k + '"]').find(".addon-footer").html(this.periodMap[k].label);
}
this.$["body"].find('[<API key>="' + k + '"]').addClass(this.periodMap[k].theme);
}
}
}).bind(this));
},
clearPeriodMap = function () {
if (cfg.mode === "day" || cfg.mode === "d") {
for (var k in this.periodMap) {
this.$["body"].find('[<API key>="' + k + '"]').find(".addon-footer").empty();
this.$["body"].find('[<API key>="' + k + '"]').removeClass(this.periodMap[k].theme);
}
}
};
/**
* Preferences of calendar UI
* @method ax5calendar.setConfig
* @param {Object} config -
* @param {Element|nodelist} config.target
* @param {String} [config.mode=day|month|year]
* @param {Function} [config.onClick}
* @returns {ax5calendar}
* @example
* ```js
* var myCalendar = new ax5.ui.calendar();
* myCalendar.setConfig({
* target: $("#target"),
* mode: "day"
* });
* ```
*/
//== class body start
this.init = function () {
// after setConfig();
this.onStateChanged = cfg.onStateChanged;
this.onClick = cfg.onClick;
if (!cfg.target) {
console.log(ax5.info.getError("ax5calendar", "401", "setConfig"));
}
this.target = jQuery(cfg.target);
cfg.displayDate = U.date(cfg.displayDate);
this.target.html(getFrame.call(this));
this.$ = {
"root": this.target.find('[data-calendar-els="root"]'),
"control": this.target.find('[data-calendar-els="control"]'),
"control-display": this.target.find('[data-calendar-els="control-display"]'),
"body": this.target.find('[data-calendar-els="body"]')
};
if (cfg.control) {
this.$["control"].find('[data-calendar-move]').on(cfg.clickEventName, (function (e) {
move.call(this, e || window.event);
}).bind(this));
}
// collect selectableMap
if (cfg.selection) {
this.setSelection(cfg.selection, false);
}
// collect selectableMap
if (cfg.selectable) {
this.setSelectable(cfg.selectable, false);
}
// collect markerMap
if (cfg.marker) {
this.setMarker(cfg.marker, false);
}
setTimeout((function () {
if (cfg.mode === "day" || cfg.mode === "d") {
printDay.call(this, cfg.displayDate);
}
else if (cfg.mode === "month" || cfg.mode === "m") {
printMonth.call(this, cfg.displayDate);
}
else if (cfg.mode === "year" || cfg.mode === "y") {
printYear.call(this, cfg.displayDate);
}
}).bind(this));
};
/**
* @method ax5calendar.changeMode
* @param {String} mode
* @param {String} changeDate
* @returns {ax5calendar}
*/
this.changeMode = function (mode, changeDate) {
if (typeof changeDate != "undefined") cfg.displayDate = changeDate;
if (mode) cfg.mode = mode;
this.$["body"].removeClass("fadein").addClass("fadeout");
setTimeout((function () {
if (cfg.mode == "day" || cfg.mode == "d") {
printDay.call(this, cfg.displayDate);
}
else if (cfg.mode == "month" || cfg.mode == "m") {
printMonth.call(this, cfg.displayDate);
}
else if (cfg.mode == "year" || cfg.mode == "y") {
printYear.call(this, cfg.displayDate);
}
this.$["body"].removeClass("fadeout").addClass("fadein");
}).bind(this), cfg.animateTime);
return this;
};
/**
* @method ax5calendar.setSelection
* @param {Array} selection
* @returns {ax5calendar}
* @example
* ```
*
* ```
*/
this.setSelection = (function () {
self.selectionMap = {};
var processor = {
'arr': function (v, map, count) {
map = {};
if (!U.isArray(v)) return map;
self.selection = v = v.splice(0, count);
v.forEach(function (n) {
if (U.isDate(n))
n = U.date(n, {'return': cfg.dateFormat});
map[n] = true;
});
return map;
}
};
return function (selection, isPrint) {
var
result = {}
;
selectableCount = (cfg.multipleSelect) ? (U.isNumber(cfg.multipleSelect)) ? cfg.multipleSelect : 2 : 1;
if (cfg.selection = selection) {
if (U.isArray(selection)) {
result = processor.arr(selection, {}, selectableCount);
} else {
return this;
}
}
this.selectionMap = jQuery.extend({}, result);
if (isPrint !== false) applySelectionMap.call(this);
result = null;
return this;
};
})();
/**
* @method ax5calendar.getSelection
*/
this.getSelection = function () {
return this.selection;
};
/**
* @method ax5calendar.setSelectable
*/
this.setSelectable = (function () {
self.selectableMap = {};
var processor = {
'arr': function (v, map) {
map = {};
if (!U.isArray(v)) return map;
v.forEach(function (n) {
if (U.isDate(n))
n = U.date(n, {'return': cfg.dateFormat});
map[n] = true;
});
return map;
},
'obj': function (v, map) {
map = {};
if (U.isArray(v)) return map;
if (v.range) return map;
for (var k in v) {
map[k] = v[k];
}
return map;
},
'range': function (v, map) {
map = {};
if (U.isArray(v)) return map;
if (!v.range) return map;
v.range.forEach(function (n) {
if (U.isDateFormat(n.from) && U.isDateFormat(n.to)) {
for (var d = U.date(n.from); d <= U.date(n.to); d.setDate(d.getDate() + 1)) {
map[U.date(d, {"return": cfg.dateFormat})] = true;
}
}
else {
for (var i = n.from; i <= n.to; i++) {
map[i] = true;
}
}
});
return map;
}
};
return function (selectable, isPrint) {
var
key,
result = {}
;
if (cfg.selectable = selectable) {
if (U.isArray(selectable)) {
result = processor.arr(selectable);
}
else {
for (key in processor) {
if (selectable[key]) {
result = processor[key](selectable);
break;
}
}
if (Object.keys(result).length === 0) {
result = processor.obj(selectable);
}
}
}
this.selectableMap = result;
if (isPrint !== false) this.changeMode();
return this;
};
})();
/**
* @method ax5calendar.setMarker
*/
this.setMarker = (function () {
self.markerMap = {};
var processor = {
'obj': function (v, map) {
map = {};
if (U.isArray(v)) return map;
if (v.range) return map;
for (var k in v) {
map[k] = v[k];
}
v = null;
return map;
},
'range': function (v, map) {
map = {};
if (U.isArray(v)) return map;
if (!v.range) return map;
v.range.forEach(function (n) {
if (U.isDateFormat(n.from) && U.isDateFormat(n.to)) {
for (var d = U.date(n.from); d <= U.date(n.to); d.setDate(d.getDate() + 1)) {
map[U.date(d, {"return": cfg.dateFormat})] = {theme: n.theme, label: n.label};
}
}
else {
for (var i = n.from; i <= n.to; i++) {
map[i] = {theme: n.theme, label: n.label};
}
}
});
v = null;
return map;
}
};
return function (marker, isApply) {
var
key,
result = {}
;
if (cfg.marker = marker) {
for (key in processor) {
if (marker[key]) {
result = processor[key](marker);
break;
}
}
if (Object.keys(result).length === 0) {
result = processor.obj(marker);
}
}
this.markerMap = result;
if (isApply !== false) applyMarkerMap.call(this);
return this;
};
})();
/**
* @method ax5calendar.setPeriod
*/
this.setPeriod = (function () {
self.periodMap = {};
var processor = {
'range': function (v, map) {
map = {};
if (U.isArray(v)) return map;
if (!v.range) return map;
v.range.forEach(function (n) {
if (U.isDateFormat(n.from) && U.isDateFormat(n.to)) {
for (var d = new Date(U.date(n.from)); d <= U.date(n.to); d.setDate(d.getDate() + 1)) {
if (d.getTime() == U.date(n.from).getTime()) {
map[U.date(d, {"return": cfg.dateFormat})] = {theme: n.theme || cfg.defaultPeriodTheme, label: n.fromLabel};
} else if (d.getTime() == U.date(n.to).getTime()) {
map[U.date(d, {"return": cfg.dateFormat})] = {theme: n.theme || cfg.defaultPeriodTheme, label: n.toLabel};
} else {
map[U.date(d, {"return": cfg.dateFormat})] = {theme: n.theme || cfg.defaultPeriodTheme};
}
}
}
});
v = null;
return map;
}
};
return function (period, isApply) {
var
key,
result = {}
;
if (isApply !== false) {
clearPeriodMap.call(this);
}
if (cfg.period = period) {
result = processor.range(period);
}
this.periodMap = result;
//console.log(this.periodMap);
if (isApply !== false) {
applyPeriodMap.call(this);
}
return this;
};
})();
this.main = (function () {
UI.calendar_instance = UI.calendar_instance || [];
UI.calendar_instance.push(this);
if (arguments && U.isObject(arguments[0])) {
this.setConfig(arguments[0]);
}
}).apply(this, arguments);
};
return ax5calendar;
})());
})(); |
package org.tsaikd.java.weblire.ext;
import net.semanticmetadata.lire.imageanalysis.ColorLayout;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class ColorLayoutext extends ColorLayout {
static Log log = LogFactory.getLog(ColorLayoutext.class);
public double getSumY() {
double result = 0;
for (int i=0 ; i<numYCoeff ; i++) {
result += YCoeff[i];
}
return result;
}
public double getStdDiffPow2Y(double sum) {
double result = 0;
double avg = sum / numYCoeff;
for (int i=0 ; i<numYCoeff ; i++) {
result += (YCoeff[i] - avg) * (YCoeff[i] - avg);
}
return result;
}
public double getSumC() {
double result = 0;
for (int i=0 ; i<numCCoeff ; i++) {
result += CbCoeff[i];
result += CrCoeff[i];
}
return result;
}
public double getStdDiffPow2C(double sum) {
double result = 0;
double avg = sum / numCCoeff / 2;
for (int i=0 ; i<numCCoeff ; i++) {
result += (CbCoeff[i] - avg) * (CbCoeff[i] - avg);
result += (CrCoeff[i] - avg) * (CrCoeff[i] - avg);
}
return result;
}
} |
package org.sonar.scanner.scan;
import java.util.Map;
import org.sonar.api.config.Encryption;
import org.sonar.api.config.PropertyDefinitions;
import org.sonar.scanner.config.<API key>;
public class <API key> extends <API key> {
public <API key>(PropertyDefinitions propertyDefinitions, Encryption encryption, Map<String, String> props) {
super(propertyDefinitions, encryption, props);
}
} |
#include "<API key>.h"
#include "<API key>.h"
#include <QDebug>
#include <QNetworkReply>
#include <QXmlStreamReader>
namespace QtAws {
namespace EventBridge {
/*!
* Constructs a <API key> object for \a reply to \a request, with parent \a parent.
*/
<API key>::<API key>(
const <API key> &request,
QNetworkReply * const reply,
QObject * const parent)
: EventBridgeResponse(new <API key>(this), parent)
{
setRequest(new <API key>(request));
setReply(reply);
}
/*!
* \reimp
*/
const <API key> * <API key>::request() const
{
Q_D(const <API key>);
return static_cast<const <API key> *>(d->request);
}
/*!
* \reimp
* Parses a successful EventBridge <API key> \a response.
*/
void <API key>::parseSuccess(QIODevice &response)
{
//Q_D(<API key>);
QXmlStreamReader xml(&response);
@todo
}
/*!
* \class QtAws::EventBridge::<API key>
* \brief The <API key> class provides private implementation for <API key>.
* \internal
*
* \inmodule QtAwsEventBridge
*/
/*!
* Constructs a <API key> object with public implementation \a q.
*/
<API key>::<API key>(
<API key> * const q) : <API key>(q)
{
}
/*!
* Parses a EventBridge <API key> response element from \a xml.
*/
void <API key>::<API key>(QXmlStreamReader &xml)
{
Q_ASSERT(xml.name() == QLatin1String("<API key>"));
Q_UNUSED(xml) ///< @todo
}
} // namespace EventBridge
} // namespace QtAws |
package fr.unice.polytech.soa1.cookbook.rest.Shoes;
import org.json.JSONArray;
import org.json.JSONString;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.Collection;
@Path("/customers")
// Here we generate JSON data from scratch, one should use a framework instead
@Produces(MediaType.APPLICATION_JSON)
public class CustomerService implements ICustomer{
public Response createNewCustomer(String name, String f, String e, int p, Adress s, Adress b) {
if(Storage.read(name) != null) {
return Response.status(Response.Status.CONFLICT)
.entity("\"Existing name " + name + "\"")
.build();
}
Storage.create(name, f, e, p, s, b);
return Response.ok().build();
}
public Response <API key>() {
Collection<Customer> cust = Storage.findAll();
JSONArray result = new JSONArray();
for(Customer c: cust) {
result.put(c.getName());
}
return Response.ok().entity(result.toString(2)).build();
}
public Response generateIdentifier(String name) {
if(Storage.read(name) == null) {
return Response.status(Response.Status.NOT_FOUND).build();
}
String value = Storage.read(name).run();
return Response.ok().entity("\""+value+"\"").build();
}
public Response deleteCustomer(String name) {
if(Storage.read(name) == null) {
return Response.status(Response.Status.NOT_FOUND).build();
}
Storage.delete(name);
return Response.ok().build();
}
public Response addToCart(String name, String ref) {
if(Storage.read(name) == null) {
return Response.status(Response.Status.NOT_FOUND).build();
}
Storage.read(name).addProduct(ref);
return Response.ok().build();
}
public Response deleteFromCart(String name, String ref) {
if(Storage.read(name) == null) {
return Response.status(Response.Status.NOT_FOUND).build();
}
Storage.read(name).deleteProduct(ref);
return Response.ok().build();
}
static {
Storage.create("aaa", "firstname", "email", 0410121416, new Adress(10,"rue lamartine", 05000, "nice", "france"),new Adress(10,"rue lamartine", 05000, "nice", "france"));
}
} |
<?php
namespace xecon\account;
use pocketmine\Server;
use xecon\modifier\AccountModifier;
use xecon\xEcon;
final class Account{
const PATH_SEPARATOR = ":";
/** @var AccountOwner */
private $owner;
/** @var string */
private $name;
/** @var int */
private $lastFinalize;
/** @var float */
private $balance;
/** @var AccountModifier[]|null[] */
private $modifiers = [];
/** @var int */
private $loadTime;
private $balanceChanged = false;
private $removedModifiers = [];
private $newModifiers = [];
public function __construct(AccountOwner $owner, string $name, int $lastFinalize, float $balance){
$this->owner = $owner;
xEcon::validate(mb_strlen($name) <= 40, "Account name is too long");
$this->name = $name;
$this->lastFinalize = $lastFinalize;
$this->balance = $balance;
$this->loadTime = time();
}
/**
* @internal Only to be called from Database::loadAccounts()
*
* @param string $modifierName
* @param int $additionTime
*/
public function initModifier(string $modifierName, int $additionTime){
$this->modifiers[$modifierName] = AccountModifier::getModifier($this, $modifierName, $additionTime);
}
/**
* @internal Only to be called from Database::loadAccounts()
*/
public function inited(){
foreach($this->modifiers as $modifier){
$modifier->onLoad();
}
}
public function getServer() : Server{
return $this->owner->getPlugin()->getServer();
}
public function getPlugin() : xEcon{
return $this->owner->getPlugin();
}
public function getOwner() : AccountOwner{
return $this->owner;
}
public function getName() : string{
return $this->name;
}
public function getAbsoluteName(){
return $this->getOwner()->getType() . Account::PATH_SEPARATOR . $this->getOwner()->getName() . Account::PATH_SEPARATOR . $this->name;
}
public function getLoadTime(){
return $this->loadTime;
}
public function getLastFinalize(){
return $this->lastFinalize;
}
public function getBalance() : float{
return $this->balance;
}
public function setBalance(float $balance){
foreach($this->modifiers as $modifier){
if($modifier->isDummyAccount() || !$modifier->canSetBalance($balance)){
return;
}
}
$this->balance = $balance;
$this->balanceChanged = true;
}
/**
* @return string[]
*/
public function getModifiers() : array{
return array_keys($this->modifiers);
}
public function applyModifier(AccountModifier $modifier){
if($modifier->getAccount() !== $this){
throw new \RuntimeException("AccountModifier is applied to the wrong account");
}
if(isset($this->modifiers[$modifier->getName()])){
throw new \RuntimeException("Attempt to apply an existing modifier to an account");
}
$this->modifiers[$modifier->getName()] = $modifier;
$this->newModifiers[$modifier->getName()] = true;
$modifier->onApply();
}
public function removeModifier(AccountModifier $modifier){
if($modifier->getAccount() !== $this){
throw new \RuntimeException("AccountModifier is applied to the wrong account");
}
$modifier->onRemove();
unset($this->modifiers[$modifier->getName()]);
if(isset($this->newModifiers[$modifier->getName()])){
unset($this->newModifiers[$modifier->getName()]);
}else{
$this->removedModifiers[$modifier->getName()] = true;
}
$modifier->invalidate();
}
public function finalize(){
$this->lastFinalize = time();
// TODO delete removed modifiers
// TODO save new modifiers
foreach($this->modifiers as $modifier){
$modifier->onFinalize();
}
// TODO check balanceChanged
}
} |
using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using Lidgren.Network;
using StardewValley.Network;
namespace StardewModdingAPI.Framework.Networking
{
<summary>A multiplayer server used to connect to an incoming player. This is an implementation of <see cref="LidgrenServer"/> that adds support for SMAPI's metadata context exchange.</summary>
internal class SLidgrenServer : LidgrenServer
{
<summary>SMAPI's implementation of the game's core multiplayer logic.</summary>
private readonly SMultiplayer Multiplayer;
<summary>A callback to raise when receiving a message. This receives the incoming message, a method to send a message, and a callback to run the default logic.</summary>
private readonly Action<IncomingMessage, Action<OutgoingMessage>, Action> OnProcessingMessage;
<summary>Construct an instance.</summary>
<param name="multiplayer">SMAPI's implementation of the game's core multiplayer logic.</param>
<param name="gameServer">The underlying game server.</param>
<param name="onProcessingMessage">A callback to raise when receiving a message. This receives the incoming message, a method to send a message, and a callback to run the default logic.</param>
public SLidgrenServer(IGameServer gameServer, SMultiplayer multiplayer, Action<IncomingMessage, Action<OutgoingMessage>, Action> onProcessingMessage)
: base(gameServer)
{
this.Multiplayer = multiplayer;
this.OnProcessingMessage = onProcessingMessage;
}
<summary>Parse a data message from a client.</summary>
<param name="rawMessage">The raw network message to parse.</param>
[SuppressMessage("ReSharper", "<API key>", Justification = "The callback is invoked synchronously.")]
protected override void <API key>(NetIncomingMessage rawMessage)
{
// add hook to call multiplayer core
NetConnection peer = rawMessage.SenderConnection;
using (IncomingMessage message = new IncomingMessage())
using (Stream readStream = new NetBufferReadStream(rawMessage))
using (BinaryReader reader = new BinaryReader(readStream))
{
while (rawMessage.LengthBits - rawMessage.Position >= 8)
{
message.Read(reader);
NetConnection connection = rawMessage.SenderConnection; // don't pass rawMessage into context because it gets reused
this.OnProcessingMessage(message, outgoing => this.sendMessage(connection, outgoing), () =>
{
if (this.peers.ContainsLeft(message.FarmerID) && this.peers[message.FarmerID] == peer)
this.gameServer.<API key>(message);
else if (message.MessageType == StardewValley.Multiplayer.playerIntroduction)
{
NetFarmerRoot farmer = this.Multiplayer.readFarmer(message.Reader);
this.gameServer.<API key>("", this.getConnectionId(rawMessage.SenderConnection), farmer, msg => this.sendMessage(peer, msg), () => this.peers[farmer.Value.UniqueMultiplayerID] = peer);
}
});
}
}
}
}
} |
#include "../../core.h"
#include "../../cache.h"
static GList * <API key> (cb_object * capo)
{
GList * converter_list = NULL;
if (capo->s && capo->s->local_db != NULL)
{
gint counter = 0;
GlyrMemCache * head = glyr_db_lookup (capo->s->local_db,capo->s);
while (head != NULL)
{
if (counter < capo->s->number)
{
converter_list = g_list_prepend (converter_list,head);
head->cached = TRUE;
head = head->next;
counter++;
}
else
{
GlyrMemCache * to_delete = head;
head = head->next;
DL_free (to_delete);
}
}
}
return converter_list;
}
static const gchar * local_provider_url (GlyrQuery * sets)
{
return OFFLINE_PROVIDER;
}
MetaDataSource local_provider_src =
{
.name = "local",
.key = 'l',
.parser = <API key>,
.get_url = local_provider_url,
.type = GLYR_GET_ANY,
.quality = 4200,
.speed = 4200,
.endmarker = NULL,
.free_url = false
}; |
#ifndef <API key>
#define <API key>
#include "athenaresponse.h"
#include "<API key>.h"
namespace QtAws {
namespace Athena {
class <API key>;
class QTAWSATHENA_EXPORT <API key> : public AthenaResponse {
Q_OBJECT
public:
<API key>(const <API key> &request, QNetworkReply * const reply, QObject * const parent = 0);
virtual const <API key> * request() const Q_DECL_OVERRIDE;
protected slots:
virtual void parseSuccess(QIODevice &response) Q_DECL_OVERRIDE;
private:
Q_DECLARE_PRIVATE(<API key>)
Q_DISABLE_COPY(<API key>)
};
} // namespace Athena
} // namespace QtAws
#endif |
@javax.xml.bind.annotation.XmlSchema(namespace = "http://iuclid6.echa.europa.eu/namespaces/<API key>/2.0", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
package eu.europa.echa.iuclid6.namespaces.<API key>._2; |
class CreateServicesUsers < ActiveRecord::Migration
def self.up
create_table :services_users, :id => false do |t|
t.integer :user_id
t.integer :service_id
end
end
def self.down
drop_table :services_users
end
end |
DELIMITER
DROP PROCEDURE IF EXISTS <API key>;
CREATE PROCEDURE `<API key>`()
BEGIN
DECLARE vIndexPs INT DEFAULT 0;
DECLARE vIndexOs INT DEFAULT 0;
DECLARE vIndexSp INT DEFAULT 0;
SELECT COUNT(*)
INTO vIndexPs
FROM information_schema.statistics
WHERE table_schema = DATABASE()
AND table_name = 'triple'
AND index_name = 'ps';
IF vIndexPs > 0 THEN
DROP INDEX ps ON triple;
END IF;
SELECT COUNT(*)
INTO vIndexOs
FROM information_schema.statistics
WHERE table_schema = DATABASE()
AND table_name = 'triple'
AND index_name = 'os';
IF vIndexOs > 0 THEN
DROP INDEX os ON triple;
END IF;
SELECT COUNT(*)
INTO vIndexSp
FROM information_schema.statistics
WHERE table_schema = DATABASE()
AND table_name = 'triple'
AND index_name = 'sp';
IF vIndexSp > 0 THEN
DROP INDEX sp ON triple;
END IF;
-- count all sub occurrences
UPDATE dict_sub d SET sub_count = (SELECT count(*) FROM triple t WHERE t.sub_id = d.sub_id);
-- count all prop occurences
-- first we ensure that there is the correct index
CREATE INDEX ps ON triple (prop_id,sub_id);
UPDATE dict_prop d
SET prop_count = (SELECT count(*) FROM triple t WHERE t.prop_id = d.prop_id),
prop_count_dist = (SELECT count(distinct(t.sub_id)) FROM triple t WHERE t.prop_id = d.prop_id);
-- count all obj occurrences
-- first we ensure that there is the correct index
CREATE INDEX os ON triple (obj_id,sub_id);
UPDATE dict_obj d SET obj_count = (SELECT count(*) FROM triple t WHERE t.obj_id = d.obj_id);
-- other indices
CREATE INDEX sp ON triple (sub_id,prop_id);
END
DELIMITER ; |
package nl.welteninstituut.tel.la.bigquery;
import com.google.api.client.extensions.appengine.http.UrlFetchTransport;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.extensions.appengine.auth.oauth2.<API key>;
import com.google.api.client.http.<API key>;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.bigquery.Bigquery;
import java.util.Arrays;
public class Common {
private static final String SCOPE = "https:
private static final HttpTransport TRANSPORT = new UrlFetchTransport();
private static final JsonFactory JSON_FACTORY = new JacksonFactory();
public final static String DONE = "DONE";
// @VisibleForTesting
static Bigquery bigquery = new Bigquery(TRANSPORT, JSON_FACTORY, <API key>());
private static <API key> <API key>() {
if (System.getProperty("OAUTH_ACCESS_TOKEN") != null) {
return new GoogleCredential().setAccessToken(System.getProperty("OAUTH_ACCESS_TOKEN"));
}
return new <API key>(Arrays.asList(new String[]{SCOPE}));
}
} |
// This file is part of the go-ethereum library.
// The go-ethereum library is free software: you can redistribute it and/or modify
// (at your option) any later version.
// The go-ethereum library is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// Contains the Whisper protocol Topic element. For formal details please see
// the specs at https://github.com/ethereum/wiki/wiki/<API key>#topics.
package whisperv2
import "github.com/kejace/go-ethereum/crypto"
// Topic represents a cryptographically secure, probabilistic partial
// classifications of a message, determined as the first (left) 4 bytes of the
// SHA3 hash of some arbitrary data given by the original author of the message.
type Topic [4]byte
// NewTopic creates a topic from the 4 byte prefix of the SHA3 hash of the data.
// Note, empty topics are considered the wildcard, and cannot be used in messages.
func NewTopic(data []byte) Topic {
prefix := [4]byte{}
copy(prefix[:], crypto.Keccak256(data)[:4])
return Topic(prefix)
}
// NewTopics creates a list of topics from a list of binary data elements, by
// iteratively calling NewTopic on each of them.
func NewTopics(data ...[]byte) []Topic {
topics := make([]Topic, len(data))
for i, element := range data {
topics[i] = NewTopic(element)
}
return topics
}
// NewTopicFromString creates a topic using the binary data contents of the
// specified string.
func NewTopicFromString(data string) Topic {
return NewTopic([]byte(data))
}
// <API key> creates a list of topics from a list of textual data
// elements, by iteratively calling NewTopicFromString on each of them.
func <API key>(data ...string) []Topic {
topics := make([]Topic, len(data))
for i, element := range data {
topics[i] = NewTopicFromString(element)
}
return topics
}
// String converts a topic byte array to a string representation.
func (self *Topic) String() string {
return string(self[:])
}
// topicMatcher is a filter expression to verify if a list of topics contained
// in an arriving message matches some topic conditions. The topic matcher is
// built up of a list of conditions, each of which must be satisfied by the
// corresponding topic in the message. Each condition may require: a) an exact
// topic match; b) a match from a set of topics; or c) a wild-card matching all.
// If a message contains more topics than required by the matcher, those beyond
// the condition count are ignored and assumed to match.
// Consider the following sample topic matcher:
// sample := {
// {TopicA1, TopicA2, TopicA3},
// {TopicB},
// nil,
// {TopicD1, TopicD2}
// In order for a message to pass this filter, it should enumerate at least 4
// topics, the first any of [TopicA1, TopicA2, TopicA3], the second mandatory
// "TopicB", the third is ignored by the filter and the fourth either "TopicD1"
// or "TopicD2". If the message contains further topics, the filter will match
// them too.
type topicMatcher struct {
conditions []map[Topic]struct{}
}
// newTopicMatcher create a topic matcher from a list of topic conditions.
func newTopicMatcher(topics ...[]Topic) *topicMatcher {
matcher := make([]map[Topic]struct{}, len(topics))
for i, condition := range topics {
matcher[i] = make(map[Topic]struct{})
for _, topic := range condition {
matcher[i][topic] = struct{}{}
}
}
return &topicMatcher{conditions: matcher}
}
// <API key> create a topic matcher from a list of binary conditions.
func <API key>(data ...[][]byte) *topicMatcher {
topics := make([][]Topic, len(data))
for i, condition := range data {
topics[i] = NewTopics(condition...)
}
return newTopicMatcher(topics...)
}
// <API key> creates a topic matcher from a list of textual
// conditions.
func <API key>(data ...[]string) *topicMatcher {
topics := make([][]Topic, len(data))
for i, condition := range data {
topics[i] = <API key>(condition...)
}
return newTopicMatcher(topics...)
}
// Matches checks if a list of topics matches this particular condition set.
func (self *topicMatcher) Matches(topics []Topic) bool {
// Mismatch if there aren't enough topics
if len(self.conditions) > len(topics) {
return false
}
// Check each topic condition for existence (skip wild-cards)
for i := 0; i < len(topics) && i < len(self.conditions); i++ {
if len(self.conditions[i]) > 0 {
if _, ok := self.conditions[i][topics[i]]; !ok {
return false
}
}
}
return true
} |
ravenous_torton = Creature:new {
objectName = "@mob/creature_names:ravenous_torton",
socialGroup = "torton",
pvpFaction = "",
faction = "",
level = 34,
chanceHit = 0.4,
damageMin = 325,
damageMax = 360,
baseXp = 3370,
baseHAM = 8600,
baseHAMmax = 10500,
armor = 0,
resists = {20,20,20,-1,-1,45,45,80,-1},
meatType = "meat_carnivore",
meatAmount = 1000,
hideType = "hide_wooly",
hideAmount = 1000,
boneType = "bone_mammal",
boneAmount = 1000,
milk = 0,
tamingChance = 0.25,
ferocity = 9,
pvpBitmask = AGGRESSIVE + ATTACKABLE + ENEMY,
creatureBitmask = PACK + HERD,
optionsBitmask = 128,
diet = CARNIVORE,
templates = {"object/mobile/torton_hue.iff"},
<API key> = "object/intangible/pet/torton_hue.iff",
lootGroups = {},
weapons = {},
<API key> = "",
attacks = {
{"dizzyattack","dizzyChance=50"},
{"knockdownattack","knockdownChance=50"}
}
}
CreatureTemplates:addCreatureTemplate(ravenous_torton, "ravenous_torton") |
import os
import imp
util = imp.load_source("__pyblish_util", os.path.join(__file__, "..", "..", "__pyblish_util.py"))
util.wrap_module(__name__, "pyblish-base") |
package io.github.albertus82.jface.preference.field;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.eclipse.swt.events.FocusAdapter;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Text;
import io.github.albertus82.jface.listener.ByteVerifyListener;
import io.github.albertus82.util.Supplier;
import io.github.albertus82.util.logging.LoggerFactory;
public class ByteFieldEditor extends <API key><Byte> {
private static final Logger log = LoggerFactory.getLogger(ByteFieldEditor.class);
private static final int DEFAULT_TEXT_LIMIT = Byte.toString(Byte.MAX_VALUE).length();
public ByteFieldEditor(final String name, final String labelText, final Composite parent) {
super(name, labelText, parent);
setMinValidValue((byte) 0); // Positive by default
setMaxValidValue(Byte.MAX_VALUE); // Not so ugly (127)
getTextControl().addVerifyListener(new ByteVerifyListener(new Supplier<Boolean>() {
@Override
public Boolean get() {
return getMinValidValue() == null || getMinValidValue().byteValue() < 0;
}
}));
getTextControl().addFocusListener(new ByteFocusListener());
}
@Override
protected int getDefaultTextLimit() {
return DEFAULT_TEXT_LIMIT;
}
@Override
protected void doLoad() {
super.doLoad();
final Text text = getTextControl();
if (text != null) {
String value;
try {
value = Byte.valueOf(getPreferenceStore().getString(getPreferenceName()).trim()).toString();
}
catch (final <API key> e) {
log.log(Level.FINEST, "The value provided does not contain a parsable byte:", e);
value = "";
}
text.setText(value);
oldValue = value;
}
updateFontStyle();
}
@Override
protected void doStore() {
final Text text = getTextControl();
if (text != null) {
if (text.getText().isEmpty() && <API key>()) {
getPreferenceStore().setValue(getPreferenceName(), "");
}
else {
final Byte value = Byte.valueOf(text.getText());
getPreferenceStore().setValue(getPreferenceName(), value.toString());
}
}
}
@Override
protected String getDefaultValue() {
final String defaultValue = super.getDefaultValue();
try {
return Byte.valueOf(defaultValue).toString();
}
catch (final <API key> e) {
log.log(Level.FINEST, "The value provided does not contain a parsable byte:", e);
return "";
}
}
@Override
public Byte getNumberValue() {
return Byte.valueOf(getStringValue());
}
protected class ByteFocusListener extends FocusAdapter {
@Override
public void focusLost(final FocusEvent fe) {
final Text text = (Text) fe.widget;
final String oldText = text.getText();
try {
final String newText = Byte.toString(Byte.parseByte(oldText));
if (!oldText.equals(newText)) {
text.setText(newText);
}
valueChanged();
}
catch (final Exception e) {
log.log(Level.FINE, "Cannot change the value of the field:", e);
}
}
}
} |
#pragma once
#include "message_channel.h"
#include "service_debug.h"
#include "protocol_defs.h"
#include "ping.h"
#include "chunked_transfer.h"
#include "spark_descriptor.h"
#include "<API key>.h"
#include "functions.h"
#include "events.h"
#include "publisher.h"
#include "subscriptions.h"
#include "variables.h"
#include "hal_platform.h"
#include "timesyncmanager.h"
namespace particle
{
namespace protocol
{
/**
* Tie ALL the bits together.
*/
class Protocol
{
/**
* The message channel that sends and receives message packets.
*/
MessageChannel& channel;
/**
* The tick time of the last communication with the cloud.
* todo - move this into the message channel?
*/
system_tick_t last_message_millis;
/**
* The product_id represented by this device. set_product_id()
*/
product_id_t product_id;
/**
* The product version for this device.
*/
<API key> <API key>;
/**
* Descriptor callbacks that provide externally hosted functions and variables.
*/
SparkDescriptor descriptor;
/**
* Functional callbacks that provide key system services to this communications layer.
*/
SparkCallbacks callbacks;
/**
* Application-level callbacks.
*/
<API key> handlers;
/**
* Manages Ping functionality.
*/
Pinger pinger;
/**
* Manages chunked file transfer functionality.
*/
ChunkedTransfer chunkedTransfer;
class <API key> : public ChunkedTransfer::Callbacks {
SparkCallbacks* callbacks;
public:
void init(SparkCallbacks* callbacks) {
this->callbacks = callbacks;
}
virtual int <API key>(FileTransfer::Descriptor& data, uint32_t flags, void*);
virtual int save_firmware_chunk(FileTransfer::Descriptor& descriptor, const unsigned char* chunk, void*);
virtual int <API key>(FileTransfer::Descriptor& data, uint32_t flags, void*);
virtual uint32_t calculate_crc(const unsigned char *buf, uint32_t buflen);
virtual system_tick_t millis();
} <API key>;
/**
* Manages device-hosted variables.
*/
Variables variables;
/**
* Manages device-hosted functions.
*/
Functions functions;
/**
* Manages subscriptions from this device.
*/
Subscriptions subscriptions;
/**
* Manages published events from this device.
*/
Publisher publisher;
/**
* Manages time sync requests
*/
TimeSyncManager timesync_;
/**
* Completion handlers for messages with confirmable delivery.
*/
<API key><message_id_t> ack_handlers;
system_tick_t <API key>;
/**
* The token ID for the next request made.
* If we have a bone-fide CoAP layer this will eventually disappear into that layer, just like message-id has.
*/
token_t token;
uint8_t initialized;
uint8_t flags;
public:
enum Flags
{
/**
* Set when the protocol expects a hello response from the server.
*/
<API key> = 1<<0,
/**
* Internal flag. Used by the protocol to disable sending a hello on session resume.
* Set if sending a hello response on resuming a session isn't required.
*/
<API key> = 1<<1,
/**
* send ping as an empty message - this functions as
* a keep-alive for UDP
*/
<API key> = 1<<2,
};
protected:
void set_protocol_flags(int flags)
{
this->flags = flags;
}
/**
* Retrieves the next token.
*/
uint8_t next_token()
{
return ++token;
}
ProtocolError handle_key_change(Message& message);
/**
* Send the hello message over the channel.
* @param <API key> {@code true} if the previous OTA update was successful.
*/
ProtocolError hello(bool <API key>);
/**
* Send a hello response
*/
ProtocolError hello_response();
virtual size_t build_hello(Message& message, bool <API key>)=0;
/**
* Send a Ping message over the channel.
*/
ProtocolError ping(bool forceCoAP=false)
{
Message message;
channel.create(message);
size_t len = 0;
if (!forceCoAP && (flags & <API key>)) {
len = Messages::keep_alive(message.buf());
}
else {
len = Messages::ping(message.buf(), 0);
}
last_message_millis = callbacks.millis();
message.set_length(len);
return channel.send(message);
}
/**
* Background processing when there are no messages to handle.
*/
ProtocolError event_loop_idle()
{
if (chunkedTransfer.is_updating())
{
return chunkedTransfer.idle(channel);
}
else
{
ProtocolError error = pinger.process(
callbacks.millis() - last_message_millis, [this]
{ return ping();});
if (error)
return error;
}
return NO_ERROR;
}
/**
* The number of missed chunks to send in a single flight.
*/
const int <API key> = 50;
/**
* Produces and transmits a describe message.
* @param desc_flags Flags describing the information to provide. A combination of {@code <API key>) and {@code DESCRIBE_SYSTEM) flags.
*/
ProtocolError send_description(token_t token, message_id_t msg_id, int desc_flags);
/**
* Decodes and dispatches a received message to its handler.
*/
ProtocolError <API key>(Message& message, CoAPMessageType::Enum& message_type);
/**
* Sends an empty acknoweldgement for the given message.
*/
ProtocolError send_empty_ack(Message& request, message_id_t msg_id);
/**
* Handles the time delivered from the cloud.
*/
void <API key>(uint32_t time);
/**
* Copy an initialize a block of memory from a source to a target, where the source may be smaller than the target.
* This handles the case where the caller was compiled using a smaller version of the struct memory than what is the current.
*
* @param target The destination structure
* @param target_size The size of the destination structure in bytes
* @param source The source structure
* @param source_size The size of the source structure in bytes
*/
static void copy_and_init(void* target, size_t target_size, const void* source, size_t source_size);
void init(const SparkCallbacks &callbacks, const SparkDescriptor &descriptor);
/**
* Updates the cached crc of subscriptions registered with the cloud.
*/
void <API key>();
uint32_t <API key>();
public:
Protocol(MessageChannel& channel) :
channel(channel),
product_id(PRODUCT_ID),
<API key>(<API key>),
publisher(this),
<API key>(0),
initialized(false)
{
}
virtual void init(const char *id,
const SparkKeys &keys,
const SparkCallbacks &callbacks,
const SparkDescriptor &descriptor)=0;
void initialize_ping(system_tick_t interval, system_tick_t timeout)
{
pinger.init(interval, timeout);
}
void set_keepalive(system_tick_t interval)
{
pinger.set_interval(interval);
}
void set_handlers(<API key>& handlers)
{
copy_and_init(&this->handlers, sizeof(this->handlers), &handlers, handlers.size);
}
void add_ack_handler(message_id_t msg_id, CompletionHandler handler, unsigned timeout)
{
ack_handlers.addHandler(msg_id, std::move(handler), timeout);
}
/**
* Determines the checksum of the application state.
* Application state comprises cloud functinos, variables and subscriptions.
*/
static uint32_t <API key>(uint32_t (*calc_crc)(const uint8_t* data, uint32_t len), uint32_t subscriptions_crc,
uint32_t describe_app_crc, uint32_t describe_system_crc);
/**
* Establish a secure connection and send and process the hello message.
*/
int begin();
/**
* Wait for a specific message type to be received.
* @param message_type The type of message wait for
* @param timeout The duration to wait for the message before giving up.
*
* @returns NO_ERROR if the message was successfully matched within the timeout.
* Returns MESSAGE_TIMEOUT if the message wasn't received within the timeout.
* Other protocol errors may return additional error values.
*/
ProtocolError event_loop(CoAPMessageType::Enum message_type, system_tick_t timeout);
/**
* Processes one event. Retrieves the type of the event processed, or NONE if no event processed.
* If an error occurs, the event type is undefined.
*/
ProtocolError event_loop(CoAPMessageType::Enum& message_type);
/**
* no-arg version of event loop for those callers that don't care about the message.
*/
bool event_loop()
{
CoAPMessageType::Enum message;
return !event_loop(message);
}
// Returns true on success, false on sending timeout or rate-limiting failure
bool send_event(const char *event_name, const char *data, int ttl,
EventType::Enum event_type, int flags, CompletionHandler handler)
{
if (chunkedTransfer.is_updating())
{
handler.setError(SYSTEM_ERROR_BUSY);
return false;
}
const ProtocolError error = publisher.send_event(channel, event_name, data, ttl, event_type, flags,
callbacks.millis(), std::move(handler));
if (error != NO_ERROR)
{
handler.setError(toSystemError(error));
return false;
}
return true;
}
inline bool send_subscription(const char *event_name, const char *device_id)
{
bool success = !subscriptions.send_subscription(channel, event_name, device_id);
if (success)
<API key>();
return success;
}
inline bool send_subscription(const char *event_name,
SubscriptionScope::Enum scope)
{
bool success = !subscriptions.send_subscription(channel, event_name, scope);
if (success)
<API key>();
return success;
}
inline bool add_event_handler(const char *event_name, EventHandler handler)
{
return add_event_handler(event_name, handler, NULL,
SubscriptionScope::FIREHOSE, NULL);
}
inline bool add_event_handler(const char *event_name, EventHandler handler,
void *handler_data, SubscriptionScope::Enum scope,
const char* device_id)
{
return !subscriptions.add_event_handler(event_name, handler,
handler_data, scope, device_id);
}
inline bool send_subscriptions()
{
bool success = !subscriptions.send_subscriptions(channel);
if (success)
<API key>();
return success;
}
inline bool <API key>(const char* name)
{
subscriptions.<API key>(name);
return true;
}
inline void set_product_id(product_id_t product_id)
{
this->product_id = product_id;
}
inline void <API key>(
<API key> <API key>)
{
this-><API key> = <API key>;
}
inline void get_product_details(product_details_t& details)
{
if (details.size >= 4)
{
details.product_id = this->product_id;
details.product_version = this-><API key>;
}
}
inline bool send_time_request()
{
if (chunkedTransfer.is_updating())
{
return false;
}
return timesync_.send_request(callbacks.millis(), [&]() {
uint8_t token = next_token();
Message message;
channel.create(message);
size_t len = Messages::time_request(message.buf(), 0, token);
message.set_length(len);
return !channel.send(message);
});
}
bool <API key>() const { return timesync_.is_request_pending(); }
system_tick_t time_last_synced(time_t* tm) const { return timesync_.last_sync(*tm); }
bool is_initialized() { return initialized; }
int <API key>(uint8_t* buf, const uint8_t* id)
{
return -1;
}
system_tick_t millis() { return callbacks.millis(); }
virtual void command(ProtocolCommands::Enum command, uint32_t data)=0;
};
}
} |
#ifndef <API key>
#define <API key>
#include "kafkarequest.h"
namespace QtAws {
namespace Kafka {
class <API key>;
class QTAWSKAFKA_EXPORT <API key> : public KafkaRequest {
public:
<API key>(const <API key> &other);
<API key>();
virtual bool isValid() const Q_DECL_OVERRIDE;
protected:
virtual QtAws::Core::AwsAbstractResponse * response(QNetworkReply * const reply) const Q_DECL_OVERRIDE;
private:
Q_DECLARE_PRIVATE(<API key>)
};
} // namespace Kafka
} // namespace QtAws
#endif |
package com.github.steveice10.packetlib.io.buffer;
import com.github.steveice10.packetlib.io.NetOutput;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.UUID;
/**
* A NetOutput implementation backed by a ByteBuffer (Java NIO).
*/
public class ByteBufferNetOutput implements NetOutput {
private ByteBuffer buffer;
public ByteBufferNetOutput(ByteBuffer buffer) {
this.buffer = buffer;
}
public ByteBuffer getByteBuffer() {
return this.buffer;
}
@Override
public void writeBoolean(boolean b) throws IOException {
this.buffer.put(b ? (byte) 1 : 0);
}
@Override
public void writeByte(int b) throws IOException {
this.buffer.put((byte) b);
}
@Override
public void writeShort(int s) throws IOException {
this.buffer.putShort((short) s);
}
@Override
public void writeChar(int c) throws IOException {
this.buffer.putChar((char) c);
}
@Override
public void writeInt(int i) throws IOException {
this.buffer.putInt(i);
}
@Override
public void writeVarInt(int i) throws IOException {
while((i & ~0x7F) != 0) {
this.writeByte((i & 0x7F) | 0x80);
i >>>= 7;
}
this.writeByte(i);
}
@Override
public void writeLong(long l) throws IOException {
this.buffer.putLong(l);
}
@Override
public void writeVarLong(long l) throws IOException {
while((l & ~0x7F) != 0) {
this.writeByte((int) (l & 0x7F) | 0x80);
l >>>= 7;
}
this.writeByte((int) l);
}
@Override
public void writeFloat(float f) throws IOException {
this.buffer.putFloat(f);
}
@Override
public void writeDouble(double d) throws IOException {
this.buffer.putDouble(d);
}
@Override
public void writeBytes(byte b[]) throws IOException {
this.buffer.put(b);
}
@Override
public void writeBytes(byte b[], int length) throws IOException {
this.buffer.put(b, 0, length);
}
@Override
public void writeShorts(short[] s) throws IOException {
this.writeShorts(s, s.length);
}
@Override
public void writeShorts(short[] s, int length) throws IOException {
for(int index = 0; index < length; index++) {
this.writeShort(s[index]);
}
}
@Override
public void writeInts(int[] i) throws IOException {
this.writeInts(i, i.length);
}
@Override
public void writeInts(int[] i, int length) throws IOException {
for(int index = 0; index < length; index++) {
this.writeInt(i[index]);
}
}
@Override
public void writeLongs(long[] l) throws IOException {
this.writeLongs(l, l.length);
}
@Override
public void writeLongs(long[] l, int length) throws IOException {
for(int index = 0; index < length; index++) {
this.writeLong(l[index]);
}
}
@Override
public void writeString(String s) throws IOException {
if(s == null) {
throw new <API key>("String cannot be null!");
}
byte[] bytes = s.getBytes("UTF-8");
if(bytes.length > 32767) {
throw new IOException("String too big (was " + s.length() + " bytes encoded, max " + 32767 + ")");
} else {
this.writeVarInt(bytes.length);
this.writeBytes(bytes);
}
}
@Override
public void writeUUID(UUID uuid) throws IOException {
this.writeLong(uuid.<API key>());
this.writeLong(uuid.<API key>());
}
@Override
public void flush() throws IOException {
}
} |
package mattparks.mods.space.venus.world.gen;
import micdoodle8.mods.galacticraft.api.prefab.world.gen.<API key>;
import net.minecraft.world.biome.BiomeGenBase;
public class <API key> extends <API key> {
@Override
public BiomeGenBase getBiome() {
return BiomeGenBaseVenus.venus;
}
} |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.obinject.sample.inception;
import org.obinject.annotation.Persistent;
/**
*
* @author windows
*/
@Persistent
public class Quimico extends Sonhador{
private String formulaDrogra;
public String getFormulaDrogra() {
return formulaDrogra;
}
public void setFormulaDrogra(String formulaDrogra) {
this.formulaDrogra = formulaDrogra;
}
} |
using System;
using CoreDht.Node;
using CoreDht.Utils;
using CoreDht.Utils.Hashing;
namespace <API key>
{
public class NodeServicesFactory
{
private readonly <API key> _hashingService;
public NodeServicesFactory(<API key> hashingService)
{
_hashingService = hashingService;
}
public NodeServices CreateServices()
{
var result = new <API key>
{
Logger = Console.WriteLine,
<API key> = _hashingService,
<API key> = new <API key>(new <API key>(new MessageSerializer()))
};
return result;
}
}
} |
<?php
/**
* Changes the attrid/priceid/textid column to allow NULL in catalog index attr/price/text table.
*/
class <API key> extends <API key>
{
private $_mysql = array(
'<API key>' => array(
'attrid' => 'ALTER TABLE "<API key>" MODIFY "attrid" INTEGER NULL',
),
'<API key>' => array(
'priceid' => 'ALTER TABLE "<API key>" MODIFY "priceid" INTEGER NULL',
),
'<API key>' => array(
'textid' => 'ALTER TABLE "<API key>" MODIFY "textid" INTEGER NULL',
),
);
/**
* Returns the list of task names which this task depends on.
*
* @return string[] List of task names
*/
public function getPreDependencies()
{
return array( '<API key>' );
}
/**
* Returns the list of task names which depends on this task.
*
* @return string[] List of task names
*/
public function getPostDependencies()
{
return array( 'TablesCreateMShop' );
}
/**
* Executes the task for MySQL databases.
*/
protected function _mysql()
{
$this->_process( $this->_mysql );
}
/**
* Add column to table if it doesn't exist.
*
* @param array $stmts List of SQL statements to execute for adding columns
*/
protected function _process( $stmts )
{
$this->_msg( 'Changing reference ID columns of catalog index tables to NULL', 0 );
$this->_status( '' );
foreach( $stmts as $table => $pairs )
{
foreach( $pairs as $column => $sql )
{
$this->_msg( sprintf( 'Checking table "%1$s" and column "%2$s"', $table, $column ), 1 );
if( $this->_schema->tableExists( $table ) === true
&& $this->_schema->columnExists( $table, $column ) === true
&& $this->_schema->getColumnDetails( $table, $column )->isNullable() === false )
{
$this->_execute( $sql );
$this->_status( 'changed' );
}
else
{
$this->_status( 'OK' );
}
}
}
}
} |
import autocomplete_light
from association.models import Word
from django.utils.translation import ugettext as _
class WordAutocomplete(autocomplete_light.<API key>):
search_fields=['name']
choice_html_format = '<span class="block os" data-value="%s">%s (%s)</span>'
attrs={
'placeholder': _('Filter'),
'<API key>': 1,
}
widget_attrs={
'<API key>': 6,
'class': 'modern-style',
}
def choice_html(self, choice):
return self.choice_html_format % (self.choice_value(choice), self.choice_label(choice), choice.language)
autocomplete_light.register(Word, WordAutocomplete) |
#include <sys/times.h>
#include <errno.h>
clock_t times (struct tms * tp) {
errno = EINVAL;
return (clock_t) -1;
} |
<?php
class Menu
{
const APP = 'menu';
const APPID = iCMS_APP_MENU;
public static $SET = array();
public static $DATA = array();
public static $HREFS = array();
public static $TITLES = array();
public static $callback = array();
public static $url = null;
const CACHE_DATA_KEY = iPHP_APP_SITE . '/menu/data';
const CACHE_HREF_KEY = iPHP_APP_SITE . '/menu/hrefs';
public static function init()
{
self::get();
}
public static function set($d = 'manage', $a = null)
{
$a === null && $a = Admincp::$APP_NAME;
self::$url = ADMINCP_URL . '=' . $a . '&do=' . $d;
}
public static function active($d = 'manage', $a = null)
{
$a === null && $a = Admincp::$APP_NAME;
self::$SET['nav']['link'] = ADMINCP_URL . '=' . $a . '&do=' . $d;
}
public static function setData($k, $v)
{
self::$SET[$k] = $v;
return new self();
}
public static function makeJson($apps, $menuData = null)
{
$menuData === null && $menuData = Request::post('menuData');
if ($menuData) {
MenuHelper::vars($menuData, $apps);
MenuHelper::sortData($menuData);
$app = null;
if ($apps['apptype'] == Apps::CONTENT_TYPE) {
$app = 'content';
$name = 'menu/admincp.' . $apps['app'];
} else {
$name = 'menu/admincp';
}
$app && Etc::set($app, $name, $menuData);
}
}
public static function get($flag = false)
{
if ($flag) {
return Menu::cache();
}
$Cache = Cache::newFileCache();
self::$DATA = $Cache->get(self::CACHE_DATA_KEY);
self::$HREFS = $Cache->get(self::CACHE_HREF_KEY);
if (empty(self::$DATA) || empty(self::$HREFS)) {
Menu::cache();
}
}
public static function cache()
{
$variable = array();
$rs = Apps::getMenuArray();
foreach ($rs as $app) {
$result = MenuHelper::get($app);
$first = reset($result);
if (is_array($first)) {
array_key_exists('id', $first) && $result = array_column($result, null, 'id');
}
$variable[] = $result;
}
self::$HREFS = [];
self::$TITLES = [];
if ($variable) {
$variable = <API key>('<API key>', $variable);
array_walk($variable, array('MenuHelper', 'arrayUnique'));
self::itemSort($variable);
self::itemData($variable);
self::$DATA = $variable;
unset($variable);
$Cache = Cache::newFileCache();
$Cache->add(self::CACHE_DATA_KEY, self::$DATA, 0);
// self::$HREFS = array_map('array_filter', self::$HREFS);
$HREFS = [];
if (self::$HREFS) foreach (self::$HREFS as $key => $value) {
$HREFS[$key] = array_filter($value);
}
self::$HREFS = $HREFS;
unset($HREFS);
$Cache->add(self::CACHE_HREF_KEY, self::$HREFS, 0);
// put_php_file(__DIR__ . '/menu.array.php', var_export(self::$DATA, true));
// $iCache->add(iPHP_APP_SITE.'/menu/caption',$caption,0);
}
}
public static function itemData($variable, $id = null)
{
// $array = array();
foreach ($variable as $value) {
// $id = $value['id'];
empty($id) && $id = $value['id'];
if ($value['href']) {
self::$HREFS[$value['href']][] = $id;
self::$TITLES[$value['href']] = $value['caption'];
} else {
self::$HREFS[$value['id']][] = $id;
}
if ($value['children']) {
self::itemData($value['children'], $value['id']);
}
}
}
public static function itemSort(&$variable)
{
sortKey($variable);
foreach ($variable as $key => $value) {
if ($value['children']) {
self::itemSort($variable[$key]['children']);
}
}
}
public static function url($a)
{
$a['href'] && $url = ADMINCP_URL . '=' . $a['href'];
$a['href'] == 'iPHP_SELF' && $url = iPHP_SELF;
$a['href'] or $url = 'javascript:;';
Request::isUrl($a['href']) && $url = $a['href'];
return $url;
}
public static $nav_item_active = '';
public static $nav_link_active = '';
public static function navPaths($path, $array, $id, &$navArray)
{
$_array = $array[$id];
$_array && $array = $_array;
if (isset($array['children'])) {
$navArray[] = self::arr($array);
return self::navPaths($path, $array['children'], $id, $navArray);
}
if ($array) foreach ($array as $idx => $value) {
if (isset($value['children'])) {
$navArray[] = self::arr($value);
self::navPaths($path, $value['children'], $id, $navArray);
} else {
$href = $value['href'];
if ($path == $href || strstr($href, $path)) {
$navArray[] = self::arr($value);
return true;
}
}
}
}
public static function getNav($app = null)
{
// $app = Admincp::$APP_NAME;
$app = self::$SET['getNav.APP'] ?: Admincp::$APP;
$uri = Admincp::uri();
$path = str_replace(iPHP_SELF . '?app=', '', $uri);
$appMenuArray = MenuHelper::app($app);
if ($appMenuArray && is_array($appMenuArray)) {
$fkey = key($appMenuArray);
$mArray = current($appMenuArray);
$navArray = [self::arr(self::$DATA[$fkey])];
}
$hrefkey = self::findHref();
if (!$fkey) {
$mArray = self::$DATA[$hrefkey];
$navArray = [self::arr(self::$DATA[$hrefkey])];
}
// var_dump($mArray['children']);
// array_walk($mArray['children'], function ($a, $b) {
// var_dump($a, $b);
self::navPaths($path, $mArray['children'], $hrefkey, $navArray);
// if (self::$SET['nav']['parent']) {
// $id = self::$SET['nav']['id'];
// var_dump(self::$SET['nav']);
// $navArray[] = self::arr(self::$DATA[$id]);
self::$SET['breadcrumb'] && $navArray[] = self::$SET['breadcrumb'];
$navArray = array_filter($navArray);
$last = end($navArray);
$navlink = self::$SET['nav']['link'] ?: $last['url'];
return array($navArray, $last, $navlink);
}
public static function arr($item)
{
if (!$item['caption']) {
return null;
}
return array(
'name' => $item['caption'],
'title' => $item['title'],
'url' => self::url($item)
);
}
public static function findHref($url = null, $array = null)
{
$url === null or self::$url = $url;
empty($url) && self::$url = Admincp::uri();
empty($array) && $array = self::$HREFS;
$path = str_replace(iPHP_SELF . '?app=', '', self::$url);
$value = $array[$path];
if ($value) return $value[0];
foreach ($array as $href => $value) {
if (strstr($href, $path)) {
return $value[0];
}
}
}
public static function navTabs($app)
{
$menuArray = current(MenuHelper::app($app));
if ($menuArray['id'] == $app) {
$array = $menuArray['children'];
} elseif ($menuArray['children']) {
$array = $menuArray['children'][$app]['children'];
}
$tabs = '';
$uri = Admincp::uri();
if ($array) foreach ((array) $array as $node) {
if ($node['caption'] == '-') {
continue;
}
$tabs .= sprintf(
'<li class="nav-item"><a class="nav-link %s" href="%s">%s</a></li>',
($uri == $node['href'] ? 'active' : 'js-tabs-link'),
self::url($node),
$node['caption']
);
}
return $tabs;
}
public static function findUrl($data = null, $url = null)
{
$url === null && $url = $_SERVER['REQUEST_URI'];
$url = str_replace(iPHP_SELF . '?', '', $url);
foreach ($data as $item) {
if ($item['href']) {
$murl = 'app=' . $item['href'];
if ($url == $murl) {
return $item;
} else {
$a1 = parse_url_qs($url);
// ksort($a1);
// var_dump(http_build_query($a1));
$a2 = parse_url_qs($murl);
// ksort($a2);
// var_dump(http_build_query($a2));
if ($a1['app'] == $a2['app']) {
if ((empty($a1['do']) && in_array($a2['do'], array(iPHP_APP, 'manage'))) ||
(empty($a2['do']) && in_array($a1['do'], array(iPHP_APP, 'manage'))) ||
($a1['do'] == $a2['do'])
) {
return $item;
}
}
}
}
}
}
public static function buildNav($key = null)
{
if ($key) {
self::$nav_item_active = $key;
$node = self::$DATA[$key];
$node && $nav_html = self::navNode($node);
} else {
$nav_html = self::buildNavArray(self::$DATA);
}
echo $nav_html;
}
public static function buildNavArray($nav_array, $root = null)
{
$nav_html = '';
foreach ((array) $nav_array as $node) {
$nav_html .= self::navNode($node, $root);
}
return $nav_html;
}
public static function navNode($node, $root = null)
{
if (!Menu::access($node)) return false;
if (empty($node['caption'])) {
return;
}
if ($node['caption'] == '-') {
return '<li class="nav-main-divider"></li>';
}
self::nodeArray($node);
// Get all vital link info
$link_name = sprintf(
'<span class="nav-main-link-name">%s</span>',
$node['caption']
);
isset($node['icon']) && $link_icon = sprintf(
'<i class="nav-main-link-icon %s"></i>',
$node['icon']
);
if (empty($node['id'])) {
$link_array = parse_url_qs('app=' . $node['href']);
$link_array = array_values($link_array);
$node['id'] = implode('_', $link_array);
}
$sub_active = ($node['id'] && $node['id'] === self::$nav_item_active) ? true : false;;
$link_active = (isset($node['href']) && $node['href'] == self::$nav_link_active) ? true : false;
// Set menu properties
$attr = [];
// $root && $attr['root'] = $root;
$attr['class'] = ['nav-main-link'];
$link_active && $attr['class'][] = 'active';
if ($node['hasChild']) {
$attr['data-toggle'] = 'submenu';
$attr['aria-expanded'] = ($sub_active ? 'true' : 'false');
$node['badge'] && $link_badge = sprintf(
'<span class="nav-main-link-badge badge badge-pill badge-%s">%d</span>',
$node['badge'],
count($node['children'])
);
}
$link_attr = self::navLinkAttr($node, $attr);
// Add the link
$link = sprintf(
'<a %s>%s</a>',
$link_attr,
$link_icon . $link_name . $link_badge
);
// If it is a submenu, call the function again
if ($node['hasChild']) {
$subNav = self::buildNavArray($node['children'], $node['id']);
empty($node['id']) && $node['id'] = md5($subNav);
$submenu = sprintf(
'<ul class="nav-main-submenu" root="%s">%s</ul>',
$node['id'],
$subNav
);
}
return sprintf(
'<li id="Menu-%s" class="nav-main-item %s" data-sort="%d">%s</li>',
$node['id'],
($sub_active ? 'open' : ''),
$node['sort'],
$link . $submenu
);
}
public static function nodeArray(&$node)
{
if ($node['icon'] && strpos($node['icon'], ' ') === false) {
$node['icon'] = 'fa fa-' . $node['icon'];
}
if ($node['icon'] == 'fa <API key>') {
$node['icon'] = 'si si-grid';
}
$node['icon'] .= ' fa-fw';
$node['hasChild'] = isset($node['children']) && is_array($node['children']) ? true : false;
}
public static function navLinkAttr($node, $attr = [])
{
$attr['href'] = self::url($node);
$node['target'] && $attr['target'] = $node['target'];
$node['class'] && $attr['class'][] = $node['class'];
if ($node['data-toggle'] == 'modal') {
$attr['data-toggle'] = 'modal';
$attr['data-target'] = '#iCMS-MODAL';
if ($node['data-meta']) {
if (is_array($node['data-meta'])) {
$node['data-meta'] = json_encode($node['data-meta']);
}
$attr['data-meta'] = $node['data-meta'];
}
}
if ($attr['data-toggle'] == 'dropdown-submenu') {
$attr['class'][] = 'dropdown-toggle';
$attr['id'] = 'dropdown-' . $node['id'];
$attr['aria-haspopup'] = 'true';
$attr['aria-expanded'] = 'false';
$attr['href'] = 'javascript:;';
}
if ($attr['data-toggle'] == 'submenu') {
$attr['class'][] = '<API key>';
$attr['aria-haspopup'] = 'true';
}
$prop = '';
foreach ($attr as $key => $value) {
is_array($value) && $value = implode(' ', $value);
$value = str_replace('"', """, $value);
$prop .= sprintf(' %s="%s"', $key, $value);
}
return $prop;
}
public static function dropdown_menu($array)
{
if ($array['children']) {
print '<div class="dropdown-menu font-size-sm" aria-labelledby="dropdown-' . $array['id'] . '">';
foreach ($array['children'] as $node) {
if (!Menu::access($node)) continue;
if (empty($node['caption'])) {
continue;
}
if ($node['caption'] == '-') {
print '<div class="dropdown-divider"></div>';
continue;
}
self::nodeArray($node);
$attr = array();
$attr['class'] = ['dropdown-item'];
$node['hasChild'] && $attr['data-toggle'] = 'dropdown-submenu';
$link_attr = self::navLinkAttr($node, $attr);
$node['hasChild'] && print('<div class="dropdown-submenu">');
printf(
'<a %s><i class="%s"></i> %s</a>',
$link_attr,
$node['icon'],
$node['caption']
);
$node['hasChild'] && self::dropdown_menu($node);
$node['hasChild'] && print('</div>');
}
print '</div>';
}
}
// public static function access_data($pk, $key)
public static function getAccessData($app = null)
{
$data = Menu::$DATA;
$app && $data = Menu::$DATA[$app]['children'];
return self::<API key>($data);
}
public static function <API key>($data = null)
{
$data = array_map(function ($node) {
if ($node['children']) {
if (self::access($node)) {
$children = self::<API key>($node['children']);
$children = array_filter($children);
$node['children'] = $children;
return $node;
}
} else {
if (self::access($node)) {
return $node;
}
}
}, $data);
return array_filter($data);
}
/**
* []
* @param [array] $node []
* @return [bool] [false ]
* @return [bool] [true ]
*/
public static function access($node)
{
if (!is_callable(self::$callback['access'])) {
return false;
}
return <API key>(self::$callback['access'], array($node));
}
public static function callfunc($array = null, $level = 1, $pid = 0)
{
$array === null && $array = self::$DATA;
//self::$callback['result']
$data = self::$callback['result'];
if ($array) foreach ($array as $key => $M) {
$child = $M['children'] ? true : false;
empty($M['id']) && $M['id'] = substr(md5(json_encode($M)), 8, 16);
if (self::$callback['func'] && is_callable(self::$callback['func'])) {
$param = array($M, $level, $child, $pid);
self::$callback['param'] && $param = array_merge($param, self::$callback['param']);
$result = <API key>(self::$callback['func'], $param);
if (!empty($result)) {
if (is_array(self::$callback['result'])) {
$data[] = $result;
} else {
$data .= $result;
}
}
}
//self::$callback['recursive'] = false ,
// self::$callback['func']
if (self::$callback['recursive'] !== false) {
if ($child) {
$result = self::callfunc($M['children'], $level + 1, $M['id']);
if (!empty($result)) {
if (is_array(self::$callback['result'])) {
$data[] = $result;
} else {
$data .= $result;
}
}
}
}
}
return $data;
}
} |
package com.nextgis.maplib.display;
import android.database.sqlite.SQLiteDatabase;
import android.os.Build;
import android.util.Log;
import com.nextgis.maplib.api.ITextStyle;
import com.nextgis.maplib.datasource.Feature;
import com.nextgis.maplib.datasource.GeoEnvelope;
import com.nextgis.maplib.datasource.GeoGeometry;
import com.nextgis.maplib.map.Layer;
import com.nextgis.maplib.map.MapBase;
import com.nextgis.maplib.map.<API key>;
import com.nextgis.maplib.map.VectorLayer;
import com.nextgis.maplib.util.Constants;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.<API key>;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.<API key>;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.atomic.AtomicReference;
import static com.nextgis.maplib.util.Constants.*;
public class <API key>
extends Renderer
{
protected Style mStyle;
protected ThreadPoolExecutor mDrawThreadPool;
//protected final Object lock = new Object();
public static final String JSON_STYLE_KEY = "style";
protected static final int GEOMETRY_PER_TASK = 15;
public <API key>(Layer layer)
{
super(layer);
mStyle = null;
}
public <API key>(
Layer layer,
Style style)
{
super(layer);
mStyle = style;
}
@Override
public void runDraw(final GISDisplay display)
{
long startTime;
if(Constants.DEBUG_MODE) {
startTime = System.currentTimeMillis();
}
if (null == mStyle) {
Log.d(TAG, "mStyle == null");
return;
}
final double zoom = display.getZoomLevel();
GeoEnvelope env = display.getBounds();
final VectorLayer vectorLayer = (VectorLayer) getLayer();
//GeoEnvelope layerEnv = vectorLayer.getExtents();
//if (null == layerEnv || !env.intersects(layerEnv)) {
// return;
int decimalZoom = (int) zoom;
if(decimalZoom % 2 != 0)
decimalZoom++;
List<Long> featureIds = vectorLayer.query(env);
cancelDraw();
int threadCount = <API key>;
int coreCount = Runtime.getRuntime().availableProcessors();
// FIXME more than 1 pool size causing strange behaviour on 6.0
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
coreCount = 1;
mDrawThreadPool = new ThreadPoolExecutor(
coreCount, threadCount, KEEP_ALIVE_TIME, <API key>,
new LinkedBlockingQueue<Runnable>(), new <API key>()
{
@Override
public void rejectedExecution(
Runnable r,
ThreadPoolExecutor executor)
{
try {
executor.getQueue().put(r);
} catch (<API key> e) {
//e.printStackTrace();
}
}
});
if(Constants.DEBUG_MODE) {
long stopTime = System.currentTimeMillis();
long elapsedTime = stopTime - startTime;
Log.d(TAG, "Vector layer " + vectorLayer.getName() + " prepare time: " + elapsedTime);
}
int tilesSize = featureIds.size() / GEOMETRY_PER_TASK + 1;
List<Future> futures = new ArrayList<>(tilesSize);
final int finalDecimalZoom = decimalZoom;
int counter = 0;
for (int i = 0; i < featureIds.size(); i += GEOMETRY_PER_TASK) {
DrawTask task = new DrawTask(finalDecimalZoom, vectorLayer, display);
for(int j = 0; j < GEOMETRY_PER_TASK; j++) {
if (Thread.currentThread().isInterrupted()) {
break;
}
if (counter >= featureIds.size())
break;
final long featureId = featureIds.get(counter);
task.addTaskData(featureId);
counter++;
}
futures.add(mDrawThreadPool.submit(task));
vectorLayer.onDrawFinished(vectorLayer.getId(), 0.01f);
}
// wait for draw ending
int nStep = futures.size() / Constants.<API key>;
if(nStep == 0)
nStep = 1;
for (int i = 0, futuresSize = futures.size(); i < futuresSize; i++) {
if (Thread.currentThread().isInterrupted()) {
break;
}
try {
Future future = futures.get(i);
future.get(); // wait for task ending
float percent = (float) i / futuresSize;
if(i % nStep == 0) //0..10..20..30..40..50..60..70..80..90..100
vectorLayer.onDrawFinished(vectorLayer.getId(), percent);
//Log.d(TAG, "TMS percent: " + percent + " complete: " + i +
// " tiles count: " + tilesSize + " layer: " + mLayer.getName());
} catch (<API key> | <API key> e) {
//e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
vectorLayer.onDrawFinished(vectorLayer.getId(), 1.0f);
if(Constants.DEBUG_MODE) {
long stopTime = System.currentTimeMillis();
long elapsedTime = stopTime - startTime;
Log.d(TAG, "Vector layer " + vectorLayer.getName() + " exec time: " + elapsedTime);
}
}
/**
* If subclass's getStyle(long featureId) changes style params then must be so in the method
* body:
* <pre> {@code
* try {
* Style styleClone = mStyle.clone();
* // changing styleClone params
* return styleClone;
* } catch (<API key> e) {
* e.printStackTrace();
* return mStyle;
* // or treat this situation instead
* }
* } </pre>
* or
* <pre> {@code
* Style style = new Style(); // or from subclass of Style
* // changing style params
* return style;
* } </pre>
*/
protected Style getStyle(long featureId)
{
applyField(mStyle, featureId);
return mStyle;
}
protected Style applyField(Style style, long featureId) {
if (style instanceof ITextStyle) {
String fieldValue = ((ITextStyle) style).getField();
if (fieldValue != null) {
Feature feature = ((VectorLayer) getLayer()).getFeature(featureId);
if (fieldValue.equals(FIELD_ID))
fieldValue = feature.getId() + "";
else
fieldValue = feature.<API key>(fieldValue);
((ITextStyle) style).setText(fieldValue);
}
}
return style;
}
@Override
public void cancelDraw()
{
if (mDrawThreadPool != null) {
//synchronized (lock) {
mDrawThreadPool.shutdownNow();
try {
mDrawThreadPool.awaitTermination(TERMINATE_TIME, <API key>);
//mDrawThreadPool.purge();
} catch (<API key> e) {
//e.printStackTrace();
}
}
}
public Style getStyle()
{
return mStyle;
}
@Override
public JSONObject toJSON()
throws JSONException
{
JSONObject rootJsonObject = new JSONObject();
rootJsonObject.put(JSON_NAME_KEY, "<API key>");
if (null != mStyle) {
rootJsonObject.put(JSON_STYLE_KEY, mStyle.toJSON());
}
return rootJsonObject;
}
@Override
public void fromJSON(JSONObject jsonObject)
throws JSONException
{
AtomicReference<Style> reference = new AtomicReference<>();
fromJSON(jsonObject, reference);
mStyle = reference.get();
}
public static void fromJSON(JSONObject jsonObject, AtomicReference<Style> style) throws JSONException {
JSONObject styleJsonObject = jsonObject.getJSONObject(JSON_STYLE_KEY);
String styleName = styleJsonObject.getString(JSON_NAME_KEY);
switch (styleName) {
case "SimpleMarkerStyle":
style.set(new SimpleMarkerStyle());
break;
case "SimpleLineStyle":
style.set(new SimpleLineStyle());
break;
case "SimplePolygonStyle":
style.set(new SimplePolygonStyle());
break;
case "<API key>":
style.set(new <API key>());
break;
default:
throw new JSONException("Unknown style type: " + styleName);
}
style.get().fromJSON(styleJsonObject);
}
protected class DrawTask implements Runnable {
protected final GISDisplay mDisplay;
protected final int mZoom;
protected final VectorLayer mLayer;
protected final List<Long> mFeatureIds = new ArrayList<>(GEOMETRY_PER_TASK);
public DrawTask(final int zoom, final VectorLayer layer, final GISDisplay display) {
mDisplay = display;
mZoom = zoom;
mLayer = layer;
}
public void addTaskData(final Long featureId){
mFeatureIds.add(featureId);
}
@Override
public void run() {
android.os.Process.setThreadPriority(
Constants.<API key>);
<API key> map = (<API key>) MapBase.getInstance();
SQLiteDatabase db = map.getDatabase(true);
for(Long id : mFeatureIds) {
if(mLayer.isFeatureHidden(id))
continue;
final GeoGeometry geometry = mLayer.getGeometryForId(id, mZoom, db);
if (geometry != null) {
final Style style = getStyle(id);
style.onDraw(geometry, mDisplay);
}
}
}
}
} |
#ifndef <API key>
#define <API key>
#include "eksrequest_p.h"
#include "<API key>.h"
namespace QtAws {
namespace EKS {
class <API key>;
class <API key> : public EksRequestPrivate {
public:
<API key>(const EksRequest::Action action,
<API key> * const q);
<API key>(const <API key> &other,
<API key> * const q);
private:
Q_DECLARE_PUBLIC(<API key>)
};
} // namespace EKS
} // namespace QtAws
#endif |
#include "<API key>.h"
#include "<API key>.h"
#include "<API key>.h"
#include "lightsailrequest_p.h"
namespace QtAws {
namespace Lightsail {
/*!
* Constructs a copy of \a other.
*/
<API key>::<API key>(const <API key> &other)
: LightsailRequest(new <API key>(*other.d_func(), this))
{
}
/*!
* Constructs a <API key> object.
*/
<API key>::<API key>()
: LightsailRequest(new <API key>(LightsailRequest::<API key>, this))
{
}
/*!
* \reimp
*/
bool <API key>::isValid() const
{
return false;
}
/*!
* Returns a <API key> object to process \a reply.
*
* \sa QtAws::Core::AwsAbstractClient::send
*/
QtAws::Core::AwsAbstractResponse * <API key>::response(QNetworkReply * const reply) const
{
return new <API key>(*this, reply);
}
/*!
* \class QtAws::Lightsail::<API key>
* \brief The <API key> class provides private implementation for <API key>.
* \internal
*
* \inmodule QtAwsLightsail
*/
/*!
* Constructs a <API key> object for Lightsail \a action,
* with public implementation \a q.
*/
<API key>::<API key>(
const LightsailRequest::Action action, <API key> * const q)
: <API key>(action, q)
{
}
/*!
* Constructs a copy of \a other, with public implementation \a q.
*
* This copy-like constructor exists for the benefit of the <API key>
* class' copy constructor.
*/
<API key>::<API key>(
const <API key> &other, <API key> * const q)
: <API key>(other, q)
{
}
} // namespace Lightsail
} // namespace QtAws |
package org.spoutcraft.api.block.design;
public class <API key> extends GenericBlockDesign {
/**
* Creates a basic cube custom block model
*
* @param addon making this block
* @param texture to use
* @param textureId[6] Array of faces, give Id's for SubTexture locations
*/
public <API key>(String addon, Texture texture, int[] textureId) {
if (textureId.length != 6) {
throw new <API key>("Invalid textureId Array length: " + textureId.length + ". Should be 6");
}
setBoundingBox(0, 0, 0, 1, 1, 1);
setQuadNumber(6);
setMinBrightness(0.0F).setMaxBrightness(1.0F).setTexture(addon, texture);
Quad bottom = new Quad(0, texture.getSubTexture(textureId[0]));
bottom.addVertex(0, 0.0F, 0.0F, 0.0F);
bottom.addVertex(1, 1.0F, 0.0F, 0.0F);
bottom.addVertex(2, 1.0F, 0.0F, 1.0F);
bottom.addVertex(3, 0.0F, 0.0F, 1.0F);
setLightSource(0, 0, -1, 0);
Quad face1 = new Quad(1, texture.getSubTexture(textureId[1]));
face1.addVertex(0, 0.0F, 0.0F, 0.0F);
face1.addVertex(1, 0.0F, 1.0F, 0.0F);
face1.addVertex(2, 1.0F, 1.0F, 0.0F);
face1.addVertex(3, 1.0F, 0.0F, 0.0F);
setLightSource(1, 0, 0, -1);
Quad face2 = new Quad(2, texture.getSubTexture(textureId[2]));
face2.addVertex(0, 1.0F, 0.0F, 0.0F);
face2.addVertex(1, 1.0F, 1.0F, 0.0F);
face2.addVertex(2, 1.0F, 1.0F, 1.0F);
face2.addVertex(3, 1.0F, 0.0F, 1.0F);
setLightSource(2, 1, 0, 0);
Quad face3 = new Quad(3, texture.getSubTexture(textureId[3]));
face3.addVertex(0, 1.0F, 0.0F, 1.0F);
face3.addVertex(1, 1.0F, 1.0F, 1.0F);
face3.addVertex(2, 0.0F, 1.0F, 1.0F);
face3.addVertex(3, 0.0F, 0.0F, 1.0F);
setLightSource(3, 0, 0, 1);
Quad face4 = new Quad(4, texture.getSubTexture(textureId[4]));
face4.addVertex(0, 0.0F, 0.0F, 1.0F);
face4.addVertex(1, 0.0F, 1.0F, 1.0F);
face4.addVertex(2, 0.0F, 1.0F, 0.0F);
face4.addVertex(3, 0.0F, 0.0F, 0.0F);
setLightSource(4, -1, 0, 0);
Quad top = new Quad(5, texture.getSubTexture(textureId[5]));
top.addVertex(0, 0.0F, 1.0F, 0.0F);
top.addVertex(1, 0.0F, 1.0F, 1.0F);
top.addVertex(2, 1.0F, 1.0F, 1.0F);
top.addVertex(3, 1.0F, 1.0F, 0.0F);
setLightSource(5, 0, 1, 0);
setQuad(bottom).setQuad(face1).setQuad(face2).setQuad(face3).setQuad(face4).setQuad(top);
}
/**
* Creates a basic cube custom block model with only one texture
*
* @param addon making this block
* @param texture to use
* @param textureId to get the SubTexture to use
*/
public <API key>(String addon, Texture texture, int textureId) {
this(addon, texture, getIdMap(textureId));
}
/**
* Creates a basic cube custom block model with only one texture
*
* @param addon making this block
* @param texture url to use - must be square
* @param textureSize size of the width/height of the texture in pixels
*/
public <API key>(String addon, String texture, int textureSize) {
this(addon, new Texture(addon, texture, textureSize, textureSize, textureSize), 0);
}
private static int[] getIdMap(int textureId) {
int[] idMap = new int[6];
for (int i = 0; i < 6; i++) {
idMap[i] = textureId;
}
return idMap;
}
} |
package de.Keyle.MyPet.entity;
import de.Keyle.MyPet.api.entity.MyPetType;
import de.Keyle.MyPet.api.player.MyPetPlayer;
import de.Keyle.MyPet.entity.types.*;
import java.lang.reflect.Constructor;
public enum MyPetClass {
Bat(MyBat.class),
Blaze(MyBlaze.class),
CaveSpider(MyCaveSpider.class),
Chicken(MyChicken.class),
Cow(MyCow.class),
Creeper(MyCreeper.class),
Donkey(MyDonkey.class),
ElderGuardian(MyElderGuardian.class),
EnderDragon(MyEnderDragon.class),
Enderman(MyEnderman.class),
Endermite(MyEndermite.class),
Ghast(MyGhast.class),
Giant(MyGiant.class),
Guardian(MyGuardian.class),
Horse(MyHorse.class),
Husk(MyHusk.class),
Evoker(MyEvoker.class),
Illusioner(MyIllusioner.class),
IronGolem(MyIronGolem.class),
Llama(MyLlama.class),
MagmaCube(MyMagmaCube.class),
Mooshroom(MyMooshroom.class),
Mule(MyMule.class),
Ocelot(MyOcelot.class),
Parrot(MyParrot.class),
Pig(MyPig.class),
PigZombie(MyPigZombie.class),
PolarBear(MyPolarBear.class),
Rabbit(MyRabbit.class),
Sheep(MySheep.class),
Silverfish(MySilverfish.class),
Skeleton(MySkeleton.class),
SkeletonHorse(MySkeletonHorse.class),
Slime(MySlime.class),
Snowman(MySnowman.class),
Spider(MySpider.class),
Squid(MySquid.class),
Stray(MyStray.class),
Witch(MyWitch.class),
Wither(MyWither.class),
WitherSkeleton(MyWitherSkeleton.class),
Wolf(MyWolf.class),
Vex(MyVex.class),
Villager(MyVillager.class),
Vindicator(MyVindicator.class),
Zombie(MyZombie.class),
ZombieHorse(MyZombieHorse.class),
ZombieVillager(MyZombieVillager.class);
private Class<? extends MyPet> clazz;
MyPetClass(Class<? extends MyPet> clazz) {
this.clazz = clazz;
}
public static MyPetClass getByMyPetType(MyPetType type) {
return valueOf(type.name());
}
public Class<? extends MyPet> getMyPetClass() {
return clazz;
}
public MyPet getNewMyPetInstance(MyPetPlayer owner) {
try {
Constructor<?> ctor = clazz.getConstructor(MyPetPlayer.class);
Object obj = ctor.newInstance(owner);
if (obj instanceof MyPet) {
return (MyPet) obj;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
} |
package ccre.cluck;
import ccre.verifier.SetupPhase;
/**
* A listener that is told about objects on the network as they are discovered.
*
* @see CluckPublisher#setupSearching(ccre.cluck.CluckNode,
* ccre.cluck.CluckRemoteListener)
* @author skeggsc
*/
public interface CluckRemoteListener {
/**
* Handle information about the specified remote of the specified RMT type.
*
* @param remote The remote path.
* @param remoteType The remote type.
*/
@SetupPhase
public void handle(String remote, int remoteType);
} |
package tools.io;
import java.io.IOException;
import java.io.InputStream;
public class <API key>
{
public static int toInt(byte[] b)
{
return (((b[3] & 0xff) << 24) | ((b[2] & 0xff) << 16) | ((b[1] & 0xff) << 8) | (b[0] & 0xff));
}
public static short toShort(byte[] b)
{
return (short) (((b[1] & 0xff) << 8) | (b[0] & 0xff));
}
public static byte readByte(InputStream stream) throws IOException
{
byte[] b = new byte[1];
stream.read(b, 0, 1);
return b[0];
}
public static short readUnsignedByte(InputStream stream) throws IOException
{
return byteToUnsigned(readByte(stream));
}
public static short byteToUnsigned(byte in)
{
return (short) (in & 0xFF);
}
public static byte[] readBytes(int numBytes, InputStream stream) throws IOException
{
byte[] b = new byte[numBytes];
stream.read(b, 0, numBytes);
return b;
}
public static short[] readUnsignedBytes(int numBytes, InputStream stream) throws IOException
{
byte[] b = readBytes(numBytes, stream);
short[] s = new short[numBytes];
for (int i = 0; i < b.length; i++)
s[i] = byteToUnsigned(b[i]);
return s;
}
public static int readInt(InputStream stream) throws IOException
{
byte b[] = new byte[4];
stream.read(b, 0, 4);
return toInt(b);
}
public static int[] readInts(int numInts, InputStream stream) throws IOException
{
int[] is = new int[numInts];
for (int i = 0; i < numInts; i++)
{
is[i] = readInt(stream);
}
return is;
}
public static short readShort(InputStream stream) throws IOException
{
byte b[] = new byte[2];
stream.read(b, 0, 2);
return toShort(b);
}
public static int readUnsignedShort(InputStream stream) throws IOException
{
return shortToUnsigned(readShort(stream));
}
public static int shortToUnsigned(short in)
{
return (in & 0xFFFF);
}
public static int[] readUnsignedShorts(int numBytes, InputStream stream) throws IOException
{
short[] s1 = readShorts(numBytes, stream);
int[] s2 = new int[numBytes];
for (int i = 0; i < s1.length; i++)
s2[i] = shortToUnsigned(s1[i]);
return s2;
}
public static short[] readShorts(int numShorts, InputStream stream) throws IOException
{
short[] ss = new short[numShorts];
for (int i = 0; i < numShorts; i++)
{
ss[i] = readShort(stream);
}
return ss;
}
public static float readFloat(InputStream stream) throws IOException
{
byte b[] = new byte[4];
stream.read(b, 0, 4);
return toFloat(b);
}
public static float[] readFloats(int numFloats, InputStream stream) throws IOException
{
float[] fs = new float[numFloats];
for (int i = 0; i < numFloats; i++)
{
fs[i] = readFloat(stream);
}
return fs;
}
/**
* <compound name="SizedString" niflibtype="string" nifskopetype="sizedstring">
*
* A string of given length.
*
* <add name="Length" type="uint">The string length.</add> <add name="Value" type="char" arr1="Length">The string itself.</add> </compound>
*
* @param stream
* @return
* @throws IOException
*/
public static String readSizedString(InputStream stream) throws IOException
{
int len = readInt(stream);
byte[] buffer = new byte[len];
stream.read(buffer, 0, len);
return new String(buffer);
}
public static String[] readSizedStrings(int numStrings, InputStream stream) throws IOException
{
String[] ss = new String[numStrings];
for (int i = 0; i < numStrings; i++)
{
ss[i] = readSizedString(stream);
}
return ss;
}
/**
<compound name="ShortString" ver1="10.1.0.0" niflibtype="ShortString" nifskopetype="shortstring">
Another string format, for short strings. Specific to Bethesda-specific header tags.
<add name="Length" type="byte">The string length.</add>
<add name="Value" type="char" arr1="Length">
The string itself, null terminated (the null terminator is taken into account in the length byte).
</add>
</compound>
*/
public static String readShortString(InputStream stream) throws IOException
{
short len = readUnsignedByte(stream);
byte[] buffer = new byte[len];
stream.read(buffer, 0, len);
return new String(buffer);
}
//private static HashMap<Integer, Integer> floatHitCount = new HashMap<Integer, Integer>();
//private static int c = 0;
public static float toFloat(byte[] b)
{
//System.out.println("1.0 : "+ Integer.toBinaryString(Float.floatToRawIntBits(1.0f)) + " " + Float.floatToRawIntBits(1.0f));
int i = toInt(b);
// output the top hits, NOTE! no discernable saving from this crap!
/* switch (i)
{
case (0)://count= 287699
return 0f;
case (1065353216)://count= 1085445
return 1.0f;
case (1053345994)://count= 123019
return 0.3921569f;
case (1056964608)://count= 43501
return 0.5f;
case (1061734602)://count= 11479
return 0.7843138f;
case (-1006632960)://count= 27376
return -512.0f;
case (1061158912)://count= 16092
return 0.75f;
case (1050253722)://count= 11991
return 0.3f;
case (1207959552)://count= 14100
return 131072.0f;
case (1048576000)://count= 18146
return 0.25f;
case (1058444951)://count= 11001
return 0.5882353f;
default:*/
return Float.intBitsToFloat(i);
}
} |
# MSPPG
Multiwii Serial Protocol Parser Generator for Python3, Java, and C++, and C.
Instructions
This repository is now part of [RoboFirmwareToolkit](https://github.com/simondlevy/RoboFirmwareToolkit).
Look in the [parser](https://github.com/simondlevy/RoboFirmwareToolkit/tree/master/extras/parser) subfolder. |
package Sirius.server.middleware.interfaces.proxy;
import Sirius.server.newuser.User;
import Sirius.server.newuser.UserException;
import Sirius.server.newuser.UserGroup;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.security.Key;
import java.util.Vector;
import de.cismet.connectioncontext.ConnectionContext;
/**
* encapsulates methods relatad to user management.
*
* @version $Revision$, $Date$
*/
public interface UserService extends Remote {
/**
* DOCUMENT ME!
*
* @param user DOCUMENT ME!
* @param oldPassword DOCUMENT ME!
* @param newPassword DOCUMENT ME!
*
* @return DOCUMENT ME!
*
* @throws RemoteException DOCUMENT ME!
* @throws UserException DOCUMENT ME!
*/
@Deprecated
boolean changePassword(User user, String oldPassword, String newPassword) throws RemoteException, UserException;
// change password
/**
* changes users password.
*
* @param user user token of the user whose password is to be changed
* @param oldPassword current password
* @param newPassword new password
* @param context DOCUMENT ME!
*
* @return password changed successfully
*
* @throws RemoteException non user related server error
* @throws UserException Sirius.server.newuser.UserException server error (eg wrong current password)
*/
boolean changePassword(final User user,
final String oldPassword,
final String newPassword,
final ConnectionContext context) throws RemoteException, UserException;
/**
* DOCUMENT ME!
*
* @param userGroupLsName DOCUMENT ME!
* @param userGroupName DOCUMENT ME!
* @param userLsName DOCUMENT ME!
* @param userName DOCUMENT ME!
* @param password DOCUMENT ME!
*
* @return DOCUMENT ME!
*
* @throws RemoteException DOCUMENT ME!
* @throws UserException DOCUMENT ME!
*/
@Deprecated
User getUser(String userGroupLsName, String userGroupName, String userLsName, String userName, String password)
throws RemoteException, UserException;
// login retrieving userAccessToken
/**
* retrieves a user token.
*
* @param userGroupLsName domain of the user group the user belongs to
* @param userGroupName name of the user group the user belongs to
* @param userLsName domain where the user is hosted
* @param userName login of the user
* @param password password
* @param context DOCUMENT ME!
*
* @return a user abject (user token)
*
* @throws RemoteException server error (non user dependant)
* @throws UserException Sirius.server.newuser.UserException server error (eg bad login)
*/
User getUser(final String userGroupLsName,
final String userGroupName,
final String userLsName,
final String userName,
final String password,
final ConnectionContext context) throws RemoteException, UserException;
/**
* DOCUMENT ME!
*
* @param domain DOCUMENT ME!
*
* @return DOCUMENT ME!
*
* @throws RemoteException DOCUMENT ME!
*/
Key getPublicJwtKey(String domain) throws RemoteException;
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*
* @throws RemoteException DOCUMENT ME!
*/
@Deprecated
Vector getUserGroupNames() throws RemoteException; // Vector contains String[2] name +lsName
/**
* list all available (of domain servers online) usergroups eg admins@altlasten.
*
* @param context DOCUMENT ME!
*
* @return list of user group names eg admins@altlasen
*
* @throws RemoteException server error (eg no domain servers online)
*/
Vector getUserGroupNames(final ConnectionContext context) throws RemoteException; // Vector contains String[2]
// name +lsName
/**
* DOCUMENT ME!
*
* @param userName DOCUMENT ME!
* @param lsHome DOCUMENT ME!
*
* @return DOCUMENT ME!
*
* @throws RemoteException DOCUMENT ME!
*/
@Deprecated
Vector getUserGroupNames(String userName, String lsHome) throws RemoteException;
/**
* list all available (of domain servers online) usergroups eg admins@altlasten for a certain login.
*
* @param userName login name
* @param lsHome domain where the user login is hosted
* @param context DOCUMENT ME!
*
* @return list of user group names eg admins@altlasen if userName is member of these user groups
*
* @throws RemoteException server error (bad login)
*/
Vector getUserGroupNames(final String userName, final String lsHome, final ConnectionContext context)
throws RemoteException;
/**
* DOCUMENT ME!
*
* @param user DOCUMENT ME!
* @param key DOCUMENT ME!
*
* @return DOCUMENT ME!
*
* @throws RemoteException DOCUMENT ME!
*/
@Deprecated
String getConfigAttr(final User user, final String key) throws RemoteException;
/**
* Retrieves the value for the given key for the given {@link User}. That means if a user requests a value for a key
* the value is delivered with the following strategy:
*
* <ul>
* <li>the value of the <code>User</code> if it is set</li>
* <li>the value of the <code>User</code>'s {@link UserGroup} if it is set</li>
* <li>the value of the <code>UserGroup</code>'s <code>Domain</code> if it is set.</li>
* <li><code>null</code> otherwise.</li>
* </ul>
* <br/>
* <br/>
* If you want to explicitely retrieve the value for the <code>UserGroup</code> though the <code>User</code>'s value
* is set hand over an <code>User</code> object with <code>id < 0</code>.<br/>
* If you want to explicitely retrieve the value for the <code>Domain</code> though any other value is set hand over
* an <code>User</code> object with <code>id < 0</code> that contains a <code>UserGroup</code> object with <code>id
* < 0</code>.
*
* @param user the <code>User</code> whose value shall be retrieved
* @param key the key for the value to be retrieved
* @param context DOCUMENT ME!
*
* @return the associated values or <code>null</code>
*
* @throws RemoteException if an internal error occurs
*/
String getConfigAttr(final User user, final String key, final ConnectionContext context) throws RemoteException;
/**
* DOCUMENT ME!
*
* @param user DOCUMENT ME!
* @param key DOCUMENT ME!
*
* @return DOCUMENT ME!
*
* @throws RemoteException DOCUMENT ME!
*/
@Deprecated
boolean hasConfigAttr(final User user, final String key) throws RemoteException;
/**
* Determines whether the given {@link User} has a value associated with the given key or not. For value retrieval
* strategy see {@link #getConfigAttr(Sirius.server.newuser.User, java.lang.String) }.
*
* @param user the <code>User</code> to be checked
* @param key the key to be checked
* @param context DOCUMENT ME!
*
* @return true whether there is a value associated with the given key for the given <code>User</code>, false
* otherwise.
*
* @throws RemoteException if an internal error occurs
*
* @see #getConfigAttr(Sirius.server.newuser.User, java.lang.String)
*/
boolean hasConfigAttr(final User user, final String key, final ConnectionContext context) throws RemoteException;
} |
<?php
/**
* @package wa-apps/photos/frontend
*/
class <API key> extends <API key>
{
public function execute()
{
$this->init();
$type = waRequest::param('type');
$this->hash = waRequest::param('hash');
if ($type == 'tag') {
$this->view->assign('criteria', 'by-tag');
$this->view->assign('tag', waRequest::param('tag'));
} else if ($type == 'favorites') {
$this->view->assign('criteria', 'favorites');
}
if (in_array($type, array(
'author',
'search',
'tag',
'favorites',
'id')))
{
waRequest::setParam('disable_sidebar', true);
$template = 'search.html';
} else {
$template = 'home.html';
if (!file_exists($this->getTheme()->getPath().'/'.$template)) {
$template = 'view-thumbs.html'; // for backward compatibility reason
}
}
if ($type != 'all' && $type != 'favorites') {
waRequest::setParam('nofollow', true);
}
$layout = $this->getLayout();
if ($layout) {
$layout->assign('hash', $this->hash);
}
$this->setThemeTemplate($template);
$this->finite();
}
public function display($clear_assign = false)
{
return parent::display($clear_assign);
}
} |
#if !defined( _PYFWEVT_UNUSED_H )
#define _PYFWEVT_UNUSED_H
#include <common.h>
#if !defined( <API key> )
#if defined( __GNUC__ ) && __GNUC__ >= 3
#define <API key> __attribute__ ((__unused__))
#else
#define <API key>
#endif
#endif
#if defined( _MSC_VER )
#define <API key>( parameter ) \
<API key>( parameter );
#else
#define <API key>( parameter ) \
/* parameter */
#endif
#endif /* !defined( _PYFWEVT_UNUSED_H ) */ |
<?php
use yii\helpers\Html;
use yii\helpers\Url;
use yii\bootstrap\Nav;
use yii\bootstrap\NavBar;
use yii\web\View;
use yii\widgets\Breadcrumbs;
use app\assets\AppAsset;
AppAsset::register($this);
$this->title = 'ASD company';
?>
<?php $this->beginPage() ?>
<!DOCTYPE html>
<html lang="<?= Yii::$app->language ?>">
<head>
<meta charset="<?= Yii::$app->charset ?>">
<meta name="viewport" content="width=device-width, initial-scale=1">
<?= Html::csrfMetaTags() ?>
<title><?= Html::encode($this->title) ?></title>
<?php $this->head() ?>
<link href="/web/css/styles.css" rel="stylesheet"></link>
<!--<script src=<?php echo Url::to('/web/assets/js/jquery-1.11.2.js') ?> type="text/javascript"></script>
<script src=<?php echo Url::to('/web/assets/js/navmenu-settings.js') ?> type="text/javascript"></script>
</head>
<body>
<?php $this->beginBody() ?>
<div class="wrap">
<?php
NavBar::begin([
'brandLabel' => $this->title,
'brandUrl' => Yii::$app->homeUrl,
'options' => [
'class' => 'navbar-inverse navbar-fixed-top',
],
]);
NavBar::end();
?>
<div class="container">
<?= Breadcrumbs::widget([
'links' => isset($this->params['breadcrumbs']) ? $this->params['breadcrumbs'] : [],
]) ?>
<?= Nav::widget([
'items' => [
[
'label' => 'Поставщики',
'url' => ['vendors/index'],
'active' => true,
],
[
'label' => 'Продукция',
'url' => ['products/index'],
],
],
'options' => ['class' => 'nav-tabs'],
]);
?>
<p></p>
<ul class="nav nav-tabs" role="tablist">
<li role="presentation" class="active">
<a href="#home" aria-controls="home" role="tab" data-toggle="tab">Home</a></li>
<li role="presentation">
<a href="#profile" aria-controls="profile" role="tab" data-toggle="tab">Profile</a></li>
<li role="presentation">
<a href="#messages" aria-controls="messages" role="tab" data-toggle="tab">Messages</a></li>
<li role="presentation">
<a href="#settings" aria-controls="settings" role="tab" data-toggle="tab">Settings</a></li>
</ul>
<!--<ul class="nav nav-tabs">
<li id="navmenu-vendors" role="presentation" class="active"><a href="
<li id="navmenu-products" role="presentation"><a href="
</ul>
<?= $content ?>
</div>
</div>
<footer class="footer">
<div class="container">
<p class="pull-left">© <?= $this->title ?> <?= date('Y'). ' г.' ?></p>
<p class="pull-right"><?= Yii::powered() ?></p>
</div>
</footer>
<?php $this->endBody() ?>
</body>
</html>
<?php $this->endPage() ?> |
kevoree-<%= rawEntityType %>-<%= _.slugify(tdef.name) %>
Default README generated by `generator-kevoree`, a `yo` generator for [__kevoree-js__](https://github.com/kevoree/kevoree-js)
## Test
grunt kev
Starts a kevoree runtime with the developped component deployed. |
package crom_l1_composed;
import org.eclipse.emf.common.util.EList;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Relation Target</b></em>'.
* <!-- end-user-doc -->
*
* <p>
* The following features are supported:
* </p>
* <ul>
* <li>{@link crom_l1_composed.RelationTarget#getIncoming <em>Incoming</em>}</li>
* <li>{@link crom_l1_composed.RelationTarget#getOutgoing <em>Outgoing</em>}</li>
* </ul>
*
* @see crom_l1_composed.<API key>#getRelationTarget()
* @model abstract="true"
* @generated
*/
public interface RelationTarget extends NamedElement {
/**
* Returns the value of the '<em><b>Incoming</b></em>' reference list.
* The list contents are of type {@link crom_l1_composed.Relation}.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Incoming</em>' reference list isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Incoming</em>' reference list.
* @see crom_l1_composed.<API key>#<API key>()
* @model ordered="false"
* @generated
*/
EList<Relation> getIncoming();
/**
* Returns the value of the '<em><b>Outgoing</b></em>' reference list.
* The list contents are of type {@link crom_l1_composed.Relation}.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Outgoing</em>' reference list isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Outgoing</em>' reference list.
* @see crom_l1_composed.<API key>#<API key>()
* @model ordered="false"
* @generated
*/
EList<Relation> getOutgoing();
} // RelationTarget |
using System.Management.Automation;
namespace PowerShellAudio.Commands
{
[Cmdlet(VerbsCommon.Set, "AudioFileCoverArt"), OutputType(typeof(TaggedAudioFile))]
public class <API key> : Cmdlet
{
[Parameter(Mandatory = true, Position = 0)]
public CoverArt CoverArt { get; set; }
[Parameter(Mandatory = true, Position = 1, ValueFromPipeline = true)]
public AudioFile AudioFile { get; set; }
[Parameter]
public SwitchParameter PassThru { get; set; }
protected override void ProcessRecord()
{
var taggedAudioFile = new TaggedAudioFile(AudioFile);
taggedAudioFile.Metadata.CoverArt = CoverArt;
if (PassThru)
WriteObject(taggedAudioFile);
}
}
} |
package com.silicolife.textmining.core.init;
import static org.junit.Assert.assertTrue;
import java.io.<API key>;
import java.io.IOException;
import java.sql.SQLException;
import org.junit.Test;
import com.silicolife.textmining.core.datastructures.dataaccess.database.DatabaseFactory;
import com.silicolife.textmining.core.datastructures.init.exception.<API key>;
import com.silicolife.textmining.core.interfaces.core.dataaccess.database.DataBaseTypeEnum;
import com.silicolife.textmining.core.interfaces.core.dataaccess.database.IDatabase;
public class <API key>{
@Test
public void <API key>() throws <API key>, <API key>, SQLException, IOException
{
IDatabase database = createDatabase("localhost","3306","todelete","root","admin");
if(database==null)
{
assertTrue(false);
}
assertTrue(fillDatabase(database));
}
/**
* Fill Database
*
* @param database
* @return
* @throws SQLException
* @throws <API key>
* @throws IOException
*/
public static boolean fillDatabase(IDatabase database) throws SQLException, <API key>, IOException
{
if(!database.isfill())
{
database.fillDataBaseTables("src/test/resources/<API key>.sql");
return true;
}
return false;
}
/**
* Create Database
*
* @return
* @throws <API key>
* @throws SQLException
*/
public static IDatabase createDatabase(String host,String port,String schema,String username,String password) throws <API key>, SQLException
{
DataBaseTypeEnum databaseType = DataBaseTypeEnum.MYSQL;
if (host.trim().equals("") || port.trim().equals("") || schema.trim().equals("")) {
if(host.isEmpty())
{
throw new <API key>("Host can not be null (localhost by default)");
}
if(port.isEmpty())
{
throw new <API key>("Port can not be null (3306 by default)");
}
if(schema.isEmpty())
{
throw new <API key>("Schema can not be null");
}
return null;
} else {
IDatabase databaseAdded = DatabaseFactory.createDatabase(databaseType, host, port, schema, username, password);
databaseAdded.createDataBase();
checkConnection(databaseAdded);
return databaseAdded;
}
}
/**
* Check databse connection
*
* @param databaseAdded
* @return
*/
private static boolean checkConnection(IDatabase databaseAdded) {
try {
databaseAdded.openConnection();
if (databaseAdded.getConnection() != null) {
return true;
}
}catch (SQLException e) {
return false;
}
return false;
}
} |
package fr.ymanvieu.trading.common.rate;
import java.math.BigDecimal;
import java.time.Instant;
import java.util.Objects;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import fr.ymanvieu.trading.common.symbol.Symbol;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
@ToString
@AllArgsConstructor
@NoArgsConstructor
@Setter
@Getter
public class Rate {
private Symbol fromcur;
private Symbol tocur;
private BigDecimal value;
private Instant date;
@Override
public int hashCode() {
return Objects.hash(fromcur, tocur, date, value);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!(obj instanceof Rate))
return false;
Rate other = (Rate) obj;
return Objects.equals(fromcur, other.fromcur)
&& Objects.equals(tocur, other.tocur)
&& Objects.equals(date, other.date)
&& value.compareTo(other.value) == 0;
}
} |
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.core.context_processors import csrf
from django.views.generic.base import View, TemplateView
from django.views import generic
from django.shortcuts import render_to_response
from django.template import RequestContext, loader, Context
from django.utils import simplejson
from settings import <API key>
import psycopg2, sys, pprint, json
from datetime import datetime
from django.views.decorators.csrf import ensure_csrf_cookie
import logging
from array import *
# logger = logging.getLogger('print')
class LoadCanvas(View):
template_name= "index.html"
def get(self, request, *args, **kwargs):
c = {}
c.update(csrf(request))
return render_to_response(self.template_name, c)
class FetchObservations(View):
# template_name = "timeline/timelines.html"
obsType = array('i'); # 575
startTime = '' ;
stationID ='';
#@route ('/observe', method='POST')
def post(self, request, *args, **kwargs):
try:
json_data = simplejson.loads(request.body)
print 'Raw Data: "%s"' % request.body
# print json_data
self.startTime = str(json_data['startTime'])
# self.startTime = '2013-07-09 00:00:00';
# print self.startTime
self.stationID = json_data['stationID']
stationList = ",".join([str(x) for x in self.stationID])
# print stationList
self.obsType = json_data['obsType']
# print self.obsType
conn_string = <API key> # get a connection, if a connect cannot be made an exception will be raised here
conn = psycopg2.connect(conn_string) # conn.cursor will return a cursor object, you can use this cursor to perform queries
cursor = conn.cursor()
r = [];
# print self.obsType[0]
# print self.obsType[1]
for obs in self.obsType:
# execute our Query
data = {}
obsStr = str(obs)
cursor.execute("SELECT "+
"TO_CHAR( (date_trunc('hour', tstamp) + INTERVAL '15 min' * ROUND(date_part('minute', tstamp) / 15.0)), 'YYYY-MM-DD HH24:MI' ) AS tstamp, "+
"AVG( metric_value ) AS metric_value " +
"FROM clarus.observation, clarus.sensor "+
"WHERE clarus.observation.sensor_id=clarus.sensor.sensor_id "+
"AND station_id IN (" + stationList + ") AND observation_type = " + obsStr + " "+
"AND tstamp >= (timestamp '"+self.startTime+"' - INTERVAL '1 week') AND tstamp < timestamp '"+self.startTime+"' " +
"GROUP BY date_trunc('hour', tstamp) + INTERVAL '15 min' * ROUND(date_part('minute', tstamp) / 15.0) "+
"ORDER BY tstamp asc" );
data['rows'] = [dict((cursor.description[i][0], value)
for i, value in enumerate(row)) for row in cursor.fetchall()]
# this query is no longer needed as the metadata is all loaded separately
#cursor.execute("SELECT name, description, metric_abbreviation "+
# "FROM clarus.<API key> "+
# "WHERE clarus.<API key>.observation_type= "+ obs +"");
#data['title'] = ([dict((cursor.description[i][0], value)
# for i, value in enumerate(row)) for row in cursor.fetchall()])
data['title'] = obs
r.append(data);
cursor.connection.close();
# now process it
json_output = simplejson.dumps(r)
return HttpResponse(json_output, content_type="application/json")
except:
return HttpResponse("<h1>Error in running query</h1>")
# logger.error('Getting observation data failed') |
double *shepard_interp_nd ( int m, int nd, double xd[], double zd[], double p,
int ni, double xi[] );
double r8vec_dot_product ( int n, double a1[], double a2[] ); |
package netgloo.models;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.util.HashSet;
import java.util.Set;
@Entity
@Table(name = "Beer")
public class Beer
{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long beerId;
@NotNull
@Column(unique=true)
private String name;
@NotNull
private long degree;
@ManyToMany (mappedBy = "listBeer")
@Transient
private Set<Bar> listBars = new HashSet<>();
// PUBLIC METHODS
public Beer(){}
public Beer(String Name, long Degree)
{
name = Name;
degree = Degree;
}
public long getBeerId() {
return this.beerId;
}
public void setBeerId(long beerId) {
this.beerId = beerId;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public long getDegree() {
return this.degree;
}
public void setDegree(long degree) {
this.degree = degree;
}
public Set<Bar> getlistBars() {
return this.listBars;
}
public void setlistBars(Set<Bar> listBars) {
this.listBars = listBars;
}
} // class Beer |
@javax.annotation.<API key>
package org.sonar.api.batch.sensor.code; |
package cz.vutbr.web.csskit.fn;
import java.util.List;
import cz.vutbr.web.css.Term;
import cz.vutbr.web.css.TermFunction;
import cz.vutbr.web.css.TermLength;
import cz.vutbr.web.css.TermList;
import cz.vutbr.web.csskit.TermFunctionImpl;
public class BlurImpl extends TermFunctionImpl implements TermFunction.Blur {
private TermLength radius;
public BlurImpl() {
setValid(false);
}
@Override
public TermLength getRadius() {
return radius;
}
@Override
public TermList setValue(List<Term<?>> value)
{
super.setValue(value);
List<Term<?>> args = getSeparatedValues(DEFAULT_ARG_SEP, false);
if (args != null && args.size() == 1 && (radius = getLengthArg(args.get(0))) != null) {
setValid(true);
}
return this;
}
} |
$(document).ready(function () {
$('.data').inputmask("dd/mm/yyyy", {placeholder: "_"});
$('.hora').inputmask('hh:mm');
<API key>();
});
function <API key>() {
$("#<API key>").fadeOut();
$("#causaNaoDoacao").prop("value", "");
}
function <API key>() {
$("#divCorneasCaptadas").fadeOut();
$("#dataCaptacao").prop("value", "");
$("#horarioCaptacao").prop("value", "");
}
$("#captacaoRealizada\\:0").click(function () {
<API key>();
$("#divCorneasCaptadas").fadeIn();
});
$("#captacaoRealizada\\:1").click(function () {
$("#<API key>").fadeIn();
<API key>();
});
$("#processoCaptacao").validate({
errorPlacement: <API key>,
success: <API key>,
rules:{
'captacaoRealizada': {
required: true
},
'causaNaoDoacao': {
required: true
},
'dataCaptacao': {
required: true
},
'horarioCaptacao': {
required: true
}
},
messages: {
'captacaoRealizada': {
required: "Por favor, confirme se a captação foi realizada ou não"
},
'causaNaoDoacao': {
required: "Por favor, selecione o problema logístico"
},
'dataCaptacao': {
required: "Por favor, informe a a data da captação"
},
'horarioCaptacao': {
required: "Por favor, informe o horário da captação"
}
}
}); |
package org.geowebcache.grid;
import static java.util.Arrays.asList;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.geowebcache.<API key>;
public class SRS implements Comparable<SRS> {
private static Map<Integer, SRS> list = new ConcurrentHashMap<Integer, SRS>();
private static final SRS EPSG4326 = new SRS(4326);
/**
* The EPSG says EPSG:3857 is the identifier for web mercator. ArcGIS 10 says either of
* EPSG:102113 or EPSG:102100 identifies web mercator. The "community" first defined it as
* EPSG:900913.
*/
private static final SRS EPSG3857 = new SRS(3857, new ArrayList<Integer>(asList(900913, 102113,
102100)));
/**
* The EPSG says EPSG:3857 is the identifier for web mercator. ArcGIS 10 says either of
* EPSG:102113 or EPSG:102100 identifies web mercator. The "community" first defined it as
* EPSG:900913.
*/
private static final SRS EPSG900913 = new SRS(900913, new ArrayList<Integer>(asList(3857,
102113, 102100)));
private int number;
private transient List<Integer> aliases;
private SRS() {
// default constructor for XStream
}
private SRS(int epsgNumber) {
this(epsgNumber, null);
}
private SRS(int epsgNumber, List<Integer> aliases) {
this.number = epsgNumber;
this.aliases = aliases;
readResolve();
}
// called by XStream for custom initialization
private SRS readResolve() {
if (!list.containsKey(Integer.valueOf(number))) {
list.put(number, this);
}
return this;
}
/**
* Returns an SRS object for the given epsg code.
* <p>
* If an SRS for this code already exists, it's returned. Otherwise a registered SRS is looked
* up that has an alias defined for the given code, and if found the alias is returned. If no
* SRS is registered nor an alias is found, a new SRS for this code is registered and returned.
*
* @param epsgCode
* @return
*/
public static SRS getSRS(final int epsgCode) {
final Integer code = Integer.valueOf(epsgCode);
final SRS existing = list.get(code);
if (existing != null) {
return existing;
}
for (SRS candidate : new ArrayList<SRS>(list.values())) {
if (candidate.aliases != null && candidate.aliases.contains(Integer.valueOf(code))) {
list.put(code, candidate);
return candidate;
}
}
return new SRS(epsgCode);
}
public static SRS getSRS(String epsgStr) throws <API key> {
final String crsAuthPrefix = "EPSG:";
if (epsgStr.substring(0, 5).equalsIgnoreCase(crsAuthPrefix)) {
int epsgNumber = Integer.parseInt(epsgStr.substring(5, epsgStr.length()));
return getSRS(epsgNumber);
} else {
throw new <API key>("Can't parse " + epsgStr + " as SRS string.");
}
}
/**
* Two SRS are equal if they have the same code or any of them have the other one as an alias.
*
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (!(obj instanceof SRS)) {
return false;
}
boolean equivalent = false;
SRS other = (SRS) obj;
if (other.number == this.number) {
equivalent = true;
} else if (this.aliases != null && other.aliases != null) {
equivalent = this.aliases.contains(other.number) || other.aliases.contains(this.number);
}
return equivalent;
}
/**
* @deprecated just use {@link #equals}
*/
public boolean <API key>(Object o) {
return equals(o);
}
public int getNumber() {
return number;
}
@Override
public int hashCode() {
return number;
}
public String toString() {
return "EPSG:" + Integer.toString(number);
}
public static SRS getEPSG4326() {
return EPSG4326;
}
public static SRS getEPSG3857() {
return EPSG3857;
}
public static SRS getEPSG900913() {
return EPSG900913;
}
/**
* @see java.lang.Comparable#compareTo(java.lang.Object)
*/
public int compareTo(SRS other) {
return number - other.number;
}
} |
package cf.monteux.silvertunnel.netlib.util;
import java.io.<API key>;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.<API key>;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import cf.monteux.silvertunnel.netlib.api.NetLayer;
import cf.monteux.silvertunnel.netlib.api.NetSocket;
import cf.monteux.silvertunnel.netlib.api.util.TcpipNetAddress;
import cf.monteux.silvertunnel.netlib.layer.tor.util.Util;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
/**
* This class provides simple methods to access HTTP - they can be used for
* testing.
*
* The class should not be used in productive environments (because these
* methods do not handle all edge cases). Consider to use class HttpClient in
* productive environments.
*
* This method does NOT internally use java.net.URL.
*
* @author hapke
* @author Tobias Boese
*/
public class HttpUtil
{
private static final Logger logger = LogManager.getLogger(HttpUtil.class);
public static final String <API key> = "httptest.silvertunnel-ng.org";
public static final int <API key> = 80;
public static final TcpipNetAddress <API key> = new TcpipNetAddress(<API key>, <API key>);
private static HttpUtil instance = new HttpUtil();
public static HttpUtil getInstance()
{
return instance;
}
/**
* Try to execute the /httptest/smalltest.php over the provided net socket
* with a random id.
*
* Closes the socket after the test.
*
* @param lowerLayerNetSocket
* this net socket will be closed inside the method
* @param idPrefix
* only digits and ASCII letters, becomes part of the id sent to
* the server
* @param timeoutInMs
* @return true=test OK; false=test failed
* @throws IOException
*/
public boolean executeSmallTest(NetSocket lowerLayerNetSocket,
String idPrefix, long timeoutInMs) throws IOException
{
// generate the id
final int randomNo = (int) (1000000000 * Math.random());
final String id = idPrefix + randomNo;
// communicate with the remote side
final byte[] httpResponse = get(lowerLayerNetSocket,
HttpUtil.<API key>,
"/httptest/smalltest.php?id=" + id, timeoutInMs);
// check response
logger.info("http response body: " + ByteArrayUtil.showAsString(httpResponse));
final byte[] expectedResponse = ("<response><id>" + id + "</id></response>\n").getBytes(Util.UTF8);
final boolean testOK = Arrays.equals(expectedResponse, httpResponse);
if (testOK)
{
logger.info("http response body = expected response body");
}
else
{
logger.info("expected http response body is different: "
+ ByteArrayUtil.showAsString(expectedResponse));
}
lowerLayerNetSocket.close();
return testOK;
}
/**
* Execute a simple HTTP 1.1 request and read the response.
*
* @param lowerNetLayer
* @param <API key>
* @param pathOnHttpServer
* @param timeoutInMs
* do not wait longer the the specified milliseconds
* @return
* @throws IOException
*/
public byte[] get(final NetLayer lowerNetLayer,
final TcpipNetAddress <API key>,
final String pathOnHttpServer,
final long timeoutInMs) throws IOException
{
// open network connection
final NetSocket s = lowerNetLayer.createNetSocket(null, null, <API key>);
return get(s, <API key>, pathOnHttpServer, timeoutInMs);
}
/**
* Execute a simple HTTP 1.1 request and provide the response body as
* InputStream. The response header is not part of the returned InputStream.
*
* @param lowerLayerNetSocket
* @param <API key>
* @param pathOnHttpServer
* @param timeoutInMs
* do not wait longer the the specified milliseconds
* @return the response body
* @throws IOException
*/
public InputStream <API key>(final NetSocket lowerLayerNetSocket,
final TcpipNetAddress <API key>,
final String pathOnHttpServer,
final long timeoutInMs) throws IOException
{
final byte[] responseBody = get(lowerLayerNetSocket, <API key>, pathOnHttpServer, timeoutInMs);
return new <API key>(responseBody);
}
/**
* Execute a simple HTTP 1.1 request and read the response.
*
* @param lowerLayerNetSocket
* @param <API key>
* @param pathOnHttpServer
* @param timeoutInMs
* do not wait longer than the specified milliseconds
* @return the response body
* @throws IOException
*/
public static byte[] get(final NetSocket lowerLayerNetSocket,
final TcpipNetAddress <API key>,
final String pathOnHttpServer,
final long timeoutInMs) throws IOException
{
try
{
final String request = "GET " + pathOnHttpServer + " HTTP/1.1\n"
+ "Host: " + getCleanHostname(<API key>.<API key>())
+ "\n"
// disable keep-alive
+ "Connection: close\n" + "\n";
final byte[] requestBytes = request.getBytes(Util.UTF8);
// do the work
return request(lowerLayerNetSocket, <API key>, pathOnHttpServer, requestBytes, timeoutInMs);
}
catch (final <API key> e)
{
logger.error("this exception may never occur", e);
throw new IOException(e.toString());
}
}
/**
* Get a clean hostname.
*
* removes the exit-node fingerprint and the .exit from hostname
*
* @param hostname the hostname which needs to be cleaned
* @return the cleaned hostname
*/
private static String getCleanHostname(final String hostname)
{
if (hostname.endsWith(".exit"))
{
String tmp = hostname.substring(0, hostname.length() - 5);
tmp = tmp.substring(0, tmp.lastIndexOf('.'));
return tmp;
}
return hostname;
}
/**
* Execute a simple HTTP 1.1 post and read the response.
*
* @param lowerLayerNetSocket
* @param <API key>
* @param pathOnHttpServer
* @param timeoutInMs
* do not wait longer the the specified milliseconds
* @return the response body
* @throws IOException
*/
public byte[] post(final NetSocket lowerLayerNetSocket,
final TcpipNetAddress <API key>,
final String pathOnHttpServer,
final byte[] dataToPost,
final long timeoutInMs) throws IOException
{
try
{
final String request = "POST " + pathOnHttpServer + " HTTP/1.1\r\n"
+ "Host: " + <API key>.<API key>()
+ "\r\n" + "Content-Type: text/plain; charset=utf-8\r\n"
+ "Content-Length: " + dataToPost.length + "\r\n"
// disable keep-alive
+ "Connection: close\r\n" + "\r\n";
final byte[] requestBytes1 = request.getBytes(Util.UTF8);
final byte[] requestBytes = ByteArrayUtil.concatByteArrays(requestBytes1, dataToPost);
// TODO - remove?:
logger.info("<API key>=" + <API key> + " with request=" + new String(requestBytes, Util.UTF8));
// do the work
final byte[] response = request(lowerLayerNetSocket,
<API key>, pathOnHttpServer, requestBytes,
timeoutInMs);
// result
if (logger.isDebugEnabled())
{
try
{
logger.debug("response=" + new String(response, Util.UTF8));
}
catch (final Exception e)
{
logger.debug("response={}", Arrays.toString(response));
}
}
return response;
}
catch (final <API key> e)
{
logger.error("this exception may never occur", e);
throw new IOException(e.toString());
}
}
/**
* Execute a simple HTTP 1.1 get or post request and read the response.
*
* @param lowerLayerNetSocket
* @param <API key>
* @param pathOnHttpServer
* @param timeoutInMs
* do not wait longer the the specified milliseconds
* @return the response body
* @throws IOException
*/
private static byte[] request(final NetSocket lowerLayerNetSocket,
final TcpipNetAddress <API key>,
final String pathOnHttpServer,
final byte[] requestBytes,
final long timeoutInMs) throws IOException
{
final long startTime = System.currentTimeMillis();
// open network connection
final NetSocket s = lowerLayerNetSocket;
// receive HTTP response
// (start the extra thread before sending the HTTP request
// to avoid dead locks in certain circumstances)
final <API key> receiverThread = new <API key>(s.getInputStream());
// send HTTP request
final OutputStream os = s.getOutputStream();
try
{
logger.info("send HTTP request now: " + ByteArrayUtil.showAsString(requestBytes));
os.write(requestBytes);
}
catch (final <API key> e)
{
logger.error("this exception may never occur", e);
}
os.flush();
receiverThread.start();
// wait for receiving data
final long millis = Math.max(100, timeoutInMs - (System.currentTimeMillis() - startTime));
try
{
receiverThread.join(millis);
}
catch (final <API key> e)
{
// to ignore
logger.debug("got IterruptedException", e.getMessage());
}
// read the HTTP response from the other thread
final byte[] response = receiverThread.<API key>();
s.close();
if (logger.isDebugEnabled())
{
try
{
logger.debug("response=" + new String(response, Util.UTF8));
}
catch (final Exception e)
{
logger.debug("response=" + response);
}
}
// split response header and body
int endOfHeaders = response.length;
int startOfBody = response.length + 1;
for (int i = 0; i < response.length; i++)
{
if (i + 1 < response.length && response[i] == '\n'
&& response[i + 1] == '\n')
{
endOfHeaders = i;
startOfBody = i + 2;
break;
}
else if (i + 3 < response.length)
{
if (response[i] == '\n' && response[i + 1] == '\r'
&& response[i + 2] == '\n' && response[i + 3] == '\r')
{
endOfHeaders = i;
startOfBody = i + 4;
break;
}
if (response[i] == '\r' && response[i + 1] == '\n'
&& response[i + 2] == '\r' && response[i + 3] == '\n')
{
endOfHeaders = i;
startOfBody = i + 4;
break;
}
}
}
final byte[] responseHeaders = new byte[endOfHeaders];
if (endOfHeaders > 0)
{
System.arraycopy(response, 0, responseHeaders, 0, endOfHeaders);
}
final int bodyLen = Math.max(0, response.length - startOfBody);
byte[] responseBody = new byte[bodyLen];
if (bodyLen > 0)
{
System.arraycopy(response, startOfBody, responseBody, 0, bodyLen);
}
// need to handle chunked HTTP response?
final String <API key> = ByteArrayUtil.showAsString(responseHeaders);
final String <API key> = "Transfer-Encoding: chunked";
if (<API key>.contains(<API key>))
{
// yes: handle chunked response
responseBody = <API key>(responseBody);
}
// short log of results
logger.info("received HTTP response header: " + <API key>);
logger.info("received HTTP response body of " + responseBody.length + " bytes");
// result
return responseBody;
}
/**
* Decode a chunked HTTP response.
*
* @param chunkedResponse
* @return the decoded response
*/
protected static byte[] <API key>(final byte[] chunkedResponse)
{
final List<Byte> result = new ArrayList<Byte>(chunkedResponse.length);
StringBuffer chunkLenStr = new StringBuffer();
for (int i = 0; i < chunkedResponse.length;)
{
// end of chunk header?
final int offset = isNewLine(chunkedResponse, i);
if (offset > 0)
{
// yes: end of chunk header
// convert hex length value to int
i += offset;
final int HEX_RADIX = 16;
int chunkLength = Integer.parseInt(chunkLenStr.toString(),
HEX_RADIX);
if (chunkLength == 0)
{
// found the end
break;
}
else
{
for (; i < chunkedResponse.length && chunkLength > 0; i++, chunkLength
{
result.add(chunkedResponse[i]);
}
// prepare collecting the byte of the next chunk header
chunkLenStr = new StringBuffer();
i += isNewLine(chunkedResponse, i);
}
}
else
{
// no: this is part of the chunk header
chunkLenStr.append((char) chunkedResponse[i++]);
}
}
// end reached: convert result
final byte[] <API key> = new byte[result.size()];
for (int i = 0; i < <API key>.length; i++)
{
<API key>[i] = result.get(i);
}
return <API key>;
}
/**
* Check whether the index points to a 1 or 2 byte long new line.
*
* @param data
* @param index
* @return 1=1 byte new line; 2=2 byte new lin; 0=no new line in data at
* position index
*/
private static int isNewLine(final byte[] data, final int index)
{
if (index + 1 < data.length
&& ((data[index] == '\n' && data[index + 1] == '\r') || data[index] == '\r'
&& data[index + 1] == '\n'))
{
// found 2 byte new line
return 2;
}
else if (index < data.length && data[index] == '\n')
{
// line
return 1;
}
else
{
return 0;
}
}
} |
<!DOCTYPE HTML>
<html>
<head>
<script>
/**
* Global variables for scalable content.
*/
var width = 900;
var height = 2 * width / 3;
var globalFont = 'Arial';
var functionStrokeWidth = width / 90;
var <API key> = functionStrokeWidth / 2;
var <API key> = width / 20;
var <API key> = <API key> - functionStrokeWidth;
var functionColor = '#508C37';
var valueSideLength = <API key> / 1.414;
var valueXYColor = 'gray'
var valueTimeColor = 'gold'
var valueConstantColor = 'purple'
var imageBoxSideLength = width / 80;
var imageBoxColor = 'white'
var <API key> = width / 300;
var valueImageBoxOffset = width / 30;
var outletXOffset = width / 255;
var outletYOffset = <API key> / 3;
var outletColor = '#FFC440';
var lineStrokeWidth = 2;
var menuHeight = width / 9;
var menuCornerWidth = width / 5;
var valMenuXSpacing = width / 32;
var functMenuXSpacing = width / 68;
var menuYspacing = width * 11/360;
var buttonWidth = width / 10;
var menuFunctsXStart = 2 * (buttonWidth - <API key>) + menuCornerWidth- <API key> / 2;
var menuFunctsXEnd = width - buttonWidth + <API key> / 2;
var menuValuesXStart = menuCornerWidth + buttonWidth / 2;
var menuAnimDuration = 1;
</script>
<script>
/**
* Arrays of the basic function and value names, and tables of their specific settings
*/
var funNames = ['add', 'multiply', 'negate', 'sine', 'cosine', 'absolute', 'average', 'sign', 'rgb'];
var functions = {
add: {rep: '+', max: 20, min: 2},
multiply: {rep: '*', max: 20, min: 2},
negate: {rep: '-', max: 1, min: 1},
sine: {rep: 'sin', max: 1, min: 1},
cosine: {rep: 'cos', max: 1, min: 1},
absolute: {rep: 'abs', max: 1, min: 1},
average: {rep: 'ave', max: 20, min: 2},
sign: {rep: 'sign',max: 1, min: 1},
wrap: {rep: 'wrap',max: 1, min: 1},
rgb: {rep: 'rgb', max: 3, min: 3}
}
var valNames = ['x', 'y', 'second', 'minute', 'hour', 'day', 'constant'];
var values = {
x: {rep: 'x', max: 20, min: 2, color: valueXYColor},
y: {rep: 'y', max: 20, min: 2, color: valueXYColor},
second: {rep: 't.s', max: 1, min: 1, color: valueTimeColor},
minute: {rep: 't.m', max: 1, min: 1, color: valueTimeColor},
hour: {rep: 't.h', max: 1, min: 1, color: valueTimeColor},
day: {rep: 't.d', max: 1, min: 1, color: valueTimeColor},
constant: {rep: '', max: 20, min: 2, color: valueConstantColor},
}
</script>
<style>
body {
margin: 0px;
padding: 0px;
}
#container {
background-color: rgb(241, 248, 255);
width: 900px;
height: 600px;
}
</style>
</head>
<body>
<div id="container"></div>
<script src="http:
</script>
<script src="http://d3lp1msu2r81bx.cloudfront.net/kjs/js/lib/kinetic-v5.1.0.min.js">
</script>
<script defer="defer">
var stage = new Kinetic.Stage({
container: 'container',
width: width,
height: height
});
/**
* Layers of the workspace:
* 1. The line layer holds connecting lines between nodes in the work area.
* 2. The menu layer holds the buttons that users can click on to drag a new node into
* the work area.
* 3. The menuButton layer holds the super buttons that are used to expand the menus.
* 4. The work layer holds all active nodes that are either connected or available to
* be connected.
* 5. The border layer stores static elements of the page such as dividing lines.
* 6. The drag layer holds nodes while they are being moved about the workspace.
*/
var lineLayer = new Kinetic.Layer();
var menuLayer = new Kinetic.Layer();
var menuButtonLayer = new Kinetic.Layer();
var workLayer = new Kinetic.Layer();
var borderLayer = new Kinetic.Layer();
var dragLayer = new Kinetic.Layer();
/**
* Add the layers to the stage. The top layer is the one most recently added, and
* objects within a layer follow the same logic.
*/
stage.add(lineLayer);
stage.add(menuLayer);
stage.add(menuButtonLayer);
stage.add(workLayer);
stage.add(borderLayer);
stage.add(dragLayer);
//UTILITY FUNCTIONS
/*
isFunction determines if target is a functionGroup and returns a boolean value.
target is an object.
*/
var isFunction = function(target) {
return (target.attrs.maxInputs != null);
};
/*
isValue determines if target is a valueGroup and returns a boolean value.
target is an object.
*/
var isValue = function(target) {
return (target.attrs.maxInputs == null);
};
/*
isOutlet determines if target is an outletGroup and returns a boolean value.
target is an object.
*/
var isOutlet = function(target) {
return (target.name() != null && target.attrs.name.substring(0,6) == 'outlet');
};
/*
isLine determines if target is a line and returns a boolean value.
target is an object.
*/
var isLine = function(target) {
return (target.attrs.outlet != null);
};
var isImageBox = function(target) {
return (target.name() != null && target.attrs.name == 'imageBox');
}
// CONSTRUCTORS
/*
Function nodes and Value nodes are groups of objects. Members of groups can
be accessed through the array 'group'.children[].
Children are stored in the following order:
0. Underlying Shape
1. Text
2. render box
3+. Outlet nodes (only for functions)
*/
/*
makeFunctionGroup takes a string funName, a key in the functions object above,
an integer x, and an integer y, and returns the corresponding function node object,
with top right corner at the given x, y coordinate.
*/
var makeFunctionGroup = function(funName, x, y) {
/* create group that will contain information on the function and the shapes making up the representation on screen. */
var newGroup = new Kinetic.Group({
name: funName,
x: x - <API key>,
y: y,
numInputs: 0,
maxInputs: functions[funName].max,
minInputs: functions[funName].min,
lineOut: [],
funct: funName,
index: functions[funName].index,
visible: false,
renderLayer: null
});
/* create rectangle shape */
var newRect = new Kinetic.Rect({
name: funName,
x: <API key>,
y: <API key>,
width: <API key>,
height: <API key>,
fill: functionColor,
lineJoin: 'round',
stroke: functionColor,
strokeWidth: functionStrokeWidth
});
newGroup.add(newRect);
/* create text to be displayed on top of rectangle */
var newText = new Kinetic.Text({
text: functions[funName].rep,
fontFamily: globalFont,
fill: 'black',
fontSize: 16,
x: 0,
y: <API key>/2 - <API key>,
width: <API key>,
align: 'center'
});
newGroup.add(newText);
/* create small box in the bottom right corner. Originally is not visible.*/
var newBox = new Kinetic.Rect({
name: 'imageBox',
x: <API key> + <API key>,
y: <API key> + <API key>,
width: imageBoxSideLength,
height: imageBoxSideLength,
fill: imageBoxColor,
stroke: 'black',
strokeWidth: .5,
visible: false,
expanded: false
});
newGroup.add(newBox);
return newGroup;
};
/*
makeValueGroup takes a string valName, the name of a key in the values object above,
an integer x, and an integer y, and returns the corresponding function node object,
centered at (x + width / 40, y + width / 40).
*/
var makeValueGroup = function(valName, x, y) {
/* create group that contains information on the value and shapes to be displayed. */
var newGroup = new Kinetic.Group({
name: valName,
x: x,
y: y,
lineOut: [],
index: values[valName].index,
visible: false,
renderLayer: null
});
/* create diamond shape. */
var newRect = new Kinetic.Rect({
x: <API key>/2,
y: 0,
width: valueSideLength,
height: valueSideLength,
fill: values[valName].color,
rotation: 45,
name: valName
});
newGroup.add(newRect);
/* create text to be displayed on diamond. */
var newText = new Kinetic.Text({
text: values[valName].rep,
fontFamily: 'OpenSans',
fill: 'black',
fontSize: 16,
x: 0,
y: valueSideLength/2,
width: <API key>,
align: 'center'
});
newGroup.add(newText);
/* create small box in bottom right corner. Originally not visible. */
var newBox = new Kinetic.Rect({
name: 'imageBox',
x: valueImageBoxOffset,
y: valueImageBoxOffset,
width: imageBoxSideLength,
height: imageBoxSideLength,
fill: imageBoxColor,
stroke: 'black',
strokeWidth: .5,
visible: false,
expanded: false
});
newGroup.add(newBox);
return newGroup;
};
/*
makeOutlet takes a function node object, functGroup, and returns an outlet node object
to be added to that group.
It DOES NOT add the outlet to the group.
*/
var makeOutlet = function(functGroup) {
var bezPoint = width / 50;
var outlet = new Kinetic.Shape({
sceneFunc: function(context) {
context.beginPath();
context.moveTo(0, 0);
context.bezierCurveTo(-bezPoint, -bezPoint, -bezPoint, bezPoint, 0, 0);
context.closePath();
context.fillStrokeShape(this);
},
name: 'outlet' + (functGroup.children.length - 3),
x:functGroup.children[0].x() + outletXOffset,
y:functGroup.children[0].y() + (functGroup.children.length - 3) * outletYOffset + <API key>,
fill: '#FFC440',
stroke: 'black',
strokeWidth: 1,
lineIn: null
});
return outlet;
};
/*
makeLine takes either a functionGroup object or valueGroup object as input (source) and creates a line that begins at the left edge of source.
*/
var makeLine = function(source) {
var newLine = new Kinetic.Line({
points: [
source.x() + <API key> - 3,
source.y() + <API key> / 2,
source.x() + <API key>,
source.y() + <API key> / 2,
],
stroke: 'black',
strokeWidth: lineStrokeWidth,
source: source,
sourceIndex: source.attrs.lineOut.length,
outlet: null
});
return newLine;
}
/*
makeMenuTween takes a node (target), an integer (xEnd), and a boolean (visibility). It returns a kinetic tween that will move target to xEnd, without changing y value; and with the visibility to the specified boolean values.*/
var makeMenuTween = function(target, xEnd, visibility) {
return new Kinetic.Tween({
node: target,
duration: menuAnimDuration,
x: xEnd,
visible: visibility,
easing: Kinetic.Easings.StrongEaseOut
});
};
//METHODS
/*
addOutlet takes a function group funGroup and adds an outlet to it, expanding the node if there is not enough space for the outlet.
*/
var addOutlet = function(funGroup) {
if(funGroup.children.length - 3 < funGroup.attrs.maxInputs) {
if(funGroup.children.length - 3 > 2) {
funGroup.children[0].setAttr('height',
funGroup.children[0].attrs.height + outletYOffset);
funGroup.children[1].setAttr('y', funGroup.children[1].attrs.y + outletYOffset / 2);
}
var newOutlet = makeOutlet(funGroup);
funGroup.add(newOutlet);
workLayer.draw();
}
};
/*
checkBoxValidity takes a functionGroup and determines if its render box should be visible or not, and changes whether the box is visible.
*/
var checkBoxValidity = function(parent) {
if (parent.attrs.numInputs >= parent.attrs.minInputs) {
parent.children[2].setAttr('visible', true);
} else {
parent.children[2].setAttr('visible', false);
}
}
/*
renderCanvas takes a function or value group and renders a 50 by 50 image starting where the image box is located.
*/
var renderCanvas = function(group) {
var currLayer = group.attrs.renderLayer;
if (currLayer == null){
currLayer = new Kinetic.Layer();
group.setAttr('renderLayer', currLayer);
stage.add(currLayer);
}
group.children[2].setAttrs({
width: 50,
height: 50
});
var box = group.children[2];
canvas = currLayer.canvas._canvas;
renderFun(MOIbody2fun("x+y+t.s"), canvas, group.x() + box.x(), group.y() + box.y(), 50, 50);
};
// Create functions to Move Menu Items
/* move the valueGroups in the menu to their original location. */
var moveValueNodesIn = function() {
for (var i = 0; i < menuValues.length; i++) {
var moveValue = makeMenuTween(menuValues[i], menuValuesXStart, false);
moveValue.play();
}
};
/* move the valueGroups to their expanded location. */
var expandValueNodes = function() {
for (var i = 0; i < menuValues.length; i++) {
var moveValue = makeMenuTween(menuValues[i], menuCornerWidth + buttonWidth + valMenuXSpacing + i * (valMenuXSpacing + <API key>), true);
moveValue.play();
}
};
/* move the functionGroups to their original position. */
var moveFunctionNodesIn = function() {
for (var i = 0; i < menuFunctions.length; i++) {
var moveFunction = makeMenuTween(menuFunctions[i], menuFunctsXStart, false);
moveFunction.play();
}
};
/* move the functionGroups to the right of the screen. (For when values are expanded).*/
var <API key> = function() {
for (var i = 0; i < menuFunctions.length; i++) {
var moveFunction = makeMenuTween(menuFunctions[i], menuFunctsXEnd, false);
moveFunction.play();
}
};
/* move the functionGroups to their expanded position. */
var expandFunctionNodes = function() {
for (var i = 0; i < menuFunctions.length; i++) {
var moveFunction = makeMenuTween(menuFunctions[i], menuCornerWidth + 2 * buttonWidth + functMenuXSpacing + i * (functMenuXSpacing + <API key>), true)
moveFunction.play();
}
}
/* move the functionsButton to the right of the screen (for when values are expanded). */
var <API key> = function() {
var moveButton = makeMenuTween(functionsButton, width - buttonWidth, true)
moveButton.play();
};
/* move the functionsButon to it's original position. */
var <API key> = function() {
var moveButton = makeMenuTween(functionsButton, menuCornerWidth + buttonWidth, true)
moveButton.play();
};
//SETUP STAGE
/* create and add menu border */
var borderLine = new Kinetic.Line({
points: [0, menuHeight, width, menuHeight],
stroke: 'black',
strokeWidth: 2
});
borderLayer.add(borderLine);
borderLayer.draw();
/* create and add menu buttons */
var valuesButton = new Kinetic.Group({
x: menuCornerWidth
});
menuButtonLayer.add(valuesButton);
var valuesButtonBox = new Kinetic.Rect({
x:0,
y:0,
width: buttonWidth,
height: menuHeight,
fill: 'lavender',
stroke: 'black',
strokeWidth: 2
});
valuesButton.add(valuesButtonBox);
var valuesButtonRect = new Kinetic.Rect({
x: buttonWidth / 2,
y: menuHeight / 4,
width: valueSideLength,
height: valueSideLength,
fill: 'purple',
rotation: 45,
});
valuesButton.add(valuesButtonRect);
var valuesButtonText = new Kinetic.Text({
text: 'add a value',
x: 0,
y: menuHeight / 2 + menuHeight / 4,
width: buttonWidth,
height: menuHeight / 4,
fill: 'black',
align: 'center'
});
valuesButton.add(valuesButtonText);
var functionsButton = new Kinetic.Group({
x: menuCornerWidth + buttonWidth
});
menuButtonLayer.add(functionsButton);
var functionsButtonBox = new Kinetic.Rect({
x:0,
y:0,
width: buttonWidth,
height: menuHeight,
fill: '#D7EBCF',
stroke: 'black',
strokeWidth: 2
});
functionsButton.add(functionsButtonBox);
var functionsButtonRect = new Kinetic.Rect({
x: buttonWidth / 2 - <API key> / 2,
y: menuHeight / 4,
width: <API key>,
height: <API key>,
fill: functionColor,
lineJoin: 'round',
stroke: functionColor,
strokeWidth: functionStrokeWidth
});
functionsButton.add(functionsButtonRect);
var functionsButtonText = new Kinetic.Text({
text: 'add a function',
x: 0,
y: menuHeight / 2 + menuHeight / 4,
width: buttonWidth,
height: menuHeight / 4,
fill: 'black',
align: 'center'
});
functionsButton.add(functionsButtonText);
menuButtonLayer.draw();
/* add functions to menu */
var menuFunctions = [];
for (var i = 0; i < funNames.length; i++) {
menuFunctions[i] = makeFunctionGroup(funNames[i], menuFunctsXStart, menuYspacing);
menuLayer.add(menuFunctions[i]);
}
/* add values to menu */
var menuValues = [];
for (var i = 0; i < valNames.length; i++) {
menuValues[i] = makeValueGroup(valNames[i], menuValuesXStart, menuYspacing);
menuLayer.add(menuValues[i]);
}
stage.draw();
//MENU ANIMATIONS
var valueExpanded = false;
var functionExpanded = false;
/*
On click of value menu button:
1. Neither values or functions are expanded.
- move functionsButton right.
- expand values
2. Values are not expanded, functions are expanded.
- collapse functions to the right and move functionsButon
- expand values
3. Values are expanded, functions are not.
- collapse values
- move functionsButton left.
*/
valuesButton.on('click', function(){
if (!valueExpanded) {
if (!functionExpanded) {
<API key>();
<API key>();
expandValueNodes();
valueExpanded = true;
} // if functions are also not expanded
else {
<API key>();
<API key>();
expandValueNodes();
valueExpanded = true;
functionExpanded = false;
} // else functions were already expanded
} // if values are not expanded
else {
moveValueNodesIn();
moveFunctionNodesIn();
<API key>();
valueExpanded = false;
} // else values were already expanded
});
/*
On click of function menu button:
1. Neither functions or values are expanded.
- expand functions
2. Functions are not expanded, values are expanded.
- collapse values
- move functionsButton left
- expand functions
3. Functions are expanded, values are not.
- collapse functions
*/
functionsButton.on('click', function(){
if (!functionExpanded) {
if (!valueExpanded) {
expandFunctionNodes();
functionExpanded = true;
} // functions and values not expanded
else {
moveValueNodesIn();
<API key>();
expandFunctionNodes();
functionExpanded = true;
valueExpanded = false;
} // functions not expanded, values expanded
}
else {
moveFunctionNodesIn();
functionExpanded = false;
} // functions are expanded
});
// ADDING TO WORKSPACE
/* variables to globally reference the most recently used object/line */
var currShape;
var currLine;
var makingLine = false;
var animation = false;
/*
On mousedown of a menu object (value or function prototype), you create a copy of that object and begin to draw it.
*/
menuLayer.on('mousedown', function(evt) {
if (!makingLine) {
var group = evt.target.getParent();
if (isFunction(group)) {
var newGroup = makeFunctionGroup(group.attrs.name, group.attrs.x, group.attrs.y);
} else {
var newGroup = makeValueGroup(group.attrs.name, group.attrs.x, group.attrs.y);
} // if function / else value
newGroup.setAttr('visible', true);
dragLayer.add(newGroup);
newGroup.startDrag();
dragLayer.draw();
}
});
/*
when an object being dragged is released:
1. check that it isnt in the menu area
--if it is a new object, add the appropriate number of outlets to it
2. if its in the menu area destroy it and all lines attached to it
*/
dragLayer.on('mouseup', function(evt) {
var group = evt.target.getParent();
if (group.attrs.y > menuHeight) {
group.moveTo(workLayer);
if (isFunction(group) && group.children.length < 4) {
for (var i = 0; i < functions[group.attrs.name].min; i++) {
addOutlet(group);
} // for
}
if (group.children[2].attrs.expanded) {
console.log("im here");
renderCanvas(group);
}
} else {
var targetLine;
for(var i = 0; i < group.children.length - 3; i++) {
targetLine = group.children[i+3].attrs.lineIn;
if(targetLine != null) {
targetLine.attrs.outlet = null;
targetLine.attrs.source.attrs.lineOut[targetLine.attrs.sourceIndex].destroy();
}
}
var outletParent;
for(var i = 0; i < group.attrs.lineOut.length; i++) {
targetLine = group.attrs.lineOut[i];
if (targetLine.attrs.outlet != null) {
outletParent = targetLine.attrs.outlet.getParent();
outletParent.attrs.numInputs
targetLine.attrs.outlet.attrs.lineIn = null;
checkBoxValidity(outletParent);
}
targetLine.destroy();
}
lineLayer.draw();
group.destroy();
}
menuButtonLayer.draw();
menuLayer.draw();
dragLayer.draw();
workLayer.draw();
});
/*
When you click down on an object in the workLayer and arent in the process of making
a line, move that object to the dragLayer and allow it to be dragged.
*/
workLayer.on('mousedown', function(evt) {
if (!makingLine && !isImageBox(evt.target)) {
var group = evt.target.getParent();
group.moveTo(dragLayer);
currShape = group;
group.startDrag();
workLayer.draw();
dragLayer.draw();
if (group.attrs.renderLayer != null) {
group.attrs.renderLayer.draw();
}
}
});
/*
when you double click on an object in the workLayer and you arent already drawing a
line, you should begin drawing a line starting from that object.
*/
workLayer.on('dblclick', function(evt) {
if (!makingLine) {
makingLine = true;
var group = evt.target.getParent();
currLine = makeLine(group);
group.attrs.lineOut[group.attrs.lineOut.length] = currLine;
lineLayer.add(currLine);
lineLayer.draw();
}
});
/*
while you are drawing a line, make it move with the cursor.
*/
stage.addEventListener('contentMousemove', function(){
if(makingLine) {
currLine.points()[2] = stage.getPointerPosition().x;
currLine.points()[3] = stage.getPointerPosition().y;
lineLayer.draw();
}
});
/*
while making a line, make outlets grow when they are moused over to signify that they
are valid connections
*/
workLayer.on('mouseover', function(evt) {
var shape = evt.target;
if (makingLine) {
if (isOutlet(shape)) {
shape.scale({
x: 1.5,
y: 1.5
});
workLayer.draw();
} // if outlet
} // if makingLine
else if (isImageBox(shape) && shape.attrs.expanded) {
animation = true;
var frame = function() {
renderCanvas(shape.getParent());
if (animation) {
setTimeout(frame, 50);
}
}
console.log("im here");
frame();
}
});
/*
when the cursor is moved out of an outlet while drawing a line, return it to its
original size
*/
workLayer.on('mouseout', function(evt) {
var shape = evt.target;
if (makingLine) {
if (isOutlet(shape)) {
shape.scale({
x: 1,
y: 1
});
workLayer.draw();
} // if outlet
} // if makingLine
else if (isImageBox(shape) && shape.attrs.expanded) {
animation = false;
}
});
/*
When making a line, form a connection on click if the click was on an outlet.
Behind the scenes:
1. if the object clicked was the source of the line, destroy the line.
2. If the outlet already had a connection, make that connection null and destroy it
--otherwise, this is connected to a new outlet so increment numInputs for the group
3. set connections within the line and its outlet, so line has a reference to the
outlet, and the outlet has a reference to the line
--make the line stick to the outlet
--set makingLine = false
--shrink the outlet back to its original size
--check if we have enough outlets to show the render box
4. if we have all visible outlets filled but the function can take more inputs, add
an outlet.
5. otherwise keep drawing the line.
*/
workLayer.on('click', function(evt) {
var shape = evt.target;
var parent = shape.getParent();
if (makingLine) {
if (shape.getParent() === currLine.attrs.source) {
currLine.attrs.source.attrs.lineOut[currLine.attrs.source.attrs.lineOut.length - 1].destroy();
currLine.destroy();
if (isOutlet(shape)) {
shape.scale({ x: 1, y: 1 });
}
makingLine = false;
} else if (isOutlet(shape)) {
//check if outlet already has an input
if (shape.attrs.lineIn != null) {
//POSSIBLE NEED TO DESTROY LINE ITSELF
shape.attrs.lineIn.attrs.source.attrs.lineOut[shape.attrs.lineIn.attrs.sourceIndex].attrs.outlet = null;
shape.attrs.lineIn.attrs.source.attrs.lineOut[shape.attrs.lineIn.attrs.sourceIndex].destroy();
} else {
parent.attrs.numInputs++;
}
shape.attrs.lineIn = currLine;
currLine.points()[2] = parent.x();
currLine.points()[3] = parent.y() + shape.y();
currLine.attrs.outlet = shape;
makingLine = false;
shape.scale({ x: 1, y: 1 });
checkBoxValidity(parent);
if (parent.attrs.numInputs == parent.children.length - 3 &&
parent.attrs.numInputs < parent.attrs.maxInputs) {
addOutlet(parent);
}
} // if clicked on self, else clicked on a valid outlet
workLayer.draw();
lineLayer.draw();
} // if makingLine
else if (isImageBox(shape)) {
if (!shape.attrs.expanded) {
renderCanvas(parent);
shape.attrs.expanded = true;
} else {
shape.attrs.expanded = false;
animation = false;
var collapseCanvas = function(){
parent.attrs.renderLayer.destroy();
parent.attrs.renderLayer = null;
parent.children[2].setAttrs({
width: imageBoxSideLength,
height: imageBoxSideLength
});
}
setTimeout(collapseCanvas, 50);
}
setTimeout(function() {workLayer.draw()}, 50);
}
});
/*
While an object is being dragged, move all lines connected to it with it.
*/
dragLayer.on('draw', function() {
if(currShape != null) {
var targetLine;
for(var i = 0; i < currShape.children.length - 3; i++) {
targetLine = currShape.children[i+3].attrs.lineIn;
if(targetLine != null) {
targetLine.points()[2] = currShape.x();
targetLine.points()[3] = currShape.y() + currShape.children[i+3].y();
}
}
for(var i = 0; i < currShape.attrs.lineOut.length; i++) {
targetLine = currShape.attrs.lineOut[i];
targetLine.points()[0] = currShape.x() + <API key> - 3;
targetLine.points()[1] = currShape.y() + <API key> / 2;
}
lineLayer.draw();
}
});
</script>
</body>
<html> |
#ifndef <API key>
#define <API key>
#include "core/Query.h"
#include "core/use_cases/SprintDTO.h"
#include "date_wrapper/date_wrapper.h"
namespace sprint_timer::use_cases {
struct RequestSprintsQuery : public Query<std::vector<SprintDTO>> {
explicit RequestSprintsQuery(dw::DateRange dateRange);
dw::DateRange dateRange;
friend bool operator==(const RequestSprintsQuery&,
const RequestSprintsQuery&) = default;
};
template <class CharT, class Traits>
std::basic_ostream<CharT, Traits>&
operator<<(std::basic_ostream<CharT, Traits>& os,
const RequestSprintsQuery& query)
{
os << "RequestSprintsQuery {" << query.dateRange << "}";
return os;
}
} // namespace sprint_timer::use_cases
#endif /* end of include guard: <API key> */ |
package fun.guruqu.portal.structures;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.*;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.Server;
import org.bukkit.World;
import org.bukkit.block.Block;
import com.cedarsoftware.util.io.JsonReader;
import com.cedarsoftware.util.io.JsonWriter;
import com.sk89q.worldedit.CuboidClipboard;
import com.sk89q.worldedit.blocks.BaseBlock;
import fun.guruqu.portal.PortalBeaconPlugin;
public class BlockManager {
PortalBeaconPlugin plugin;
Map<StrippedLocation, Map<String, Object>> locationToKeyValue;
Map<String, List<StrippedLocation>> keyToLocation;
public static final String saveFile = "blockstructure.json";
public BlockManager(PortalBeaconPlugin plugin) {
locationToKeyValue = new HashMap<>();
keyToLocation = new HashMap<>();
this.plugin = plugin;
loadState();
}
public void batchAddKey(CuboidClipboard board, Location location,
Set<Integer> exclude, Set<Integer> include, String key, Object value) {
com.sk89q.worldedit.Vector size = board.getSize();
for (int y = 0; y < size.getY(); y++) {
for (int x = 0; x < size.getX(); x++) {
for (int z = 0; z < size.getZ(); z++) {
BaseBlock block = board
.getBlock(new com.sk89q.worldedit.Vector(x, y, z));
if (include != null) {
if (!include.contains(block.getId()))
continue;
} else {
if (exclude != null) {
if (exclude.contains(block.getId()))
continue;
}
}
setBlockMeta(
new Location(location.getWorld(), location.getX()
+ x, location.getY() + y, location.getZ()
+ z), key, value);
}
}
}
}
public void batchAddKey(CuboidClipboard board, Location location,
boolean ignoreAir, String key, Object value) {
HashSet<Integer> air = new HashSet<>();
air.add(0);
batchAddKey(board, location, air, null, key, value);
}
public void setBlockMeta(Location location, String key, Object value) {
StrippedLocation sLocation = new StrippedLocation(location);
Map<String, Object> keyValue = locationToKeyValue.get(sLocation);
if (keyValue == null) {
keyValue = new HashMap<>();
locationToKeyValue.put(sLocation, keyValue);
}
keyValue.put(key, value);
List<StrippedLocation> locations = keyToLocation.get(key);
if (locations == null) {
locations = new Vector<>();
keyToLocation.put(key, locations);
}
locations.add(sLocation);
}
public Map<String, Object> getBlockMeta(Location location) {
return getBlockMeta(new StrippedLocation(location));
}
public Map<String, Object> getBlockMeta(StrippedLocation location) {
if (locationToKeyValue.containsKey(location))
return locationToKeyValue.get(location);
return null;
}
public List<StrippedLocation> findAllBlockWithKey(String key) {
return keyToLocation.get(key);
}
public void clearBlock(Location location) {
clearBlock(new StrippedLocation(location));
}
public void clearBlock(StrippedLocation location) {
Map<String, Object> removed = locationToKeyValue.remove(location);
for (String key : removed.keySet()) {
List<StrippedLocation> list = keyToLocation.get(key);
if (list != null) {
list.remove(key);
}
}
}
public boolean saveState() {
try {
JsonWriter writer = new JsonWriter(new FileOutputStream(new File(
plugin.getDataFolder(), saveFile)));
writer.write(locationToKeyValue);
writer.write(keyToLocation);
writer.close();
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
public boolean loadState() {
try {
File file = new File(plugin.getDataFolder(), saveFile);
if (!file.exists())
return true;
JsonReader reader = new JsonReader(new FileInputStream(file));
locationToKeyValue = (Map<StrippedLocation, Map<String, Object>>) reader
.readObject();
keyToLocation = (Map<String, List<StrippedLocation>>) reader
.readObject();
reader.close();
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
} |
<!DOCTYPE HTML PUBLIC "-
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_92) on Sun Mar 11 12:21:30 PDT 2018 -->
<title>Uses of Interface com.poesys.db.dao.query.<API key></title>
<meta name="date" content="2018-03-11">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Interface com.poesys.db.dao.query.<API key>";
}
}
catch(err) {
}
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<div class="topNav"><a name="navbar.top">
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../com/poesys/db/dao/query/<API key>.html" title="interface in com.poesys.db.dao.query">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?com/poesys/db/dao/query/class-use/<API key>.html" target="_top">Frames</a></li>
<li><a href="<API key>.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="<API key>">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!
allClassesLink = document.getElementById("<API key>");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
</script>
</div>
<a name="skip.navbar.top">
</a></div>
<div class="header">
<h2 title="Uses of Interface com.poesys.db.dao.query.<API key>" class="title">Uses of Interface<br>com.poesys.db.dao.query.<API key></h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../../../com/poesys/db/dao/query/<API key>.html" title="interface in com.poesys.db.dao.query"><API key></a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#com.poesys.db.dao">com.poesys.db.dao</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="#com.poesys.db.dao.query">com.poesys.db.dao.query</a></td>
<td class="colLast"> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="#com.poesys.db.dto">com.poesys.db.dto</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="com.poesys.db.dao">
</a>
<h3>Uses of <a href="../../../../../../com/poesys/db/dao/query/<API key>.html" title="interface in com.poesys.db.dao.query"><API key></a> in <a href="../../../../../../com/poesys/db/dao/package-summary.html">com.poesys.db.dao</a></h3>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../com/poesys/db/dao/package-summary.html">com.poesys.db.dao</a> with parameters of type <a href="../../../../../../com/poesys/db/dao/query/<API key>.html" title="interface in com.poesys.db.dao.query"><API key></a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><S extends <a href="../../../../../../com/poesys/db/dto/IDbDto.html" title="interface in com.poesys.db.dto">IDbDto</a>,C extends java.util.Collection<<a href="../../../../../../com/poesys/db/dao/IDaoFactory.html" title="type parameter in IDaoFactory">T</a>>><br><a href="../../../../../../com/poesys/db/dao/query/<API key>.html" title="interface in com.poesys.db.dao.query"><API key></a><<a href="../../../../../../com/poesys/db/dao/IDaoFactory.html" title="type parameter in IDaoFactory">T</a>,S,C></code></td>
<td class="colLast"><span class="typeNameLabel">IDaoFactory.</span><code><span class="memberNameLink"><a href="../../../../../../com/poesys/db/dao/IDaoFactory.html#<API key>.poesys.db.dao.query.<API key>.lang.String-int-"><API key></a></span>(<a href="../../../../../../com/poesys/db/dao/query/<API key>.html" title="interface in com.poesys.db.dao.query"><API key></a><<a href="../../../../../../com/poesys/db/dao/IDaoFactory.html" title="type parameter in IDaoFactory">T</a>,S> sql,
java.lang.String subsystem,
int rows)</code>
<div class="block">Generate a <API key> DAO that queries a list of objects based
on a set of parameters using a SQL query specification that contains
parameters and parameter-binding capabilities.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code><S extends <a href="../../../../../../com/poesys/db/dto/IDbDto.html" title="interface in com.poesys.db.dto">IDbDto</a>,C extends java.util.Collection<<a href="../../../../../../com/poesys/db/dao/DaoDirectFactory.html" title="type parameter in DaoDirectFactory">T</a>>><br><a href="../../../../../../com/poesys/db/dao/query/<API key>.html" title="interface in com.poesys.db.dao.query"><API key></a><<a href="../../../../../../com/poesys/db/dao/DaoDirectFactory.html" title="type parameter in DaoDirectFactory">T</a>,S,C></code></td>
<td class="colLast"><span class="typeNameLabel">DaoDirectFactory.</span><code><span class="memberNameLink"><a href="../../../../../../com/poesys/db/dao/DaoDirectFactory.html#<API key>.poesys.db.dao.query.<API key>.lang.String-int-"><API key></a></span>(<a href="../../../../../../com/poesys/db/dao/query/<API key>.html" title="interface in com.poesys.db.dao.query"><API key></a><<a href="../../../../../../com/poesys/db/dao/DaoDirectFactory.html" title="type parameter in DaoDirectFactory">T</a>,S> sql,
java.lang.String subsystem,
int rows)</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code><S extends <a href="../../../../../../com/poesys/db/dto/IDbDto.html" title="interface in com.poesys.db.dto">IDbDto</a>,C extends java.util.Collection<<a href="../../../../../../com/poesys/db/dao/DaoMemcachedFactory.html" title="type parameter in DaoMemcachedFactory">T</a>>><br><a href="../../../../../../com/poesys/db/dao/query/<API key>.html" title="interface in com.poesys.db.dao.query"><API key></a><<a href="../../../../../../com/poesys/db/dao/DaoMemcachedFactory.html" title="type parameter in DaoMemcachedFactory">T</a>,S,C></code></td>
<td class="colLast"><span class="typeNameLabel">DaoMemcachedFactory.</span><code><span class="memberNameLink"><a href="../../../../../../com/poesys/db/dao/DaoMemcachedFactory.html#<API key>.poesys.db.dao.query.<API key>.lang.String-int-"><API key></a></span>(<a href="../../../../../../com/poesys/db/dao/query/<API key>.html" title="interface in com.poesys.db.dao.query"><API key></a><<a href="../../../../../../com/poesys/db/dao/DaoMemcachedFactory.html" title="type parameter in DaoMemcachedFactory">T</a>,S> sql,
java.lang.String subsystem,
int rows)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code><S extends <a href="../../../../../../com/poesys/db/dto/IDbDto.html" title="interface in com.poesys.db.dto">IDbDto</a>,C extends java.util.Collection<<a href="../../../../../../com/poesys/db/dao/DaoCacheFactory.html" title="type parameter in DaoCacheFactory">T</a>>><br><a href="../../../../../../com/poesys/db/dao/query/<API key>.html" title="interface in com.poesys.db.dao.query"><API key></a><<a href="../../../../../../com/poesys/db/dao/DaoCacheFactory.html" title="type parameter in DaoCacheFactory">T</a>,S,C></code></td>
<td class="colLast"><span class="typeNameLabel">DaoCacheFactory.</span><code><span class="memberNameLink"><a href="../../../../../../com/poesys/db/dao/DaoCacheFactory.html#<API key>.poesys.db.dao.query.<API key>.lang.String-int-"><API key></a></span>(<a href="../../../../../../com/poesys/db/dao/query/<API key>.html" title="interface in com.poesys.db.dao.query"><API key></a><<a href="../../../../../../com/poesys/db/dao/DaoCacheFactory.html" title="type parameter in DaoCacheFactory">T</a>,S> sql,
java.lang.String subsystem,
int rows)</code> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="com.poesys.db.dao.query">
</a>
<h3>Uses of <a href="../../../../../../com/poesys/db/dao/query/<API key>.html" title="interface in com.poesys.db.dao.query"><API key></a> in <a href="../../../../../../com/poesys/db/dao/query/package-summary.html">com.poesys.db.dao.query</a></h3>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing fields, and an explanation">
<caption><span>Fields in <a href="../../../../../../com/poesys/db/dao/query/package-summary.html">com.poesys.db.dao.query</a> declared as <a href="../../../../../../com/poesys/db/dao/query/<API key>.html" title="interface in com.poesys.db.dao.query"><API key></a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Field and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>protected <a href="../../../../../../com/poesys/db/dao/query/<API key>.html" title="interface in com.poesys.db.dao.query"><API key></a><<a href="../../../../../../com/poesys/db/dao/query/<API key>.html" title="type parameter in <API key>">T</a>,<a href="../../../../../../com/poesys/db/dao/query/<API key>.html" title="type parameter in <API key>">S</a>></code></td>
<td class="colLast"><span class="typeNameLabel"><API key>.</span><code><span class="memberNameLink"><a href="../../../../../../com/poesys/db/dao/query/<API key>.html#sql">sql</a></span></code>
<div class="block">Internal Strategy-pattern object containing the SQL query with parameters</div>
</td>
</tr>
</tbody>
</table>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing constructors, and an explanation">
<caption><span>Constructors in <a href="../../../../../../com/poesys/db/dao/query/package-summary.html">com.poesys.db.dao.query</a> with parameters of type <a href="../../../../../../com/poesys/db/dao/query/<API key>.html" title="interface in com.poesys.db.dao.query"><API key></a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../com/poesys/db/dao/query/<API key>.html#<API key>.poesys.db.dao.query.<API key>.poesys.db.dto.IDtoCache-java.lang.String-int-"><API key></a></span>(<a href="../../../../../../com/poesys/db/dao/query/<API key>.html" title="interface in com.poesys.db.dao.query"><API key></a><<a href="../../../../../../com/poesys/db/dao/query/<API key>.html" title="type parameter in <API key>">T</a>,<a href="../../../../../../com/poesys/db/dao/query/<API key>.html" title="type parameter in <API key>">S</a>> sql,
<a href="../../../../../../com/poesys/db/dto/IDtoCache.html" title="interface in com.poesys.db.dto">IDtoCache</a><<a href="../../../../../../com/poesys/db/dao/query/<API key>.html" title="type parameter in <API key>">T</a>> cache,
java.lang.String subsystem,
int rows)</code>
<div class="block">Create a QueryCacheList object.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../com/poesys/db/dao/query/<API key>.html#<API key>.poesys.db.dao.query.<API key>.lang.String-int-"><API key></a></span>(<a href="../../../../../../com/poesys/db/dao/query/<API key>.html" title="interface in com.poesys.db.dao.query"><API key></a><<a href="../../../../../../com/poesys/db/dao/query/<API key>.html" title="type parameter in <API key>">T</a>,<a href="../../../../../../com/poesys/db/dao/query/<API key>.html" title="type parameter in <API key>">S</a>> sql,
java.lang.String subsystem,
int rows)</code>
<div class="block">Create a <API key> object.</div>
</td>
</tr>
<tr class="altColor">
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../com/poesys/db/dao/query/<API key>.html#<API key>.poesys.db.dao.query.<API key>.lang.String-java.lang.Integer-int-"><API key></a></span>(<a href="../../../../../../com/poesys/db/dao/query/<API key>.html" title="interface in com.poesys.db.dao.query"><API key></a><<a href="../../../../../../com/poesys/db/dao/query/<API key>.html" title="type parameter in <API key>">T</a>,<a href="../../../../../../com/poesys/db/dao/query/<API key>.html" title="type parameter in <API key>">S</a>> sql,
java.lang.String subsystem,
java.lang.Integer expiration,
int rows)</code>
<div class="block">Create a QueryCacheList object with the appropriate SQL class, the name of
the subsystem that contains T, the memcached expiration time for objects of
type T in the cache, and the number of rows to fetch at once.</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="com.poesys.db.dto">
</a>
<h3>Uses of <a href="../../../../../../com/poesys/db/dao/query/<API key>.html" title="interface in com.poesys.db.dao.query"><API key></a> in <a href="../../../../../../com/poesys/db/dto/package-summary.html">com.poesys.db.dto</a></h3>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../com/poesys/db/dto/package-summary.html">com.poesys.db.dto</a> that return <a href="../../../../../../com/poesys/db/dao/query/<API key>.html" title="interface in com.poesys.db.dao.query"><API key></a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>protected abstract <a href="../../../../../../com/poesys/db/dao/query/<API key>.html" title="interface in com.poesys.db.dao.query"><API key></a><<a href="../../../../../../com/poesys/db/dto/AbstractListSetter.html" title="type parameter in AbstractListSetter">T</a>,<a href="../../../../../../com/poesys/db/dto/AbstractListSetter.html" title="type parameter in AbstractListSetter">S</a>></code></td>
<td class="colLast"><span class="typeNameLabel">AbstractListSetter.</span><code><span class="memberNameLink"><a href="../../../../../../com/poesys/db/dto/AbstractListSetter.html#getSql--">getSql</a></span>()</code>
<div class="block">Get the SQL object that contains the parameterized query.</div>
</td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<div class="bottomNav"><a name="navbar.bottom">
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../com/poesys/db/dao/query/<API key>.html" title="interface in com.poesys.db.dao.query">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?com/poesys/db/dao/query/class-use/<API key>.html" target="_top">Frames</a></li>
<li><a href="<API key>.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="<API key>">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!
allClassesLink = document.getElementById("<API key>");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
</script>
</div>
<a name="skip.navbar.bottom">
</a></div>
</body>
</html> |
#include <iostream>
#include "vector2d.hpp"
using namespace std;
using namespace LW;
int main()
{
vector2d<int> a(3,4);
for(unsigned i = 0; i < 3; ++i)
for(unsigned j = 0; j < 4; ++j)
a(i,j) = 10*i + j;
vector2d<int> b = a;
a.resize(1, 15);
for(unsigned k = 0; k < 15; ++k)
cout<< a.at(0, k) <<endl;
vector2d<bool> B(32, 8); // invokes specialized template
B.resize(256, 1);
B(23, 0) = true;
return 0;
} |
// This file is part of Nfield.SDK.
// Nfield.SDK is free software: you can redistribute it and/or modify
// (at your option) any later version.
// Nfield.SDK is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
using System;
namespace Nfield.Models
{
<summary>
Holds the properties of a Survey response code
</summary>
public class SurveyResponseCode
{
<summary>
User defined response code for the survey
The code is part of the identity of the Entity so once it's assigned it can not changed
</summary>
public int ResponseCode { get; set; }
<summary>
User defined description of the response code given
</summary>
public string Description { get; set; }
<summary>
Determines if the Response code is a definitive or not (IsFinal - true or false)
</summary>
public bool? IsDefinite { get; set; }
<summary>
Determines if response code is selectable by the interviewer
</summary>
public bool? IsSelectable { get; set; }
<summary>
Determines if the Response code is meant for an appointment or not (IsIntermediate - true or false)
</summary>
public bool? AllowAppointment { get; set; }
<summary>
Relocation url of the response code
</summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1056:<API key>",
Justification = "Entity Framework, out of the box, can't map Uri's to a sql server data type")]
public string RelocationUrl { get; set; }
}
} |
module Authentication
module AuthnJwt
ValidateStatus = CommandClass.new(
dependencies: {
<API key>: Authentication::AuthnJwt::SigningKey::<API key>.new,
fetch_issuer_value: Authentication::AuthnJwt::ValidateAndDecode::FetchIssuerValue.new,
<API key>: Authentication::AuthnJwt::ValidateAndDecode::FetchAudienceValue.new,
<API key>: Authentication::AuthnJwt::<API key>::FetchEnforcedClaims.new,
fetch_claim_aliases: Authentication::AuthnJwt::<API key>::FetchClaimAliases.new,
<API key>: Authentication::AuthnJwt::IdentityProviders::<API key>.new,
<API key>: ::Authentication::Security::<API key>.new,
<API key>: ::Authentication::Security::<API key>.new,
<API key>: ::Authentication::Security::<API key>.new,
<API key>: ::Authentication::Security::<API key>.new,
<API key>: Authentication::AuthenticatorInput,
jwt_<API key>: Authentication::AuthnJwt::<API key>,
logger: Rails.logger
},
inputs: %i[<API key> <API key>]
) do
extend(Forwardable)
def_delegators(:@<API key>, :authenticator_name, :account,
:username, :status_webservice, :service_id, :client_ip)
def call
@logger.info(LogMessages::Authentication::AuthnJwt::<API key>.new)
<API key>
<API key>
validate_issuer
validate_audience
<API key>
<API key>
<API key>
@logger.info(LogMessages::Authentication::AuthnJwt::<API key>.new)
end
private
def <API key>
<API key>
<API key>
<API key>
validate_<API key>
<API key>
end
def <API key>
@<API key>.(
account: account
)
@logger.debug(LogMessages::Authentication::AuthnJwt::<API key>.new)
end
def <API key>
raise Errors::Authentication::AuthnJwt::ServiceIdMissing unless service_id
@logger.debug(LogMessages::Authentication::AuthnJwt::<API key>.new)
end
def <API key>
@<API key>.(
webservice: status_webservice,
account: account,
user_id: username,
privilege: 'read'
)
@logger.debug(LogMessages::Authentication::AuthnJwt::<API key>.new)
end
def validate_<API key>
@<API key>.(
webservice: webservice,
account: account
)
@logger.debug(LogMessages::Authentication::AuthnJwt::Validated<API key>.new)
end
def <API key>
@<API key>.(
webservice: webservice,
account: account,
<API key>: @<API key>
)
@logger.debug(LogMessages::Authentication::AuthnJwt::<API key>.new)
end
def validate_issuer
@fetch_issuer_value.call(authenticator_input: authenticator_input)
@logger.debug(LogMessages::Authentication::AuthnJwt::<API key>.new)
end
def validate_audience
@<API key>.call(authenticator_input: authenticator_input)
@logger.debug(LogMessages::Authentication::AuthnJwt::<API key>.new)
end
def <API key>
@<API key>.call(<API key>: <API key>)
@logger.debug(LogMessages::Authentication::AuthnJwt::<API key>.new)
end
def <API key>
@fetch_claim_aliases.call(<API key>: <API key>)
@logger.debug(LogMessages::Authentication::AuthnJwt::<API key>.new)
end
def <API key>
@<API key>.call(
<API key>: <API key>
)
@logger.debug(LogMessages::Authentication::AuthnJwt::<API key>.new)
end
def <API key>
@<API key> ||= @jwt_<API key>.new(
authenticator_input: authenticator_input,
decoded_token: nil
)
end
def authenticator_input
@authenticator_input ||= @<API key>.new(
authenticator_name: authenticator_name,
service_id: service_id,
account: account,
username: username,
client_ip: client_ip,
credentials: nil,
request: nil
)
end
def webservice
@webservice ||= ::Authentication::Webservice.new(
account: account,
authenticator_name: authenticator_name,
service_id: service_id
)
end
def <API key>
<API key>.call(
force_fetch: false
)
@logger.debug(LogMessages::Authentication::AuthnJwt::<API key>.new)
end
def <API key>
@<API key> ||= @<API key>.call(
authenticator_input: authenticator_input
)
end
end
end
end |
// Created file "Lib\src\amstrmid\X64\strmiids"
typedef struct _GUID
{
unsigned long Data1;
unsigned short Data2;
unsigned short Data3;
unsigned char Data4[8];
} GUID;
#define DEFINE_GUID(name, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) \
extern const GUID name = { l, w1, w2, { b1, b2, b3, b4, b5, b6, b7, b8 } }
DEFINE_GUID(<API key>, 0xe6f7ce40, 0x4673, 0x44f1, 0x8f, 0x77, 0x54, 0x99, 0xd6, 0x8c, 0xb4, 0xea); |
from RMPY.rig import rigSingleJoint
from RMPY.rig import rigBase
import pymel.core as pm
class RigPropModel(rigBase.BaseModel):
def __init__(self):
super(RigPropModel, self).__init__()
self.single_joints = []
class RigProp(rigBase.RigBase):
def __init__(self, *args, **kwargs):
kwargs['model'] = kwargs.pop('model', RigPropModel())
super(RigProp, self).__init__(*args, **kwargs)
@property
def single_joints(self):
return self._model.single_joints
def create_point_base(self, *points, **kwargs):
"""
:param points:
:param kwargs:
depth: the number of controls that will be nested inside each reference point default 2
size: size of the controls default 1
step size: a multiplier for each one of the nested controls, default will be size /10
align: the alignment of the controls
'point' each control will be aligned to each one of the points
'world' each control will align to the world
:return:
"""
depth = kwargs.pop('depth', 2)
size = kwargs.pop('size', 1.0)
size_step = kwargs.pop('size_step', -size/10.0)
align = kwargs.pop('align', 'point')
offset_visibility = kwargs.pop('offset_visibility', False)
single_joint = rigSingleJoint.RigSingleJoint(rig_system=self.rig_system)
self.single_joints.append(single_joint)
for each_point in points:
for index in range(depth):
single_joint.create_point_base(each_point, size=size + size_step*index, **kwargs)
if index >= 1:
single_joint.reset_controls[-1].setParent(single_joint.controls[-2])
if offset_visibility:
single_joint.controls[0].offset_visibility >> single_joint.reset_controls[-1].visibility
else:
if offset_visibility:
single_joint.controls[0].addAttr('offset_visibility', at='bool', k=True)
if align == 'world':
self.custom_world_align(single_joint.reset_controls[-1])
self.joints.extend(single_joint.joints)
self.controls.extend(single_joint.controls)
self.reset_controls.extend(single_joint.reset_controls)
self.reset_joints.extend(single_joint.reset_joints)
# self.controls = single_joint.controls
# self.reset_controls = single_joint.reset_controls
# self.joints = single_joint.joints
# self.reset_joints = single_joint.reset_joints
if __name__ == '__main__':
reference_points = pm.ls('<API key>')[0]
rig_prop = RigProp()
rig_prop.create_point_base(reference_points, depth=2, type='box', centered=True, align='world') |
#include "wrapper.h"
WRAP_API WINDOW *
wrap_newpad(int nlines, int ncols)
{
return newpad(nlines, ncols);
}
WRAP_API WINDOW *
wrap_subpad(WINDOW *orig, int nlines, int ncols, int begy, int begx)
{
return subpad(orig, nlines, ncols, begy, begx);
}
WRAP_API int
wrap_prefresh(WINDOW *win, int py, int px, int sy1, int sx1, int sy2, int sx2)
{
return prefresh(win, py, px, sy1, sx1, sy2, sx2);
}
WRAP_API int
wrap_pnoutrefresh(WINDOW *win, int py, int px, int sy1, int sx1, int sy2, int sx2)
{
return pnoutrefresh(win, py, px, sy1, sx1, sy2, sx2);
}
WRAP_API int
wrap_pechochar(WINDOW *pad, unsigned int ch)
{
return pechochar(pad, ch);
} |
// S t o p W a t c h //
// <editor-fold defaultstate="collapsed" desc="hdr"> //
// </editor-fold>
package omr.util;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.List;
public class StopWatch
{
/** Name for this watch instance */
private final String name;
/** Sequence of all tasks so far */
private final List<Task> tasks = new ArrayList<>(128);
/** Current task (null if not running) */
private Task task;
/** Current sum of tasks times */
private long total;
// StopWatch //
/**
* Creates a new StopWatch object.
*
* @param name name of the watch instance
*/
public StopWatch (String name)
{
this.name = name;
}
// print //
public void print ()
{
print(System.out);
}
// print //
public void print (PrintStream out)
{
stop();
final String format = "%5d %3d%% %s";
final String dashes = "
out.println(getClass().getSimpleName() + " \"" + name + "\"");
out.println(dashes);
out.println(" ms % Task");
out.println(dashes);
for (Task t : tasks) {
if (t != task) {
out.println(
String.format(
format,
t.elapsed,
(total != 0) ? ((100 * t.elapsed) / total) : 100,
t.label));
}
}
out.println(dashes);
out.println(String.format(format, total, 100, "Total"));
}
// start //
public void start (String label)
{
if (task != null) {
stop();
}
tasks.add(task = new Task(label));
}
// stop //
public void stop ()
{
if (task != null) {
task.elapsed = System.currentTimeMillis() - task.start;
total += task.elapsed;
task = null;
}
}
// toString //
@Override
public String toString ()
{
StringBuilder sb = new StringBuilder(getClass().getSimpleName());
sb.append(" \"")
.append(name)
.append("\"");
sb.append(" tasks:")
.append(tasks.size());
sb.append(" total:")
.append(total);
if (task != null) {
sb.append(" running");
} else {
sb.append(" stopped");
}
return sb.toString();
}
// Task //
private static class Task
{
/** Label for this task */
private final String label;
/** Start time */
private final long start;
/** Elapsed time */
private long elapsed;
public Task (String label)
{
this.label = label;
start = System.currentTimeMillis();
}
}
} |
using System.Xml.Serialization;
using StreetSmart.Common.Interfaces.SLD;
namespace StreetSmart.Common.Data.SLD
{
#pragma warning disable 1591
<exclude/>
public class UserLayer : <API key>, IUserLayer
{
private UserStyle _userStyle;
[XmlElement("UserStyle", Namespace = "http:
public UserStyle UserStyle
{
get => _userStyle;
set
{
_userStyle = value;
<API key>();
}
}
}
#pragma warning restore 1591
} |
RSpec.describe Epics::AZV do
let(:client) { Epics::Client.new( File.open(File.join( File.dirname(__FILE__), '..', 'fixtures', 'SIZBN001.key')), 'secret' , 'https://194.180.18.30/ebicsweb/ebicsweb', 'SIZBN001', 'EBIX', 'EBICS') }
let(:document) { 'DTAZV' }
subject { described_class.new(client, document) }
describe '#to_xml' do
specify { expect(subject.to_xml).to <API key> }
end
describe '#to_transfer_xml' do
before { subject.transaction_id = SecureRandom.hex(16) }
specify { expect(subject.to_transfer_xml).to <API key> }
end
end |
#ifndef __MCF52235_RCM_H__
#define __MCF52235_RCM_H__
/* Register read/write macros */
#define MCF_RCM_RCR (*(vuint8 *)(0x40110000))
#define MCF_RCM_RSR (*(vuint8 *)(0x40110001))
/* Bit definitions and macros for MCF_RCM_RCR */
#define MCF_RCM_RCR_LVDE (0x1)
#define MCF_RCM_RCR_LVDRE (0x4)
#define MCF_RCM_RCR_LVDIE (0x8)
#define MCF_RCM_RCR_LVDF (0x10)
#define <API key> (0x40)
#define MCF_RCM_RCR_SOFTRST (0x80)
/* Bit definitions and macros for MCF_RCM_RSR */
#define MCF_RCM_RSR_LOL (0x1)
#define MCF_RCM_RSR_LOC (0x2)
#define MCF_RCM_RSR_EXT (0x4)
#define MCF_RCM_RSR_POR (0x8)
#define MCF_RCM_RSR_SOFT (0x20)
#define MCF_RCM_RSR_LVD (0x40)
#endif /* __MCF52235_RCM_H__ */ |
/**
* Class Polygon provides a polygon {@linkplain DrawingItem} whose boundary
* consists of one or more straight line segments. The polygon has an outline
* and a filled interior.
*
* @author Alan Kaminsky
* @version 23-Jun-2008
*/
public class Polygon
extends ShapeItem
{
// Hidden data members.
private static final long serialVersionUID = -<API key>;
// Line segment endpoints.
LinkedList<Point> myPoints = new LinkedList<Point>();
// For adding line segments.
Point myLastPoint;
// For computing the bounding box.
Point myNw;
Point mySe;
Size mySize;
// Exported constructors.
/**
* Construct a new polygon. The polygon has no points initially. The default
* outline and fill paint are used.
*/
public Polygon()
{
super();
}
/**
* Construct a new polygon with the same points, outline, and fill paint as
* the given polygon.
*
* @param thePolygon Polygon.
*
* @exception <API key>
* (unchecked exception) Thrown if <TT>thePolygon</TT> is null.
*/
public Polygon
(Polygon thePolygon)
{
super (thePolygon);
myPoints.clear();
myPoints.addAll (thePolygon.myPoints);
if (! myPoints.isEmpty())
{
myLastPoint = myPoints.get (myPoints.size()-1);
}
}
// Exported operations.
/**
* Returns the size of this polygon's bounding box.
*
* @return Size.
*/
public Size size()
{
computeBoundingBox();
return mySize;
}
/**
* Returns the width of this polygon's bounding box.
*
* @return Width.
*/
public double width()
{
computeBoundingBox();
return mySize.width;
}
/**
* Returns the height of this polygon's bounding box.
*
* @return Height.
*/
public double height()
{
computeBoundingBox();
return mySize.height;
}
/**
* Returns the northwest corner point of this polygon's bounding box.
*
* @return Northwest corner point.
*/
public Point nw()
{
computeBoundingBox();
return myNw;
}
/**
* Set this polygon's outline.
*
* @param theOutline Outline, or <TT>Outline.NONE</TT>.
*
* @return This polygon.
*/
public Polygon outline
(Outline theOutline)
{
doOutline (theOutline);
return this;
}
/**
* Set this polygon's fill paint.
*
* @param theFill Fill paint, or <TT>Fill.NONE</TT>.
*
* @return This polygon.
*/
public Polygon fill
(Fill theFill)
{
doFill (theFill);
return this;
}
/**
* Clear this polygon. All of this polygon's line segments are removed.
*
* @return This polygon.
*/
public Polygon clear()
{
myPoints.clear();
myLastPoint = null;
myNw = null;
return this;
}
/**
* Add a line segment to this polygon. The new endpoint is (<TT>x</TT>,
* <TT>y</TT>). If this polygon has no line segments, the <TT>to()</TT>
* method specifies this polygon's starting endpoint.
*
* @param x Endpoint's X coordinate.
* @param y Endpoint's Y coordinate.
*
* @return This polygon.
*/
public Polygon to
(double x,
double y)
{
return addEndpoint (new Point (x, y));
}
/**
* Add a line segment to this polygon. The new endpoint is
* <TT>thePoint</TT>. If this polygon has no line segments, the
* <TT>to()</TT> method specifies this polygon's starting endpoint.
*
* @param thePoint Endpoint.
*
* @return This polygon.
*
* @exception <API key>
* (unchecked exception) Thrown if <TT>thePoint</TT> is null.
*/
public Polygon to
(Point thePoint)
{
if (thePoint == null) throw new <API key>();
return addEndpoint (thePoint);
}
/**
* Add a horizontal line segment to this polygon. The new endpoint is
* (<TT>x</TT>, previous endpoint's Y coordinate).
*
* @param x Endpoint's X coordinate.
*
* @return This polygon.
*
* @exception <API key>
* (unchecked exception) Thrown if there is no previous endpoint.
*/
public Polygon hto
(double x)
{
return addEndpoint (new Point (x, myLastPoint.y));
}
/**
* Add a horizontal line segment to this polygon. The new endpoint is
* (<TT>thePoint</TT>'s X coordinate, previous endpoint's Y coordinate).
*
* @param thePoint Endpoint.
*
* @return This polygon.
*
* @exception <API key>
* (unchecked exception) Thrown if <TT>thePoint</TT> is null. Thrown if
* there is no previous endpoint.
*/
public Polygon hto
(Point thePoint)
{
return addEndpoint (new Point (thePoint.x, myLastPoint.y));
}
/**
* Add a vertical line segment to this polygon. The new endpoint is
* (previous endpoint's X coordinate, <TT>y</TT>).
*
* @param y Endpoint's Y coordinate.
*
* @return This polygon.
*
* @exception <API key>
* (unchecked exception) Thrown if there is no previous endpoint.
*/
public Polygon vto
(double y)
{
return addEndpoint (new Point (myLastPoint.x, y));
}
/**
* Add a vertical line segment to this polygon. The new endpoint is
* (previous endpoint's X coordinate, <TT>thePoint</TT>'s Y coordinate).
*
* @param thePoint Endpoint.
*
* @return This polygon.
*
* @exception <API key>
* (unchecked exception) Thrown if <TT>thePoint</TT> is null. Thrown if
* there is no previous endpoint.
*/
public Polygon vto
(Point thePoint)
{
return addEndpoint (new Point (myLastPoint.x, thePoint.y));
}
/**
* Add a line segment to this polygon. The new endpoint is (previous
* endpoint's X coordinate + <TT>dx</TT>, previous endpoint's Y coordinate +
* <TT>dy</TT>).
*
* @param dx X distance.
* @param dy Y distance.
*
* @return This polygon.
*
* @exception <API key>
* (unchecked exception) Thrown if there is no previous endpoint.
*/
public Polygon by
(double dx,
double dy)
{
return addEndpoint (new Point (myLastPoint.x+dx, myLastPoint.y+dy));
}
/**
* Add a line segment to this polygon. The new endpoint is (previous
* endpoint's X coordinate + <TT>theSize.width()</TT>, previous endpoint's Y
* coordinate + <TT>theSize.height()</TT>).
*
* @param theSize Distance.
*
* @return This polygon.
*
* @exception <API key>
* (unchecked exception) Thrown if <TT>theSize</TT> is null. Thrown if
* there is no previous endpoint.
*/
public Polygon by
(Size theSize)
{
return addEndpoint
(new Point
(myLastPoint.x+theSize.width, myLastPoint.y+theSize.height));
}
/**
* Add a horizontal line segment to this polygon. The new endpoint is
* (previous endpoint's X coordinate + <TT>dx</TT>, previous endpoint's Y
* coordinate).
*
* @param dx X distance.
*
* @return This polygon.
*
* @exception <API key>
* (unchecked exception) Thrown if there is no previous endpoint.
*/
public Polygon hby
(double dx)
{
return addEndpoint (new Point (myLastPoint.x+dx, myLastPoint.y));
}
/**
* Add a horizontal line segment to this polygon. The new endpoint is
* (previous endpoint's X coordinate + <TT>theSize.width()</TT>, previous
* endpoint's Y coordinate).
*
* @param theSize Distance.
*
* @return This polygon.
*
* @exception <API key>
* (unchecked exception) Thrown if <TT>theSize</TT> is null. Thrown if
* there is no previous endpoint.
*/
public Polygon hby
(Size theSize)
{
return addEndpoint
(new Point (myLastPoint.x+theSize.width, myLastPoint.y));
}
/**
* Add a vertical line segment to this polygon. The new endpoint is
* (previous endpoint's X coordinate, previous endpoint's Y coordinate +
* <TT>dy</TT>).
*
* @param dy Y distance.
*
* @return This polygon.
*
* @exception <API key>
* (unchecked exception) Thrown if there is no previous endpoint.
*/
public Polygon vby
(double dy)
{
return addEndpoint (new Point (myLastPoint.x, myLastPoint.y+dy));
}
/**
* Add a vertical line segment to this polygon. The new endpoint is
* (previous endpoint's X coordinate, previous endpoint's Y coordinate +
* <TT>theSize.height()</TT>).
*
* @param theSize Distance.
*
* @return This polygon.
*
* @exception <API key>
* (unchecked exception) Thrown if <TT>theSize</TT> is null. Thrown if
* there is no previous endpoint.
*/
public Polygon vby
(Size theSize)
{
return addEndpoint
(new Point (myLastPoint.x, myLastPoint.y+theSize.height));
}
/**
* Add this polygon to the end of the default drawing's sequence of drawing
* items.
*
* @return This polygon.
*
* @exception <API key>
* (unchecked exception) Thrown if there is no default drawing.
*
* @see Drawing#defaultDrawing()
*/
public Polygon add()
{
doAdd (Drawing.defaultDrawing());
return this;
}
/**
* Add this polygon to the end of the given drawing's sequence of drawing
* items.
*
* @param theDrawing Drawing.
*
* @return This polygon.
*
* @exception <API key>
* (unchecked exception) Thrown if <TT>theDrawing</TT> is null.
*/
public Polygon add
(Drawing theDrawing)
{
doAdd (theDrawing);
return this;
}
/**
* Add this polygon to the beginning of the default drawing's sequence of
* drawing items.
*
* @return This polygon.
*
* @exception <API key>
* (unchecked exception) Thrown if there is no default drawing.
*
* @see Drawing#defaultDrawing()
*/
public Polygon addFirst()
{
doAddFirst (Drawing.defaultDrawing());
return this;
}
/**
* Add this polygon to the beginning of the given drawing's sequence of
* drawing items.
*
* @param theDrawing Drawing.
*
* @return This polygon.
*
* @exception <API key>
* (unchecked exception) Thrown if <TT>theDrawing</TT> is null.
*/
public Polygon addFirst
(Drawing theDrawing)
{
doAddFirst (theDrawing);
return this;
}
/**
* Write this polygon to the given object output stream.
*
* @param out Object output stream.
*
* @exception IOException
* Thrown if an I/O error occurred.
*/
public void writeExternal
(ObjectOutput out)
throws IOException
{
super.writeExternal (out);
out.writeInt (myPoints.size());
for (Point point : myPoints)
{
out.writeObject (point);
}
}
/**
* Read this polygon from the given object input stream.
*
* @param in Object input stream.
*
* @exception IOException
* Thrown if an I/O error occurred.
* @exception <API key>
* Thrown if any class needed to deserialize this polygon cannot be
* found.
*/
public void readExternal
(ObjectInput in)
throws IOException, <API key>
{
super.readExternal (in);
int n = in.readInt();
myPoints.clear();
for (int i = 0; i < n; ++ i)
{
myPoints.add ((Point) in.readObject());
}
if (! myPoints.isEmpty())
{
myLastPoint = myPoints.get (myPoints.size()-1);
}
myNw = null;
mySe = null;
mySize = null;
}
// Hidden operations.
/**
* Add the given endpoint to this polygon.
*/
private Polygon addEndpoint
(Point p)
{
myLastPoint = p;
myPoints.add (p);
myNw = null;
return this;
}
/**
* Compute this polygon's bounding box from myPoints. The results are stored
* in myNw, mySe, and mySize.
*/
private void computeBoundingBox()
{
if (myNw == null)
{
myNw = new Point
(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY);
mySe = new Point
(Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY);
for (Point p : myPoints)
{
myNw = myNw.min (p);
mySe = mySe.max (p);
}
mySize = mySe.difference (myNw);
}
}
/**
* Determine the 2-D graphics shape that this shape object will draw.
*
* @return Shape.
*/
Shape getShape()
{
GeneralPath path = new GeneralPath();
int n = myPoints.size();
Iterator<Point> iter = myPoints.iterator();
Point point = null;
if (n > 0)
{
point = iter.next();
path.moveTo ((float) point.x, (float) point.y);
while (iter.hasNext())
{
point = iter.next();
path.lineTo ((float) point.x, (float) point.y);
}
path.closePath();
}
return path;
}
} |
package com.craftfire.babelcraft.util;
import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerLoginEvent;
public class Messages {
Util util = new Util();
public static String <API key>, message_autodetect, message_usage;
public static String <API key>, <API key>, message_savesuccess;
public static String message_savefailure;
public enum Message {
default_lang (<API key>),
autodetect (message_autodetect),
usage (message_usage),
notsupported (<API key>),
nottranslated (<API key>),
savesuccess (message_savesuccess),
savefailure (message_savefailure);
public String text;
Message (String text) {
this.text = text;
}
}
public void SendMessage(final Message message, Player player, PlayerLoginEvent event) {
player.sendMessage(util.replaceStrings(message.text, player, null));
}
} |
package ch.loway.oss.ari4java.generated;
// THIS CLASS WAS GENERATED AUTOMATICALLY
// PLEASE DO NOT EDIT
// Generated on: Tue Dec 19 09:55:48 CET 2017
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.ArrayList;
import ch.loway.oss.ari4java.tools.RestException;
import ch.loway.oss.ari4java.tools.AriCallback;
import ch.loway.oss.ari4java.tools.tags.*;
public interface Sound {
// List<FormatLangPair> getFormats
public List<FormatLangPair> getFormats();
// String getText
public String getText();
// void setFormats List<FormatLangPair>
public void setFormats(List<FormatLangPair> val );
// void setId String
public void setId(String val );
// String getId
public String getId();
// void setText String
public void setText(String val );
}
; |
<!DOCTYPE html PUBLIC "-
<html xmlns="http:
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.3.1"/>
<title>Core3: /Users/victor/git/Core3Mda/MMOCoreORB/src/server/login/packets/ErrorMessage.h File Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td style="padding-left: 0.5em;">
<div id="projectname">Core3
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.3.1 -->
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="namespaces.html"><span>Namespaces</span></a></li>
<li><a href="annotated.html"><span>Classes</span></a></li>
<li class="current"><a href="files.html"><span>Files</span></a></li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="files.html"><span>File List</span></a></li>
<li><a href="globals.html"><span>File Members</span></a></li>
</ul>
</div>
<div id="nav-path" class="navpath">
<ul>
<li class="navelem"><a class="el" href="<API key>.html">src</a></li><li class="navelem"><a class="el" href="<API key>.html">server</a></li><li class="navelem"><a class="el" href="<API key>.html">login</a></li><li class="navelem"><a class="el" href="<API key>.html">packets</a></li> </ul>
</div>
</div><!-- top -->
<div class="header">
<div class="summary">
<a href="#nested-classes">Classes</a> </div>
<div class="headertitle">
<div class="title">ErrorMessage.h File Reference</div> </div>
</div><!--header
<div class="contents">
<div class="textblock"><code>#include "engine/engine.h"</code><br/>
</div>
<p><a href="<API key>.html">Go to the source code of this file.</a></p>
<table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="nested-classes"></a>
Classes</h2></td></tr>
<tr class="memitem:"><td class="memItemLeft" align="right" valign="top">class  </td><td class="memItemRight" valign="bottom"><a class="el" href="class_error_message.html">ErrorMessage</a></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
</table>
</div><!-- contents -->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated on Tue Oct 15 2013 17:29:15 for Core3 by &
<img class="footer" src="doxygen.png" alt="doxygen"/>
</a> 1.8.3.1
</small></address>
</body>
</html> |
package com.freiheit.function.serializable;
import java.io.Serializable;
import java.util.function.IntBinaryOperator;
/**
* Serializable version of {@link IntBinaryOperator}.
*
* @see IntBinaryOperator
* @author Michael Bohn (initial creation)
*/
@FunctionalInterface
public interface <API key> extends IntBinaryOperator, Serializable {
//nothing
} |
package exter.eveindustry.dataprovider.planet;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import exter.eveindustry.data.inventory.IItem;
import exter.eveindustry.data.planet.IPlanet;
import exter.eveindustry.dataprovider.item.ItemDA;
import exter.tsl.TSLObject;
public class Planet implements IPlanet
{
public final List<IItem> Resources;
public final String TypeName;
public final int ID;
public final boolean Advanced;
public Planet(TSLObject tsl,ItemDA inventory)
{
ID = tsl.getStringAsInt("id",-1);
TypeName = tsl.getString("name",null);
Advanced = (tsl.getStringAsInt("advanced",0) != 0);
List<IItem> res = new ArrayList<IItem>();
for(Integer id:tsl.<API key>("resource"))
{
res.add(inventory.items.get(id));
}
Resources = Collections.unmodifiableList(res);
}
@Override
public List<IItem> getResources()
{
return Resources;
}
@Override
public int getID()
{
return ID;
}
@Override
public boolean isAdvanced()
{
return Advanced;
}
} |
using <API key>.Data.Models;
using System;
using System.Collections.Generic;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Gmail.v1;
using Google.Apis.Services;
using Google.Apis.Gmail.v1.Data;
using System.Diagnostics;
using System.Linq;
using <API key>.Data.Database;
namespace <API key>.Data.API
{
public class GoogleGmailService : <API key><GoogleGmailModel, List<GoogleGmailModel>, Message>
{
private List<GoogleGmailModel> _gmails = new List<GoogleGmailModel>();
private readonly UserCredential _credential;
private const string ApplicationName = "Smart Mirror Gmail Service";
public GoogleGmailService(UserCredential credential)
{
this._credential = credential;
}
public override List<GoogleGmailModel> GetData()
{
return _gmails;
}
protected override void SetData(List<GoogleGmailModel> itemList)
{
this._gmails = itemList;
}
public override void CreateService()
{
var service = new GmailService(new BaseClientService.Initializer
{
<API key> = _credential,
ApplicationName = ApplicationName,
});
var allMailRequest = service.Users.Messages.List("me");
allMailRequest.MaxResults = 20;
allMailRequest.LabelIds = "CATEGORY_PERSONAL";
allMailRequest.IncludeSpamTrash = false;
try
{
var messages = allMailRequest.Execute().Messages;
// messages does not contain all the details of the mail, so we need to get more details
if (messages == null || messages.Count <= 0) return;
SetData(GetDetailsMail(messages, service));
InsertToDb(_gmails);
} catch (Exception error)
{
// TODO; Catch 400 error meaning user has no gmail
Debug.WriteLine(error);
}
}
<summary>
Gets more details of all the mails
</summary>
<param name="emails">all the emails from the ListResponse</param>
<param name="service">the created GmailService</param>
<returns></returns>
private List<GoogleGmailModel> GetDetailsMail(IEnumerable<Message> emails, GmailService service)
{
var allMails = new List<GoogleGmailModel>();
foreach (var message in emails)
{
allMails.Add(this.ResponseParser(service.Users.Messages.Get("me", message.Id).Execute()));
}
return allMails;
}
protected override GoogleGmailModel ResponseParser(Message response)
{
var email = new GoogleGmailModel
{
userId = _credential.UserId,
snippet = response.Snippet,
id = response.Id,
labels = FilterLabels(response.LabelIds)
};
email = FilterHeadersMail(response, email);
return email;
}
<summary>
Filters only the neccessary data we need from the mail
</summary>
<param name="response">the mail detail response</param>
<param name="email">the mail we want to save/use</param>
<returns>the mail you want to save/use</returns>
private static GoogleGmailModel FilterHeadersMail(Message response, GoogleGmailModel email)
{
foreach (var header in response.Payload.Headers)
{
if (header.Name == "From")
email.from = header.Value;
if (header.Name == "Subject")
email.subject = header.Value;
if (header.Name == "Date")
{
DateTime date;
DateTime.TryParse(header.Value, out date);
email.date = date;
}
}
return email;
}
<summary>
Sets all Labels of the mail in one string
</summary>
<param name="labels">The list of labels</param>
<returns>One string with all labels seperated by a "-"</returns>
private static string FilterLabels(IEnumerable<string> labels)
{
return labels.Aggregate("", (current, label) => current + (label + "-"));
}
public override void InsertToDb(List<GoogleGmailModel> data)
{
var gmailTable = new GoogleGmailTable();
foreach (var mail in data)
{
gmailTable.InsertRow(mail);
}
}
}
} |
<?php
class <API key> extends <API key>
{
protected $result;
public function __construct()
{
//$this->bootstrap = true;
$this->className = '<API key>';
include_once(_PS_MODULE_DIR_ . '/envoimoinscher/envoimoinscher.php');
parent::__construct();
$this->result = '';
}
public function postProcess()
{
$emc = new Envoimoinscher();
$option = Tools::getValue('option'); // Get option
// getModuleLink
//$link = new Link();
//$admin_link_base = $link->getAdminLink($emc->name,'getModuleLink');
switch ($option) {
case 'get_point':
$this->result = $emc->getPoints();
break;
case 'set_point':
$this->result = $emc->setPoint(Tools::getValue('point'));
break;
case 'push':
$this->result = (int)$emc->handlePush();
break;
case 'choixRelais':
die(require(_PS_MODULE_DIR_ . 'envoimoinscher/ajax/choix-relais.php'));
break;
}
}
public function display()
{
echo $this->result;
//die();
}
} |
@cond DOXYGEN_HIDDEN
#ifndef <API key>
#define <API key>
#ifndef <API key>
#include <sstream>
#include <tulip/<API key>.h>
#include <tulip/tulipconf.h>
#include <tulip/Color.h>
namespace tlp {
/**
* Class to build EPS file with OpenGL feedback buffer
*/
class TLP_GL_SCOPE <API key> : public <API key> {
public:
<API key>() : stream_out(std::stringstream::in | std::stringstream::out) {}
/**
* Begin new EPS document with viewport, clearColor, pointSize and lineWidth information
*/
void begin(const Vector<int, 4> &viewport, GLfloat *clearColor, GLfloat pointSize,
GLfloat lineWidth) override;
/**
* Record a new color
*/
void colorInfo(GLfloat *data) override;
/**
* Record a new GlEntity
*/
void beginGlEntity(GLfloat data) override;
/**
* End of a GlEntity
*/
void endGlEntity() override;
/**
* Record a new GlGraph
*/
void beginGlGraph(GLfloat data) override;
/**
* End of a GlGraph
*/
void endGlGraph() override;
/**
* Record a new Node
*/
void beginNode(GLfloat data) override;
/**
* End of a Node
*/
void endNode() override;
/**
* Record a new Edge
*/
void beginEdge(GLfloat data) override;
/**
* End of a Edge
*/
void endEdge() override;
/**
* Record a new pointToken
*/
void pointToken(GLfloat *data) override;
/**
* Record a new lineToken
*/
void lineToken(GLfloat *data) override;
/**
* Record a new lineResetToken
*/
void lineResetToken(GLfloat *data) override;
/**
* Record a new polygonToken
*/
void polygonToken(GLfloat *data) override;
/**
* End of the EPS document
*/
void end() override;
/**
* Put in str the built EPS document
*/
void getResult(std::string *str) override;
private:
std::stringstream stream_out;
GLfloat pointSize;
Color fillColor;
Color strokeColor;
Color textColor;
};
} // namespace tlp
#endif // <API key>
#endif // <API key>
@endcond |
/*
* server/zone/objects/tangible/resource/ResourceContainer.cpp generated by engine3 IDL compiler 0.55
*/
#include "ResourceContainer.h"
#include "<API key>.h"
#include "../../scene/SceneObject.h"
#include "../../creature/CreatureObject.h"
#include "../../player/Player.h"
#include "../TangibleObject.h"
/*
* <API key>
*/
ResourceContainer::ResourceContainer(unsigned long long oid) : TangibleObject(<API key>::instance()) {
_impl = new <API key>(oid);
_impl->_setStub(this);
}
ResourceContainer::ResourceContainer(unsigned long long oid, unsigned int tempCRC, const UnicodeString& n, const String& tempn) : TangibleObject(<API key>::instance()) {
_impl = new <API key>(oid, tempCRC, n, tempn);
_impl->_setStub(this);
}
ResourceContainer::ResourceContainer(CreatureObject* creature, unsigned int tempCRC, const UnicodeString& n, const String& tempn) : TangibleObject(<API key>::instance()) {
_impl = new <API key>(creature, tempCRC, n, tempn);
_impl->_setStub(this);
}
ResourceContainer::ResourceContainer(<API key>* param) : TangibleObject(param) {
}
ResourceContainer::~ResourceContainer() {
}
bool ResourceContainer::compare(ResourceContainer* inResource) {
if (_impl == NULL) {
if (!deployed)
throw <API key>(this);
DistributedMethod method(this, 6);
method.addObjectParameter(inResource);
return method.<API key>();
} else
return ((<API key>*) _impl)->compare(inResource);
}
void ResourceContainer::init() {
if (_impl == NULL) {
if (!deployed)
throw <API key>(this);
DistributedMethod method(this, 7);
method.<API key>();
} else
((<API key>*) _impl)->init();
}
void ResourceContainer::sendTo(Player* player, bool doClose) {
if (_impl == NULL) {
if (!deployed)
throw <API key>(this);
DistributedMethod method(this, 8);
method.addObjectParameter(player);
method.addBooleanParameter(doClose);
method.<API key>();
} else
((<API key>*) _impl)->sendTo(player, doClose);
}
void ResourceContainer::sendDeltas(Player* player) {
if (_impl == NULL) {
if (!deployed)
throw <API key>(this);
DistributedMethod method(this, 9);
method.addObjectParameter(player);
method.<API key>();
} else
((<API key>*) _impl)->sendDeltas(player);
}
void ResourceContainer::generateAttributes(SceneObject* obj) {
if (_impl == NULL) {
if (!deployed)
throw <API key>(this);
DistributedMethod method(this, 10);
method.addObjectParameter(obj);
method.<API key>();
} else
((<API key>*) _impl)->generateAttributes(obj);
}
void ResourceContainer::splitContainer(Player* player, int newQuantity) {
if (_impl == NULL) {
if (!deployed)
throw <API key>(this);
DistributedMethod method(this, 11);
method.addObjectParameter(player);
method.<API key>(newQuantity);
method.<API key>();
} else
((<API key>*) _impl)->splitContainer(player, newQuantity);
}
void ResourceContainer::transferContents(Player* player, ResourceContainer* fromRCO) {
if (_impl == NULL) {
if (!deployed)
throw <API key>(this);
DistributedMethod method(this, 12);
method.addObjectParameter(player);
method.addObjectParameter(fromRCO);
method.<API key>();
} else
((<API key>*) _impl)->transferContents(player, fromRCO);
}
void ResourceContainer::setContents(int i) {
if (_impl == NULL) {
if (!deployed)
throw <API key>(this);
DistributedMethod method(this, 13);
method.<API key>(i);
method.<API key>();
} else
((<API key>*) _impl)->setContents(i);
}
void ResourceContainer::setDecayResistance(int i) {
if (_impl == NULL) {
if (!deployed)
throw <API key>(this);
DistributedMethod method(this, 14);
method.<API key>(i);
method.<API key>();
} else
((<API key>*) _impl)->setDecayResistance(i);
}
void ResourceContainer::setQuality(int i) {
if (_impl == NULL) {
if (!deployed)
throw <API key>(this);
DistributedMethod method(this, 15);
method.<API key>(i);
method.<API key>();
} else
((<API key>*) _impl)->setQuality(i);
}
void ResourceContainer::setFlavor(int i) {
if (_impl == NULL) {
if (!deployed)
throw <API key>(this);
DistributedMethod method(this, 16);
method.<API key>(i);
method.<API key>();
} else
((<API key>*) _impl)->setFlavor(i);
}
void ResourceContainer::setPotentialEnergy(int i) {
if (_impl == NULL) {
if (!deployed)
throw <API key>(this);
DistributedMethod method(this, 17);
method.<API key>(i);
method.<API key>();
} else
((<API key>*) _impl)->setPotentialEnergy(i);
}
void ResourceContainer::setMalleability(int i) {
if (_impl == NULL) {
if (!deployed)
throw <API key>(this);
DistributedMethod method(this, 18);
method.<API key>(i);
method.<API key>();
} else
((<API key>*) _impl)->setMalleability(i);
}
void ResourceContainer::setToughness(int i) {
if (_impl == NULL) {
if (!deployed)
throw <API key>(this);
DistributedMethod method(this, 19);
method.<API key>(i);
method.<API key>();
} else
((<API key>*) _impl)->setToughness(i);
}
void ResourceContainer::setShockResistance(int i) {
if (_impl == NULL) {
if (!deployed)
throw <API key>(this);
DistributedMethod method(this, 20);
method.<API key>(i);
method.<API key>();
} else
((<API key>*) _impl)->setShockResistance(i);
}
void ResourceContainer::setColdResistance(int i) {
if (_impl == NULL) {
if (!deployed)
throw <API key>(this);
DistributedMethod method(this, 21);
method.<API key>(i);
method.<API key>();
} else
((<API key>*) _impl)->setColdResistance(i);
}
void ResourceContainer::setHeatResistance(int i) {
if (_impl == NULL) {
if (!deployed)
throw <API key>(this);
DistributedMethod method(this, 22);
method.<API key>(i);
method.<API key>();
} else
((<API key>*) _impl)->setHeatResistance(i);
}
void ResourceContainer::setConductivity(int i) {
if (_impl == NULL) {
if (!deployed)
throw <API key>(this);
DistributedMethod method(this, 23);
method.<API key>(i);
method.<API key>();
} else
((<API key>*) _impl)->setConductivity(i);
}
void ResourceContainer::<API key>(int i) {
if (_impl == NULL) {
if (!deployed)
throw <API key>(this);
DistributedMethod method(this, 24);
method.<API key>(i);
method.<API key>();
} else
((<API key>*) _impl)-><API key>(i);
}
void ResourceContainer::setClassSeven(String& str) {
if (_impl == NULL) {
if (!deployed)
throw <API key>(this);
DistributedMethod method(this, 25);
method.addAsciiParameter(str);
method.<API key>();
} else
((<API key>*) _impl)->setClassSeven(str);
}
void ResourceContainer::setResourceName(String& str) {
if (_impl == NULL) {
if (!deployed)
throw <API key>(this);
DistributedMethod method(this, 26);
method.addAsciiParameter(str);
method.<API key>();
} else
((<API key>*) _impl)->setResourceName(str);
}
void ResourceContainer::setContainerFile(String& tempn) {
if (_impl == NULL) {
if (!deployed)
throw <API key>(this);
DistributedMethod method(this, 27);
method.addAsciiParameter(tempn);
method.<API key>();
} else
((<API key>*) _impl)->setContainerFile(tempn);
}
void ResourceContainer::setName(UnicodeString& n) {
if (_impl == NULL) {
if (!deployed)
throw <API key>(this);
DistributedMethod method(this, 28);
method.addUnicodeParameter(n);
method.<API key>();
} else
((<API key>*) _impl)->setName(n);
}
void ResourceContainer::setObjectCRC(int tempCRC) {
if (_impl == NULL) {
if (!deployed)
throw <API key>(this);
DistributedMethod method(this, 29);
method.<API key>(tempCRC);
method.<API key>();
} else
((<API key>*) _impl)->setObjectCRC(tempCRC);
}
void ResourceContainer::setResourceID(unsigned long long rid) {
if (_impl == NULL) {
if (!deployed)
throw <API key>(this);
DistributedMethod method(this, 30);
method.<API key>(rid);
method.<API key>();
} else
((<API key>*) _impl)->setResourceID(rid);
}
void ResourceContainer::setObjectSubType(int subType) {
if (_impl == NULL) {
if (!deployed)
throw <API key>(this);
DistributedMethod method(this, 31);
method.<API key>(subType);
method.<API key>();
} else
((<API key>*) _impl)->setObjectSubType(subType);
}
void ResourceContainer::setIsEnergy(bool state) {
if (_impl == NULL) {
if (!deployed)
throw <API key>(this);
DistributedMethod method(this, 32);
method.addBooleanParameter(state);
method.<API key>();
} else
((<API key>*) _impl)->setIsEnergy(state);
}
int ResourceContainer::getContents() {
if (_impl == NULL) {
if (!deployed)
throw <API key>(this);
DistributedMethod method(this, 33);
return method.<API key>();
} else
return ((<API key>*) _impl)->getContents();
}
int ResourceContainer::getDecayResistance() {
if (_impl == NULL) {
if (!deployed)
throw <API key>(this);
DistributedMethod method(this, 34);
return method.<API key>();
} else
return ((<API key>*) _impl)->getDecayResistance();
}
int ResourceContainer::getQuality() {
if (_impl == NULL) {
if (!deployed)
throw <API key>(this);
DistributedMethod method(this, 35);
return method.<API key>();
} else
return ((<API key>*) _impl)->getQuality();
}
int ResourceContainer::getFlavor() {
if (_impl == NULL) {
if (!deployed)
throw <API key>(this);
DistributedMethod method(this, 36);
return method.<API key>();
} else
return ((<API key>*) _impl)->getFlavor();
}
int ResourceContainer::getPotentialEnergy() {
if (_impl == NULL) {
if (!deployed)
throw <API key>(this);
DistributedMethod method(this, 37);
return method.<API key>();
} else
return ((<API key>*) _impl)->getPotentialEnergy();
}
int ResourceContainer::getMalleability() {
if (_impl == NULL) {
if (!deployed)
throw <API key>(this);
DistributedMethod method(this, 38);
return method.<API key>();
} else
return ((<API key>*) _impl)->getMalleability();
}
int ResourceContainer::getToughness() {
if (_impl == NULL) {
if (!deployed)
throw <API key>(this);
DistributedMethod method(this, 39);
return method.<API key>();
} else
return ((<API key>*) _impl)->getToughness();
}
int ResourceContainer::getShockResistance() {
if (_impl == NULL) {
if (!deployed)
throw <API key>(this);
DistributedMethod method(this, 40);
return method.<API key>();
} else
return ((<API key>*) _impl)->getShockResistance();
}
int ResourceContainer::getColdResistance() {
if (_impl == NULL) {
if (!deployed)
throw <API key>(this);
DistributedMethod method(this, 41);
return method.<API key>();
} else
return ((<API key>*) _impl)->getColdResistance();
}
int ResourceContainer::getHeatResistance() {
if (_impl == NULL) {
if (!deployed)
throw <API key>(this);
DistributedMethod method(this, 42);
return method.<API key>();
} else
return ((<API key>*) _impl)->getHeatResistance();
}
int ResourceContainer::getConductivity() {
if (_impl == NULL) {
if (!deployed)
throw <API key>(this);
DistributedMethod method(this, 43);
return method.<API key>();
} else
return ((<API key>*) _impl)->getConductivity();
}
int ResourceContainer::<API key>() {
if (_impl == NULL) {
if (!deployed)
throw <API key>(this);
DistributedMethod method(this, 44);
return method.<API key>();
} else
return ((<API key>*) _impl)-><API key>();
}
String& ResourceContainer::getClassSeven() {
if (_impl == NULL) {
if (!deployed)
throw <API key>(this);
DistributedMethod method(this, 45);
method.<API key>(<API key>);
return <API key>;
} else
return ((<API key>*) _impl)->getClassSeven();
}
String& ResourceContainer::getResourceName() {
if (_impl == NULL) {
if (!deployed)
throw <API key>(this);
DistributedMethod method(this, 46);
method.<API key>(<API key>);
return <API key>;
} else
return ((<API key>*) _impl)->getResourceName();
}
unsigned long long ResourceContainer::getResourceID() {
if (_impl == NULL) {
if (!deployed)
throw <API key>(this);
DistributedMethod method(this, 47);
return method.<API key>();
} else
return ((<API key>*) _impl)->getResourceID();
}
int ResourceContainer::getMaxContents() {
if (_impl == NULL) {
if (!deployed)
throw <API key>(this);
DistributedMethod method(this, 48);
return method.<API key>();
} else
return ((<API key>*) _impl)->getMaxContents();
}
bool ResourceContainer::isEnergy() {
if (_impl == NULL) {
if (!deployed)
throw <API key>(this);
DistributedMethod method(this, 49);
return method.<API key>();
} else
return ((<API key>*) _impl)->isEnergy();
}
/*
* <API key>
*/
<API key>::<API key>(<API key>* obj) : <API key>(obj) {
}
Packet* <API key>::invokeMethod(uint32 methid, DistributedMethod* inv) {
Packet* resp = new MethodReturnMessage(0);
switch (methid) {
case 6:
resp->insertBoolean(compare((ResourceContainer*) inv->getObjectParameter()));
break;
case 7:
init();
break;
case 8:
sendTo((Player*) inv->getObjectParameter(), inv->getBooleanParameter());
break;
case 9:
sendDeltas((Player*) inv->getObjectParameter());
break;
case 10:
generateAttributes((SceneObject*) inv->getObjectParameter());
break;
case 11:
splitContainer((Player*) inv->getObjectParameter(), inv-><API key>());
break;
case 12:
transferContents((Player*) inv->getObjectParameter(), (ResourceContainer*) inv->getObjectParameter());
break;
case 13:
setContents(inv-><API key>());
break;
case 14:
setDecayResistance(inv-><API key>());
break;
case 15:
setQuality(inv-><API key>());
break;
case 16:
setFlavor(inv-><API key>());
break;
case 17:
setPotentialEnergy(inv-><API key>());
break;
case 18:
setMalleability(inv-><API key>());
break;
case 19:
setToughness(inv-><API key>());
break;
case 20:
setShockResistance(inv-><API key>());
break;
case 21:
setColdResistance(inv-><API key>());
break;
case 22:
setHeatResistance(inv-><API key>());
break;
case 23:
setConductivity(inv-><API key>());
break;
case 24:
<API key>(inv-><API key>());
break;
case 25:
setClassSeven(inv->getAsciiParameter(<API key>));
break;
case 26:
setResourceName(inv->getAsciiParameter(<API key>));
break;
case 27:
setContainerFile(inv->getAsciiParameter(<API key>));
break;
case 28:
setName(inv->getUnicodeParameter(<API key>));
break;
case 29:
setObjectCRC(inv-><API key>());
break;
case 30:
setResourceID(inv-><API key>());
break;
case 31:
setObjectSubType(inv-><API key>());
break;
case 32:
setIsEnergy(inv->getBooleanParameter());
break;
case 33:
resp->insertSignedInt(getContents());
break;
case 34:
resp->insertSignedInt(getDecayResistance());
break;
case 35:
resp->insertSignedInt(getQuality());
break;
case 36:
resp->insertSignedInt(getFlavor());
break;
case 37:
resp->insertSignedInt(getPotentialEnergy());
break;
case 38:
resp->insertSignedInt(getMalleability());
break;
case 39:
resp->insertSignedInt(getToughness());
break;
case 40:
resp->insertSignedInt(getShockResistance());
break;
case 41:
resp->insertSignedInt(getColdResistance());
break;
case 42:
resp->insertSignedInt(getHeatResistance());
break;
case 43:
resp->insertSignedInt(getConductivity());
break;
case 44:
resp->insertSignedInt(<API key>());
break;
case 45:
resp->insertAscii(getClassSeven());
break;
case 46:
resp->insertAscii(getResourceName());
break;
case 47:
resp->insertLong(getResourceID());
break;
case 48:
resp->insertSignedInt(getMaxContents());
break;
case 49:
resp->insertBoolean(isEnergy());
break;
default:
return NULL;
}
return resp;
}
bool <API key>::compare(ResourceContainer* inResource) {
return ((<API key>*) impl)->compare(inResource);
}
void <API key>::init() {
return ((<API key>*) impl)->init();
}
void <API key>::sendTo(Player* player, bool doClose) {
return ((<API key>*) impl)->sendTo(player, doClose);
}
void <API key>::sendDeltas(Player* player) {
return ((<API key>*) impl)->sendDeltas(player);
}
void <API key>::generateAttributes(SceneObject* obj) {
return ((<API key>*) impl)->generateAttributes(obj);
}
void <API key>::splitContainer(Player* player, int newQuantity) {
return ((<API key>*) impl)->splitContainer(player, newQuantity);
}
void <API key>::transferContents(Player* player, ResourceContainer* fromRCO) {
return ((<API key>*) impl)->transferContents(player, fromRCO);
}
void <API key>::setContents(int i) {
return ((<API key>*) impl)->setContents(i);
}
void <API key>::setDecayResistance(int i) {
return ((<API key>*) impl)->setDecayResistance(i);
}
void <API key>::setQuality(int i) {
return ((<API key>*) impl)->setQuality(i);
}
void <API key>::setFlavor(int i) {
return ((<API key>*) impl)->setFlavor(i);
}
void <API key>::setPotentialEnergy(int i) {
return ((<API key>*) impl)->setPotentialEnergy(i);
}
void <API key>::setMalleability(int i) {
return ((<API key>*) impl)->setMalleability(i);
}
void <API key>::setToughness(int i) {
return ((<API key>*) impl)->setToughness(i);
}
void <API key>::setShockResistance(int i) {
return ((<API key>*) impl)->setShockResistance(i);
}
void <API key>::setColdResistance(int i) {
return ((<API key>*) impl)->setColdResistance(i);
}
void <API key>::setHeatResistance(int i) {
return ((<API key>*) impl)->setHeatResistance(i);
}
void <API key>::setConductivity(int i) {
return ((<API key>*) impl)->setConductivity(i);
}
void <API key>::<API key>(int i) {
return ((<API key>*) impl)-><API key>(i);
}
void <API key>::setClassSeven(String& str) {
return ((<API key>*) impl)->setClassSeven(str);
}
void <API key>::setResourceName(String& str) {
return ((<API key>*) impl)->setResourceName(str);
}
void <API key>::setContainerFile(String& tempn) {
return ((<API key>*) impl)->setContainerFile(tempn);
}
void <API key>::setName(UnicodeString& n) {
return ((<API key>*) impl)->setName(n);
}
void <API key>::setObjectCRC(int tempCRC) {
return ((<API key>*) impl)->setObjectCRC(tempCRC);
}
void <API key>::setResourceID(unsigned long long rid) {
return ((<API key>*) impl)->setResourceID(rid);
}
void <API key>::setObjectSubType(int subType) {
return ((<API key>*) impl)->setObjectSubType(subType);
}
void <API key>::setIsEnergy(bool state) {
return ((<API key>*) impl)->setIsEnergy(state);
}
int <API key>::getContents() {
return ((<API key>*) impl)->getContents();
}
int <API key>::getDecayResistance() {
return ((<API key>*) impl)->getDecayResistance();
}
int <API key>::getQuality() {
return ((<API key>*) impl)->getQuality();
}
int <API key>::getFlavor() {
return ((<API key>*) impl)->getFlavor();
}
int <API key>::getPotentialEnergy() {
return ((<API key>*) impl)->getPotentialEnergy();
}
int <API key>::getMalleability() {
return ((<API key>*) impl)->getMalleability();
}
int <API key>::getToughness() {
return ((<API key>*) impl)->getToughness();
}
int <API key>::getShockResistance() {
return ((<API key>*) impl)->getShockResistance();
}
int <API key>::getColdResistance() {
return ((<API key>*) impl)->getColdResistance();
}
int <API key>::getHeatResistance() {
return ((<API key>*) impl)->getHeatResistance();
}
int <API key>::getConductivity() {
return ((<API key>*) impl)->getConductivity();
}
int <API key>::<API key>() {
return ((<API key>*) impl)-><API key>();
}
String& <API key>::getClassSeven() {
return ((<API key>*) impl)->getClassSeven();
}
String& <API key>::getResourceName() {
return ((<API key>*) impl)->getResourceName();
}
unsigned long long <API key>::getResourceID() {
return ((<API key>*) impl)->getResourceID();
}
int <API key>::getMaxContents() {
return ((<API key>*) impl)->getMaxContents();
}
bool <API key>::isEnergy() {
return ((<API key>*) impl)->isEnergy();
}
/*
* <API key>
*/
<API key>* <API key>::staticInitializer = <API key>::instance();
<API key>::<API key>() {
className = "ResourceContainer";
<API key>::instance()->registerClass(className, this);
}
void <API key>::finalizeHelper() {
<API key>::finalize();
}
DistributedObject* <API key>::instantiateObject() {
return new ResourceContainer(<API key>::instance());
}
<API key>* <API key>::createAdapter(<API key>* obj) {
<API key>* adapter = new <API key>((<API key>*) obj->_getImplementation());
obj->_setClassName(className);
obj->_setClassHelper(this);
adapter->setStub(obj);
return adapter;
}
/*
* <API key>
*/
<API key>::<API key>(unsigned long long oid, int tp) : <API key>(oid, tp) {
_classHelper = <API key>::instance();
}
<API key>::<API key>(unsigned long long oid, unsigned int tempCRC, const UnicodeString& n, const String& tempn, int tp) : <API key>(oid, tempCRC, n, tempn, tp) {
_classHelper = <API key>::instance();
}
<API key>::<API key>(CreatureObject* creature, unsigned int tempCRC, const UnicodeString& n, const String& tempn, int tp) : <API key>(creature, tempCRC, n, tempn, tp) {
_classHelper = <API key>::instance();
}
<API key>::~<API key>() {
}
void <API key>::_setStub(<API key>* stub) {
_this = (ResourceContainer*) stub;
<API key>::_setStub(stub);
}
<API key>* <API key>::_getStub() {
return _this;
} |
/**
* @file d2xx_init.h
* API for initialisation of user defined <em>VID</em>/<em>PID</em> pairs.
*/
#ifndef D2XX_INIT_H_
#define D2XX_INIT_H_
#include <stdio.h>
#include "d2xx_table.h"
/**
* Defines the linkage of declared functions. If this file is included by an
* application they're marked as <code>external</code>.
*/
#ifdef <API key>
#define D2XX_INIT_DECL
#else
#define D2XX_INIT_DECL extern
#endif
#ifdef __cplusplus
extern "C" {
#endif
D2XX_INIT_DECL FILE *D2xx_OpenConfigFile(void);
D2XX_INIT_DECL void <API key>(FILE * file);
D2XX_INIT_DECL void D2xx_ReadTable(FILE * file, ProductDescriptor* table, int tableSize, int tableOffset);
#ifdef __cplusplus
}
#endif
#endif /*D2XX_INIT_H_*/ |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Net;
using NLog;
using Newtonsoft.Json.Linq;
namespace Gelf4NLog.Target
{
public class GelfConverter : IConverter
{
private const int <API key> = 250;
private const string GelfVersion = "1.0";
public JObject GetGelfJson(LogEventInfo logEventInfo, string facility)
{
//Retrieve the formatted message from LogEventInfo
var logEventMessage = logEventInfo.FormattedMessage;
if (logEventMessage == null) return null;
//If we are dealing with an exception, pass exception properties to LogEventInfo properties
if (logEventInfo.Exception != null)
{
logEventInfo.Properties.Add("ExceptionSource", logEventInfo.Exception.Source);
logEventInfo.Properties.Add("ExceptionMessage", logEventInfo.Exception.Message);
logEventInfo.Properties.Add("StackTrace", logEventInfo.Exception.StackTrace);
}
//Figure out the short message
var shortMessage = logEventMessage;
if (shortMessage.Length > <API key>)
{
shortMessage = shortMessage.Substring(0, <API key>);
}
//Construct the instance of GelfMessage
var gelfMessage = new GelfMessage
{
Version = GelfVersion,
Host = Dns.GetHostName(),
ShortMessage = shortMessage,
FullMessage = logEventMessage,
Timestamp = logEventInfo.TimeStamp,
Level = GetSeverityLevel(logEventInfo.Level),
//Spec says: facility must be set by the client to "GELF" if empty
Facility = (string.IsNullOrEmpty(facility) ? "GELF" : facility),
Line = (logEventInfo.UserStackFrame != null)
? logEventInfo.UserStackFrame.GetFileLineNumber().ToString(
CultureInfo.InvariantCulture)
: string.Empty,
File = (logEventInfo.UserStackFrame != null)
? logEventInfo.UserStackFrame.GetFileName()
: string.Empty,
};
//Convert to JSON
var jsonObject = JObject.FromObject(gelfMessage);
//Add any other interesting data to LogEventInfo properties
logEventInfo.Properties.Add("LoggerName", logEventInfo.LoggerName);
//We will persist them "Additional Fields" according to Gelf spec
foreach (var property in logEventInfo.Properties)
{
AddAdditionalField(jsonObject, property);
}
return jsonObject;
}
private static void AddAdditionalField(IDictionary<string, JToken> jObject, KeyValuePair<object, object> property)
{
var key = property.Key as string;
var value = property.Value as string;
if (key == null) return;
//According to the GELF spec, libraries should NOT allow to send id as additional field (_id)
//Server MUST skip the field because it could override the MongoDB _key field
if (key.Equals("id", StringComparison.OrdinalIgnoreCase))
key = "id_";
//According to the GELF spec, additional field keys should start with '_' to avoid collision
if (!key.StartsWith("_", StringComparison.OrdinalIgnoreCase))
key = "_" + key;
jObject.Add(key, value);
}
<summary>
Values from SyslogSeverity enum here: http://marc.info/?l=log4net-dev&m=109519564630799
</summary>
<param name="level"></param>
<returns></returns>
private static int GetSeverityLevel(LogLevel level)
{
if (level == LogLevel.Debug)
{
return 7;
}
if (level == LogLevel.Fatal)
{
return 2;
}
if (level == LogLevel.Info)
{
return 6;
}
if (level == LogLevel.Trace)
{
return 6;
}
if (level == LogLevel.Warn)
{
return 4;
}
return 3; //LogLevel.Error
}
}
} |
package com.sones;
import java.math.BigInteger;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"<API key>"
})
@XmlRootElement(name = "<API key>")
public class <API key> {
@XmlElement(name = "<API key>")
@XmlSchemaType(name = "unsignedLong")
protected BigInteger <API key>;
/**
* Gets the value of the <API key> property.
*
* @return
* possible object is
* {@link BigInteger }
*
*/
public BigInteger <API key>() {
return <API key>;
}
/**
* Sets the value of the <API key> property.
*
* @param value
* allowed object is
* {@link BigInteger }
*
*/
public void <API key>(BigInteger value) {
this.<API key> = value;
}
} |
<?php
namespace App\Migrations;
use T4\Orm\Migration;
class <API key>
extends Migration
{
public function up()
{
$this->createTable('categories', [
'title' => ['type' => 'string'],
], [], ['tree']);
}
public function down()
{
$this->dropTable('categories');
}
} |
#include "GUI/Button.h"
Button::Button()
{
//ctor
}
Button::~Button()
{
//dtor
}
void Button::load(sf::Vector2f pos, const sf::Texture& tex, sf::Vector2f texCoord, sf::Vector2f texDimensions, sf::Vector2i scale) {
this->pos = pos;
this->tex = tex;
this->texCoord = texCoord;
this->texDimensions = texDimensions;
selected = false;
change = 1;
vertices.setPrimitiveType(sf::Quads);
vertices.resize(4);
vertices[0].position = sf::Vector2f(pos.x, pos.y);
vertices[1].position = sf::Vector2f(pos.x + (scale.x * texDimensions.x), pos.y);
vertices[2].position = sf::Vector2f(pos.x + (scale.x * texDimensions.x), pos.y + (scale.y * texDimensions.y));
vertices[3].position = sf::Vector2f(pos.x, pos.y + (scale.y * texDimensions.y));
vertices[0].texCoords = sf::Vector2f(texCoord.x, texCoord.y);
vertices[1].texCoords = sf::Vector2f(texCoord.x + texDimensions.x, texCoord.y);
vertices[2].texCoords = sf::Vector2f(texCoord.x + texDimensions.x, texCoord.y + texDimensions.y);
vertices[3].texCoords = sf::Vector2f(texCoord.x, texCoord.y + texDimensions.y);
bounds.left = pos.x;
bounds.top = pos.y;
bounds.width = scale.x * texDimensions.x;
bounds.height = scale.y * texDimensions.y;
}
void Button::unload() {
Entity::unload();
}
void Button::update(sf::Vector2i &p) {
if (bounds.contains(p.x, p.y)) {
change = 1;
highlight(change);
if (sf::Mouse::isButtonPressed(sf::Mouse::Button::Left)) {
pressed = true;
}
} else {
change = 0;
highlight(change);
pressed = false;
}
}
void Button::highlight(int change) {
vertices[0].texCoords = sf::Vector2f(texCoord.x + (change * texDimensions.x), texCoord.y);
vertices[1].texCoords = sf::Vector2f(texCoord.x + ((change + 1) * texDimensions.x), texCoord.y);
vertices[2].texCoords = sf::Vector2f(texCoord.x + ((change + 1) * texDimensions.x), texCoord.y + texDimensions.y);
vertices[3].texCoords = sf::Vector2f(texCoord.x + (change * texDimensions.x), texCoord.y + texDimensions.y);
} |
package org.geolatte.common.reflection;
import org.junit.Assert;
import org.junit.Test;
public class <API key> {
@SuppressWarnings({"<API key>"})
@Test
public void ConstructorTest()
{
<API key> exc = new <API key>();
Assert.assertEquals(null, exc.getMessage());
Assert.assertEquals(null, exc.getCause());
String message = "Hallo";
Exception cause = new <API key>();
exc = new <API key>(message);
Assert.assertEquals(message, exc.getMessage());
Assert.assertEquals(null, exc.getCause());
exc = new <API key>(cause);
Assert.assertEquals(cause, exc.getCause());
exc = new <API key>(message, cause);
Assert.assertEquals(message, exc.getMessage());
Assert.assertEquals(cause, exc.getCause());
}
} |
<?php
namespace <API key>\FedExPHP\Structs;
use \WsdlToPhp\PackageBase\AbstractStructBase;
/**
* This class stands for <API key> Structs
* Meta informations extracted from the WSDL
* - documentation: Specifies the concept of a container used to package dangerous goods commodities.
* @subpackage Structs
*/
class <API key> extends AbstractStructBase
{
/**
* The QValue
* Meta informations extracted from the WSDL
* - documentation: Indicates that the quantity of the dangerous goods packaged is permissible for shipping. This is used to ensure that the dangerous goods commodities do not exceed the net quantity per package restrictions.
* - minOccurs: 0
* @var float
*/
public $QValue;
/**
* The <API key>
* Meta informations extracted from the WSDL
* - documentation: Documents the kinds and quantities of all hazardous commodities in the current package.
* - maxOccurs: unbounded
* - minOccurs: 0
* @var \<API key>\FedExPHP\Structs\<API key>[]
*/
public $<API key>;
/**
* Constructor method for <API key>
* @uses <API key>::setQValue()
* @uses <API key>::<API key>()
* @param float $qValue
* @param \<API key>\FedExPHP\Structs\<API key>[] $<API key>
*/
public function __construct($qValue = null, array $<API key> = array())
{
$this
->setQValue($qValue)
-><API key>($<API key>);
}
/**
* Get QValue value
* @return float|null
*/
public function getQValue()
{
return $this->QValue;
}
/**
* Set QValue value
* @param float $qValue
* @return \<API key>\FedExPHP\Structs\<API key>
*/
public function setQValue($qValue = null)
{
$this->QValue = $qValue;
return $this;
}
/**
* Get <API key> value
* @return \<API key>\FedExPHP\Structs\<API key>[]|null
*/
public function <API key>()
{
return $this-><API key>;
}
/**
* Set <API key> value
* @throws \<API key>
* @param \<API key>\FedExPHP\Structs\<API key>[] $<API key>
* @return \<API key>\FedExPHP\Structs\<API key>
*/
public function <API key>(array $<API key> = array())
{
foreach ($<API key> as $<API key>) {
// validation for constraint: itemType
if (!$<API key> instanceof \<API key>\FedExPHP\Structs\<API key>) {
throw new \<API key>(sprintf('The <API key> property can only contain items of \<API key>\FedExPHP\Structs\<API key>, "%s" given', is_object($<API key>) ? get_class($<API key>) : gettype($<API key>)), __LINE__);
}
}
$this-><API key> = $<API key>;
return $this;
}
/**
* Add item to <API key> value
* @throws \<API key>
* @param \<API key>\FedExPHP\Structs\<API key> $item
* @return \<API key>\FedExPHP\Structs\<API key>
*/
public function <API key>(\<API key>\FedExPHP\Structs\<API key> $item)
{
// validation for constraint: itemType
if (!$item instanceof \<API key>\FedExPHP\Structs\<API key>) {
throw new \<API key>(sprintf('The <API key> property can only contain items of \<API key>\FedExPHP\Structs\<API key>, "%s" given', is_object($item) ? get_class($item) : gettype($item)), __LINE__);
}
$this-><API key>[] = $item;
return $this;
}
/**
* Method called when an object has been exported with var_export() functions
* It allows to return an object instantiated with the values
* @see AbstractStructBase::__set_state()
* @uses AbstractStructBase::__set_state()
* @param array $array the exported values
* @return \<API key>\FedExPHP\Structs\<API key>
*/
public static function __set_state(array $array)
{
return parent::__set_state($array);
}
/**
* Method returning the class name
* @return string __CLASS__
*/
public function __toString()
{
return __CLASS__;
}
} |
// CoderG the 2016 project
// Insight 0+0 [ 0+0 ]
// Stephen Fire Meditation Qin [ ] -> firemeditation@gmail.com
package drule
import (
"fmt"
"strings"
"github.com/idcsource/insight00-lib/hardstore"
"github.com/idcsource/insight00-lib/nst"
)
// <-- DATA_PLEASEslave
func (d *DRule) beginTransaction(conn_exec *nst.ConnExec) (err error) {
err = d.serverDataReceipt(conn_exec, DATA_PLEASE, nil, nil)
if err != nil {
return err
}
tranid_b, err := conn_exec.GetData()
if err != nil {
return err
}
tranid := string(tranid_b)
// masterslaveID
if d.dmode == DMODE_MASTER {
var can []*slaveIn
can, err = d.<API key>(tranid)
if err != nil {
// canRollback
d.<API key>(tranid, can)
// ExecTCP
return err
}
}
err = d.trule.beginForDRule(tranid)
if err != nil && d.dmode == DMODE_MASTER {
d.<API key>(tranid)
}
if err == nil {
d.serverDataReceipt(conn_exec, DATA_ALL_OK, nil, nil)
}
return
}
// slave
func (d *DRule) <API key>(tranid string) (can []*slaveIn, err error) {
can = make([]*slaveIn, 0)
errarray := make([]string, 0)
for _, onec := range d.slavecpool {
errn := d.<API key>(tranid, onec)
if errn != nil {
errarray = append(errarray, errn.Error())
} else {
can = append(can, onec)
}
}
if len(errarray) != 0 {
errstr := strings.Join(errarray, " | ")
err = fmt.Errorf(errstr)
}
return
}
// slave
// --> OPERATE_TRAN_BEGIN
// <-- DATA_PLEASE
// --> tranid
// <-- DATA_ALL_OK
func (d *DRule) <API key>(tranid string, onec *slaveIn) (err error) {
cprocess := onec.tcpconn.OpenProgress()
defer cprocess.Close()
slave_receipt, err := SendPrefixStat(cprocess, onec.unid, d.selfname, tranid, false, "", OPERATE_TRAN_BEGIN)
if err != nil {
return err
}
if slave_receipt.DataStat != DATA_PLEASE {
return fmt.Errorf(slave_receipt.Error)
}
// tranid
slave_receipt, err = <API key>(cprocess, []byte(tranid))
if err != nil {
return err
}
if slave_receipt.DataStat != DATA_ALL_OK {
return fmt.Errorf(slave_receipt.Error)
}
return
}
// --> DATA_PLEASE
// <-- Net_Transaction
// --> DATA_ALL_OK
func (d *DRule) prepareTransaction(conn_exec *nst.ConnExec) (err error) {
err = d.serverDataReceipt(conn_exec, DATA_PLEASE, nil, nil)
if err != nil {
return err
}
// Net
tran_b, err := conn_exec.GetData()
if err != nil {
return err
}
tran_net := Net_Transaction{}
err = nst.BytesGobStruct(tran_b, &tran_net)
// masterslaveID
if d.dmode == DMODE_MASTER {
var can []*slaveIn
can, err = d.<API key>(tran_net)
if err != nil {
// canRollback
d.<API key>(tran_net.TransactionId, can)
// ExecTCP
return err
}
}
// tran_net
tran_net.PrepareIDs = d.<API key>(tran_net.PrepareIDs)
err = d.trule.prepareForDRule(tran_net.TransactionId, tran_net.PrepareIDs)
if err != nil && d.dmode == DMODE_MASTER {
d.<API key>(tran_net.TransactionId)
}
if err == nil {
d.serverDataReceipt(conn_exec, DATA_ALL_OK, nil, nil)
}
return
}
// slave
func (d *DRule) <API key>(tran_net Net_Transaction) (can []*slaveIn, err error) {
can = make([]*slaveIn, 0)
errarray := make([]string, 0)
for _, onec := range d.slavecpool {
errn := d.<API key>(tran_net, onec)
if errn != nil {
errarray = append(errarray, errn.Error())
} else {
can = append(can, onec)
}
}
if len(errarray) != 0 {
errstr := strings.Join(errarray, " | ")
err = fmt.Errorf(errstr)
}
return
}
// slave
// --> OPERATE_TRAN_PREPARE
// <-- DATA_PLEASE
// --> Net_Transaction
// <-- DATA_ALL_OK
func (d *DRule) <API key>(tran_net Net_Transaction, onec *slaveIn) (err error) {
cprocess := onec.tcpconn.OpenProgress()
defer cprocess.Close()
slave_receipt, err := SendPrefixStat(cprocess, onec.unid, d.selfname, tran_net.TransactionId, false, "", <API key>)
if err != nil {
return err
}
if slave_receipt.DataStat != DATA_PLEASE {
return fmt.Errorf(slave_receipt.Error)
}
// tran_net
tran_net.PrepareIDs = d.<API key>(tran_net.PrepareIDs, onec)
// tran_net
tran_b, err := nst.StructGobBytes(tran_net)
if err != nil {
return err
}
slave_receipt, err = <API key>(cprocess, tran_b)
if err != nil {
return err
}
if slave_receipt.DataStat != DATA_ALL_OK {
return fmt.Errorf(slave_receipt.Error)
}
return
}
// slave
func (d *DRule) <API key>(ids []string, conn *slaveIn) (newids []string) {
newids = make([]string, 0)
for key := range ids {
id := hardstore.GetRoleStoreName(ids[key])
theChar := string(id[0])
// slave
conns, find := d.slaves[theChar]
if find == true {
for onek := range conns {
if conns[onek].name == conn.name {
newids = append(newids, ids[key])
break
}
}
}
}
return
}
func (d *DRule) <API key>(ids []string) (newids []string) {
newids = make([]string, 0)
for key := range ids {
id := hardstore.GetRoleStoreName(ids[key])
theChar := string(id[0])
// slave
_, find := d.slaves[theChar]
if find == false {
newids = append(newids, ids[key])
}
}
return
}
func (d *DRule) <API key>(tranid string, can []*slaveIn) {
for _, onec := range can {
d.rollbackSlaveOne(tranid, onec)
}
}
// slave
func (d *DRule) <API key>(tranid string) (err error) {
for _, onec := range d.slavecpool {
d.rollbackSlaveOne(tranid, onec)
}
return
}
// ExecTCP
func (d *DRule) rollbackTransaction(tranid string, conn_exec *nst.ConnExec) (err error) {
// Masterslave
if d.dmode == DMODE_MASTER {
d.<API key>(tranid)
}
tran, err := d.trule.<API key>(tranid)
if err == nil {
tran.Rollback()
d.serverDataReceipt(conn_exec, DATA_ALL_OK, nil, nil)
}
return nil
}
// ExecTCPtcp
func (d *DRule) <API key>(tranid string, conn_exec *nst.ConnExec) (err error) {
// Masterslave
if d.dmode == DMODE_MASTER {
d.<API key>(tranid)
}
tran, err := d.trule.<API key>(tranid)
if err == nil {
tran.Rollback()
}
return nil
}
// slave
// --> OPERATE_TRAN_ROLLBACK
// <-- DATA_ALL_OK
func (d *DRule) rollbackSlaveOne(tranid string, onec *slaveIn) (err error) {
cprocess := onec.tcpconn.OpenProgress()
defer cprocess.Close()
slave_receipt, err := SendPrefixStat(cprocess, onec.unid, d.selfname, tranid, true, "", <API key>)
if err != nil {
return err
}
if slave_receipt.DataStat != DATA_ALL_OK {
return fmt.Errorf(slave_receipt.Error)
}
return
}
// ExecTCP
func (d *DRule) commitTransaction(tranid string, conn_exec *nst.ConnExec) (err error) {
errarray := make([]string, 0)
// Masterslave
if d.dmode == DMODE_MASTER {
for _, onec := range d.slavecpool {
errone := d.<API key>(tranid, onec)
if errone != nil {
errarray = append(errarray, fmt.Sprint(errone))
}
}
}
tran, errone := d.trule.<API key>(tranid)
if errone != nil {
errarray = append(errarray, fmt.Sprint(errone))
} else {
errone = tran.Commit()
if errone != nil {
errarray = append(errarray, fmt.Sprint(errone))
}
}
if len(errarray) != 0 {
errstr := strings.Join(errarray, " | ")
err = fmt.Errorf(errstr)
} else {
d.serverDataReceipt(conn_exec, DATA_ALL_OK, nil, nil)
}
return
}
// slave
func (d *DRule) <API key>(tranid string, onec *slaveIn) (err error) {
cprocess := onec.tcpconn.OpenProgress()
defer cprocess.Close()
slave_receipt, err := SendPrefixStat(cprocess, onec.unid, d.selfname, tranid, true, "", OPERATE_TRAN_COMMIT)
if err != nil {
return err
}
if slave_receipt.DataStat != DATA_ALL_OK {
return fmt.Errorf(slave_receipt.Error)
}
return
} |
// This file is part of the go-ethereum library.
// The go-ethereum library is free software: you can redistribute it and/or modify
// (at your option) any later version.
// The go-ethereum library is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
package chunk
import (
"bytes"
"sync"
"testing"
"time"
)
var (
allStates = []State{StateSplit, StateStored, StateSeen, StateSent, StateSynced}
)
// <API key> tests if Inc increments the tag state value
func <API key>(t *testing.T) {
tg := &Tag{Total: 10}
tc := []struct {
state uint32
inc int
expcount int64
exptotal int64
}{
{state: StateSplit, inc: 10, expcount: 10, exptotal: 10},
{state: StateStored, inc: 9, expcount: 9, exptotal: 9},
{state: StateSeen, inc: 1, expcount: 1, exptotal: 10},
{state: StateSent, inc: 9, expcount: 9, exptotal: 9},
{state: StateSynced, inc: 9, expcount: 9, exptotal: 9},
}
for _, tc := range tc {
for i := 0; i < tc.inc; i++ {
tg.Inc(tc.state)
}
}
for _, tc := range tc {
if tg.Get(tc.state) != tc.expcount {
t.Fatalf("not incremented")
}
}
}
// TestTagStatus is a unit test to cover Tag.Status method functionality
func TestTagStatus(t *testing.T) {
tg := &Tag{Total: 10}
tg.Inc(StateSeen)
tg.Inc(StateSent)
tg.Inc(StateSynced)
for i := 0; i < 10; i++ {
tg.Inc(StateSplit)
tg.Inc(StateStored)
}
for _, v := range []struct {
state State
expVal int64
expTotal int64
}{
{state: StateStored, expVal: 10, expTotal: 10},
{state: StateSplit, expVal: 10, expTotal: 10},
{state: StateSeen, expVal: 1, expTotal: 10},
{state: StateSent, expVal: 1, expTotal: 9},
{state: StateSynced, expVal: 1, expTotal: 9},
} {
val, total, err := tg.Status(v.state)
if err != nil {
t.Fatal(err)
}
if val != v.expVal {
t.Fatalf("should be %d, got %d", v.expVal, val)
}
if total != v.expTotal {
t.Fatalf("expected Total to be %d, got %d", v.expTotal, total)
}
}
}
// tests ETA is precise
func TestTagETA(t *testing.T) {
now := time.Now()
maxDiff := 100000 // 100 microsecond
tg := &Tag{Total: 10, StartedAt: now}
time.Sleep(100 * time.Millisecond)
tg.Inc(StateSplit)
eta, err := tg.ETA(StateSplit)
if err != nil {
t.Fatal(err)
}
diff := time.Until(eta) - 9*time.Since(now)
if int(diff) > maxDiff {
t.Fatalf("ETA is not precise, got diff %v > .1ms", diff)
}
}
// <API key> tests Inc calls concurrently
func <API key>(t *testing.T) {
tg := &Tag{}
n := 1000
wg := sync.WaitGroup{}
wg.Add(5 * n)
for _, f := range allStates {
go func(f State) {
for j := 0; j < n; j++ {
go func() {
tg.Inc(f)
wg.Done()
}()
}
}(f)
}
wg.Wait()
for _, f := range allStates {
v := tg.Get(f)
if v != int64(n) {
t.Fatalf("expected state %v to be %v, got %v", f, n, v)
}
}
}
// <API key> tests Inc calls concurrently
func <API key>(t *testing.T) {
ts := NewTags()
n := 100
wg := sync.WaitGroup{}
wg.Add(10 * 5 * n)
for i := 0; i < 10; i++ {
s := string([]byte{uint8(i)})
tag, err := ts.Create(s, int64(n), false)
if err != nil {
t.Fatal(err)
}
for _, f := range allStates {
go func(tag *Tag, f State) {
for j := 0; j < n; j++ {
go func() {
tag.Inc(f)
wg.Done()
}()
}
}(tag, f)
}
}
wg.Wait()
i := 0
ts.Range(func(k, v interface{}) bool {
i++
uid := k.(uint32)
for _, f := range allStates {
tag, err := ts.Get(uid)
if err != nil {
t.Fatal(err)
}
stateVal := tag.Get(f)
if stateVal != int64(n) {
t.Fatalf("expected tag %v state %v to be %v, got %v", uid, f, n, v)
}
}
return true
})
if i != 10 {
t.Fatal("not enough tagz")
}
}
// <API key> tests that marshalling and unmarshalling is done correctly when the
// tag Address (byte slice) contains some arbitrary value
func <API key>(t *testing.T) {
tg := NewTag(111, "test/tag", 10, false)
tg.Address = []byte{0, 1, 2, 3, 4, 5, 6}
for _, f := range allStates {
tg.Inc(f)
}
b, err := tg.MarshalBinary()
if err != nil {
t.Fatal(err)
}
unmarshalledTag := &Tag{}
err = unmarshalledTag.UnmarshalBinary(b)
if err != nil {
t.Fatal(err)
}
if unmarshalledTag.Uid != tg.Uid {
t.Fatalf("tag uids not equal. want %d got %d", tg.Uid, unmarshalledTag.Uid)
}
if unmarshalledTag.Name != tg.Name {
t.Fatalf("tag names not equal. want %s got %s", tg.Name, unmarshalledTag.Name)
}
if unmarshalledTag.Anonymous != tg.Anonymous {
t.Fatalf("tag anon field not equal. want %t got %t", tg.Anonymous, unmarshalledTag.Anonymous)
}
for _, state := range allStates {
uv, tv := unmarshalledTag.Get(state), tg.Get(state)
if uv != tv {
t.Fatalf("state %d inconsistent. expected %d to equal %d", state, uv, tv)
}
}
if unmarshalledTag.TotalCounter() != tg.TotalCounter() {
t.Fatalf("tag names not equal. want %d got %d", tg.TotalCounter(), unmarshalledTag.TotalCounter())
}
if len(unmarshalledTag.Address) != len(tg.Address) {
t.Fatalf("tag addresses length mismatch, want %d, got %d", len(tg.Address), len(unmarshalledTag.Address))
}
if !bytes.Equal(unmarshalledTag.Address, tg.Address) {
t.Fatalf("expected tag address to be %v got %v", unmarshalledTag.Address, tg.Address)
}
}
// <API key> tests that marshalling and unmarshalling is done correctly
func <API key>(t *testing.T) {
tg := NewTag(111, "test/tag", 10, false)
for _, f := range allStates {
tg.Inc(f)
}
b, err := tg.MarshalBinary()
if err != nil {
t.Fatal(err)
}
unmarshalledTag := &Tag{}
err = unmarshalledTag.UnmarshalBinary(b)
if err != nil {
t.Fatal(err)
}
if unmarshalledTag.Uid != tg.Uid {
t.Fatalf("tag uids not equal. want %d got %d", tg.Uid, unmarshalledTag.Uid)
}
if unmarshalledTag.Name != tg.Name {
t.Fatalf("tag names not equal. want %s got %s", tg.Name, unmarshalledTag.Name)
}
for _, state := range allStates {
uv, tv := unmarshalledTag.Get(state), tg.Get(state)
if uv != tv {
t.Fatalf("state %d inconsistent. expected %d to equal %d", state, uv, tv)
}
}
if unmarshalledTag.TotalCounter() != tg.TotalCounter() {
t.Fatalf("tag names not equal. want %d got %d", tg.TotalCounter(), unmarshalledTag.TotalCounter())
}
if len(unmarshalledTag.Address) != len(tg.Address) {
t.Fatalf("expected tag addresses to be equal length")
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
// ReSharper disable once CheckNamespace
namespace Referenception.Website.SitecoreModules.Shell.Referenception
{
using System.Data;
using Core.Providers;
using Sitecore.Configuration;
using Sitecore.Data;
using Sitecore.Data.Items;
using Sitecore.Data.Managers;
using Sitecore.Globalization;
using Sitecore.Shell.Web.UI;
<summary>
Shows all references of all configured providers
</summary>
public partial class ShowReferences : SecurePage
{
<summary>
The item
</summary>
private Item item;
<summary>
Handles the Load event of the Page control.
</summary>
<param name="sender">The source of the event.</param>
<param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
<exception cref="System.Exception">No item found</exception>
protected void Page_Load(object sender, EventArgs e)
{
try
{
// get querystring params
var language = Language.Parse(Sitecore.Web.WebUtil.GetSafeQueryString("la"));
var database = Factory.GetDatabase(Sitecore.Web.WebUtil.GetSafeQueryString("db"));
var version = Version.Parse(Sitecore.Web.WebUtil.GetSafeQueryString("v"));
var id = HttpUtility.UrlDecode(Sitecore.Web.WebUtil.GetSafeQueryString("id"));
// get the item
this.item = ItemManager.GetItem(id, language, version, database);
if (this.item == null) throw new Exception("No item found");
this.litTitle.Text = string.Format("{0} {1}", ThemeManager.GetIconImage(this.item, 32, 32, string.Empty, string.Empty), this.item.DisplayName);
// load the providers
var providers = Core.Configuration.<API key>.GetProviders(this.item).ToList();
if (!providers.Any())
{
this.panNoProviders.Visible = true;
return;
}
this.plhData.Visible = true;
this.repProviders.ItemDataBound += this.<API key>;
this.repProviders.DataSource = providers;
this.repProviders.DataBind();
}
catch (Exception ex)
{
Sitecore.Diagnostics.Log.Error("Could not load item references", ex, this);
this.panError.Visible = true;
this.plhData.Visible = false;
}
}
<summary>
Returns the CSS class based on the index position
</summary>
<param name="index">The index.</param>
<returns>The CSS class</returns>
protected string FirstCssClass(int index)
{
return index == 0 ? "in" : string.Empty;
}
<summary>
Gets the tooltip identifier.
</summary>
<param name="item">The item.</param>
<returns>The unique tooltip identifier</returns>
protected string GetTooltipId(RepeaterItem item)
{
return string.Format("{0}_{1}", ((RepeaterItem)item.Parent.Parent.Parent).ItemIndex, item.ItemIndex);
}
<summary>
Determines whether the specified item has tooltip.
</summary>
<param name="repeaterItem">The repeater item.</param>
<returns>
The evaluation result
</returns>
protected bool HasTooltip(RepeaterItem repeaterItem)
{
return this.GetProvider(repeaterItem).GetTooltip((DataRow)repeaterItem.DataItem) != null;
}
<summary>
Determines whether the specified item has tooltip.
</summary>
<param name="repeaterItem">The repeater item.</param>
<returns>
The evaluation result
</returns>
protected bool HasItemLink(RepeaterItem repeaterItem)
{
return !this.GetProvider(repeaterItem).GetLinkItemId((DataRow)repeaterItem.DataItem).IsNull;
}
<summary>
Gets the link item identifier.
</summary>
<param name="repeaterItem">The repeater item.</param>
<returns>The link item id</returns>
protected string GetLinkItemId(RepeaterItem repeaterItem)
{
return this.GetProvider(repeaterItem).GetLinkItemId((DataRow)repeaterItem.DataItem).ToString();
}
<summary>
Gets the provider.
</summary>
<param name="item">The item.</param>
<returns>The provider</returns>
private <API key> GetProvider(RepeaterItem item)
{
return ((RepeaterItem)item.Parent.Parent.Parent).DataItem as <API key>;
}
<summary>
Handles the OnItemDataBound event of the Providers control.
</summary>
<param name="sender">The source of the event.</param>
<param name="e">The <see cref="<API key>"/> instance containing the event data.</param>
private void <API key>(object sender, <API key> e)
{
var repeaterItem = e.Item;
if (repeaterItem.ItemType == ListItemType.Item || repeaterItem.ItemType == ListItemType.AlternatingItem)
{
var provider = (<API key>)repeaterItem.DataItem;
var dataTable = provider.GetData(this.item);
var rowCount = dataTable.Rows.Count;
((Literal)repeaterItem.FindControl("litTitle")).Text = provider.Title;
((Literal)repeaterItem.FindControl("litRowCount")).Text = rowCount.ToString();
if (rowCount > 0)
{
var repColumns = (Repeater)repeaterItem.FindControl("repColumns");
repColumns.DataSource = dataTable.Columns.Cast<DataColumn>()
.Where(column => column.ColumnName != <API key>.ToolTipColumnName)
.Select(column => column.ColumnName);
repColumns.DataBind();
var rowsRepeater = (Repeater)repeaterItem.FindControl("repRows");
rowsRepeater.ItemDataBound += this.<API key>;
rowsRepeater.DataSource = dataTable.Rows;
rowsRepeater.DataBind();
return;
}
repeaterItem.FindControl("panBody").Visible = false;
repeaterItem.FindControl("panNoReferences").Visible = true;
}
}
<summary>
Handles the OnItemDataBound event of the Rows control.
</summary>
<param name="sender">The source of the event.</param>
<param name="e">The <see cref="<API key>"/> instance containing the event data.</param>
private void <API key>(object sender, <API key> e)
{
var repeaterItem = e.Item;
if (repeaterItem.ItemType == ListItemType.Item || repeaterItem.ItemType == ListItemType.AlternatingItem)
{
var dataRow = (DataRow)repeaterItem.DataItem;
var repColumns = (Repeater)repeaterItem.FindControl("repColumns");
repColumns.DataSource = dataRow.ItemArray.Where(column => column as IDictionary<string, string> == null);
repColumns.DataBind();
var tooltip = this.GetProvider(repeaterItem).GetTooltip(dataRow);
if (tooltip != null)
{
var repTooltip = (Repeater)repeaterItem.FindControl("repTooltip");
repTooltip.DataSource = tooltip;
repTooltip.DataBind();
}
}
}
}
} |
package cz.cvut.kbss.jopa.test.integration.jena;
import cz.cvut.kbss.jopa.test.environment.JenaDataAccessor;
import cz.cvut.kbss.jopa.test.environment.<API key>;
import cz.cvut.kbss.jopa.test.runner.<API key>;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class <API key> extends <API key> {
private static final Logger LOG = LoggerFactory.getLogger(<API key>.class);
public <API key>() {
super(LOG, new <API key>(), new JenaDataAccessor());
}
} |
<?php
namespace Aimeos\Controller;
/**
* Factory which can create all job controllers
*
* @package Controller
* @subpackage Jobs
*/
class Jobs
{
public static function create( \Aimeos\MShop\Context\Item\Iface $context, \Aimeos\Bootstrap $aimeos, string $path ) : \Aimeos\Controller\Jobs\Iface
{
if( empty( $path ) ) {
throw new \Aimeos\Controller\Jobs\Exception( sprintf( 'Controller path is empty' ) );
}
$parts = explode( '/', $path );
foreach( $parts as $key => $part )
{
if( ctype_alnum( $part ) === false ) {
throw new \Aimeos\Controller\Jobs\Exception( sprintf( 'Invalid controller "%1$s" in "%2$s"', $part, $path ) );
}
$parts[$key] = ucwords( $part );
}
$factory = '\Aimeos\Controller\Jobs\\' . join( '\\', $parts ) . '\Factory';
if( class_exists( $factory ) === false ) {
throw new \Aimeos\Controller\Jobs\Exception( sprintf( 'Class "%1$s" not found', $factory ) );
}
if( ( $controller = <API key>( [$factory, 'create'], [$context, $aimeos] ) ) === false ) {
throw new \Aimeos\Controller\Jobs\Exception( sprintf( 'Invalid factory "%1$s"', $factory ) );
}
return $controller;
}
/**
* Returns all available controller instances.
*
* @param \Aimeos\MShop\Context\Item\Iface $context Context object required by controllers
* @param \Aimeos\Bootstrap $aimeos \Aimeos\Bootstrap object
* @param array $cntlPaths Associative list of the base path as key and all relative job controller paths (core and extensions)
* @return \Aimeos\Controller\Jobs\Iface[] Associative list of controller names as values and class instance as values
*/
public static function get( \Aimeos\MShop\Context\Item\Iface $context, \Aimeos\Bootstrap $aimeos, array $cntlPaths ) : array
{
$cntlList = [];
$ds = DIRECTORY_SEPARATOR;
foreach( $cntlPaths as $path => $list )
{
foreach( $list as $relpath )
{
$path .= $ds . str_replace( '/', $ds, $relpath . '/Controller/Jobs' );
if( is_dir( $path ) )
{
$it = new \DirectoryIterator( $path );
$list = self::createControllers( $it, $context, $aimeos );
$cntlList = array_merge( $cntlList, $list );
}
}
}
ksort( $cntlList );
return $cntlList;
}
/**
* Instantiates all found factories and stores the controller instances in the class variable.
*
* @param \DirectoryIterator $dir Iterator over the (sub-)directory which might contain a factory
* @param \Aimeos\MShop\Context\Item\Iface $context Context object required by controllers
* @param \Aimeos\Bootstrap $aimeos \Aimeos\Bootstrap object
* @param string $prefix Part of the class name between "\Aimeos\Controller\Jobs" and "Factory"
* @return \Aimeos\Controller\Jobs\Iface[] Associative list if prefixes as values and job controller instances as values
* @throws \Aimeos\Controller\Jobs\Exception If factory name is invalid or if the controller couldn't be instantiated
*/
protected static function createControllers( \DirectoryIterator $dir, \Aimeos\MShop\Context\Item\Iface $context,
\Aimeos\Bootstrap $aimeos, string $prefix = '' ) : array
{
$list = [];
foreach( $dir as $entry )
{
if( $entry->getType() === 'dir' && $entry->isDot() === false )
{
$name = strtolower( $entry->getBaseName() );
$it = new \DirectoryIterator( $entry->getPathName() );
$pref = ( $prefix !== '' ? $prefix . '/' : '' ) . $name;
$subList = self::createControllers( $it, $context, $aimeos, $pref );
$list = array_merge( $list, $subList );
}
else if( $prefix !== '' && $entry->getType() === 'file'
&& $entry->getBaseName( '.php' ) === 'Factory' )
{
$list[$prefix] = self::create( $context, $aimeos, $prefix );
}
}
return $list;
}
} |
''' Helpers functions and classes for sequence manipulation.
'''
__author__ = "Juan Palacios <juan.palacios@nikhef.nl>"
__all__ = ('isiterable',
'flattenList')
def isIterable(obj) :
'''
Test if an object is iterable but not a string type.
'''
return hasattr(obj, "__iter__") and not isinstance(obj, basestring)
def flattenList(tree) :
"""flattenList(tree) -> flat list
Return a flat list containing all the non-iterable elements retrieved tree and tree's sub-trees.
"""
flatList = []
for member in tree :
if isIterable(member) :
flatList.extend(flattenList(member))
else :
flatList.append(member)
return flatList |
using System.IO;
using System.Management.Automation;
using Net.Sf.Dbdeploy;
namespace Dbdeploy.Powershell.Commands
{
using Net.Sf.Dbdeploy.Configuration;
[Cmdlet(VerbsData.Export, "DbUpdate")]
public class ExportDbUpdate : DbUpdateBase
{
[Parameter(Mandatory = true)]
public string OutputFile { get; set; }
[Parameter]
public string UndoOutputFile { get; set; }
protected override void ProcessRecord()
{
base.ProcessRecord();
if (string.IsNullOrEmpty(this.OutputFile))
{
this.WriteError(new ErrorRecord(new <API key>(
"Missing a file for output"),
"NoOutputFile",
ErrorCategory.MetadataError,
null));
return;
}
var config = new DbDeployConfig
{
Dbms = this.DatabaseType,
ConnectionString = this.ConnectionString,
ChangeLogTableName = this.TableName,
ScriptDirectory = new DirectoryInfo(this.deltasDirectory),
<API key> = this.<API key>,
ForceUpdate = this.ForceUpdate,
UseSqlCmd = this.UseSqlCmd,
OutputFile = new FileInfo(this.ToAbsolutePath(this.OutputFile))
};
if (!string.IsNullOrEmpty(this.UndoOutputFile))
{
config.OutputFile = new FileInfo(this.ToAbsolutePath(UndoOutputFile));
}
var deployer = new DbDeployer();
deployer.Execute(config, new LambdaTextWriter(WriteVerbose));
}
}
} |
#ifndef <API key>
#define <API key>
#include "swfresponse.h"
#include "<API key>.h"
namespace QtAws {
namespace SWF {
class <API key>;
class QTAWSSWF_EXPORT <API key> : public SwfResponse {
Q_OBJECT
public:
<API key>(const <API key> &request, QNetworkReply * const reply, QObject * const parent = 0);
virtual const <API key> * request() const Q_DECL_OVERRIDE;
protected slots:
virtual void parseSuccess(QIODevice &response) Q_DECL_OVERRIDE;
private:
Q_DECLARE_PRIVATE(<API key>)
Q_DISABLE_COPY(<API key>)
};
} // namespace SWF
} // namespace QtAws
#endif |
from django.db import models
from django.contrib import admin
# Create your models here.
class BlogPost(models.Model):
title = models.CharField(max_length=150)
body = models.TextField()
timestamp = models.DateTimeField()
class Meta:
ordering = ('-timestamp',)
class BlogPostAdmin(admin.ModelAdmin):
list_display = ("title", 'timestamp')
class Links(models.Model):
"""
A model for links to other sites
"""
label = models.CharField(max_length=100)
site_link = models.CharField(max_length=300)
slug = models.SlugField()
class Meta:
ordering = ['label']
verbose_name_plural = "links"
def __unicode__(self):
return self.label
admin.site.register(BlogPost, BlogPostAdmin)
admin.site.register(Links) |
package ch.loway.oss.ari4java.generated.ari_1_7_0.models;
// THIS CLASS WAS GENERATED AUTOMATICALLY
// PLEASE DO NOT EDIT
// Generated on: Sat Feb 04 15:23:09 CET 2017
import ch.loway.oss.ari4java.generated.*;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import java.util.Date;
import java.util.List;
import java.util.Map;
public class <API key> implements DialplanCEP, java.io.Serializable {
private static final long serialVersionUID = 1L;
/** Context in the dialplan */
private String context;
public String getContext() {
return context;
}
@JsonDeserialize( as=String.class )
public void setContext(String val ) {
context = val;
}
/** Extension in the dialplan */
private String exten;
public String getExten() {
return exten;
}
@JsonDeserialize( as=String.class )
public void setExten(String val ) {
exten = val;
}
/** Priority in the dialplan */
private long priority;
public long getPriority() {
return priority;
}
@JsonDeserialize( as=long.class )
public void setPriority(long val ) {
priority = val;
}
/** No missing signatures from interface */
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.