text stringlengths 2 1.04M | meta dict |
|---|---|
<?php
namespace Doctrine\ODM\PHPCR\Exception;
use Doctrine\ODM\PHPCR\PHPCRExceptionInterface;
/**
* InvalidArgumentException for the PHPCR-ODM.
*/
class BadMethodCallException extends \BadMethodCallException implements PHPCRExceptionInterface
{
}
| {
"content_hash": "6f44531e34cc0923812df158324dbc28",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 95,
"avg_line_length": 21,
"alnum_prop": 0.8174603174603174,
"repo_name": "doctrine/phpcr-odm",
"id": "3c537314d64b6925897da1b6f7a79b01310fa5a9",
"size": "252",
"binary": false,
"copies": "1",
"ref": "refs/heads/2.x",
"path": "lib/Doctrine/ODM/PHPCR/Exception/BadMethodCallException.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "1322171"
},
{
"name": "Shell",
"bytes": "1887"
}
],
"symlink_target": ""
} |
/* $NetBSD: svr4_ttold.h,v 1.3 1998/09/04 19:54:41 christos Exp $ */
/*-
* Copyright (c) 1994 The NetBSD Foundation, Inc.
* All rights reserved.
*
* This code is derived from software contributed to The NetBSD Foundation
* by Christos Zoulas.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the NetBSD
* Foundation, Inc. and its contributors.
* 4. Neither the name of The NetBSD Foundation nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef _SVR4_TTOLD_H_
#define _SVR4_TTOLD_H_
struct svr4_tchars {
char t_intrc;
char t_quitc;
char t_startc;
char t_stopc;
char t_eofc;
char t_brkc;
};
struct svr4_sgttyb {
u_char sg_ispeed;
u_char sg_ospeed;
u_char sg_erase;
u_char sg_kill;
int sg_flags;
};
struct svr4_ltchars {
char t_suspc;
char t_dsuspc;
char t_rprntc;
char t_flushc;
char t_werasc;
char t_lnextc;
};
#ifndef SVR4_tIOC
#define SVR4_tIOC ('t' << 8)
#endif
#define SVR4_TIOCGETD (SVR4_tIOC | 0)
#define SVR4_TIOCSETD (SVR4_tIOC | 1)
#define SVR4_TIOCHPCL (SVR4_tIOC | 2)
#define SVR4_TIOCGETP (SVR4_tIOC | 8)
#define SVR4_TIOCSETP (SVR4_tIOC | 9)
#define SVR4_TIOCSETN (SVR4_tIOC | 10)
#define SVR4_TIOCEXCL (SVR4_tIOC | 13)
#define SVR4_TIOCNXCL (SVR4_tIOC | 14)
#define SVR4_TIOCFLUSH (SVR4_tIOC | 16)
#define SVR4_TIOCSETC (SVR4_tIOC | 17)
#define SVR4_TIOCGETC (SVR4_tIOC | 18)
#define SVR4_TIOCGPGRP (SVR4_tIOC | 20)
#define SVR4_TIOCSPGRP (SVR4_tIOC | 21)
#define SVR4_TIOCGSID (SVR4_tIOC | 22)
#define SVR4_TIOCSTI (SVR4_tIOC | 23)
#define SVR4_TIOCSSID (SVR4_tIOC | 24)
#define SVR4_TIOCMSET (SVR4_tIOC | 26)
#define SVR4_TIOCMBIS (SVR4_tIOC | 27)
#define SVR4_TIOCMBIC (SVR4_tIOC | 28)
#define SVR4_TIOCMGET (SVR4_tIOC | 29)
#define SVR4_TIOCREMOTE (SVR4_tIOC | 30)
#define SVR4_TIOCSIGNAL (SVR4_tIOC | 31)
#define SVR4_TIOCSTART (SVR4_tIOC | 110)
#define SVR4_TIOCSTOP (SVR4_tIOC | 111)
#define SVR4_TIOCNOTTY (SVR4_tIOC | 113)
#define SVR4_TIOCOUTQ (SVR4_tIOC | 115)
#define SVR4_TIOCGLTC (SVR4_tIOC | 116)
#define SVR4_TIOCSLTC (SVR4_tIOC | 117)
#define SVR4_TIOCCDTR (SVR4_tIOC | 120)
#define SVR4_TIOCSDTR (SVR4_tIOC | 121)
#define SVR4_TIOCCBRK (SVR4_tIOC | 122)
#define SVR4_TIOCSBRK (SVR4_tIOC | 123)
#define SVR4_TIOCLGET (SVR4_tIOC | 124)
#define SVR4_TIOCLSET (SVR4_tIOC | 125)
#define SVR4_TIOCLBIC (SVR4_tIOC | 126)
#define SVR4_TIOCLBIS (SVR4_tIOC | 127)
#define SVR4_TIOCM_LE 0001
#define SVR4_TIOCM_DTR 0002
#define SVR4_TIOCM_RTS 0004
#define SVR4_TIOCM_ST 0010
#define SVR4_TIOCM_SR 0020
#define SVR4_TIOCM_CTS 0040
#define SVR4_TIOCM_CAR 0100
#define SVR4_TIOCM_CD SVR4_TIOCM_CAR
#define SVR4_TIOCM_RNG 0200
#define SVR4_TIOCM_RI SVR4_TIOCM_RNG
#define SVR4_TIOCM_DSR 0400
#define SVR4_OTTYDISC 0
#define SVR4_NETLDISC 1
#define SVR4_NTTYDISC 2
#define SVR4_TABLDISC 3
#define SVR4_NTABLDISC 4
#define SVR4_MOUSELDISC 5
#define SVR4_KBDLDISC 6
#endif /* !_SVR4_TTOLD_H_ */
| {
"content_hash": "cdb0b2073db4459ac3a5b367ce7d8618",
"timestamp": "",
"source": "github",
"line_count": 130,
"max_line_length": 78,
"avg_line_length": 34.146153846153844,
"alnum_prop": 0.7316963280018022,
"repo_name": "MarginC/kame",
"id": "27539bdc03de7683c1c4f5ac5427ff7aabc7b89e",
"size": "4439",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "netbsd/sys/compat/svr4/svr4_ttold.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Arc",
"bytes": "7491"
},
{
"name": "Assembly",
"bytes": "14375563"
},
{
"name": "Awk",
"bytes": "313712"
},
{
"name": "Batchfile",
"bytes": "6819"
},
{
"name": "C",
"bytes": "356715789"
},
{
"name": "C++",
"bytes": "4231647"
},
{
"name": "DIGITAL Command Language",
"bytes": "11155"
},
{
"name": "Emacs Lisp",
"bytes": "790"
},
{
"name": "Forth",
"bytes": "253695"
},
{
"name": "GAP",
"bytes": "9964"
},
{
"name": "Groff",
"bytes": "2220485"
},
{
"name": "Lex",
"bytes": "168376"
},
{
"name": "Logos",
"bytes": "570213"
},
{
"name": "Makefile",
"bytes": "1778847"
},
{
"name": "Mathematica",
"bytes": "16549"
},
{
"name": "Objective-C",
"bytes": "529629"
},
{
"name": "PHP",
"bytes": "11283"
},
{
"name": "Perl",
"bytes": "151251"
},
{
"name": "Perl6",
"bytes": "2572"
},
{
"name": "Ruby",
"bytes": "7283"
},
{
"name": "Scheme",
"bytes": "76872"
},
{
"name": "Shell",
"bytes": "583253"
},
{
"name": "Stata",
"bytes": "408"
},
{
"name": "Yacc",
"bytes": "606054"
}
],
"symlink_target": ""
} |
<?php
/**
* DO NOT EDIT THIS FILE!
*
* This file was automatically generated from external sources.
*
* Any manual change here will be lost the next time the SDK
* is updated. You've been warned!
*/
namespace DTS\eBaySDK\Test\PostOrder\Types;
use DTS\eBaySDK\PostOrder\Types\CaseDetails;
class CaseDetailsTest extends \PHPUnit_Framework_TestCase
{
private $obj;
protected function setUp()
{
$this->obj = new CaseDetails();
}
public function testCanBeCreated()
{
$this->assertInstanceOf('\DTS\eBaySDK\PostOrder\Types\CaseDetails', $this->obj);
}
public function testExtendsBaseType()
{
$this->assertInstanceOf('\DTS\eBaySDK\Types\BaseType', $this->obj);
}
}
| {
"content_hash": "9eee1f85a4e0f37a63c00d51f10e25b5",
"timestamp": "",
"source": "github",
"line_count": 33,
"max_line_length": 88,
"avg_line_length": 22.242424242424242,
"alnum_prop": 0.6757493188010899,
"repo_name": "davidtsadler/ebay-sdk-php",
"id": "4cce760843b8b9ec8414a3007e789be328ad1805",
"size": "734",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/PostOrder/Types/CaseDetailsTest.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Makefile",
"bytes": "10944"
},
{
"name": "PHP",
"bytes": "9958599"
}
],
"symlink_target": ""
} |
namespace memory_pressure {
TEST(MultiSourceMemoryPressureMonitorTest, RunDispatchCallback) {
base::test::SingleThreadTaskEnvironment task_environment(
base::test::TaskEnvironment::MainThreadType::IO);
MultiSourceMemoryPressureMonitor monitor;
monitor.Start();
auto* aggregator = monitor.aggregator_for_testing();
bool callback_called = false;
monitor.SetDispatchCallback(base::BindLambdaForTesting(
[&](base::MemoryPressureListener::MemoryPressureLevel) {
callback_called = true;
}));
aggregator->OnVoteForTesting(
absl::nullopt, base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_NONE);
aggregator->NotifyListenersForTesting();
EXPECT_TRUE(callback_called);
// Clear vote so aggregator's destructor doesn't think there are loose voters.
aggregator->OnVoteForTesting(
base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_NONE, absl::nullopt);
}
} // namespace memory_pressure
| {
"content_hash": "11062e4c2b5817c21f7271d1c1f65b20",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 80,
"avg_line_length": 36.26923076923077,
"alnum_prop": 0.7582184517497349,
"repo_name": "chromium/chromium",
"id": "422e02bcb5e6f6519935f19dcec2a6a5c3fb6ba0",
"size": "1413",
"binary": false,
"copies": "6",
"ref": "refs/heads/main",
"path": "components/memory_pressure/multi_source_memory_pressure_monitor_unittest.cc",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
import faker from 'faker'
import {Response} from 'src/server/services/dataService'
const now = new Date()
export default function define(factory) {
factory.define('response', Response, {
id: cb => cb(null, faker.random.uuid()),
value: 5,
questionId: factory.assoc('question', 'id'),
respondentId: factory.assoc('member', 'id'),
surveyId: factory.assoc('survey', 'id'),
subjectId: factory.assoc('member', 'id'),
createdAt: cb => cb(null, now),
updatedAt: cb => cb(null, now),
})
}
| {
"content_hash": "7bf4fa487d67c6ac4f83a377ebd9a898",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 56,
"avg_line_length": 28.833333333333332,
"alnum_prop": 0.6473988439306358,
"repo_name": "ian-deans/echo",
"id": "b2a656308c438deabfb30d56d8b90bd4d3b4ad6b",
"size": "519",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "src/test/factories/response.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "14409"
},
{
"name": "JavaScript",
"bytes": "915947"
}
],
"symlink_target": ""
} |
/* Includes ------------------------------------------------------------------*/
#include "stm32f4xx_hal.h"
/** @addtogroup STM32F4xx_HAL_Driver
* @{
*/
/** @defgroup CRYP CRYP
* @brief CRYP HAL module driver.
* @{
*/
#ifdef HAL_CRYP_MODULE_ENABLED
#if defined(STM32F415xx) || defined(STM32F417xx) || defined(STM32F437xx) || defined(STM32F439xx) || defined(STM32F479xx)
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/** @addtogroup CRYP_Private_define
* @{
*/
#define CRYP_TIMEOUT_VALUE 1
/**
* @}
*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/** @addtogroup CRYP_Private_Functions_prototypes
* @{
*/
static void CRYP_SetInitVector(CRYP_HandleTypeDef *hcryp, uint8_t *InitVector, uint32_t IVSize);
static void CRYP_SetKey(CRYP_HandleTypeDef *hcryp, uint8_t *Key, uint32_t KeySize);
static HAL_StatusTypeDef CRYP_ProcessData(CRYP_HandleTypeDef *hcryp, uint8_t* Input, uint16_t Ilength, uint8_t* Output, uint32_t Timeout);
static HAL_StatusTypeDef CRYP_ProcessData2Words(CRYP_HandleTypeDef *hcryp, uint8_t* Input, uint16_t Ilength, uint8_t* Output, uint32_t Timeout);
static void CRYP_DMAInCplt(DMA_HandleTypeDef *hdma);
static void CRYP_DMAOutCplt(DMA_HandleTypeDef *hdma);
static void CRYP_DMAError(DMA_HandleTypeDef *hdma);
static void CRYP_SetDMAConfig(CRYP_HandleTypeDef *hcryp, uint32_t inputaddr, uint16_t Size, uint32_t outputaddr);
static void CRYP_SetTDESECBMode(CRYP_HandleTypeDef *hcryp, uint32_t Direction);
static void CRYP_SetTDESCBCMode(CRYP_HandleTypeDef *hcryp, uint32_t Direction);
static void CRYP_SetDESECBMode(CRYP_HandleTypeDef *hcryp, uint32_t Direction);
static void CRYP_SetDESCBCMode(CRYP_HandleTypeDef *hcryp, uint32_t Direction);
/**
* @}
*/
/* Private functions ---------------------------------------------------------*/
/** @addtogroup CRYP_Private_Functions
* @{
*/
/**
* @brief DMA CRYP Input Data process complete callback.
* @param hdma: DMA handle
* @retval None
*/
static void CRYP_DMAInCplt(DMA_HandleTypeDef *hdma)
{
CRYP_HandleTypeDef* hcryp = (CRYP_HandleTypeDef*)((DMA_HandleTypeDef*)hdma)->Parent;
/* Disable the DMA transfer for input FIFO request by resetting the DIEN bit
in the DMACR register */
hcryp->Instance->DMACR &= (uint32_t)(~CRYP_DMACR_DIEN);
/* Call input data transfer complete callback */
HAL_CRYP_InCpltCallback(hcryp);
}
/**
* @brief DMA CRYP Output Data process complete callback.
* @param hdma: DMA handle
* @retval None
*/
static void CRYP_DMAOutCplt(DMA_HandleTypeDef *hdma)
{
CRYP_HandleTypeDef* hcryp = (CRYP_HandleTypeDef*)((DMA_HandleTypeDef*)hdma)->Parent;
/* Disable the DMA transfer for output FIFO request by resetting the DOEN bit
in the DMACR register */
hcryp->Instance->DMACR &= (uint32_t)(~CRYP_DMACR_DOEN);
/* Disable CRYP */
__HAL_CRYP_DISABLE(hcryp);
/* Change the CRYP state to ready */
hcryp->State = HAL_CRYP_STATE_READY;
/* Call output data transfer complete callback */
HAL_CRYP_OutCpltCallback(hcryp);
}
/**
* @brief DMA CRYP communication error callback.
* @param hdma: DMA handle
* @retval None
*/
static void CRYP_DMAError(DMA_HandleTypeDef *hdma)
{
CRYP_HandleTypeDef* hcryp = (CRYP_HandleTypeDef*)((DMA_HandleTypeDef*)hdma)->Parent;
hcryp->State= HAL_CRYP_STATE_READY;
HAL_CRYP_ErrorCallback(hcryp);
}
/**
* @brief Writes the Key in Key registers.
* @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module
* @param Key: Pointer to Key buffer
* @param KeySize: Size of Key
* @retval None
*/
static void CRYP_SetKey(CRYP_HandleTypeDef *hcryp, uint8_t *Key, uint32_t KeySize)
{
uint32_t keyaddr = (uint32_t)Key;
switch(KeySize)
{
case CRYP_KEYSIZE_256B:
/* Key Initialisation */
hcryp->Instance->K0LR = __REV(*(uint32_t*)(keyaddr));
keyaddr+=4;
hcryp->Instance->K0RR = __REV(*(uint32_t*)(keyaddr));
keyaddr+=4;
hcryp->Instance->K1LR = __REV(*(uint32_t*)(keyaddr));
keyaddr+=4;
hcryp->Instance->K1RR = __REV(*(uint32_t*)(keyaddr));
keyaddr+=4;
hcryp->Instance->K2LR = __REV(*(uint32_t*)(keyaddr));
keyaddr+=4;
hcryp->Instance->K2RR = __REV(*(uint32_t*)(keyaddr));
keyaddr+=4;
hcryp->Instance->K3LR = __REV(*(uint32_t*)(keyaddr));
keyaddr+=4;
hcryp->Instance->K3RR = __REV(*(uint32_t*)(keyaddr));
break;
case CRYP_KEYSIZE_192B:
hcryp->Instance->K1LR = __REV(*(uint32_t*)(keyaddr));
keyaddr+=4;
hcryp->Instance->K1RR = __REV(*(uint32_t*)(keyaddr));
keyaddr+=4;
hcryp->Instance->K2LR = __REV(*(uint32_t*)(keyaddr));
keyaddr+=4;
hcryp->Instance->K2RR = __REV(*(uint32_t*)(keyaddr));
keyaddr+=4;
hcryp->Instance->K3LR = __REV(*(uint32_t*)(keyaddr));
keyaddr+=4;
hcryp->Instance->K3RR = __REV(*(uint32_t*)(keyaddr));
break;
case CRYP_KEYSIZE_128B:
hcryp->Instance->K2LR = __REV(*(uint32_t*)(keyaddr));
keyaddr+=4;
hcryp->Instance->K2RR = __REV(*(uint32_t*)(keyaddr));
keyaddr+=4;
hcryp->Instance->K3LR = __REV(*(uint32_t*)(keyaddr));
keyaddr+=4;
hcryp->Instance->K3RR = __REV(*(uint32_t*)(keyaddr));
break;
default:
break;
}
}
/**
* @brief Writes the InitVector/InitCounter in IV registers.
* @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module
* @param InitVector: Pointer to InitVector/InitCounter buffer
* @param IVSize: Size of the InitVector/InitCounter
* @retval None
*/
static void CRYP_SetInitVector(CRYP_HandleTypeDef *hcryp, uint8_t *InitVector, uint32_t IVSize)
{
uint32_t ivaddr = (uint32_t)InitVector;
switch(IVSize)
{
case CRYP_KEYSIZE_128B:
hcryp->Instance->IV0LR = __REV(*(uint32_t*)(ivaddr));
ivaddr+=4;
hcryp->Instance->IV0RR = __REV(*(uint32_t*)(ivaddr));
ivaddr+=4;
hcryp->Instance->IV1LR = __REV(*(uint32_t*)(ivaddr));
ivaddr+=4;
hcryp->Instance->IV1RR = __REV(*(uint32_t*)(ivaddr));
break;
/* Whatever key size 192 or 256, Init vector is written in IV0LR and IV0RR */
case CRYP_KEYSIZE_192B:
hcryp->Instance->IV0LR = __REV(*(uint32_t*)(ivaddr));
ivaddr+=4;
hcryp->Instance->IV0RR = __REV(*(uint32_t*)(ivaddr));
break;
case CRYP_KEYSIZE_256B:
hcryp->Instance->IV0LR = __REV(*(uint32_t*)(ivaddr));
ivaddr+=4;
hcryp->Instance->IV0RR = __REV(*(uint32_t*)(ivaddr));
break;
default:
break;
}
}
/**
* @brief Process Data: Writes Input data in polling mode and read the output data
* @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module
* @param Input: Pointer to the Input buffer
* @param Ilength: Length of the Input buffer, must be a multiple of 16.
* @param Output: Pointer to the returned buffer
* @param Timeout: Timeout value
* * @retval None
*/
static HAL_StatusTypeDef CRYP_ProcessData(CRYP_HandleTypeDef *hcryp, uint8_t* Input, uint16_t Ilength, uint8_t* Output, uint32_t Timeout)
{
uint32_t tickstart = 0;
uint32_t i = 0;
uint32_t inputaddr = (uint32_t)Input;
uint32_t outputaddr = (uint32_t)Output;
for(i=0; (i < Ilength); i+=16)
{
/* Write the Input block in the IN FIFO */
hcryp->Instance->DR = *(uint32_t*)(inputaddr);
inputaddr+=4;
hcryp->Instance->DR = *(uint32_t*)(inputaddr);
inputaddr+=4;
hcryp->Instance->DR = *(uint32_t*)(inputaddr);
inputaddr+=4;
hcryp->Instance->DR = *(uint32_t*)(inputaddr);
inputaddr+=4;
/* Get tick */
tickstart = HAL_GetTick();
while(HAL_IS_BIT_CLR(hcryp->Instance->SR, CRYP_FLAG_OFNE))
{
/* Check for the Timeout */
if(Timeout != HAL_MAX_DELAY)
{
if((Timeout == 0)||((HAL_GetTick() - tickstart ) > Timeout))
{
/* Change state */
hcryp->State = HAL_CRYP_STATE_TIMEOUT;
/* Process Unlocked */
__HAL_UNLOCK(hcryp);
return HAL_TIMEOUT;
}
}
}
/* Read the Output block from the Output FIFO */
*(uint32_t*)(outputaddr) = hcryp->Instance->DOUT;
outputaddr+=4;
*(uint32_t*)(outputaddr) = hcryp->Instance->DOUT;
outputaddr+=4;
*(uint32_t*)(outputaddr) = hcryp->Instance->DOUT;
outputaddr+=4;
*(uint32_t*)(outputaddr) = hcryp->Instance->DOUT;
outputaddr+=4;
}
/* Return function status */
return HAL_OK;
}
/**
* @brief Process Data: Write Input data in polling mode.
* @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module
* @param Input: Pointer to the Input buffer
* @param Ilength: Length of the Input buffer, must be a multiple of 8
* @param Output: Pointer to the returned buffer
* @param Timeout: Specify Timeout value
* @retval None
*/
static HAL_StatusTypeDef CRYP_ProcessData2Words(CRYP_HandleTypeDef *hcryp, uint8_t* Input, uint16_t Ilength, uint8_t* Output, uint32_t Timeout)
{
uint32_t tickstart = 0;
uint32_t i = 0;
uint32_t inputaddr = (uint32_t)Input;
uint32_t outputaddr = (uint32_t)Output;
for(i=0; (i < Ilength); i+=8)
{
/* Write the Input block in the IN FIFO */
hcryp->Instance->DR = *(uint32_t*)(inputaddr);
inputaddr+=4;
hcryp->Instance->DR = *(uint32_t*)(inputaddr);
inputaddr+=4;
/* Get tick */
tickstart = HAL_GetTick();
while(HAL_IS_BIT_CLR(hcryp->Instance->SR, CRYP_FLAG_OFNE))
{
/* Check for the Timeout */
if(Timeout != HAL_MAX_DELAY)
{
if((Timeout == 0)||((HAL_GetTick() - tickstart ) > Timeout))
{
/* Change state */
hcryp->State = HAL_CRYP_STATE_TIMEOUT;
/* Process Unlocked */
__HAL_UNLOCK(hcryp);
return HAL_TIMEOUT;
}
}
}
/* Read the Output block from the Output FIFO */
*(uint32_t*)(outputaddr) = hcryp->Instance->DOUT;
outputaddr+=4;
*(uint32_t*)(outputaddr) = hcryp->Instance->DOUT;
outputaddr+=4;
}
/* Return function status */
return HAL_OK;
}
/**
* @brief Set the DMA configuration and start the DMA transfer
* @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module
* @param inputaddr: address of the Input buffer
* @param Size: Size of the Input buffer, must be a multiple of 16.
* @param outputaddr: address of the Output buffer
* @retval None
*/
static void CRYP_SetDMAConfig(CRYP_HandleTypeDef *hcryp, uint32_t inputaddr, uint16_t Size, uint32_t outputaddr)
{
/* Set the CRYP DMA transfer complete callback */
hcryp->hdmain->XferCpltCallback = CRYP_DMAInCplt;
/* Set the DMA error callback */
hcryp->hdmain->XferErrorCallback = CRYP_DMAError;
/* Set the CRYP DMA transfer complete callback */
hcryp->hdmaout->XferCpltCallback = CRYP_DMAOutCplt;
/* Set the DMA error callback */
hcryp->hdmaout->XferErrorCallback = CRYP_DMAError;
/* Enable CRYP */
__HAL_CRYP_ENABLE(hcryp);
/* Enable the DMA In DMA Stream */
HAL_DMA_Start_IT(hcryp->hdmain, inputaddr, (uint32_t)&hcryp->Instance->DR, Size/4);
/* Enable In DMA request */
hcryp->Instance->DMACR = (CRYP_DMACR_DIEN);
/* Enable the DMA Out DMA Stream */
HAL_DMA_Start_IT(hcryp->hdmaout, (uint32_t)&hcryp->Instance->DOUT, outputaddr, Size/4);
/* Enable Out DMA request */
hcryp->Instance->DMACR |= CRYP_DMACR_DOEN;
}
/**
* @brief Sets the CRYP peripheral in DES ECB mode.
* @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module
* @param Direction: Encryption or decryption
* @retval None
*/
static void CRYP_SetDESECBMode(CRYP_HandleTypeDef *hcryp, uint32_t Direction)
{
/* Check if initialization phase has already been performed */
if(hcryp->Phase == HAL_CRYP_PHASE_READY)
{
/* Set the CRYP peripheral in AES ECB mode */
__HAL_CRYP_SET_MODE(hcryp, CRYP_CR_ALGOMODE_DES_ECB | Direction);
/* Set the key */
hcryp->Instance->K1LR = __REV(*(uint32_t*)(hcryp->Init.pKey));
hcryp->Instance->K1RR = __REV(*(uint32_t*)(hcryp->Init.pKey+4));
/* Flush FIFO */
__HAL_CRYP_FIFO_FLUSH(hcryp);
/* Set the phase */
hcryp->Phase = HAL_CRYP_PHASE_PROCESS;
}
}
/**
* @brief Sets the CRYP peripheral in DES CBC mode.
* @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module
* @param Direction: Encryption or decryption
* @retval None
*/
static void CRYP_SetDESCBCMode(CRYP_HandleTypeDef *hcryp, uint32_t Direction)
{
/* Check if initialization phase has already been performed */
if(hcryp->Phase == HAL_CRYP_PHASE_READY)
{
/* Set the CRYP peripheral in AES ECB mode */
__HAL_CRYP_SET_MODE(hcryp, CRYP_CR_ALGOMODE_DES_CBC | Direction);
/* Set the key */
hcryp->Instance->K1LR = __REV(*(uint32_t*)(hcryp->Init.pKey));
hcryp->Instance->K1RR = __REV(*(uint32_t*)(hcryp->Init.pKey+4));
/* Set the Initialization Vector */
CRYP_SetInitVector(hcryp, hcryp->Init.pInitVect, CRYP_KEYSIZE_256B);
/* Flush FIFO */
__HAL_CRYP_FIFO_FLUSH(hcryp);
/* Set the phase */
hcryp->Phase = HAL_CRYP_PHASE_PROCESS;
}
}
/**
* @brief Sets the CRYP peripheral in TDES ECB mode.
* @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module
* @param Direction: Encryption or decryption
* @retval None
*/
static void CRYP_SetTDESECBMode(CRYP_HandleTypeDef *hcryp, uint32_t Direction)
{
/* Check if initialization phase has already been performed */
if(hcryp->Phase == HAL_CRYP_PHASE_READY)
{
/* Set the CRYP peripheral in AES ECB mode */
__HAL_CRYP_SET_MODE(hcryp, CRYP_CR_ALGOMODE_TDES_ECB | Direction);
/* Set the key */
CRYP_SetKey(hcryp, hcryp->Init.pKey, CRYP_KEYSIZE_192B);
/* Flush FIFO */
__HAL_CRYP_FIFO_FLUSH(hcryp);
/* Set the phase */
hcryp->Phase = HAL_CRYP_PHASE_PROCESS;
}
}
/**
* @brief Sets the CRYP peripheral in TDES CBC mode
* @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module
* @param Direction: Encryption or decryption
* @retval None
*/
static void CRYP_SetTDESCBCMode(CRYP_HandleTypeDef *hcryp, uint32_t Direction)
{
/* Check if initialization phase has already been performed */
if(hcryp->Phase == HAL_CRYP_PHASE_READY)
{
/* Set the CRYP peripheral in AES CBC mode */
__HAL_CRYP_SET_MODE(hcryp, CRYP_CR_ALGOMODE_TDES_CBC | Direction);
/* Set the key */
CRYP_SetKey(hcryp, hcryp->Init.pKey, CRYP_KEYSIZE_192B);
/* Set the Initialization Vector */
CRYP_SetInitVector(hcryp, hcryp->Init.pInitVect, CRYP_KEYSIZE_256B);
/* Flush FIFO */
__HAL_CRYP_FIFO_FLUSH(hcryp);
/* Set the phase */
hcryp->Phase = HAL_CRYP_PHASE_PROCESS;
}
}
/**
* @}
*/
/* Exported functions --------------------------------------------------------*/
/** @addtogroup CRYP_Exported_Functions
* @{
*/
/** @defgroup CRYP_Exported_Functions_Group1 Initialization and de-initialization functions
* @brief Initialization and Configuration functions.
*
@verbatim
==============================================================================
##### Initialization and de-initialization functions #####
==============================================================================
[..] This section provides functions allowing to:
(+) Initialize the CRYP according to the specified parameters
in the CRYP_InitTypeDef and creates the associated handle
(+) DeInitialize the CRYP peripheral
(+) Initialize the CRYP MSP
(+) DeInitialize CRYP MSP
@endverbatim
* @{
*/
/**
* @brief Initializes the CRYP according to the specified
* parameters in the CRYP_InitTypeDef and creates the associated handle.
* @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module
* @retval HAL status
*/
HAL_StatusTypeDef HAL_CRYP_Init(CRYP_HandleTypeDef *hcryp)
{
/* Check the CRYP handle allocation */
if(hcryp == NULL)
{
return HAL_ERROR;
}
/* Check the parameters */
assert_param(IS_CRYP_KEYSIZE(hcryp->Init.KeySize));
assert_param(IS_CRYP_DATATYPE(hcryp->Init.DataType));
if(hcryp->State == HAL_CRYP_STATE_RESET)
{
/* Allocate lock resource and initialize it */
hcryp->Lock = HAL_UNLOCKED;
/* Init the low level hardware */
HAL_CRYP_MspInit(hcryp);
}
/* Change the CRYP state */
hcryp->State = HAL_CRYP_STATE_BUSY;
/* Set the key size and data type*/
CRYP->CR = (uint32_t) (hcryp->Init.KeySize | hcryp->Init.DataType);
/* Reset CrypInCount and CrypOutCount */
hcryp->CrypInCount = 0;
hcryp->CrypOutCount = 0;
/* Change the CRYP state */
hcryp->State = HAL_CRYP_STATE_READY;
/* Set the default CRYP phase */
hcryp->Phase = HAL_CRYP_PHASE_READY;
/* Return function status */
return HAL_OK;
}
/**
* @brief DeInitializes the CRYP peripheral.
* @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module
* @retval HAL status
*/
HAL_StatusTypeDef HAL_CRYP_DeInit(CRYP_HandleTypeDef *hcryp)
{
/* Check the CRYP handle allocation */
if(hcryp == NULL)
{
return HAL_ERROR;
}
/* Change the CRYP state */
hcryp->State = HAL_CRYP_STATE_BUSY;
/* Set the default CRYP phase */
hcryp->Phase = HAL_CRYP_PHASE_READY;
/* Reset CrypInCount and CrypOutCount */
hcryp->CrypInCount = 0;
hcryp->CrypOutCount = 0;
/* Disable the CRYP Peripheral Clock */
__HAL_CRYP_DISABLE(hcryp);
/* DeInit the low level hardware: CLOCK, NVIC.*/
HAL_CRYP_MspDeInit(hcryp);
/* Change the CRYP state */
hcryp->State = HAL_CRYP_STATE_RESET;
/* Release Lock */
__HAL_UNLOCK(hcryp);
/* Return function status */
return HAL_OK;
}
/**
* @brief Initializes the CRYP MSP.
* @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module
* @retval None
*/
__weak void HAL_CRYP_MspInit(CRYP_HandleTypeDef *hcryp)
{
/* NOTE : This function Should not be modified, when the callback is needed,
the HAL_CRYP_MspInit could be implemented in the user file
*/
}
/**
* @brief DeInitializes CRYP MSP.
* @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module
* @retval None
*/
__weak void HAL_CRYP_MspDeInit(CRYP_HandleTypeDef *hcryp)
{
/* NOTE : This function Should not be modified, when the callback is needed,
the HAL_CRYP_MspDeInit could be implemented in the user file
*/
}
/**
* @}
*/
/** @defgroup CRYP_Exported_Functions_Group2 AES processing functions
* @brief processing functions.
*
@verbatim
==============================================================================
##### AES processing functions #####
==============================================================================
[..] This section provides functions allowing to:
(+) Encrypt plaintext using AES-128/192/256 using chaining modes
(+) Decrypt cyphertext using AES-128/192/256 using chaining modes
[..] Three processing functions are available:
(+) Polling mode
(+) Interrupt mode
(+) DMA mode
@endverbatim
* @{
*/
/**
* @brief Initializes the CRYP peripheral in AES ECB encryption mode
* then encrypt pPlainData. The cypher data are available in pCypherData
* @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module
* @param pPlainData: Pointer to the plaintext buffer
* @param Size: Length of the plaintext buffer, must be a multiple of 16.
* @param pCypherData: Pointer to the cyphertext buffer
* @param Timeout: Specify Timeout value
* @retval HAL status
*/
HAL_StatusTypeDef HAL_CRYP_AESECB_Encrypt(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData, uint32_t Timeout)
{
/* Process Locked */
__HAL_LOCK(hcryp);
/* Change the CRYP state */
hcryp->State = HAL_CRYP_STATE_BUSY;
/* Check if initialization phase has already been performed */
if(hcryp->Phase == HAL_CRYP_PHASE_READY)
{
/* Set the key */
CRYP_SetKey(hcryp, hcryp->Init.pKey, hcryp->Init.KeySize);
/* Set the CRYP peripheral in AES ECB mode */
__HAL_CRYP_SET_MODE(hcryp, CRYP_CR_ALGOMODE_AES_ECB);
/* Flush FIFO */
__HAL_CRYP_FIFO_FLUSH(hcryp);
/* Enable CRYP */
__HAL_CRYP_ENABLE(hcryp);
/* Set the phase */
hcryp->Phase = HAL_CRYP_PHASE_PROCESS;
}
/* Write Plain Data and Get Cypher Data */
if(CRYP_ProcessData(hcryp, pPlainData, Size, pCypherData, Timeout) != HAL_OK)
{
return HAL_TIMEOUT;
}
/* Change the CRYP state */
hcryp->State = HAL_CRYP_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hcryp);
/* Return function status */
return HAL_OK;
}
/**
* @brief Initializes the CRYP peripheral in AES CBC encryption mode
* then encrypt pPlainData. The cypher data are available in pCypherData
* @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module
* @param pPlainData: Pointer to the plaintext buffer
* @param Size: Length of the plaintext buffer, must be a multiple of 16.
* @param pCypherData: Pointer to the cyphertext buffer
* @param Timeout: Specify Timeout value
* @retval HAL status
*/
HAL_StatusTypeDef HAL_CRYP_AESCBC_Encrypt(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData, uint32_t Timeout)
{
/* Process Locked */
__HAL_LOCK(hcryp);
/* Change the CRYP state */
hcryp->State = HAL_CRYP_STATE_BUSY;
/* Check if initialization phase has already been performed */
if(hcryp->Phase == HAL_CRYP_PHASE_READY)
{
/* Set the key */
CRYP_SetKey(hcryp, hcryp->Init.pKey, hcryp->Init.KeySize);
/* Set the CRYP peripheral in AES ECB mode */
__HAL_CRYP_SET_MODE(hcryp, CRYP_CR_ALGOMODE_AES_CBC);
/* Set the Initialization Vector */
CRYP_SetInitVector(hcryp, hcryp->Init.pInitVect, CRYP_KEYSIZE_128B);
/* Flush FIFO */
__HAL_CRYP_FIFO_FLUSH(hcryp);
/* Enable CRYP */
__HAL_CRYP_ENABLE(hcryp);
/* Set the phase */
hcryp->Phase = HAL_CRYP_PHASE_PROCESS;
}
/* Write Plain Data and Get Cypher Data */
if(CRYP_ProcessData(hcryp,pPlainData, Size, pCypherData, Timeout) != HAL_OK)
{
return HAL_TIMEOUT;
}
/* Change the CRYP state */
hcryp->State = HAL_CRYP_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hcryp);
/* Return function status */
return HAL_OK;
}
/**
* @brief Initializes the CRYP peripheral in AES CTR encryption mode
* then encrypt pPlainData. The cypher data are available in pCypherData
* @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module
* @param pPlainData: Pointer to the plaintext buffer
* @param Size: Length of the plaintext buffer, must be a multiple of 16.
* @param pCypherData: Pointer to the cyphertext buffer
* @param Timeout: Specify Timeout value
* @retval HAL status
*/
HAL_StatusTypeDef HAL_CRYP_AESCTR_Encrypt(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData, uint32_t Timeout)
{
/* Process Locked */
__HAL_LOCK(hcryp);
/* Change the CRYP state */
hcryp->State = HAL_CRYP_STATE_BUSY;
/* Check if initialization phase has already been performed */
if(hcryp->Phase == HAL_CRYP_PHASE_READY)
{
/* Set the key */
CRYP_SetKey(hcryp, hcryp->Init.pKey, hcryp->Init.KeySize);
/* Set the CRYP peripheral in AES ECB mode */
__HAL_CRYP_SET_MODE(hcryp, CRYP_CR_ALGOMODE_AES_CTR);
/* Set the Initialization Vector */
CRYP_SetInitVector(hcryp, hcryp->Init.pInitVect, CRYP_KEYSIZE_128B);
/* Flush FIFO */
__HAL_CRYP_FIFO_FLUSH(hcryp);
/* Enable CRYP */
__HAL_CRYP_ENABLE(hcryp);
/* Set the phase */
hcryp->Phase = HAL_CRYP_PHASE_PROCESS;
}
/* Write Plain Data and Get Cypher Data */
if(CRYP_ProcessData(hcryp, pPlainData, Size, pCypherData, Timeout) != HAL_OK)
{
return HAL_TIMEOUT;
}
/* Change the CRYP state */
hcryp->State = HAL_CRYP_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hcryp);
/* Return function status */
return HAL_OK;
}
/**
* @brief Initializes the CRYP peripheral in AES ECB decryption mode
* then decrypted pCypherData. The cypher data are available in pPlainData
* @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module
* @param pCypherData: Pointer to the cyphertext buffer
* @param Size: Length of the plaintext buffer, must be a multiple of 16.
* @param pPlainData: Pointer to the plaintext buffer
* @param Timeout: Specify Timeout value
* @retval HAL status
*/
HAL_StatusTypeDef HAL_CRYP_AESECB_Decrypt(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData, uint32_t Timeout)
{
uint32_t tickstart = 0;
/* Process Locked */
__HAL_LOCK(hcryp);
/* Change the CRYP state */
hcryp->State = HAL_CRYP_STATE_BUSY;
/* Check if initialization phase has already been performed */
if(hcryp->Phase == HAL_CRYP_PHASE_READY)
{
/* Set the key */
CRYP_SetKey(hcryp, hcryp->Init.pKey, hcryp->Init.KeySize);
/* Set the CRYP peripheral in AES Key mode */
__HAL_CRYP_SET_MODE(hcryp, CRYP_CR_ALGOMODE_AES_KEY | CRYP_CR_ALGODIR);
/* Enable CRYP */
__HAL_CRYP_ENABLE(hcryp);
/* Get tick */
tickstart = HAL_GetTick();
while(HAL_IS_BIT_SET(hcryp->Instance->SR, CRYP_FLAG_BUSY))
{
/* Check for the Timeout */
if(Timeout != HAL_MAX_DELAY)
{
if((Timeout == 0)||((HAL_GetTick() - tickstart ) > Timeout))
{
/* Change state */
hcryp->State = HAL_CRYP_STATE_TIMEOUT;
/* Process Unlocked */
__HAL_UNLOCK(hcryp);
return HAL_TIMEOUT;
}
}
}
/* Disable CRYP */
__HAL_CRYP_DISABLE(hcryp);
/* Reset the ALGOMODE bits*/
CRYP->CR &= (uint32_t)(~CRYP_CR_ALGOMODE);
/* Set the CRYP peripheral in AES ECB decryption mode */
__HAL_CRYP_SET_MODE(hcryp, CRYP_CR_ALGOMODE_AES_ECB | CRYP_CR_ALGODIR);
/* Flush FIFO */
__HAL_CRYP_FIFO_FLUSH(hcryp);
/* Enable CRYP */
__HAL_CRYP_ENABLE(hcryp);
/* Set the phase */
hcryp->Phase = HAL_CRYP_PHASE_PROCESS;
}
/* Write Plain Data and Get Cypher Data */
if(CRYP_ProcessData(hcryp, pCypherData, Size, pPlainData, Timeout) != HAL_OK)
{
return HAL_TIMEOUT;
}
/* Change the CRYP state */
hcryp->State = HAL_CRYP_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hcryp);
/* Return function status */
return HAL_OK;
}
/**
* @brief Initializes the CRYP peripheral in AES ECB decryption mode
* then decrypted pCypherData. The cypher data are available in pPlainData
* @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module
* @param pCypherData: Pointer to the cyphertext buffer
* @param Size: Length of the plaintext buffer, must be a multiple of 16.
* @param pPlainData: Pointer to the plaintext buffer
* @param Timeout: Specify Timeout value
* @retval HAL status
*/
HAL_StatusTypeDef HAL_CRYP_AESCBC_Decrypt(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData, uint32_t Timeout)
{
uint32_t tickstart = 0;
/* Process Locked */
__HAL_LOCK(hcryp);
/* Change the CRYP state */
hcryp->State = HAL_CRYP_STATE_BUSY;
/* Check if initialization phase has already been performed */
if(hcryp->Phase == HAL_CRYP_PHASE_READY)
{
/* Set the key */
CRYP_SetKey(hcryp, hcryp->Init.pKey, hcryp->Init.KeySize);
/* Set the CRYP peripheral in AES Key mode */
__HAL_CRYP_SET_MODE(hcryp, CRYP_CR_ALGOMODE_AES_KEY | CRYP_CR_ALGODIR);
/* Enable CRYP */
__HAL_CRYP_ENABLE(hcryp);
/* Get tick */
tickstart = HAL_GetTick();
while(HAL_IS_BIT_SET(hcryp->Instance->SR, CRYP_FLAG_BUSY))
{
/* Check for the Timeout */
if(Timeout != HAL_MAX_DELAY)
{
if((Timeout == 0)||((HAL_GetTick() - tickstart ) > Timeout))
{
/* Change state */
hcryp->State = HAL_CRYP_STATE_TIMEOUT;
/* Process Unlocked */
__HAL_UNLOCK(hcryp);
return HAL_TIMEOUT;
}
}
}
/* Reset the ALGOMODE bits*/
CRYP->CR &= (uint32_t)(~CRYP_CR_ALGOMODE);
/* Set the CRYP peripheral in AES CBC decryption mode */
__HAL_CRYP_SET_MODE(hcryp, CRYP_CR_ALGOMODE_AES_CBC | CRYP_CR_ALGODIR);
/* Set the Initialization Vector */
CRYP_SetInitVector(hcryp, hcryp->Init.pInitVect, CRYP_KEYSIZE_128B);
/* Flush FIFO */
__HAL_CRYP_FIFO_FLUSH(hcryp);
/* Enable CRYP */
__HAL_CRYP_ENABLE(hcryp);
/* Set the phase */
hcryp->Phase = HAL_CRYP_PHASE_PROCESS;
}
/* Write Plain Data and Get Cypher Data */
if(CRYP_ProcessData(hcryp, pCypherData, Size, pPlainData, Timeout) != HAL_OK)
{
return HAL_TIMEOUT;
}
/* Change the CRYP state */
hcryp->State = HAL_CRYP_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hcryp);
/* Return function status */
return HAL_OK;
}
/**
* @brief Initializes the CRYP peripheral in AES CTR decryption mode
* then decrypted pCypherData. The cypher data are available in pPlainData
* @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module
* @param pCypherData: Pointer to the cyphertext buffer
* @param Size: Length of the plaintext buffer, must be a multiple of 16.
* @param pPlainData: Pointer to the plaintext buffer
* @param Timeout: Specify Timeout value
* @retval HAL status
*/
HAL_StatusTypeDef HAL_CRYP_AESCTR_Decrypt(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData, uint32_t Timeout)
{
/* Process Locked */
__HAL_LOCK(hcryp);
/* Check if initialization phase has already been performed */
if(hcryp->Phase == HAL_CRYP_PHASE_READY)
{
/* Change the CRYP state */
hcryp->State = HAL_CRYP_STATE_BUSY;
/* Set the key */
CRYP_SetKey(hcryp, hcryp->Init.pKey, hcryp->Init.KeySize);
/* Set the CRYP peripheral in AES CTR mode */
__HAL_CRYP_SET_MODE(hcryp, CRYP_CR_ALGOMODE_AES_CTR | CRYP_CR_ALGODIR);
/* Set the Initialization Vector */
CRYP_SetInitVector(hcryp, hcryp->Init.pInitVect, CRYP_KEYSIZE_128B);
/* Flush FIFO */
__HAL_CRYP_FIFO_FLUSH(hcryp);
/* Enable CRYP */
__HAL_CRYP_ENABLE(hcryp);
/* Set the phase */
hcryp->Phase = HAL_CRYP_PHASE_PROCESS;
}
/* Write Plain Data and Get Cypher Data */
if(CRYP_ProcessData(hcryp, pCypherData, Size, pPlainData, Timeout) != HAL_OK)
{
return HAL_TIMEOUT;
}
/* Change the CRYP state */
hcryp->State = HAL_CRYP_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hcryp);
/* Return function status */
return HAL_OK;
}
/**
* @brief Initializes the CRYP peripheral in AES ECB encryption mode using Interrupt.
* @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module
* @param pPlainData: Pointer to the plaintext buffer
* @param Size: Length of the plaintext buffer, must be a multiple of 16 bytes
* @param pCypherData: Pointer to the cyphertext buffer
* @retval HAL status
*/
HAL_StatusTypeDef HAL_CRYP_AESECB_Encrypt_IT(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData)
{
uint32_t inputaddr;
uint32_t outputaddr;
if(hcryp->State == HAL_CRYP_STATE_READY)
{
/* Process Locked */
__HAL_LOCK(hcryp);
hcryp->CrypInCount = Size;
hcryp->pCrypInBuffPtr = pPlainData;
hcryp->pCrypOutBuffPtr = pCypherData;
hcryp->CrypOutCount = Size;
/* Change the CRYP state */
hcryp->State = HAL_CRYP_STATE_BUSY;
/* Check if initialization phase has already been performed */
if(hcryp->Phase == HAL_CRYP_PHASE_READY)
{
/* Set the key */
CRYP_SetKey(hcryp, hcryp->Init.pKey, hcryp->Init.KeySize);
/* Set the CRYP peripheral in AES ECB mode */
__HAL_CRYP_SET_MODE(hcryp, CRYP_CR_ALGOMODE_AES_ECB);
/* Flush FIFO */
__HAL_CRYP_FIFO_FLUSH(hcryp);
/* Set the phase */
hcryp->Phase = HAL_CRYP_PHASE_PROCESS;
}
/* Enable Interrupts */
__HAL_CRYP_ENABLE_IT(hcryp, CRYP_IT_INI | CRYP_IT_OUTI);
/* Enable CRYP */
__HAL_CRYP_ENABLE(hcryp);
/* Return function status */
return HAL_OK;
}
else if(__HAL_CRYP_GET_IT(hcryp, CRYP_IT_INI))
{
inputaddr = (uint32_t)hcryp->pCrypInBuffPtr;
/* Write the Input block in the IN FIFO */
hcryp->Instance->DR = *(uint32_t*)(inputaddr);
inputaddr+=4;
hcryp->Instance->DR = *(uint32_t*)(inputaddr);
inputaddr+=4;
hcryp->Instance->DR = *(uint32_t*)(inputaddr);
inputaddr+=4;
hcryp->Instance->DR = *(uint32_t*)(inputaddr);
hcryp->pCrypInBuffPtr += 16;
hcryp->CrypInCount -= 16;
if(hcryp->CrypInCount == 0)
{
__HAL_CRYP_DISABLE_IT(hcryp, CRYP_IT_INI);
/* Call the Input data transfer complete callback */
HAL_CRYP_InCpltCallback(hcryp);
}
}
else if(__HAL_CRYP_GET_IT(hcryp, CRYP_IT_OUTI))
{
outputaddr = (uint32_t)hcryp->pCrypOutBuffPtr;
/* Read the Output block from the Output FIFO */
*(uint32_t*)(outputaddr) = hcryp->Instance->DOUT;
outputaddr+=4;
*(uint32_t*)(outputaddr) = hcryp->Instance->DOUT;
outputaddr+=4;
*(uint32_t*)(outputaddr) = hcryp->Instance->DOUT;
outputaddr+=4;
*(uint32_t*)(outputaddr) = hcryp->Instance->DOUT;
hcryp->pCrypOutBuffPtr += 16;
hcryp->CrypOutCount -= 16;
if(hcryp->CrypOutCount == 0)
{
__HAL_CRYP_DISABLE_IT(hcryp, CRYP_IT_OUTI);
/* Process Locked */
__HAL_UNLOCK(hcryp);
/* Change the CRYP state */
hcryp->State = HAL_CRYP_STATE_READY;
/* Call Input transfer complete callback */
HAL_CRYP_OutCpltCallback(hcryp);
}
}
/* Return function status */
return HAL_OK;
}
/**
* @brief Initializes the CRYP peripheral in AES CBC encryption mode using Interrupt.
* @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module
* @param pPlainData: Pointer to the plaintext buffer
* @param Size: Length of the plaintext buffer, must be a multiple of 16 bytes
* @param pCypherData: Pointer to the cyphertext buffer
* @retval HAL status
*/
HAL_StatusTypeDef HAL_CRYP_AESCBC_Encrypt_IT(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData)
{
uint32_t inputaddr;
uint32_t outputaddr;
if(hcryp->State == HAL_CRYP_STATE_READY)
{
/* Process Locked */
__HAL_LOCK(hcryp);
hcryp->CrypInCount = Size;
hcryp->pCrypInBuffPtr = pPlainData;
hcryp->pCrypOutBuffPtr = pCypherData;
hcryp->CrypOutCount = Size;
/* Change the CRYP state */
hcryp->State = HAL_CRYP_STATE_BUSY;
/* Check if initialization phase has already been performed */
if(hcryp->Phase == HAL_CRYP_PHASE_READY)
{
/* Set the key */
CRYP_SetKey(hcryp, hcryp->Init.pKey, hcryp->Init.KeySize);
/* Set the CRYP peripheral in AES CBC mode */
__HAL_CRYP_SET_MODE(hcryp, CRYP_CR_ALGOMODE_AES_CBC);
/* Set the Initialization Vector */
CRYP_SetInitVector(hcryp, hcryp->Init.pInitVect, CRYP_KEYSIZE_128B);
/* Flush FIFO */
__HAL_CRYP_FIFO_FLUSH(hcryp);
/* Set the phase */
hcryp->Phase = HAL_CRYP_PHASE_PROCESS;
}
/* Enable Interrupts */
__HAL_CRYP_ENABLE_IT(hcryp, CRYP_IT_INI | CRYP_IT_OUTI);
/* Enable CRYP */
__HAL_CRYP_ENABLE(hcryp);
/* Return function status */
return HAL_OK;
}
else if(__HAL_CRYP_GET_IT(hcryp, CRYP_IT_INI))
{
inputaddr = (uint32_t)hcryp->pCrypInBuffPtr;
/* Write the Input block in the IN FIFO */
hcryp->Instance->DR = *(uint32_t*)(inputaddr);
inputaddr+=4;
hcryp->Instance->DR = *(uint32_t*)(inputaddr);
inputaddr+=4;
hcryp->Instance->DR = *(uint32_t*)(inputaddr);
inputaddr+=4;
hcryp->Instance->DR = *(uint32_t*)(inputaddr);
hcryp->pCrypInBuffPtr += 16;
hcryp->CrypInCount -= 16;
if(hcryp->CrypInCount == 0)
{
__HAL_CRYP_DISABLE_IT(hcryp, CRYP_IT_INI);
/* Call the Input data transfer complete callback */
HAL_CRYP_InCpltCallback(hcryp);
}
}
else if(__HAL_CRYP_GET_IT(hcryp, CRYP_IT_OUTI))
{
outputaddr = (uint32_t)hcryp->pCrypOutBuffPtr;
/* Read the Output block from the Output FIFO */
*(uint32_t*)(outputaddr) = hcryp->Instance->DOUT;
outputaddr+=4;
*(uint32_t*)(outputaddr) = hcryp->Instance->DOUT;
outputaddr+=4;
*(uint32_t*)(outputaddr) = hcryp->Instance->DOUT;
outputaddr+=4;
*(uint32_t*)(outputaddr) = hcryp->Instance->DOUT;
hcryp->pCrypOutBuffPtr += 16;
hcryp->CrypOutCount -= 16;
if(hcryp->CrypOutCount == 0)
{
__HAL_CRYP_DISABLE_IT(hcryp, CRYP_IT_OUTI);
/* Process Locked */
__HAL_UNLOCK(hcryp);
/* Change the CRYP state */
hcryp->State = HAL_CRYP_STATE_READY;
/* Call Input transfer complete callback */
HAL_CRYP_OutCpltCallback(hcryp);
}
}
/* Return function status */
return HAL_OK;
}
/**
* @brief Initializes the CRYP peripheral in AES CTR encryption mode using Interrupt.
* @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module
* @param pPlainData: Pointer to the plaintext buffer
* @param Size: Length of the plaintext buffer, must be a multiple of 16 bytes
* @param pCypherData: Pointer to the cyphertext buffer
* @retval HAL status
*/
HAL_StatusTypeDef HAL_CRYP_AESCTR_Encrypt_IT(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData)
{
uint32_t inputaddr;
uint32_t outputaddr;
if(hcryp->State == HAL_CRYP_STATE_READY)
{
/* Process Locked */
__HAL_LOCK(hcryp);
hcryp->CrypInCount = Size;
hcryp->pCrypInBuffPtr = pPlainData;
hcryp->pCrypOutBuffPtr = pCypherData;
hcryp->CrypOutCount = Size;
/* Change the CRYP state */
hcryp->State = HAL_CRYP_STATE_BUSY;
/* Check if initialization phase has already been performed */
if(hcryp->Phase == HAL_CRYP_PHASE_READY)
{
/* Set the key */
CRYP_SetKey(hcryp, hcryp->Init.pKey, hcryp->Init.KeySize);
/* Set the CRYP peripheral in AES CTR mode */
__HAL_CRYP_SET_MODE(hcryp, CRYP_CR_ALGOMODE_AES_CTR);
/* Set the Initialization Vector */
CRYP_SetInitVector(hcryp, hcryp->Init.pInitVect, CRYP_KEYSIZE_128B);
/* Flush FIFO */
__HAL_CRYP_FIFO_FLUSH(hcryp);
/* Set the phase */
hcryp->Phase = HAL_CRYP_PHASE_PROCESS;
}
/* Enable Interrupts */
__HAL_CRYP_ENABLE_IT(hcryp, CRYP_IT_INI | CRYP_IT_OUTI);
/* Enable CRYP */
__HAL_CRYP_ENABLE(hcryp);
/* Return function status */
return HAL_OK;
}
else if(__HAL_CRYP_GET_IT(hcryp, CRYP_IT_INI))
{
inputaddr = (uint32_t)hcryp->pCrypInBuffPtr;
/* Write the Input block in the IN FIFO */
hcryp->Instance->DR = *(uint32_t*)(inputaddr);
inputaddr+=4;
hcryp->Instance->DR = *(uint32_t*)(inputaddr);
inputaddr+=4;
hcryp->Instance->DR = *(uint32_t*)(inputaddr);
inputaddr+=4;
hcryp->Instance->DR = *(uint32_t*)(inputaddr);
hcryp->pCrypInBuffPtr += 16;
hcryp->CrypInCount -= 16;
if(hcryp->CrypInCount == 0)
{
__HAL_CRYP_DISABLE_IT(hcryp, CRYP_IT_INI);
/* Call the Input data transfer complete callback */
HAL_CRYP_InCpltCallback(hcryp);
}
}
else if(__HAL_CRYP_GET_IT(hcryp, CRYP_IT_OUTI))
{
outputaddr = (uint32_t)hcryp->pCrypOutBuffPtr;
/* Read the Output block from the Output FIFO */
*(uint32_t*)(outputaddr) = hcryp->Instance->DOUT;
outputaddr+=4;
*(uint32_t*)(outputaddr) = hcryp->Instance->DOUT;
outputaddr+=4;
*(uint32_t*)(outputaddr) = hcryp->Instance->DOUT;
outputaddr+=4;
*(uint32_t*)(outputaddr) = hcryp->Instance->DOUT;
hcryp->pCrypOutBuffPtr += 16;
hcryp->CrypOutCount -= 16;
if(hcryp->CrypOutCount == 0)
{
__HAL_CRYP_DISABLE_IT(hcryp, CRYP_IT_OUTI);
/* Process Unlocked */
__HAL_UNLOCK(hcryp);
/* Change the CRYP state */
hcryp->State = HAL_CRYP_STATE_READY;
/* Call Input transfer complete callback */
HAL_CRYP_OutCpltCallback(hcryp);
}
}
/* Return function status */
return HAL_OK;
}
/**
* @brief Initializes the CRYP peripheral in AES ECB decryption mode using Interrupt.
* @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module
* @param pCypherData: Pointer to the cyphertext buffer
* @param Size: Length of the plaintext buffer, must be a multiple of 16.
* @param pPlainData: Pointer to the plaintext buffer
* @retval HAL status
*/
HAL_StatusTypeDef HAL_CRYP_AESECB_Decrypt_IT(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData)
{
uint32_t tickstart = 0;
uint32_t inputaddr;
uint32_t outputaddr;
if(hcryp->State == HAL_CRYP_STATE_READY)
{
/* Process Locked */
__HAL_LOCK(hcryp);
hcryp->CrypInCount = Size;
hcryp->pCrypInBuffPtr = pCypherData;
hcryp->pCrypOutBuffPtr = pPlainData;
hcryp->CrypOutCount = Size;
/* Change the CRYP state */
hcryp->State = HAL_CRYP_STATE_BUSY;
/* Check if initialization phase has already been performed */
if(hcryp->Phase == HAL_CRYP_PHASE_READY)
{
/* Set the key */
CRYP_SetKey(hcryp, hcryp->Init.pKey, hcryp->Init.KeySize);
/* Set the CRYP peripheral in AES Key mode */
__HAL_CRYP_SET_MODE(hcryp, CRYP_CR_ALGOMODE_AES_KEY | CRYP_CR_ALGODIR);
/* Enable CRYP */
__HAL_CRYP_ENABLE(hcryp);
/* Get tick */
tickstart = HAL_GetTick();
while(HAL_IS_BIT_SET(hcryp->Instance->SR, CRYP_FLAG_BUSY))
{
/* Check for the Timeout */
if((HAL_GetTick() - tickstart ) > CRYP_TIMEOUT_VALUE)
{
/* Change state */
hcryp->State = HAL_CRYP_STATE_TIMEOUT;
/* Process Unlocked */
__HAL_UNLOCK(hcryp);
return HAL_TIMEOUT;
}
}
/* Reset the ALGOMODE bits*/
CRYP->CR &= (uint32_t)(~CRYP_CR_ALGOMODE);
/* Set the CRYP peripheral in AES ECB decryption mode */
__HAL_CRYP_SET_MODE(hcryp, CRYP_CR_ALGOMODE_AES_ECB | CRYP_CR_ALGODIR);
/* Flush FIFO */
__HAL_CRYP_FIFO_FLUSH(hcryp);
/* Set the phase */
hcryp->Phase = HAL_CRYP_PHASE_PROCESS;
}
/* Enable Interrupts */
__HAL_CRYP_ENABLE_IT(hcryp, CRYP_IT_INI | CRYP_IT_OUTI);
/* Enable CRYP */
__HAL_CRYP_ENABLE(hcryp);
/* Return function status */
return HAL_OK;
}
else if(__HAL_CRYP_GET_IT(hcryp, CRYP_IT_INI))
{
inputaddr = (uint32_t)hcryp->pCrypInBuffPtr;
/* Write the Input block in the IN FIFO */
hcryp->Instance->DR = *(uint32_t*)(inputaddr);
inputaddr+=4;
hcryp->Instance->DR = *(uint32_t*)(inputaddr);
inputaddr+=4;
hcryp->Instance->DR = *(uint32_t*)(inputaddr);
inputaddr+=4;
hcryp->Instance->DR = *(uint32_t*)(inputaddr);
hcryp->pCrypInBuffPtr += 16;
hcryp->CrypInCount -= 16;
if(hcryp->CrypInCount == 0)
{
__HAL_CRYP_DISABLE_IT(hcryp, CRYP_IT_INI);
/* Call the Input data transfer complete callback */
HAL_CRYP_InCpltCallback(hcryp);
}
}
else if(__HAL_CRYP_GET_IT(hcryp, CRYP_IT_OUTI))
{
outputaddr = (uint32_t)hcryp->pCrypOutBuffPtr;
/* Read the Output block from the Output FIFO */
*(uint32_t*)(outputaddr) = hcryp->Instance->DOUT;
outputaddr+=4;
*(uint32_t*)(outputaddr) = hcryp->Instance->DOUT;
outputaddr+=4;
*(uint32_t*)(outputaddr) = hcryp->Instance->DOUT;
outputaddr+=4;
*(uint32_t*)(outputaddr) = hcryp->Instance->DOUT;
hcryp->pCrypOutBuffPtr += 16;
hcryp->CrypOutCount -= 16;
if(hcryp->CrypOutCount == 0)
{
__HAL_CRYP_DISABLE_IT(hcryp, CRYP_IT_OUTI);
/* Process Unlocked */
__HAL_UNLOCK(hcryp);
/* Change the CRYP state */
hcryp->State = HAL_CRYP_STATE_READY;
/* Call Input transfer complete callback */
HAL_CRYP_OutCpltCallback(hcryp);
}
}
/* Return function status */
return HAL_OK;
}
/**
* @brief Initializes the CRYP peripheral in AES CBC decryption mode using IT.
* @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module
* @param pCypherData: Pointer to the cyphertext buffer
* @param Size: Length of the plaintext buffer, must be a multiple of 16
* @param pPlainData: Pointer to the plaintext buffer
* @retval HAL status
*/
HAL_StatusTypeDef HAL_CRYP_AESCBC_Decrypt_IT(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData)
{
uint32_t tickstart = 0;
uint32_t inputaddr;
uint32_t outputaddr;
if(hcryp->State == HAL_CRYP_STATE_READY)
{
/* Process Locked */
__HAL_LOCK(hcryp);
/* Get the buffer addresses and sizes */
hcryp->CrypInCount = Size;
hcryp->pCrypInBuffPtr = pCypherData;
hcryp->pCrypOutBuffPtr = pPlainData;
hcryp->CrypOutCount = Size;
/* Change the CRYP state */
hcryp->State = HAL_CRYP_STATE_BUSY;
/* Check if initialization phase has already been performed */
if(hcryp->Phase == HAL_CRYP_PHASE_READY)
{
/* Set the key */
CRYP_SetKey(hcryp, hcryp->Init.pKey, hcryp->Init.KeySize);
/* Set the CRYP peripheral in AES Key mode */
__HAL_CRYP_SET_MODE(hcryp, CRYP_CR_ALGOMODE_AES_KEY | CRYP_CR_ALGODIR);
/* Enable CRYP */
__HAL_CRYP_ENABLE(hcryp);
/* Get tick */
tickstart = HAL_GetTick();
while(HAL_IS_BIT_SET(hcryp->Instance->SR, CRYP_FLAG_BUSY))
{
/* Check for the Timeout */
if((HAL_GetTick() - tickstart ) > CRYP_TIMEOUT_VALUE)
{
/* Change state */
hcryp->State = HAL_CRYP_STATE_TIMEOUT;
/* Process Unlocked */
__HAL_UNLOCK(hcryp);
return HAL_TIMEOUT;
}
}
/* Reset the ALGOMODE bits*/
CRYP->CR &= (uint32_t)(~CRYP_CR_ALGOMODE);
/* Set the CRYP peripheral in AES CBC decryption mode */
__HAL_CRYP_SET_MODE(hcryp, CRYP_CR_ALGOMODE_AES_CBC | CRYP_CR_ALGODIR);
/* Set the Initialization Vector */
CRYP_SetInitVector(hcryp, hcryp->Init.pInitVect, CRYP_KEYSIZE_128B);
/* Flush FIFO */
__HAL_CRYP_FIFO_FLUSH(hcryp);
/* Enable CRYP */
__HAL_CRYP_ENABLE(hcryp);
/* Set the phase */
hcryp->Phase = HAL_CRYP_PHASE_PROCESS;
}
/* Enable Interrupts */
__HAL_CRYP_ENABLE_IT(hcryp, CRYP_IT_INI | CRYP_IT_OUTI);
/* Enable CRYP */
__HAL_CRYP_ENABLE(hcryp);
/* Return function status */
return HAL_OK;
}
else if(__HAL_CRYP_GET_IT(hcryp, CRYP_IT_INI))
{
inputaddr = (uint32_t)hcryp->pCrypInBuffPtr;
/* Write the Input block in the IN FIFO */
hcryp->Instance->DR = *(uint32_t*)(inputaddr);
inputaddr+=4;
hcryp->Instance->DR = *(uint32_t*)(inputaddr);
inputaddr+=4;
hcryp->Instance->DR = *(uint32_t*)(inputaddr);
inputaddr+=4;
hcryp->Instance->DR = *(uint32_t*)(inputaddr);
hcryp->pCrypInBuffPtr += 16;
hcryp->CrypInCount -= 16;
if(hcryp->CrypInCount == 0)
{
__HAL_CRYP_DISABLE_IT(hcryp, CRYP_IT_INI);
/* Call the Input data transfer complete callback */
HAL_CRYP_InCpltCallback(hcryp);
}
}
else if(__HAL_CRYP_GET_IT(hcryp, CRYP_IT_OUTI))
{
outputaddr = (uint32_t)hcryp->pCrypOutBuffPtr;
/* Read the Output block from the Output FIFO */
*(uint32_t*)(outputaddr) = hcryp->Instance->DOUT;
outputaddr+=4;
*(uint32_t*)(outputaddr) = hcryp->Instance->DOUT;
outputaddr+=4;
*(uint32_t*)(outputaddr) = hcryp->Instance->DOUT;
outputaddr+=4;
*(uint32_t*)(outputaddr) = hcryp->Instance->DOUT;
hcryp->pCrypOutBuffPtr += 16;
hcryp->CrypOutCount -= 16;
if(hcryp->CrypOutCount == 0)
{
__HAL_CRYP_DISABLE_IT(hcryp, CRYP_IT_OUTI);
/* Process Unlocked */
__HAL_UNLOCK(hcryp);
/* Change the CRYP state */
hcryp->State = HAL_CRYP_STATE_READY;
/* Call Input transfer complete callback */
HAL_CRYP_OutCpltCallback(hcryp);
}
}
/* Return function status */
return HAL_OK;
}
/**
* @brief Initializes the CRYP peripheral in AES CTR decryption mode using Interrupt.
* @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module
* @param pCypherData: Pointer to the cyphertext buffer
* @param Size: Length of the plaintext buffer, must be a multiple of 16
* @param pPlainData: Pointer to the plaintext buffer
* @retval HAL status
*/
HAL_StatusTypeDef HAL_CRYP_AESCTR_Decrypt_IT(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData)
{
uint32_t inputaddr;
uint32_t outputaddr;
if(hcryp->State == HAL_CRYP_STATE_READY)
{
/* Process Locked */
__HAL_LOCK(hcryp);
/* Get the buffer addresses and sizes */
hcryp->CrypInCount = Size;
hcryp->pCrypInBuffPtr = pCypherData;
hcryp->pCrypOutBuffPtr = pPlainData;
hcryp->CrypOutCount = Size;
/* Change the CRYP state */
hcryp->State = HAL_CRYP_STATE_BUSY;
/* Check if initialization phase has already been performed */
if(hcryp->Phase == HAL_CRYP_PHASE_READY)
{
/* Set the key */
CRYP_SetKey(hcryp, hcryp->Init.pKey, hcryp->Init.KeySize);
/* Set the CRYP peripheral in AES CTR mode */
__HAL_CRYP_SET_MODE(hcryp, CRYP_CR_ALGOMODE_AES_CTR | CRYP_CR_ALGODIR);
/* Set the Initialization Vector */
CRYP_SetInitVector(hcryp, hcryp->Init.pInitVect, CRYP_KEYSIZE_128B);
/* Flush FIFO */
__HAL_CRYP_FIFO_FLUSH(hcryp);
/* Set the phase */
hcryp->Phase = HAL_CRYP_PHASE_PROCESS;
}
/* Enable Interrupts */
__HAL_CRYP_ENABLE_IT(hcryp, CRYP_IT_INI | CRYP_IT_OUTI);
/* Enable CRYP */
__HAL_CRYP_ENABLE(hcryp);
/* Return function status */
return HAL_OK;
}
else if(__HAL_CRYP_GET_IT(hcryp, CRYP_IT_INI))
{
inputaddr = (uint32_t)hcryp->pCrypInBuffPtr;
/* Write the Input block in the IN FIFO */
hcryp->Instance->DR = *(uint32_t*)(inputaddr);
inputaddr+=4;
hcryp->Instance->DR = *(uint32_t*)(inputaddr);
inputaddr+=4;
hcryp->Instance->DR = *(uint32_t*)(inputaddr);
inputaddr+=4;
hcryp->Instance->DR = *(uint32_t*)(inputaddr);
hcryp->pCrypInBuffPtr += 16;
hcryp->CrypInCount -= 16;
if(hcryp->CrypInCount == 0)
{
__HAL_CRYP_DISABLE_IT(hcryp, CRYP_IT_INI);
/* Call the Input data transfer complete callback */
HAL_CRYP_InCpltCallback(hcryp);
}
}
else if(__HAL_CRYP_GET_IT(hcryp, CRYP_IT_OUTI))
{
outputaddr = (uint32_t)hcryp->pCrypOutBuffPtr;
/* Read the Output block from the Output FIFO */
*(uint32_t*)(outputaddr) = hcryp->Instance->DOUT;
outputaddr+=4;
*(uint32_t*)(outputaddr) = hcryp->Instance->DOUT;
outputaddr+=4;
*(uint32_t*)(outputaddr) = hcryp->Instance->DOUT;
outputaddr+=4;
*(uint32_t*)(outputaddr) = hcryp->Instance->DOUT;
hcryp->pCrypOutBuffPtr += 16;
hcryp->CrypOutCount -= 16;
if(hcryp->CrypOutCount == 0)
{
__HAL_CRYP_DISABLE_IT(hcryp, CRYP_IT_OUTI);
/* Process Unlocked */
__HAL_UNLOCK(hcryp);
/* Change the CRYP state */
hcryp->State = HAL_CRYP_STATE_READY;
/* Call Input transfer complete callback */
HAL_CRYP_OutCpltCallback(hcryp);
}
}
/* Return function status */
return HAL_OK;
}
/**
* @brief Initializes the CRYP peripheral in AES ECB encryption mode using DMA.
* @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module
* @param pPlainData: Pointer to the plaintext buffer
* @param Size: Length of the plaintext buffer, must be a multiple of 16 bytes
* @param pCypherData: Pointer to the cyphertext buffer
* @retval HAL status
*/
HAL_StatusTypeDef HAL_CRYP_AESECB_Encrypt_DMA(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData)
{
uint32_t inputaddr;
uint32_t outputaddr;
if((hcryp->State == HAL_CRYP_STATE_READY) || (hcryp->Phase == HAL_CRYP_PHASE_PROCESS))
{
/* Process Locked */
__HAL_LOCK(hcryp);
inputaddr = (uint32_t)pPlainData;
outputaddr = (uint32_t)pCypherData;
/* Change the CRYP state */
hcryp->State = HAL_CRYP_STATE_BUSY;
/* Check if initialization phase has already been performed */
if(hcryp->Phase == HAL_CRYP_PHASE_READY)
{
/* Set the key */
CRYP_SetKey(hcryp, hcryp->Init.pKey, hcryp->Init.KeySize);
/* Set the CRYP peripheral in AES ECB mode */
__HAL_CRYP_SET_MODE(hcryp, CRYP_CR_ALGOMODE_AES_ECB);
/* Flush FIFO */
__HAL_CRYP_FIFO_FLUSH(hcryp);
/* Set the phase */
hcryp->Phase = HAL_CRYP_PHASE_PROCESS;
}
/* Set the input and output addresses and start DMA transfer */
CRYP_SetDMAConfig(hcryp, inputaddr, Size, outputaddr);
/* Process Unlocked */
__HAL_UNLOCK(hcryp);
/* Return function status */
return HAL_OK;
}
else
{
return HAL_ERROR;
}
}
/**
* @brief Initializes the CRYP peripheral in AES CBC encryption mode using DMA.
* @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module
* @param pPlainData: Pointer to the plaintext buffer
* @param Size: Length of the plaintext buffer, must be a multiple of 16.
* @param pCypherData: Pointer to the cyphertext buffer
* @retval HAL status
*/
HAL_StatusTypeDef HAL_CRYP_AESCBC_Encrypt_DMA(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData)
{
uint32_t inputaddr;
uint32_t outputaddr;
if((hcryp->State == HAL_CRYP_STATE_READY) || (hcryp->Phase == HAL_CRYP_PHASE_PROCESS))
{
/* Process Locked */
__HAL_LOCK(hcryp);
inputaddr = (uint32_t)pPlainData;
outputaddr = (uint32_t)pCypherData;
/* Change the CRYP state */
hcryp->State = HAL_CRYP_STATE_BUSY;
/* Check if initialization phase has already been performed */
if(hcryp->Phase == HAL_CRYP_PHASE_READY)
{
/* Set the key */
CRYP_SetKey(hcryp, hcryp->Init.pKey, hcryp->Init.KeySize);
/* Set the CRYP peripheral in AES ECB mode */
__HAL_CRYP_SET_MODE(hcryp, CRYP_CR_ALGOMODE_AES_CBC);
/* Set the Initialization Vector */
CRYP_SetInitVector(hcryp, hcryp->Init.pInitVect, CRYP_KEYSIZE_128B);
/* Flush FIFO */
__HAL_CRYP_FIFO_FLUSH(hcryp);
/* Set the phase */
hcryp->Phase = HAL_CRYP_PHASE_PROCESS;
}
/* Set the input and output addresses and start DMA transfer */
CRYP_SetDMAConfig(hcryp, inputaddr, Size, outputaddr);
/* Process Unlocked */
__HAL_UNLOCK(hcryp);
/* Return function status */
return HAL_OK;
}
else
{
return HAL_ERROR;
}
}
/**
* @brief Initializes the CRYP peripheral in AES CTR encryption mode using DMA.
* @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module
* @param pPlainData: Pointer to the plaintext buffer
* @param Size: Length of the plaintext buffer, must be a multiple of 16.
* @param pCypherData: Pointer to the cyphertext buffer
* @retval HAL status
*/
HAL_StatusTypeDef HAL_CRYP_AESCTR_Encrypt_DMA(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData)
{
uint32_t inputaddr;
uint32_t outputaddr;
if((hcryp->State == HAL_CRYP_STATE_READY) || (hcryp->Phase == HAL_CRYP_PHASE_PROCESS))
{
/* Process Locked */
__HAL_LOCK(hcryp);
inputaddr = (uint32_t)pPlainData;
outputaddr = (uint32_t)pCypherData;
/* Change the CRYP state */
hcryp->State = HAL_CRYP_STATE_BUSY;
/* Check if initialization phase has already been performed */
if(hcryp->Phase == HAL_CRYP_PHASE_READY)
{
/* Set the key */
CRYP_SetKey(hcryp, hcryp->Init.pKey, hcryp->Init.KeySize);
/* Set the CRYP peripheral in AES ECB mode */
__HAL_CRYP_SET_MODE(hcryp, CRYP_CR_ALGOMODE_AES_CTR);
/* Set the Initialization Vector */
CRYP_SetInitVector(hcryp, hcryp->Init.pInitVect, CRYP_KEYSIZE_128B);
/* Flush FIFO */
__HAL_CRYP_FIFO_FLUSH(hcryp);
/* Set the phase */
hcryp->Phase = HAL_CRYP_PHASE_PROCESS;
}
/* Set the input and output addresses and start DMA transfer */
CRYP_SetDMAConfig(hcryp, inputaddr, Size, outputaddr);
/* Process Unlocked */
__HAL_UNLOCK(hcryp);
/* Return function status */
return HAL_OK;
}
else
{
return HAL_ERROR;
}
}
/**
* @brief Initializes the CRYP peripheral in AES ECB decryption mode using DMA.
* @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module
* @param pCypherData: Pointer to the cyphertext buffer
* @param Size: Length of the plaintext buffer, must be a multiple of 16 bytes
* @param pPlainData: Pointer to the plaintext buffer
* @retval HAL status
*/
HAL_StatusTypeDef HAL_CRYP_AESECB_Decrypt_DMA(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData)
{
uint32_t tickstart = 0;
uint32_t inputaddr;
uint32_t outputaddr;
if((hcryp->State == HAL_CRYP_STATE_READY) || (hcryp->Phase == HAL_CRYP_PHASE_PROCESS))
{
/* Process Locked */
__HAL_LOCK(hcryp);
inputaddr = (uint32_t)pCypherData;
outputaddr = (uint32_t)pPlainData;
/* Change the CRYP state */
hcryp->State = HAL_CRYP_STATE_BUSY;
/* Check if initialization phase has already been performed */
if(hcryp->Phase == HAL_CRYP_PHASE_READY)
{
/* Set the key */
CRYP_SetKey(hcryp, hcryp->Init.pKey, hcryp->Init.KeySize);
/* Set the CRYP peripheral in AES Key mode */
__HAL_CRYP_SET_MODE(hcryp, CRYP_CR_ALGOMODE_AES_KEY | CRYP_CR_ALGODIR);
/* Enable CRYP */
__HAL_CRYP_ENABLE(hcryp);
/* Get tick */
tickstart = HAL_GetTick();
while(HAL_IS_BIT_SET(hcryp->Instance->SR, CRYP_FLAG_BUSY))
{
/* Check for the Timeout */
if((HAL_GetTick() - tickstart ) > CRYP_TIMEOUT_VALUE)
{
/* Change state */
hcryp->State = HAL_CRYP_STATE_TIMEOUT;
/* Process Unlocked */
__HAL_UNLOCK(hcryp);
return HAL_TIMEOUT;
}
}
/* Reset the ALGOMODE bits*/
CRYP->CR &= (uint32_t)(~CRYP_CR_ALGOMODE);
/* Set the CRYP peripheral in AES ECB decryption mode */
__HAL_CRYP_SET_MODE(hcryp, CRYP_CR_ALGOMODE_AES_ECB | CRYP_CR_ALGODIR);
/* Flush FIFO */
__HAL_CRYP_FIFO_FLUSH(hcryp);
/* Set the phase */
hcryp->Phase = HAL_CRYP_PHASE_PROCESS;
}
/* Set the input and output addresses and start DMA transfer */
CRYP_SetDMAConfig(hcryp, inputaddr, Size, outputaddr);
/* Process Unlocked */
__HAL_UNLOCK(hcryp);
/* Return function status */
return HAL_OK;
}
else
{
return HAL_ERROR;
}
}
/**
* @brief Initializes the CRYP peripheral in AES CBC encryption mode using DMA.
* @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module
* @param pCypherData: Pointer to the cyphertext buffer
* @param Size: Length of the plaintext buffer, must be a multiple of 16 bytes
* @param pPlainData: Pointer to the plaintext buffer
* @retval HAL status
*/
HAL_StatusTypeDef HAL_CRYP_AESCBC_Decrypt_DMA(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData)
{
uint32_t tickstart = 0;
uint32_t inputaddr;
uint32_t outputaddr;
if((hcryp->State == HAL_CRYP_STATE_READY) || (hcryp->Phase == HAL_CRYP_PHASE_PROCESS))
{
/* Process Locked */
__HAL_LOCK(hcryp);
inputaddr = (uint32_t)pCypherData;
outputaddr = (uint32_t)pPlainData;
/* Change the CRYP state */
hcryp->State = HAL_CRYP_STATE_BUSY;
/* Check if initialization phase has already been performed */
if(hcryp->Phase == HAL_CRYP_PHASE_READY)
{
/* Set the key */
CRYP_SetKey(hcryp, hcryp->Init.pKey, hcryp->Init.KeySize);
/* Set the CRYP peripheral in AES Key mode */
__HAL_CRYP_SET_MODE(hcryp, CRYP_CR_ALGOMODE_AES_KEY | CRYP_CR_ALGODIR);
/* Enable CRYP */
__HAL_CRYP_ENABLE(hcryp);
/* Get tick */
tickstart = HAL_GetTick();
while(HAL_IS_BIT_SET(hcryp->Instance->SR, CRYP_FLAG_BUSY))
{
/* Check for the Timeout */
if((HAL_GetTick() - tickstart ) > CRYP_TIMEOUT_VALUE)
{
/* Change state */
hcryp->State = HAL_CRYP_STATE_TIMEOUT;
/* Process Unlocked */
__HAL_UNLOCK(hcryp);
return HAL_TIMEOUT;
}
}
/* Reset the ALGOMODE bits*/
CRYP->CR &= (uint32_t)(~CRYP_CR_ALGOMODE);
/* Set the CRYP peripheral in AES CBC decryption mode */
__HAL_CRYP_SET_MODE(hcryp, CRYP_CR_ALGOMODE_AES_CBC | CRYP_CR_ALGODIR);
/* Set the Initialization Vector */
CRYP_SetInitVector(hcryp, hcryp->Init.pInitVect, CRYP_KEYSIZE_128B);
/* Flush FIFO */
__HAL_CRYP_FIFO_FLUSH(hcryp);
/* Set the phase */
hcryp->Phase = HAL_CRYP_PHASE_PROCESS;
}
/* Set the input and output addresses and start DMA transfer */
CRYP_SetDMAConfig(hcryp, inputaddr, Size, outputaddr);
/* Process Unlocked */
__HAL_UNLOCK(hcryp);
/* Return function status */
return HAL_OK;
}
else
{
return HAL_ERROR;
}
}
/**
* @brief Initializes the CRYP peripheral in AES CTR decryption mode using DMA.
* @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module
* @param pCypherData: Pointer to the cyphertext buffer
* @param Size: Length of the plaintext buffer, must be a multiple of 16
* @param pPlainData: Pointer to the plaintext buffer
* @retval HAL status
*/
HAL_StatusTypeDef HAL_CRYP_AESCTR_Decrypt_DMA(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData)
{
uint32_t inputaddr;
uint32_t outputaddr;
if((hcryp->State == HAL_CRYP_STATE_READY) || (hcryp->Phase == HAL_CRYP_PHASE_PROCESS))
{
/* Process Locked */
__HAL_LOCK(hcryp);
inputaddr = (uint32_t)pCypherData;
outputaddr = (uint32_t)pPlainData;
/* Change the CRYP state */
hcryp->State = HAL_CRYP_STATE_BUSY;
/* Check if initialization phase has already been performed */
if(hcryp->Phase == HAL_CRYP_PHASE_READY)
{
/* Set the key */
CRYP_SetKey(hcryp, hcryp->Init.pKey, hcryp->Init.KeySize);
/* Set the CRYP peripheral in AES CTR mode */
__HAL_CRYP_SET_MODE(hcryp, CRYP_CR_ALGOMODE_AES_CTR | CRYP_CR_ALGODIR);
/* Set the Initialization Vector */
CRYP_SetInitVector(hcryp, hcryp->Init.pInitVect, CRYP_KEYSIZE_128B);
/* Flush FIFO */
__HAL_CRYP_FIFO_FLUSH(hcryp);
/* Set the phase */
hcryp->Phase = HAL_CRYP_PHASE_PROCESS;
}
/* Set the input and output addresses and start DMA transfer */
CRYP_SetDMAConfig(hcryp, inputaddr, Size, outputaddr);
/* Process Unlocked */
__HAL_UNLOCK(hcryp);
/* Return function status */
return HAL_OK;
}
else
{
return HAL_ERROR;
}
}
/**
* @}
*/
/** @defgroup CRYP_Exported_Functions_Group3 DES processing functions
* @brief processing functions.
*
@verbatim
==============================================================================
##### DES processing functions #####
==============================================================================
[..] This section provides functions allowing to:
(+) Encrypt plaintext using DES using ECB or CBC chaining modes
(+) Decrypt cyphertext using ECB or CBC chaining modes
[..] Three processing functions are available:
(+) Polling mode
(+) Interrupt mode
(+) DMA mode
@endverbatim
* @{
*/
/**
* @brief Initializes the CRYP peripheral in DES ECB encryption mode.
* @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module
* @param pPlainData: Pointer to the plaintext buffer
* @param Size: Length of the plaintext buffer, must be a multiple of 8
* @param pCypherData: Pointer to the cyphertext buffer
* @param Timeout: Specify Timeout value
* @retval HAL status
*/
HAL_StatusTypeDef HAL_CRYP_DESECB_Encrypt(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData, uint32_t Timeout)
{
/* Process Locked */
__HAL_LOCK(hcryp);
/* Change the CRYP state */
hcryp->State = HAL_CRYP_STATE_BUSY;
/* Set CRYP peripheral in DES ECB encryption mode */
CRYP_SetDESECBMode(hcryp, 0);
/* Enable CRYP */
__HAL_CRYP_ENABLE(hcryp);
/* Write Plain Data and Get Cypher Data */
if(CRYP_ProcessData2Words(hcryp, pPlainData, Size, pCypherData, Timeout) != HAL_OK)
{
return HAL_TIMEOUT;
}
/* Change the CRYP state */
hcryp->State = HAL_CRYP_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hcryp);
/* Return function status */
return HAL_OK;
}
/**
* @brief Initializes the CRYP peripheral in DES ECB decryption mode.
* @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module
* @param pPlainData: Pointer to the plaintext buffer
* @param Size: Length of the plaintext buffer, must be a multiple of 8
* @param pCypherData: Pointer to the cyphertext buffer
* @param Timeout: Specify Timeout value
* @retval HAL status
*/
HAL_StatusTypeDef HAL_CRYP_DESECB_Decrypt(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData, uint32_t Timeout)
{
/* Process Locked */
__HAL_LOCK(hcryp);
/* Change the CRYP state */
hcryp->State = HAL_CRYP_STATE_BUSY;
/* Set CRYP peripheral in DES ECB decryption mode */
CRYP_SetDESECBMode(hcryp, CRYP_CR_ALGODIR);
/* Enable CRYP */
__HAL_CRYP_ENABLE(hcryp);
/* Write Plain Data and Get Cypher Data */
if(CRYP_ProcessData2Words(hcryp, pPlainData, Size, pCypherData, Timeout) != HAL_OK)
{
return HAL_TIMEOUT;
}
/* Change the CRYP state */
hcryp->State = HAL_CRYP_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hcryp);
/* Return function status */
return HAL_OK;
}
/**
* @brief Initializes the CRYP peripheral in DES CBC encryption mode.
* @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module
* @param pPlainData: Pointer to the plaintext buffer
* @param Size: Length of the plaintext buffer, must be a multiple of 8
* @param pCypherData: Pointer to the cyphertext buffer
* @param Timeout: Specify Timeout value
* @retval HAL status
*/
HAL_StatusTypeDef HAL_CRYP_DESCBC_Encrypt(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData, uint32_t Timeout)
{
/* Process Locked */
__HAL_LOCK(hcryp);
/* Change the CRYP state */
hcryp->State = HAL_CRYP_STATE_BUSY;
/* Set CRYP peripheral in DES CBC encryption mode */
CRYP_SetDESCBCMode(hcryp, 0);
/* Enable CRYP */
__HAL_CRYP_ENABLE(hcryp);
/* Write Plain Data and Get Cypher Data */
if(CRYP_ProcessData2Words(hcryp, pPlainData, Size, pCypherData, Timeout) != HAL_OK)
{
return HAL_TIMEOUT;
}
/* Change the CRYP state */
hcryp->State = HAL_CRYP_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hcryp);
/* Return function status */
return HAL_OK;
}
/**
* @brief Initializes the CRYP peripheral in DES ECB decryption mode.
* @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module
* @param pPlainData: Pointer to the plaintext buffer
* @param Size: Length of the plaintext buffer, must be a multiple of 8
* @param pCypherData: Pointer to the cyphertext buffer
* @param Timeout: Specify Timeout value
* @retval HAL status
*/
HAL_StatusTypeDef HAL_CRYP_DESCBC_Decrypt(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData, uint32_t Timeout)
{
/* Process Locked */
__HAL_LOCK(hcryp);
/* Change the CRYP state */
hcryp->State = HAL_CRYP_STATE_BUSY;
/* Set CRYP peripheral in DES CBC decryption mode */
CRYP_SetDESCBCMode(hcryp, CRYP_CR_ALGODIR);
/* Enable CRYP */
__HAL_CRYP_ENABLE(hcryp);
/* Write Plain Data and Get Cypher Data */
if(CRYP_ProcessData2Words(hcryp, pPlainData, Size, pCypherData, Timeout) != HAL_OK)
{
return HAL_TIMEOUT;
}
/* Change the CRYP state */
hcryp->State = HAL_CRYP_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hcryp);
/* Return function status */
return HAL_OK;
}
/**
* @brief Initializes the CRYP peripheral in DES ECB encryption mode using IT.
* @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module
* @param pPlainData: Pointer to the plaintext buffer
* @param Size: Length of the plaintext buffer, must be a multiple of 8
* @param pCypherData: Pointer to the cyphertext buffer
* @retval HAL status
*/
HAL_StatusTypeDef HAL_CRYP_DESECB_Encrypt_IT(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData)
{
uint32_t inputaddr;
uint32_t outputaddr;
if(hcryp->State == HAL_CRYP_STATE_READY)
{
/* Process Locked */
__HAL_LOCK(hcryp);
hcryp->CrypInCount = Size;
hcryp->pCrypInBuffPtr = pPlainData;
hcryp->pCrypOutBuffPtr = pCypherData;
hcryp->CrypOutCount = Size;
/* Change the CRYP state */
hcryp->State = HAL_CRYP_STATE_BUSY;
/* Set CRYP peripheral in DES ECB encryption mode */
CRYP_SetDESECBMode(hcryp, 0);
/* Enable Interrupts */
__HAL_CRYP_ENABLE_IT(hcryp, CRYP_IT_INI | CRYP_IT_OUTI);
/* Enable CRYP */
__HAL_CRYP_ENABLE(hcryp);
/* Return function status */
return HAL_OK;
}
else if(__HAL_CRYP_GET_IT(hcryp, CRYP_IT_INI))
{
inputaddr = (uint32_t)hcryp->pCrypInBuffPtr;
/* Write the Input block in the IN FIFO */
hcryp->Instance->DR = *(uint32_t*)(inputaddr);
inputaddr+=4;
hcryp->Instance->DR = *(uint32_t*)(inputaddr);
hcryp->pCrypInBuffPtr += 8;
hcryp->CrypInCount -= 8;
if(hcryp->CrypInCount == 0)
{
__HAL_CRYP_DISABLE_IT(hcryp, CRYP_IT_INI);
/* Call the Input data transfer complete callback */
HAL_CRYP_InCpltCallback(hcryp);
}
}
else if(__HAL_CRYP_GET_IT(hcryp, CRYP_IT_OUTI))
{
outputaddr = (uint32_t)hcryp->pCrypOutBuffPtr;
/* Read the Output block from the Output FIFO */
*(uint32_t*)(outputaddr) = hcryp->Instance->DOUT;
outputaddr+=4;
*(uint32_t*)(outputaddr) = hcryp->Instance->DOUT;
hcryp->pCrypOutBuffPtr += 8;
hcryp->CrypOutCount -= 8;
if(hcryp->CrypOutCount == 0)
{
/* Disable IT */
__HAL_CRYP_DISABLE_IT(hcryp, CRYP_IT_OUTI);
/* Disable CRYP */
__HAL_CRYP_DISABLE(hcryp);
/* Process Unlocked */
__HAL_UNLOCK(hcryp);
/* Change the CRYP state */
hcryp->State = HAL_CRYP_STATE_READY;
/* Call Input transfer complete callback */
HAL_CRYP_OutCpltCallback(hcryp);
}
}
/* Return function status */
return HAL_OK;
}
/**
* @brief Initializes the CRYP peripheral in DES CBC encryption mode using interrupt.
* @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module
* @param pPlainData: Pointer to the plaintext buffer
* @param Size: Length of the plaintext buffer, must be a multiple of 8
* @param pCypherData: Pointer to the cyphertext buffer
* @retval HAL status
*/
HAL_StatusTypeDef HAL_CRYP_DESCBC_Encrypt_IT(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData)
{
uint32_t inputaddr;
uint32_t outputaddr;
if(hcryp->State == HAL_CRYP_STATE_READY)
{
/* Process Locked */
__HAL_LOCK(hcryp);
hcryp->CrypInCount = Size;
hcryp->pCrypInBuffPtr = pPlainData;
hcryp->pCrypOutBuffPtr = pCypherData;
hcryp->CrypOutCount = Size;
/* Change the CRYP state */
hcryp->State = HAL_CRYP_STATE_BUSY;
/* Set CRYP peripheral in DES CBC encryption mode */
CRYP_SetDESCBCMode(hcryp, 0);
/* Enable Interrupts */
__HAL_CRYP_ENABLE_IT(hcryp, CRYP_IT_INI | CRYP_IT_OUTI);
/* Enable CRYP */
__HAL_CRYP_ENABLE(hcryp);
/* Return function status */
return HAL_OK;
}
else if(__HAL_CRYP_GET_IT(hcryp, CRYP_IT_INI))
{
inputaddr = (uint32_t)hcryp->pCrypInBuffPtr;
/* Write the Input block in the IN FIFO */
hcryp->Instance->DR = *(uint32_t*)(inputaddr);
inputaddr+=4;
hcryp->Instance->DR = *(uint32_t*)(inputaddr);
hcryp->pCrypInBuffPtr += 8;
hcryp->CrypInCount -= 8;
if(hcryp->CrypInCount == 0)
{
__HAL_CRYP_DISABLE_IT(hcryp, CRYP_IT_INI);
/* Call the Input data transfer complete callback */
HAL_CRYP_InCpltCallback(hcryp);
}
}
else if(__HAL_CRYP_GET_IT(hcryp, CRYP_IT_OUTI))
{
outputaddr = (uint32_t)hcryp->pCrypOutBuffPtr;
/* Read the Output block from the Output FIFO */
*(uint32_t*)(outputaddr) = hcryp->Instance->DOUT;
outputaddr+=4;
*(uint32_t*)(outputaddr) = hcryp->Instance->DOUT;
hcryp->pCrypOutBuffPtr += 8;
hcryp->CrypOutCount -= 8;
if(hcryp->CrypOutCount == 0)
{
/* Disable IT */
__HAL_CRYP_DISABLE_IT(hcryp, CRYP_IT_OUTI);
/* Disable CRYP */
__HAL_CRYP_DISABLE(hcryp);
/* Process Unlocked */
__HAL_UNLOCK(hcryp);
/* Change the CRYP state */
hcryp->State = HAL_CRYP_STATE_READY;
/* Call Input transfer complete callback */
HAL_CRYP_OutCpltCallback(hcryp);
}
}
/* Return function status */
return HAL_OK;
}
/**
* @brief Initializes the CRYP peripheral in DES ECB decryption mode using IT.
* @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module
* @param pPlainData: Pointer to the plaintext buffer
* @param Size: Length of the plaintext buffer, must be a multiple of 8
* @param pCypherData: Pointer to the cyphertext buffer
* @retval HAL status
*/
HAL_StatusTypeDef HAL_CRYP_DESECB_Decrypt_IT(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData)
{
uint32_t inputaddr;
uint32_t outputaddr;
if(hcryp->State == HAL_CRYP_STATE_READY)
{
/* Process Locked */
__HAL_LOCK(hcryp);
hcryp->CrypInCount = Size;
hcryp->pCrypInBuffPtr = pCypherData;
hcryp->pCrypOutBuffPtr = pPlainData;
hcryp->CrypOutCount = Size;
/* Change the CRYP state */
hcryp->State = HAL_CRYP_STATE_BUSY;
/* Set CRYP peripheral in DES ECB decryption mode */
CRYP_SetDESECBMode(hcryp, CRYP_CR_ALGODIR);
/* Enable Interrupts */
__HAL_CRYP_ENABLE_IT(hcryp, CRYP_IT_INI | CRYP_IT_OUTI);
/* Enable CRYP */
__HAL_CRYP_ENABLE(hcryp);
/* Return function status */
return HAL_OK;
}
else if(__HAL_CRYP_GET_IT(hcryp, CRYP_IT_INI))
{
inputaddr = (uint32_t)hcryp->pCrypInBuffPtr;
/* Write the Input block in the IN FIFO */
hcryp->Instance->DR = *(uint32_t*)(inputaddr);
inputaddr+=4;
hcryp->Instance->DR = *(uint32_t*)(inputaddr);
hcryp->pCrypInBuffPtr += 8;
hcryp->CrypInCount -= 8;
if(hcryp->CrypInCount == 0)
{
__HAL_CRYP_DISABLE_IT(hcryp, CRYP_IT_INI);
/* Call the Input data transfer complete callback */
HAL_CRYP_InCpltCallback(hcryp);
}
}
else if(__HAL_CRYP_GET_IT(hcryp, CRYP_IT_OUTI))
{
outputaddr = (uint32_t)hcryp->pCrypOutBuffPtr;
/* Read the Output block from the Output FIFO */
*(uint32_t*)(outputaddr) = hcryp->Instance->DOUT;
outputaddr+=4;
*(uint32_t*)(outputaddr) = hcryp->Instance->DOUT;
hcryp->pCrypOutBuffPtr += 8;
hcryp->CrypOutCount -= 8;
if(hcryp->CrypOutCount == 0)
{
/* Disable IT */
__HAL_CRYP_DISABLE_IT(hcryp, CRYP_IT_OUTI);
/* Disable CRYP */
__HAL_CRYP_DISABLE(hcryp);
/* Process Unlocked */
__HAL_UNLOCK(hcryp);
/* Change the CRYP state */
hcryp->State = HAL_CRYP_STATE_READY;
/* Call Input transfer complete callback */
HAL_CRYP_OutCpltCallback(hcryp);
}
}
/* Return function status */
return HAL_OK;
}
/**
* @brief Initializes the CRYP peripheral in DES ECB decryption mode using interrupt.
* @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module
* @param pPlainData: Pointer to the plaintext buffer
* @param Size: Length of the plaintext buffer, must be a multiple of 8
* @param pCypherData: Pointer to the cyphertext buffer
* @retval HAL status
*/
HAL_StatusTypeDef HAL_CRYP_DESCBC_Decrypt_IT(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData)
{
uint32_t inputaddr;
uint32_t outputaddr;
if(hcryp->State == HAL_CRYP_STATE_READY)
{
/* Process Locked */
__HAL_LOCK(hcryp);
hcryp->CrypInCount = Size;
hcryp->pCrypInBuffPtr = pCypherData;
hcryp->pCrypOutBuffPtr = pPlainData;
hcryp->CrypOutCount = Size;
/* Change the CRYP state */
hcryp->State = HAL_CRYP_STATE_BUSY;
/* Set CRYP peripheral in DES CBC decryption mode */
CRYP_SetDESCBCMode(hcryp, CRYP_CR_ALGODIR);
/* Enable Interrupts */
__HAL_CRYP_ENABLE_IT(hcryp, CRYP_IT_INI | CRYP_IT_OUTI);
/* Enable CRYP */
__HAL_CRYP_ENABLE(hcryp);
/* Return function status */
return HAL_OK;
}
else if(__HAL_CRYP_GET_IT(hcryp, CRYP_IT_INI))
{
inputaddr = (uint32_t)hcryp->pCrypInBuffPtr;
/* Write the Input block in the IN FIFO */
hcryp->Instance->DR = *(uint32_t*)(inputaddr);
inputaddr+=4;
hcryp->Instance->DR = *(uint32_t*)(inputaddr);
hcryp->pCrypInBuffPtr += 8;
hcryp->CrypInCount -= 8;
if(hcryp->CrypInCount == 0)
{
__HAL_CRYP_DISABLE_IT(hcryp, CRYP_IT_INI);
/* Call the Input data transfer complete callback */
HAL_CRYP_InCpltCallback(hcryp);
}
}
else if(__HAL_CRYP_GET_IT(hcryp, CRYP_IT_OUTI))
{
outputaddr = (uint32_t)hcryp->pCrypOutBuffPtr;
/* Read the Output block from the Output FIFO */
*(uint32_t*)(outputaddr) = hcryp->Instance->DOUT;
outputaddr+=4;
*(uint32_t*)(outputaddr) = hcryp->Instance->DOUT;
hcryp->pCrypOutBuffPtr += 8;
hcryp->CrypOutCount -= 8;
if(hcryp->CrypOutCount == 0)
{
/* Disable IT */
__HAL_CRYP_DISABLE_IT(hcryp, CRYP_IT_OUTI);
/* Disable CRYP */
__HAL_CRYP_DISABLE(hcryp);
/* Process Unlocked */
__HAL_UNLOCK(hcryp);
/* Change the CRYP state */
hcryp->State = HAL_CRYP_STATE_READY;
/* Call Input transfer complete callback */
HAL_CRYP_OutCpltCallback(hcryp);
}
}
/* Return function status */
return HAL_OK;
}
/**
* @brief Initializes the CRYP peripheral in DES ECB encryption mode using DMA.
* @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module
* @param pPlainData: Pointer to the plaintext buffer
* @param Size: Length of the plaintext buffer, must be a multiple of 8
* @param pCypherData: Pointer to the cyphertext buffer
* @retval HAL status
*/
HAL_StatusTypeDef HAL_CRYP_DESECB_Encrypt_DMA(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData)
{
uint32_t inputaddr;
uint32_t outputaddr;
if((hcryp->State == HAL_CRYP_STATE_READY) || (hcryp->Phase == HAL_CRYP_PHASE_PROCESS))
{
/* Process Locked */
__HAL_LOCK(hcryp);
inputaddr = (uint32_t)pPlainData;
outputaddr = (uint32_t)pCypherData;
/* Change the CRYP state */
hcryp->State = HAL_CRYP_STATE_BUSY;
/* Set CRYP peripheral in DES ECB encryption mode */
CRYP_SetDESECBMode(hcryp, 0);
/* Set the input and output addresses and start DMA transfer */
CRYP_SetDMAConfig(hcryp, inputaddr, Size, outputaddr);
/* Process Unlocked */
__HAL_UNLOCK(hcryp);
/* Return function status */
return HAL_OK;
}
else
{
return HAL_ERROR;
}
}
/**
* @brief Initializes the CRYP peripheral in DES CBC encryption mode using DMA.
* @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module
* @param pPlainData: Pointer to the plaintext buffer
* @param Size: Length of the plaintext buffer, must be a multiple of 8
* @param pCypherData: Pointer to the cyphertext buffer
* @retval HAL status
*/
HAL_StatusTypeDef HAL_CRYP_DESCBC_Encrypt_DMA(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData)
{
uint32_t inputaddr;
uint32_t outputaddr;
if((hcryp->State == HAL_CRYP_STATE_READY) || (hcryp->Phase == HAL_CRYP_PHASE_PROCESS))
{
/* Process Locked */
__HAL_LOCK(hcryp);
inputaddr = (uint32_t)pPlainData;
outputaddr = (uint32_t)pCypherData;
/* Change the CRYP state */
hcryp->State = HAL_CRYP_STATE_BUSY;
/* Set CRYP peripheral in DES CBC encryption mode */
CRYP_SetDESCBCMode(hcryp, 0);
/* Set the input and output addresses and start DMA transfer */
CRYP_SetDMAConfig(hcryp, inputaddr, Size, outputaddr);
/* Process Unlocked */
__HAL_UNLOCK(hcryp);
/* Return function status */
return HAL_OK;
}
else
{
return HAL_ERROR;
}
}
/**
* @brief Initializes the CRYP peripheral in DES ECB decryption mode using DMA.
* @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module
* @param pPlainData: Pointer to the plaintext buffer
* @param Size: Length of the plaintext buffer, must be a multiple of 8
* @param pCypherData: Pointer to the cyphertext buffer
* @retval HAL status
*/
HAL_StatusTypeDef HAL_CRYP_DESECB_Decrypt_DMA(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData)
{
uint32_t inputaddr;
uint32_t outputaddr;
if((hcryp->State == HAL_CRYP_STATE_READY) || (hcryp->Phase == HAL_CRYP_PHASE_PROCESS))
{
/* Process Locked */
__HAL_LOCK(hcryp);
inputaddr = (uint32_t)pCypherData;
outputaddr = (uint32_t)pPlainData;
/* Change the CRYP state */
hcryp->State = HAL_CRYP_STATE_BUSY;
/* Set CRYP peripheral in DES ECB decryption mode */
CRYP_SetDESECBMode(hcryp, CRYP_CR_ALGODIR);
/* Set the input and output addresses and start DMA transfer */
CRYP_SetDMAConfig(hcryp, inputaddr, Size, outputaddr);
/* Process Unlocked */
__HAL_UNLOCK(hcryp);
/* Return function status */
return HAL_OK;
}
else
{
return HAL_ERROR;
}
}
/**
* @brief Initializes the CRYP peripheral in DES ECB decryption mode using DMA.
* @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module
* @param pPlainData: Pointer to the plaintext buffer
* @param Size: Length of the plaintext buffer, must be a multiple of 8
* @param pCypherData: Pointer to the cyphertext buffer
* @retval HAL status
*/
HAL_StatusTypeDef HAL_CRYP_DESCBC_Decrypt_DMA(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData)
{
uint32_t inputaddr;
uint32_t outputaddr;
if((hcryp->State == HAL_CRYP_STATE_READY) || (hcryp->Phase == HAL_CRYP_PHASE_PROCESS))
{
/* Process Locked */
__HAL_LOCK(hcryp);
inputaddr = (uint32_t)pCypherData;
outputaddr = (uint32_t)pPlainData;
/* Change the CRYP state */
hcryp->State = HAL_CRYP_STATE_BUSY;
/* Set CRYP peripheral in DES CBC decryption mode */
CRYP_SetDESCBCMode(hcryp, CRYP_CR_ALGODIR);
/* Set the input and output addresses and start DMA transfer */
CRYP_SetDMAConfig(hcryp, inputaddr, Size, outputaddr);
/* Process Unlocked */
__HAL_UNLOCK(hcryp);
/* Return function status */
return HAL_OK;
}
else
{
return HAL_ERROR;
}
}
/**
* @}
*/
/** @defgroup CRYP_Exported_Functions_Group4 TDES processing functions
* @brief processing functions.
*
@verbatim
==============================================================================
##### TDES processing functions #####
==============================================================================
[..] This section provides functions allowing to:
(+) Encrypt plaintext using TDES based on ECB or CBC chaining modes
(+) Decrypt cyphertext using TDES based on ECB or CBC chaining modes
[..] Three processing functions are available:
(+) Polling mode
(+) Interrupt mode
(+) DMA mode
@endverbatim
* @{
*/
/**
* @brief Initializes the CRYP peripheral in TDES ECB encryption mode
* then encrypt pPlainData. The cypher data are available in pCypherData
* @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module
* @param pPlainData: Pointer to the plaintext buffer
* @param Size: Length of the plaintext buffer, must be a multiple of 8
* @param pCypherData: Pointer to the cyphertext buffer
* @param Timeout: Specify Timeout value
* @retval HAL status
*/
HAL_StatusTypeDef HAL_CRYP_TDESECB_Encrypt(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData, uint32_t Timeout)
{
/* Process Locked */
__HAL_LOCK(hcryp);
/* Change the CRYP state */
hcryp->State = HAL_CRYP_STATE_BUSY;
/* Set CRYP peripheral in TDES ECB encryption mode */
CRYP_SetTDESECBMode(hcryp, 0);
/* Enable CRYP */
__HAL_CRYP_ENABLE(hcryp);
/* Write Plain Data and Get Cypher Data */
if(CRYP_ProcessData2Words(hcryp, pPlainData, Size, pCypherData, Timeout) != HAL_OK)
{
return HAL_TIMEOUT;
}
/* Change the CRYP state */
hcryp->State = HAL_CRYP_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hcryp);
/* Return function status */
return HAL_OK;
}
/**
* @brief Initializes the CRYP peripheral in TDES ECB decryption mode
* then decrypted pCypherData. The cypher data are available in pPlainData
* @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module
* @param pPlainData: Pointer to the plaintext buffer
* @param Size: Length of the plaintext buffer, must be a multiple of 8
* @param pCypherData: Pointer to the cyphertext buffer
* @param Timeout: Specify Timeout value
* @retval HAL status
*/
HAL_StatusTypeDef HAL_CRYP_TDESECB_Decrypt(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData, uint32_t Timeout)
{
/* Process Locked */
__HAL_LOCK(hcryp);
/* Change the CRYP state */
hcryp->State = HAL_CRYP_STATE_BUSY;
/* Set CRYP peripheral in TDES ECB decryption mode */
CRYP_SetTDESECBMode(hcryp, CRYP_CR_ALGODIR);
/* Enable CRYP */
__HAL_CRYP_ENABLE(hcryp);
/* Write Cypher Data and Get Plain Data */
if(CRYP_ProcessData2Words(hcryp, pCypherData, Size, pPlainData, Timeout) != HAL_OK)
{
return HAL_TIMEOUT;
}
/* Change the CRYP state */
hcryp->State = HAL_CRYP_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hcryp);
/* Return function status */
return HAL_OK;
}
/**
* @brief Initializes the CRYP peripheral in TDES CBC encryption mode
* then encrypt pPlainData. The cypher data are available in pCypherData
* @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module
* @param pPlainData: Pointer to the plaintext buffer
* @param Size: Length of the plaintext buffer, must be a multiple of 8
* @param pCypherData: Pointer to the cyphertext buffer
* @param Timeout: Specify Timeout value
* @retval HAL status
*/
HAL_StatusTypeDef HAL_CRYP_TDESCBC_Encrypt(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData, uint32_t Timeout)
{
/* Process Locked */
__HAL_LOCK(hcryp);
/* Change the CRYP state */
hcryp->State = HAL_CRYP_STATE_BUSY;
/* Set CRYP peripheral in TDES CBC encryption mode */
CRYP_SetTDESCBCMode(hcryp, 0);
/* Enable CRYP */
__HAL_CRYP_ENABLE(hcryp);
/* Write Plain Data and Get Cypher Data */
if(CRYP_ProcessData2Words(hcryp, pPlainData, Size, pCypherData, Timeout) != HAL_OK)
{
return HAL_TIMEOUT;
}
/* Change the CRYP state */
hcryp->State = HAL_CRYP_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hcryp);
/* Return function status */
return HAL_OK;
}
/**
* @brief Initializes the CRYP peripheral in TDES CBC decryption mode
* then decrypted pCypherData. The cypher data are available in pPlainData
* @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module
* @param pCypherData: Pointer to the cyphertext buffer
* @param Size: Length of the plaintext buffer, must be a multiple of 8
* @param pPlainData: Pointer to the plaintext buffer
* @param Timeout: Specify Timeout value
* @retval HAL status
*/
HAL_StatusTypeDef HAL_CRYP_TDESCBC_Decrypt(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData, uint32_t Timeout)
{
/* Process Locked */
__HAL_LOCK(hcryp);
/* Change the CRYP state */
hcryp->State = HAL_CRYP_STATE_BUSY;
/* Set CRYP peripheral in TDES CBC decryption mode */
CRYP_SetTDESCBCMode(hcryp, CRYP_CR_ALGODIR);
/* Enable CRYP */
__HAL_CRYP_ENABLE(hcryp);
/* Write Cypher Data and Get Plain Data */
if(CRYP_ProcessData2Words(hcryp, pCypherData, Size, pPlainData, Timeout) != HAL_OK)
{
return HAL_TIMEOUT;
}
/* Change the CRYP state */
hcryp->State = HAL_CRYP_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hcryp);
/* Return function status */
return HAL_OK;
}
/**
* @brief Initializes the CRYP peripheral in TDES ECB encryption mode using interrupt.
* @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module
* @param pPlainData: Pointer to the plaintext buffer
* @param Size: Length of the plaintext buffer, must be a multiple of 8
* @param pCypherData: Pointer to the cyphertext buffer
* @retval HAL status
*/
HAL_StatusTypeDef HAL_CRYP_TDESECB_Encrypt_IT(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData)
{
uint32_t inputaddr;
uint32_t outputaddr;
if(hcryp->State == HAL_CRYP_STATE_READY)
{
/* Process Locked */
__HAL_LOCK(hcryp);
hcryp->CrypInCount = Size;
hcryp->pCrypInBuffPtr = pPlainData;
hcryp->pCrypOutBuffPtr = pCypherData;
hcryp->CrypOutCount = Size;
/* Change the CRYP state */
hcryp->State = HAL_CRYP_STATE_BUSY;
/* Set CRYP peripheral in TDES ECB encryption mode */
CRYP_SetTDESECBMode(hcryp, 0);
/* Enable Interrupts */
__HAL_CRYP_ENABLE_IT(hcryp, CRYP_IT_INI | CRYP_IT_OUTI);
/* Enable CRYP */
__HAL_CRYP_ENABLE(hcryp);
/* Return function status */
return HAL_OK;
}
else if(__HAL_CRYP_GET_IT(hcryp, CRYP_IT_INI))
{
inputaddr = (uint32_t)hcryp->pCrypInBuffPtr;
/* Write the Input block in the IN FIFO */
hcryp->Instance->DR = *(uint32_t*)(inputaddr);
inputaddr+=4;
hcryp->Instance->DR = *(uint32_t*)(inputaddr);
hcryp->pCrypInBuffPtr += 8;
hcryp->CrypInCount -= 8;
if(hcryp->CrypInCount == 0)
{
__HAL_CRYP_DISABLE_IT(hcryp, CRYP_IT_INI);
/* Call the Input data transfer complete callback */
HAL_CRYP_InCpltCallback(hcryp);
}
}
else if(__HAL_CRYP_GET_IT(hcryp, CRYP_IT_OUTI))
{
outputaddr = (uint32_t)hcryp->pCrypOutBuffPtr;
/* Read the Output block from the Output FIFO */
*(uint32_t*)(outputaddr) = hcryp->Instance->DOUT;
outputaddr+=4;
*(uint32_t*)(outputaddr) = hcryp->Instance->DOUT;
hcryp->pCrypOutBuffPtr += 8;
hcryp->CrypOutCount -= 8;
if(hcryp->CrypOutCount == 0)
{
/* Disable IT */
__HAL_CRYP_DISABLE_IT(hcryp, CRYP_IT_OUTI);
/* Disable CRYP */
__HAL_CRYP_DISABLE(hcryp);
/* Process Unlocked */
__HAL_UNLOCK(hcryp);
/* Change the CRYP state */
hcryp->State = HAL_CRYP_STATE_READY;
/* Call the Output data transfer complete callback */
HAL_CRYP_OutCpltCallback(hcryp);
}
}
/* Return function status */
return HAL_OK;
}
/**
* @brief Initializes the CRYP peripheral in TDES CBC encryption mode.
* @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module
* @param pPlainData: Pointer to the plaintext buffer
* @param Size: Length of the plaintext buffer, must be a multiple of 8
* @param pCypherData: Pointer to the cyphertext buffer
* @retval HAL status
*/
HAL_StatusTypeDef HAL_CRYP_TDESCBC_Encrypt_IT(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData)
{
uint32_t inputaddr;
uint32_t outputaddr;
if(hcryp->State == HAL_CRYP_STATE_READY)
{
/* Process Locked */
__HAL_LOCK(hcryp);
hcryp->CrypInCount = Size;
hcryp->pCrypInBuffPtr = pPlainData;
hcryp->pCrypOutBuffPtr = pCypherData;
hcryp->CrypOutCount = Size;
/* Change the CRYP state */
hcryp->State = HAL_CRYP_STATE_BUSY;
/* Set CRYP peripheral in TDES CBC encryption mode */
CRYP_SetTDESCBCMode(hcryp, 0);
/* Enable Interrupts */
__HAL_CRYP_ENABLE_IT(hcryp, CRYP_IT_INI | CRYP_IT_OUTI);
/* Enable CRYP */
__HAL_CRYP_ENABLE(hcryp);
/* Return function status */
return HAL_OK;
}
else if(__HAL_CRYP_GET_IT(hcryp, CRYP_IT_INI))
{
inputaddr = (uint32_t)hcryp->pCrypInBuffPtr;
/* Write the Input block in the IN FIFO */
hcryp->Instance->DR = *(uint32_t*)(inputaddr);
inputaddr+=4;
hcryp->Instance->DR = *(uint32_t*)(inputaddr);
hcryp->pCrypInBuffPtr += 8;
hcryp->CrypInCount -= 8;
if(hcryp->CrypInCount == 0)
{
__HAL_CRYP_DISABLE_IT(hcryp, CRYP_IT_INI);
/* Call the Input data transfer complete callback */
HAL_CRYP_InCpltCallback(hcryp);
}
}
else if(__HAL_CRYP_GET_IT(hcryp, CRYP_IT_OUTI))
{
outputaddr = (uint32_t)hcryp->pCrypOutBuffPtr;
/* Read the Output block from the Output FIFO */
*(uint32_t*)(outputaddr) = hcryp->Instance->DOUT;
outputaddr+=4;
*(uint32_t*)(outputaddr) = hcryp->Instance->DOUT;
hcryp->pCrypOutBuffPtr += 8;
hcryp->CrypOutCount -= 8;
if(hcryp->CrypOutCount == 0)
{
__HAL_CRYP_DISABLE_IT(hcryp, CRYP_IT_OUTI);
/* Disable CRYP */
__HAL_CRYP_DISABLE(hcryp);
/* Process Unlocked */
__HAL_UNLOCK(hcryp);
/* Change the CRYP state */
hcryp->State = HAL_CRYP_STATE_READY;
/* Call Input transfer complete callback */
HAL_CRYP_OutCpltCallback(hcryp);
}
}
/* Return function status */
return HAL_OK;
}
/**
* @brief Initializes the CRYP peripheral in TDES ECB decryption mode.
* @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module
* @param pPlainData: Pointer to the plaintext buffer
* @param Size: Length of the plaintext buffer, must be a multiple of 8
* @param pCypherData: Pointer to the cyphertext buffer
* @retval HAL status
*/
HAL_StatusTypeDef HAL_CRYP_TDESECB_Decrypt_IT(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData)
{
uint32_t inputaddr;
uint32_t outputaddr;
if(hcryp->State == HAL_CRYP_STATE_READY)
{
/* Process Locked */
__HAL_LOCK(hcryp);
hcryp->CrypInCount = Size;
hcryp->pCrypInBuffPtr = pCypherData;
hcryp->pCrypOutBuffPtr = pPlainData;
hcryp->CrypOutCount = Size;
/* Change the CRYP state */
hcryp->State = HAL_CRYP_STATE_BUSY;
/* Set CRYP peripheral in TDES ECB decryption mode */
CRYP_SetTDESECBMode(hcryp, CRYP_CR_ALGODIR);
/* Enable Interrupts */
__HAL_CRYP_ENABLE_IT(hcryp, CRYP_IT_INI | CRYP_IT_OUTI);
/* Enable CRYP */
__HAL_CRYP_ENABLE(hcryp);
/* Return function status */
return HAL_OK;
}
else if(__HAL_CRYP_GET_IT(hcryp, CRYP_IT_INI))
{
inputaddr = (uint32_t)hcryp->pCrypInBuffPtr;
/* Write the Input block in the IN FIFO */
hcryp->Instance->DR = *(uint32_t*)(inputaddr);
inputaddr+=4;
hcryp->Instance->DR = *(uint32_t*)(inputaddr);
hcryp->pCrypInBuffPtr += 8;
hcryp->CrypInCount -= 8;
if(hcryp->CrypInCount == 0)
{
__HAL_CRYP_DISABLE_IT(hcryp, CRYP_IT_INI);
/* Call the Input data transfer complete callback */
HAL_CRYP_InCpltCallback(hcryp);
}
}
else if(__HAL_CRYP_GET_IT(hcryp, CRYP_IT_OUTI))
{
outputaddr = (uint32_t)hcryp->pCrypOutBuffPtr;
/* Read the Output block from the Output FIFO */
*(uint32_t*)(outputaddr) = hcryp->Instance->DOUT;
outputaddr+=4;
*(uint32_t*)(outputaddr) = hcryp->Instance->DOUT;
hcryp->pCrypOutBuffPtr += 8;
hcryp->CrypOutCount -= 8;
if(hcryp->CrypOutCount == 0)
{
__HAL_CRYP_DISABLE_IT(hcryp, CRYP_IT_OUTI);
/* Disable CRYP */
__HAL_CRYP_DISABLE(hcryp);
/* Process Unlocked */
__HAL_UNLOCK(hcryp);
/* Change the CRYP state */
hcryp->State = HAL_CRYP_STATE_READY;
/* Call Input transfer complete callback */
HAL_CRYP_OutCpltCallback(hcryp);
}
}
/* Return function status */
return HAL_OK;
}
/**
* @brief Initializes the CRYP peripheral in TDES CBC decryption mode.
* @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module
* @param pCypherData: Pointer to the cyphertext buffer
* @param Size: Length of the plaintext buffer, must be a multiple of 8
* @param pPlainData: Pointer to the plaintext buffer
* @retval HAL status
*/
HAL_StatusTypeDef HAL_CRYP_TDESCBC_Decrypt_IT(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData)
{
uint32_t inputaddr;
uint32_t outputaddr;
if(hcryp->State == HAL_CRYP_STATE_READY)
{
/* Process Locked */
__HAL_LOCK(hcryp);
hcryp->CrypInCount = Size;
hcryp->pCrypInBuffPtr = pCypherData;
hcryp->pCrypOutBuffPtr = pPlainData;
hcryp->CrypOutCount = Size;
/* Change the CRYP state */
hcryp->State = HAL_CRYP_STATE_BUSY;
/* Set CRYP peripheral in TDES CBC decryption mode */
CRYP_SetTDESCBCMode(hcryp, CRYP_CR_ALGODIR);
/* Enable Interrupts */
__HAL_CRYP_ENABLE_IT(hcryp, CRYP_IT_INI | CRYP_IT_OUTI);
/* Enable CRYP */
__HAL_CRYP_ENABLE(hcryp);
/* Return function status */
return HAL_OK;
}
else if(__HAL_CRYP_GET_IT(hcryp, CRYP_IT_INI))
{
inputaddr = (uint32_t)hcryp->pCrypInBuffPtr;
/* Write the Input block in the IN FIFO */
hcryp->Instance->DR = *(uint32_t*)(inputaddr);
inputaddr+=4;
hcryp->Instance->DR = *(uint32_t*)(inputaddr);
hcryp->pCrypInBuffPtr += 8;
hcryp->CrypInCount -= 8;
if(hcryp->CrypInCount == 0)
{
__HAL_CRYP_DISABLE_IT(hcryp, CRYP_IT_INI);
/* Call the Input data transfer complete callback */
HAL_CRYP_InCpltCallback(hcryp);
}
}
else if(__HAL_CRYP_GET_IT(hcryp, CRYP_IT_OUTI))
{
outputaddr = (uint32_t)hcryp->pCrypOutBuffPtr;
/* Read the Output block from the Output FIFO */
*(uint32_t*)(outputaddr) = hcryp->Instance->DOUT;
outputaddr+=4;
*(uint32_t*)(outputaddr) = hcryp->Instance->DOUT;
hcryp->pCrypOutBuffPtr += 8;
hcryp->CrypOutCount -= 8;
if(hcryp->CrypOutCount == 0)
{
__HAL_CRYP_DISABLE_IT(hcryp, CRYP_IT_OUTI);
/* Disable CRYP */
__HAL_CRYP_DISABLE(hcryp);
/* Process Unlocked */
__HAL_UNLOCK(hcryp);
/* Change the CRYP state */
hcryp->State = HAL_CRYP_STATE_READY;
/* Call Input transfer complete callback */
HAL_CRYP_OutCpltCallback(hcryp);
}
}
/* Return function status */
return HAL_OK;
}
/**
* @brief Initializes the CRYP peripheral in TDES ECB encryption mode using DMA.
* @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module
* @param pPlainData: Pointer to the plaintext buffer
* @param Size: Length of the plaintext buffer, must be a multiple of 8
* @param pCypherData: Pointer to the cyphertext buffer
* @retval HAL status
*/
HAL_StatusTypeDef HAL_CRYP_TDESECB_Encrypt_DMA(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData)
{
uint32_t inputaddr;
uint32_t outputaddr;
if((hcryp->State == HAL_CRYP_STATE_READY) || (hcryp->Phase == HAL_CRYP_PHASE_PROCESS))
{
/* Process Locked */
__HAL_LOCK(hcryp);
inputaddr = (uint32_t)pPlainData;
outputaddr = (uint32_t)pCypherData;
/* Change the CRYP state */
hcryp->State = HAL_CRYP_STATE_BUSY;
/* Set CRYP peripheral in TDES ECB encryption mode */
CRYP_SetTDESECBMode(hcryp, 0);
/* Set the input and output addresses and start DMA transfer */
CRYP_SetDMAConfig(hcryp, inputaddr, Size, outputaddr);
/* Process Unlocked */
__HAL_UNLOCK(hcryp);
/* Return function status */
return HAL_OK;
}
else
{
return HAL_ERROR;
}
}
/**
* @brief Initializes the CRYP peripheral in TDES CBC encryption mode using DMA.
* @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module
* @param pPlainData: Pointer to the plaintext buffer
* @param Size: Length of the plaintext buffer, must be a multiple of 8
* @param pCypherData: Pointer to the cyphertext buffer
* @retval HAL status
*/
HAL_StatusTypeDef HAL_CRYP_TDESCBC_Encrypt_DMA(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData)
{
uint32_t inputaddr;
uint32_t outputaddr;
if((hcryp->State == HAL_CRYP_STATE_READY) || (hcryp->Phase == HAL_CRYP_PHASE_PROCESS))
{
/* Process Locked */
__HAL_LOCK(hcryp);
inputaddr = (uint32_t)pPlainData;
outputaddr = (uint32_t)pCypherData;
/* Change the CRYP state */
hcryp->State = HAL_CRYP_STATE_BUSY;
/* Set CRYP peripheral in TDES CBC encryption mode */
CRYP_SetTDESCBCMode(hcryp, 0);
/* Set the input and output addresses and start DMA transfer */
CRYP_SetDMAConfig(hcryp, inputaddr, Size, outputaddr);
/* Process Unlocked */
__HAL_UNLOCK(hcryp);
/* Return function status */
return HAL_OK;
}
else
{
return HAL_ERROR;
}
}
/**
* @brief Initializes the CRYP peripheral in TDES ECB decryption mode using DMA.
* @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module
* @param pPlainData: Pointer to the plaintext buffer
* @param Size: Length of the plaintext buffer, must be a multiple of 8
* @param pCypherData: Pointer to the cyphertext buffer
* @retval HAL status
*/
HAL_StatusTypeDef HAL_CRYP_TDESECB_Decrypt_DMA(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData)
{
uint32_t inputaddr;
uint32_t outputaddr;
if((hcryp->State == HAL_CRYP_STATE_READY) || (hcryp->Phase == HAL_CRYP_PHASE_PROCESS))
{
/* Process Locked */
__HAL_LOCK(hcryp);
inputaddr = (uint32_t)pCypherData;
outputaddr = (uint32_t)pPlainData;
/* Change the CRYP state */
hcryp->State = HAL_CRYP_STATE_BUSY;
/* Set CRYP peripheral in TDES ECB decryption mode */
CRYP_SetTDESECBMode(hcryp, CRYP_CR_ALGODIR);
/* Set the input and output addresses and start DMA transfer */
CRYP_SetDMAConfig(hcryp, inputaddr, Size, outputaddr);
/* Process Unlocked */
__HAL_UNLOCK(hcryp);
/* Return function status */
return HAL_OK;
}
else
{
return HAL_ERROR;
}
}
/**
* @brief Initializes the CRYP peripheral in TDES CBC decryption mode using DMA.
* @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module
* @param pCypherData: Pointer to the cyphertext buffer
* @param Size: Length of the plaintext buffer, must be a multiple of 8
* @param pPlainData: Pointer to the plaintext buffer
* @retval HAL status
*/
HAL_StatusTypeDef HAL_CRYP_TDESCBC_Decrypt_DMA(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData)
{
uint32_t inputaddr;
uint32_t outputaddr;
if((hcryp->State == HAL_CRYP_STATE_READY) || (hcryp->Phase == HAL_CRYP_PHASE_PROCESS))
{
/* Process Locked */
__HAL_LOCK(hcryp);
inputaddr = (uint32_t)pCypherData;
outputaddr = (uint32_t)pPlainData;
/* Change the CRYP state */
hcryp->State = HAL_CRYP_STATE_BUSY;
/* Set CRYP peripheral in TDES CBC decryption mode */
CRYP_SetTDESCBCMode(hcryp, CRYP_CR_ALGODIR);
/* Set the input and output addresses and start DMA transfer */
CRYP_SetDMAConfig(hcryp, inputaddr, Size, outputaddr);
/* Process Unlocked */
__HAL_UNLOCK(hcryp);
/* Return function status */
return HAL_OK;
}
else
{
return HAL_ERROR;
}
}
/**
* @}
*/
/** @defgroup CRYP_Exported_Functions_Group5 DMA callback functions
* @brief DMA callback functions.
*
@verbatim
==============================================================================
##### DMA callback functions #####
==============================================================================
[..] This section provides DMA callback functions:
(+) DMA Input data transfer complete
(+) DMA Output data transfer complete
(+) DMA error
@endverbatim
* @{
*/
/**
* @brief Input FIFO transfer completed callbacks.
* @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module
* @retval None
*/
__weak void HAL_CRYP_InCpltCallback(CRYP_HandleTypeDef *hcryp)
{
/* NOTE : This function Should not be modified, when the callback is needed,
the HAL_CRYP_InCpltCallback could be implemented in the user file
*/
}
/**
* @brief Output FIFO transfer completed callbacks.
* @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module
* @retval None
*/
__weak void HAL_CRYP_OutCpltCallback(CRYP_HandleTypeDef *hcryp)
{
/* NOTE : This function Should not be modified, when the callback is needed,
the HAL_CRYP_OutCpltCallback could be implemented in the user file
*/
}
/**
* @brief CRYP error callbacks.
* @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module
* @retval None
*/
__weak void HAL_CRYP_ErrorCallback(CRYP_HandleTypeDef *hcryp)
{
/* NOTE : This function Should not be modified, when the callback is needed,
the HAL_CRYP_ErrorCallback could be implemented in the user file
*/
}
/**
* @}
*/
/** @defgroup CRYP_Exported_Functions_Group6 CRYP IRQ handler management
* @brief CRYP IRQ handler.
*
@verbatim
==============================================================================
##### CRYP IRQ handler management #####
==============================================================================
[..] This section provides CRYP IRQ handler function.
@endverbatim
* @{
*/
/**
* @brief This function handles CRYP interrupt request.
* @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module
* @retval None
*/
void HAL_CRYP_IRQHandler(CRYP_HandleTypeDef *hcryp)
{
switch(CRYP->CR & CRYP_CR_ALGOMODE_DIRECTION)
{
case CRYP_CR_ALGOMODE_TDES_ECB_ENCRYPT:
HAL_CRYP_TDESECB_Encrypt_IT(hcryp, NULL, 0, NULL);
break;
case CRYP_CR_ALGOMODE_TDES_ECB_DECRYPT:
HAL_CRYP_TDESECB_Decrypt_IT(hcryp, NULL, 0, NULL);
break;
case CRYP_CR_ALGOMODE_TDES_CBC_ENCRYPT:
HAL_CRYP_TDESCBC_Encrypt_IT(hcryp, NULL, 0, NULL);
break;
case CRYP_CR_ALGOMODE_TDES_CBC_DECRYPT:
HAL_CRYP_TDESCBC_Decrypt_IT(hcryp, NULL, 0, NULL);
break;
case CRYP_CR_ALGOMODE_DES_ECB_ENCRYPT:
HAL_CRYP_DESECB_Encrypt_IT(hcryp, NULL, 0, NULL);
break;
case CRYP_CR_ALGOMODE_DES_ECB_DECRYPT:
HAL_CRYP_DESECB_Decrypt_IT(hcryp, NULL, 0, NULL);
break;
case CRYP_CR_ALGOMODE_DES_CBC_ENCRYPT:
HAL_CRYP_DESCBC_Encrypt_IT(hcryp, NULL, 0, NULL);
break;
case CRYP_CR_ALGOMODE_DES_CBC_DECRYPT:
HAL_CRYP_DESCBC_Decrypt_IT(hcryp, NULL, 0, NULL);
break;
case CRYP_CR_ALGOMODE_AES_ECB_ENCRYPT:
HAL_CRYP_AESECB_Encrypt_IT(hcryp, NULL, 0, NULL);
break;
case CRYP_CR_ALGOMODE_AES_ECB_DECRYPT:
HAL_CRYP_AESECB_Decrypt_IT(hcryp, NULL, 0, NULL);
break;
case CRYP_CR_ALGOMODE_AES_CBC_ENCRYPT:
HAL_CRYP_AESCBC_Encrypt_IT(hcryp, NULL, 0, NULL);
break;
case CRYP_CR_ALGOMODE_AES_CBC_DECRYPT:
HAL_CRYP_AESCBC_Decrypt_IT(hcryp, NULL, 0, NULL);
break;
case CRYP_CR_ALGOMODE_AES_CTR_ENCRYPT:
HAL_CRYP_AESCTR_Encrypt_IT(hcryp, NULL, 0, NULL);
break;
case CRYP_CR_ALGOMODE_AES_CTR_DECRYPT:
HAL_CRYP_AESCTR_Decrypt_IT(hcryp, NULL, 0, NULL);
break;
default:
break;
}
}
/**
* @}
*/
/** @defgroup CRYP_Exported_Functions_Group7 Peripheral State functions
* @brief Peripheral State functions.
*
@verbatim
==============================================================================
##### Peripheral State functions #####
==============================================================================
[..]
This subsection permits to get in run-time the status of the peripheral.
@endverbatim
* @{
*/
/**
* @brief Returns the CRYP state.
* @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module
* @retval HAL state
*/
HAL_CRYP_STATETypeDef HAL_CRYP_GetState(CRYP_HandleTypeDef *hcryp)
{
return hcryp->State;
}
/**
* @}
*/
/**
* @}
*/
#endif /* STM32F415xx || STM32F417xx || STM32F437xx || STM32F439xx || STM32F479xx */
#endif /* HAL_CRYP_MODULE_ENABLED */
/**
* @}
*/
/**
* @}
*/
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
| {
"content_hash": "4b70fd4981be6b99472e98ba69a4bfea",
"timestamp": "",
"source": "github",
"line_count": 3716,
"max_line_length": 145,
"avg_line_length": 31.6243272335845,
"alnum_prop": 0.6109976513836414,
"repo_name": "janhieber/HTWAA_car_32b",
"id": "06edd1070781f4e5703dfd22f33c9db9f232278d",
"size": "123288",
"binary": false,
"copies": "9",
"ref": "refs/heads/master",
"path": "Test_GPIO/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_cryp.c",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "5121548"
},
{
"name": "C",
"bytes": "84604891"
},
{
"name": "C++",
"bytes": "557070"
},
{
"name": "HTML",
"bytes": "11659"
},
{
"name": "Python",
"bytes": "288"
}
],
"symlink_target": ""
} |
class SS::Migration20211116000000
include SS::Migration::Base
depends_on "20211021000000"
def change
each_file do |file|
file.set(name: SS::FilenameUtils.convert_to_url_safe_japanese(file.basename))
end
end
private
def each_file(&block)
criteria = SS::File.all.exists(name: false)
all_ids = criteria.pluck(:id)
SS::File.each_file(all_ids, &block)
end
end
| {
"content_hash": "0cb95873e2351406e58272b519c73bea",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 83,
"avg_line_length": 21,
"alnum_prop": 0.6842105263157895,
"repo_name": "ShinjiTanimoto/shirasagi",
"id": "de752ad13043638dd10c640c759ae7a6fbc72c59",
"size": "399",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "lib/migrations/ss/20211116000000_set_file_name.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "82226"
},
{
"name": "HTML",
"bytes": "3233606"
},
{
"name": "JavaScript",
"bytes": "11964294"
},
{
"name": "Ruby",
"bytes": "12347112"
},
{
"name": "SCSS",
"bytes": "525875"
},
{
"name": "Shell",
"bytes": "20130"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<appengine-web-app xmlns="http://appengine.google.com/ns/1.0">
<application>myApplicationId</application>
<version>1</version>
<threadsafe>true</threadsafe>
<system-properties>
<property name="java.util.logging.config.file" value="WEB-INF/logging.properties"/>
<!--
TODO: Before you run your application, you need a Google Cloud Messaging API key.
To get one, follow this link, follow the directions and press "Create" at the end:
https://console.developers.google.com/flows/enableapi?apiid=googlecloudmessaging&keyType=SERVER_SIDE&r=0.0.0.0/0
Once you have your API key (which starts with “AIza...”), replace the "gcm.api.key" string in this file.
-->
<property name="gcm.api.key" value="YOUR_KEY_HERE"/>
</system-properties>
</appengine-web-app> | {
"content_hash": "7bbbc6f9d863a9b420b3ca61d48e12d5",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 126,
"avg_line_length": 40.86363636363637,
"alnum_prop": 0.657397107897664,
"repo_name": "ECE2014/ECEMobile",
"id": "c0794881702ffe46c5ff168a07316ebb8ae0cb81",
"size": "903",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "backend/src/main/webapp/WEB-INF/appengine-web.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "6283"
},
{
"name": "Java",
"bytes": "12233"
}
],
"symlink_target": ""
} |
const RuleDefinition = require('../../../../lib/Definitions/RuleDefinition');
class BooleanRule extends RuleDefinition {
constructor(definition) {
super( definition );
this.id = "booleanRule";
this.name = "Boolean Rule";
if(!this.getOnConflict()) this.setOnConflict("standard");
if(!this.getDataType()) this.setDataType("boolean");
}
}
module.exports = BooleanRule;
| {
"content_hash": "49e89c78919ba0929334352ed844de90",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 77,
"avg_line_length": 29.785714285714285,
"alnum_prop": 0.6474820143884892,
"repo_name": "kennethchatfield/rule-evaluator",
"id": "eb381f3583241fed0152128c2fc7743e2b815365",
"size": "418",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/utilities/definitions/rules/BooleanRule.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "138458"
}
],
"symlink_target": ""
} |
SPHINXOPTS = -W
SPHINXBUILD = sphinx-build
PAPER =
BUILDDIR = build
# Internal variables.
PAPEROPT_a4 = -D latex_paper_size=a4
PAPEROPT_letter = -D latex_paper_size=letter
ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source
# the i18n builder cannot share the environment and doctrees with the others
I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source
.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext
help:
@echo "Please use \`make <target>' where <target> is one of"
@echo " html to make standalone HTML files"
@echo " dirhtml to make HTML files named index.html in directories"
@echo " singlehtml to make a single large HTML file"
@echo " pickle to make pickle files"
@echo " json to make JSON files"
@echo " htmlhelp to make HTML files and a HTML help project"
@echo " qthelp to make HTML files and a qthelp project"
@echo " devhelp to make HTML files and a Devhelp project"
@echo " epub to make an epub"
@echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
@echo " latexpdf to make LaTeX files and run them through pdflatex"
@echo " text to make text files"
@echo " man to make manual pages"
@echo " texinfo to make Texinfo files"
@echo " info to make Texinfo files and run them through makeinfo"
@echo " gettext to make PO message catalogs"
@echo " changes to make an overview of all changed/added/deprecated items"
@echo " linkcheck to check all external links for integrity"
@echo " doctest to run all doctests embedded in the documentation (if enabled)"
clean:
-rm -rf $(BUILDDIR)/*
html:
$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
dirhtml:
$(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
singlehtml:
$(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
@echo
@echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
pickle:
$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
@echo
@echo "Build finished; now you can process the pickle files."
json:
$(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
@echo
@echo "Build finished; now you can process the JSON files."
htmlhelp:
$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
@echo
@echo "Build finished; now you can run HTML Help Workshop with the" \
".hhp project file in $(BUILDDIR)/htmlhelp."
qthelp:
$(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
@echo
@echo "Build finished; now you can run "qcollectiongenerator" with the" \
".qhcp project file in $(BUILDDIR)/qthelp, like this:"
@echo "# qcollectiongenerator $(BUILDDIR)/qthelp/emailprocessor.qhcp"
@echo "To view the help file:"
@echo "# assistant -collectionFile $(BUILDDIR)/qthelp/emailprocessor.qhc"
devhelp:
$(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
@echo
@echo "Build finished."
@echo "To view the help file:"
@echo "# mkdir -p $HOME/.local/share/devhelp/emailprocessor"
@echo "# ln -s $(BUILDDIR)/devhelp $HOME/.local/share/devhelp/emailprocessor"
@echo "# devhelp"
epub:
$(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
@echo
@echo "Build finished. The epub file is in $(BUILDDIR)/epub."
latex:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo
@echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
@echo "Run \`make' in that directory to run these through (pdf)latex" \
"(use \`make latexpdf' here to do that automatically)."
latexpdf:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo "Running LaTeX files through pdflatex..."
$(MAKE) -C $(BUILDDIR)/latex all-pdf
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
text:
$(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
@echo
@echo "Build finished. The text files are in $(BUILDDIR)/text."
man:
$(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
@echo
@echo "Build finished. The manual pages are in $(BUILDDIR)/man."
texinfo:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo
@echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
@echo "Run \`make' in that directory to run these through makeinfo" \
"(use \`make info' here to do that automatically)."
info:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo "Running Texinfo files through makeinfo..."
make -C $(BUILDDIR)/texinfo info
@echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."
gettext:
$(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
@echo
@echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."
changes:
$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
@echo
@echo "The overview file is in $(BUILDDIR)/changes."
linkcheck:
$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
@echo
@echo "Link check complete; look for any errors in the above output " \
"or in $(BUILDDIR)/linkcheck/output.txt."
doctest:
$(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
@echo "Testing of doctests in the sources finished, look at the " \
"results in $(BUILDDIR)/doctest/output.txt."
| {
"content_hash": "1aed6aa089927907e547c48c2ac40069",
"timestamp": "",
"source": "github",
"line_count": 149,
"max_line_length": 141,
"avg_line_length": 37.006711409395976,
"alnum_prop": 0.7040261153427638,
"repo_name": "InnovativeTravel/email-processor",
"id": "dcc47365de573e78f609e2db7e0cb05d92e10410",
"size": "5606",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "docs/Makefile",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "29622"
},
{
"name": "Ruby",
"bytes": "3845"
},
{
"name": "Shell",
"bytes": "839"
}
],
"symlink_target": ""
} |
@interface locationModel : NSObject
@property (nonatomic, strong) NSString *address;
@property (nonatomic, assign) CLLocationCoordinate2D coordinate;
@property (nonatomic, strong) NSString *time;
+ (instancetype)LocationWithAddress:(NSString *)address coordinate:(CLLocationCoordinate2D)coordinate time:(NSString *)time;
@end
| {
"content_hash": "8116b0c9b49672c894c1e243b3bc05ec",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 124,
"avg_line_length": 37,
"alnum_prop": 0.7957957957957958,
"repo_name": "SummerHenry/Tool_General",
"id": "58419b1dd0d0ffab486c7f8c82d42663f599458e",
"size": "540",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "yqDemo/yqDemo/Main/Model/locationModel.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C++",
"bytes": "54687"
},
{
"name": "Objective-C",
"bytes": "477731"
},
{
"name": "Objective-C++",
"bytes": "124423"
}
],
"symlink_target": ""
} |
@interface DemoVC2_04 : BABaseViewController
@end
| {
"content_hash": "e18b2130d3f383449d478adfd12aeffc",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 44,
"avg_line_length": 17,
"alnum_prop": 0.803921568627451,
"repo_name": "boai/BABaseProject",
"id": "bc787781b5914c168c4008c09718015d1d1934a1",
"size": "224",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "BABaseProject/BAMainCode/BACode/Message(消息)/DemoVC/DemoVC2-4/DemoVC2_04.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "1847"
},
{
"name": "Objective-C",
"bytes": "2178947"
},
{
"name": "Ruby",
"bytes": "5938"
}
],
"symlink_target": ""
} |
set -x # print cmds
set -e # exit as soon as an error occurs
# log
msg=$(git log --pretty=oneline -1)
echo "Building commit: $msg"
# build
conda build --no-test recipes/pyembree
# install
conda install --use-local pyembree
| {
"content_hash": "8ae3715529eb1f188ef566f861b407b8",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 41,
"avg_line_length": 19.083333333333332,
"alnum_prop": 0.6986899563318777,
"repo_name": "astrohckr/pyembree",
"id": "26dc6f1b5496abedc499f957735ce7b14dbd2818",
"size": "241",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": ".travis-install.sh",
"mode": "33261",
"license": "bsd-2-clause",
"language": [
{
"name": "Batchfile",
"bytes": "33"
},
{
"name": "Objective-C",
"bytes": "747"
},
{
"name": "Python",
"bytes": "30655"
},
{
"name": "Shell",
"bytes": "621"
}
],
"symlink_target": ""
} |
A simple snake game. It has only one level, and no win condition, basically the goal is to get as much points as possible.
Use arrow keys to control the snake.
### Installation
```
npm install
bower install
grunt dist
```
### Run
```
node server.js
open http://localhost:3000/
```
### To do
- add sounds
- add server side with score board
| {
"content_hash": "128e9cc7d6ef91bddc2dd82d72d3c655",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 122,
"avg_line_length": 15.043478260869565,
"alnum_prop": 0.7023121387283237,
"repo_name": "igormilla/phaserjs-snake-game",
"id": "9e53450bb42100aad96d12ee8ba96dae293987cc",
"size": "347",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "588"
},
{
"name": "JavaScript",
"bytes": "12034"
}
],
"symlink_target": ""
} |
The rdoinfo module
==================
rdoinfo module provides a set of methods to interact with metadata files
contained in the repository.
.. automodule:: rdoinfo
:members:
| {
"content_hash": "921f18ecafd098f86bfc238c71cb4eab",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 72,
"avg_line_length": 20.11111111111111,
"alnum_prop": 0.6906077348066298,
"repo_name": "redhat-openstack/rdoinfo",
"id": "e4e154758a6f08dfb469e588eb698e1486a34892",
"size": "181",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "source/rdoinfo_module.rst",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Python",
"bytes": "24067"
}
],
"symlink_target": ""
} |
========
Overview
========
This document is a high-level overview of Trigger's features and a little
history about why it exists in the first place.
About
=====
Trigger is a Python framework and suite of tools for interfacing with network
devices and managing network configuration and security policy. Trigger was
designed to increase the speed and efficiency of network configuration
management.
Trigger's core device interaction utilizes the `Twisted
<http://twistedmatrix.com/>`_ event-driven networking engine. The libraries can
connect to network devices by any available method (e.g. telnet, SSH),
communicate with them in their native interface (e.g. Juniper JunoScript, Cisco
IOS), and return output. Trigger is able to manage any number of jobs in
parallel and handle output or errors as they return.
Motivation
==========
Trigger was created to facilitate rapid provisioning and automation of
firewall policy change requests by Network Security. It has since expanded to
cover all network device configuration.
The complexity of the AOL network was increasing much more quickly than the
amount of time we had to spend on administering it, both because AOL's products
and services were becoming more sophisticated and because we were continually
expanding infrastructure. This pressure created a workload gap that had be
filled with tools that increased productivity.
Pre-Trigger tools worked only for some common cases and required extensive
knowledge of the network, and careful attention during edits and loads.
Sometimes this resulted in a system-impacting errors, and it caused routine
work more dangerous and unrewarding than it should have been.
With the high number of network devices on the AOL network Trigger has become
invaluable to the performance and reliability of the AOL network infrastructure.
History
=======
Trigger was originally written by the AOL Network Security team and
is now maintained by the Network Engineering organization.
Once upon a time Trigger was actually called **SIMIAN**, a really bad acronym
that stood for **System Integrating Management of Individual Access to
Networks**. It has since outgrown its original purpose and can be used for any
network hardware configuration management operations, so we decided to ditch
the acronym and just go with a name that more accurately hints at what it does.
Components
==========
Trigger is comprised of the following core components:
NetDevices
----------
An abstract interface to network device metadata and security policy associations.
Twister
-------
Asynchronous device interaction library. Performs login and basic command-line
interaction support via telnet or SSH using the Twisted asynchronous I/O
framework.
Access-List Parser
------------------
An ACL parsing library which contains various modules that allow for parsing,
manipulation, and management of network access control lists (ACLs). It will
parse a complete ACL and return an ACL object that can be easily translated to
any supported vendor syntax.
+ Converting ACLs from one format to another (e.g. Cisco to Juniper)
+ Testing an ACL to determine is access is permitted
+ Automatically associate ACLs to devices by metatdata
Change Management
-----------------
An abstract interface to bounce windows and moratoria. Includes support for RCS
version-control system for maintaining configuration data and an integrated
automated task queue.
Commands
--------
Command execution library which abstracts the execution of commands on network
devices. Allows for integrated parsing and manipulation of return data for
rapid integration to existing or newly created tools.
TACACSrc
--------
Network credentials library that provides an abstract interface to storing user
credentials encrypted on disk.
Command-Line Tools
------------------
Trigger includes a suite of tools for simplifying many common tasks, including:
+ Quickly get an interactive shell
+ Simple metadata search tool
| {
"content_hash": "520d04aa554286c15c0f7f75029efc91",
"timestamp": "",
"source": "github",
"line_count": 112,
"max_line_length": 82,
"avg_line_length": 35.473214285714285,
"alnum_prop": 0.7903347596274856,
"repo_name": "johnfzc/trigger",
"id": "f1a23ee514cdb5e25d6662fac3ad872dec932fc7",
"size": "3973",
"binary": false,
"copies": "6",
"ref": "refs/heads/develop",
"path": "docs/overview.rst",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Python",
"bytes": "902675"
},
{
"name": "Shell",
"bytes": "1300"
}
],
"symlink_target": ""
} |
exportiphoto
============
Exports an iPhoto library to a folder structure, optionally writing
metadata to the copies.
This script has been tested with iPhoto 8.1.2 (from iLife '09); other versions
may or may not work.
Originally written by [Derrick Childers](https://github.com/derrickchilders) and
[posted to macosxhints](http://www.macosxhints.com/article.php?story=20081108132735425).
Modifications by
[Guillaume Boudreau](http://github.com/gboudreau),
[Brian Morearty](http://github.com/BMorearty),
[Mark Nottingham](http://github.com/mnot),
[Duoglas Du](http://github.com/duoglas),
[Avinash Meetoo](http://github.com/avinash), and
[J.G. Field](http://gitub.com/jgfield)
iPhoto can do this now
----------------------
Great news. If you upgrade to iPhoto 9.4.3 or later, [you can export
dirctly out of iPhoto to a folder
structure](https://discussions.apple.com/message/24759040#24759040). You don't need to use
exportiphoto.
Here's how:
1. Choose File → Export from the menu.
2. Choose Kind: Original or JPEG. If you want the original picture at
their original resolution, use Original. If you want to include all
edits, use JPEG and check both checkboxes to get the keywords,
titles, etc. included in the file.
3. Choose Subfolder Format: Event Name.

Installation
------------
Run Terminal and enter this command:
curl https://raw.github.com/BMorearty/exportiphoto/master/exportiphoto.py > exportiphoto.py
This copies exportiphoto.py to your Home folder. Actually you can put it
anywhere you want.
Usage
-----
1. Run this:
python exportiphoto.py [options] "iPhoto-Library-dir" "destination-dir"
See example below.
Options include:
-a, --albums use albums instead of events
-m, --metadata write metadata to images
-f, --faces store faces as keywords (requires -m)
-q, --quiet use quiet mode
-d, --date stop using date prefix in folder name
-o, --originals export original images instead of edited ones
-x, --deconflict deconflict export directories of same name (without
this, two events with the same name on the same date
are merged.)
-y, --yeardir add year directory to output
-e DATE_DELIMITER, --date_delimiter=DATE_DELIMITER
date delimiter default=-
-i, --import import missing albums from dest directory
-z IMPORT_FROM_DATE, --import_from_date=IMPORT_FROM_DATE
only import missing folers if folder date occurs after
(YYYY-MM-DD). Uses date in folder name.
-t, --test dont actually copy files or import folders
2. There is no step 2
Note that the -m flag is only available if extra libraries are installed;
see below.
If you are facing encoding problems like "UnicodeEncodeError", try -q flag to stop the console output;
Output
------
By default, exportiphoto exports Events. It can export Albums instead; use
the -a option on the command line.
It creates a separate folder on disk for each event. Every folder is prefixed
by the event date in this format: yyyy-mm-dd (because this format is sortable by name)
unless you use the -d option.
If the event has a name it is appended to the end of the folder name.
Example
-------
Let's say you have the following events in iPhoto--two unnamed and one named:
Jun 10, 2009
Charlie's Birthday Party
Jun 20, 2009
Run:
python exportiphoto.py "$HOME/Pictures/iPhoto Library/" "$HOME/iPhoto Export"
If Charlie's birthday party was on June 15th, the output folders will be:
2009-06-10
2009-06-15 Charlie's Birthday Party
2009-06-20
If you set the -d option to turn off the prepended date, the folder names will be:
Jun 10, 2009
Charlie's Birthday Party
Jun 20, 2009
Writing Metadata
----------------
If pyexiv2 is installed, exportiphoto can write iPhoto metadata into
images as they're exported, with the -m option. Currently, it writes:
- iPhoto image name to Iptc.Application2.Headline
- iPhoto description to Iptc.Application2.Caption
- iPhoto keywords to Iptc.Application2.Keywords
- iPhoto rating to Xmp.xmp.Rating
See below for information on installing pyexiv2.
NOTE: if you see messages like this:
Error: Directory Canon with 1100 entries considered invalid; not read.
you can safely ignore them; they indicate a problem reading the metadata
already in the file. Installing a newer version of pyexiv2 should fix this
(as of this writing, it's fixed in the repository, but not released).
Installing pyexiv2
------------------
Unfortunately, there is no easy way to install pyexiv2, but if you have
MacPorts <http://macports.org/>, it's relatively simple; follow these steps
to set up:
sudo port install scons
sudo port install exiv2
sudo port install boost +python26
Then, after downloading Pyexiv2 <http://tilloy.net/dev/pyexiv2/> and changing
into its source directory:
export CXXFLAGS="-I/opt/local/include"
export LDFLAGS="-L/opt/local/lib -lpython2.6"
sudo scons install
cd /opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/
sudo mv libexiv2python.dylib libexiv2python.so
Note that you'll have to use python2.6 to run the script; e.g.,
python2.6 exportiphoto ...
| {
"content_hash": "c5d08f09ffdd9181b3dee2b179246996",
"timestamp": "",
"source": "github",
"line_count": 165,
"max_line_length": 102,
"avg_line_length": 33.11515151515152,
"alnum_prop": 0.7049780380673499,
"repo_name": "BMorearty/exportiphoto",
"id": "5e96ea3a95756472c37bf8bc8be5327aa12148fe",
"size": "5464",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "25316"
}
],
"symlink_target": ""
} |
package org.apache.camel.processor;
import org.apache.camel.ContextTestSupport;
import org.apache.camel.builder.RouteBuilder;
import org.junit.Test;
public class LoopNoCopyTest extends ContextTestSupport {
@Test
public void testLoopNoCopy() throws Exception {
getMockEndpoint("mock:loop").expectedBodiesReceived("AB", "ABB", "ABBB");
getMockEndpoint("mock:result").expectedBodiesReceived("ABBB");
template.sendBody("direct:start", "A");
assertMockEndpointsSatisfied();
}
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
@Override
public void configure() throws Exception {
// START SNIPPET: e1
from("direct:start")
// by default loop will keep using the same exchange so on the 2nd and 3rd iteration its
// the same exchange that was previous used that are being looped all over
.loop(3)
.transform(body().append("B"))
.to("mock:loop")
.end()
.to("mock:result");
// END SNIPPET: e1
}
};
}
}
| {
"content_hash": "64f287cd412e249aa34b5030f9ea8500",
"timestamp": "",
"source": "github",
"line_count": 38,
"max_line_length": 108,
"avg_line_length": 33,
"alnum_prop": 0.5765550239234449,
"repo_name": "davidkarlsen/camel",
"id": "bfdf1385b05c418f1edb093e041fe7d20d1f6851",
"size": "2056",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "core/camel-core/src/test/java/org/apache/camel/processor/LoopNoCopyTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Apex",
"bytes": "6521"
},
{
"name": "Batchfile",
"bytes": "2353"
},
{
"name": "CSS",
"bytes": "17204"
},
{
"name": "Elm",
"bytes": "10852"
},
{
"name": "FreeMarker",
"bytes": "8015"
},
{
"name": "Groovy",
"bytes": "14479"
},
{
"name": "HTML",
"bytes": "909437"
},
{
"name": "Java",
"bytes": "82303679"
},
{
"name": "JavaScript",
"bytes": "102432"
},
{
"name": "Makefile",
"bytes": "513"
},
{
"name": "Shell",
"bytes": "17240"
},
{
"name": "TSQL",
"bytes": "28835"
},
{
"name": "Tcl",
"bytes": "4974"
},
{
"name": "Thrift",
"bytes": "6979"
},
{
"name": "XQuery",
"bytes": "546"
},
{
"name": "XSLT",
"bytes": "271473"
}
],
"symlink_target": ""
} |
/*
* (C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved
* (C) Copyright IBM Corp. 1996 - 1998 - All Rights Reserved
*
* The original version of this source code and documentation
* is copyrighted and owned by Taligent, Inc., a wholly-owned
* subsidiary of IBM. These materials are provided under terms
* of a License Agreement between Taligent and Sun. This technology
* is protected by multiple US and International patents.
*
* This notice and attribution to Taligent may not be removed.
* Taligent is a registered trademark of Taligent, Inc.
*
*/
package sun.text.resources;
import java.util.ListResourceBundle;
public class FormatData_es_ES extends ListResourceBundle {
/**
* Overrides ListResourceBundle
*/
protected final Object[][] getContents() {
return new Object[][] {
{ "NumberPatterns",
new String[] {
"#,##0.###;-#,##0.###", // decimal pattern
"#,##0 \u00A4;-#,##0 \u00A4", // currency pattern
"#,##0%" // percent pattern
}
},
};
}
}
| {
"content_hash": "5afacbd72d320a1b76e41449437bd3b6",
"timestamp": "",
"source": "github",
"line_count": 37,
"max_line_length": 69,
"avg_line_length": 30.54054054054054,
"alnum_prop": 0.6061946902654868,
"repo_name": "rokn/Count_Words_2015",
"id": "2afa5727ef212fc6514206359ecd564258106487",
"size": "2342",
"binary": false,
"copies": "35",
"ref": "refs/heads/master",
"path": "testing/openjdk/jdk/src/share/classes/sun/text/resources/FormatData_es_ES.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "61802"
},
{
"name": "Ruby",
"bytes": "18888605"
}
],
"symlink_target": ""
} |
from itertools import product
from distutils.version import LooseVersion
import operator
import pytest
from numpy import nan
import numpy as np
import pandas as pd
from pandas import (Series, Categorical, DataFrame, isna, notna,
bdate_range, date_range, _np_version_under1p10,
CategoricalIndex)
from pandas.core.index import MultiIndex
from pandas.core.indexes.datetimes import Timestamp
from pandas.core.indexes.timedeltas import Timedelta
import pandas.core.nanops as nanops
from pandas.compat import lrange, range, PY35
from pandas import compat
from pandas.util.testing import (assert_series_equal, assert_almost_equal,
assert_frame_equal, assert_index_equal)
import pandas.util.testing as tm
import pandas.util._test_decorators as td
from .common import TestData
class TestSeriesAnalytics(TestData):
@pytest.mark.parametrize("use_bottleneck", [True, False])
@pytest.mark.parametrize("method, unit", [
("sum", 0.0),
("prod", 1.0)
])
def test_empty(self, method, unit, use_bottleneck):
with pd.option_context("use_bottleneck", use_bottleneck):
# GH 9422 / 18921
# Entirely empty
s = Series([])
# NA by default
result = getattr(s, method)()
assert result == unit
# Explicit
result = getattr(s, method)(min_count=0)
assert result == unit
result = getattr(s, method)(min_count=1)
assert isna(result)
# Skipna, default
result = getattr(s, method)(skipna=True)
result == unit
# Skipna, explicit
result = getattr(s, method)(skipna=True, min_count=0)
assert result == unit
result = getattr(s, method)(skipna=True, min_count=1)
assert isna(result)
# All-NA
s = Series([np.nan])
# NA by default
result = getattr(s, method)()
assert result == unit
# Explicit
result = getattr(s, method)(min_count=0)
assert result == unit
result = getattr(s, method)(min_count=1)
assert isna(result)
# Skipna, default
result = getattr(s, method)(skipna=True)
result == unit
# skipna, explicit
result = getattr(s, method)(skipna=True, min_count=0)
assert result == unit
result = getattr(s, method)(skipna=True, min_count=1)
assert isna(result)
# Mix of valid, empty
s = Series([np.nan, 1])
# Default
result = getattr(s, method)()
assert result == 1.0
# Explicit
result = getattr(s, method)(min_count=0)
assert result == 1.0
result = getattr(s, method)(min_count=1)
assert result == 1.0
# Skipna
result = getattr(s, method)(skipna=True)
assert result == 1.0
result = getattr(s, method)(skipna=True, min_count=0)
assert result == 1.0
result = getattr(s, method)(skipna=True, min_count=1)
assert result == 1.0
# GH #844 (changed in 9422)
df = DataFrame(np.empty((10, 0)))
assert (getattr(df, method)(1) == unit).all()
s = pd.Series([1])
result = getattr(s, method)(min_count=2)
assert isna(result)
s = pd.Series([np.nan])
result = getattr(s, method)(min_count=2)
assert isna(result)
s = pd.Series([np.nan, 1])
result = getattr(s, method)(min_count=2)
assert isna(result)
@pytest.mark.parametrize('method, unit', [
('sum', 0.0),
('prod', 1.0),
])
def test_empty_multi(self, method, unit):
s = pd.Series([1, np.nan, np.nan, np.nan],
index=pd.MultiIndex.from_product([('a', 'b'), (0, 1)]))
# 1 / 0 by default
result = getattr(s, method)(level=0)
expected = pd.Series([1, unit], index=['a', 'b'])
tm.assert_series_equal(result, expected)
# min_count=0
result = getattr(s, method)(level=0, min_count=0)
expected = pd.Series([1, unit], index=['a', 'b'])
tm.assert_series_equal(result, expected)
# min_count=1
result = getattr(s, method)(level=0, min_count=1)
expected = pd.Series([1, np.nan], index=['a', 'b'])
tm.assert_series_equal(result, expected)
@pytest.mark.parametrize(
"method", ['mean', 'median', 'std', 'var'])
def test_ops_consistency_on_empty(self, method):
# GH 7869
# consistency on empty
# float
result = getattr(Series(dtype=float), method)()
assert isna(result)
# timedelta64[ns]
result = getattr(Series(dtype='m8[ns]'), method)()
assert result is pd.NaT
def test_nansum_buglet(self):
s = Series([1.0, np.nan], index=[0, 1])
result = np.nansum(s)
assert_almost_equal(result, 1)
@pytest.mark.parametrize("use_bottleneck", [True, False])
def test_sum_overflow(self, use_bottleneck):
with pd.option_context('use_bottleneck', use_bottleneck):
# GH 6915
# overflowing on the smaller int dtypes
for dtype in ['int32', 'int64']:
v = np.arange(5000000, dtype=dtype)
s = Series(v)
result = s.sum(skipna=False)
assert int(result) == v.sum(dtype='int64')
result = s.min(skipna=False)
assert int(result) == 0
result = s.max(skipna=False)
assert int(result) == v[-1]
for dtype in ['float32', 'float64']:
v = np.arange(5000000, dtype=dtype)
s = Series(v)
result = s.sum(skipna=False)
assert result == v.sum(dtype=dtype)
result = s.min(skipna=False)
assert np.allclose(float(result), 0.0)
result = s.max(skipna=False)
assert np.allclose(float(result), v[-1])
def test_sum(self):
self._check_stat_op('sum', np.sum, check_allna=False)
def test_sum_inf(self):
s = Series(np.random.randn(10))
s2 = s.copy()
s[5:8] = np.inf
s2[5:8] = np.nan
assert np.isinf(s.sum())
arr = np.random.randn(100, 100).astype('f4')
arr[:, 2] = np.inf
with pd.option_context("mode.use_inf_as_na", True):
assert_almost_equal(s.sum(), s2.sum())
res = nanops.nansum(arr, axis=1)
assert np.isinf(res).all()
def test_mean(self):
self._check_stat_op('mean', np.mean)
def test_median(self):
self._check_stat_op('median', np.median)
# test with integers, test failure
int_ts = Series(np.ones(10, dtype=int), index=lrange(10))
tm.assert_almost_equal(np.median(int_ts), int_ts.median())
def test_prod(self):
self._check_stat_op('prod', np.prod)
def test_min(self):
self._check_stat_op('min', np.min, check_objects=True)
def test_max(self):
self._check_stat_op('max', np.max, check_objects=True)
def test_var_std(self):
alt = lambda x: np.std(x, ddof=1)
self._check_stat_op('std', alt)
alt = lambda x: np.var(x, ddof=1)
self._check_stat_op('var', alt)
result = self.ts.std(ddof=4)
expected = np.std(self.ts.values, ddof=4)
assert_almost_equal(result, expected)
result = self.ts.var(ddof=4)
expected = np.var(self.ts.values, ddof=4)
assert_almost_equal(result, expected)
# 1 - element series with ddof=1
s = self.ts.iloc[[0]]
result = s.var(ddof=1)
assert isna(result)
result = s.std(ddof=1)
assert isna(result)
def test_sem(self):
alt = lambda x: np.std(x, ddof=1) / np.sqrt(len(x))
self._check_stat_op('sem', alt)
result = self.ts.sem(ddof=4)
expected = np.std(self.ts.values,
ddof=4) / np.sqrt(len(self.ts.values))
assert_almost_equal(result, expected)
# 1 - element series with ddof=1
s = self.ts.iloc[[0]]
result = s.sem(ddof=1)
assert isna(result)
@td.skip_if_no_scipy
def test_skew(self):
from scipy.stats import skew
alt = lambda x: skew(x, bias=False)
self._check_stat_op('skew', alt)
# test corner cases, skew() returns NaN unless there's at least 3
# values
min_N = 3
for i in range(1, min_N + 1):
s = Series(np.ones(i))
df = DataFrame(np.ones((i, i)))
if i < min_N:
assert np.isnan(s.skew())
assert np.isnan(df.skew()).all()
else:
assert 0 == s.skew()
assert (df.skew() == 0).all()
@td.skip_if_no_scipy
def test_kurt(self):
from scipy.stats import kurtosis
alt = lambda x: kurtosis(x, bias=False)
self._check_stat_op('kurt', alt)
index = MultiIndex(levels=[['bar'], ['one', 'two', 'three'], [0, 1]],
labels=[[0, 0, 0, 0, 0, 0], [0, 1, 2, 0, 1, 2],
[0, 1, 0, 1, 0, 1]])
s = Series(np.random.randn(6), index=index)
tm.assert_almost_equal(s.kurt(), s.kurt(level=0)['bar'])
# test corner cases, kurt() returns NaN unless there's at least 4
# values
min_N = 4
for i in range(1, min_N + 1):
s = Series(np.ones(i))
df = DataFrame(np.ones((i, i)))
if i < min_N:
assert np.isnan(s.kurt())
assert np.isnan(df.kurt()).all()
else:
assert 0 == s.kurt()
assert (df.kurt() == 0).all()
def test_describe(self):
s = Series([0, 1, 2, 3, 4], name='int_data')
result = s.describe()
expected = Series([5, 2, s.std(), 0, 1, 2, 3, 4],
name='int_data',
index=['count', 'mean', 'std', 'min', '25%',
'50%', '75%', 'max'])
tm.assert_series_equal(result, expected)
s = Series([True, True, False, False, False], name='bool_data')
result = s.describe()
expected = Series([5, 2, False, 3], name='bool_data',
index=['count', 'unique', 'top', 'freq'])
tm.assert_series_equal(result, expected)
s = Series(['a', 'a', 'b', 'c', 'd'], name='str_data')
result = s.describe()
expected = Series([5, 4, 'a', 2], name='str_data',
index=['count', 'unique', 'top', 'freq'])
tm.assert_series_equal(result, expected)
def test_argsort(self):
self._check_accum_op('argsort', check_dtype=False)
argsorted = self.ts.argsort()
assert issubclass(argsorted.dtype.type, np.integer)
# GH 2967 (introduced bug in 0.11-dev I think)
s = Series([Timestamp('201301%02d' % (i + 1)) for i in range(5)])
assert s.dtype == 'datetime64[ns]'
shifted = s.shift(-1)
assert shifted.dtype == 'datetime64[ns]'
assert isna(shifted[4])
result = s.argsort()
expected = Series(lrange(5), dtype='int64')
assert_series_equal(result, expected)
result = shifted.argsort()
expected = Series(lrange(4) + [-1], dtype='int64')
assert_series_equal(result, expected)
def test_argsort_stable(self):
s = Series(np.random.randint(0, 100, size=10000))
mindexer = s.argsort(kind='mergesort')
qindexer = s.argsort()
mexpected = np.argsort(s.values, kind='mergesort')
qexpected = np.argsort(s.values, kind='quicksort')
tm.assert_series_equal(mindexer, Series(mexpected),
check_dtype=False)
tm.assert_series_equal(qindexer, Series(qexpected),
check_dtype=False)
pytest.raises(AssertionError, tm.assert_numpy_array_equal,
qindexer, mindexer)
def test_cumsum(self):
self._check_accum_op('cumsum')
def test_cumprod(self):
self._check_accum_op('cumprod')
def test_cummin(self):
tm.assert_numpy_array_equal(self.ts.cummin().values,
np.minimum.accumulate(np.array(self.ts)))
ts = self.ts.copy()
ts[::2] = np.NaN
result = ts.cummin()[1::2]
expected = np.minimum.accumulate(ts.dropna())
tm.assert_series_equal(result, expected)
def test_cummax(self):
tm.assert_numpy_array_equal(self.ts.cummax().values,
np.maximum.accumulate(np.array(self.ts)))
ts = self.ts.copy()
ts[::2] = np.NaN
result = ts.cummax()[1::2]
expected = np.maximum.accumulate(ts.dropna())
tm.assert_series_equal(result, expected)
def test_cummin_datetime64(self):
s = pd.Series(pd.to_datetime(['NaT', '2000-1-2', 'NaT', '2000-1-1',
'NaT', '2000-1-3']))
expected = pd.Series(pd.to_datetime(['NaT', '2000-1-2', 'NaT',
'2000-1-1', 'NaT', '2000-1-1']))
result = s.cummin(skipna=True)
tm.assert_series_equal(expected, result)
expected = pd.Series(pd.to_datetime(
['NaT', '2000-1-2', '2000-1-2', '2000-1-1', '2000-1-1', '2000-1-1'
]))
result = s.cummin(skipna=False)
tm.assert_series_equal(expected, result)
def test_cummax_datetime64(self):
s = pd.Series(pd.to_datetime(['NaT', '2000-1-2', 'NaT', '2000-1-1',
'NaT', '2000-1-3']))
expected = pd.Series(pd.to_datetime(['NaT', '2000-1-2', 'NaT',
'2000-1-2', 'NaT', '2000-1-3']))
result = s.cummax(skipna=True)
tm.assert_series_equal(expected, result)
expected = pd.Series(pd.to_datetime(
['NaT', '2000-1-2', '2000-1-2', '2000-1-2', '2000-1-2', '2000-1-3'
]))
result = s.cummax(skipna=False)
tm.assert_series_equal(expected, result)
def test_cummin_timedelta64(self):
s = pd.Series(pd.to_timedelta(['NaT',
'2 min',
'NaT',
'1 min',
'NaT',
'3 min', ]))
expected = pd.Series(pd.to_timedelta(['NaT',
'2 min',
'NaT',
'1 min',
'NaT',
'1 min', ]))
result = s.cummin(skipna=True)
tm.assert_series_equal(expected, result)
expected = pd.Series(pd.to_timedelta(['NaT',
'2 min',
'2 min',
'1 min',
'1 min',
'1 min', ]))
result = s.cummin(skipna=False)
tm.assert_series_equal(expected, result)
def test_cummax_timedelta64(self):
s = pd.Series(pd.to_timedelta(['NaT',
'2 min',
'NaT',
'1 min',
'NaT',
'3 min', ]))
expected = pd.Series(pd.to_timedelta(['NaT',
'2 min',
'NaT',
'2 min',
'NaT',
'3 min', ]))
result = s.cummax(skipna=True)
tm.assert_series_equal(expected, result)
expected = pd.Series(pd.to_timedelta(['NaT',
'2 min',
'2 min',
'2 min',
'2 min',
'3 min', ]))
result = s.cummax(skipna=False)
tm.assert_series_equal(expected, result)
def test_npdiff(self):
pytest.skip("skipping due to Series no longer being an "
"ndarray")
# no longer works as the return type of np.diff is now nd.array
s = Series(np.arange(5))
r = np.diff(s)
assert_series_equal(Series([nan, 0, 0, 0, nan]), r)
def _check_stat_op(self, name, alternate, check_objects=False,
check_allna=False):
with pd.option_context('use_bottleneck', False):
f = getattr(Series, name)
# add some NaNs
self.series[5:15] = np.NaN
# idxmax, idxmin, min, and max are valid for dates
if name not in ['max', 'min']:
ds = Series(date_range('1/1/2001', periods=10))
pytest.raises(TypeError, f, ds)
# skipna or no
assert notna(f(self.series))
assert isna(f(self.series, skipna=False))
# check the result is correct
nona = self.series.dropna()
assert_almost_equal(f(nona), alternate(nona.values))
assert_almost_equal(f(self.series), alternate(nona.values))
allna = self.series * nan
if check_allna:
assert np.isnan(f(allna))
# dtype=object with None, it works!
s = Series([1, 2, 3, None, 5])
f(s)
# 2888
l = [0]
l.extend(lrange(2 ** 40, 2 ** 40 + 1000))
s = Series(l, dtype='int64')
assert_almost_equal(float(f(s)), float(alternate(s.values)))
# check date range
if check_objects:
s = Series(bdate_range('1/1/2000', periods=10))
res = f(s)
exp = alternate(s)
assert res == exp
# check on string data
if name not in ['sum', 'min', 'max']:
pytest.raises(TypeError, f, Series(list('abc')))
# Invalid axis.
pytest.raises(ValueError, f, self.series, axis=1)
# Unimplemented numeric_only parameter.
if 'numeric_only' in compat.signature(f).args:
tm.assert_raises_regex(NotImplementedError, name, f,
self.series, numeric_only=True)
def _check_accum_op(self, name, check_dtype=True):
func = getattr(np, name)
tm.assert_numpy_array_equal(func(self.ts).values,
func(np.array(self.ts)),
check_dtype=check_dtype)
# with missing values
ts = self.ts.copy()
ts[::2] = np.NaN
result = func(ts)[1::2]
expected = func(np.array(ts.dropna()))
tm.assert_numpy_array_equal(result.values, expected,
check_dtype=False)
def test_compress(self):
cond = [True, False, True, False, False]
s = Series([1, -1, 5, 8, 7],
index=list('abcde'), name='foo')
expected = Series(s.values.compress(cond),
index=list('ac'), name='foo')
tm.assert_series_equal(s.compress(cond), expected)
def test_numpy_compress(self):
cond = [True, False, True, False, False]
s = Series([1, -1, 5, 8, 7],
index=list('abcde'), name='foo')
expected = Series(s.values.compress(cond),
index=list('ac'), name='foo')
tm.assert_series_equal(np.compress(cond, s), expected)
msg = "the 'axis' parameter is not supported"
tm.assert_raises_regex(ValueError, msg, np.compress,
cond, s, axis=1)
msg = "the 'out' parameter is not supported"
tm.assert_raises_regex(ValueError, msg, np.compress,
cond, s, out=s)
def test_round(self):
self.ts.index.name = "index_name"
result = self.ts.round(2)
expected = Series(np.round(self.ts.values, 2),
index=self.ts.index, name='ts')
assert_series_equal(result, expected)
assert result.name == self.ts.name
def test_numpy_round(self):
# See gh-12600
s = Series([1.53, 1.36, 0.06])
out = np.round(s, decimals=0)
expected = Series([2., 1., 0.])
assert_series_equal(out, expected)
msg = "the 'out' parameter is not supported"
with tm.assert_raises_regex(ValueError, msg):
np.round(s, decimals=0, out=s)
def test_built_in_round(self):
if not compat.PY3:
pytest.skip(
'build in round cannot be overridden prior to Python 3')
s = Series([1.123, 2.123, 3.123], index=lrange(3))
result = round(s)
expected_rounded0 = Series([1., 2., 3.], index=lrange(3))
tm.assert_series_equal(result, expected_rounded0)
decimals = 2
expected_rounded = Series([1.12, 2.12, 3.12], index=lrange(3))
result = round(s, decimals)
tm.assert_series_equal(result, expected_rounded)
def test_prod_numpy16_bug(self):
s = Series([1., 1., 1.], index=lrange(3))
result = s.prod()
assert not isinstance(result, Series)
def test_all_any(self):
ts = tm.makeTimeSeries()
bool_series = ts > 0
assert not bool_series.all()
assert bool_series.any()
# Alternative types, with implicit 'object' dtype.
s = Series(['abc', True])
assert 'abc' == s.any() # 'abc' || True => 'abc'
def test_all_any_params(self):
# Check skipna, with implicit 'object' dtype.
s1 = Series([np.nan, True])
s2 = Series([np.nan, False])
assert s1.all(skipna=False) # nan && True => True
assert s1.all(skipna=True)
assert np.isnan(s2.any(skipna=False)) # nan || False => nan
assert not s2.any(skipna=True)
# Check level.
s = pd.Series([False, False, True, True, False, True],
index=[0, 0, 1, 1, 2, 2])
assert_series_equal(s.all(level=0), Series([False, True, False]))
assert_series_equal(s.any(level=0), Series([False, True, True]))
# bool_only is not implemented with level option.
pytest.raises(NotImplementedError, s.any, bool_only=True, level=0)
pytest.raises(NotImplementedError, s.all, bool_only=True, level=0)
# bool_only is not implemented alone.
pytest.raises(NotImplementedError, s.any, bool_only=True)
pytest.raises(NotImplementedError, s.all, bool_only=True)
def test_modulo(self):
with np.errstate(all='ignore'):
# GH3590, modulo as ints
p = DataFrame({'first': [3, 4, 5, 8], 'second': [0, 0, 0, 3]})
result = p['first'] % p['second']
expected = Series(p['first'].values % p['second'].values,
dtype='float64')
expected.iloc[0:3] = np.nan
assert_series_equal(result, expected)
result = p['first'] % 0
expected = Series(np.nan, index=p.index, name='first')
assert_series_equal(result, expected)
p = p.astype('float64')
result = p['first'] % p['second']
expected = Series(p['first'].values % p['second'].values)
assert_series_equal(result, expected)
p = p.astype('float64')
result = p['first'] % p['second']
result2 = p['second'] % p['first']
assert not result.equals(result2)
# GH 9144
s = Series([0, 1])
result = s % 0
expected = Series([nan, nan])
assert_series_equal(result, expected)
result = 0 % s
expected = Series([nan, 0.0])
assert_series_equal(result, expected)
@td.skip_if_no_scipy
def test_corr(self):
import scipy.stats as stats
# full overlap
tm.assert_almost_equal(self.ts.corr(self.ts), 1)
# partial overlap
tm.assert_almost_equal(self.ts[:15].corr(self.ts[5:]), 1)
assert isna(self.ts[:15].corr(self.ts[5:], min_periods=12))
ts1 = self.ts[:15].reindex(self.ts.index)
ts2 = self.ts[5:].reindex(self.ts.index)
assert isna(ts1.corr(ts2, min_periods=12))
# No overlap
assert np.isnan(self.ts[::2].corr(self.ts[1::2]))
# all NA
cp = self.ts[:10].copy()
cp[:] = np.nan
assert isna(cp.corr(cp))
A = tm.makeTimeSeries()
B = tm.makeTimeSeries()
result = A.corr(B)
expected, _ = stats.pearsonr(A, B)
tm.assert_almost_equal(result, expected)
@td.skip_if_no_scipy
def test_corr_rank(self):
import scipy
import scipy.stats as stats
# kendall and spearman
A = tm.makeTimeSeries()
B = tm.makeTimeSeries()
A[-5:] = A[:5]
result = A.corr(B, method='kendall')
expected = stats.kendalltau(A, B)[0]
tm.assert_almost_equal(result, expected)
result = A.corr(B, method='spearman')
expected = stats.spearmanr(A, B)[0]
tm.assert_almost_equal(result, expected)
# these methods got rewritten in 0.8
if LooseVersion(scipy.__version__) < LooseVersion('0.9'):
pytest.skip("skipping corr rank because of scipy version "
"{0}".format(scipy.__version__))
# results from R
A = Series(
[-0.89926396, 0.94209606, -1.03289164, -0.95445587, 0.76910310, -
0.06430576, -2.09704447, 0.40660407, -0.89926396, 0.94209606])
B = Series(
[-1.01270225, -0.62210117, -1.56895827, 0.59592943, -0.01680292,
1.17258718, -1.06009347, -0.10222060, -0.89076239, 0.89372375])
kexp = 0.4319297
sexp = 0.5853767
tm.assert_almost_equal(A.corr(B, method='kendall'), kexp)
tm.assert_almost_equal(A.corr(B, method='spearman'), sexp)
def test_cov(self):
# full overlap
tm.assert_almost_equal(self.ts.cov(self.ts), self.ts.std() ** 2)
# partial overlap
tm.assert_almost_equal(self.ts[:15].cov(self.ts[5:]),
self.ts[5:15].std() ** 2)
# No overlap
assert np.isnan(self.ts[::2].cov(self.ts[1::2]))
# all NA
cp = self.ts[:10].copy()
cp[:] = np.nan
assert isna(cp.cov(cp))
# min_periods
assert isna(self.ts[:15].cov(self.ts[5:], min_periods=12))
ts1 = self.ts[:15].reindex(self.ts.index)
ts2 = self.ts[5:].reindex(self.ts.index)
assert isna(ts1.cov(ts2, min_periods=12))
def test_count(self):
assert self.ts.count() == len(self.ts)
self.ts[::2] = np.NaN
assert self.ts.count() == np.isfinite(self.ts).sum()
mi = MultiIndex.from_arrays([list('aabbcc'), [1, 2, 2, nan, 1, 2]])
ts = Series(np.arange(len(mi)), index=mi)
left = ts.count(level=1)
right = Series([2, 3, 1], index=[1, 2, nan])
assert_series_equal(left, right)
ts.iloc[[0, 3, 5]] = nan
assert_series_equal(ts.count(level=1), right - 1)
def test_dot(self):
a = Series(np.random.randn(4), index=['p', 'q', 'r', 's'])
b = DataFrame(np.random.randn(3, 4), index=['1', '2', '3'],
columns=['p', 'q', 'r', 's']).T
result = a.dot(b)
expected = Series(np.dot(a.values, b.values), index=['1', '2', '3'])
assert_series_equal(result, expected)
# Check index alignment
b2 = b.reindex(index=reversed(b.index))
result = a.dot(b)
assert_series_equal(result, expected)
# Check ndarray argument
result = a.dot(b.values)
assert np.all(result == expected.values)
assert_almost_equal(a.dot(b['2'].values), expected['2'])
# Check series argument
assert_almost_equal(a.dot(b['1']), expected['1'])
assert_almost_equal(a.dot(b2['1']), expected['1'])
pytest.raises(Exception, a.dot, a.values[:3])
pytest.raises(ValueError, a.dot, b.T)
@pytest.mark.skipif(not PY35,
reason='matmul supported for Python>=3.5')
def test_matmul(self):
# matmul test is for GH #10259
a = Series(np.random.randn(4), index=['p', 'q', 'r', 's'])
b = DataFrame(np.random.randn(3, 4), index=['1', '2', '3'],
columns=['p', 'q', 'r', 's']).T
# Series @ DataFrame
result = operator.matmul(a, b)
expected = Series(np.dot(a.values, b.values), index=['1', '2', '3'])
assert_series_equal(result, expected)
# DataFrame @ Series
result = operator.matmul(b.T, a)
expected = Series(np.dot(b.T.values, a.T.values),
index=['1', '2', '3'])
assert_series_equal(result, expected)
# Series @ Series
result = operator.matmul(a, a)
expected = np.dot(a.values, a.values)
assert_almost_equal(result, expected)
# np.array @ Series (__rmatmul__)
result = operator.matmul(a.values, a)
expected = np.dot(a.values, a.values)
assert_almost_equal(result, expected)
# mixed dtype DataFrame @ Series
a['p'] = int(a.p)
result = operator.matmul(b.T, a)
expected = Series(np.dot(b.T.values, a.T.values),
index=['1', '2', '3'])
assert_series_equal(result, expected)
# different dtypes DataFrame @ Series
a = a.astype(int)
result = operator.matmul(b.T, a)
expected = Series(np.dot(b.T.values, a.T.values),
index=['1', '2', '3'])
assert_series_equal(result, expected)
pytest.raises(Exception, a.dot, a.values[:3])
pytest.raises(ValueError, a.dot, b.T)
def test_value_counts_nunique(self):
# basics.rst doc example
series = Series(np.random.randn(500))
series[20:500] = np.nan
series[10:20] = 5000
result = series.nunique()
assert result == 11
# GH 18051
s = pd.Series(pd.Categorical([]))
assert s.nunique() == 0
s = pd.Series(pd.Categorical([np.nan]))
assert s.nunique() == 0
def test_unique(self):
# 714 also, dtype=float
s = Series([1.2345] * 100)
s[::2] = np.nan
result = s.unique()
assert len(result) == 2
s = Series([1.2345] * 100, dtype='f4')
s[::2] = np.nan
result = s.unique()
assert len(result) == 2
# NAs in object arrays #714
s = Series(['foo'] * 100, dtype='O')
s[::2] = np.nan
result = s.unique()
assert len(result) == 2
# decision about None
s = Series([1, 2, 3, None, None, None], dtype=object)
result = s.unique()
expected = np.array([1, 2, 3, None], dtype=object)
tm.assert_numpy_array_equal(result, expected)
# GH 18051
s = pd.Series(pd.Categorical([]))
tm.assert_categorical_equal(s.unique(), pd.Categorical([]),
check_dtype=False)
s = pd.Series(pd.Categorical([np.nan]))
tm.assert_categorical_equal(s.unique(), pd.Categorical([np.nan]),
check_dtype=False)
@pytest.mark.parametrize(
"tc1, tc2",
[
(
Series([1, 2, 3, 3], dtype=np.dtype('int_')),
Series([1, 2, 3, 5, 3, 2, 4], dtype=np.dtype('int_'))
),
(
Series([1, 2, 3, 3], dtype=np.dtype('uint')),
Series([1, 2, 3, 5, 3, 2, 4], dtype=np.dtype('uint'))
),
(
Series([1, 2, 3, 3], dtype=np.dtype('float_')),
Series([1, 2, 3, 5, 3, 2, 4], dtype=np.dtype('float_'))
),
(
Series([1, 2, 3, 3], dtype=np.dtype('unicode_')),
Series([1, 2, 3, 5, 3, 2, 4], dtype=np.dtype('unicode_'))
)
]
)
def test_drop_duplicates_non_bool(self, tc1, tc2):
# Test case 1
expected = Series([False, False, False, True])
assert_series_equal(tc1.duplicated(), expected)
assert_series_equal(tc1.drop_duplicates(), tc1[~expected])
sc = tc1.copy()
sc.drop_duplicates(inplace=True)
assert_series_equal(sc, tc1[~expected])
expected = Series([False, False, True, False])
assert_series_equal(tc1.duplicated(keep='last'), expected)
assert_series_equal(tc1.drop_duplicates(keep='last'), tc1[~expected])
sc = tc1.copy()
sc.drop_duplicates(keep='last', inplace=True)
assert_series_equal(sc, tc1[~expected])
expected = Series([False, False, True, True])
assert_series_equal(tc1.duplicated(keep=False), expected)
assert_series_equal(tc1.drop_duplicates(keep=False), tc1[~expected])
sc = tc1.copy()
sc.drop_duplicates(keep=False, inplace=True)
assert_series_equal(sc, tc1[~expected])
# Test case 2
expected = Series([False, False, False, False, True, True, False])
assert_series_equal(tc2.duplicated(), expected)
assert_series_equal(tc2.drop_duplicates(), tc2[~expected])
sc = tc2.copy()
sc.drop_duplicates(inplace=True)
assert_series_equal(sc, tc2[~expected])
expected = Series([False, True, True, False, False, False, False])
assert_series_equal(tc2.duplicated(keep='last'), expected)
assert_series_equal(tc2.drop_duplicates(keep='last'), tc2[~expected])
sc = tc2.copy()
sc.drop_duplicates(keep='last', inplace=True)
assert_series_equal(sc, tc2[~expected])
expected = Series([False, True, True, False, True, True, False])
assert_series_equal(tc2.duplicated(keep=False), expected)
assert_series_equal(tc2.drop_duplicates(keep=False), tc2[~expected])
sc = tc2.copy()
sc.drop_duplicates(keep=False, inplace=True)
assert_series_equal(sc, tc2[~expected])
def test_drop_duplicates_bool(self):
tc = Series([True, False, True, False])
expected = Series([False, False, True, True])
assert_series_equal(tc.duplicated(), expected)
assert_series_equal(tc.drop_duplicates(), tc[~expected])
sc = tc.copy()
sc.drop_duplicates(inplace=True)
assert_series_equal(sc, tc[~expected])
expected = Series([True, True, False, False])
assert_series_equal(tc.duplicated(keep='last'), expected)
assert_series_equal(tc.drop_duplicates(keep='last'), tc[~expected])
sc = tc.copy()
sc.drop_duplicates(keep='last', inplace=True)
assert_series_equal(sc, tc[~expected])
expected = Series([True, True, True, True])
assert_series_equal(tc.duplicated(keep=False), expected)
assert_series_equal(tc.drop_duplicates(keep=False), tc[~expected])
sc = tc.copy()
sc.drop_duplicates(keep=False, inplace=True)
assert_series_equal(sc, tc[~expected])
def test_clip(self):
val = self.ts.median()
assert self.ts.clip_lower(val).min() == val
assert self.ts.clip_upper(val).max() == val
assert self.ts.clip(lower=val).min() == val
assert self.ts.clip(upper=val).max() == val
result = self.ts.clip(-0.5, 0.5)
expected = np.clip(self.ts, -0.5, 0.5)
assert_series_equal(result, expected)
assert isinstance(expected, Series)
def test_clip_types_and_nulls(self):
sers = [Series([np.nan, 1.0, 2.0, 3.0]), Series([None, 'a', 'b', 'c']),
Series(pd.to_datetime(
[np.nan, 1, 2, 3], unit='D'))]
for s in sers:
thresh = s[2]
l = s.clip_lower(thresh)
u = s.clip_upper(thresh)
assert l[notna(l)].min() == thresh
assert u[notna(u)].max() == thresh
assert list(isna(s)) == list(isna(l))
assert list(isna(s)) == list(isna(u))
def test_clip_with_na_args(self):
"""Should process np.nan argument as None """
# GH # 17276
s = Series([1, 2, 3])
assert_series_equal(s.clip(np.nan), Series([1, 2, 3]))
assert_series_equal(s.clip(upper=[1, 1, np.nan]), Series([1, 2, 3]))
assert_series_equal(s.clip(lower=[1, np.nan, 1]), Series([1, 2, 3]))
assert_series_equal(s.clip(upper=np.nan, lower=np.nan),
Series([1, 2, 3]))
def test_clip_against_series(self):
# GH #6966
s = Series([1.0, 1.0, 4.0])
threshold = Series([1.0, 2.0, 3.0])
assert_series_equal(s.clip_lower(threshold), Series([1.0, 2.0, 4.0]))
assert_series_equal(s.clip_upper(threshold), Series([1.0, 1.0, 3.0]))
lower = Series([1.0, 2.0, 3.0])
upper = Series([1.5, 2.5, 3.5])
assert_series_equal(s.clip(lower, upper), Series([1.0, 2.0, 3.5]))
assert_series_equal(s.clip(1.5, upper), Series([1.5, 1.5, 3.5]))
@pytest.mark.parametrize("inplace", [True, False])
@pytest.mark.parametrize("upper", [[1, 2, 3], np.asarray([1, 2, 3])])
def test_clip_against_list_like(self, inplace, upper):
# GH #15390
original = pd.Series([5, 6, 7])
result = original.clip(upper=upper, inplace=inplace)
expected = pd.Series([1, 2, 3])
if inplace:
result = original
tm.assert_series_equal(result, expected, check_exact=True)
def test_clip_with_datetimes(self):
# GH 11838
# naive and tz-aware datetimes
t = Timestamp('2015-12-01 09:30:30')
s = Series([Timestamp('2015-12-01 09:30:00'),
Timestamp('2015-12-01 09:31:00')])
result = s.clip(upper=t)
expected = Series([Timestamp('2015-12-01 09:30:00'),
Timestamp('2015-12-01 09:30:30')])
assert_series_equal(result, expected)
t = Timestamp('2015-12-01 09:30:30', tz='US/Eastern')
s = Series([Timestamp('2015-12-01 09:30:00', tz='US/Eastern'),
Timestamp('2015-12-01 09:31:00', tz='US/Eastern')])
result = s.clip(upper=t)
expected = Series([Timestamp('2015-12-01 09:30:00', tz='US/Eastern'),
Timestamp('2015-12-01 09:30:30', tz='US/Eastern')])
assert_series_equal(result, expected)
def test_cummethods_bool(self):
# GH 6270
# looks like a buggy np.maximum.accumulate for numpy 1.6.1, py 3.2
def cummin(x):
return np.minimum.accumulate(x)
def cummax(x):
return np.maximum.accumulate(x)
a = pd.Series([False, False, False, True, True, False, False])
b = ~a
c = pd.Series([False] * len(b))
d = ~c
methods = {'cumsum': np.cumsum,
'cumprod': np.cumprod,
'cummin': cummin,
'cummax': cummax}
args = product((a, b, c, d), methods)
for s, method in args:
expected = Series(methods[method](s.values))
result = getattr(s, method)()
assert_series_equal(result, expected)
e = pd.Series([False, True, nan, False])
cse = pd.Series([0, 1, nan, 1], dtype=object)
cpe = pd.Series([False, 0, nan, 0])
cmin = pd.Series([False, False, nan, False])
cmax = pd.Series([False, True, nan, True])
expecteds = {'cumsum': cse,
'cumprod': cpe,
'cummin': cmin,
'cummax': cmax}
for method in methods:
res = getattr(e, method)()
assert_series_equal(res, expecteds[method])
def test_isin(self):
s = Series(['A', 'B', 'C', 'a', 'B', 'B', 'A', 'C'])
result = s.isin(['A', 'C'])
expected = Series([True, False, True, False, False, False, True, True])
assert_series_equal(result, expected)
# GH: 16012
# This specific issue has to have a series over 1e6 in len, but the
# comparison array (in_list) must be large enough so that numpy doesn't
# do a manual masking trick that will avoid this issue altogether
s = Series(list('abcdefghijk' * 10 ** 5))
# If numpy doesn't do the manual comparison/mask, these
# unorderable mixed types are what cause the exception in numpy
in_list = [-1, 'a', 'b', 'G', 'Y', 'Z', 'E',
'K', 'E', 'S', 'I', 'R', 'R'] * 6
assert s.isin(in_list).sum() == 200000
def test_isin_with_string_scalar(self):
# GH4763
s = Series(['A', 'B', 'C', 'a', 'B', 'B', 'A', 'C'])
with pytest.raises(TypeError):
s.isin('a')
with pytest.raises(TypeError):
s = Series(['aaa', 'b', 'c'])
s.isin('aaa')
def test_isin_with_i8(self):
# GH 5021
expected = Series([True, True, False, False, False])
expected2 = Series([False, True, False, False, False])
# datetime64[ns]
s = Series(date_range('jan-01-2013', 'jan-05-2013'))
result = s.isin(s[0:2])
assert_series_equal(result, expected)
result = s.isin(s[0:2].values)
assert_series_equal(result, expected)
# fails on dtype conversion in the first place
result = s.isin(s[0:2].values.astype('datetime64[D]'))
assert_series_equal(result, expected)
result = s.isin([s[1]])
assert_series_equal(result, expected2)
result = s.isin([np.datetime64(s[1])])
assert_series_equal(result, expected2)
result = s.isin(set(s[0:2]))
assert_series_equal(result, expected)
# timedelta64[ns]
s = Series(pd.to_timedelta(lrange(5), unit='d'))
result = s.isin(s[0:2])
assert_series_equal(result, expected)
@pytest.mark.parametrize("empty", [[], Series(), np.array([])])
def test_isin_empty(self, empty):
# see gh-16991
s = Series(["a", "b"])
expected = Series([False, False])
result = s.isin(empty)
tm.assert_series_equal(expected, result)
def test_timedelta64_analytics(self):
from pandas import date_range
# index min/max
td = Series(date_range('2012-1-1', periods=3, freq='D')) - \
Timestamp('20120101')
result = td.idxmin()
assert result == 0
result = td.idxmax()
assert result == 2
# GH 2982
# with NaT
td[0] = np.nan
result = td.idxmin()
assert result == 1
result = td.idxmax()
assert result == 2
# abs
s1 = Series(date_range('20120101', periods=3))
s2 = Series(date_range('20120102', periods=3))
expected = Series(s2 - s1)
# this fails as numpy returns timedelta64[us]
# result = np.abs(s1-s2)
# assert_frame_equal(result,expected)
result = (s1 - s2).abs()
assert_series_equal(result, expected)
# max/min
result = td.max()
expected = Timedelta('2 days')
assert result == expected
result = td.min()
expected = Timedelta('1 days')
assert result == expected
def test_idxmin(self):
# test idxmin
# _check_stat_op approach can not be used here because of isna check.
# add some NaNs
self.series[5:15] = np.NaN
# skipna or no
assert self.series[self.series.idxmin()] == self.series.min()
assert isna(self.series.idxmin(skipna=False))
# no NaNs
nona = self.series.dropna()
assert nona[nona.idxmin()] == nona.min()
assert (nona.index.values.tolist().index(nona.idxmin()) ==
nona.values.argmin())
# all NaNs
allna = self.series * nan
assert isna(allna.idxmin())
# datetime64[ns]
from pandas import date_range
s = Series(date_range('20130102', periods=6))
result = s.idxmin()
assert result == 0
s[0] = np.nan
result = s.idxmin()
assert result == 1
def test_numpy_argmin_deprecated(self):
# See gh-16830
data = np.arange(1, 11)
s = Series(data, index=data)
with tm.assert_produces_warning(FutureWarning, check_stacklevel=False):
# The deprecation of Series.argmin also causes a deprecation
# warning when calling np.argmin. This behavior is temporary
# until the implementation of Series.argmin is corrected.
result = np.argmin(s)
assert result == 1
with tm.assert_produces_warning(FutureWarning):
# argmin is aliased to idxmin
result = s.argmin()
assert result == 1
if not _np_version_under1p10:
with tm.assert_produces_warning(FutureWarning,
check_stacklevel=False):
msg = "the 'out' parameter is not supported"
tm.assert_raises_regex(ValueError, msg, np.argmin,
s, out=data)
def test_idxmax(self):
# test idxmax
# _check_stat_op approach can not be used here because of isna check.
# add some NaNs
self.series[5:15] = np.NaN
# skipna or no
assert self.series[self.series.idxmax()] == self.series.max()
assert isna(self.series.idxmax(skipna=False))
# no NaNs
nona = self.series.dropna()
assert nona[nona.idxmax()] == nona.max()
assert (nona.index.values.tolist().index(nona.idxmax()) ==
nona.values.argmax())
# all NaNs
allna = self.series * nan
assert isna(allna.idxmax())
from pandas import date_range
s = Series(date_range('20130102', periods=6))
result = s.idxmax()
assert result == 5
s[5] = np.nan
result = s.idxmax()
assert result == 4
# Float64Index
# GH 5914
s = pd.Series([1, 2, 3], [1.1, 2.1, 3.1])
result = s.idxmax()
assert result == 3.1
result = s.idxmin()
assert result == 1.1
s = pd.Series(s.index, s.index)
result = s.idxmax()
assert result == 3.1
result = s.idxmin()
assert result == 1.1
def test_numpy_argmax_deprecated(self):
# See gh-16830
data = np.arange(1, 11)
s = Series(data, index=data)
with tm.assert_produces_warning(FutureWarning, check_stacklevel=False):
# The deprecation of Series.argmax also causes a deprecation
# warning when calling np.argmax. This behavior is temporary
# until the implementation of Series.argmax is corrected.
result = np.argmax(s)
assert result == 10
with tm.assert_produces_warning(FutureWarning):
# argmax is aliased to idxmax
result = s.argmax()
assert result == 10
if not _np_version_under1p10:
with tm.assert_produces_warning(FutureWarning,
check_stacklevel=False):
msg = "the 'out' parameter is not supported"
tm.assert_raises_regex(ValueError, msg, np.argmax,
s, out=data)
def test_ptp(self):
N = 1000
arr = np.random.randn(N)
ser = Series(arr)
assert np.ptp(ser) == np.ptp(arr)
# GH11163
s = Series([3, 5, np.nan, -3, 10])
assert s.ptp() == 13
assert pd.isna(s.ptp(skipna=False))
mi = pd.MultiIndex.from_product([['a', 'b'], [1, 2, 3]])
s = pd.Series([1, np.nan, 7, 3, 5, np.nan], index=mi)
expected = pd.Series([6, 2], index=['a', 'b'], dtype=np.float64)
tm.assert_series_equal(s.ptp(level=0), expected)
expected = pd.Series([np.nan, np.nan], index=['a', 'b'])
tm.assert_series_equal(s.ptp(level=0, skipna=False), expected)
with pytest.raises(ValueError):
s.ptp(axis=1)
s = pd.Series(['a', 'b', 'c', 'd', 'e'])
with pytest.raises(TypeError):
s.ptp()
with pytest.raises(NotImplementedError):
s.ptp(numeric_only=True)
def test_empty_timeseries_redections_return_nat(self):
# covers #11245
for dtype in ('m8[ns]', 'm8[ns]', 'M8[ns]', 'M8[ns, UTC]'):
assert Series([], dtype=dtype).min() is pd.NaT
assert Series([], dtype=dtype).max() is pd.NaT
def test_unique_data_ownership(self):
# it works! #1807
Series(Series(["a", "c", "b"]).unique()).sort_values()
def test_repeat(self):
s = Series(np.random.randn(3), index=['a', 'b', 'c'])
reps = s.repeat(5)
exp = Series(s.values.repeat(5), index=s.index.values.repeat(5))
assert_series_equal(reps, exp)
with tm.assert_produces_warning(FutureWarning):
result = s.repeat(reps=5)
assert_series_equal(result, exp)
to_rep = [2, 3, 4]
reps = s.repeat(to_rep)
exp = Series(s.values.repeat(to_rep),
index=s.index.values.repeat(to_rep))
assert_series_equal(reps, exp)
def test_numpy_repeat(self):
s = Series(np.arange(3), name='x')
expected = Series(s.values.repeat(2), name='x',
index=s.index.values.repeat(2))
assert_series_equal(np.repeat(s, 2), expected)
msg = "the 'axis' parameter is not supported"
tm.assert_raises_regex(ValueError, msg, np.repeat, s, 2, axis=0)
def test_searchsorted(self):
s = Series([1, 2, 3])
idx = s.searchsorted(1, side='left')
tm.assert_numpy_array_equal(idx, np.array([0], dtype=np.intp))
idx = s.searchsorted(1, side='right')
tm.assert_numpy_array_equal(idx, np.array([1], dtype=np.intp))
with tm.assert_produces_warning(FutureWarning):
idx = s.searchsorted(v=1, side='left')
tm.assert_numpy_array_equal(idx, np.array([0], dtype=np.intp))
def test_searchsorted_numeric_dtypes_scalar(self):
s = Series([1, 2, 90, 1000, 3e9])
r = s.searchsorted(30)
e = 2
assert r == e
r = s.searchsorted([30])
e = np.array([2], dtype=np.intp)
tm.assert_numpy_array_equal(r, e)
def test_searchsorted_numeric_dtypes_vector(self):
s = Series([1, 2, 90, 1000, 3e9])
r = s.searchsorted([91, 2e6])
e = np.array([3, 4], dtype=np.intp)
tm.assert_numpy_array_equal(r, e)
def test_search_sorted_datetime64_scalar(self):
s = Series(pd.date_range('20120101', periods=10, freq='2D'))
v = pd.Timestamp('20120102')
r = s.searchsorted(v)
e = 1
assert r == e
def test_search_sorted_datetime64_list(self):
s = Series(pd.date_range('20120101', periods=10, freq='2D'))
v = [pd.Timestamp('20120102'), pd.Timestamp('20120104')]
r = s.searchsorted(v)
e = np.array([1, 2], dtype=np.intp)
tm.assert_numpy_array_equal(r, e)
def test_searchsorted_sorter(self):
# GH8490
s = Series([3, 1, 2])
r = s.searchsorted([0, 3], sorter=np.argsort(s))
e = np.array([0, 2], dtype=np.intp)
tm.assert_numpy_array_equal(r, e)
def test_is_unique(self):
# GH11946
s = Series(np.random.randint(0, 10, size=1000))
assert not s.is_unique
s = Series(np.arange(1000))
assert s.is_unique
def test_is_unique_class_ne(self, capsys):
# GH 20661
class Foo(object):
def __init__(self, val):
self._value = val
def __ne__(self, other):
raise Exception("NEQ not supported")
li = [Foo(i) for i in range(5)]
s = pd.Series(li, index=[i for i in range(5)])
_, err = capsys.readouterr()
s.is_unique
_, err = capsys.readouterr()
assert len(err) == 0
def test_is_monotonic(self):
s = Series(np.random.randint(0, 10, size=1000))
assert not s.is_monotonic
s = Series(np.arange(1000))
assert s.is_monotonic
assert s.is_monotonic_increasing
s = Series(np.arange(1000, 0, -1))
assert s.is_monotonic_decreasing
s = Series(pd.date_range('20130101', periods=10))
assert s.is_monotonic
assert s.is_monotonic_increasing
s = Series(list(reversed(s.tolist())))
assert not s.is_monotonic
assert s.is_monotonic_decreasing
def test_sort_index_level(self):
mi = MultiIndex.from_tuples([[1, 1, 3], [1, 1, 1]], names=list('ABC'))
s = Series([1, 2], mi)
backwards = s.iloc[[1, 0]]
res = s.sort_index(level='A')
assert_series_equal(backwards, res)
res = s.sort_index(level=['A', 'B'])
assert_series_equal(backwards, res)
res = s.sort_index(level='A', sort_remaining=False)
assert_series_equal(s, res)
res = s.sort_index(level=['A', 'B'], sort_remaining=False)
assert_series_equal(s, res)
def test_apply_categorical(self):
values = pd.Categorical(list('ABBABCD'), categories=list('DCBA'),
ordered=True)
s = pd.Series(values, name='XX', index=list('abcdefg'))
result = s.apply(lambda x: x.lower())
# should be categorical dtype when the number of categories are
# the same
values = pd.Categorical(list('abbabcd'), categories=list('dcba'),
ordered=True)
exp = pd.Series(values, name='XX', index=list('abcdefg'))
tm.assert_series_equal(result, exp)
tm.assert_categorical_equal(result.values, exp.values)
result = s.apply(lambda x: 'A')
exp = pd.Series(['A'] * 7, name='XX', index=list('abcdefg'))
tm.assert_series_equal(result, exp)
assert result.dtype == np.object
def test_shift_int(self):
ts = self.ts.astype(int)
shifted = ts.shift(1)
expected = ts.astype(float).shift(1)
assert_series_equal(shifted, expected)
def test_shift_categorical(self):
# GH 9416
s = pd.Series(['a', 'b', 'c', 'd'], dtype='category')
assert_series_equal(s.iloc[:-1], s.shift(1).shift(-1).dropna())
sp1 = s.shift(1)
assert_index_equal(s.index, sp1.index)
assert np.all(sp1.values.codes[:1] == -1)
assert np.all(s.values.codes[:-1] == sp1.values.codes[1:])
sn2 = s.shift(-2)
assert_index_equal(s.index, sn2.index)
assert np.all(sn2.values.codes[-2:] == -1)
assert np.all(s.values.codes[2:] == sn2.values.codes[:-2])
assert_index_equal(s.values.categories, sp1.values.categories)
assert_index_equal(s.values.categories, sn2.values.categories)
def test_unstack(self):
from numpy import nan
index = MultiIndex(levels=[['bar', 'foo'], ['one', 'three', 'two']],
labels=[[1, 1, 0, 0], [0, 1, 0, 2]])
s = Series(np.arange(4.), index=index)
unstacked = s.unstack()
expected = DataFrame([[2., nan, 3.], [0., 1., nan]],
index=['bar', 'foo'],
columns=['one', 'three', 'two'])
assert_frame_equal(unstacked, expected)
unstacked = s.unstack(level=0)
assert_frame_equal(unstacked, expected.T)
index = MultiIndex(levels=[['bar'], ['one', 'two', 'three'], [0, 1]],
labels=[[0, 0, 0, 0, 0, 0], [0, 1, 2, 0, 1, 2],
[0, 1, 0, 1, 0, 1]])
s = Series(np.random.randn(6), index=index)
exp_index = MultiIndex(levels=[['one', 'two', 'three'], [0, 1]],
labels=[[0, 1, 2, 0, 1, 2], [0, 1, 0, 1, 0, 1]])
expected = DataFrame({'bar': s.values},
index=exp_index).sort_index(level=0)
unstacked = s.unstack(0).sort_index()
assert_frame_equal(unstacked, expected)
# GH5873
idx = pd.MultiIndex.from_arrays([[101, 102], [3.5, np.nan]])
ts = pd.Series([1, 2], index=idx)
left = ts.unstack()
right = DataFrame([[nan, 1], [2, nan]], index=[101, 102],
columns=[nan, 3.5])
assert_frame_equal(left, right)
idx = pd.MultiIndex.from_arrays([['cat', 'cat', 'cat', 'dog', 'dog'
], ['a', 'a', 'b', 'a', 'b'],
[1, 2, 1, 1, np.nan]])
ts = pd.Series([1.0, 1.1, 1.2, 1.3, 1.4], index=idx)
right = DataFrame([[1.0, 1.3], [1.1, nan], [nan, 1.4], [1.2, nan]],
columns=['cat', 'dog'])
tpls = [('a', 1), ('a', 2), ('b', nan), ('b', 1)]
right.index = pd.MultiIndex.from_tuples(tpls)
assert_frame_equal(ts.unstack(level=0), right)
def test_value_counts_datetime(self):
# most dtypes are tested in test_base.py
values = [pd.Timestamp('2011-01-01 09:00'),
pd.Timestamp('2011-01-01 10:00'),
pd.Timestamp('2011-01-01 11:00'),
pd.Timestamp('2011-01-01 09:00'),
pd.Timestamp('2011-01-01 09:00'),
pd.Timestamp('2011-01-01 11:00')]
exp_idx = pd.DatetimeIndex(['2011-01-01 09:00', '2011-01-01 11:00',
'2011-01-01 10:00'])
exp = pd.Series([3, 2, 1], index=exp_idx, name='xxx')
s = pd.Series(values, name='xxx')
tm.assert_series_equal(s.value_counts(), exp)
# check DatetimeIndex outputs the same result
idx = pd.DatetimeIndex(values, name='xxx')
tm.assert_series_equal(idx.value_counts(), exp)
# normalize
exp = pd.Series(np.array([3., 2., 1]) / 6.,
index=exp_idx, name='xxx')
tm.assert_series_equal(s.value_counts(normalize=True), exp)
tm.assert_series_equal(idx.value_counts(normalize=True), exp)
def test_value_counts_datetime_tz(self):
values = [pd.Timestamp('2011-01-01 09:00', tz='US/Eastern'),
pd.Timestamp('2011-01-01 10:00', tz='US/Eastern'),
pd.Timestamp('2011-01-01 11:00', tz='US/Eastern'),
pd.Timestamp('2011-01-01 09:00', tz='US/Eastern'),
pd.Timestamp('2011-01-01 09:00', tz='US/Eastern'),
pd.Timestamp('2011-01-01 11:00', tz='US/Eastern')]
exp_idx = pd.DatetimeIndex(['2011-01-01 09:00', '2011-01-01 11:00',
'2011-01-01 10:00'], tz='US/Eastern')
exp = pd.Series([3, 2, 1], index=exp_idx, name='xxx')
s = pd.Series(values, name='xxx')
tm.assert_series_equal(s.value_counts(), exp)
idx = pd.DatetimeIndex(values, name='xxx')
tm.assert_series_equal(idx.value_counts(), exp)
exp = pd.Series(np.array([3., 2., 1]) / 6.,
index=exp_idx, name='xxx')
tm.assert_series_equal(s.value_counts(normalize=True), exp)
tm.assert_series_equal(idx.value_counts(normalize=True), exp)
def test_value_counts_period(self):
values = [pd.Period('2011-01', freq='M'),
pd.Period('2011-02', freq='M'),
pd.Period('2011-03', freq='M'),
pd.Period('2011-01', freq='M'),
pd.Period('2011-01', freq='M'),
pd.Period('2011-03', freq='M')]
exp_idx = pd.PeriodIndex(['2011-01', '2011-03', '2011-02'], freq='M')
exp = pd.Series([3, 2, 1], index=exp_idx, name='xxx')
s = pd.Series(values, name='xxx')
tm.assert_series_equal(s.value_counts(), exp)
# check DatetimeIndex outputs the same result
idx = pd.PeriodIndex(values, name='xxx')
tm.assert_series_equal(idx.value_counts(), exp)
# normalize
exp = pd.Series(np.array([3., 2., 1]) / 6.,
index=exp_idx, name='xxx')
tm.assert_series_equal(s.value_counts(normalize=True), exp)
tm.assert_series_equal(idx.value_counts(normalize=True), exp)
def test_value_counts_categorical_ordered(self):
# most dtypes are tested in test_base.py
values = pd.Categorical([1, 2, 3, 1, 1, 3], ordered=True)
exp_idx = pd.CategoricalIndex([1, 3, 2], categories=[1, 2, 3],
ordered=True)
exp = pd.Series([3, 2, 1], index=exp_idx, name='xxx')
s = pd.Series(values, name='xxx')
tm.assert_series_equal(s.value_counts(), exp)
# check CategoricalIndex outputs the same result
idx = pd.CategoricalIndex(values, name='xxx')
tm.assert_series_equal(idx.value_counts(), exp)
# normalize
exp = pd.Series(np.array([3., 2., 1]) / 6.,
index=exp_idx, name='xxx')
tm.assert_series_equal(s.value_counts(normalize=True), exp)
tm.assert_series_equal(idx.value_counts(normalize=True), exp)
def test_value_counts_categorical_not_ordered(self):
values = pd.Categorical([1, 2, 3, 1, 1, 3], ordered=False)
exp_idx = pd.CategoricalIndex([1, 3, 2], categories=[1, 2, 3],
ordered=False)
exp = pd.Series([3, 2, 1], index=exp_idx, name='xxx')
s = pd.Series(values, name='xxx')
tm.assert_series_equal(s.value_counts(), exp)
# check CategoricalIndex outputs the same result
idx = pd.CategoricalIndex(values, name='xxx')
tm.assert_series_equal(idx.value_counts(), exp)
# normalize
exp = pd.Series(np.array([3., 2., 1]) / 6.,
index=exp_idx, name='xxx')
tm.assert_series_equal(s.value_counts(normalize=True), exp)
tm.assert_series_equal(idx.value_counts(normalize=True), exp)
@pytest.fixture
def s_main_dtypes():
df = pd.DataFrame(
{'datetime': pd.to_datetime(['2003', '2002',
'2001', '2002',
'2005']),
'datetimetz': pd.to_datetime(
['2003', '2002',
'2001', '2002',
'2005']).tz_localize('US/Eastern'),
'timedelta': pd.to_timedelta(['3d', '2d', '1d',
'2d', '5d'])})
for dtype in ['int8', 'int16', 'int32', 'int64',
'float32', 'float64',
'uint8', 'uint16', 'uint32', 'uint64']:
df[dtype] = Series([3, 2, 1, 2, 5], dtype=dtype)
return df
class TestMode(object):
@pytest.mark.parametrize('dropna, expected', [
(True, Series([], dtype=np.float64)),
(False, Series([], dtype=np.float64))
])
def test_mode_empty(self, dropna, expected):
s = Series([], dtype=np.float64)
result = s.mode(dropna)
tm.assert_series_equal(result, expected)
@pytest.mark.parametrize('dropna, data, expected', [
(True, [1, 1, 1, 2], [1]),
(True, [1, 1, 1, 2, 3, 3, 3], [1, 3]),
(False, [1, 1, 1, 2], [1]),
(False, [1, 1, 1, 2, 3, 3, 3], [1, 3]),
])
@pytest.mark.parametrize(
'dt',
list(np.typecodes['AllInteger'] + np.typecodes['Float'])
)
def test_mode_numerical(self, dropna, data, expected, dt):
s = Series(data, dtype=dt)
result = s.mode(dropna)
expected = Series(expected, dtype=dt)
tm.assert_series_equal(result, expected)
@pytest.mark.parametrize('dropna, expected', [
(True, [1.0]),
(False, [1, np.nan]),
])
def test_mode_numerical_nan(self, dropna, expected):
s = Series([1, 1, 2, np.nan, np.nan])
result = s.mode(dropna)
expected = Series(expected)
tm.assert_series_equal(result, expected)
@pytest.mark.parametrize('dropna, expected1, expected2, expected3', [
(True, ['b'], ['bar'], ['nan']),
(False, ['b'], [np.nan], ['nan'])
])
def test_mode_str_obj(self, dropna, expected1, expected2, expected3):
# Test string and object types.
data = ['a'] * 2 + ['b'] * 3
s = Series(data, dtype='c')
result = s.mode(dropna)
expected1 = Series(expected1, dtype='c')
tm.assert_series_equal(result, expected1)
data = ['foo', 'bar', 'bar', np.nan, np.nan, np.nan]
s = Series(data, dtype=object)
result = s.mode(dropna)
expected2 = Series(expected2, dtype=object)
tm.assert_series_equal(result, expected2)
data = ['foo', 'bar', 'bar', np.nan, np.nan, np.nan]
s = Series(data, dtype=object).astype(str)
result = s.mode(dropna)
expected3 = Series(expected3, dtype=str)
tm.assert_series_equal(result, expected3)
@pytest.mark.parametrize('dropna, expected1, expected2', [
(True, ['foo'], ['foo']),
(False, ['foo'], [np.nan])
])
def test_mode_mixeddtype(self, dropna, expected1, expected2):
s = Series([1, 'foo', 'foo'])
result = s.mode(dropna)
expected = Series(expected1)
tm.assert_series_equal(result, expected)
s = Series([1, 'foo', 'foo', np.nan, np.nan, np.nan])
result = s.mode(dropna)
expected = Series(expected2, dtype=object)
tm.assert_series_equal(result, expected)
@pytest.mark.parametrize('dropna, expected1, expected2', [
(True, ['1900-05-03', '2011-01-03', '2013-01-02'],
['2011-01-03', '2013-01-02']),
(False, [np.nan], [np.nan, '2011-01-03', '2013-01-02']),
])
def test_mode_datetime(self, dropna, expected1, expected2):
s = Series(['2011-01-03', '2013-01-02',
'1900-05-03', 'nan', 'nan'], dtype='M8[ns]')
result = s.mode(dropna)
expected1 = Series(expected1, dtype='M8[ns]')
tm.assert_series_equal(result, expected1)
s = Series(['2011-01-03', '2013-01-02', '1900-05-03',
'2011-01-03', '2013-01-02', 'nan', 'nan'],
dtype='M8[ns]')
result = s.mode(dropna)
expected2 = Series(expected2, dtype='M8[ns]')
tm.assert_series_equal(result, expected2)
@pytest.mark.parametrize('dropna, expected1, expected2', [
(True, ['-1 days', '0 days', '1 days'], ['2 min', '1 day']),
(False, [np.nan], [np.nan, '2 min', '1 day']),
])
def test_mode_timedelta(self, dropna, expected1, expected2):
# gh-5986: Test timedelta types.
s = Series(['1 days', '-1 days', '0 days', 'nan', 'nan'],
dtype='timedelta64[ns]')
result = s.mode(dropna)
expected1 = Series(expected1, dtype='timedelta64[ns]')
tm.assert_series_equal(result, expected1)
s = Series(['1 day', '1 day', '-1 day', '-1 day 2 min',
'2 min', '2 min', 'nan', 'nan'],
dtype='timedelta64[ns]')
result = s.mode(dropna)
expected2 = Series(expected2, dtype='timedelta64[ns]')
tm.assert_series_equal(result, expected2)
@pytest.mark.parametrize('dropna, expected1, expected2, expected3', [
(True, Categorical([1, 2], categories=[1, 2]),
Categorical(['a'], categories=[1, 'a']),
Categorical([3, 1], categories=[3, 2, 1], ordered=True)),
(False, Categorical([np.nan], categories=[1, 2]),
Categorical([np.nan, 'a'], categories=[1, 'a']),
Categorical([np.nan, 3, 1], categories=[3, 2, 1], ordered=True)),
])
def test_mode_category(self, dropna, expected1, expected2, expected3):
s = Series(Categorical([1, 2, np.nan, np.nan]))
result = s.mode(dropna)
expected1 = Series(expected1, dtype='category')
tm.assert_series_equal(result, expected1)
s = Series(Categorical([1, 'a', 'a', np.nan, np.nan]))
result = s.mode(dropna)
expected2 = Series(expected2, dtype='category')
tm.assert_series_equal(result, expected2)
s = Series(Categorical([1, 1, 2, 3, 3, np.nan, np.nan],
categories=[3, 2, 1], ordered=True))
result = s.mode(dropna)
expected3 = Series(expected3, dtype='category')
tm.assert_series_equal(result, expected3)
@pytest.mark.parametrize('dropna, expected1, expected2', [
(True, [2**63], [1, 2**63]),
(False, [2**63], [1, 2**63])
])
def test_mode_intoverflow(self, dropna, expected1, expected2):
# Test for uint64 overflow.
s = Series([1, 2**63, 2**63], dtype=np.uint64)
result = s.mode(dropna)
expected1 = Series(expected1, dtype=np.uint64)
tm.assert_series_equal(result, expected1)
s = Series([1, 2**63], dtype=np.uint64)
result = s.mode(dropna)
expected2 = Series(expected2, dtype=np.uint64)
tm.assert_series_equal(result, expected2)
@pytest.mark.skipif(not compat.PY3, reason="only PY3")
def test_mode_sortwarning(self):
# Check for the warning that is raised when the mode
# results cannot be sorted
expected = Series(['foo', np.nan])
s = Series([1, 'foo', 'foo', np.nan, np.nan])
with tm.assert_produces_warning(UserWarning, check_stacklevel=False):
result = s.mode(dropna=False)
result = result.sort_values().reset_index(drop=True)
tm.assert_series_equal(result, expected)
def assert_check_nselect_boundary(vals, dtype, method):
# helper function for 'test_boundary_{dtype}' tests
s = Series(vals, dtype=dtype)
result = getattr(s, method)(3)
expected_idxr = [0, 1, 2] if method == 'nsmallest' else [3, 2, 1]
expected = s.loc[expected_idxr]
tm.assert_series_equal(result, expected)
class TestNLargestNSmallest(object):
@pytest.mark.parametrize(
"r", [Series([3., 2, 1, 2, '5'], dtype='object'),
Series([3., 2, 1, 2, 5], dtype='object'),
# not supported on some archs
# Series([3., 2, 1, 2, 5], dtype='complex256'),
Series([3., 2, 1, 2, 5], dtype='complex128'),
Series(list('abcde')),
Series(list('abcde'), dtype='category')])
def test_error(self, r):
dt = r.dtype
msg = ("Cannot use method 'n(larg|small)est' with "
"dtype {dt}".format(dt=dt))
args = 2, len(r), 0, -1
methods = r.nlargest, r.nsmallest
for method, arg in product(methods, args):
with tm.assert_raises_regex(TypeError, msg):
method(arg)
@pytest.mark.parametrize(
"s",
[v for k, v in s_main_dtypes().iteritems()])
def test_nsmallest_nlargest(self, s):
# float, int, datetime64 (use i8), timedelts64 (same),
# object that are numbers, object that are strings
assert_series_equal(s.nsmallest(2), s.iloc[[2, 1]])
assert_series_equal(s.nsmallest(2, keep='last'), s.iloc[[2, 3]])
empty = s.iloc[0:0]
assert_series_equal(s.nsmallest(0), empty)
assert_series_equal(s.nsmallest(-1), empty)
assert_series_equal(s.nlargest(0), empty)
assert_series_equal(s.nlargest(-1), empty)
assert_series_equal(s.nsmallest(len(s)), s.sort_values())
assert_series_equal(s.nsmallest(len(s) + 1), s.sort_values())
assert_series_equal(s.nlargest(len(s)), s.iloc[[4, 0, 1, 3, 2]])
assert_series_equal(s.nlargest(len(s) + 1),
s.iloc[[4, 0, 1, 3, 2]])
def test_misc(self):
s = Series([3., np.nan, 1, 2, 5])
assert_series_equal(s.nlargest(), s.iloc[[4, 0, 3, 2]])
assert_series_equal(s.nsmallest(), s.iloc[[2, 3, 0, 4]])
msg = 'keep must be either "first", "last"'
with tm.assert_raises_regex(ValueError, msg):
s.nsmallest(keep='invalid')
with tm.assert_raises_regex(ValueError, msg):
s.nlargest(keep='invalid')
# GH 15297
s = Series([1] * 5, index=[1, 2, 3, 4, 5])
expected_first = Series([1] * 3, index=[1, 2, 3])
expected_last = Series([1] * 3, index=[5, 4, 3])
result = s.nsmallest(3)
assert_series_equal(result, expected_first)
result = s.nsmallest(3, keep='last')
assert_series_equal(result, expected_last)
result = s.nlargest(3)
assert_series_equal(result, expected_first)
result = s.nlargest(3, keep='last')
assert_series_equal(result, expected_last)
@pytest.mark.parametrize('n', range(1, 5))
def test_n(self, n):
# GH 13412
s = Series([1, 4, 3, 2], index=[0, 0, 1, 1])
result = s.nlargest(n)
expected = s.sort_values(ascending=False).head(n)
assert_series_equal(result, expected)
result = s.nsmallest(n)
expected = s.sort_values().head(n)
assert_series_equal(result, expected)
def test_boundary_integer(self, nselect_method, any_int_dtype):
# GH 21426
dtype_info = np.iinfo(any_int_dtype)
min_val, max_val = dtype_info.min, dtype_info.max
vals = [min_val, min_val + 1, max_val - 1, max_val]
assert_check_nselect_boundary(vals, any_int_dtype, nselect_method)
def test_boundary_float(self, nselect_method, float_dtype):
# GH 21426
dtype_info = np.finfo(float_dtype)
min_val, max_val = dtype_info.min, dtype_info.max
min_2nd, max_2nd = np.nextafter(
[min_val, max_val], 0, dtype=float_dtype)
vals = [min_val, min_2nd, max_2nd, max_val]
assert_check_nselect_boundary(vals, float_dtype, nselect_method)
@pytest.mark.parametrize('dtype', ['datetime64[ns]', 'timedelta64[ns]'])
def test_boundary_datetimelike(self, nselect_method, dtype):
# GH 21426
# use int64 bounds and +1 to min_val since true minimum is NaT
# (include min_val/NaT at end to maintain same expected_idxr)
dtype_info = np.iinfo('int64')
min_val, max_val = dtype_info.min, dtype_info.max
vals = [min_val + 1, min_val + 2, max_val - 1, max_val, min_val]
assert_check_nselect_boundary(vals, dtype, nselect_method)
class TestCategoricalSeriesAnalytics(object):
def test_count(self):
s = Series(Categorical([np.nan, 1, 2, np.nan],
categories=[5, 4, 3, 2, 1], ordered=True))
result = s.count()
assert result == 2
def test_min_max(self):
# unordered cats have no min/max
cat = Series(Categorical(["a", "b", "c", "d"], ordered=False))
pytest.raises(TypeError, lambda: cat.min())
pytest.raises(TypeError, lambda: cat.max())
cat = Series(Categorical(["a", "b", "c", "d"], ordered=True))
_min = cat.min()
_max = cat.max()
assert _min == "a"
assert _max == "d"
cat = Series(Categorical(["a", "b", "c", "d"], categories=[
'd', 'c', 'b', 'a'], ordered=True))
_min = cat.min()
_max = cat.max()
assert _min == "d"
assert _max == "a"
cat = Series(Categorical(
[np.nan, "b", "c", np.nan], categories=['d', 'c', 'b', 'a'
], ordered=True))
_min = cat.min()
_max = cat.max()
assert np.isnan(_min)
assert _max == "b"
cat = Series(Categorical(
[np.nan, 1, 2, np.nan], categories=[5, 4, 3, 2, 1], ordered=True))
_min = cat.min()
_max = cat.max()
assert np.isnan(_min)
assert _max == 1
def test_value_counts(self):
# GH 12835
cats = Categorical(list('abcccb'), categories=list('cabd'))
s = Series(cats, name='xxx')
res = s.value_counts(sort=False)
exp_index = CategoricalIndex(list('cabd'), categories=cats.categories)
exp = Series([3, 1, 2, 0], name='xxx', index=exp_index)
tm.assert_series_equal(res, exp)
res = s.value_counts(sort=True)
exp_index = CategoricalIndex(list('cbad'), categories=cats.categories)
exp = Series([3, 2, 1, 0], name='xxx', index=exp_index)
tm.assert_series_equal(res, exp)
# check object dtype handles the Series.name as the same
# (tested in test_base.py)
s = Series(["a", "b", "c", "c", "c", "b"], name='xxx')
res = s.value_counts()
exp = Series([3, 2, 1], name='xxx', index=["c", "b", "a"])
tm.assert_series_equal(res, exp)
def test_value_counts_with_nan(self):
# see gh-9443
# sanity check
s = Series(["a", "b", "a"], dtype="category")
exp = Series([2, 1], index=CategoricalIndex(["a", "b"]))
res = s.value_counts(dropna=True)
tm.assert_series_equal(res, exp)
res = s.value_counts(dropna=True)
tm.assert_series_equal(res, exp)
# same Series via two different constructions --> same behaviour
series = [
Series(["a", "b", None, "a", None, None], dtype="category"),
Series(Categorical(["a", "b", None, "a", None, None],
categories=["a", "b"]))
]
for s in series:
# None is a NaN value, so we exclude its count here
exp = Series([2, 1], index=CategoricalIndex(["a", "b"]))
res = s.value_counts(dropna=True)
tm.assert_series_equal(res, exp)
# we don't exclude the count of None and sort by counts
exp = Series([3, 2, 1], index=CategoricalIndex([np.nan, "a", "b"]))
res = s.value_counts(dropna=False)
tm.assert_series_equal(res, exp)
# When we aren't sorting by counts, and np.nan isn't a
# category, it should be last.
exp = Series([2, 1, 3], index=CategoricalIndex(["a", "b", np.nan]))
res = s.value_counts(dropna=False, sort=False)
tm.assert_series_equal(res, exp)
@pytest.mark.parametrize(
"dtype",
["int_", "uint", "float_", "unicode_", "timedelta64[h]",
pytest.param("datetime64[D]",
marks=pytest.mark.xfail(reason="issue7996"))]
)
@pytest.mark.parametrize("is_ordered", [True, False])
def test_drop_duplicates_categorical_non_bool(self, dtype, is_ordered):
cat_array = np.array([1, 2, 3, 4, 5], dtype=np.dtype(dtype))
# Test case 1
input1 = np.array([1, 2, 3, 3], dtype=np.dtype(dtype))
tc1 = Series(Categorical(input1, categories=cat_array,
ordered=is_ordered))
expected = Series([False, False, False, True])
tm.assert_series_equal(tc1.duplicated(), expected)
tm.assert_series_equal(tc1.drop_duplicates(), tc1[~expected])
sc = tc1.copy()
sc.drop_duplicates(inplace=True)
tm.assert_series_equal(sc, tc1[~expected])
expected = Series([False, False, True, False])
tm.assert_series_equal(tc1.duplicated(keep='last'), expected)
tm.assert_series_equal(tc1.drop_duplicates(keep='last'),
tc1[~expected])
sc = tc1.copy()
sc.drop_duplicates(keep='last', inplace=True)
tm.assert_series_equal(sc, tc1[~expected])
expected = Series([False, False, True, True])
tm.assert_series_equal(tc1.duplicated(keep=False), expected)
tm.assert_series_equal(tc1.drop_duplicates(keep=False), tc1[~expected])
sc = tc1.copy()
sc.drop_duplicates(keep=False, inplace=True)
tm.assert_series_equal(sc, tc1[~expected])
# Test case 2
input2 = np.array([1, 2, 3, 5, 3, 2, 4], dtype=np.dtype(dtype))
tc2 = Series(Categorical(
input2, categories=cat_array, ordered=is_ordered)
)
expected = Series([False, False, False, False, True, True, False])
tm.assert_series_equal(tc2.duplicated(), expected)
tm.assert_series_equal(tc2.drop_duplicates(), tc2[~expected])
sc = tc2.copy()
sc.drop_duplicates(inplace=True)
tm.assert_series_equal(sc, tc2[~expected])
expected = Series([False, True, True, False, False, False, False])
tm.assert_series_equal(tc2.duplicated(keep='last'), expected)
tm.assert_series_equal(tc2.drop_duplicates(keep='last'),
tc2[~expected])
sc = tc2.copy()
sc.drop_duplicates(keep='last', inplace=True)
tm.assert_series_equal(sc, tc2[~expected])
expected = Series([False, True, True, False, True, True, False])
tm.assert_series_equal(tc2.duplicated(keep=False), expected)
tm.assert_series_equal(tc2.drop_duplicates(keep=False), tc2[~expected])
sc = tc2.copy()
sc.drop_duplicates(keep=False, inplace=True)
tm.assert_series_equal(sc, tc2[~expected])
@pytest.mark.parametrize("is_ordered", [True, False])
def test_drop_duplicates_categorical_bool(self, is_ordered):
tc = Series(Categorical([True, False, True, False],
categories=[True, False], ordered=is_ordered))
expected = Series([False, False, True, True])
tm.assert_series_equal(tc.duplicated(), expected)
tm.assert_series_equal(tc.drop_duplicates(), tc[~expected])
sc = tc.copy()
sc.drop_duplicates(inplace=True)
tm.assert_series_equal(sc, tc[~expected])
expected = Series([True, True, False, False])
tm.assert_series_equal(tc.duplicated(keep='last'), expected)
tm.assert_series_equal(tc.drop_duplicates(keep='last'), tc[~expected])
sc = tc.copy()
sc.drop_duplicates(keep='last', inplace=True)
tm.assert_series_equal(sc, tc[~expected])
expected = Series([True, True, True, True])
tm.assert_series_equal(tc.duplicated(keep=False), expected)
tm.assert_series_equal(tc.drop_duplicates(keep=False), tc[~expected])
sc = tc.copy()
sc.drop_duplicates(keep=False, inplace=True)
tm.assert_series_equal(sc, tc[~expected])
| {
"content_hash": "97756c3ba4f78df10cb1939cfe5e3d4b",
"timestamp": "",
"source": "github",
"line_count": 2256,
"max_line_length": 79,
"avg_line_length": 36.82225177304964,
"alnum_prop": 0.5316416077812955,
"repo_name": "louispotok/pandas",
"id": "b9c7b837b8b817e8bfc1dd84e18c99ee0a88d4c5",
"size": "83121",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "pandas/tests/series/test_analytics.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Batchfile",
"bytes": "3847"
},
{
"name": "C",
"bytes": "432930"
},
{
"name": "C++",
"bytes": "17193"
},
{
"name": "HTML",
"bytes": "551714"
},
{
"name": "Makefile",
"bytes": "563"
},
{
"name": "PowerShell",
"bytes": "2970"
},
{
"name": "Python",
"bytes": "13452425"
},
{
"name": "Shell",
"bytes": "25056"
},
{
"name": "Smarty",
"bytes": "2045"
}
],
"symlink_target": ""
} |
CLASS({
package: 'foam.apps.builder.questionnaire',
name: 'NewOrExistingDAOWizard',
extends: 'foam.apps.builder.wizard.NewOrExistingDAOWizard',
requires: [
'foam.apps.builder.questionnaire.DAOWizard',
'foam.apps.builder.questionnaire.NewOrExistingModelWizard',
],
properties: [
{
name: 'newViewFactory',
defaultValue: { factory_: 'foam.apps.builder.questionnaire.NewDAOWizard' },
},
{
name: 'existingViewFactory',
defaultValue: null,
// defaultValue: {
// factory_: 'foam.apps.builder.questionnaire.NewOrExistingModelWizard',
// },
},
{
name: 'title',
defaultValue: 'Choose a Data Source',
},
],
templates: [
function instructionHTML() {/*
<p>When a user completes their Questionnaire, it will
be saved into a Data Source. This could be inside the tablet the user is holding,
in the cloud with Google Drive, or on another device on your network.
You can create a new Data Source, or share
an existing one with your other Apps. Typically you can re-use an existing Data
Source if you have several questionnaires used in the same office, or want
a centralized store of all the results.
</p>
*/},
],
});
| {
"content_hash": "f1c5c6edd150f007dab68a47f582a7c7",
"timestamp": "",
"source": "github",
"line_count": 45,
"max_line_length": 89,
"avg_line_length": 28.57777777777778,
"alnum_prop": 0.6477449455676516,
"repo_name": "jacksonic/foam",
"id": "32c3514cc4f0a5e15467c3e603940d3f01480a8f",
"size": "1590",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "js/foam/apps/builder/questionnaire/NewOrExistingDAOWizard.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "913"
},
{
"name": "CSS",
"bytes": "55653"
},
{
"name": "HTML",
"bytes": "317438"
},
{
"name": "Java",
"bytes": "166812"
},
{
"name": "JavaScript",
"bytes": "5028390"
},
{
"name": "Objective-J",
"bytes": "834"
},
{
"name": "Shell",
"bytes": "23387"
}
],
"symlink_target": ""
} |
require "spec_helper"
describe Redistat::Event do
include Redistat::Database
before(:each) do
db.flushdb
@scope = "PageViews"
@label = "about_us"
@label_hash = Digest::SHA1.hexdigest(@label)
@stats = {'views' => 1}
@meta = {'user_id' => 239}
@options = {:depth => :hour}
@date = Time.now
@event = Redistat::Event.new(@scope, @label, @date, @stats, @options, @meta)
end
it "should initialize properly" do
@event.id.should be_nil
@event.scope.to_s.should == @scope
@event.label.to_s.should == @label
@event.label_hash.should == @label_hash
@event.date.to_time.to_s.should == @date.to_s
@event.stats.should == @stats
@event.meta.should == @meta
@event.options.should == @event.default_options.merge(@options)
end
it "should allow changing attributes" do
# date
@event.date.to_time.to_s.should == @date.to_s
@date = Time.now
@event.date = @date
@event.date.to_time.to_s.should == @date.to_s
# label
@event.label.to_s.should == @label
@event.label_hash.should == @label_hash
@label = "contact_us"
@label_hash = Digest::SHA1.hexdigest(@label)
@event.label = @label
@event.label.to_s.should == @label
@event.label_hash.should == @label_hash
end
it "should increment next_id" do
event = Redistat::Event.new("VisitorCount", @label, @date, @stats, @options, @meta)
@event.next_id.should == 1
event.next_id.should == 1
@event.next_id.should == 2
event.next_id.should == 2
end
it "should store event properly" do
@event = Redistat::Event.new(@scope, @label, @date, @stats, @options.merge({:store_event => true}), @meta)
@event.new?.should be_true
@event.save
@event.new?.should be_false
keys = db.keys "*"
keys.should include("#{@event.scope}#{Redistat::KEY_EVENT}#{@event.id}")
keys.should include("#{@event.scope}#{Redistat::KEY_EVENT_IDS}")
end
it "should find event by id" do
@event = Redistat::Event.new(@scope, @label, @date, @stats, @options.merge({:store_event => true}), @meta).save
fetched = Redistat::Event.find(@scope, @event.id)
@event.scope.to_s.should == fetched.scope.to_s
@event.label.to_s.should == fetched.label.to_s
@event.date.to_s.should == fetched.date.to_s
@event.stats.should == fetched.stats
@event.meta.should == fetched.meta
end
it "should store summarized statistics" do
2.times do |i|
@event = Redistat::Event.new(@scope, @label, @date, @stats, @options, @meta).save
Redistat::Date::DEPTHS.each do |depth|
summary = db.hgetall @event.key.to_s(depth)
summary.should have_at_least(1).items
summary["views"].should == (i+1).to_s
break if depth == :hour
end
end
end
end
| {
"content_hash": "b65f2a0eef5490941b9377eda8a283c7",
"timestamp": "",
"source": "github",
"line_count": 85,
"max_line_length": 115,
"avg_line_length": 32.67058823529412,
"alnum_prop": 0.6262153402952827,
"repo_name": "jylamont/redistat",
"id": "232ba9625608a702036356280866e67fc3af0093",
"size": "2777",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "spec/event_spec.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "106713"
}
],
"symlink_target": ""
} |
#ifndef DEFINE_H
#define DEFINE_H
// This file holds all of the things that should be preprocessed.
#include "..\headers\global.h"
#include "..\headers\itempid.h"
#include "..\headers\scripts.h"
#include "..\headers\teams.h"
#include "..\headers\Condtion.h"
//#include "..\headers\RepPoint.h"
#include "..\headers\AIPacket.h"
#include "..\headers\ExpPoint.h"
#include "..\headers\ScenePid.h"
#include "..\headers\Maps.h"
#include "..\headers\animcomd.h"
#include "..\headers\CritrPid.h"
#include "..\headers\ArtFid.h"
#include "..\headers\Party.h"
#include "..\headers\Reaction.h"
// script.h: Script Procedure Types //
#define no_proc (0)
#define start_proc (1)
#define spatial_proc (2)
#define description_proc (3)
#define pickup_proc (4)
#define drop_proc (5)
#define use_proc (6)
#define use_obj_on_proc (7)
#define use_skill_on_proc (8)
#define use_ad_on_proc (9)
#define use_disad_on_proc (10)
#define talk_proc (11)
#define critter_proc (12)
#define combat_proc (13)
#define damage_proc (14)
#define map_enter_proc (15)
#define map_exit_proc (16)
#define create_proc (17)
#define destroy_proc (18)
#define barter_init_proc (19)
#define barter_proc (20)
#define look_at_proc (21)
#define timed_event_proc (22)
#define map_update_proc (23)
// Map-Enter Proc subdefines
// Warning: This one is only valid in map_enter proc right when run!
///#define map_first_run (fixed_param)
#define METARULE_TEST_FIRSTRUN 14
#define map_first_run metarule(METARULE_TEST_FIRSTRUN, 0)
#define METARULE_IS_LOADGAME 22
#define is_loading_game metarule(METARULE_IS_LOADGAME, 0)
// script.h: Script Combat Procedure SubTypes //
#define COMBAT_SUBTYPE_WEAPON_USED (1)
#define COMBAT_SUBTYPE_HIT_SUCCEEDED (2)
#define COMBAT_SUBTYPE_SEQUENCING (3)
#define COMBAT_SUBTYPE_TURN (4)
#define COMBAT_SUBTYPE_NONCOM_TURN (5)
// ----------------------------------------------------------------------- //
// pc critter defines //
#define give_character_points(X) give_exp_points(X)
// create_object defines //
#define create_object(X,Y,Z) create_object_sid(X,Y,Z,-1)
//#define destroy_object(X) destroy_mult_objs(X,1)
//#define add_obj_to_inven(X,Y) add_mult_objs_to_inven(X,Y,1)
//#define rm_obj_from_inven(X,Y) rm_mult_objs_from_inven(X,Y,1)
// combat defines //
#define attack(WHO) attack_complex(WHO,0,1,0,0,30000,0,0)
// wield_obj defines //
#define wield_obj(WHAT) wield_obj_critter(self_obj,WHAT)
#define gdialog_barter gdialog_mod_barter(0)
// Movie number defines //
// Commented out movies are done in the C-engine. JLR
//#define INTERPLAY_LOGO_MOVIE_PC 0 // "iplogo.mve", // Interplay logo.
//#define INTRO_MOVIE 1 // "intro.mve", // Intro.
//#define ELDER_MOVIE 2 // "elder.mve",
#define VSUIT_MOVIE 3 // "vsuit.mve",
#define AFAILED_MOVIE 4 // "afailed.mve",
#define ADESTROY_MOVIE 5 // "adestroy.mve",
#define CAR_MOVIE 6 // "car.mve",
#define CARTUCCI_MOVIE 7 // "cartucci.mve",
#define DETHCLAW_MOVIE 8 // "dethclaw.mve",
#define TANKER_MOVIE 9 // "tanker.mve",
#define ENCLAVE_MOVIE 10 // "enclave.mve",
#define DERRICK_MOVIE 11 // "derrick.mve"
// float_msg defines //
#define FLOAT_MSG_WARNING (-2)
#define FLOAT_MSG_SEQUENTIAL (-1)
#define FLOAT_MSG_NORMAL (0)
#define FLOAT_MSG_BLACK (1)
#define FLOAT_MSG_RED (2)
#define FLOAT_MSG_GREEN (3)
#define FLOAT_MSG_BLUE (4)
#define FLOAT_MSG_PURPLE (5)
#define FLOAT_MSG_NEAR_WHITE (6)
#define FLOAT_MSG_LIGHT_RED (7)
#define FLOAT_MSG_YELLOW (8)
#define FLOAT_MSG_WHITE (9)
#define FLOAT_MSG_GREY (10)
#define FLOAT_MSG_DARK_GREY (11)
#define FLOAT_MSG_LIGHT_GREY (12)
#define float_msg_clear(WHO) float_msg(WHO,0,0)
// dialogue defines //
#define start_dialogue(X,Y) start_gdialog(-1,X,Y,-1,-1)
// head_anim enums
//#define very_good_reaction (0)
#define good_fidget (1)
//#define good_to_neutral (2)
//#define neutral_to_good (3)
#define neutral_fidget (4)
//#define neutral_to_bad (5)
//#define bad_to_neutral (6)
#define bad_fidget (7)
//#define very_bad_reaction (8)
//#define good_phonemes (9)
//#define neutral_phonemes (10)
//#define bad_phonemes (11)
// Head defines //
#define HEAD_MARCUS (1) //marcus -- Party Member (found in Broken Hills)
#define HEAD_MYRON (2) //Myron -- Party Member (found in New Reno)
#define HEAD_ELDER (3) // Elder -- (found in Arroyo)
#define HEAD_LYNETTE (4) // Lynette -- fount in Vault City
#define HEAD_HAROLD (5) // HAROLD -- found in Gecko
#define HEAD_TANDI (6) // Tandi -- Leader of the NCR
#define HEAD_COM_OFFICER (7) // Com Officer in Gecko
#define HEAD_SULIK (8) // Sulik -- Party Member (found in Klamath)
#define HEAD_PRESIDENT (9) // President of the Enclave
#define HEAD_HAKUNIN (10) // Hakunin -- Found in Arroyo
#define HEAD_BOSS (11)
#define HEAD_DYING_HAKUNIN (12)
/*
#define HEAD_OVERSEER (1) //ovrsr -- vault
*/
// Head defines //
#define BACKGROUND1 (2) // rstymetl
#define BACKGROUND_HUB (3) //hub.frm
#define BACKGROUND_NECROPOLIS (4) //necro.frm
#define BACKGROUND_BHOOD (5) //bhood.frm
#define BACKGROUND_MILITARYBS (6) //military.frm
#define BACKGROUND_JUNKTOWN (7) //junktown.frm
#define BACKGROUND_CATHEDRAL (8) //cath.frm
#define BACKGROUND_SHADY (9) //shady.frm
#define BACKGROUND_VAULT (10) //vault.frm
#define BACKGROUND_MASTER (11) //master.frm
#define BACKGROUND_FOLLOWER (12) //follow.frm
#define BACKGROUND_RAIDERS (13) //raider.frm
// Start of Fallout 2: Backgrounds
#define BACKGROUND_CAVE (14) //cave0001.frm
#define BACKGROUND_ENCLAVE (15) //enclave.frm
#define BACKGROUND_WASTELAND (16) //wastelnd.frm
#define BACKGROUND_BOSS (17) // boss.frm
#define BACKGROUND_PRESIDENT (18) // pres.frm
#define BACKGROUND_TENT (19) // tent.frm
#define BACKGROUND_ADOBE (20) // Adobe.frm
// Mood defines //
#define GOOD_REACTION (49)
#define NEUTRAL_REACTION (50)
#define BAD_REACTION (51)
//#define BAD_REACTION (49)
//#define NEUTRAL_REACTION (50)
//#define GOOD_REACTION (51)
// ----------------------------------------------------------------------- //
// ----------------------------------------------------------------------- //
#define IAN_MEMBER_PTR party_member_obj(PID_IAN)
#define KATJA_MEMBER_PTR party_member_obj(PID_KATJA)
#define TYCHO_MEMBER_PTR party_member_obj(PID_TYCHO)
#define DOGMEAT_MEMBER_PTR party_member_obj(PID_DOGMEAT)
#define TANDI_MEMBER_PTR party_member_obj(PID_TANDI)
// ----------------------------------------------------------------------- //
// ----------------------------------------------------------------------- //
// Trait defines //
#define TRAIT_PERK (0)
#define TRAIT_OBJECT (1)
#define TRAIT_TRAIT (2)
// Perk Trait Types
#define PERK_bonus_awareness (0)
#define PERK_bonus_hth_attacks (1)
#define PERK_bonus_hth_damage (2)
#define PERK_bonus_move (3)
#define PERK_bonus_ranged_damage (4)
#define PERK_bonus_rate_of_fire (5)
#define PERK_earlier_sequence (6)
#define PERK_faster_healing (7)
#define PERK_more_criticals (8)
#define PERK_night_vision (9)
#define PERK_presence (10)
#define PERK_rad_resistance (11)
#define PERK_toughness (12)
#define PERK_strong_back (13)
#define PERK_sharpshooter (14)
#define PERK_silent_running (15)
#define PERK_survivalist (16)
#define PERK_master_trader (17)
#define PERK_educated (18)
#define PERK_healer (19)
#define PERK_fortune_finder (20)
#define PERK_better_criticals (21)
#define PERK_empathy (22)
#define PERK_slayer (23)
#define PERK_sniper (24)
#define PERK_silent_death (25)
#define PERK_action_boy (26)
///#define PERK_mental_block (27) -- Disabled FO2
#define PERK_lifegiver (28)
#define PERK_dodger (29)
#define PERK_snakeater (30)
#define PERK_mr_fixit (31)
#define PERK_medic (32)
#define PERK_master_thief (33)
#define PERK_speaker (34)
#define PERK_heave_ho (35)
///#define PERK_friendly_foe (36) -- Disabled FO2
#define PERK_pickpocket (37)
#define PERK_ghost (38)
#define PERK_cult_of_personality (39)
///#define PERK_scrounger (40) -- Disabled FO2
#define PERK_explorer (41)
///#define PERK_flower_child (42) -- Disabled FO2
#define PERK_pathfinder (43)
///#define PERK_animal_friend (44) -- Disabled FO2
#define PERK_scout (45)
#define PERK_mysterious_stranger (46)
#define PERK_ranger (47)
#define PERK_quick_pockets (48)
#define PERK_smooth_talker (49)
#define PERK_swift_learner (50)
#define PERK_tag (51)
#define PERK_mutate (52)
//#define PERK_add_nuka // Do NOT USE! Engine ONLY!
//#define PERK_add_buffout // Do NOT USE! Engine ONLY!
//#define PERK_add_mentats // Do NOT USE! Engine ONLY!
//#define PERK_add_psycho // Do NOT USE! Engine ONLY!
//#define PERK_add_radaway // Do NOT USE! Engine ONLY!
//#define PERK_weapon_long_range // Do NOT USE! Engine ONLY!
//#define PERK_weapon_accurate // Do NOT USE! Engine ONLY!
//#define PERK_weapon_penetrate // Do NOT USE! Engine ONLY!
//#define PERK_weapon_knockback // Do NOT USE! Engine ONLY!
//#define PERK_armor_powered // Do NOT USE! Engine ONLY!
//#define PERK_armor_combat // Do NOT USE! Engine ONLY!
// Note: Fallout 2: New Perks // Do NOT USE! Engine ONLY!
//#define PERK_weapon_scope_range // Do NOT USE! Engine ONLY!
//#define PERK_weapon_fast_reload // Do NOT USE! Engine ONLY!
//#define PERK_weapon_night_sight // Do NOT USE! Engine ONLY!
//#define PERK_weapon_flameboy // Do NOT USE! Engine ONLY!
//#define PERK_armor_advanced_1 // Do NOT USE! Engine ONLY!
//#define PERK_armor_advanced_2 // Do NOT USE! Engine ONLY!
//#define PERK_add_jet // Do NOT USE! Engine ONLY!
//#define PERK_add_tragic // Do NOT USE! Engine ONLY!
//#define PERK_armor_charisma // Do NOT USE! Engine ONLY!
#define PERK_gecko_skinning_perk (73)
#define PERK_dermal_armor_perk (74)
#define PERK_dermal_enhancement_perk (75)
#define PERK_phoenix_armor_perk (76)
#define PERK_phoenix_enhancement_perk (77)
#define PERK_vault_city_inoculations_perk (78)
#define PERK_adrenaline_rush_perk (79)
#define PERK_cautious_nature_perk (80)
#define PERK_comprehension_perk (81)
#define PERK_demolition_expert_perk (82)
#define PERK_gambler_perk (83)
#define PERK_gain_strength_perk (84)
#define PERK_gain_perception_perk (85)
#define PERK_gain_endurance_perk (86)
#define PERK_gain_charisma_perk (87)
#define PERK_gain_intelligence_perk (88)
#define PERK_gain_agility_perk (89)
#define PERK_gain_luck_perk (90)
#define PERK_harmless_perk (91)
#define PERK_here_and_now_perk (92)
#define PERK_hth_evade_perk (93)
#define PERK_kama_sutra_perk (94)
#define PERK_karma_beacon_perk (95)
#define PERK_light_step_perk (96)
#define PERK_living_anatomy_perk (97)
#define PERK_magnetic_personality_perk (98)
#define PERK_negotiator_perk (99)
#define PERK_pack_rat_perk (100)
#define PERK_pyromaniac_perk (101)
#define PERK_quick_recovery_perk (102)
#define PERK_salesman_perk (103)
#define PERK_stonewall_perk (104)
#define PERK_thief_perk (105)
#define PERK_weapon_handling_perk (106)
#define PERK_vault_city_training_perk (107)
#define PERK_alcohol_hp_bonus1_perk (108)
#define PERK_alcohol_hp_bonus2_perk (109)
#define PERK_alcohol_hp_neg1_perk (110)
#define PERK_alcohol_hp_neg2_perk (111)
#define PERK_autodoc_hp_bonus1_perk (112)
#define PERK_autodoc_hp_bonus2_perk (113)
#define PERK_autodoc_hp_neg1_perk (114)
#define PERK_autodoc_hp_neg2_perk (115)
#define PERK_expert_excrement_expediter_perk (116)
#define PERK_weapon_knockout_perk (117)
#define PERK_jinxed_perk (118)
// Object Trait Subtypes
#define OBJECT_AI_PACKET (5)
#define OBJECT_TEAM_NUM (6)
#define OBJECT_CUR_ROT (10)
#define OBJECT_VISIBILITY (666)
#define OBJECT_CUR_WEIGHT (669)
#define obj_is_visible_flag(WHO) has_trait(TRAIT_OBJECT,WHO,OBJECT_VISIBILITY)
// Trait Types
#define TRAIT_fast_metabolism (0)
#define TRAIT_bruiser (1)
#define TRAIT_small_frame (2)
#define TRAIT_one_hander (3)
#define TRAIT_finesse (4)
#define TRAIT_kamikaze (5)
#define TRAIT_heavy_handed (6)
#define TRAIT_fast_shot (7)
#define TRAIT_bloody_mess (8)
#define TRAIT_jinxed (9)
#define TRAIT_good_natured (10)
#define TRAIT_drug_addict (11)
#define TRAIT_drug_resistant (12)
#define TRAIT_sex_appeal (13)
#define TRAIT_skilled (14)
#define TRAIT_gifted (15)
// ----------------------------------------------------------------------- //
// ----------------------------------------------------------------------- //
// proto.h: stats //
// SPECIAL System stats
#define STAT_st (0)
#define STAT_pe (1)
#define STAT_en (2)
#define STAT_ch (3)
#define STAT_iq (4)
#define STAT_ag (5)
#define STAT_lu (6)
#define STAT_max_hp (7)
/// strength, perception, endurance, charisma, intelligence, agility,
/// luck, // luck MUST be the last basic stat
// derived stats
#define STAT_max_hit_points (7)
#define STAT_max_move_points (8)
#define STAT_ac (9)
///#define STAT_unarmed_dmg (10)
#define STAT_unused (10)
#define STAT_melee_dmg (11)
#define STAT_carry_amt (12)
#define STAT_sequence (13)
#define STAT_heal_rate (14)
#define STAT_crit_chance (15)
#define STAT_better_crit (16)
#define STAT_dmg_thresh (17)
#define STAT_dmg_thresh_laser (18)
#define STAT_dmg_thresh_fire (19)
#define STAT_dmg_thresh_plasma (20)
#define STAT_dmg_thresh_electrical (21)
#define STAT_dmg_thresh_emp (22)
#define STAT_dmg_thresh_explosion (23)
#define STAT_dmg_resist (24)
#define STAT_dmg_resist_laser (25)
#define STAT_dmg_resist_fire (26)
#define STAT_dmg_resist_plasma (27)
#define STAT_dmg_resist_electrical (28)
#define STAT_dmg_resist_emp (29)
#define STAT_dmg_resist_explosion (30)
#define STAT_rad_resist (31)
#define STAT_poison_resist (32)
// poison_resist MUST be the last derived stat
// nonderived stats
#define STAT_age (33)
#define STAT_gender (34)
// gender MUST be the last nonderived stat
#define STAT_current_hp (35)
#define STAT_current_poison (36)
#define STAT_current_rad (37)
#define STAT_real_max_stat (38)
// extra stat-like values that are treated specially
#define STAT_max_stat STAT_current_hp
#define PCSTAT_unspent_skill_points (0)
#define PCSTAT_level (1)
#define PCSTAT_experience (2)
#define PCSTAT_reputation (3)
#define PCSTAT_karma (4)
#define PCSTAT_max_pc_stat (5)
// ----------------------------------------------------------------------- //
// ----------------------------------------------------------------------- //
// skill.h: Skill Equates //
// the following are skills for the SPECIAL system
#define SKILL_SMALL_GUNS (0)
#define SKILL_BIG_GUNS (1)
#define SKILL_ENERGY_WEAPONS (2)
#define SKILL_UNARMED_COMBAT (3)
#define SKILL_MELEE (4)
#define SKILL_THROWING (5)
#define SKILL_FIRST_AID (6)
#define SKILL_DOCTOR (7)
#define SKILL_SNEAK (8)
#define SKILL_LOCKPICK (9)
#define SKILL_STEAL (10)
#define SKILL_TRAPS (11)
#define SKILL_SCIENCE (12)
#define SKILL_REPAIR (13)
#define SKILL_CONVERSANT (14)
#define SKILL_BARTER (15)
#define SKILL_GAMBLING (16)
#define SKILL_OUTDOORSMAN (17)
#define CRITTER_SKILL_LEVEL(X,Y) has_skill(X,Y)
#define critter_skill_level(X,Y) has_skill(X,Y)
// ----------------------------------------------------------------------- //
// ----------------------------------------------------------------------- //
// reaction.h: Reaction Levels //
#define rl_disastrous (0)
#define rl_very_bad (1)
#define rl_bad (2)
#define rl_poor (3)
#define rl_neutral (4)
#define rl_good (5)
#define rl_very_good (6)
#define rl_excellent (7)
// proto.h //
//#define LOAD_MAP_INDEX (32)
// proto.h //
#define GENDER_MALE (0)
#define GENDER_FEMALE (1)
// critter_state States //
#define CRITTER_IS_NORMAL (0)
#define CRITTER_IS_DEAD (1)
#define CRITTER_IS_PRONE (2)
#define is_critter_dead(who) (critter_state(who) bwand CRITTER_IS_DEAD)
#define is_critter_prone(who) (critter_state(who) bwand CRITTER_IS_PRONE)
// inventory Equates //
#define INVEN_TYPE_WORN (0)
#define INVEN_TYPE_RIGHT_HAND (1)
#define INVEN_TYPE_LEFT_HAND (2)
#define INVEN_TYPE_INV_COUNT (-2)
#define inven_count(WHO) critter_inven_obj(WHO, INVEN_TYPE_INV_COUNT)
// ----------------------------------------------------------------------- //
// ----------------------------------------------------------------------- //
/* proto_data data_member Equates */
/* Item subtypes */
#define item_type_armor (0)
#define item_type_container (1)
#define item_type_drug (2)
#define item_type_weapon (3)
#define item_type_ammo (4)
#define item_type_misc_item (5)
#define item_type_key_item (6)
/* Item data_members */
#define it_pid (0)
#define it_name (1)
#define it_description (2)
#define it_fid (3)
#define it_light_distance (4)
#define it_light_intensity (5)
#define it_flags (6)
#define it_flags_ext (7)
#define it_sid (8)
#define it_type (9)
#define it_data (10)
#define it_material (11)
#define it_size (12)
#define it_weight (13)
#define it_cost (14)
#define it_inv_fid (15)
#define it_weapon_range (555)
/* Critter data_members */
#define cr_pid (0)
#define cr_name (1)
#define cr_description (2)
#define cr_fid (3)
#define cr_light_distance (4)
#define cr_light_intensity (5)
#define cr_flags (6)
#define cr_flags_ext (7)
#define cr_sid (8)
#define cr_data (9)
#define cr_head_fid (10)
#define cr_body_type (11)
// cr_body_type values:
#define CR_BODY_BIPED 0
#define CR_BODY_QUADRUPED 1
#define CR_BODY_ROBOTIC 2
/* Scenery data_members */
#define sc_pid (0)
#define sc_name (1)
#define sc_description (2)
#define sc_fid (3)
#define sc_light_distance (4)
#define sc_light_intensity (5)
#define sc_flags (6)
#define sc_flags_ext (7)
#define sc_sid (8)
#define sc_type (9)
#define sc_data (10)
#define sc_material (11)
/* Wall data_members */
#define wa_pid (0)
#define wa_name (1)
#define wa_description (2)
#define wa_fid (3)
#define wa_light_distance (4)
#define wa_light_intensity (5)
#define wa_flags (6)
#define wa_flags_ext (7)
#define wa_sid (8)
#define wa_material (9)
/* Tile data_members */
// NONE
/* Misc data_members */
#define mi_pid (0)
#define mi_name (1)
#define mi_description (2)
#define mi_fid (3)
#define mi_light_distance (4)
#define mi_light_intensity (5)
#define mi_flags (6)
#define mi_flags_ext (7)
// ----------------------------------------------------------------------- //
// ----------------------------------------------------------------------- //
/* Combat Flags */
// WIP! These are old and incorrect now, look below! 6/18/97 JLR
/*
#define DAM_KNOCKED_OUT (1) // 0x00000001 // valid flags for damage_results
#define DAM_STUNNED (2) // 0x00000002
#define DAM_KNOCKED_DOWN (4) // 0x00000004
#define DAM_DODGED (8) // 0x00000008
#define DAM_CRIP_LEG_LEFT (16) // 0x00000010
#define DAM_CRIP_LEG_RIGHT (32) // 0x00000020
#define DAM_CRIP_FOOT_LEFT (64) // 0x00000040
#define DAM_CRIP_FOOT_RIGHT (128) // 0x00000080
#define DAM_CRIP_ARM_LEFT (256) // 0x00000100
#define DAM_CRIP_ARM_RIGHT (512) // 0x00000200
#define DAM_CRIP_HAND_LEFT (1024) // 0x00000400
#define DAM_CRIP_HAND_RIGHT (2048) // 0x00000800
#define DAM_BLIND_EYE_LEFT (4096) // 0x00001000
#define DAM_BLIND_EYE_RIGHT (8192) // 0x00002000
#define DAM_DECAPITATED (16384) // 0x00004000
#define DAM_SURPRISED (32768) // 0x00008000
#define DAM_DEATH_1 (65536) // 0x00010000
#define DAM_DEATH_2 (131072) // 0x00020000
#define DAM_DEATH_3 (262144) // 0x00040000
#define DAM_HIT (524288) // 0x00080000 // true if hit or critical hit
#define DAM_UNBALANCED (1048576) // 0x00100000
#define DAM_DEAF (2097152) // 0x00200000
#define DAM_DROP_WEAPON (4194304) // 0x00400000
#define DAM_BREAK_WEAPON (8388608) // 0x00800000
#define DAM_UNREADY_WEAPON_LEFT (16777216) // 0x01000000
#define DAM_UNREADY_WEAPON_RIGHT (33554432) // 0x02000000
#define DAM_EXPLODE_WEAPON (67108864) // 0x04000000
#define DAM_DUD_SHOT (134217728) // 0x08000000
#define DAM_IGNORE_DR (268435456) // 0x10000000
#define DAM_CRITICAL (536870912) // 0x20000000 // could be a critical hit or critical miss
#define DAM_ON_FIRE (1073741824) // 0x40000000
*/
#define DAM_KNOCKED_OUT 1
#define DAM_KNOCKED_DOWN 2
#define DAM_CRIP_LEG_LEFT 4
#define DAM_CRIP_LEG_RIGHT 8
#define DAM_CRIP_ARM_LEFT 16
#define DAM_CRIP_ARM_RIGHT 32
#define DAM_BLIND 64
#define DAM_DEAD 128
#define DAM_HIT 256
#define DAM_CRITICAL 512 // could be a critical hit or critical miss
#define DAM_ON_FIRE 1024
#define DAM_BYPASS 2048
#define DAM_EXPLODE 4096
#define DAM_DESTROY 8192
#define DAM_DROP 16384
#define DAM_LOSE_TURN 32768
#define DAM_HIT_SELF 65536
#define DAM_LOSE_AMMO 131072
#define DAM_DUD 262144
#define DAM_HURT_SELF 524288
#define DAM_RANDOM_HIT 1048576
#define DAM_CRIP_RANDOM 2097152
#define DAM_BACKWASH 4194304
// Fallout 2:
#define DAM_PERFORM_REVERSE 8388608
#define critter_uninjure(WHO, FLAGS) critter_injure(WHO, (FLAGS BWOR DAM_PERFORM_REVERSE))
#define DMG_normal_dam 0
#define DMG_laser 1
#define DMG_fire 2
#define DMG_plasma 3
#define DMG_electrical 4
#define DMG_emp 5
#define DMG_explosion 6
// These are BWOR'd into the above damage type
#define DMG_BYPASS_ARMOR (256)
#define DMG_NOANIMATE (512)
//#define critter_damage(WHO,AMT) critter_dmg(WHO,AMT,(DMG_normal_dam BWOR DMG_NOANIMATE))
#define critter_damage(WHO,AMT) critter_dmg(WHO,AMT,DMG_normal_dam)
/* Kill Critter Equates */
#define KILL_DONT_LEAVE_BODY (0)
#define KILL_LEAVE_BODY (1)
#define KILL_LEAVE_NV_BODY (2)
/* Script MetaRules */
#define METARULE_SIGNAL_END_GAME 13
#define METARULE_TEST_FIRSTRUN 14
#define signal_end_game metarule(METARULE_SIGNAL_END_GAME, 0)
#define METARULE_ELEVATOR 15
#define elevator(X) metarule(METARULE_ELEVATOR, X)
#define ELEV_BOS1 (0) // Brotherhood of Steel main elevator
#define ELEV_BOS2 (1) // Brotherhood of Steel surface elevator
#define ELEV_MASTR1 (2) // Master's upper-level elevator
#define ELEV_MASTR2 (3) // Master's lower-level elevator
#define ELEV_MILB1 (4) // Military Base upper-level elevator
#define ELEV_MILB2 (5) // Military Base lower-level elevator
#define ELEV_GLOW1 (6) // Glow Elevator upper
#define ELEV_GLOW2 (7) // Glow elevator lower
#define ELEV_VAULT (8) // Vault13 elevator
#define ELEV_NECVLT (9) // Necropolis elevator
#define ELEV_SIERRA1 (10) // Sierra Elev 1 (1-2-3)
#define ELEV_SIERRA2 (11) // Sierra Elev 2 (3-4)
#define ELEV_SIERRAS (12) // Sierra Service Elev (1-2-3-4)
#define METARULE_PARTY_COUNT 16
#define party_member_count(X) metarule(METARULE_PARTY_COUNT, X)
#define DONT_LIST_HIDDEN_MEMBERS (0)
#define LIST_HIDDEN_MEMBERS (1)
#define METARULE_AREA_KNOWN 17
#define town_known(X) metarule(METARULE_AREA_KNOWN, X)
#define METARULE_WHO_ON_DRUGS 18
#define drug_influence(WHO) metarule(METARULE_WHO_ON_DRUGS, WHO)
#define METARULE_MAP_KNOWN 19
#define map_is_known(X) metarule(METARULE_MAP_KNOWN, X)
//#define DEFINE_METARULE_IS_LOADGAME 22
#define METARULE_CAR_CURRENT_TOWN 30
#define METARULE_GIVE_CAR_TO_PARTY 31
#define METARULE_GIVE_CAR_GAS 32
#define car_current_town metarule(METARULE_CAR_CURRENT_TOWN, 0)
#define car_give_to_party metarule(METARULE_GIVE_CAR_TO_PARTY, 0)
#define car_give_gas(AMOUNT) metarule(METARULE_GIVE_CAR_GAS, AMOUNT)
#define METARULE_SKILL_CHECK_TAG 40
#define is_skill_tagged(SKILL) metarule(METARULE_SKILL_CHECK_TAG, SKILL)
#define METARULE_DROP_ALL_INVEN 42
#define obj_drop_everything(WHO) metarule(METARULE_DROP_ALL_INVEN, WHO)
#define METARULE_INVEN_UNWIELD_WHO 43
#define inven_unwield(WHO) metarule(METARULE_INVEN_UNWIELD_WHO, WHO)
#define METARULE_GET_WORLDMAP_XPOS 44
#define worldmap_xpos metarule(METARULE_GET_WORLDMAP_XPOS, 0)
#define METARULE_GET_WORLDMAP_YPOS 45
#define worldmap_ypos metarule(METARULE_GET_WORLDMAP_YPOS, 0)
#define METARULE_CURRENT_TOWN 46
#define cur_town metarule(METARULE_CURRENT_TOWN, 0)
#define METARULE_LANGUAGE_FILTER 47
#define language_filter_is_on metarule(METARULE_LANGUAGE_FILTER, 0)
#define METARULE_VIOLENCE_FILTER 48
#define violence_filter_setting metarule(METARULE_VIOLENCE_FILTER, 0)
#define VLNCLVL_NONE 0 // Violence Level settings.
#define VLNCLVL_MIN 1
#define VLNCLVL_NORMAL 2
#define VLNCLVL_MAX 3
#define METARULE_W_DAMAGE_TYPE 49
#define weapon_dmg_type(WEAP) metarule(METARULE_W_DAMAGE_TYPE, WEAP)
#define METARULE_CRITTER_BARTERS 50
#define critter_can_barter(WHO) metarule(METARULE_CRITTER_BARTERS, WHO)
#define METARULE_CRITTER_KILL_TYPE 51
#define critter_kill_type(WHO) metarule(METARULE_CRITTER_KILL_TYPE, WHO)
#define KILL_TYPE_men_kills 0
#define KILL_TYPE_women_kills 1
#define KILL_TYPE_children_kills 2
#define KILL_TYPE_super_mutant_kills 3
#define KILL_TYPE_ghoul_kills 4
#define KILL_TYPE_brahmin_kills 5
#define KILL_TYPE_radscorpion_kills 6
#define KILL_TYPE_rat_kills 7
#define KILL_TYPE_floater_kills 8
#define KILL_TYPE_centaur_kills 9
#define KILL_TYPE_robot_kills 10
#define KILL_TYPE_dog_kills 11
#define KILL_TYPE_manti_kills 12
#define KILL_TYPE_deathclaw_kills 13
#define KILL_TYPE_plant_kills 14
#define KILL_TYPE_gecko_kills 15
#define KILL_TYPE_alien_kills 16
#define KILL_TYPE_giant_ant_kills 17
#define DEFINE_METARULE_SET_CAR_CARRY_AMOUNT 52
#define set_car_carry_amount(VALUE) metarule(DEFINE_METARULE_SET_CAR_CARRY_AMOUNT, VALUE)
#define DEFINE_METARULE_GET_CAR_CARRY_AMOUNT 53
#define car_carry_amount metarule(DEFINE_METARULE_GET_CAR_CARRY_AMOUNT, 0)
// Script MetaRule3's
#define METARULE3_CLR_FIXED_TIMED_EVENTS 100
#define rm_fixed_timer_event(WHO,FIXED_VAL) metarule3(METARULE3_CLR_FIXED_TIMED_EVENTS,WHO,FIXED_VAL,0)
#define METARULE3_MARK_SUBTILE 101
#define mark_world_subtile_visited(XPOS,YPOS,RADIUS) metarule3(METARULE3_MARK_SUBTILE,XPOS,YPOS,RADIUS)
///#define METARULE3_SET_WM_MUSIC 102
///#define set_worldmap_music(MAPIDX,MUSICNAME) metarule3(METARULE3_SET_WM_MUSIC,MAPIDX,MUSICNAME,0)
#define METARULE3_GET_KILL_COUNT 103
#define player_kill_count(TYPE) metarule3(METARULE3_GET_KILL_COUNT,TYPE,0,0)
// Off/On states for mark_map_entrance_state
#define OFFSTATE 0
#define ONSTATE 1
#define METARULE3_MARK_MAP_ENTRANCE 104
#define mark_map_entrance_state(MAPIDX,STATE) metarule3(METARULE3_MARK_MAP_ENTRANCE,MAPIDX,STATE,-1)
#define mark_map_entrance_elev_state(MAPIDX,ELEV,STATE) metarule3(METARULE3_MARK_MAP_ENTRANCE,MAPIDX,STATE,ELEV)
// wmSubTileVisitInfo Types:
#define UNKNOWNTILETYPE 0
#define KNOWNTILETYPE 1
#define VISITEDTILETYPE 2
#define METARULE3_WM_SUBTILE_STATE 105
#define wm_get_subtile_state(XPOS,YPOS) metarule3(METARULE3_WM_SUBTILE_STATE,XPOS,YPOS,0)
// Begin <objptr> tile_get_next_critter(tile, elevation, lastCritter)
//CMH
//Note these defines are really messey.
#define METARULE3_TILE_GET_NEXT_CRITTER (106)
#define tile_get_next_critter(tile, elevation, lastCritter) metarule3(METARULE3_TILE_GET_NEXT_CRITTER, tile, elevation, lastCritter)
//CMH
// End
#define METARULE3_ART_SET_BASE_FID_NUM (107)
#define art_change_fid_num(WHO, NUM) metarule3(METARULE3_ART_SET_BASE_FID_NUM,WHO,NUM,0)
#define METARULE3_TILE_SET_CENTER (108)
#define tile_set_center(tileNum) metarule3(METARULE3_TILE_SET_CENTER,tileNum,0,0)
#define METARULE3_CHEM_USE_LEVEL (109)
#define chem_use_level(WHO) metarule3(METARULE3_CHEM_USE_LEVEL,WHO,0,0)
#define METARULE3_CAR_OUT_OF_FUEL (110)
#define car_out_of_fuel metarule3(METARULE3_CAR_OUT_OF_FUEL,0,0,0)
#define METARULE3_MAP_GET_LOAD_AREA (111)
#define map_get_load_area metarule3(METARULE3_MAP_GET_LOAD_AREA,0,0,0)
// Used with mark_area_known
#define MARK_TYPE_TOWN (0)
#define MARK_TYPE_MAP (1)
// wmAreaVisitStateInfo;
#define MARK_STATE_UNKNOWN (0)
#define MARK_STATE_KNOWN (1)
#define MARK_STATE_VISITED (2)
#define MARK_STATE_INVISIBLE (-66)
// Inven Cmd defines //
#define INVEN_CMD_INDEX_PTR (13)
#define inven_ptr(WHO,WHERE) inven_cmds(WHO,INVEN_CMD_INDEX_PTR,WHERE)
/* GSound Values */
// gsound_character_types
#define snd_human (0)
#define snd_monster (1)
// gsound_character_extra
#define snd_unused (0)
#define snd_knock_down (1)
#define snd_pass_out (2)
#define snd_die (3)
#define snd_contact (4)
// gsound_sfx_action
#define snd_active (0)
#define snd_passive (1)
// gsound_sfx_weapon_action_type
#define snd_weapon_ready (0)
#define snd_weapon_attack (1)
#define snd_weapon_out (2)
#define snd_weapon_ammo_flying (3)
#define snd_weapon_hitting (4)
// gsound_sfx_scenery_action
#define snd_open (0)
#define snd_close (1)
#define snd_locked (2)
#define snd_unlocked (3)
#define snd_used (4)
// hit_mode
#define hit_left_weapon_primary (0)
#define hit_left_weapon_secondary (1)
#define hit_right_weapon_primary (2)
#define hit_right_weapon_secondary (3)
#define hit_punch (4)
#define hit_kick (5)
#define hit_left_weapon_reload (6)
#define hit_right_weapon_reload (7)
/* Extra */
#define fadeout(X) gfade_out(X)
#define fadein(X) gfade_in(X)
#define fdout gfade_out(1) //time param is not used anyway
#define fdin gfade_in(1)
/* Time Information (in Ticks) */
#define ONE_GAME_SECOND (10)
#define ONE_GAME_MINUTE (60*ONE_GAME_SECOND)
#define ONE_GAME_HOUR (60*ONE_GAME_MINUTE)
#define ONE_GAME_DAY (24*ONE_GAME_HOUR)
#define ONE_GAME_WEEK (7*ONE_GAME_DAY)
#define ONE_GAME_MONTH (30*ONE_GAME_DAY)
/* bits */
#define bit_1 (1)
#define bit_2 (2)
#define bit_3 (4)
#define bit_4 (8)
#define bit_5 (16)
#define bit_6 (32)
#define bit_7 (64)
#define bit_8 (128)
#define bit_9 (256)
#define bit_10 (512)
#define bit_11 (1024)
#define bit_12 (2048)
#define bit_13 (4096)
#define bit_14 (8192)
#define bit_15 (16384)
#define bit_16 (32768)
#define bit_17 (65536)
#define bit_18 (131072)
#define bit_19 (262144)
#define bit_20 (524288)
#define bit_21 (1048576)
#define bit_22 (2097152)
#define bit_23 (4194304)
#define bit_24 (8388608)
#define bit_25 (16777216)
#define bit_26 (33554432)
#define bit_27 (67108864)
#define bit_28 (134217728)
#define bit_29 (268435456)
#define bit_30 (536870912)
#define bit_31 (1073741824)
#define bit_32 (-2147483648)
#define bit_ALL (-1)
/* macros for pickup_p_proc responses. */
#define REACTION_TG 1
#define REACTION_G 2
#define REACTION_TC 3
#define REACTION_C 4
#define R_CALL_THROUGH 1
#define R_NOCALL_THROUGH -1
#ifndef PICKUP_THRESH
#define PICKUP_THRESH 1
#endif
#ifndef CALL_PICKUP
#define CALL_PICKUP R_NOCALL_THROUGH
#endif
#ifndef NPC_REACTION_VAR
#define NPC_REACTION_VAR (-1)
#endif
#ifdef NPC_REACTION_TYPE
// Tough Guard Architype == 1
// Guard Architype == 2
// Tough Citizen Architype == 3
// Citizen Architype == 4
#define caught_pickpocket if (NPC_REACTION_TYPE == REACTION_TG) then begin \
attack(source_obj); \
end \
else if (NPC_REACTION_TYPE == REACTION_G) then begin \
float_msg(self_obj, message_str(SCRIPT_GENERIC,random(3325,3329)), FLOAT_MSG_NORMAL); \
if (NPC_REACTION_VAR > -1) then begin \
if (local_var(NPC_REACTION_VAR) >= PICKUP_THRESH) then begin \
attack(source_obj); \
end \
set_local_var(NPC_REACTION_VAR,local_var(NPC_REACTION_VAR)+1); \
end \
end \
else if (NPC_REACTION_TYPE == REACTION_TC) then begin \
float_msg(self_obj, message_str(SCRIPT_GENERIC,random(3050,3064)), FLOAT_MSG_NORMAL); \
if (NPC_REACTION_VAR > -1) then begin \
if (local_var(NPC_REACTION_VAR) >= PICKUP_THRESH) then begin \
attack(source_obj); \
end \
set_local_var(NPC_REACTION_VAR,local_var(NPC_REACTION_VAR)+1); \
end \
end \
else if (NPC_REACTION_TYPE == REACTION_C) then begin \
animate_run_to_tile(tile_num_in_direction(tile_num(self_obj), rotation_to_tile(tile_num(source_obj),tile_num(self_obj)), random(8,14))); \
end
// global pickups
procedure old_pickup_p_proc;
procedure pickup_p_proc begin
if (source_obj == dude_obj) then begin
caught_pickpocket
end
if (CALL_PICKUP == R_CALL_THROUGH) then begin
call old_pickup_p_proc;
end
end
#define pickup_p_proc old_pickup_p_proc
#endif
/*
// this will debug messages if there are characters that violation the anti-barter act of 1998
#define check_barterable if (critter_can_barter(self_obj)) then begin \
debug_msg("BARTER SHIT ERROR: name == "+obj_name(self_obj)); \
end
#define check_barterable_float if (critter_can_barter(self_obj)) then begin \
float_msg(self_obj, "GET A SCRIPTER, I'M FUCKED UP!!! HELP, MY NAME IS "+obj_name(self_obj)+"!!! PHEW, THANKS!!!", FLOAT_COLOR_NORMAL); \
end
// global map enters
procedure map_enter_p_proc begin
check_barterable
call old_map_enter_p_proc;
end
#define map_enter_p_proc old_map_enter_p_proc
// global critter procs
procedure critter_p_proc begin
check_barterable_float
else call old_critter_p_proc;
end
#define critter_p_proc old_critter_p_proc
*/
//Misc commands
#define obj_get_rot(obj) (has_trait(TRAIT_OBJECT, obj, OBJECT_CUR_ROT))
//late includes go here
#include "..\headers\party2.h"
#endif // DEFINE_H
| {
"content_hash": "d0dd6369b69b7804d1866fc879109a15",
"timestamp": "",
"source": "github",
"line_count": 990,
"max_line_length": 185,
"avg_line_length": 39.567676767676765,
"alnum_prop": 0.5740324721740019,
"repo_name": "NovaRain/FO2_UP_postfix",
"id": "5d15d8d36ce05a5c6e68ee4bb386ca6c3e43a9b3",
"size": "39250",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "scripts_src/HEADERS/DEFINE.H",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "24149"
},
{
"name": "C",
"bytes": "362369"
},
{
"name": "C++",
"bytes": "983415"
}
],
"symlink_target": ""
} |
<?php
/**
* PHPMailerOAuth - PHPMailer subclass adding OAuth support.
* @author @sherryl4george
* @author Marcus Bointon (@Synchro) <phpmailer@synchromedia.co.uk>
*/
class PHPMailerOAuth extends PHPMailer
{
/**
* The OAuth user's email address.
* @var string
*/
public $oauthUserEmail = '';
/**
* The OAuth refresh token.
* @var string
*/
public $oauthRefreshToken = '';
/**
* The OAuth client ID.
* @var string
*/
public $oauthClientId = '';
/**
* The OAuth client secret.
* @var string
*/
public $oauthClientSecret = '';
/**
* An instance of the OAuth class.
* @var OAuth
*/
protected $oauth = null;
/**
* Get an OAuth instance to use.
* @return OAuth
*/
public function getOAUTHInstance()
{
if (! is_object($this->oauth)) {
$this->oauth = new PHPMailerOAuthGoogle(
$this->oauthUserEmail,
$this->oauthClientSecret,
$this->oauthClientId,
$this->oauthRefreshToken
);
}
return $this->oauth;
}
/**
* Initiate a connection to an SMTP server.
* Overrides the original smtpConnect method to add support for OAuth.
* @param array $options An array of options compatible with stream_context_create()
* @uses SMTP
* @throws phpmailerException
* @return bool
*/
public function smtpConnect($options = [])
{
if (is_null($this->smtp)) {
$this->smtp = $this->getSMTPInstance();
}
if (is_null($this->oauth)) {
$this->oauth = $this->getOAUTHInstance();
}
// Already connected?
if ($this->smtp->connected()) {
return true;
}
$this->smtp->setTimeout($this->Timeout);
$this->smtp->setDebugLevel($this->SMTPDebug);
$this->smtp->setDebugOutput($this->Debugoutput);
$this->smtp->setVerp($this->do_verp);
$hosts = explode(';', $this->Host);
$lastexception = null;
foreach ($hosts as $hostentry) {
$hostinfo = [];
if (! preg_match('/^((ssl|tls):\/\/)*([a-zA-Z0-9\.-]*):?([0-9]*)$/', trim($hostentry), $hostinfo)) {
// Not a valid host entry
continue;
}
// $hostinfo[2]: optional ssl or tls prefix
// $hostinfo[3]: the hostname
// $hostinfo[4]: optional port number
// The host string prefix can temporarily override the current setting for SMTPSecure
// If it's not specified, the default value is used
$prefix = '';
$secure = $this->SMTPSecure;
$tls = ($this->SMTPSecure == 'tls');
if ('ssl' == $hostinfo[2] or ('' == $hostinfo[2] and 'ssl' == $this->SMTPSecure)) {
$prefix = 'ssl://';
$tls = false; // Can't have SSL and TLS at the same time
$secure = 'ssl';
} elseif ($hostinfo[2] == 'tls') {
$tls = true;
// tls doesn't use a prefix
$secure = 'tls';
}
//Do we need the OpenSSL extension?
$sslext = defined('OPENSSL_ALGO_SHA1');
if ('tls' === $secure or 'ssl' === $secure) {
//Check for an OpenSSL constant rather than using extension_loaded, which is sometimes disabled
if (! $sslext) {
throw new phpmailerException($this->lang('extension_missing').'openssl', self::STOP_CRITICAL);
}
}
$host = $hostinfo[3];
$port = $this->Port;
$tport = (int) $hostinfo[4];
if ($tport > 0 and $tport < 65536) {
$port = $tport;
}
if ($this->smtp->connect($prefix.$host, $port, $this->Timeout, $options)) {
try {
if ($this->Helo) {
$hello = $this->Helo;
} else {
$hello = $this->serverHostname();
}
$this->smtp->hello($hello);
//Automatically enable TLS encryption if:
// * it's not disabled
// * we have openssl extension
// * we are not already using SSL
// * the server offers STARTTLS
if ($this->SMTPAutoTLS and $sslext and $secure != 'ssl' and $this->smtp->getServerExt('STARTTLS')) {
$tls = true;
}
if ($tls) {
if (! $this->smtp->startTLS()) {
throw new phpmailerException($this->lang('connect_host'));
}
// We must resend HELO after tls negotiation
$this->smtp->hello($hello);
}
if ($this->SMTPAuth) {
if (! $this->smtp->authenticate(
$this->Username,
$this->Password,
$this->AuthType,
$this->Realm,
$this->Workstation,
$this->oauth
)
) {
throw new phpmailerException($this->lang('authenticate'));
}
}
return true;
} catch (phpmailerException $exc) {
$lastexception = $exc;
$this->edebug($exc->getMessage());
// We must have connected, but then failed TLS or Auth, so close connection nicely
$this->smtp->quit();
}
}
}
// If we get here, all connection attempts have failed, so close connection hard
$this->smtp->close();
// As we've caught all exceptions, just report whatever the last one was
if ($this->exceptions and ! is_null($lastexception)) {
throw $lastexception;
}
return false;
}
}
| {
"content_hash": "34700fbda59022970c4d0d60a1be8a68",
"timestamp": "",
"source": "github",
"line_count": 181,
"max_line_length": 120,
"avg_line_length": 34.55801104972376,
"alnum_prop": 0.45995203836930454,
"repo_name": "amch123/qruzh_ci",
"id": "186e55d405315544ea7a0d2e157a727867808874",
"size": "7065",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "template/php/php-mailer/class.phpmaileroauth.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "240"
},
{
"name": "CSS",
"bytes": "1811018"
},
{
"name": "HTML",
"bytes": "6982398"
},
{
"name": "JavaScript",
"bytes": "122034"
},
{
"name": "PHP",
"bytes": "2917433"
},
{
"name": "Shell",
"bytes": "4442"
}
],
"symlink_target": ""
} |
package uk.ac.ebi.eva.server.utils;
import java.io.IOException;
import java.io.OutputStream;
/**
* Created by jorizci on 16/09/16.
*/
public interface DataGenerator {
void generate(OutputStream outputStream) throws IOException;
}
| {
"content_hash": "27147e691c0ff2c9b23dbf6165381dfe",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 64,
"avg_line_length": 18.46153846153846,
"alnum_prop": 0.75,
"repo_name": "EBIvariation/examples",
"id": "caf298cd0b281846902f521e0c77405e6441b095",
"size": "240",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "spring-boot-authentication-rest-server-oauth2/rest/src/main/java/uk/ac/ebi/eva/server/utils/DataGenerator.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "15018"
},
{
"name": "Java",
"bytes": "152122"
},
{
"name": "Shell",
"bytes": "21174"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Mazel - Multiprapose Html template</title>
<meta name="description" content="" />
<meta name="keywords" content="" />
<meta name="author" content="nileforest">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0" />
<!--[if IE]><meta http-equiv='X-UA-Compatible' content='IE=edge,chrome=1'><![endif]-->
<!-- Favicone Icon -->
<link rel="shortcut icon" type="image/x-icon" href="img/favicon.ico">
<link rel="icon" type="image/png" href="img/favicon.png">
<link rel="apple-touch-icon" href="img/favicon.png">
<!-- CSS -->
<link href="css/style.css" rel="stylesheet" type="text/css" />
<link href="css/bootstrap.css" rel="stylesheet" type="text/css" />
<link href="css/font-awesome.css" rel="stylesheet" type="text/css" />
<link href="css/ionicons.css" rel="stylesheet" type="text/css" />
<link href="css/plugin/jPushMenu.css" rel="stylesheet" type="text/css" />
<link href="css/plugin/animate.css" rel="stylesheet" type="text/css" />
<link href="css/jquery-ui.css" rel="stylesheet" type="text/css" />
</head>
<body class="full-intro background--dark">
<!-- Preloader -->
<section id="preloader">
<div class="loader" id="loader">
<div class="loader-img"></div>
</div>
</section>
<!-- End Preloader -->
<!-- Sidemenu -->
<section class="side-menu cbp-spmenu cbp-spmenu-vertical cbp-spmenu-right">
<a class="menu-close toggle-menu menu-right push-body"><i class="ion ion-android-close"></i></a>
<h5 class="white">Sign In</h5>
<div class="sign-in">
<input class="input-sm form-full" type="email" aria-required="true" id="email" name="email" placeholder="Email" value="" />
<input class="input-sm form-full" type="password" aria-required="true" id="password" name="password" placeholder="Password" value="" />
<input type="submit" class="btn btn-md btn-color-b form-full" value="Sign In" />
<a>New Customer?</a>
</div>
<ul>
<li><a target="_blank" href="index.html">Main Demo Page</a></li>
<li><a href="home.html">Home Default</a></li>
<li><a href="portfolio-grid-2col.html">Portfolio</a></li>
<li><a href="login-register.html">Login & Signup</a></li>
<li><a href="faq-1.html">FAQ</a></li>
<li><a href="about-1.html">About</a></li>
<li><a href="service-1.html">Service</a></li>
<li><a href="blog-grid-3col.html">Blog</a></li>
<li><a href="404-error-1.html">404 Error</a></li>
<li><a href="shop-checkout.html">Shopping Cart</a></li>
<li><a href="contact-1.html">Contact Us</a></li>
</ul>
</section>
<!--End Sidemenu -->
<!-- Search menu Top -->
<section class=" top-search-bar cbp-spmenu cbp-spmenu-horizontal cbp-spmenu-top">
<div class="container">
<div class="search-wraper">
<input type="text" class="input-sm form-full" placeholder="Search..." name="search" />
<a class="search-bar-icon"><i class="fa fa-search"></i></a>
<a class="bar-close toggle-menu menu-top push-body"><i class="ion ion-android-close"></i></a>
</div>
</div>
</section>
<!--End Search menu Top -->
<!-- Site Wraper -->
<div class="wrapper">
<!-- HEADER -->
<header class="header">
<div class="container">
<!-- logo -->
<div class="logo">
<a href="home.html">
<img class="l-black" src="img/logo-black.png" />
<img class="l-white" src="img/logo-white.png" />
<img class="l-color" src="img/logo-color.png" />
</a>
</div>
<!--End logo-->
<!-- Rightside Menu (Search, Cart, Bart icon) -->
<div class="side-menu-btn">
<ul>
<!-- Search Icon -->
<li class="">
<a class="right-icon search toggle-menu menu-top push-body"><i class="fa fa-search"></i></a>
</li>
<!-- End Search Icon -->
<!-- Cart Icon -->
<li class="">
<a href="shop-checkout.html" class="right-icon cart">
<i class="fa fa-shopping-cart"></i>
<span class="cart-notification">2</span>
</a>
<!-- Cart Dropdown List -->
<div class="cart-dropdown">
<ul class="cart-list">
<li class="light-color">
<a class="close-cart-list"><i class="fa fa-times-circle"></i></a>
<div class="media">
<a class="pull-left">
<img src="img/product/02.jpg" alt="fashion" /></a>
<div class="media-body">
<h6><a>Fashion Model New /01</a></h6>
<p>$399.00</p>
</div>
</div>
</li>
<li class="light-color">
<a class="close-cart-list"><i class="fa fa-times-circle"></i></a>
<div class="media">
<a class="pull-left">
<img src="img/product/06.jpg" alt="fashion" /></a>
<div class="media-body">
<h6><a>Fashion Model New /02</a></h6>
<p>$399.00</p>
</div>
</div>
</li>
</ul>
<p class="cart-sub-totle"><span class="pull-left">Cart Subtotal</span><span class="pull-right totle"><strong>$798.00</strong></span></p>
<div class="clearfix"></div>
<div class="cart-checkout-btn">
<a href="shop-checkout.html" class="btn btn-md btn-color-b form-full checkout">Checkout</a>
</div>
</div>
<!-- End Cart Dropdown List -->
</li>
<!-- End Cart Icon -->
<!--Sidebar Menu Icon-->
<li class="">
<a class="right-icon bar-icon toggle-menu menu-right push-body"><i class="fa fa-bars"></i></a>
</li>
<!-- End Sidebar Menu Icon-->
</ul>
</div>
<!-- End Rightside Menu -->
<!-- Navigation Menu -->
<nav class='navigation'>
<ul>
<li>
<a href="home.html">Home</a>
<!-- Nav Dropdown -->
<ul class="nav-dropdown">
<li class="nav-has-sub">
<a href='#'>Multi Page</a>
<ul class="nav-sub-dropdown">
<li><a href="home.html">Default</a></li>
<li><a href="home-video.html">Intro Video</a></li>
<li><a href="home-youtube.html">Intro Youtube</a></li>
<li><a href="home-static.html">Intro Static</a></li>
<li><a href="home-agency-grid.html">Agency Grid</a></li>
<li><a href="home-agency-masonry.html">Agency Masonry</a></li>
<li><a href="home-fullwidth-slider.html">Fullwidth Slider</a></li>
<li><a href="home-text-rotator1.html">Text Rotator1</a></li>
<li><a href="home-text-rotator2.html">Text Rotator2</a></li>
<li><a href="home-personal.html">Personal</a></li>
<li><a href="home-fullscreen.html">Full Screen</a></li>
<li><a href="home-canvas-pattern.html">Canvas Pattern</a></li>
<li><a href="home-section-scroll.html">Page Section Scroll</a></li>
<li><a href="shop-2col.html">Shop</a></li>
<li><a href="home-coming-soon.html">Comming Soon</a></li>
</ul>
</li>
<li class="nav-has-sub">
<a href="#">One Page</a>
<ul class="nav-sub-dropdown">
<li><a href="onepage.html">Default</a></li>
<li><a href="onepage-personal.html">Personal</a></li>
<li><a href="onepage-video.html">Video</a></li>
<li><a href="onepage-youtube.html">Youtube</a></li>
<li><a href="onepage-static.html">Static</a></li>
<li><a href="onepage-fullwidth-slider.html">Fullwidth</a></li>
<li><a href="onepage-text-rotator1.html">Text Rotator1</a></li>
<li><a href="onepage-text-rotator2.html">Text Rotator2</a></li>
<li><a href="onepage-canvas-pattern.html">Canvas Pattern</a></li>
</ul>
</li>
</ul>
<!-- End Nav Dropdown -->
</li>
<li class="nav-has-sub">
<a>Page</a>
<!-- Nav Dropdown -->
<ul class="nav-dropdown">
<li class="nav-has-sub">
<a href="#">About Us</a>
<ul class="nav-sub-dropdown">
<li><a href="about-1.html">About 1</a></li>
<li><a href="about-2.html">About 2</a></li>
<li><a href="about-3.html">About 3</a></li>
</ul>
</li>
<li class="nav-has-sub">
<a href="#">Service</a>
<ul class="nav-sub-dropdown">
<li><a href="service-1.html">Service 1</a></li>
<li><a href="service-2.html">Service 2</a></li>
<li><a href="service-3.html">Service 3</a></li>
</ul>
</li>
<li class="nav-has-sub">
<a href="#">Contact Us</a>
<ul class="nav-sub-dropdown">
<li><a href="contact-1.html">Contact 1</a></li>
<li><a href="contact-2.html">Contact 2</a></li>
<li><a href="contact-3.html">Contact 3</a></li>
</ul>
</li>
<li class="nav-has-sub">
<a href="#">Faq</a>
<ul class="nav-sub-dropdown">
<li><a href="faq-1.html">Faq 1</a></li>
<li><a href="faq-2.html">Faq 2</a></li>
</ul>
</li>
<li class="nav-has-sub">
<a href="#">Login / Register</a>
<ul class="nav-sub-dropdown">
<li><a href="login.html">Login</a></li>
<li><a href="register.html">Register</a></li>
<li><a href="login-register.html">Login / Register</a></li>
</ul>
</li>
<li><a href="pricing.html">Pricing</a></li>
<li class="nav-has-sub">
<a href="#">404 Error</a>
<ul class="nav-sub-dropdown">
<li><a href="404-error-1.html">404 page1</a></li>
<li><a href="404-error-2.html">404 page2</a></li>
</ul>
</li>
<li><a href="sidebar-left.html">Sidebar Left</a></li>
<li><a href="sidebar-right.html">Sidebar Right</a></li>
<li><a href="blank-page.html">Blank Page</a></li>
</ul>
<!-- End Nav Dropdown-->
</li>
<li>
<a>Portfolio</a>
<!-- Nav Dropdown -->
<ul class="nav-dropdown">
<li class="nav-has-sub">
<a href='#'>Grid</a>
<ul class="nav-sub-dropdown">
<li><a href="portfolio-grid-2col.html">2 Columns</a></li>
<li><a href="portfolio-grid-2col-no_spacing.html">2 Columns no-Spacing</a></li>
<li><a href="portfolio-grid-3col.html">3 Columns</a></li>
<li><a href="portfolio-grid-3col-no_spacing.html">3 Columns no-Spacing</a></li>
<li><a href="portfolio-grid-4col.html">4 Columns</a></li>
<li><a href="portfolio-grid-4col-no_spacing.html">4 Columns no-Spacing</a></li>
</ul>
</li>
<li class="nav-has-sub">
<a href="">Masonry</a>
<ul class="nav-sub-dropdown">
<li><a href="portfolio-masonry-2col.html">2 Columns</a></li>
<li><a href="portfolio-masonry-2col-no_spacing.html">2 Columns no-Spacing</a></li>
<li><a href="portfolio-masonry-3col.html">3 Columns</a></li>
<li><a href="portfolio-masonry-3col-no_spacing.html">3 Columns no-Spacing</a></li>
<li><a href="portfolio-masonry-4col.html">4 Columns</a></li>
<li><a href="portfolio-masonry-4col-no_spacing.html">4 Columns no-Spacing</a></li>
</ul>
</li>
<li class="nav-has-sub">
<a href="">wide</a>
<ul class="nav-sub-dropdown">
<li><a href="portfolio-wide-grid.html">Grid</a></li>
<li><a href="portfolio-wide-grid-no_spacing.html">Grid no-Spacing</a></li>
<li><a href="portfolio-wide-masonry.html">Masonry</a></li>
<li><a href="portfolio-wide-masonry-no_spacing.html">Masonry no-Spacing</a></li>
</ul>
</li>
<li class="nav-has-sub">
<a href='#'>Classical</a>
<ul class="nav-sub-dropdown">
<li><a href="portfolio-classical-spacing.html">Spacing</a></li>
<li><a href="portfolio-classical-no_spacing.html">no-Spacing</a></li>
</ul>
</li>
<li class="nav-has-sub">
<a href='#'>Lightbox</a>
<ul class="nav-sub-dropdown">
<li><a href="portfolio-lightbox-grid.html">Grid</a></li>
<li><a href="portfolio-lightbox-masonry.html">Masonry</a></li>
</ul>
</li>
<li class="nav-has-sub">
<a href="">Single</a>
<ul class="nav-sub-dropdown">
<li><a href="portfolio-single1.html">Single 1</a></li>
<li><a href="portfolio-single2.html">Single 2</a></li>
<li><a href="portfolio-single3.html">Single 3</a></li>
<li><a href="portfolio-single4.html">Single 4</a></li>
<li><a href="portfolio-single5-slider.html">Single 5 - Slider</a></li>
<li><a href="portfolio-single6-video.html">Single 6 - Video</a></li>
<li><a href="portfolio-single7-youtube.html">Single 7 - youtube</a></li>
<li><a href="portfolio-single8-vimeo.html">Single 8 - vimeo</a></li>
</ul>
</li>
</ul>
<!-- End Nav Dropdown -->
</li>
<li>
<a>Blog</a>
<!-- Nav Dropdown -->
<ul class="nav-dropdown">
<li class="nav-has-sub">
<a href=''>Grid</a>
<ul class="nav-sub-dropdown">
<li><a href="blog-grid-2col.html">2 Columns</a></li>
<li><a href="blog-grid-2col-sidebar.html">2 Columns - sidebar</a></li>
<li><a href="blog-grid-3col.html">3 Columns</a></li>
</ul>
</li>
<li class="nav-has-sub">
<a href="">Masonry</a>
<ul class="nav-sub-dropdown">
<li><a href="blog-masonry-2col.html">2 Columns</a></li>
<li><a href="blog-masonry-2col-sidebar.html">2 Columns - sidebar</a></li>
<li><a href="blog-masonry-3col.html">3 Columns</a></li>
</ul>
</li>
<li class="nav-has-sub">
<a href="">One Columns</a>
<ul class="nav-sub-dropdown">
<li><a href="blog-1col.html">no-sidebar</a></li>
<li><a href="blog-1col-sidebar.html">with sidebar</a></li>
</ul>
</li>
<li class="nav-has-sub">
<a href="">Blog Detail</a>
<ul class="nav-sub-dropdown">
<li><a href="blog-single-image-post.html">Image Post</a></li>
<li><a href="blog-single-slider-post.html">Slider Post</a></li>
<li><a href="blog-single-video-post.html">Video Post</a></li>
<li><a href="blog-single-audio-post.html">Audio Post</a></li>
<li><a href="blog-single-youtube-post.html">Youtube Post</a></li>
<li><a href="blog-single-vimeo-post.html">Vimeo Post</a></li>
<li><a href="blog-single-quote-post.html">Quote Post</a></li>
</ul>
</li>
</ul>
<!-- End Nav Dropdown -->
</li>
<li>
<a>Elements</a>
<!-- Nav Dropdown -->
<ul class="nav-dropdown">
<li><a href="element-components.html">Components</a></li>
<li><a href="element-tabs-and-accordian.html">Tabs & Accordian</a></li>
<li><a href="element-slider.html">Slider</a></li>
<li><a href="element-team.html">Team</a></li>
<li><a href="element-pricing.html">Pricing</a></li>
<li><a href="element-video-and-audio.html">Video / Audio</a></li>
<li><a href="element-typography.html">Typography</a></li>
</ul>
<!-- End Nav Dropdown -->
</li>
<li>
<a href="">Shop</a>
<!-- Nav Dropdown -->
<ul class="nav-dropdown">
<li class=""><a href="shop-2col.html">2 Columns</a></li>
<li class=""><a href="shop-3col.html">3 Columns</a></li>
<li class=""><a href="shop-4col.html">4 Columns</a></li>
<li class=""><a href="shop-left-sidebar.html">Left Sidebar</a></li>
<li class=""><a href="shop-right-sidebar.html">Right Sidebar</a></li>
<li class=""><a href="shop-detail.html">Shop Detail</a></li>
<li class=""><a href="shop-checkout.html">Checkout</a></li>
</ul>
<!-- End Nav Dropdown -->
</li>
</ul>
</nav>
<!--End Navigation Menu -->
</div>
</header>
<!-- END HEADER -->
<!-- CONTENT --------------------------------------------------------------------------------->
<!-- Intro Section -->
<section class="inner-intro bg-img24 overlay-dark light-color parallax parallax-background2">
<div class="container">
<div class="row title">
<h2 class="h2">Service</h2>
<div class="page-breadcrumb">
<a>Home</a>/<span>Service</span>
</div>
</div>
</div>
</section>
<div class="clearfix"></div>
<!-- End Intro Section -->
<!-- Service Section -->
<section id="service" class="wow fadeIn pt pb-80">
<div class="container text-center">
<div class="row text-center">
<div class="col-md-8 col-md-offset-2">
<h3 class="h4">Our Service</h3>
<div class="spacer-15"></div>
<p class="lead">Integer tincidunt Cras dapibus ultricies nisi vel augue. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac.</p>
</div>
</div>
<div class="row mt-60">
<div class="wow fadeInLeft col-md-4 pt-80 pt-sm-0">
<div class="features-box-right">
<div class="features-icon-right"><i class="ion ion-ios-monitor-outline"></i></div>
<h5>bootstrap 3</h5>
<p>Consectetuer Adipiscing elit Aenean commodo Ligula dolor.</p>
</div>
<div class="features-box-right">
<div class="features-icon-right"><i class="ion ion-ios-videocam-outline"></i></div>
<h5>html 5 video</h5>
<p>Nullam dictum felis eu pede mollis pretium leo eget bibendum sodales augue velit cursus.</p>
</div>
<div class="features-box-right">
<div class="features-icon-right"><i class="ion ion-ios-barcode-outline"></i></div>
<h5>Clean code & design</h5>
<p>tellus eget condimentum rhoncus sem quam semper libero.</p>
</div>
<div class="features-box-right">
<div class="features-icon-right"><i class="ion ion-ios-albums-outline"></i></div>
<h5>Unlimited layouts</h5>
<p>Donec sodales sagittis magna. Sed consequat.</p>
</div>
</div>
<div class="wow fadeIn col-md-4 text-center hidden-sm">
<img src="img/moc-3.png" />
</div>
<div class="wow fadeInRight col-md-4 pt-80 pt-sm-0">
<div class="features-box-left">
<div class="features-icon-left"><i class="ion ion-ios-compose-outline"></i></div>
<h5>Flexible & Customizable</h5>
<p>Donec vitae sapien ut libero venenatis faucibus.</p>
</div>
<div class="features-box-left">
<div class="features-icon-left"><i class="ion ion-ios-eye-outline"></i></div>
<h5>Multi Concept & Mutli prapose Theme</h5>
<p>Quisque rutrum. Aenean imperdiet Etiam ultricies nisi.</p>
</div>
<div class="features-box-left">
<div class="features-icon-left"><i class="ion ion-ios-paper-outline"></i></div>
<h5>Well Documented</h5>
<p>Aenean vulputate eleifend tellus Aenean leo ligula porttitor.</p>
</div>
<div class="features-box-left">
<div class="features-icon-left"><i class="ion ion-ios-chatbubble-outline"></i></div>
<h5>Friendly Support</h5>
<p>Phasellus viverra nulla ut metus laoreet Quisque rutrum.</p>
</div>
</div>
</div>
</div>
</section>
<hr />
<!-- Process Section -->
<section class="ptb ptb-sm-80" id="process">
<div class="container text-center">
<div class="row">
<div class="col-md-2 col-sm-4 col-xs-6">
<div class="tipped" data-title="Step1 - Skype Interview" data-tipper-options='{"direction":"top"}'>
<div class="page-icon-top"><i class="ion ion-ios-people-outline"></i></div>
<h6>Interview</h6>
</div>
</div>
<div class="col-md-2 col-sm-4 col-xs-6">
<div class="tipped" data-title="Step2 - Project Plan" data-tipper-options='{"direction":"top"}'>
<div class="page-icon-top"><i class="ion ion-ios-paper-outline"></i></div>
<h6>Plan</h6>
</div>
</div>
<div class="col-md-2 col-sm-4 col-xs-6">
<div class="tipped" data-title="Step3 - Design" data-tipper-options='{"direction":"top"}'>
<div class="page-icon-top"><i class="ion ion-ios-compose-outline"></i></div>
<h6>Design</h6>
</div>
</div>
<div class="col-md-2 col-sm-4 col-xs-6">
<div class="tipped" data-title="Step4 - Development" data-tipper-options='{"direction":"top"}'>
<div class="page-icon-top"><i class="ion ion-ios-gear-outline"></i></div>
<h6>Development</h6>
</div>
</div>
<div class="col-md-2 col-sm-4 col-xs-6">
<div class="tipped" data-title="Step5 - Testing" data-tipper-options='{"direction":"top"}'>
<div class="page-icon-top"><i class="ion ion-ios-pulse"></i></div>
<h6>Testing</h6>
</div>
</div>
<div class="col-md-2 col-sm-4 col-xs-6">
<div class="tipped" data-title="Step6 - Delivery" data-tipper-options='{"direction":"top"}'>
<div class="page-icon-top"><i class="ion ion-ios-clock-outline"></i></div>
<h6>Delivery</h6>
</div>
</div>
</div>
</div>
</section>
<!-- End Process Section -->
<!-- Statement Section -->
<section class="dark-bg ptb-60" id="statement">
<div class="container text-center">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<h4 class="mb-15">Pellentesque eu pretium quis adipiscing sem?</h4>
<a class="btn btn-md btn-white">See More</a>
</div>
</div>
</div>
</section>
<!-- End Statement Section -->
<!-- Tab And Accordion -->
<section class="ptb ptb-sm-80">
<div class="container">
<div class="row">
<!-- Accordion -->
<div class="col-md-6 mb-30">
<div class="accordion">
<div class="accordion-section">
<h6 class="accordion-title">Design</h6>
<div class="accordion-content">
<p>Etiam rhoncus. Maecenas tempus, tellus eget condimentum rhoncus, sem quam semper libero, sit amet adipiscing sem neque sed ipsum. Nam quam nunc, blandit vel</p>
<p>Maecenas nec odio et ante tincidunt tempus. Donec vitae sapien ut libero venenatis faucibus. Nullam quis ante. Etiam sit amet orci eget eros.</p>
</div>
</div>
<div class="accordion-section">
<h6 class="accordion-title">Development</h6>
<div class="accordion-content">
<p>Etiam rhoncus. Maecenas tempus, tellus eget condimentum rhoncus, sem quam semper libero, sit amet adipiscing sem neque sed ipsum. Nam quam nunc, blandit vel</p>
<ul class="gray">
<li>Sit amet adipiscing sem neque.</li>
<li>Sapien ut libero venenatis faucibus.</li>
<li>Eget eros faucibus.</li>
</ul>
</div>
</div>
<div class="accordion-section">
<h6 class="accordion-title">Branding</h6>
<div class="accordion-content">
<p>Etiam rhoncus. Maecenas tempus, tellus eget condimentum rhoncus, sem quam semper libero, sit amet adipiscing sem neque sed ipsum. Nam quam nunc, blandit vel</p>
<p>Maecenas nec odio et ante tincidunt tempus. Donec vitae sapien ut libero venenatis faucibus. Nullam quis ante. Etiam sit amet orci eget eros.</p>
</div>
</div>
<div class="accordion-section">
<h6 class="accordion-title">Photography</h6>
<div class="accordion-content">
<p>Etiam rhoncus. Maecenas tempus, tellus eget condimentum rhoncus, sem quam semper libero, sit amet adipiscing sem neque sed ipsum. Nam quam nunc, blandit vel</p>
<p>Maecenas nec odio et ante tincidunt tempus. Donec vitae sapien ut libero venenatis faucibus. Nullam quis ante. Etiam sit amet orci eget eros.</p>
</div>
</div>
</div>
</div>
<!-- End Accordion -->
<div class="col-md-6">
<div class="tabs">
<ul>
<li><a href="#tabs-1"><i class="ion ion-help-circled left"></i>Help</a></li>
<li><a href="#tabs-2"><i class="ion ion-help-buoy left"></i>Support</a></li>
</ul>
<div class="ui-tab-content">
<div id="tabs-1">
<p>Etiam rhoncus. Maecenas tempus, tellus eget condimentum rhoncus, sem quam semper libero, sit amet adipiscing sem neque sed ipsum. Nam quam nunc, blandit vel</p>
<p>Maecenas nec odio et ante tincidunt tempus. Donec vitae sapien ut libero venenatis faucibus.</p>
</div>
<div id="tabs-2">
<p>Maecenas nec odio et ante tincidunt tempus. Donec vitae sapien ut libero venenatis faucibus. Nullam quis ante. Etiam sit amet orci eget eros.</p>
<p>Tellus eget condimentum rhoncus, sem quam semper libero, sit amet adipiscing sem neque sed ipsum. Nam quam nunc, blandit vel</p>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
<!-- End Tab And Accordion -->
<!-- End Service Section -->
<!-- End CONTENT ------------------------------------------------------------------------------>
<!-- FOOTER -->
<footer class="footer pt-80">
<div class="container">
<div class="row mb-60">
<!-- Logo -->
<div class="col-md-3 col-sm-3 col-xs-12 mb-xs-30">
<a class="footer-logo" href="home.html">
<img src="img/logo-black.png" /></a>
</div>
<!-- Logo -->
<!-- Newsletter -->
<div class="col-md-4 col-sm-5 col-xs-12 mb-xs-30">
<div class="newsletter">
<form>
<input type="email" class="newsletter-input input-md newsletter-input mb-0" placeholder="Enter Your Email">
<button class="newsletter-btn btn btn-xs btn-white" type="submit" value=""><i class="fa fa-angle-right mr-0"></i></button>
</form>
</div>
</div>
<!-- End Newsletter -->
<!-- Social -->
<div class="col-md-3 col-md-offset-2 col-sm-4 col-xs-12">
<ul class="social">
<li><a target="_blank" href="https://www.twitter.com/"><i class="fa fa-twitter"></i></a></li>
<li><a target="_blank" href="https://instagram.com/"><i class="fa fa-instagram"></i></a></li>
<li><a target="_blank" href="https://www.facebook.com/"><i class="fa fa-facebook"></i></a></li>
<li><a target="_blank" href="https://vimeo.com/"><i class="fa fa-vimeo-square"></i></a></li>
<li><a target="_blank" href="https://www.behance.net/"><i class="fa fa-behance"></i></a></li>
</ul>
</div>
<!-- End Social -->
</div>
<!--Footer Info -->
<div class="row footer-info mb-60">
<div class="col-md-3 col-sm-12 col-xs-12 mb-sm-30">
<p class="mb-xs-0">Our ante tincidunt tempus, Donec vitae sapien ut libero venenatis faucibus. Nullam quis ante. Etiam sit amet orci eget eros.</p>
<a class="btn-link-a" href="about-1.html">Read More</a>
</div>
<div class="col-md-3 col-sm-6 col-xs-12 mb-sm-30 mb-xs-0">
<ul class="link">
<li><a href="blog-grid-3col.html">Blog</a></li>
<li><a href="portfolio-grid-3col.html">Portfolio</a></li>
<li><a href="login-register.html">Login & Signup</a></li>
<li><a href="faq-1.html">FAQ</a></li>
<li><a href="about-1.html">About</a></li>
<li><a href="service-1.html">Service</a></li>
</ul>
</div>
<div class="col-md-3 col-sm-6 col-xs-12 mb-sm-30">
<ul class="link">
<li><a href="contact-1.html">Contact Us</a></li>
<li><a href="shop-checkout.html">Shopping Cart</a></li>
<li><a href="404-error-1.html">404 Error</a></li>
<li><a href="home.html">Home</a></li>
</ul>
</div>
<div class="col-md-3 col-sm-12 col-xs-12">
<p>502, DieSachbearbeiter, Schönhauser Allee, 167c10435 Berlin,Germany.</p>
<ul class="link-small">
<li><a href="mailto:yourname@domain.com"><i class="fa fa-envelope-o left"></i>yourname@domain.com</a></li>
<li><a><i class="fa fa-phone left"></i>+40 (0) 012 345 6789</a></li>
</ul>
</div>
</div>
<!-- End Footer Info -->
</div>
<hr />
<!-- Copyright Bar -->
<section class="copyright ptb-60">
<div class="container">
<p class="">
© 2015 <a><b>Mazel Template</b></a>. All Rights Reserved.
<br />
Template by <a target="_blank" href="http://nileforest.com/"><b>nileforest</b></a>
</p>
</div>
</section>
<!-- End Copyright Bar -->
</footer>
<!-- END FOOTER -->
<!-- Scroll Top -->
<a class="scroll-top">
<i class="fa fa-angle-double-up"></i>
</a>
<!-- End Scroll Top -->
</div>
<!-- Site Wraper End -->
<!-- JS -->
<script src="js/jquery-1.11.2.min.js" type="text/javascript"></script>
<script src="js/jquery-ui.min.js" type="text/javascript"></script>
<script src="js/plugin/jquery.easing.js" type="text/javascript"></script>
<script src="js/bootstrap.min.js" type="text/javascript"></script>
<script src="js/plugin/jquery.flexslider.js" type="text/javascript"></script>
<script src="js/plugin/background-check.min.js" type="text/javascript"></script>
<script src="js/plugin/jquery.fitvids.js" type="text/javascript"></script>
<script src="js/plugin/jquery.viewportchecker.js" type="text/javascript"></script>
<script src="js/plugin/jquery.stellar.min.js" type="text/javascript"></script>
<script src="js/plugin/wow.min.js" type="text/javascript"></script>
<script src="js/plugin/jquery.colorbox-min.js" type="text/javascript"></script>
<script src="js/plugin/owl.carousel.min.js" type="text/javascript"></script>
<script src="js/plugin/isotope.pkgd.min.js" type="text/javascript"></script>
<script src="js/plugin/masonry.pkgd.min.js" type="text/javascript"></script>
<script src="js/plugin/imagesloaded.pkgd.min.js" type="text/javascript"></script>
<script src="js/plugin/jPushMenu.js" type="text/javascript"></script>
<script src="js/plugin/jquery.fs.tipper.min.js" type="text/javascript"></script>
<script src="js/plugin/mediaelement-and-player.min.js"></script>
<script src="js/plugin/jquery.validate.min.js" type="text/javascript"></script>
<script src="js/theme.js" type="text/javascript"></script>
<script src="js/navigation.js" type="text/javascript"></script>
</body>
</html>
| {
"content_hash": "ed14ef3804cd3923161783165671058d",
"timestamp": "",
"source": "github",
"line_count": 732,
"max_line_length": 199,
"avg_line_length": 59.736338797814206,
"alnum_prop": 0.3899878793422828,
"repo_name": "georgetoothman/MunchyFuel",
"id": "e22f5fd3659d923b45466825b2858e5337d37f0e",
"size": "43731",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "Mazel-html-template/service-2.html",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "533208"
},
{
"name": "CoffeeScript",
"bytes": "422"
},
{
"name": "HTML",
"bytes": "4648023"
},
{
"name": "JavaScript",
"bytes": "945938"
},
{
"name": "PHP",
"bytes": "1023"
},
{
"name": "Ruby",
"bytes": "61220"
}
],
"symlink_target": ""
} |
package com.pg85.otg.util.biome;
import com.pg85.otg.exceptions.InvalidConfigException;
import com.pg85.otg.util.helpers.StringHelper;
import java.util.ArrayList;
import java.util.List;
public class ReplaceBlocks
{
private final String sourceBlock;
private final String targetBlock;
private ReplaceBlocks(String sourceBlock, String targetBlock)
{
this.sourceBlock = sourceBlock;
this.targetBlock = targetBlock;
}
public String getSourceBlock()
{
return this.sourceBlock;
}
public String getTargetBlock()
{
return this.targetBlock;
}
public static List<ReplaceBlocks> fromJson(String originalJson) throws InvalidConfigException
{
if(originalJson == null || originalJson.length() == 0)
{
return null;
}
// Example: [{"mob": "Sheep", "weight": 12, "min": 4, "max": 4}]
List<ReplaceBlocks> mobGroups = new ArrayList<ReplaceBlocks>();
String json = originalJson.trim();
if (json.length() <= 2)
{
// Empty Json
return mobGroups;
}
// Remove the [..]
json = removeFirstAndLastChar(json);
// Every group is separated by a , but in the group the , is also
// used.
// So convert the ( to {, the ) to } and use an existing function to
// get each group
json = json.replace('{', '(');
json = json.replace('}', ')');
String[] groups = StringHelper.readCommaSeperatedString(json);
for (String group : groups)
{
mobGroups.add(readSingleGroup(group));
}
return mobGroups;
}
private static ReplaceBlocks readSingleGroup(String json) throws InvalidConfigException
{
String group = removeFirstAndLastChar(json.trim());
String[] groupParts = StringHelper.readCommaSeperatedString(group);
String sourceBlock = null;
String targetBlock = null;
// Read all options
for (String option : groupParts)
{
option = option.replace(" ", "");
String[] optionParts = option.split("\"");
if (optionParts.length != 4)
{
throw new InvalidConfigException("Invalid JSON structure near " + option);
}
sourceBlock = optionParts[1];
targetBlock = optionParts[3];
}
// Check if data is complete and valid
if (sourceBlock == null || targetBlock == null)
{
throw new InvalidConfigException("Invalid JSON: " + json + ". Expected [{\"sourceblock1\":\"targetblock1\"},{\"sourceblock2\":\"targetblock2\"}] etc.");
}
return new ReplaceBlocks(sourceBlock, targetBlock);
}
/**
* Converts a list of mob groups to a single, JSON-formatted string.
* @param list The list to convert.
* @return The mob groups.
*/
public static String toJson(List<ReplaceBlocks> list)
{
StringBuilder json = new StringBuilder("[");
if(list != null)
{
for (ReplaceBlocks group : list)
{
group.toJson(json);
json.append(", ");
}
} else {
return "";
}
// Remove ", " at end
if (json.length() != 1)
{
json.deleteCharAt(json.length() - 1);
json.deleteCharAt(json.length() - 1);
}
// Add closing bracket
json.append(']');
return json.toString();
}
/**
* Converts this group to a JSON string.
* @param json The {@link StringBuilder} to append the JSON to.
*/
private void toJson(StringBuilder json)
{
json.append("{\"");
json.append(sourceBlock);
json.append("\":\"");
json.append(targetBlock);
json.append("\"}");
}
@Override
public String toString()
{
StringBuilder builder = new StringBuilder();
toJson(builder);
return builder.toString();
}
@Override
public int hashCode()
{
int prime = 31;
int result = 1;
result = prime * result + sourceBlock.hashCode();
result = prime * result + targetBlock.hashCode();
return result;
}
@Override
public boolean equals(Object obj)
{
if (this == obj)
{
return true;
}
if (obj == null)
{
return false;
}
if (!(obj instanceof ReplaceBlocks))
{
return false;
}
ReplaceBlocks other = (ReplaceBlocks) obj;
if (sourceBlock != other.sourceBlock || targetBlock != other.targetBlock)
{
return false;
}
if (!sourceBlock.equals(other.sourceBlock) || !targetBlock.equals(other.targetBlock))
{
return false;
}
return true;
}
private static String removeFirstAndLastChar(String string)
{
return string.substring(1, string.length() - 1);
}
}
| {
"content_hash": "1bf21dbc227c4c2ce44bbed4a51bc7e5",
"timestamp": "",
"source": "github",
"line_count": 186,
"max_line_length": 155,
"avg_line_length": 22.64516129032258,
"alnum_prop": 0.6678537511870846,
"repo_name": "PG85/OpenTerrainGenerator",
"id": "155b2c9008b7d40ebd6bbee287b929fa9129bbd1",
"size": "4212",
"binary": false,
"copies": "1",
"ref": "refs/heads/1.16.4",
"path": "common/common-util/src/main/java/com/pg85/otg/util/biome/ReplaceBlocks.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "2736931"
}
],
"symlink_target": ""
} |
/* tslint:disable:no-unused-variable */
import {
beforeEach, beforeEachProviders,
describe, xdescribe,
expect, it, xit,
async, inject
} from '@angular/core/testing';
import {NgModelInput} from './ng-model-input';
describe('NgModelInput', () => {
it('should create an instance', () => {
expect(new NgModelInput()).toBeTruthy();
});
});
| {
"content_hash": "c7d89092af3ad8fe509b528cdcf0bbec",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 46,
"avg_line_length": 23.533333333333335,
"alnum_prop": 0.6628895184135978,
"repo_name": "ng2select/bootstrap",
"id": "133f8d86af8c91b4c0f3a46d41a4f7e519c5130d",
"size": "353",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/app/core/ng-model-input.spec.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "93"
},
{
"name": "CSS",
"bytes": "13161"
},
{
"name": "HTML",
"bytes": "10528"
},
{
"name": "JavaScript",
"bytes": "4186"
},
{
"name": "TypeScript",
"bytes": "44571"
}
],
"symlink_target": ""
} |
class CefStreamWriterCToCpp
: public CefCToCpp<CefStreamWriterCToCpp, CefStreamWriter,
cef_stream_writer_t> {
public:
CefStreamWriterCToCpp();
// CefStreamWriter methods.
size_t Write(const void* ptr, size_t size, size_t n) OVERRIDE;
int Seek(int64 offset, int whence) OVERRIDE;
int64 Tell() OVERRIDE;
int Flush() OVERRIDE;
bool MayBlock() OVERRIDE;
};
#endif // USING_CEF_SHARED
#endif // CEF_LIBCEF_DLL_CTOCPP_STREAM_WRITER_CTOCPP_H_
| {
"content_hash": "68f2393c13db3b81dc3d8d260da4574e",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 64,
"avg_line_length": 29.1875,
"alnum_prop": 0.7194860813704497,
"repo_name": "tnelab/tchapp",
"id": "fb6ae06e5d28febe4b70f7274c28b2d57a56a773",
"size": "1457",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "src/native/libtch_dll/libcef_dll/ctocpp/stream_writer_ctocpp.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "9081"
},
{
"name": "C#",
"bytes": "546455"
},
{
"name": "C++",
"bytes": "1886934"
},
{
"name": "CMake",
"bytes": "85327"
},
{
"name": "HTML",
"bytes": "110859"
},
{
"name": "JavaScript",
"bytes": "10444"
},
{
"name": "Objective-C",
"bytes": "862"
},
{
"name": "PowerShell",
"bytes": "50957"
},
{
"name": "Shell",
"bytes": "1682"
}
],
"symlink_target": ""
} |
package be.plutus.api.dto.response;
import be.plutus.core.model.transaction.TransactionType;
import com.fasterxml.jackson.annotation.JsonFormat;
import java.time.ZonedDateTime;
public class TransactionDTO{
private int id;
private String title;
private String description;
private double amount;
private TransactionType type;
private LocationDTO location;
private ZonedDateTime timestamp;
public TransactionDTO(){
}
public int getId(){
return id;
}
public void setId( int id ){
this.id = id;
}
public String getTitle(){
return title;
}
public void setTitle( String title ){
this.title = title;
}
public String getDescription(){
return description;
}
public void setDescription( String description ){
this.description = description;
}
public double getAmount(){
return amount;
}
public void setAmount( double amount ){
this.amount = amount;
}
public TransactionType getType(){
return type;
}
public void setType( TransactionType type ){
this.type = type;
}
public LocationDTO getLocation(){
return location;
}
public void setLocation( LocationDTO location ){
this.location = location;
}
public ZonedDateTime getTimestamp(){
return timestamp;
}
public void setTimestamp( ZonedDateTime timestamp ){
this.timestamp = timestamp;
}
@JsonFormat( pattern = "yyyy-MM-dd'T'HH:mm:ssZ" )
public ZonedDateTime getTimestampISO8601(){
return timestamp;
}
}
| {
"content_hash": "86057cef3635256ee40041013a1c45a3",
"timestamp": "",
"source": "github",
"line_count": 81,
"max_line_length": 56,
"avg_line_length": 20.25925925925926,
"alnum_prop": 0.6392443631931749,
"repo_name": "plutus-dev/PlutusAPI",
"id": "0be07bf502e0306a6b96676344506f15980db6dd",
"size": "1641",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/be/plutus/api/dto/response/TransactionDTO.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "81769"
}
],
"symlink_target": ""
} |
<?php declare(strict_types = 1);
namespace Tests\ContactModule;
use App\ContactModule\Contact;
use PHPUnit\Framework\TestCase;
final class ContactTest extends TestCase
{
private const NAME = 'name';
private const POSITION = 'position';
private const ADDRESS = 'address';
public static function createContact(): Contact
{
return new Contact(self::NAME, self::POSITION, self::ADDRESS);
}
public function test(): void
{
$contact = self::createContact();
$this->assertEquals(self::NAME, $contact->getName());
$this->assertEquals(self::POSITION, $contact->getPosition());
$this->assertEquals(self::ADDRESS, $contact->getAddress());
$this->assertNull($contact->getAvatar());
$this->assertEmpty($contact->getLinks());
$contact->setAvatar($avatar = ContactAvatarTest::createContactAvatar());
$this->assertSame($avatar, $contact->getAvatar());
$contact->addLink($link = ContactLinkTest::createContactLink());
$this->assertSame([$link], $contact->getLinks());
}
}
| {
"content_hash": "fe3a785d1069cb54974e44a8ca8a69b1",
"timestamp": "",
"source": "github",
"line_count": 38,
"max_line_length": 74,
"avg_line_length": 26.210526315789473,
"alnum_prop": 0.7128514056224899,
"repo_name": "vitkutny/vitkutny.cz",
"id": "eafcea018b28737bfeb5b0920478d38f6f9aa968",
"size": "996",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/ContactModule/ContactTest.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "571"
},
{
"name": "HTML",
"bytes": "5024"
},
{
"name": "JavaScript",
"bytes": "1369"
},
{
"name": "PHP",
"bytes": "34270"
}
],
"symlink_target": ""
} |
package org.jetbrains.plugins.javaFX.fxml.refs;
import com.intellij.codeInsight.completion.PrioritizedLookupElement;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.lookup.LookupElementBuilder;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.*;
import com.intellij.psi.util.InheritanceUtil;
import com.intellij.psi.util.PropertyUtil;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.TypeConversionUtil;
import com.intellij.psi.xml.XmlAttributeValue;
import com.intellij.psi.xml.XmlTag;
import com.intellij.util.ArrayUtil;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.ProcessingContext;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.plugins.javaFX.fxml.FxmlConstants;
import org.jetbrains.plugins.javaFX.fxml.JavaFxPsiUtil;
import org.jetbrains.plugins.javaFX.fxml.descriptors.JavaFxPropertyAttributeDescriptor;
import java.util.*;
import java.util.stream.Collectors;
/**
* User: anna
*/
public class JavaFxComponentIdReferenceProvider extends PsiReferenceProvider {
@NotNull
@Override
public PsiReference[] getReferencesByElement(@NotNull PsiElement element,
@NotNull ProcessingContext context) {
final XmlAttributeValue xmlAttributeValue = (XmlAttributeValue)element;
final String value = xmlAttributeValue.getValue();
if (JavaFxPsiUtil.isIncorrectExpressionBinding(value)) {
return PsiReference.EMPTY_ARRAY;
}
final XmlTag currentTag = PsiTreeUtil.getParentOfType(xmlAttributeValue, XmlTag.class);
final Map<String, XmlAttributeValue> fileIds = JavaFxPsiUtil.collectFileIds(currentTag);
if (JavaFxPsiUtil.isExpressionBinding(value)) {
return getExpressionReferences(element, xmlAttributeValue, value, fileIds);
}
if (value.startsWith("$")) {
return getSinglePropertyReferences(xmlAttributeValue, value, fileIds);
}
final Set<String> acceptableIds = new HashSet<String>();
if (currentTag != null) {
final XmlTag parentTag = currentTag.getParentTag();
for (final String id : fileIds.keySet()) {
final XmlAttributeValue resolvedAttrValue = fileIds.get(id);
if (JavaFxPsiUtil.isClassAcceptable(parentTag, JavaFxPsiUtil.getTagClass(resolvedAttrValue))) {
acceptableIds.add(id);
}
}
}
return new PsiReference[]{new JavaFxIdReferenceBase(xmlAttributeValue, fileIds, acceptableIds, value)};
}
@NotNull
private static PsiReference[] getExpressionReferences(@NotNull PsiElement element,
@NotNull XmlAttributeValue xmlAttributeValue,
@NotNull String value,
@NotNull Map<String, XmlAttributeValue> fileIds) {
final String expressionBody = value.substring(2, value.length() - 1);
final List<String> propertyNames = StringUtil.split(expressionBody, ".", true, false);
if (JavaFxPropertyAttributeDescriptor.isIncompletePropertyChain(propertyNames)) return PsiReference.EMPTY_ARRAY;
if (propertyNames.size() == 1) {
return getSinglePropertyReferences(xmlAttributeValue, fileIds, expressionBody, 2);
}
final PsiClass controllerClass = JavaFxPsiUtil.getControllerClass(element.getContainingFile());
final String firstPropertyName = propertyNames.get(0);
int positionInExpression = 2;
final List<PsiReference> result = new ArrayList<>();
final PsiReferenceBase firstReference =
getIdReferenceBase(xmlAttributeValue, firstPropertyName, fileIds, Collections.emptyMap(), controllerClass);
positionInExpression = adjustTextRange(firstPropertyName, firstReference, positionInExpression);
PsiClass propertyOwnerClass = FxmlConstants.CONTROLLER.equals(firstPropertyName) ?
controllerClass : JavaFxPsiUtil.getTagClass(fileIds.get(firstPropertyName));
result.add(firstReference);
final List<String> remainingPropertyNames = propertyNames.subList(1, propertyNames.size());
for (String propertyName : remainingPropertyNames) {
final JavaFxExpressionReferenceBase reference =
new JavaFxExpressionReferenceBase(xmlAttributeValue, propertyOwnerClass, propertyName);
positionInExpression = adjustTextRange(propertyName, reference, positionInExpression);
final PsiType propertyType = JavaFxPsiUtil.getReadablePropertyType(reference.resolve());
propertyOwnerClass = propertyType instanceof PsiClassType ? ((PsiClassType)propertyType).resolve() : null;
result.add(reference);
}
return result.toArray(PsiReference.EMPTY_ARRAY);
}
@NotNull
private static PsiReference[] getSinglePropertyReferences(@NotNull XmlAttributeValue xmlAttributeValue,
@NotNull String value,
@NotNull Map<String, XmlAttributeValue> fileIds) {
return getSinglePropertyReferences(xmlAttributeValue, fileIds, value.substring(1), 1);
}
@NotNull
private static PsiReference[] getSinglePropertyReferences(@NotNull XmlAttributeValue xmlAttributeValue,
@NotNull Map<String, XmlAttributeValue> fileIds,
@NotNull String propertyName,
int positionInExpression) {
final PsiClass controllerClass = JavaFxPsiUtil.getControllerClass(xmlAttributeValue.getContainingFile());
final Map<String, TypeMatch> typeMatches = getTypeMatches(xmlAttributeValue, fileIds);
final PsiReferenceBase reference = getIdReferenceBase(xmlAttributeValue, propertyName, fileIds, typeMatches, controllerClass);
adjustTextRange(propertyName, reference, positionInExpression);
return new PsiReference[]{reference};
}
private static Map<String, TypeMatch> getTypeMatches(@NotNull XmlAttributeValue xmlAttributeValue,
@NotNull Map<String, XmlAttributeValue> fileIds) {
final PsiClass targetPropertyClass = JavaFxPsiUtil.getWritablePropertyClass(xmlAttributeValue);
final boolean isConvertible = targetPropertyClass != null && JavaFxPsiUtil.hasConversionFromAnyType(targetPropertyClass);
return fileIds.entrySet().stream().collect(
Collectors.toMap(Map.Entry::getKey, e -> {
final PsiClass valueClass = JavaFxPsiUtil.getTagClassById(e.getValue(), e.getKey(), xmlAttributeValue);
return TypeMatch.getMatch(valueClass, targetPropertyClass, isConvertible);
}));
}
private static int adjustTextRange(@NotNull String propertyName, @NotNull PsiReferenceBase reference, int positionInExpression) {
final TextRange range = reference.getRangeInElement();
final int startOffset = range.getStartOffset() + positionInExpression;
final int endOffset = startOffset + propertyName.length();
reference.setRangeInElement(new TextRange(startOffset, endOffset));
return positionInExpression + propertyName.length() + 1;
}
@NotNull
private static PsiReferenceBase getIdReferenceBase(XmlAttributeValue xmlAttributeValue,
String referencesId,
Map<String, XmlAttributeValue> fileIds,
Map<String, TypeMatch> typeMatches,
PsiClass controllerClass) {
if (controllerClass != null && !FxmlConstants.CONTROLLER.equals(referencesId)) {
final PsiField controllerField = controllerClass.findFieldByName(referencesId, false);
if (controllerField != null) {
return new JavaFxFieldIdReferenceProvider.JavaFxControllerFieldRef(xmlAttributeValue, controllerField, controllerClass);
}
}
return new JavaFxIdReferenceBase(xmlAttributeValue, fileIds, typeMatches, referencesId);
}
private enum TypeMatch {
ASSIGNABLE(3.0),
CONVERTIBLE(2.0),
UNDEFINED(1.0),
INCOMPATIBLE(0.0);
private final double myPriority;
TypeMatch(double priority) {
myPriority = priority;
}
public static double getPriority(TypeMatch match) {
return match != null ? match.myPriority : 0.0;
}
@NotNull
public static TypeMatch getMatch(PsiClass valueClass, PsiClass targetPropertyClass, boolean isConvertible) {
if (valueClass == null || targetPropertyClass == null) return UNDEFINED;
if (InheritanceUtil.isInheritorOrSelf(valueClass, targetPropertyClass, true)) return ASSIGNABLE;
if (isConvertible) return CONVERTIBLE;
return INCOMPATIBLE;
}
}
public static class JavaFxIdReferenceBase extends PsiReferenceBase<XmlAttributeValue> {
private final Map<String, XmlAttributeValue> myFileIds;
private final Set<String> myAcceptableIds;
private final Map<String, TypeMatch> myTypeMatches;
private final String myReferencesId;
private JavaFxIdReferenceBase(XmlAttributeValue element,
Map<String, XmlAttributeValue> fileIds,
Set<String> acceptableIds,
String referencesId) {
super(element);
myFileIds = fileIds;
myAcceptableIds = acceptableIds;
myReferencesId = referencesId;
myTypeMatches = Collections.emptyMap();
}
public JavaFxIdReferenceBase(XmlAttributeValue xmlAttributeValue,
Map<String, XmlAttributeValue> fileIds,
Map<String, TypeMatch> typeMatches,
String referencesId) {
super(xmlAttributeValue);
myFileIds = fileIds;
myTypeMatches = typeMatches;
myReferencesId = referencesId;
myAcceptableIds = myFileIds.keySet();
}
@Nullable
@Override
public PsiElement resolve() {
return myFileIds.get(myReferencesId);
}
@NotNull
@Override
public Object[] getVariants() {
return myAcceptableIds.stream()
.map(id -> PrioritizedLookupElement.withPriority(LookupElementBuilder.create(id), TypeMatch.getPriority(myTypeMatches.get(id))))
.toArray(LookupElement[]::new);
}
public boolean isBuiltIn() {
return FxmlConstants.CONTROLLER.equals(myReferencesId) || myReferencesId.endsWith(FxmlConstants.CONTROLLER_SUFFIX);
}
}
private static class JavaFxExpressionReferenceBase extends JavaFxPropertyReference<XmlAttributeValue> {
private final String myFieldName;
public JavaFxExpressionReferenceBase(@NotNull XmlAttributeValue xmlAttributeValue, PsiClass tagClass, @NotNull String fieldName) {
super(xmlAttributeValue, tagClass);
myFieldName = fieldName;
}
@Nullable
@Override
public PsiElement resolve() {
return JavaFxPsiUtil.collectReadableProperties(myPsiClass).get(myFieldName);
}
@NotNull
@Override
public Object[] getVariants() {
final XmlAttributeValue xmlAttributeValue = getElement();
final PsiElement declaration = JavaFxPsiUtil.getAttributeDeclaration(xmlAttributeValue);
final PsiType propertyType = JavaFxPsiUtil.getWritablePropertyType(myPsiClass, declaration);
if (propertyType != null) {
return collectProperties(propertyType, xmlAttributeValue.getProject());
}
return ArrayUtil.EMPTY_OBJECT_ARRAY;
}
private Object[] collectProperties(@NotNull PsiType propertyType, @NotNull Project project) {
final PsiType resolvedType = JavaFxPsiUtil.getWritablePropertyType(propertyType, project);
final List<LookupElement> objs = new ArrayList<>();
final Collection<PsiMember> readableProperties = JavaFxPsiUtil.collectReadableProperties(myPsiClass).values();
for (PsiMember readableMember : readableProperties) {
final PsiType readableType = JavaFxPsiUtil.getReadablePropertyType(readableMember);
if (readableType == null) continue;
if (TypeConversionUtil.isAssignable(propertyType, readableType) ||
resolvedType != null && TypeConversionUtil.isAssignable(resolvedType, readableType)) {
final String propertyName = PropertyUtil.getPropertyName(readableMember);
if (propertyName != null) {
objs.add(LookupElementBuilder.create(readableMember, propertyName));
}
}
}
return ArrayUtil.toObjectArray(objs);
}
@NotNull
@Override
public String getPropertyName() {
return myFieldName;
}
@Override
public PsiElement handleElementRename(String newElementName) throws IncorrectOperationException {
final String newPropertyName = JavaFxPsiUtil.getPropertyName(newElementName, resolve() instanceof PsiMethod);
return super.handleElementRename(newPropertyName);
}
}
}
| {
"content_hash": "491272a4c6a7932f3dcf31fccb8ffe43",
"timestamp": "",
"source": "github",
"line_count": 282,
"max_line_length": 136,
"avg_line_length": 46.59219858156028,
"alnum_prop": 0.703554303980516,
"repo_name": "retomerz/intellij-community",
"id": "fe8d81f915ed39572b94ef2b4b59ea20f9dbf688",
"size": "13739",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/refs/JavaFxComponentIdReferenceProvider.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "AMPL",
"bytes": "20665"
},
{
"name": "AspectJ",
"bytes": "182"
},
{
"name": "Batchfile",
"bytes": "63896"
},
{
"name": "C",
"bytes": "214817"
},
{
"name": "C#",
"bytes": "1538"
},
{
"name": "C++",
"bytes": "191650"
},
{
"name": "CSS",
"bytes": "197224"
},
{
"name": "CoffeeScript",
"bytes": "1759"
},
{
"name": "Cucumber",
"bytes": "14382"
},
{
"name": "Erlang",
"bytes": "10"
},
{
"name": "Groff",
"bytes": "35232"
},
{
"name": "Groovy",
"bytes": "2479412"
},
{
"name": "HLSL",
"bytes": "57"
},
{
"name": "HTML",
"bytes": "1805957"
},
{
"name": "J",
"bytes": "5050"
},
{
"name": "Java",
"bytes": "155824458"
},
{
"name": "JavaScript",
"bytes": "563135"
},
{
"name": "Jupyter Notebook",
"bytes": "92629"
},
{
"name": "Kotlin",
"bytes": "1502112"
},
{
"name": "Lex",
"bytes": "179878"
},
{
"name": "Makefile",
"bytes": "2352"
},
{
"name": "NSIS",
"bytes": "53702"
},
{
"name": "Objective-C",
"bytes": "27052"
},
{
"name": "Perl",
"bytes": "903"
},
{
"name": "Perl6",
"bytes": "26"
},
{
"name": "Protocol Buffer",
"bytes": "6570"
},
{
"name": "Python",
"bytes": "23633812"
},
{
"name": "Ruby",
"bytes": "1213"
},
{
"name": "Scala",
"bytes": "11698"
},
{
"name": "Shell",
"bytes": "68088"
},
{
"name": "Smalltalk",
"bytes": "64"
},
{
"name": "TeX",
"bytes": "25473"
},
{
"name": "TypeScript",
"bytes": "9469"
},
{
"name": "XSLT",
"bytes": "113040"
}
],
"symlink_target": ""
} |
namespace capnp {
namespace schemas {
CAPNP_DECLARE_SCHEMA(9fd69ebc87b9719c);
enum class Side_9fd69ebc87b9719c: uint16_t {
SERVER,
CLIENT,
};
CAPNP_DECLARE_ENUM(Side, 9fd69ebc87b9719c);
CAPNP_DECLARE_SCHEMA(d20b909fee733a8e);
CAPNP_DECLARE_SCHEMA(b88d09a9c5f39817);
CAPNP_DECLARE_SCHEMA(89f389b6fd4082c1);
CAPNP_DECLARE_SCHEMA(b47f4979672cb59d);
CAPNP_DECLARE_SCHEMA(95b29059097fca83);
CAPNP_DECLARE_SCHEMA(9d263a3630b7ebee);
} // namespace schemas
} // namespace capnp
namespace capnp {
namespace rpc {
namespace twoparty {
typedef ::capnp::schemas::Side_9fd69ebc87b9719c Side;
struct VatId {
VatId() = delete;
class Reader;
class Builder;
class Pipeline;
struct _capnpPrivate {
CAPNP_DECLARE_STRUCT_HEADER(d20b909fee733a8e, 1, 0)
#if !CAPNP_LITE
static constexpr ::capnp::_::RawBrandedSchema const* brand() { return &schema->defaultBrand; }
#endif // !CAPNP_LITE
};
};
struct ProvisionId {
ProvisionId() = delete;
class Reader;
class Builder;
class Pipeline;
struct _capnpPrivate {
CAPNP_DECLARE_STRUCT_HEADER(b88d09a9c5f39817, 1, 0)
#if !CAPNP_LITE
static constexpr ::capnp::_::RawBrandedSchema const* brand() { return &schema->defaultBrand; }
#endif // !CAPNP_LITE
};
};
struct RecipientId {
RecipientId() = delete;
class Reader;
class Builder;
class Pipeline;
struct _capnpPrivate {
CAPNP_DECLARE_STRUCT_HEADER(89f389b6fd4082c1, 0, 0)
#if !CAPNP_LITE
static constexpr ::capnp::_::RawBrandedSchema const* brand() { return &schema->defaultBrand; }
#endif // !CAPNP_LITE
};
};
struct ThirdPartyCapId {
ThirdPartyCapId() = delete;
class Reader;
class Builder;
class Pipeline;
struct _capnpPrivate {
CAPNP_DECLARE_STRUCT_HEADER(b47f4979672cb59d, 0, 0)
#if !CAPNP_LITE
static constexpr ::capnp::_::RawBrandedSchema const* brand() { return &schema->defaultBrand; }
#endif // !CAPNP_LITE
};
};
struct JoinKeyPart {
JoinKeyPart() = delete;
class Reader;
class Builder;
class Pipeline;
struct _capnpPrivate {
CAPNP_DECLARE_STRUCT_HEADER(95b29059097fca83, 1, 0)
#if !CAPNP_LITE
static constexpr ::capnp::_::RawBrandedSchema const* brand() { return &schema->defaultBrand; }
#endif // !CAPNP_LITE
};
};
struct JoinResult {
JoinResult() = delete;
class Reader;
class Builder;
class Pipeline;
struct _capnpPrivate {
CAPNP_DECLARE_STRUCT_HEADER(9d263a3630b7ebee, 1, 1)
#if !CAPNP_LITE
static constexpr ::capnp::_::RawBrandedSchema const* brand() { return &schema->defaultBrand; }
#endif // !CAPNP_LITE
};
};
// =======================================================================================
class VatId::Reader {
public:
typedef VatId Reads;
Reader() = default;
inline explicit Reader(::capnp::_::StructReader base): _reader(base) {}
inline ::capnp::MessageSize totalSize() const {
return _reader.totalSize().asPublic();
}
#if !CAPNP_LITE
inline ::kj::StringTree toString() const {
return ::capnp::_::structString(_reader, *_capnpPrivate::brand());
}
#endif // !CAPNP_LITE
inline ::capnp::rpc::twoparty::Side getSide() const;
private:
::capnp::_::StructReader _reader;
template <typename, ::capnp::Kind>
friend struct ::capnp::ToDynamic_;
template <typename, ::capnp::Kind>
friend struct ::capnp::_::PointerHelpers;
template <typename, ::capnp::Kind>
friend struct ::capnp::List;
friend class ::capnp::MessageBuilder;
friend class ::capnp::Orphanage;
};
class VatId::Builder {
public:
typedef VatId Builds;
Builder() = delete; // Deleted to discourage incorrect usage.
// You can explicitly initialize to nullptr instead.
inline Builder(decltype(nullptr)) {}
inline explicit Builder(::capnp::_::StructBuilder base): _builder(base) {}
inline operator Reader() const { return Reader(_builder.asReader()); }
inline Reader asReader() const { return *this; }
inline ::capnp::MessageSize totalSize() const { return asReader().totalSize(); }
#if !CAPNP_LITE
inline ::kj::StringTree toString() const { return asReader().toString(); }
#endif // !CAPNP_LITE
inline ::capnp::rpc::twoparty::Side getSide();
inline void setSide( ::capnp::rpc::twoparty::Side value);
private:
::capnp::_::StructBuilder _builder;
template <typename, ::capnp::Kind>
friend struct ::capnp::ToDynamic_;
friend class ::capnp::Orphanage;
template <typename, ::capnp::Kind>
friend struct ::capnp::_::PointerHelpers;
};
#if !CAPNP_LITE
class VatId::Pipeline {
public:
typedef VatId Pipelines;
inline Pipeline(decltype(nullptr)): _typeless(nullptr) {}
inline explicit Pipeline(::capnp::AnyPointer::Pipeline&& typeless)
: _typeless(kj::mv(typeless)) {}
private:
::capnp::AnyPointer::Pipeline _typeless;
friend class ::capnp::PipelineHook;
template <typename, ::capnp::Kind>
friend struct ::capnp::ToDynamic_;
};
#endif // !CAPNP_LITE
class ProvisionId::Reader {
public:
typedef ProvisionId Reads;
Reader() = default;
inline explicit Reader(::capnp::_::StructReader base): _reader(base) {}
inline ::capnp::MessageSize totalSize() const {
return _reader.totalSize().asPublic();
}
#if !CAPNP_LITE
inline ::kj::StringTree toString() const {
return ::capnp::_::structString(_reader, *_capnpPrivate::brand());
}
#endif // !CAPNP_LITE
inline ::uint32_t getJoinId() const;
private:
::capnp::_::StructReader _reader;
template <typename, ::capnp::Kind>
friend struct ::capnp::ToDynamic_;
template <typename, ::capnp::Kind>
friend struct ::capnp::_::PointerHelpers;
template <typename, ::capnp::Kind>
friend struct ::capnp::List;
friend class ::capnp::MessageBuilder;
friend class ::capnp::Orphanage;
};
class ProvisionId::Builder {
public:
typedef ProvisionId Builds;
Builder() = delete; // Deleted to discourage incorrect usage.
// You can explicitly initialize to nullptr instead.
inline Builder(decltype(nullptr)) {}
inline explicit Builder(::capnp::_::StructBuilder base): _builder(base) {}
inline operator Reader() const { return Reader(_builder.asReader()); }
inline Reader asReader() const { return *this; }
inline ::capnp::MessageSize totalSize() const { return asReader().totalSize(); }
#if !CAPNP_LITE
inline ::kj::StringTree toString() const { return asReader().toString(); }
#endif // !CAPNP_LITE
inline ::uint32_t getJoinId();
inline void setJoinId( ::uint32_t value);
private:
::capnp::_::StructBuilder _builder;
template <typename, ::capnp::Kind>
friend struct ::capnp::ToDynamic_;
friend class ::capnp::Orphanage;
template <typename, ::capnp::Kind>
friend struct ::capnp::_::PointerHelpers;
};
#if !CAPNP_LITE
class ProvisionId::Pipeline {
public:
typedef ProvisionId Pipelines;
inline Pipeline(decltype(nullptr)): _typeless(nullptr) {}
inline explicit Pipeline(::capnp::AnyPointer::Pipeline&& typeless)
: _typeless(kj::mv(typeless)) {}
private:
::capnp::AnyPointer::Pipeline _typeless;
friend class ::capnp::PipelineHook;
template <typename, ::capnp::Kind>
friend struct ::capnp::ToDynamic_;
};
#endif // !CAPNP_LITE
class RecipientId::Reader {
public:
typedef RecipientId Reads;
Reader() = default;
inline explicit Reader(::capnp::_::StructReader base): _reader(base) {}
inline ::capnp::MessageSize totalSize() const {
return _reader.totalSize().asPublic();
}
#if !CAPNP_LITE
inline ::kj::StringTree toString() const {
return ::capnp::_::structString(_reader, *_capnpPrivate::brand());
}
#endif // !CAPNP_LITE
private:
::capnp::_::StructReader _reader;
template <typename, ::capnp::Kind>
friend struct ::capnp::ToDynamic_;
template <typename, ::capnp::Kind>
friend struct ::capnp::_::PointerHelpers;
template <typename, ::capnp::Kind>
friend struct ::capnp::List;
friend class ::capnp::MessageBuilder;
friend class ::capnp::Orphanage;
};
class RecipientId::Builder {
public:
typedef RecipientId Builds;
Builder() = delete; // Deleted to discourage incorrect usage.
// You can explicitly initialize to nullptr instead.
inline Builder(decltype(nullptr)) {}
inline explicit Builder(::capnp::_::StructBuilder base): _builder(base) {}
inline operator Reader() const { return Reader(_builder.asReader()); }
inline Reader asReader() const { return *this; }
inline ::capnp::MessageSize totalSize() const { return asReader().totalSize(); }
#if !CAPNP_LITE
inline ::kj::StringTree toString() const { return asReader().toString(); }
#endif // !CAPNP_LITE
private:
::capnp::_::StructBuilder _builder;
template <typename, ::capnp::Kind>
friend struct ::capnp::ToDynamic_;
friend class ::capnp::Orphanage;
template <typename, ::capnp::Kind>
friend struct ::capnp::_::PointerHelpers;
};
#if !CAPNP_LITE
class RecipientId::Pipeline {
public:
typedef RecipientId Pipelines;
inline Pipeline(decltype(nullptr)): _typeless(nullptr) {}
inline explicit Pipeline(::capnp::AnyPointer::Pipeline&& typeless)
: _typeless(kj::mv(typeless)) {}
private:
::capnp::AnyPointer::Pipeline _typeless;
friend class ::capnp::PipelineHook;
template <typename, ::capnp::Kind>
friend struct ::capnp::ToDynamic_;
};
#endif // !CAPNP_LITE
class ThirdPartyCapId::Reader {
public:
typedef ThirdPartyCapId Reads;
Reader() = default;
inline explicit Reader(::capnp::_::StructReader base): _reader(base) {}
inline ::capnp::MessageSize totalSize() const {
return _reader.totalSize().asPublic();
}
#if !CAPNP_LITE
inline ::kj::StringTree toString() const {
return ::capnp::_::structString(_reader, *_capnpPrivate::brand());
}
#endif // !CAPNP_LITE
private:
::capnp::_::StructReader _reader;
template <typename, ::capnp::Kind>
friend struct ::capnp::ToDynamic_;
template <typename, ::capnp::Kind>
friend struct ::capnp::_::PointerHelpers;
template <typename, ::capnp::Kind>
friend struct ::capnp::List;
friend class ::capnp::MessageBuilder;
friend class ::capnp::Orphanage;
};
class ThirdPartyCapId::Builder {
public:
typedef ThirdPartyCapId Builds;
Builder() = delete; // Deleted to discourage incorrect usage.
// You can explicitly initialize to nullptr instead.
inline Builder(decltype(nullptr)) {}
inline explicit Builder(::capnp::_::StructBuilder base): _builder(base) {}
inline operator Reader() const { return Reader(_builder.asReader()); }
inline Reader asReader() const { return *this; }
inline ::capnp::MessageSize totalSize() const { return asReader().totalSize(); }
#if !CAPNP_LITE
inline ::kj::StringTree toString() const { return asReader().toString(); }
#endif // !CAPNP_LITE
private:
::capnp::_::StructBuilder _builder;
template <typename, ::capnp::Kind>
friend struct ::capnp::ToDynamic_;
friend class ::capnp::Orphanage;
template <typename, ::capnp::Kind>
friend struct ::capnp::_::PointerHelpers;
};
#if !CAPNP_LITE
class ThirdPartyCapId::Pipeline {
public:
typedef ThirdPartyCapId Pipelines;
inline Pipeline(decltype(nullptr)): _typeless(nullptr) {}
inline explicit Pipeline(::capnp::AnyPointer::Pipeline&& typeless)
: _typeless(kj::mv(typeless)) {}
private:
::capnp::AnyPointer::Pipeline _typeless;
friend class ::capnp::PipelineHook;
template <typename, ::capnp::Kind>
friend struct ::capnp::ToDynamic_;
};
#endif // !CAPNP_LITE
class JoinKeyPart::Reader {
public:
typedef JoinKeyPart Reads;
Reader() = default;
inline explicit Reader(::capnp::_::StructReader base): _reader(base) {}
inline ::capnp::MessageSize totalSize() const {
return _reader.totalSize().asPublic();
}
#if !CAPNP_LITE
inline ::kj::StringTree toString() const {
return ::capnp::_::structString(_reader, *_capnpPrivate::brand());
}
#endif // !CAPNP_LITE
inline ::uint32_t getJoinId() const;
inline ::uint16_t getPartCount() const;
inline ::uint16_t getPartNum() const;
private:
::capnp::_::StructReader _reader;
template <typename, ::capnp::Kind>
friend struct ::capnp::ToDynamic_;
template <typename, ::capnp::Kind>
friend struct ::capnp::_::PointerHelpers;
template <typename, ::capnp::Kind>
friend struct ::capnp::List;
friend class ::capnp::MessageBuilder;
friend class ::capnp::Orphanage;
};
class JoinKeyPart::Builder {
public:
typedef JoinKeyPart Builds;
Builder() = delete; // Deleted to discourage incorrect usage.
// You can explicitly initialize to nullptr instead.
inline Builder(decltype(nullptr)) {}
inline explicit Builder(::capnp::_::StructBuilder base): _builder(base) {}
inline operator Reader() const { return Reader(_builder.asReader()); }
inline Reader asReader() const { return *this; }
inline ::capnp::MessageSize totalSize() const { return asReader().totalSize(); }
#if !CAPNP_LITE
inline ::kj::StringTree toString() const { return asReader().toString(); }
#endif // !CAPNP_LITE
inline ::uint32_t getJoinId();
inline void setJoinId( ::uint32_t value);
inline ::uint16_t getPartCount();
inline void setPartCount( ::uint16_t value);
inline ::uint16_t getPartNum();
inline void setPartNum( ::uint16_t value);
private:
::capnp::_::StructBuilder _builder;
template <typename, ::capnp::Kind>
friend struct ::capnp::ToDynamic_;
friend class ::capnp::Orphanage;
template <typename, ::capnp::Kind>
friend struct ::capnp::_::PointerHelpers;
};
#if !CAPNP_LITE
class JoinKeyPart::Pipeline {
public:
typedef JoinKeyPart Pipelines;
inline Pipeline(decltype(nullptr)): _typeless(nullptr) {}
inline explicit Pipeline(::capnp::AnyPointer::Pipeline&& typeless)
: _typeless(kj::mv(typeless)) {}
private:
::capnp::AnyPointer::Pipeline _typeless;
friend class ::capnp::PipelineHook;
template <typename, ::capnp::Kind>
friend struct ::capnp::ToDynamic_;
};
#endif // !CAPNP_LITE
class JoinResult::Reader {
public:
typedef JoinResult Reads;
Reader() = default;
inline explicit Reader(::capnp::_::StructReader base): _reader(base) {}
inline ::capnp::MessageSize totalSize() const {
return _reader.totalSize().asPublic();
}
#if !CAPNP_LITE
inline ::kj::StringTree toString() const {
return ::capnp::_::structString(_reader, *_capnpPrivate::brand());
}
#endif // !CAPNP_LITE
inline ::uint32_t getJoinId() const;
inline bool getSucceeded() const;
inline bool hasCap() const;
inline ::capnp::AnyPointer::Reader getCap() const;
private:
::capnp::_::StructReader _reader;
template <typename, ::capnp::Kind>
friend struct ::capnp::ToDynamic_;
template <typename, ::capnp::Kind>
friend struct ::capnp::_::PointerHelpers;
template <typename, ::capnp::Kind>
friend struct ::capnp::List;
friend class ::capnp::MessageBuilder;
friend class ::capnp::Orphanage;
};
class JoinResult::Builder {
public:
typedef JoinResult Builds;
Builder() = delete; // Deleted to discourage incorrect usage.
// You can explicitly initialize to nullptr instead.
inline Builder(decltype(nullptr)) {}
inline explicit Builder(::capnp::_::StructBuilder base): _builder(base) {}
inline operator Reader() const { return Reader(_builder.asReader()); }
inline Reader asReader() const { return *this; }
inline ::capnp::MessageSize totalSize() const { return asReader().totalSize(); }
#if !CAPNP_LITE
inline ::kj::StringTree toString() const { return asReader().toString(); }
#endif // !CAPNP_LITE
inline ::uint32_t getJoinId();
inline void setJoinId( ::uint32_t value);
inline bool getSucceeded();
inline void setSucceeded(bool value);
inline bool hasCap();
inline ::capnp::AnyPointer::Builder getCap();
inline ::capnp::AnyPointer::Builder initCap();
private:
::capnp::_::StructBuilder _builder;
template <typename, ::capnp::Kind>
friend struct ::capnp::ToDynamic_;
friend class ::capnp::Orphanage;
template <typename, ::capnp::Kind>
friend struct ::capnp::_::PointerHelpers;
};
#if !CAPNP_LITE
class JoinResult::Pipeline {
public:
typedef JoinResult Pipelines;
inline Pipeline(decltype(nullptr)): _typeless(nullptr) {}
inline explicit Pipeline(::capnp::AnyPointer::Pipeline&& typeless)
: _typeless(kj::mv(typeless)) {}
private:
::capnp::AnyPointer::Pipeline _typeless;
friend class ::capnp::PipelineHook;
template <typename, ::capnp::Kind>
friend struct ::capnp::ToDynamic_;
};
#endif // !CAPNP_LITE
// =======================================================================================
inline ::capnp::rpc::twoparty::Side VatId::Reader::getSide() const {
return _reader.getDataField< ::capnp::rpc::twoparty::Side>(
::capnp::bounded<0>() * ::capnp::ELEMENTS);
}
inline ::capnp::rpc::twoparty::Side VatId::Builder::getSide() {
return _builder.getDataField< ::capnp::rpc::twoparty::Side>(
::capnp::bounded<0>() * ::capnp::ELEMENTS);
}
inline void VatId::Builder::setSide( ::capnp::rpc::twoparty::Side value) {
_builder.setDataField< ::capnp::rpc::twoparty::Side>(
::capnp::bounded<0>() * ::capnp::ELEMENTS, value);
}
inline ::uint32_t ProvisionId::Reader::getJoinId() const {
return _reader.getDataField< ::uint32_t>(
::capnp::bounded<0>() * ::capnp::ELEMENTS);
}
inline ::uint32_t ProvisionId::Builder::getJoinId() {
return _builder.getDataField< ::uint32_t>(
::capnp::bounded<0>() * ::capnp::ELEMENTS);
}
inline void ProvisionId::Builder::setJoinId( ::uint32_t value) {
_builder.setDataField< ::uint32_t>(
::capnp::bounded<0>() * ::capnp::ELEMENTS, value);
}
inline ::uint32_t JoinKeyPart::Reader::getJoinId() const {
return _reader.getDataField< ::uint32_t>(
::capnp::bounded<0>() * ::capnp::ELEMENTS);
}
inline ::uint32_t JoinKeyPart::Builder::getJoinId() {
return _builder.getDataField< ::uint32_t>(
::capnp::bounded<0>() * ::capnp::ELEMENTS);
}
inline void JoinKeyPart::Builder::setJoinId( ::uint32_t value) {
_builder.setDataField< ::uint32_t>(
::capnp::bounded<0>() * ::capnp::ELEMENTS, value);
}
inline ::uint16_t JoinKeyPart::Reader::getPartCount() const {
return _reader.getDataField< ::uint16_t>(
::capnp::bounded<2>() * ::capnp::ELEMENTS);
}
inline ::uint16_t JoinKeyPart::Builder::getPartCount() {
return _builder.getDataField< ::uint16_t>(
::capnp::bounded<2>() * ::capnp::ELEMENTS);
}
inline void JoinKeyPart::Builder::setPartCount( ::uint16_t value) {
_builder.setDataField< ::uint16_t>(
::capnp::bounded<2>() * ::capnp::ELEMENTS, value);
}
inline ::uint16_t JoinKeyPart::Reader::getPartNum() const {
return _reader.getDataField< ::uint16_t>(
::capnp::bounded<3>() * ::capnp::ELEMENTS);
}
inline ::uint16_t JoinKeyPart::Builder::getPartNum() {
return _builder.getDataField< ::uint16_t>(
::capnp::bounded<3>() * ::capnp::ELEMENTS);
}
inline void JoinKeyPart::Builder::setPartNum( ::uint16_t value) {
_builder.setDataField< ::uint16_t>(
::capnp::bounded<3>() * ::capnp::ELEMENTS, value);
}
inline ::uint32_t JoinResult::Reader::getJoinId() const {
return _reader.getDataField< ::uint32_t>(
::capnp::bounded<0>() * ::capnp::ELEMENTS);
}
inline ::uint32_t JoinResult::Builder::getJoinId() {
return _builder.getDataField< ::uint32_t>(
::capnp::bounded<0>() * ::capnp::ELEMENTS);
}
inline void JoinResult::Builder::setJoinId( ::uint32_t value) {
_builder.setDataField< ::uint32_t>(
::capnp::bounded<0>() * ::capnp::ELEMENTS, value);
}
inline bool JoinResult::Reader::getSucceeded() const {
return _reader.getDataField<bool>(
::capnp::bounded<32>() * ::capnp::ELEMENTS);
}
inline bool JoinResult::Builder::getSucceeded() {
return _builder.getDataField<bool>(
::capnp::bounded<32>() * ::capnp::ELEMENTS);
}
inline void JoinResult::Builder::setSucceeded(bool value) {
_builder.setDataField<bool>(
::capnp::bounded<32>() * ::capnp::ELEMENTS, value);
}
inline bool JoinResult::Reader::hasCap() const {
return !_reader.getPointerField(
::capnp::bounded<0>() * ::capnp::POINTERS).isNull();
}
inline bool JoinResult::Builder::hasCap() {
return !_builder.getPointerField(
::capnp::bounded<0>() * ::capnp::POINTERS).isNull();
}
inline ::capnp::AnyPointer::Reader JoinResult::Reader::getCap() const {
return ::capnp::AnyPointer::Reader(_reader.getPointerField(
::capnp::bounded<0>() * ::capnp::POINTERS));
}
inline ::capnp::AnyPointer::Builder JoinResult::Builder::getCap() {
return ::capnp::AnyPointer::Builder(_builder.getPointerField(
::capnp::bounded<0>() * ::capnp::POINTERS));
}
inline ::capnp::AnyPointer::Builder JoinResult::Builder::initCap() {
auto result = ::capnp::AnyPointer::Builder(_builder.getPointerField(
::capnp::bounded<0>() * ::capnp::POINTERS));
result.clear();
return result;
}
} // namespace
} // namespace
} // namespace
#endif // CAPNP_INCLUDED_a184c7885cdaf2a1_
| {
"content_hash": "df3b91f3e1251e58b9bfb1ea445dad61",
"timestamp": "",
"source": "github",
"line_count": 713,
"max_line_length": 98,
"avg_line_length": 29.23702664796634,
"alnum_prop": 0.6751415139595126,
"repo_name": "apavlo/peloton",
"id": "9d7820646a75ec5afa25aeabeda791256cb340bf",
"size": "21232",
"binary": false,
"copies": "9",
"ref": "refs/heads/master",
"path": "third_party/capnproto/c++/src/capnp/rpc-twoparty.capnp.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "47425"
},
{
"name": "C++",
"bytes": "7112442"
},
{
"name": "CMake",
"bytes": "136686"
},
{
"name": "Cap'n Proto",
"bytes": "362"
},
{
"name": "Java",
"bytes": "76998"
},
{
"name": "PLpgSQL",
"bytes": "5855"
},
{
"name": "Python",
"bytes": "108672"
},
{
"name": "Ruby",
"bytes": "1278"
},
{
"name": "Shell",
"bytes": "25157"
}
],
"symlink_target": ""
} |
/*
* This code was generated by
* ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __
* | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/
* | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \
*
* Twilio - Media
* This is the public Twilio REST API.
*
* NOTE: This class is auto generated by OpenAPI Generator.
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package openapi
import (
"encoding/json"
"fmt"
"net/url"
"strings"
"github.com/twilio/twilio-go/client"
)
// Optional parameters for the method 'CreatePlayerStreamer'
type CreatePlayerStreamerParams struct {
// Specifies whether the PlayerStreamer is configured to stream video. Defaults to `true`.
Video *bool `json:"Video,omitempty"`
// The URL to which Twilio will send asynchronous webhook requests for every PlayerStreamer event. See [Status Callbacks](/docs/live/status-callbacks) for more details.
StatusCallback *string `json:"StatusCallback,omitempty"`
// The HTTP method Twilio should use to call the `status_callback` URL. Can be `POST` or `GET` and the default is `POST`.
StatusCallbackMethod *string `json:"StatusCallbackMethod,omitempty"`
// The maximum time, in seconds, that the PlayerStreamer is active (`created` or `started`) before automatically ends. The default value is 300 seconds, and the maximum value is 90000 seconds. Once this maximum duration is reached, Twilio will end the PlayerStreamer, regardless of whether media is still streaming.
MaxDuration *int `json:"MaxDuration,omitempty"`
}
func (params *CreatePlayerStreamerParams) SetVideo(Video bool) *CreatePlayerStreamerParams {
params.Video = &Video
return params
}
func (params *CreatePlayerStreamerParams) SetStatusCallback(StatusCallback string) *CreatePlayerStreamerParams {
params.StatusCallback = &StatusCallback
return params
}
func (params *CreatePlayerStreamerParams) SetStatusCallbackMethod(StatusCallbackMethod string) *CreatePlayerStreamerParams {
params.StatusCallbackMethod = &StatusCallbackMethod
return params
}
func (params *CreatePlayerStreamerParams) SetMaxDuration(MaxDuration int) *CreatePlayerStreamerParams {
params.MaxDuration = &MaxDuration
return params
}
//
func (c *ApiService) CreatePlayerStreamer(params *CreatePlayerStreamerParams) (*MediaV1PlayerStreamer, error) {
path := "/v1/PlayerStreamers"
data := url.Values{}
headers := make(map[string]interface{})
if params != nil && params.Video != nil {
data.Set("Video", fmt.Sprint(*params.Video))
}
if params != nil && params.StatusCallback != nil {
data.Set("StatusCallback", *params.StatusCallback)
}
if params != nil && params.StatusCallbackMethod != nil {
data.Set("StatusCallbackMethod", *params.StatusCallbackMethod)
}
if params != nil && params.MaxDuration != nil {
data.Set("MaxDuration", fmt.Sprint(*params.MaxDuration))
}
resp, err := c.requestHandler.Post(c.baseURL+path, data, headers)
if err != nil {
return nil, err
}
defer resp.Body.Close()
ps := &MediaV1PlayerStreamer{}
if err := json.NewDecoder(resp.Body).Decode(ps); err != nil {
return nil, err
}
return ps, err
}
// Returns a single PlayerStreamer resource identified by a SID.
func (c *ApiService) FetchPlayerStreamer(Sid string) (*MediaV1PlayerStreamer, error) {
path := "/v1/PlayerStreamers/{Sid}"
path = strings.Replace(path, "{"+"Sid"+"}", Sid, -1)
data := url.Values{}
headers := make(map[string]interface{})
resp, err := c.requestHandler.Get(c.baseURL+path, data, headers)
if err != nil {
return nil, err
}
defer resp.Body.Close()
ps := &MediaV1PlayerStreamer{}
if err := json.NewDecoder(resp.Body).Decode(ps); err != nil {
return nil, err
}
return ps, err
}
// Optional parameters for the method 'ListPlayerStreamer'
type ListPlayerStreamerParams struct {
// The sort order of the list by `date_created`. Can be: `asc` (ascending) or `desc` (descending) with `desc` as the default.
Order *string `json:"Order,omitempty"`
// Status to filter by, with possible values `created`, `started`, `ended`, or `failed`.
Status *string `json:"Status,omitempty"`
// How many resources to return in each list page. The default is 50, and the maximum is 1000.
PageSize *int `json:"PageSize,omitempty"`
// Max number of records to return.
Limit *int `json:"limit,omitempty"`
}
func (params *ListPlayerStreamerParams) SetOrder(Order string) *ListPlayerStreamerParams {
params.Order = &Order
return params
}
func (params *ListPlayerStreamerParams) SetStatus(Status string) *ListPlayerStreamerParams {
params.Status = &Status
return params
}
func (params *ListPlayerStreamerParams) SetPageSize(PageSize int) *ListPlayerStreamerParams {
params.PageSize = &PageSize
return params
}
func (params *ListPlayerStreamerParams) SetLimit(Limit int) *ListPlayerStreamerParams {
params.Limit = &Limit
return params
}
// Retrieve a single page of PlayerStreamer records from the API. Request is executed immediately.
func (c *ApiService) PagePlayerStreamer(params *ListPlayerStreamerParams, pageToken, pageNumber string) (*ListPlayerStreamerResponse, error) {
path := "/v1/PlayerStreamers"
data := url.Values{}
headers := make(map[string]interface{})
if params != nil && params.Order != nil {
data.Set("Order", *params.Order)
}
if params != nil && params.Status != nil {
data.Set("Status", *params.Status)
}
if params != nil && params.PageSize != nil {
data.Set("PageSize", fmt.Sprint(*params.PageSize))
}
if pageToken != "" {
data.Set("PageToken", pageToken)
}
if pageNumber != "" {
data.Set("Page", pageNumber)
}
resp, err := c.requestHandler.Get(c.baseURL+path, data, headers)
if err != nil {
return nil, err
}
defer resp.Body.Close()
ps := &ListPlayerStreamerResponse{}
if err := json.NewDecoder(resp.Body).Decode(ps); err != nil {
return nil, err
}
return ps, err
}
// Lists PlayerStreamer records from the API as a list. Unlike stream, this operation is eager and loads 'limit' records into memory before returning.
func (c *ApiService) ListPlayerStreamer(params *ListPlayerStreamerParams) ([]MediaV1PlayerStreamer, error) {
response, errors := c.StreamPlayerStreamer(params)
records := make([]MediaV1PlayerStreamer, 0)
for record := range response {
records = append(records, record)
}
if err := <-errors; err != nil {
return nil, err
}
return records, nil
}
// Streams PlayerStreamer records from the API as a channel stream. This operation lazily loads records as efficiently as possible until the limit is reached.
func (c *ApiService) StreamPlayerStreamer(params *ListPlayerStreamerParams) (chan MediaV1PlayerStreamer, chan error) {
if params == nil {
params = &ListPlayerStreamerParams{}
}
params.SetPageSize(client.ReadLimits(params.PageSize, params.Limit))
recordChannel := make(chan MediaV1PlayerStreamer, 1)
errorChannel := make(chan error, 1)
response, err := c.PagePlayerStreamer(params, "", "")
if err != nil {
errorChannel <- err
close(recordChannel)
close(errorChannel)
} else {
go c.streamPlayerStreamer(response, params, recordChannel, errorChannel)
}
return recordChannel, errorChannel
}
func (c *ApiService) streamPlayerStreamer(response *ListPlayerStreamerResponse, params *ListPlayerStreamerParams, recordChannel chan MediaV1PlayerStreamer, errorChannel chan error) {
curRecord := 1
for response != nil {
responseRecords := response.PlayerStreamers
for item := range responseRecords {
recordChannel <- responseRecords[item]
curRecord += 1
if params.Limit != nil && *params.Limit < curRecord {
close(recordChannel)
close(errorChannel)
return
}
}
record, err := client.GetNext(c.baseURL, response, c.getNextListPlayerStreamerResponse)
if err != nil {
errorChannel <- err
break
} else if record == nil {
break
}
response = record.(*ListPlayerStreamerResponse)
}
close(recordChannel)
close(errorChannel)
}
func (c *ApiService) getNextListPlayerStreamerResponse(nextPageUrl string) (interface{}, error) {
if nextPageUrl == "" {
return nil, nil
}
resp, err := c.requestHandler.Get(nextPageUrl, nil, nil)
if err != nil {
return nil, err
}
defer resp.Body.Close()
ps := &ListPlayerStreamerResponse{}
if err := json.NewDecoder(resp.Body).Decode(ps); err != nil {
return nil, err
}
return ps, nil
}
// Optional parameters for the method 'UpdatePlayerStreamer'
type UpdatePlayerStreamerParams struct {
//
Status *string `json:"Status,omitempty"`
}
func (params *UpdatePlayerStreamerParams) SetStatus(Status string) *UpdatePlayerStreamerParams {
params.Status = &Status
return params
}
// Updates a PlayerStreamer resource identified by a SID.
func (c *ApiService) UpdatePlayerStreamer(Sid string, params *UpdatePlayerStreamerParams) (*MediaV1PlayerStreamer, error) {
path := "/v1/PlayerStreamers/{Sid}"
path = strings.Replace(path, "{"+"Sid"+"}", Sid, -1)
data := url.Values{}
headers := make(map[string]interface{})
if params != nil && params.Status != nil {
data.Set("Status", *params.Status)
}
resp, err := c.requestHandler.Post(c.baseURL+path, data, headers)
if err != nil {
return nil, err
}
defer resp.Body.Close()
ps := &MediaV1PlayerStreamer{}
if err := json.NewDecoder(resp.Body).Decode(ps); err != nil {
return nil, err
}
return ps, err
}
| {
"content_hash": "bca6b1c9d608b2eb5aa7226103c30582",
"timestamp": "",
"source": "github",
"line_count": 303,
"max_line_length": 316,
"avg_line_length": 30.90759075907591,
"alnum_prop": 0.7107314468766684,
"repo_name": "twilio/twilio-go",
"id": "ca3ea77810f57b81763d56617eec65378cd52265",
"size": "9365",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "rest/media/v1/player_streamers.go",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Dockerfile",
"bytes": "200"
},
{
"name": "Go",
"bytes": "4840470"
},
{
"name": "Makefile",
"bytes": "1414"
}
],
"symlink_target": ""
} |
package be.peopleware.servlet.sessionMopup;
import java.io.Serializable;
/**
* <p>Objects of this type have data that should be cleared at certain times
* or under certain conditions (the fat should be skimmed of them). At
* certain times, {@link #skim()} will be called on objects of this type.
* The implementation of this method then decides if skimming is appropriate
* at this time, given the state of <code>this</code>instance, what should
* be skimmed, and what <def>skimming</def> entails in these circumstances.
* Potentially, the implementation can cascade the skimming request to related
* objects.</p>
* <p>The {@link MopupListener} applies this to all variables in
* session scope of a web application at the end of a HTTP request.</p>
* <p>If an instance of this type is also {@link Serializable} it is good
* practice to surely skim transient fields.</p>
*
* @author Jan Dockx
* @author PeopleWare n.v.
*/
public interface Skimmable {
/*<section name="Meta Information">*/
//------------------------------------------------------------------
/** {@value} */
public static final String CVS_REVISION = "$Revision$"; //$NON-NLS-1$
/** {@value} */
public static final String CVS_DATE = "$Date$"; //$NON-NLS-1$
/** {@value} */
public static final String CVS_STATE = "$State$"; //$NON-NLS-1$
/** {@value} */
public static final String CVS_TAG = "$Name$"; //$NON-NLS-1$
/*</section>*/
/**
* Skim unneeded data from this instance, if applicable at this time.
*/
void skim();
}
| {
"content_hash": "13f82598323306f4d756b6395ae649de",
"timestamp": "",
"source": "github",
"line_count": 50,
"max_line_length": 80,
"avg_line_length": 31.28,
"alnum_prop": 0.6432225063938619,
"repo_name": "jandppw/ppwcode-recovered-from-google-code",
"id": "09013f7412081ad79c10d3f0d52af0e9510c8713",
"size": "1724",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "_purgatory/java/jsf/branches/goBack/src/java/be/peopleware/servlet/sessionMopup/Skimmable.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ASP",
"bytes": "34295"
},
{
"name": "ApacheConf",
"bytes": "113"
},
{
"name": "Batchfile",
"bytes": "57455"
},
{
"name": "C#",
"bytes": "10765997"
},
{
"name": "CSS",
"bytes": "288454"
},
{
"name": "HTML",
"bytes": "6091904"
},
{
"name": "Java",
"bytes": "60750969"
},
{
"name": "JavaScript",
"bytes": "7433515"
},
{
"name": "PLSQL",
"bytes": "4017"
},
{
"name": "PLpgSQL",
"bytes": "113949"
},
{
"name": "PowerShell",
"bytes": "2678"
},
{
"name": "Ruby",
"bytes": "6809"
},
{
"name": "SQLPL",
"bytes": "157809"
},
{
"name": "Shell",
"bytes": "795"
},
{
"name": "Visual Basic",
"bytes": "30834"
},
{
"name": "XSLT",
"bytes": "10691"
}
],
"symlink_target": ""
} |
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
using HtmlHelp;
namespace HtmlHelp.UIComponents
{
/// <summary>
/// The class <c>TocTree</c> implements a user control which displays the HtmlHelp table of contents pane to the user.
/// </summary>
public class TocTree : System.Windows.Forms.UserControl
{
/// <summary>
/// Event if the user changes the selection in the toc tree
/// </summary>
public event TocSelectedEventHandler TocSelected;
private System.Windows.Forms.TreeView tocTreeView;
private System.Windows.Forms.ImageList hhImages;
private System.ComponentModel.IContainer components;
/// <summary>
/// Constructor of the class
/// </summary>
public TocTree()
{
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
ReloadImageList();
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.tocTreeView = new System.Windows.Forms.TreeView();
this.hhImages = new System.Windows.Forms.ImageList(this.components);
this.SuspendLayout();
//
// tocTreeView
//
this.tocTreeView.Dock = System.Windows.Forms.DockStyle.Fill;
this.tocTreeView.HideSelection = false;
this.tocTreeView.ImageList = this.hhImages;
this.tocTreeView.Location = new System.Drawing.Point(2, 2);
this.tocTreeView.Name = "tocTreeView";
this.tocTreeView.Size = new System.Drawing.Size(228, 252);
this.tocTreeView.TabIndex = 0;
this.tocTreeView.AfterExpand += new System.Windows.Forms.TreeViewEventHandler(this.tocTreeView_AfterExpand);
this.tocTreeView.AfterCollapse += new System.Windows.Forms.TreeViewEventHandler(this.tocTreeView_AfterCollapse);
this.tocTreeView.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.tocTreeView_AfterSelect);
//
// hhImages
//
this.hhImages.ColorDepth = System.Windows.Forms.ColorDepth.Depth24Bit;
this.hhImages.ImageSize = new System.Drawing.Size(16, 16);
this.hhImages.TransparentColor = System.Drawing.Color.FromArgb(((System.Byte)(128)), ((System.Byte)(64)), ((System.Byte)(0)));
//
// TocTree
//
this.Controls.Add(this.tocTreeView);
this.DockPadding.All = 2;
this.Name = "TocTree";
this.Size = new System.Drawing.Size(232, 256);
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// Fireing the on selected event
/// </summary>
/// <param name="e">event parameters</param>
protected virtual void OnTocSelected(TocEventArgs e)
{
if(TocSelected != null)
{
TocSelected(this,e);
}
}
/// <summary>
/// Reloads the imagelist using the HtmlHelpSystem.UseHH2TreePics preference
/// </summary>
public void ReloadImageList()
{
ResourceHelper resHelper = new ResourceHelper( this.GetType().Assembly );
resHelper.DefaultBitmapNamespace = "Resources";
if(hhImages.Images.Count > 0)
{
hhImages.Images.Clear();
}
hhImages.ColorDepth = System.Windows.Forms.ColorDepth.Depth24Bit;
if(HtmlHelpSystem.UseHH2TreePics)
{
hhImages.TransparentColor = System.Drawing.Color.FromArgb(((System.Byte)(128)), ((System.Byte)(64)), ((System.Byte)(0)));
hhImages.Images.AddStrip(resHelper.LoadBitmap("ContentTree.bmp"));
}
else
{
hhImages.TransparentColor = Color.Fuchsia;
hhImages.Images.AddStrip(resHelper.LoadBitmap("HH11.bmp"));
}
}
/// <summary>
/// Clears the items displayed in the toc pane
/// </summary>
public void ClearContents()
{
tocTreeView.Nodes.Clear();
}
/// <summary>
/// Call this method to build the table of contents (TOC) tree.
/// </summary>
/// <param name="tocItems">TOC instance (tree) extracted from the chm file</param>
public void BuildTOC(TableOfContents tocItems)
{
BuildTOC(tocItems, null);
}
/// <summary>
/// Call this method to build the table of contents (TOC) tree.
/// </summary>
/// <param name="tocItems">TOC instance (tree) extracted from the chm file</param>
/// <param name="filter">information type/category filter</param>
public void BuildTOC(TableOfContents tocItems, InfoTypeCategoryFilter filter)
{
tocTreeView.Nodes.Clear();
BuildTOC(tocItems.TOC, tocTreeView.Nodes, filter);
tocTreeView.Update();
}
/// <summary>
/// Snychronizes the table of content tree with the currently displayed browser url.
/// </summary>
/// <param name="URL">url to search</param>
public void Synchronize(string URL)
{
string local = URL;
string sFile = "";
if( URL.StartsWith(HtmlHelpSystem.UrlPrefix) )
{
local = local.Substring(HtmlHelpSystem.UrlPrefix.Length);
}
if( local.IndexOf("::")>-1)
{
sFile = local.Substring(0, local.IndexOf("::"));
local = local.Substring( local.IndexOf("::")+2 );
}
SelectTOCItem(tocTreeView.Nodes, sFile, local);
}
/// <summary>
/// Called if the user has expanded a tree item
/// </summary>
/// <param name="sender">event sender</param>
/// <param name="e">event parameter</param>
private void tocTreeView_AfterExpand(object sender, System.Windows.Forms.TreeViewEventArgs e)
{
TOCItem curItem = (TOCItem)(e.Node.Tag);
if(curItem != null)
{
if(HtmlHelpSystem.UseHH2TreePics)
{
if(curItem.ImageIndex <= 15)
{
e.Node.ImageIndex = curItem.ImageIndex+2;
e.Node.SelectedImageIndex = curItem.ImageIndex+2;
}
}
else
{
if(curItem.ImageIndex < 8)
{
e.Node.ImageIndex = curItem.ImageIndex+1;
e.Node.SelectedImageIndex = curItem.ImageIndex+1;
}
}
}
}
/// <summary>
/// Called if the user has collapsed a tree item
/// </summary>
/// <param name="sender">event sender</param>
/// <param name="e">event parameter</param>
private void tocTreeView_AfterCollapse(object sender, System.Windows.Forms.TreeViewEventArgs e)
{
TOCItem curItem = (TOCItem)(e.Node.Tag);
if(curItem != null)
{
if(HtmlHelpSystem.UseHH2TreePics)
{
if(curItem.ImageIndex <= 15)
{
e.Node.ImageIndex = curItem.ImageIndex;
e.Node.SelectedImageIndex = curItem.ImageIndex;
}
}
else
{
if(curItem.ImageIndex < 8)
{
e.Node.ImageIndex = curItem.ImageIndex;
e.Node.SelectedImageIndex = curItem.ImageIndex;
}
}
}
}
/// <summary>
/// Called if the user selects a tree item.
/// This method will fire the <c>TocSelected</c> event notifying the parent window, that the user whants
/// to view a new help topic.
/// </summary>
/// <param name="sender">event sender</param>
/// <param name="e">event parameter</param>
private void tocTreeView_AfterSelect(object sender, System.Windows.Forms.TreeViewEventArgs e)
{
OnTocSelected( new TocEventArgs((TOCItem)(e.Node.Tag)) );
}
/// <summary>
/// Selects a node identified by its chm file and local
/// </summary>
/// <param name="col">treenode collection to search</param>
/// <param name="chmFile">chm filename</param>
/// <param name="local">local of the toc item</param>
private void SelectTOCItem(TreeNodeCollection col, string chmFile, string local)
{
foreach(TreeNode curNode in col)
{
TOCItem curItem = curNode.Tag as TOCItem;
if(curItem!=null)
{
if((curItem.Local == local)||(("/"+curItem.Local) == local))
{
if(chmFile.Length>0)
{
if(curItem.AssociatedFile.ChmFilePath == chmFile)
{
tocTreeView.SelectedNode = curNode;
return;
}
}
else
{
tocTreeView.SelectedNode = curNode;
return;
}
}
}
SelectTOCItem(curNode.Nodes, chmFile, local);
}
}
/// <summary>
/// Recursively builds the toc tree and fills the treeview
/// </summary>
/// <param name="tocItems">list of toc-items</param>
/// <param name="col">treenode collection of the current level</param>
/// <param name="filter">information type/category filter</param>
private void BuildTOC(ArrayList tocItems, TreeNodeCollection col, InfoTypeCategoryFilter filter)
{
foreach( TOCItem curItem in tocItems )
{
bool bAdd = true;
if(filter!=null)
{
bAdd=false;
if(curItem.InfoTypeStrings.Count <= 0)
{
bAdd=true;
}
else
{
for(int i=0;i<curItem.InfoTypeStrings.Count;i++)
{
bAdd |= filter.Match( curItem.InfoTypeStrings[i].ToString() );
}
}
}
if(bAdd)
{
TreeNode newNode = new TreeNode( curItem.Name, curItem.ImageIndex, curItem.ImageIndex );
newNode.Tag = curItem;
if(curItem.Children.Count > 0)
{
BuildTOC(curItem.Children, newNode.Nodes, filter);
}
// check if we have a book/folder which doesn't have any children
// after applied filter.
if( (curItem.Children.Count > 0) && (newNode.Nodes.Count <= 0) )
{
// check if the item has a local value
// if not, this don't display this item in the tree
if( curItem.Local.Length > 0)
{
col.Add(newNode);
}
}
else
{
col.Add(newNode);
}
}
}
}
}
}
| {
"content_hash": "ac5ec76a26e9f5697fe3ca00e252a584",
"timestamp": "",
"source": "github",
"line_count": 350,
"max_line_length": 129,
"avg_line_length": 27.497142857142858,
"alnum_prop": 0.6562759767248545,
"repo_name": "ganry/Gamodo.Studio",
"id": "1e376206bb1f94d6b6a7c6a997f738938a8c80fd",
"size": "9624",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "Komponenten/HtmlHelp/Backup/HtmlHelp/UIComponents/TocTree.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "4510184"
},
{
"name": "CSS",
"bytes": "12564"
},
{
"name": "XSLT",
"bytes": "49384"
}
],
"symlink_target": ""
} |
@class RKOvalControl;
@protocol RKOvalControlDelegate <NSObject>
- (void)ovalControl:(RKOvalControl *)control didFailToSendProgramWithMessage:(NSString *)message;
- (void)ovalControlDidFinishSendingProgram:(RKOvalControl *)control;
- (void)ovalControlDidResetOvm:(RKOvalControl *)control;
- (void)ovalControl:(RKOvalControl *)control receivedOvalNotification:(RKOvalDeviceBroadcast *)notification;
- (void)ovalControl:(RKOvalControl *)control receivedVmRuntimeError:(RKOvalErrorBroadcast *)notification;
@end
@interface RKOvalControl : NSObject
@property (nonatomic) BOOL enableCompileReportOutput;
+ (instancetype)new NS_UNAVAILABLE;
+ (instancetype)controlWithRobot:(id<RKRobotBase>)robot delegate:(id<RKOvalControlDelegate>)delegate;
- (instancetype)init NS_UNAVAILABLE;
- (instancetype)initWithRobot:(id<RKRobotBase>)robot delegate:(id<RKOvalControlDelegate>)delegate;
- (void)resetOvmAndLibrary:(BOOL)resetLibrary;
- (void)sendOvalString:(NSString *)program;
- (void)sendOvalString:(NSString *)program allowQueue:(BOOL)allowsQueue;
- (void)sendOvalPrograms:(NSArray *)programs;
@end
| {
"content_hash": "bd2501b862e319d5fecf5ec87cdce71d",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 108,
"avg_line_length": 37.86206896551724,
"alnum_prop": 0.8114754098360656,
"repo_name": "danbalzerson/myo-sphero-ios",
"id": "b7a8637b0cad4b635a484fcca2c576f647487588",
"size": "1308",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "MyoSphero/Frameworks/RobotKit.framework/Frameworks/RobotLanguageKit.framework/Headers/RKOvalControl.h",
"mode": "33261",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "1313131"
},
{
"name": "C++",
"bytes": "2880"
},
{
"name": "Objective-C",
"bytes": "343839"
}
],
"symlink_target": ""
} |
/*******************************************************************************
* Product of NIST/ITL Advanced Networking Technologies Division (ANTD). *
*******************************************************************************/
package gov.nist.javax.sip.header;
import javax.sip.header.CallIdHeader;
import java.text.ParseException;
/**
* Call ID SIPHeader.
*
* @author M. Ranganathan <br/>
* @version 1.2 $Revision: 1.8 $ $Date: 2010-05-06 14:07:54 $
* @since 1.1
*/
public class CallID
extends SIPHeader
implements javax.sip.header.CallIdHeader {
/**
* Comment for <code>serialVersionUID</code>
*/
private static final long serialVersionUID = -6463630258703731156L;
/**
* callIdentifier field
*/
protected CallIdentifier callIdentifier;
/**
* Default constructor
*/
public CallID() {
super(NAME);
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*
* CallIDs are compared case-insensitively
*/
public boolean equals( Object other ) {
if (this==other) return true;
if (other instanceof CallIdHeader) {
final CallIdHeader o = (CallIdHeader) other;
return this.getCallId().equalsIgnoreCase( o.getCallId() );
}
return false;
}
/**
* Encode the body part of this header (i.e. leave out the hdrName).
*@return String encoded body part of the header.
*/
public String encodeBody() {
return encodeBody(new StringBuilder()).toString();
}
protected StringBuilder encodeBody(StringBuilder buffer) {
if (callIdentifier != null)
callIdentifier.encode(buffer);
return buffer;
}
/**
* get the CallId field. This does the same thing as
* encodeBody
* @return String the encoded body part of the
*/
public String getCallId() {
return encodeBody();
}
/**
* get the call Identifer member.
* @return CallIdentifier
*/
public CallIdentifier getCallIdentifer() {
return callIdentifier;
}
/**
* set the CallId field
* @param cid String to set. This is the body part of the Call-Id
* header. It must have the form localId@host or localId.
* @throws IllegalArgumentException if cid is null, not a token, or is
* not a token@token.
*/
public void setCallId(String cid) throws ParseException {
try {
callIdentifier = new CallIdentifier(cid);
} catch (IllegalArgumentException ex) {
throw new ParseException(cid, 0);
}
}
/**
* Set the callIdentifier member.
* @param cid CallIdentifier to set (localId@host).
*/
public void setCallIdentifier(CallIdentifier cid) {
callIdentifier = cid;
}
/** Constructor given the call Identifier.
*@param callId string call identifier (should be localid@host)
*@throws IllegalArgumentException if call identifier is bad.
*/
public CallID(String callId) throws IllegalArgumentException {
super(NAME);
this.callIdentifier = new CallIdentifier(callId);
}
public Object clone() {
CallID retval = (CallID) super.clone();
if (this.callIdentifier != null)
retval.callIdentifier = (CallIdentifier) this.callIdentifier.clone();
return retval;
}
}
| {
"content_hash": "27f7e0148d16bdc2dd6ca1334b5a0372",
"timestamp": "",
"source": "github",
"line_count": 123,
"max_line_length": 81,
"avg_line_length": 27.853658536585368,
"alnum_prop": 0.5931115002918855,
"repo_name": "fhg-fokus-nubomedia/signaling-plane",
"id": "0637a74ab5670a3b223a0e26fe845d93bdc94d49",
"size": "4486",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "modules/lib-sip/src/main/java/gov/nist/javax/sip/header/CallID.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "12152"
},
{
"name": "Groff",
"bytes": "22"
},
{
"name": "HTML",
"bytes": "2637100"
},
{
"name": "Java",
"bytes": "5622899"
},
{
"name": "JavaScript",
"bytes": "3448641"
},
{
"name": "Python",
"bytes": "161709"
},
{
"name": "Shell",
"bytes": "8658"
}
],
"symlink_target": ""
} |
<?php
namespace Symfony\Bundle\FrameworkBundle\Tests\Functional\Bundle\TestBundle\DependencyInjection;
use Symfony\Component\Config\Definition\ConfigurationInterface;
use Symfony\Component\DependencyInjection\Alias;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Extension\Extension;
use Symfony\Component\DependencyInjection\Extension\PrependExtensionInterface;
class TestExtension extends Extension implements PrependExtensionInterface
{
private $customConfig;
/**
* {@inheritdoc}
*/
public function load(array $configs, ContainerBuilder $container)
{
$configuration = $this->getConfiguration($configs, $container);
$config = $this->processConfiguration($configuration, $configs);
$container->setAlias('test.annotation_reader', new Alias('annotation_reader', true));
}
/**
* {@inheritdoc}
*/
public function prepend(ContainerBuilder $container)
{
$container->prependExtensionConfig('test', ['custom' => 'foo']);
}
/**
* {@inheritdoc}
*/
public function getConfiguration(array $config, ContainerBuilder $container): ?ConfigurationInterface
{
return new Configuration($this->customConfig);
}
public function setCustomConfig($customConfig)
{
$this->customConfig = $customConfig;
}
}
| {
"content_hash": "1c34263fee3b1294fbd69037f656ee2d",
"timestamp": "",
"source": "github",
"line_count": 48,
"max_line_length": 105,
"avg_line_length": 28.9375,
"alnum_prop": 0.7156227501799856,
"repo_name": "yceruto/symfony",
"id": "b9b22e90b41e585db3df36f23e6c42b2993f4484",
"size": "1618",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "src/Symfony/Bundle/FrameworkBundle/Tests/Functional/Bundle/TestBundle/DependencyInjection/TestExtension.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "18634"
},
{
"name": "HTML",
"bytes": "350576"
},
{
"name": "Hack",
"bytes": "26"
},
{
"name": "JavaScript",
"bytes": "28012"
},
{
"name": "PHP",
"bytes": "17680919"
},
{
"name": "Shell",
"bytes": "3136"
}
],
"symlink_target": ""
} |
package org.drools.workbench.services.verifier.api.client.index;
import org.drools.workbench.services.verifier.api.client.configuration.AnalyzerConfiguration;
import org.kie.soup.commons.validation.PortablePreconditions;
public class Field
extends FieldBase {
private final ObjectField objectField;
private final Conditions conditions = new Conditions();
private final Actions actions = new Actions();
public Field(final ObjectField objectField,
final String factType,
final String fieldType,
final String name,
final AnalyzerConfiguration configuration) {
super(factType,
fieldType,
name,
configuration);
this.objectField = PortablePreconditions.checkNotNull("objectField",
objectField);
}
public ObjectField getObjectField() {
return objectField;
}
public Conditions getConditions() {
return conditions;
}
public Actions getActions() {
return actions;
}
public void remove(final Column column) {
this.conditions.remove(column);
this.actions.remove(column);
}
}
| {
"content_hash": "fc830d74312bb468a2a94887a569fb43",
"timestamp": "",
"source": "github",
"line_count": 43,
"max_line_length": 93,
"avg_line_length": 29.302325581395348,
"alnum_prop": 0.626984126984127,
"repo_name": "karreiro/drools-wb",
"id": "9a639a7c3e895ffb853bf9e3bf4f23b8441f345e",
"size": "1879",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "drools-wb-services/drools-wb-verifier/drools-wb-verifier-api/src/main/java/org/drools/workbench/services/verifier/api/client/index/Field.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "38663"
},
{
"name": "HTML",
"bytes": "51362"
},
{
"name": "Java",
"bytes": "8367662"
},
{
"name": "JavaScript",
"bytes": "58532"
}
],
"symlink_target": ""
} |
namespace boost { namespace geometry
{
#ifndef DOXYGEN_NO_DETAIL
namespace detail { namespace overlay
{
template
<
bool Reverse1,
bool Reverse2,
overlay_type OverlayType,
typename Geometry1,
typename Geometry2,
typename Turns,
typename TurnInfoMap,
typename Clusters,
typename IntersectionStrategy,
typename RobustPolicy,
typename Visitor,
typename Backtrack
>
struct traversal_ring_creator
{
typedef traversal
<
Reverse1, Reverse2, OverlayType,
Geometry1, Geometry2, Turns, Clusters,
RobustPolicy, typename IntersectionStrategy::side_strategy_type,
Visitor
> traversal_type;
typedef typename boost::range_value<Turns>::type turn_type;
typedef typename turn_type::turn_operation_type turn_operation_type;
static const operation_type target_operation
= operation_from_overlay<OverlayType>::value;
inline traversal_ring_creator(Geometry1 const& geometry1, Geometry2 const& geometry2,
Turns& turns, TurnInfoMap& turn_info_map,
Clusters const& clusters,
IntersectionStrategy const& intersection_strategy,
RobustPolicy const& robust_policy, Visitor& visitor)
: m_trav(geometry1, geometry2, turns, clusters,
robust_policy, intersection_strategy.get_side_strategy(),
visitor)
, m_geometry1(geometry1)
, m_geometry2(geometry2)
, m_turns(turns)
, m_turn_info_map(turn_info_map)
, m_clusters(clusters)
, m_intersection_strategy(intersection_strategy)
, m_robust_policy(robust_policy)
, m_visitor(visitor)
{
}
template <typename Ring>
inline traverse_error_type travel_to_next_turn(signed_size_type start_turn_index,
int start_op_index,
signed_size_type& turn_index,
int& op_index,
Ring& current_ring,
bool is_start)
{
int const previous_op_index = op_index;
signed_size_type const previous_turn_index = turn_index;
turn_type& previous_turn = m_turns[turn_index];
turn_operation_type& previous_op = previous_turn.operations[op_index];
segment_identifier previous_seg_id;
signed_size_type to_vertex_index = -1;
if (! m_trav.select_turn_from_enriched(turn_index, previous_seg_id,
to_vertex_index, start_turn_index, start_op_index,
previous_turn, previous_op, is_start))
{
return is_start
? traverse_error_no_next_ip_at_start
: traverse_error_no_next_ip;
}
if (to_vertex_index >= 0)
{
if (previous_op.seg_id.source_index == 0)
{
geometry::copy_segments<Reverse1>(m_geometry1,
previous_op.seg_id, to_vertex_index,
m_intersection_strategy.get_side_strategy(),
m_robust_policy, current_ring);
}
else
{
geometry::copy_segments<Reverse2>(m_geometry2,
previous_op.seg_id, to_vertex_index,
m_intersection_strategy.get_side_strategy(),
m_robust_policy, current_ring);
}
}
if (m_turns[turn_index].discarded)
{
return is_start
? traverse_error_dead_end_at_start
: traverse_error_dead_end;
}
if (is_start)
{
// Register the start
previous_op.visited.set_started();
m_visitor.visit_traverse(m_turns, previous_turn, previous_op, "Start");
}
if (! m_trav.select_turn(start_turn_index, start_op_index,
turn_index, op_index,
previous_op_index, previous_turn_index, previous_seg_id,
is_start))
{
return is_start
? traverse_error_no_next_ip_at_start
: traverse_error_no_next_ip;
}
{
// Check operation (TODO: this might be redundant or should be catched before)
const turn_type& current_turn = m_turns[turn_index];
const turn_operation_type& op = current_turn.operations[op_index];
if (op.visited.finalized()
|| m_trav.is_visited(current_turn, op, turn_index, op_index))
{
return traverse_error_visit_again;
}
}
// Update registration and append point
turn_type& current_turn = m_turns[turn_index];
turn_operation_type& op = current_turn.operations[op_index];
detail::overlay::append_no_collinear(current_ring, current_turn.point,
m_intersection_strategy.get_side_strategy(),
m_robust_policy);
// Register the visit
m_trav.set_visited(current_turn, op);
m_visitor.visit_traverse(m_turns, current_turn, op, "Visit");
return traverse_error_none;
}
template <typename Ring>
inline traverse_error_type traverse(Ring& ring,
signed_size_type start_turn_index, int start_op_index)
{
turn_type const& start_turn = m_turns[start_turn_index];
turn_operation_type& start_op = m_turns[start_turn_index].operations[start_op_index];
detail::overlay::append_no_collinear(ring, start_turn.point,
m_intersection_strategy.get_side_strategy(),
m_robust_policy);
signed_size_type current_turn_index = start_turn_index;
int current_op_index = start_op_index;
traverse_error_type error = travel_to_next_turn(start_turn_index,
start_op_index,
current_turn_index, current_op_index,
ring, true);
if (error != traverse_error_none)
{
// This is not necessarily a problem, it happens for clustered turns
// which are "build in" or otherwise point inwards
return error;
}
if (current_turn_index == start_turn_index)
{
start_op.visited.set_finished();
m_visitor.visit_traverse(m_turns, m_turns[current_turn_index], start_op, "Early finish");
return traverse_error_none;
}
if (start_turn.is_clustered())
{
turn_type& turn = m_turns[current_turn_index];
turn_operation_type& op = turn.operations[current_op_index];
if (turn.cluster_id == start_turn.cluster_id
&& op.enriched.get_next_turn_index() == start_turn_index)
{
op.visited.set_finished();
m_visitor.visit_traverse(m_turns, m_turns[current_turn_index], start_op, "Early finish (cluster)");
return traverse_error_none;
}
}
std::size_t const max_iterations = 2 + 2 * m_turns.size();
for (std::size_t i = 0; i <= max_iterations; i++)
{
// We assume clockwise polygons only, non self-intersecting, closed.
// However, the input might be different, and checking validity
// is up to the library user.
// Therefore we make here some sanity checks. If the input
// violates the assumptions, the output polygon will not be correct
// but the routine will stop and output the current polygon, and
// will continue with the next one.
// Below three reasons to stop.
error = travel_to_next_turn(start_turn_index, start_op_index,
current_turn_index, current_op_index,
ring, false);
if (error != traverse_error_none)
{
return error;
}
if (current_turn_index == start_turn_index
&& current_op_index == start_op_index)
{
start_op.visited.set_finished();
m_visitor.visit_traverse(m_turns, start_turn, start_op, "Finish");
return traverse_error_none;
}
}
return traverse_error_endless_loop;
}
template <typename Rings>
void traverse_with_operation(turn_type const& start_turn,
std::size_t turn_index, int op_index,
Rings& rings, std::size_t& finalized_ring_size,
typename Backtrack::state_type& state)
{
typedef typename boost::range_value<Rings>::type ring_type;
turn_operation_type const& start_op = start_turn.operations[op_index];
if (! start_op.visited.none()
|| ! start_op.enriched.startable
|| start_op.visited.rejected()
|| ! (start_op.operation == target_operation
|| start_op.operation == detail::overlay::operation_continue))
{
return;
}
ring_type ring;
traverse_error_type traverse_error = traverse(ring, turn_index, op_index);
if (traverse_error == traverse_error_none)
{
std::size_t const min_num_points
= core_detail::closure::minimum_ring_size
<
geometry::closure<ring_type>::value
>::value;
if (geometry::num_points(ring) >= min_num_points)
{
clean_closing_dups_and_spikes(ring,
m_intersection_strategy.get_side_strategy(),
m_robust_policy);
rings.push_back(ring);
m_trav.finalize_visit_info(m_turn_info_map);
finalized_ring_size++;
}
}
else
{
Backtrack::apply(
finalized_ring_size,
rings, ring, m_turns, start_turn,
m_turns[turn_index].operations[op_index],
traverse_error,
m_geometry1, m_geometry2,
m_intersection_strategy, m_robust_policy,
state, m_visitor);
}
}
int get_operation_index(turn_type const& turn) const
{
// When starting with a continue operation, the one
// with the smallest (for intersection) or largest (for union)
// remaining distance (#8310b)
// Also to avoid skipping a turn in between, which can happen
// in rare cases (e.g. #130)
static const bool is_union
= operation_from_overlay<OverlayType>::value == operation_union;
turn_operation_type const& op0 = turn.operations[0];
turn_operation_type const& op1 = turn.operations[1];
return op0.remaining_distance <= op1.remaining_distance
? (is_union ? 1 : 0)
: (is_union ? 0 : 1);
}
template <typename Rings>
void iterate(Rings& rings, std::size_t& finalized_ring_size,
typename Backtrack::state_type& state)
{
for (std::size_t turn_index = 0; turn_index < m_turns.size(); ++turn_index)
{
turn_type const& turn = m_turns[turn_index];
if (turn.discarded || turn.blocked())
{
// Skip discarded and blocked turns
continue;
}
if (turn.both(operation_continue))
{
traverse_with_operation(turn, turn_index,
get_operation_index(turn),
rings, finalized_ring_size, state);
}
else
{
for (int op_index = 0; op_index < 2; op_index++)
{
traverse_with_operation(turn, turn_index, op_index,
rings, finalized_ring_size, state);
}
}
}
}
template <typename Rings>
void iterate_with_preference(std::size_t phase,
Rings& rings, std::size_t& finalized_ring_size,
typename Backtrack::state_type& state)
{
for (std::size_t turn_index = 0; turn_index < m_turns.size(); ++turn_index)
{
turn_type const& turn = m_turns[turn_index];
if (turn.discarded || turn.blocked())
{
// Skip discarded and blocked turns
continue;
}
turn_operation_type const& op0 = turn.operations[0];
turn_operation_type const& op1 = turn.operations[1];
if (phase == 0)
{
if (! op0.enriched.prefer_start && ! op1.enriched.prefer_start)
{
// Not preferred, take next one
continue;
}
}
if (turn.both(operation_continue))
{
traverse_with_operation(turn, turn_index,
get_operation_index(turn),
rings, finalized_ring_size, state);
}
else
{
bool const forward = op0.enriched.prefer_start;
int op_index = forward ? 0 : 1;
int const increment = forward ? 1 : -1;
for (int i = 0; i < 2; i++, op_index += increment)
{
traverse_with_operation(turn, turn_index, op_index,
rings, finalized_ring_size, state);
}
}
}
}
private:
traversal_type m_trav;
Geometry1 const& m_geometry1;
Geometry2 const& m_geometry2;
Turns& m_turns;
TurnInfoMap& m_turn_info_map; // contains turn-info information per ring
Clusters const& m_clusters;
IntersectionStrategy const& m_intersection_strategy;
RobustPolicy const& m_robust_policy;
Visitor& m_visitor;
};
}} // namespace detail::overlay
#endif // DOXYGEN_NO_DETAIL
}} // namespace boost::geometry
#endif // BOOST_GEOMETRY_ALGORITHMS_DETAIL_OVERLAY_TRAVERSAL_RING_CREATOR_HPP
| {
"content_hash": "7fae6ef20b2d5a1552a354f6ba671aa0",
"timestamp": "",
"source": "github",
"line_count": 398,
"max_line_length": 115,
"avg_line_length": 35.49246231155779,
"alnum_prop": 0.53943083675492,
"repo_name": "LedgerHQ/lib-ledger-core",
"id": "99b2834f152332a9b02c4ab67e59453c783b0151",
"size": "15294",
"binary": false,
"copies": "20",
"ref": "refs/heads/main",
"path": "core/lib/boost/boost/geometry/algorithms/detail/overlay/traversal_ring_creator.hpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ada",
"bytes": "87492"
},
{
"name": "Assembly",
"bytes": "95273"
},
{
"name": "Batchfile",
"bytes": "49710"
},
{
"name": "C",
"bytes": "17901111"
},
{
"name": "C++",
"bytes": "136103115"
},
{
"name": "CMake",
"bytes": "1117135"
},
{
"name": "CSS",
"bytes": "2536"
},
{
"name": "DIGITAL Command Language",
"bytes": "312789"
},
{
"name": "Dockerfile",
"bytes": "1746"
},
{
"name": "Emacs Lisp",
"bytes": "5297"
},
{
"name": "HTML",
"bytes": "474505"
},
{
"name": "JavaScript",
"bytes": "15286"
},
{
"name": "M4",
"bytes": "58734"
},
{
"name": "Makefile",
"bytes": "243"
},
{
"name": "Nix",
"bytes": "6555"
},
{
"name": "Perl",
"bytes": "2222280"
},
{
"name": "Prolog",
"bytes": "29177"
},
{
"name": "Python",
"bytes": "26175"
},
{
"name": "Raku",
"bytes": "34072"
},
{
"name": "Roff",
"bytes": "5"
},
{
"name": "Scala",
"bytes": "1392"
},
{
"name": "Scheme",
"bytes": "4249"
},
{
"name": "Shell",
"bytes": "186270"
},
{
"name": "XS",
"bytes": "4319"
},
{
"name": "eC",
"bytes": "5127"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "6d3b5db151c516713749e942e029e8f3",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 39,
"avg_line_length": 10.307692307692308,
"alnum_prop": 0.6940298507462687,
"repo_name": "mdoering/backbone",
"id": "924244c147715cbc2c9e38e64cb86e225ddd7a6a",
"size": "197",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Bryophyta/Bryopsida/Hypnales/Hypnaceae/Hypnum/Hypnum pratense/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
class CodeInput < SimpleForm::Inputs::TextInput
private
def html_options_for(namespace, css_classes)
return super unless namespace == :input
super.merge(lang: options[:language])
end
end
| {
"content_hash": "3d9a94ec25cf2c9cb5431102088c7859",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 47,
"avg_line_length": 22.555555555555557,
"alnum_prop": 0.729064039408867,
"repo_name": "cysjonathan/coursemology2",
"id": "74fa4f0796851aaf718ea55bb95f23c63dbc504f",
"size": "233",
"binary": false,
"copies": "5",
"ref": "refs/heads/group",
"path": "app/inputs/code_input.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "20648"
},
{
"name": "HTML",
"bytes": "158329"
},
{
"name": "JavaScript",
"bytes": "55522"
},
{
"name": "Ruby",
"bytes": "1696355"
}
],
"symlink_target": ""
} |
<?php namespace Rancherize\Plugin\Composer;
/**
* Class PODComposerPacket
* @package Rancherize\Plugin\Composer
*/
class PODComposerPacket implements ComposerPacket {
/**
* @var string
*/
private $version = '';
/**
* @var string
*/
private $name = '';
/**
* @var string
*/
private $namespace = '';
/**
* @return string
*/
public function getNamespace() {
return $this->namespace;
}
/**
* @return string
*/
public function getName() {
return $this->name;
}
/**
* @return mixed
*/
public function getVersion() {
return $this->version;
}
/**
* @param string $version
*/
public function setVersion(string $version) {
$this->version = $version;
}
/**
* @param string $name
*/
public function setName(string $name) {
$this->name = $name;
}
/**
* @param string $namespace
*/
public function setNamespace(string $namespace) {
$this->namespace = $namespace;
}
} | {
"content_hash": "3953ce1721bd8a94c5cffd1ddab40f38",
"timestamp": "",
"source": "github",
"line_count": 66,
"max_line_length": 51,
"avg_line_length": 14.212121212121213,
"alnum_prop": 0.6108742004264393,
"repo_name": "ipunkt/rancherize",
"id": "ffecdedbcc1e3f5b41ec015da3b5af16597b362d",
"size": "938",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/Plugin/Composer/PODComposerPacket.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Dockerfile",
"bytes": "2425"
},
{
"name": "PHP",
"bytes": "581029"
},
{
"name": "Shell",
"bytes": "235"
}
],
"symlink_target": ""
} |
'''This tutorial does NOT require trigonometry, but if you know some,
you can automatically generate some fancier shapes like regular polygons and
stars, as illustrated here, after importing some trig from the math module.
(And you can copy in the part before main and use the functions.)
'''
from graphics import *
from math import pi, sin, cos
toRad = pi/180 # convert degrees to radians
def atAngle(x, y, distance, angleDegrees):
'''return the Point reached by going out from Point(x,y),
the given distance, at the given angle counterclockwise from horizontal.
'''
return Point(x + distance*cos(angleDegrees*toRad),
y + distance*sin(angleDegrees*toRad) )
def regularPolygon(center, radius, sides, rotationDegrees, win):
'''Draw and return a regular polygon in GraphWin win, given the
center Point, the radius from center to vertices,
the number of sides, and degrees of rotation (0 means a flat top).
'''
vertices = []
angle = 90 + 180/sides + rotationDegrees # flat side up with 0 rotation
for i in range(sides):
vertices.append(atAngle(center.getX(), center.getY(), radius, angle))
angle = angle + 360/sides
poly = Polygon(vertices)
poly.draw(win)
return poly
def star(center, radius, points, win):
'''Draw and return a regular points-pointed star in GraphWin win, given the
center Point, the radius from center to points.
'''
vertices = []
x = center.getX()
y = center.getY()
angle = 90 # start up
angleDiff = 180/points # radial angle between points
angPoint = (2 - (points % 2))*angleDiff/2 # 2 vert apart for even, one odd
innerRadius = (radius*sin(.5*angPoint*toRad)/ # using trig law of sines
sin(.5*(angleDiff+angPoint)*toRad) )
for i in range(points):
vertices.append(atAngle(x, y, radius, angle))
angle = angle + angleDiff
vertices.append(atAngle(x, y, innerRadius, angle))
angle = angle + angleDiff
poly = Polygon(vertices)
poly.draw(win)
return poly
def main():
win = GraphWin('Regular Polygons', 400, 300)
win.yUp() # make right side up coordinates!
regularPolygon(Point(40, 240), 30, 4, 45, win) #square rotated to diamond.
c8 = Point(250, 170)
p = regularPolygon(c8, 100, 8, 0, win)
p.setWidth(5)
p = star(c8, 80, 8, win)
p.setOutline('red')
c5 = Point(100, 80)
p = regularPolygon(c5, 70, 5, 36, win) # 36: vertex up
p.setFill('blue')
p = regularPolygon(c5, 50, 5, 0, win)
p.setFill('green')
p = star(c5, 40, 5, win)
p.setFill('yellow')
win.promptClose(240, 40)
main()
| {
"content_hash": "dbbf01ca04a6ecdcb6d00324df211400",
"timestamp": "",
"source": "github",
"line_count": 77,
"max_line_length": 79,
"avg_line_length": 35.01298701298701,
"alnum_prop": 0.6450296735905044,
"repo_name": "hwheeler01/comp150",
"id": "6fce9b37e3985952abb3be5acaca7285572e9581",
"size": "2696",
"binary": false,
"copies": "2",
"ref": "refs/heads/gh-pages",
"path": "examples/polygons.py",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "11466"
},
{
"name": "Batchfile",
"bytes": "28"
},
{
"name": "CSS",
"bytes": "121532"
},
{
"name": "HTML",
"bytes": "5858311"
},
{
"name": "JavaScript",
"bytes": "524"
},
{
"name": "Jupyter Notebook",
"bytes": "6422478"
},
{
"name": "Python",
"bytes": "365319"
}
],
"symlink_target": ""
} |
<?php
declare(strict_types=1);
namespace Centreon\Domain\MetaServiceConfiguration\Exception;
/**
* This class is designed to contain all exceptions for the context of the meta service configuration.
*
* @package Centreon\Domain\MetaServiceConfiguration\Exception
*/
class MetaServiceConfigurationException extends \Exception
{
/**
* @param \Throwable $ex
* @return self
*/
public static function findMetaServicesConfigurations(\Throwable $ex): self
{
return new self(
sprintf(_('Error when searching for the meta services configurations')),
0,
$ex
);
}
/**
* @param \Throwable $ex
* @param int $metaId
* @return self
*/
public static function findOneMetaServiceConfiguration(\Throwable $ex, int $metaId): self
{
return new self(
sprintf(_('Error when searching for the meta service configuration (%s)'), $metaId),
0,
$ex
);
}
/**
* @param int $metaId
* @return self
*/
public static function findOneMetaServiceConfigurationNotFound(int $metaId): self
{
return new self(
sprintf(_('Meta service configuration (%s) not found'), $metaId)
);
}
}
| {
"content_hash": "cbabe23955466d6e8c31e82e89415b87",
"timestamp": "",
"source": "github",
"line_count": 52,
"max_line_length": 102,
"avg_line_length": 24.653846153846153,
"alnum_prop": 0.609204368174727,
"repo_name": "centreon/centreon",
"id": "54bdecbbf8a1a25bd5f8aac92ffc7ecd44197905",
"size": "1957",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "centreon/src/Centreon/Domain/MetaServiceConfiguration/Exception/MetaServiceConfigurationException.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "210043"
},
{
"name": "Gherkin",
"bytes": "174313"
},
{
"name": "HTML",
"bytes": "1276734"
},
{
"name": "JavaScript",
"bytes": "865312"
},
{
"name": "Makefile",
"bytes": "25883"
},
{
"name": "NewLisp",
"bytes": "621"
},
{
"name": "PHP",
"bytes": "15602217"
},
{
"name": "Perl",
"bytes": "1866808"
},
{
"name": "Python",
"bytes": "32748"
},
{
"name": "Raku",
"bytes": "122"
},
{
"name": "Shell",
"bytes": "473416"
},
{
"name": "Smarty",
"bytes": "42689"
},
{
"name": "TypeScript",
"bytes": "1698281"
},
{
"name": "XSLT",
"bytes": "124586"
}
],
"symlink_target": ""
} |
jQuery(document).ready(function(){
jQuery( "#dialogModal" ).dialog({
autoOpen: false,
resizable: false,
height:200,
modal: true,
buttons: {
"Send to All": function() {
jQuery('#Form_sendEntireListForm').submit();
jQuery( this ).dialog( "close" );
jQuery( "#dialogConfirm" ).dialog( "open" );
},
Cancel: function() {
jQuery( this ).dialog( "close" );
}
}
});
jQuery( "#dialogConfirm" ).dialog({
autoOpen: false
});
jQuery( "#dialogTestmailConfirm" ).dialog({
autoOpen: false
});
jQuery('#Form_sendEntireListForm_action_SendEntireList').click(function () {
jQuery( "#dialogModal" ).dialog( "open" );
return false;
});
}); | {
"content_hash": "9e1df1a235d823903f70b0bc0c47ef58",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 77,
"avg_line_length": 21.34375,
"alnum_prop": 0.616398243045388,
"repo_name": "dendeffe/Def_Newsletter",
"id": "ee528f492f65c1e55956505c97f02655bec324f5",
"size": "683",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "javascript/def_newsletter.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "683"
},
{
"name": "PHP",
"bytes": "19310"
},
{
"name": "Ruby",
"bytes": "373"
},
{
"name": "Scheme",
"bytes": "4135"
}
],
"symlink_target": ""
} |
package edu.uci.ics.hyracks.storage.am.lsm.common.impls;
import java.util.concurrent.atomic.AtomicBoolean;
import edu.uci.ics.hyracks.api.exceptions.HyracksDataException;
import edu.uci.ics.hyracks.storage.am.lsm.common.api.ILSMComponentFilter;
import edu.uci.ics.hyracks.storage.am.lsm.common.api.IVirtualBufferCache;
public abstract class AbstractMemoryLSMComponent extends AbstractLSMComponent {
private int writerCount;
private final IVirtualBufferCache vbc;
private final AtomicBoolean isModified;
private boolean requestedToBeActive;
public AbstractMemoryLSMComponent(IVirtualBufferCache vbc, boolean isActive, ILSMComponentFilter filter) {
super(filter);
this.vbc = vbc;
writerCount = 0;
if (isActive) {
state = ComponentState.READABLE_WRITABLE;
} else {
state = ComponentState.INACTIVE;
}
isModified = new AtomicBoolean();
}
public AbstractMemoryLSMComponent(IVirtualBufferCache vbc, boolean isActive) {
this(vbc, isActive, null);
}
@Override
public boolean threadEnter(LSMOperationType opType, boolean isMutableComponent) throws HyracksDataException {
if (state == ComponentState.INACTIVE && requestedToBeActive) {
state = ComponentState.READABLE_WRITABLE;
requestedToBeActive = false;
}
switch (opType) {
case FORCE_MODIFICATION:
if (isMutableComponent) {
if (state == ComponentState.READABLE_WRITABLE || state == ComponentState.READABLE_UNWRITABLE) {
writerCount++;
} else {
return false;
}
} else {
if (state == ComponentState.READABLE_UNWRITABLE
|| state == ComponentState.READABLE_UNWRITABLE_FLUSHING) {
readerCount++;
} else {
return false;
}
}
break;
case MODIFICATION:
if (isMutableComponent) {
if (state == ComponentState.READABLE_WRITABLE) {
writerCount++;
} else {
return false;
}
} else {
if (state == ComponentState.READABLE_UNWRITABLE
|| state == ComponentState.READABLE_UNWRITABLE_FLUSHING) {
readerCount++;
} else {
return false;
}
}
break;
case SEARCH:
if (state == ComponentState.READABLE_WRITABLE || state == ComponentState.READABLE_UNWRITABLE
|| state == ComponentState.READABLE_UNWRITABLE_FLUSHING) {
readerCount++;
} else {
return false;
}
break;
case FLUSH:
if (state == ComponentState.READABLE_WRITABLE || state == ComponentState.READABLE_UNWRITABLE) {
if (writerCount != 0) {
throw new IllegalStateException("Trying to flush when writerCount != 0");
}
state = ComponentState.READABLE_UNWRITABLE_FLUSHING;
readerCount++;
} else {
return false;
}
break;
default:
throw new UnsupportedOperationException("Unsupported operation " + opType);
}
return true;
}
@Override
public void threadExit(LSMOperationType opType, boolean failedOperation, boolean isMutableComponent)
throws HyracksDataException {
switch (opType) {
case FORCE_MODIFICATION:
case MODIFICATION:
if (isMutableComponent) {
writerCount--;
//A failed operation should not change the component state since it's better for the failed operation's effect to be no-op.
if (state == ComponentState.READABLE_WRITABLE && !failedOperation && isFull()) {
state = ComponentState.READABLE_UNWRITABLE;
}
} else {
readerCount--;
if (state == ComponentState.UNREADABLE_UNWRITABLE && readerCount == 0) {
state = ComponentState.INACTIVE;
}
}
break;
case SEARCH:
readerCount--;
if (state == ComponentState.UNREADABLE_UNWRITABLE && readerCount == 0) {
state = ComponentState.INACTIVE;
}
break;
case FLUSH:
if (state != ComponentState.READABLE_UNWRITABLE_FLUSHING) {
throw new IllegalStateException("Flush sees an illegal LSM memory compoenent state: " + state);
}
readerCount--;
if (readerCount == 0) {
state = ComponentState.INACTIVE;
} else {
state = ComponentState.UNREADABLE_UNWRITABLE;
}
break;
default:
throw new UnsupportedOperationException("Unsupported operation " + opType);
}
if (readerCount <= -1 || writerCount <= -1) {
throw new IllegalStateException("Invalid reader or writer count " + readerCount + " - " + writerCount);
}
}
public boolean isReadable() {
if (state == ComponentState.INACTIVE || state == ComponentState.UNREADABLE_UNWRITABLE) {
return false;
}
return true;
}
@Override
public LSMComponentType getType() {
return LSMComponentType.MEMORY;
}
@Override
public ComponentState getState() {
return state;
}
public void setState(ComponentState state) {
this.state = state;
}
public void setActive() {
requestedToBeActive = true;
}
public void setIsModified() {
isModified.set(true);
}
public boolean isModified() {
return isModified.get();
}
public boolean isFull() {
return vbc.isFull();
}
protected void reset() throws HyracksDataException {
isModified.set(false);
if (filter != null) {
filter.reset();
}
}
}
| {
"content_hash": "8baf4eab1ea9cd51a50cfee85d3ee747",
"timestamp": "",
"source": "github",
"line_count": 186,
"max_line_length": 143,
"avg_line_length": 35.44086021505376,
"alnum_prop": 0.5276092233009708,
"repo_name": "lwhay/hyracks",
"id": "76694bb9fbd529d60b46b0cafde214ccaad1b32b",
"size": "7227",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "hyracks/hyracks-storage-am-lsm-common/src/main/java/edu/uci/ics/hyracks/storage/am/lsm/common/impls/AbstractMemoryLSMComponent.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "102"
},
{
"name": "Erlang",
"bytes": "20"
},
{
"name": "HTML",
"bytes": "8070"
},
{
"name": "Java",
"bytes": "7948845"
},
{
"name": "JavaScript",
"bytes": "22477"
},
{
"name": "Shell",
"bytes": "41134"
}
],
"symlink_target": ""
} |
import {
BoundingRectangle,
Cartesian2,
Cartesian3,
Cartographic,
Color,
defaultValue,
defined,
Iso8601,
JulianDate,
PolygonHierarchy,
Rectangle,
TimeInterval,
CallbackProperty,
ColorMaterialProperty,
Entity,
EntityCollection,
exportKml,
ImageMaterialProperty,
PolylineOutlineMaterialProperty,
SampledPositionProperty,
HeightReference,
HorizontalOrigin,
VerticalOrigin,
} from "../../index.js";
import { Math as CesiumMath } from "../../index.js";
describe("DataSources/exportKml", function () {
let kmlDoc;
function checkKmlDoc(entities, properties, options) {
options = defaultValue(options, {});
options.entities = entities;
const promise = exportKml(options);
const kml = kmlDoc.documentElement;
const kmlChildNodes = kml.childNodes;
expect(kml.localName).toEqual("kml");
expect(kmlChildNodes.length).toBe(1);
checkTagWithProperties(kml, properties);
return promise;
}
function checkTagWithProperties(element, properties) {
const attributes = properties._;
if (defined(attributes)) {
const elementAttributes = element.attributes;
expect(elementAttributes.length).toBe(Object.keys(attributes).length);
for (let j = 0; j < elementAttributes.length; ++j) {
const nodeAttribute = elementAttributes[j];
const attribute = attributes[nodeAttribute.name];
if (typeof attribute === "string") {
expect(nodeAttribute.value).toEqual(attribute);
} else if (typeof attribute === "number") {
expect(Number(nodeAttribute.value)).toEqualEpsilon(
attribute,
CesiumMath.EPSILON7
);
} else {
fail();
}
}
}
const childNodes = element.childNodes;
for (let i = 0; i < childNodes.length; ++i) {
const node = childNodes[i];
let property = properties[node.tagName];
expect(property).toBeDefined();
if (defined(property.getValue)) {
property = property.getValue(Iso8601.MINIMUM_VALUE);
}
if (typeof property === "function") {
expect(property(node.textContent)).toBe(true);
} else if (typeof property === "string") {
expect(node.textContent).toEqual(property);
} else if (typeof property === "number") {
expect(Number(node.textContent)).toEqualEpsilon(
property,
CesiumMath.EPSILON7
);
} else if (typeof property === "boolean") {
expect(Number(node.textContent)).toBe(property ? 1 : 0);
} else {
checkTagWithProperties(node, property);
}
}
}
let counter = 0;
const pointPosition = Cartesian3.fromDegrees(-75.59777, 40.03883, 12);
function checkPointCoord(textContent) {
const values = textContent.split(/\s*,\s*/);
expect(values.length).toBe(3);
const cartographic1 = Cartographic.fromCartesian(pointPosition);
const cartographic2 = Cartographic.fromDegrees(
Number(values[0]),
Number(values[1]),
Number(values[2])
);
return Cartographic.equalsEpsilon(
cartographic1,
cartographic2,
CesiumMath.EPSILON7
);
}
function createEntity(properties) {
++counter;
const options = {
id: `e${counter}`,
name: `entity${counter}`,
show: true,
description: `This is entity number ${counter}`,
position: pointPosition,
};
if (defined(properties)) {
for (const propertyName in properties) {
if (properties.hasOwnProperty(propertyName)) {
options[propertyName] = properties[propertyName];
}
}
}
return new Entity(options);
}
function createExpectResult(entity) {
return {
Document: {
Style: {
_: {
id: "style-1",
},
},
Placemark: {
_: {
id: entity.id,
},
name: entity.name,
visibility: entity.show ? 1 : 0,
description: entity.description,
styleUrl: "#style-1",
},
},
};
}
let oldCreateState;
beforeAll(function () {
oldCreateState = exportKml._createState;
// We need to capture the DOM object
exportKml._createState = function (options) {
const state = oldCreateState(options);
kmlDoc = state.kmlDoc;
return state;
};
});
afterAll(function () {
exportKml._createState = oldCreateState;
});
beforeEach(function () {
counter = 0;
});
it("Hierarchy", function () {
const entity1 = createEntity({
show: false,
position: undefined,
});
const entity2 = createEntity({
position: undefined,
parent: entity1,
});
const entity3 = createEntity({
parent: entity2,
point: {},
});
const entities = new EntityCollection();
entities.add(entity1);
entities.add(entity2);
entities.add(entity3);
const hierarchy = {
Document: {
Style: {
_: {
id: "style-1",
},
IconStyle: {},
},
Folder: {
_: {
id: entity1.id,
},
name: entity1.name,
visibility: "0",
description: entity1.description,
Folder: {
_: {
id: entity2.id,
},
name: entity2.name,
visibility: true,
description: entity2.description,
Placemark: {
_: {
id: entity3.id,
},
Point: {
altitudeMode: "absolute",
coordinates: checkPointCoord,
},
name: entity3.name,
visibility: true,
description: entity3.description,
styleUrl: "#style-1",
},
},
},
},
};
checkKmlDoc(entities, hierarchy);
});
describe("Point Geometry", function () {
it("Point with constant position", function () {
const entity1 = createEntity({
point: {
color: Color.LINEN,
pixelSize: 3,
heightReference: HeightReference.CLAMP_TO_GROUND,
},
});
const entities = new EntityCollection();
entities.add(entity1);
const expectedResult = createExpectResult(entity1);
expectedResult.Document.Style.IconStyle = {
color: "ffe6f0fa",
colorMode: "normal",
scale: 3 / 32,
};
expectedResult.Document.Placemark.Point = {
altitudeMode: "clampToGround",
coordinates: checkPointCoord,
};
checkKmlDoc(entities, expectedResult);
});
it("Point with label", function () {
const entity1 = createEntity({
point: {
color: Color.LINEN,
pixelSize: 3,
heightReference: HeightReference.CLAMP_TO_GROUND,
},
label: {
text: "Im a label",
color: Color.ORANGE,
scale: 2,
},
});
const entities = new EntityCollection();
entities.add(entity1);
const expectedResult = createExpectResult(entity1);
expectedResult.Document.Style.IconStyle = {
color: "ffe6f0fa",
colorMode: "normal",
scale: 3 / 32,
};
expectedResult.Document.Style.LabelStyle = {
color: "ff00a5ff",
colorMode: "normal",
scale: 2,
};
expectedResult.Document.Placemark.name = "Im a label";
expectedResult.Document.Placemark.Point = {
altitudeMode: "clampToGround",
coordinates: checkPointCoord,
};
checkKmlDoc(entities, expectedResult);
});
it("Billboard with constant position", function () {
const entity1 = createEntity({
billboard: {
image: "http://test.invalid/image.jpg",
imageSubRegion: new BoundingRectangle(12, 0, 24, 36),
color: Color.LINEN,
scale: 2,
pixelOffset: new Cartesian2(2, 3),
width: 24,
height: 36,
horizontalOrigin: HorizontalOrigin.LEFT,
verticalOrigin: VerticalOrigin.BOTTOM,
rotation: CesiumMath.toRadians(10),
alignedAxis: Cartesian3.UNIT_Z,
heightReference: HeightReference.CLAMP_TO_GROUND,
},
});
const entities = new EntityCollection();
entities.add(entity1);
const expectedResult = createExpectResult(entity1);
expectedResult.Document.Style.IconStyle = {
Icon: {
href: "http://test.invalid/image.jpg",
x: 12,
y: 0,
w: 24,
h: 36,
},
color: "ffe6f0fa",
colorMode: "normal",
scale: 2,
hotSpot: {
_: {
x: -2 / 2,
y: 3 / 2,
xunits: "pixels",
yunits: "pixels",
},
},
heading: -10,
};
expectedResult.Document.Placemark.Point = {
altitudeMode: "clampToGround",
coordinates: checkPointCoord,
};
checkKmlDoc(entities, expectedResult);
});
it("Billboard with AlignedAxis not Z", function () {
const entity1 = createEntity({
billboard: {
rotation: CesiumMath.toRadians(10),
alignedAxis: Cartesian3.UNIT_Y,
},
});
const entities = new EntityCollection();
entities.add(entity1);
const expectedResult = createExpectResult(entity1);
expectedResult.Document.Style.IconStyle = {};
expectedResult.Document.Placemark.Point = {
altitudeMode: "absolute",
coordinates: checkPointCoord,
};
checkKmlDoc(entities, expectedResult);
});
it("Billboard with 0 degree heading should be 360", function () {
const entity1 = createEntity({
billboard: {
rotation: CesiumMath.toRadians(0),
alignedAxis: Cartesian3.UNIT_Z,
},
});
const entities = new EntityCollection();
entities.add(entity1);
const expectedResult = createExpectResult(entity1);
expectedResult.Document.Style.IconStyle = {
heading: 360,
};
expectedResult.Document.Placemark.Point = {
altitudeMode: "absolute",
coordinates: checkPointCoord,
};
checkKmlDoc(entities, expectedResult);
});
it("Billboard with HotSpot at the center", function () {
const entity1 = createEntity({
billboard: {
pixelOffset: new Cartesian2(2, 3),
width: 24,
height: 36,
horizontalOrigin: HorizontalOrigin.CENTER,
verticalOrigin: VerticalOrigin.CENTER,
},
});
const entities = new EntityCollection();
entities.add(entity1);
const expectedResult = createExpectResult(entity1);
expectedResult.Document.Style.IconStyle = {
hotSpot: {
_: {
x: -(2 - 12),
y: 3 + 18,
xunits: "pixels",
yunits: "pixels",
},
},
};
expectedResult.Document.Placemark.Point = {
altitudeMode: "absolute",
coordinates: checkPointCoord,
};
checkKmlDoc(entities, expectedResult);
});
it("Billboard with HotSpot at the TopRight", function () {
const entity1 = createEntity({
billboard: {
pixelOffset: new Cartesian2(2, 3),
width: 24,
height: 36,
horizontalOrigin: HorizontalOrigin.RIGHT,
verticalOrigin: VerticalOrigin.TOP,
},
});
const entities = new EntityCollection();
entities.add(entity1);
const expectedResult = createExpectResult(entity1);
expectedResult.Document.Style.IconStyle = {
hotSpot: {
_: {
x: -(2 - 24),
y: 3 + 36,
xunits: "pixels",
yunits: "pixels",
},
},
};
expectedResult.Document.Placemark.Point = {
altitudeMode: "absolute",
coordinates: checkPointCoord,
};
checkKmlDoc(entities, expectedResult);
});
it("Billboard with a Canvas image", function () {
const entity1 = createEntity({
billboard: {
image: document.createElement("canvas"),
},
});
const entities = new EntityCollection();
entities.add(entity1);
const expectedResult = createExpectResult(entity1);
expectedResult.Document.Style.IconStyle = {
Icon: {
href: "texture_1.png",
},
};
expectedResult.Document.Placemark.Point = {
altitudeMode: "absolute",
coordinates: checkPointCoord,
};
return checkKmlDoc(entities, expectedResult).then(function (result) {
expect(result.kml).toBeDefined();
expect(Object.keys(result.externalFiles).length).toBe(1);
expect(result.externalFiles["texture_1.png"]).toBeDefined();
});
});
it("Billboard with a Canvas image as KMZ", function () {
const entity1 = createEntity({
billboard: {
image: document.createElement("canvas"),
},
});
const entities = new EntityCollection();
entities.add(entity1);
return exportKml({
entities: entities,
kmz: true,
}).then(function (result) {
expect(result.kml).toBeUndefined();
expect(result.externalFiles).toBeUndefined();
expect(result.kmz).toBeDefined();
return new Promise((resolve) => {
const fileReader = new FileReader();
fileReader.onload = function (event) {
// Verify its a zip archive
expect(new DataView(event.target.result).getUint32(0, false)).toBe(
0x504b0304
);
resolve();
};
fileReader.readAsArrayBuffer(result.kmz);
});
});
});
});
describe("Tracks", function () {
const times = [
JulianDate.fromIso8601("2019-06-17"),
JulianDate.fromIso8601("2019-06-18"),
JulianDate.fromIso8601("2019-06-19"),
];
const positions = [
Cartesian3.fromDegrees(-75.59777, 40.03883, 12),
Cartesian3.fromDegrees(-76.59777, 39.03883, 12),
Cartesian3.fromDegrees(-77.59777, 38.03883, 12),
];
function checkWhen(textContent) {
const count = times.length;
for (let i = 0; i < count; ++i) {
if (textContent === JulianDate.toIso8601(times[i])) {
return true;
}
}
return false;
}
function checkCoord(textContent) {
const values = textContent.split(/\s*,\s*/);
expect(values.length).toBe(3);
const cartographic1 = new Cartographic();
const cartographic2 = new Cartographic();
const count = positions.length;
for (let i = 0; i < count; ++i) {
Cartographic.fromCartesian(positions[i], undefined, cartographic1);
Cartographic.fromDegrees(
Number(values[0]),
Number(values[1]),
Number(values[2]),
cartographic2
);
if (
Cartographic.equalsEpsilon(
cartographic1,
cartographic2,
CesiumMath.EPSILON7
)
) {
return true;
}
}
return false;
}
it("SampledPosition", function () {
const position = new SampledPositionProperty();
position.addSamples(times, positions);
const entity1 = createEntity({
position: position,
point: {
heightReference: HeightReference.CLAMP_TO_GROUND,
},
});
const entities = new EntityCollection();
entities.add(entity1);
const expectedResult = createExpectResult(entity1);
expectedResult.Document.Style.IconStyle = {};
expectedResult.Document.Placemark.Track = {
altitudeMode: "clampToGround",
when: checkWhen,
coord: checkCoord,
};
checkKmlDoc(entities, expectedResult);
});
it("CallbackProperty", function () {
let index = 0;
const position = new CallbackProperty(function (time) {
expect(index < times.length);
expect(JulianDate.equals(time, times[index])).toBe(true);
return positions[index++];
}, false);
const entity1 = createEntity({
position: position,
point: {},
});
const entities = new EntityCollection();
entities.add(entity1);
const expectedResult = createExpectResult(entity1);
expectedResult.Document.Style.IconStyle = {};
expectedResult.Document.Placemark.Track = {
altitudeMode: "absolute",
when: checkWhen,
coord: checkCoord,
};
checkKmlDoc(entities, expectedResult, {
defaultAvailability: new TimeInterval({
start: times[0],
stop: times[2],
}),
sampleDuration: JulianDate.secondsDifference(times[1], times[0]),
});
});
it("With Model", function () {
const position = new SampledPositionProperty();
position.addSamples(times, positions);
const entity1 = createEntity({
position: position,
model: {
uri: "http://test.invalid/test",
},
});
const entities = new EntityCollection();
entities.add(entity1);
const expectedResult = createExpectResult(entity1);
expectedResult.Document.Placemark.Track = {
altitudeMode: "absolute",
when: checkWhen,
coord: checkCoord,
Model: {
Link: {
href: "http://test.invalid/test",
},
},
};
const blob = new Blob([new Uint8Array([])], {
type: "model/vnd.collada+xml",
});
return checkKmlDoc(entities, expectedResult, {
modelCallback: function (model, time, externalFiles) {
externalFiles["test.dae"] = blob;
return model.uri;
},
}).then(function (result) {
expect(result.externalFiles["test.dae"]).toBe(blob);
});
});
it("With Path", function () {
const position = new SampledPositionProperty();
position.addSamples(times, positions);
const entity1 = createEntity({
position: position,
point: {
heightReference: HeightReference.CLAMP_TO_GROUND,
},
path: {
width: 2,
material: new ColorMaterialProperty(Color.GREEN),
},
});
const entities = new EntityCollection();
entities.add(entity1);
const expectedResult = createExpectResult(entity1);
expectedResult.Document.Style.IconStyle = {};
expectedResult.Document.Style.LineStyle = {
color: "ff008000",
colorMode: "normal",
width: 2,
};
expectedResult.Document.Placemark.Track = {
altitudeMode: "clampToGround",
when: checkWhen,
coord: checkCoord,
};
checkKmlDoc(entities, expectedResult);
});
});
describe("Polylines", function () {
const positions = [
Cartesian3.fromDegrees(-1, -1, 12),
Cartesian3.fromDegrees(1, -1, 12),
Cartesian3.fromDegrees(1, 1, 12),
Cartesian3.fromDegrees(-1, 1, 12),
];
function checkCoords(textContent) {
const coordinates = textContent.split(" ");
expect(coordinates.length).toBe(4);
const cartographic1 = new Cartographic();
const cartographic2 = new Cartographic();
const count = positions.length;
for (let i = 0; i < count; ++i) {
Cartographic.fromCartesian(positions[i], undefined, cartographic1);
const values = coordinates[i].split(",");
expect(values.length).toBe(3);
Cartographic.fromDegrees(
Number(values[0]),
Number(values[1]),
Number(values[2]),
cartographic2
);
if (
Cartographic.equalsEpsilon(
cartographic1,
cartographic2,
CesiumMath.EPSILON7
)
) {
return true;
}
}
return false;
}
it("Clamped to ground", function () {
const entity1 = createEntity({
polyline: {
positions: positions,
clampToGround: true,
material: new ColorMaterialProperty(Color.GREEN),
width: 5,
zIndex: 2,
},
});
const entities = new EntityCollection();
entities.add(entity1);
const expectedResult = createExpectResult(entity1);
expectedResult.Document.Style.LineStyle = {
color: "ff008000",
colorMode: "normal",
width: 5,
};
expectedResult.Document.Placemark.LineString = {
altitudeMode: "clampToGround",
coordinates: checkCoords,
tessellate: true,
drawOrder: 2,
};
checkKmlDoc(entities, expectedResult);
});
it("Not clamped to ground", function () {
const entity1 = createEntity({
polyline: {
positions: positions,
clampToGround: false,
material: new ColorMaterialProperty(Color.GREEN),
width: 5,
zIndex: 2,
},
});
const entities = new EntityCollection();
entities.add(entity1);
const expectedResult = createExpectResult(entity1);
expectedResult.Document.Style.LineStyle = {
color: "ff008000",
colorMode: "normal",
width: 5,
};
expectedResult.Document.Placemark.LineString = {
altitudeMode: "absolute",
coordinates: checkCoords,
drawOrder: 2,
};
checkKmlDoc(entities, expectedResult);
});
it("With outline", function () {
const entity1 = createEntity({
polyline: {
positions: positions,
clampToGround: false,
material: new PolylineOutlineMaterialProperty({
color: Color.GREEN,
outlineColor: Color.BLUE,
outlineWidth: 2,
}),
width: 5,
},
});
const entities = new EntityCollection();
entities.add(entity1);
const expectedResult = createExpectResult(entity1);
expectedResult.Document.Style.LineStyle = {
color: "ff008000",
colorMode: "normal",
width: 5,
outerColor: "ffff0000",
outerWidth: 2,
};
expectedResult.Document.Placemark.LineString = {
altitudeMode: "absolute",
coordinates: checkCoords,
};
checkKmlDoc(entities, expectedResult);
});
});
describe("Polygons", function () {
const positions = [
Cartesian3.fromDegrees(-1, -1, 12),
Cartesian3.fromDegrees(1, -1, 12),
Cartesian3.fromDegrees(1, 1, 12),
Cartesian3.fromDegrees(-1, 1, 12),
];
function getCheckCoords(height) {
return function (textContent) {
const coordinates = textContent.split(" ");
expect(coordinates.length).toBe(4);
const cartographic1 = new Cartographic();
const cartographic2 = new Cartographic();
const count = positions.length;
for (let i = 0; i < count; ++i) {
Cartographic.fromCartesian(positions[i], undefined, cartographic1);
if (defined(height)) {
cartographic1.height = height;
}
const values = coordinates[i].split(",");
expect(values.length).toBe(3);
Cartographic.fromDegrees(
Number(values[0]),
Number(values[1]),
Number(values[2]),
cartographic2
);
if (
Cartographic.equalsEpsilon(
cartographic1,
cartographic2,
CesiumMath.EPSILON7
)
) {
return true;
}
}
return false;
};
}
it("Polygon with outline", function () {
const entity1 = createEntity({
polygon: {
hierarchy: positions,
height: 10,
perPositionHeight: false,
heightReference: HeightReference.CLAMP_TO_GROUND,
extrudedHeight: 0,
fill: true,
material: new ColorMaterialProperty(Color.GREEN),
outline: true,
outlineWidth: 5,
outlineColor: Color.BLUE,
zIndex: 2,
},
});
const entities = new EntityCollection();
entities.add(entity1);
const expectedResult = createExpectResult(entity1);
expectedResult.Document.Style.PolyStyle = {
color: "ff008000",
colorMode: "normal",
fill: true,
outline: true,
};
expectedResult.Document.Style.LineStyle = {
color: "ffff0000",
colorMode: "normal",
width: 5,
};
expectedResult.Document.Placemark.Polygon = {
altitudeMode: "clampToGround",
outerBoundaryIs: {
LinearRing: {
coordinates: getCheckCoords(10),
},
},
};
checkKmlDoc(entities, expectedResult);
});
it("Polygon with extrusion", function () {
const entity1 = createEntity({
polygon: {
hierarchy: positions,
height: 10,
perPositionHeight: false,
extrudedHeight: 20,
},
});
const entities = new EntityCollection();
entities.add(entity1);
const expectedResult = createExpectResult(entity1);
expectedResult.Document.Style.PolyStyle = {};
expectedResult.Document.Placemark.Polygon = {
altitudeMode: "absolute",
outerBoundaryIs: {
LinearRing: {
coordinates: getCheckCoords(20), // We use extrudedHeight
},
},
extrude: true,
};
checkKmlDoc(entities, expectedResult);
});
it("Polygon with extrusion and perPositionHeights", function () {
const entity1 = createEntity({
polygon: {
hierarchy: positions,
height: 10,
perPositionHeight: true,
extrudedHeight: 20,
},
});
const entities = new EntityCollection();
entities.add(entity1);
const expectedResult = createExpectResult(entity1);
expectedResult.Document.Style.PolyStyle = {};
expectedResult.Document.Placemark.Polygon = {
altitudeMode: "absolute",
outerBoundaryIs: {
LinearRing: {
coordinates: getCheckCoords(), // Use per position height
},
},
extrude: true,
};
checkKmlDoc(entities, expectedResult);
});
it("Polygon with holes", function () {
const entity1 = createEntity({
polygon: {
hierarchy: new PolygonHierarchy(positions, [
new PolygonHierarchy(positions),
]),
height: 10,
},
});
const entities = new EntityCollection();
entities.add(entity1);
const expectedResult = createExpectResult(entity1);
expectedResult.Document.Style.PolyStyle = {};
expectedResult.Document.Placemark.Polygon = {
altitudeMode: "absolute",
outerBoundaryIs: {
LinearRing: {
coordinates: getCheckCoords(10),
},
},
innerBoundaryIs: {
LinearRing: {
coordinates: getCheckCoords(10),
},
},
};
checkKmlDoc(entities, expectedResult);
});
it("Rectangle extruded", function () {
const entity1 = createEntity({
rectangle: {
coordinates: Rectangle.fromDegrees(-1, -1, 1, 1),
height: 10,
perPositionHeight: false,
heightReference: HeightReference.CLAMP_TO_GROUND,
extrudedHeight: 20,
fill: true,
material: new ColorMaterialProperty(Color.GREEN),
outline: true,
outlineWidth: 5,
outlineColor: Color.BLUE,
zIndex: 2,
},
});
const entities = new EntityCollection();
entities.add(entity1);
const expectedResult = createExpectResult(entity1);
expectedResult.Document.Style.PolyStyle = {
color: "ff008000",
colorMode: "normal",
fill: true,
outline: true,
};
expectedResult.Document.Style.LineStyle = {
color: "ffff0000",
colorMode: "normal",
width: 5,
};
expectedResult.Document.Placemark.Polygon = {
altitudeMode: "clampToGround",
outerBoundaryIs: {
LinearRing: {
coordinates: getCheckCoords(20),
},
},
extrude: true,
};
checkKmlDoc(entities, expectedResult);
});
it("Rectangle not extruded", function () {
const entity1 = createEntity({
rectangle: {
coordinates: Rectangle.fromDegrees(-1, -1, 1, 1),
height: 10,
heightReference: HeightReference.CLAMP_TO_GROUND,
material: new ColorMaterialProperty(Color.GREEN),
},
});
const entities = new EntityCollection();
entities.add(entity1);
const expectedResult = createExpectResult(entity1);
expectedResult.Document.Style.PolyStyle = {
color: "ff008000",
colorMode: "normal",
};
expectedResult.Document.Placemark.Polygon = {
altitudeMode: "clampToGround",
outerBoundaryIs: {
LinearRing: {
coordinates: getCheckCoords(10),
},
},
};
checkKmlDoc(entities, expectedResult);
});
});
describe("Models", function () {
it("Model with constant position", function () {
const entity1 = createEntity({
model: {
uri: "http://test.invalid/test.glb",
scale: 3,
heightReference: HeightReference.CLAMP_TO_GROUND,
},
});
const entities = new EntityCollection();
entities.add(entity1);
const cartographic = Cartographic.fromCartesian(pointPosition);
const expectedResult = createExpectResult(entity1);
expectedResult.Document.Placemark.Model = {
altitudeMode: "clampToGround",
Location: {
longitude: CesiumMath.toDegrees(cartographic.longitude),
latitude: CesiumMath.toDegrees(cartographic.latitude),
altitude: cartographic.height,
},
Link: {
href: "http://test.invalid/test.dae",
},
scale: {
x: 3,
y: 3,
z: 3,
},
};
checkKmlDoc(entities, expectedResult, {
modelCallback: function (model, time) {
return model.uri.getValue(time).replace(".glb", ".dae");
},
});
});
});
describe("GroundOverlays", function () {
it("Rectangle", function () {
const entity = createEntity({
rectangle: {
coordinates: Rectangle.fromDegrees(-1, -1, 1, 1),
height: 10,
heightReference: HeightReference.CLAMP_TO_GROUND,
material: new ImageMaterialProperty({
image: "../images/logo.jpg",
color: Color.GREEN,
}),
},
});
const entities = new EntityCollection();
entities.add(entity);
const expectedResult = {
Document: {
GroundOverlay: {
_: {
id: entity.id,
},
name: entity.name,
visibility: entity.show ? 1 : 0,
description: entity.description,
altitude: 10,
altitudeMode: "clampToGround",
LatLonBox: {
north: 1,
south: -1,
east: 1,
west: -1,
},
Icon: {
href: "../images/logo.jpg",
},
color: "ff008000",
},
},
};
checkKmlDoc(entities, expectedResult);
});
});
describe("Multigeometry", function () {
const positions = [
Cartesian3.fromDegrees(-1, -1, 12),
Cartesian3.fromDegrees(1, -1, 12),
Cartesian3.fromDegrees(1, 1, 12),
Cartesian3.fromDegrees(-1, 1, 12),
];
function getCheckCoords() {
return function (textContent) {
const coordinates = textContent.split(" ");
expect(coordinates.length).toBe(4);
const cartographic1 = new Cartographic();
const cartographic2 = new Cartographic();
const count = positions.length;
for (let i = 0; i < count; ++i) {
Cartographic.fromCartesian(positions[i], undefined, cartographic1);
cartographic1.height = 0;
const values = coordinates[i].split(",");
expect(values.length).toBe(3);
Cartographic.fromDegrees(
Number(values[0]),
Number(values[1]),
Number(values[2]),
cartographic2
);
if (
Cartographic.equalsEpsilon(
cartographic1,
cartographic2,
CesiumMath.EPSILON7
)
) {
return true;
}
}
return false;
};
}
it("Polygon and Point", function () {
const entity1 = createEntity({
polygon: {
hierarchy: positions,
},
point: {},
});
const entities = new EntityCollection();
entities.add(entity1);
const expectedResult = createExpectResult(entity1);
expectedResult.Document.Style.IconStyle = {};
expectedResult.Document.Style.PolyStyle = {};
expectedResult.Document.Placemark.MultiGeometry = {
Point: {
altitudeMode: "absolute",
coordinates: checkPointCoord,
},
Polygon: {
altitudeMode: "absolute",
outerBoundaryIs: {
LinearRing: {
coordinates: getCheckCoords(),
},
},
extrude: true,
},
};
checkKmlDoc(entities, expectedResult);
});
});
});
| {
"content_hash": "a97ba472420748efb7faaed991a7eaa1",
"timestamp": "",
"source": "github",
"line_count": 1257,
"max_line_length": 79,
"avg_line_length": 26.895783611774064,
"alnum_prop": 0.559512541410317,
"repo_name": "CesiumGS/cesium",
"id": "542a2edcc33d20e12fb6ea88350c05a28267cc8b",
"size": "33808",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "packages/engine/Specs/DataSources/exportKmlSpec.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "54077"
},
{
"name": "GLSL",
"bytes": "396894"
},
{
"name": "HTML",
"bytes": "1763626"
},
{
"name": "Handlebars",
"bytes": "2480"
},
{
"name": "JavaScript",
"bytes": "20974134"
},
{
"name": "Python",
"bytes": "4899"
},
{
"name": "Shell",
"bytes": "1570"
},
{
"name": "TypeScript",
"bytes": "11035"
}
],
"symlink_target": ""
} |
/**
* @file sync/SyncBase.c
*
* Part of CCNx Sync.
*/
/*
* Copyright (C) 2011-2013 Palo Alto Research Center, Inc.
*
* This work is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License version 2 as published by the
* Free Software Foundation.
* This work is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details. You should have received a copy of the GNU General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "SyncMacros.h"
#include "SyncBase.h"
#include "SyncPrivate.h"
#include "SyncUtil.h"
#include <stdarg.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ccn/uri.h>
// Error support
extern void
SyncSetErrInner(struct SyncBaseStruct *base,
enum SyncErrCode code,
char * file, int line) {
struct SyncErrStruct *err = NEW_STRUCT(1, SyncErrStruct);
err->code = code;
err->file = file;
err->line = line;
struct SyncErrStruct *lag = base->errList;
while (lag != NULL) {
struct SyncErrStruct *next = lag->next;
if (next == NULL) break;
lag = next;
}
if (lag != NULL) lag->next = err;
else base->errList = err;
}
extern void
SyncClearErr(struct SyncBaseStruct *base) {
for (;;) {
struct SyncErrStruct *err = base->errList;
if (err == NULL) break;
base->errList = err->next;
free(err);
}
}
// used to forward debug messages to the client (if present)
extern void
sync_msg(struct SyncBaseStruct *base, const char *fmt, ...) {
if (base != NULL) {
struct sync_plumbing *sd = base->sd;
if (sd != NULL && sd->sync_data == base
&& sd->client_methods != NULL && sd->client_methods->r_sync_msg != NULL) {
va_list ap;
char temp[5000];
va_start(ap, fmt);
vsnprintf(temp, sizeof(temp), fmt, ap);
sd->client_methods->r_sync_msg(sd, "%s", temp);
va_end(ap);
}
}
}
// Basic object support
static int
getEnvLimited(char *key, int lo, int hi, int def) {
char *s = getenv(key);
if (s != NULL && s[0] != 0) {
int x = strtol(s, NULL, 10);
if (x >= lo && x <= hi) return x;
}
return def;
}
/**
* the default behavior for sync_start is to read the options, but not start anything
*/
static int
sync_start_default(struct sync_plumbing *sd,
struct ccn_charbuf *state_buf) {
if (sd == NULL) return -1;
struct SyncBaseStruct *base = (struct SyncBaseStruct *) sd->sync_data;
if (base == NULL || base->sd != sd) return -1;
char *here = "Sync.sync_start";
// called when there is a Repo that is ready for Sync activity
struct SyncPrivate *priv = base->priv;
int enable = getEnvLimited("CCNS_ENABLE", 0, 1, 1);
if (enable <= 0) return -1;
char *debugStr = getenv("CCNS_DEBUG");
int debug = 0;
// TBD: use a centralized definition that is NOT in Repo
if (debugStr == NULL)
debug = CCNL_NONE;
else if (strcasecmp(debugStr, "NONE") == 0)
debug = CCNL_NONE;
else if (strcasecmp(debugStr, "SEVERE") == 0)
debug = CCNL_SEVERE;
else if (strcasecmp(debugStr, "ERROR") == 0)
debug = CCNL_ERROR;
else if (strcasecmp(debugStr, "WARNING") == 0)
debug = CCNL_WARNING;
else if (strcasecmp(debugStr, "INFO") == 0)
debug = CCNL_INFO;
else if (strcasecmp(debugStr, "FINE") == 0)
debug = CCNL_FINE;
else if (strcasecmp(debugStr, "FINER") == 0)
debug = CCNL_FINER;
else if (strcasecmp(debugStr, "FINEST") == 0)
debug = CCNL_FINEST;
base->debug = debug;
// enable/disable storing of sync tree nodes
// default is to store
priv->useRepoStore = getEnvLimited("CCNS_REPO_STORE", 0, 1, 1);
// enable/disable stable recovery point
// default is to disable recovery, but to calculate stable points
priv->stableEnabled = getEnvLimited("CCNS_STABLE_ENABLED", 0, 1, 1);
// get faux error percent
priv->fauxErrorTrigger = getEnvLimited("CCNS_FAUX_ERROR",
0, 99, 0);
// get private flags for SyncActions
priv->syncActionsPrivate = getEnvLimited("CCNS_ACTIONS_PRIVATE",
0, 255, 3);
// heartbeat rate
priv->heartbeatMicros = getEnvLimited("CCNS_HEARTBEAT_MICROS",
10000, 10*1000000, 200000);
// root advise lifetime
priv->rootAdviseFresh = getEnvLimited("CCNS_ROOT_ADVISE_FRESH",
1, 30, 4);
// root advise lifetime
priv->rootAdviseLifetime = getEnvLimited("CCNS_ROOT_ADVISE_LIFETIME",
1, 30, 20);
// root advise lifetime
priv->fetchLifetime = getEnvLimited("CCNS_NODE_FETCH_LIFETIME",
1, 30, 4);
// max node or content fetches busy per root
priv->maxFetchBusy = getEnvLimited("CCNS_MAX_FETCH_BUSY",
1, 100, 6);
// max number of compares busy
priv->maxComparesBusy = getEnvLimited("CCNS_MAX_COMPARES_BUSY",
1, 100, 4);
// # of bytes permitted for RootAdvise delta mode
priv->deltasLimit = getEnvLimited("CCNS_DELTAS_LIMIT",
0, 8000, 0);
// scope for generated interests
priv->syncScope = getEnvLimited("CCNS_SYNC_SCOPE",
0, 3, 2);
if (base->debug >= CCNL_INFO) {
char temp[1024];
int pos = 0;
pos += snprintf(temp+pos, sizeof(temp)-pos,
"CCNS_ENABLE=%d",
enable);
pos += snprintf(temp+pos, sizeof(temp)-pos,
",CCNS_DEBUG=%s",
debugStr);
pos += snprintf(temp+pos, sizeof(temp)-pos,
",CCNS_REPO_STORE=%d",
priv->useRepoStore);
pos += snprintf(temp+pos, sizeof(temp)-pos,
",CCNS_STABLE_ENABLED=%d",
priv->stableEnabled);
pos += snprintf(temp+pos, sizeof(temp)-pos,
",CCNS_FAUX_ERROR=%d",
priv->fauxErrorTrigger);
pos += snprintf(temp+pos, sizeof(temp)-pos,
",CCNS_ACTIONS_PRIVATE=%d",
priv->syncActionsPrivate);
pos += snprintf(temp+pos, sizeof(temp)-pos,
",CCNS_HEARTBEAT_MICROS=%d",
priv->heartbeatMicros);
pos += snprintf(temp+pos, sizeof(temp)-pos,
",CCNS_ROOT_ADVISE_FRESH=%d",
priv->rootAdviseFresh);
pos += snprintf(temp+pos, sizeof(temp)-pos,
",CCNS_ROOT_ADVISE_LIFETIME=%d",
priv->rootAdviseLifetime);
pos += snprintf(temp+pos, sizeof(temp)-pos,
",CCNS_NODE_FETCH_LIFETIME=%d",
priv->fetchLifetime);
pos += snprintf(temp+pos, sizeof(temp)-pos,
",CCNS_MAX_FETCH_BUSY=%d",
priv->maxFetchBusy);
pos += snprintf(temp+pos, sizeof(temp)-pos,
",CCNS_MAX_COMPARES_BUSY=%d",
priv->maxComparesBusy);
pos += snprintf(temp+pos, sizeof(temp)-pos,
",CCNS_DELTAS_LIMIT=%d",
priv->deltasLimit);
pos += snprintf(temp+pos, sizeof(temp)-pos,
",CCNS_SYNC_SCOPE=%d",
priv->syncScope);
pos += snprintf(temp+pos, sizeof(temp)-pos,
",defer_verification=%d",
ccn_defer_verification(sd->ccn, -1));
sync_msg(base, "%s, %s", here, temp);
}
return 1;
}
static void
SyncFreeBase(struct SyncBaseStruct **bp) {
if (bp != NULL) {
struct SyncBaseStruct *base = *bp;
*bp = NULL;
if (base != NULL) {
struct SyncPrivate *priv = base->priv;
struct SyncNameAccumList *nal = NULL;
struct SyncNameAccumList *nalNext = NULL;
// free the errList
SyncClearErr(base);
// free the roots
while (priv->rootHead != NULL) {
if (SyncRemRoot(priv->rootHead) != NULL) break;
}
// free the name accums
if (priv->topoAccum != NULL)
SyncFreeNameAccumAndNames(priv->topoAccum);
if (priv->prefixAccum != NULL)
SyncFreeNameAccumAndNames(priv->prefixAccum);
if (priv->comps != NULL)
ccn_indexbuf_destroy(&priv->comps);
// free the name accums in the filter list
if (priv->filters != NULL) {
for (nal = priv->filters; nal != NULL; nal = nalNext) {
nalNext = nal->next;
SyncFreeNameAccumAndNames(nal->accum);
free(nal);
}
}
if (priv->saveMethods != NULL) {
free(priv->saveMethods);
}
ccn_charbuf_destroy(&priv->sliceCmdPrefix);
ccn_charbuf_destroy(&priv->localHostPrefix);
free(priv);
free(base);
}
}
}
static int
sync_notify_default(struct sync_plumbing *sd,
struct ccn_charbuf *name,
int enum_index,
uint64_t seq_num) {
struct SyncBaseStruct *base = (struct SyncBaseStruct *) sd->sync_data;
if (base == NULL || base->sd != sd) return -1;
// the default is to append the name to the namesToFetch for each root
SyncAddName(base, name, seq_num);
return 0;
}
extern void
sync_stop_default(struct sync_plumbing *sd,
struct ccn_charbuf *state_buf) {
char *here = "Sync.sync_stop";
if (sd == NULL) return;
struct SyncBaseStruct *base = (struct SyncBaseStruct *) sd->sync_data;
if (base == NULL || base->sd != sd) return;
int debug = base->debug;
if (debug >= CCNL_INFO)
sync_msg(base, "%s", here);
sd->sync_data = NULL;
base->sd = NULL;
SyncFreeBase(&base);
}
struct sync_plumbing_sync_methods defaultMethods = {
&sync_start_default,
&sync_notify_default,
&sync_stop_default
};
extern struct SyncBaseStruct *
SyncNewBase(struct sync_plumbing *sd) {
int64_t now = SyncCurrentTime();
struct SyncBaseStruct *base = NEW_STRUCT(1, SyncBaseStruct);
base->sd = sd;
sd->sync_data = base;
sd->sync_methods = &defaultMethods;
struct SyncPrivate *priv = NEW_STRUCT(1, SyncPrivate);
base->priv = priv;
priv->topoAccum = SyncAllocNameAccum(4);
priv->prefixAccum = SyncAllocNameAccum(4);
priv->sliceCmdPrefix = ccn_charbuf_create();
priv->localHostPrefix = ccn_charbuf_create();
priv->comps = ccn_indexbuf_create();
priv->lastCacheClean = now;
ccn_name_from_uri(priv->localHostPrefix, "/%C1.M.S.localhost");
ccn_name_from_uri(priv->sliceCmdPrefix, "/%C1.M.S.localhost/%C1.S.cs");
return base;
}
| {
"content_hash": "78be82eede398a2d3c72d334a6f6226f",
"timestamp": "",
"source": "github",
"line_count": 330,
"max_line_length": 86,
"avg_line_length": 35.13939393939394,
"alnum_prop": 0.5457916522938945,
"repo_name": "MobileCloudNetworking/icnaas",
"id": "2d7ec5f2dd5a1657c8d2ca173d2fb8f75162a909",
"size": "11596",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "mcn-ccn-router/ccnx-0.8.2/android/CCNx-Android-Services/jni/csrc/sync/SyncBase.c",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "5189410"
},
{
"name": "C++",
"bytes": "6050"
},
{
"name": "Groff",
"bytes": "152559"
},
{
"name": "HTML",
"bytes": "1686578"
},
{
"name": "Java",
"bytes": "4146221"
},
{
"name": "Makefile",
"bytes": "224881"
},
{
"name": "Perl",
"bytes": "1513"
},
{
"name": "Python",
"bytes": "193499"
},
{
"name": "Shell",
"bytes": "180150"
},
{
"name": "Smarty",
"bytes": "2619"
}
],
"symlink_target": ""
} |
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Azure;
using Azure.Core;
using Azure.ResourceManager;
namespace Azure.ResourceManager.AppComplianceAutomation
{
internal class ReportResourceOperationSource : IOperationSource<ReportResource>
{
private readonly ArmClient _client;
internal ReportResourceOperationSource(ArmClient client)
{
_client = client;
}
ReportResource IOperationSource<ReportResource>.CreateResult(Response response, CancellationToken cancellationToken)
{
using var document = JsonDocument.Parse(response.ContentStream);
var data = ReportResourceData.DeserializeReportResourceData(document.RootElement);
return new ReportResource(_client, data);
}
async ValueTask<ReportResource> IOperationSource<ReportResource>.CreateResultAsync(Response response, CancellationToken cancellationToken)
{
using var document = await JsonDocument.ParseAsync(response.ContentStream, default, cancellationToken).ConfigureAwait(false);
var data = ReportResourceData.DeserializeReportResourceData(document.RootElement);
return new ReportResource(_client, data);
}
}
}
| {
"content_hash": "d2a0b25b618fc9ab30c39c80f953331d",
"timestamp": "",
"source": "github",
"line_count": 33,
"max_line_length": 146,
"avg_line_length": 38.84848484848485,
"alnum_prop": 0.7293291731669267,
"repo_name": "Azure/azure-sdk-for-net",
"id": "2362c4a8afd71d47cf8fdd6d6c2ad543f7bcfbd3",
"size": "1420",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "sdk/appcomplianceautomation/Azure.ResourceManager.AppComplianceAutomation/src/Generated/LongRunningOperation/ReportResourceOperationSource.cs",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
// Type definitions for webpack-dev-middleware 3.7
// Project: https://github.com/webpack/webpack-dev-middleware
// Definitions by: Benjamin Lim <https://github.com/bumbleblym>
// reduckted <https://github.com/reduckted>
// Chris Abrams <https://github.com/chrisabrams>
// Piotr Błażejewicz <https://github.com/peterblazejewicz>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
import * as webpack from 'webpack';
import * as loglevel from 'loglevel';
import { NextHandleFunction } from 'connect';
import MemoryFileSystem = require('memory-fs');
export = WebpackDevMiddleware;
declare function WebpackDevMiddleware(
compiler: webpack.ICompiler,
options?: WebpackDevMiddleware.Options,
): WebpackDevMiddleware.WebpackDevMiddleware & NextHandleFunction;
declare namespace WebpackDevMiddleware {
interface Options {
filename?: string;
/**
* Set the default file system which will be used by webpack as primary destination of generated files
*/
fs?: MemoryFileSystem;
/** This property allows a user to pass custom HTTP headers on each request. eg. { "X-Custom-Header": "yes" } */
headers?: {
[name: string]: string;
};
/**
* The index path for web server, defaults to "index.html".
* If falsy (but not undefined), the server will not respond to requests to the root URL.
*/
index?: string | boolean;
/**
* This option instructs the module to operate in 'lazy' mode,
* meaning that it won't recompile when files change, but rather on each request.
*/
lazy?: boolean;
/**
* In the rare event that a user would like to provide a custom logging interface,
* this property allows the user to assign one
*/
logger?: Logger;
/** This property defines the level of messages that the module will log */
logLevel?: 'info' | 'warn' | 'error' | 'trace' | 'debug' | 'silent';
/**
* If true the log output of the module will be prefixed by a timestamp in the HH:mm:ss format.
* @default false
*/
logTime?: boolean;
/**
* This property allows a user to pass the list of HTTP request methods accepted by the server.
* @default [ 'GET', 'HEAD' ]
*/
methods?: string[];
/**
* This property allows a user to register custom mime types or extension mappings
* @default null
*/
mimeTypes?: MimeTypeMap | OverrideMimeTypeMap | null;
/** The public path that the middleware is bound to */
publicPath: string;
/** Allows users to provide a custom reporter to handle logging within the module */
reporter?: Reporter | null;
/** Instructs the module to enable or disable the server-side rendering mode */
serverSideRender?: boolean;
/** Options for formatting statistics displayed during and after compile */
stats?: webpack.Options.Stats;
/** The module accepts an Object containing options for file watching, which is passed directly to the compiler provided */
watchOptions?: webpack.Options.WatchOptions;
/**
* If true, the option will instruct the module to write files to the configured location on disk as specified in your webpack config file
* This option also accepts a Function value, which can be used to filter which files are written to disk
*/
writeToDisk?: boolean | ((filename: string) => boolean);
}
interface MimeTypeMap {
[type: string]: string[];
}
interface OverrideMimeTypeMap {
typeMap: MimeTypeMap;
force: boolean;
}
interface ReporterOptions {
state: boolean;
stats?: webpack.Stats;
log: Logger;
}
type Logger = loglevel.Logger;
type Reporter = (middlewareOptions: Options, reporterOptions: ReporterOptions) => void;
interface WebpackDevMiddleware {
/** A function executed once the middleware has stopped watching. */
close(callback?: () => void): void;
/** Instructs a webpack-dev-middleware instance to recompile the bundle. e.g. after a change to the configuration. */
invalidate(callback?: (stats?: webpack.Stats) => void): void;
/** Executes a callback function when the compiler bundle is valid, typically after compilation */
waitUntilValid(callback?: (stats?: webpack.Stats) => void): void;
getFilenameFromUrl: (url: string) => string | false;
fileSystem: MemoryFileSystem;
}
}
| {
"content_hash": "4354c30e1b295de5f3ac980057d50631",
"timestamp": "",
"source": "github",
"line_count": 109,
"max_line_length": 146,
"avg_line_length": 43.137614678899084,
"alnum_prop": 0.6384517226712038,
"repo_name": "dsebastien/DefinitelyTyped",
"id": "8def9015dcc27b48b1816af16462ece1da51ef51",
"size": "4704",
"binary": false,
"copies": "9",
"ref": "refs/heads/master",
"path": "types/webpack-dev-middleware/index.d.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CoffeeScript",
"bytes": "15"
},
{
"name": "HTML",
"bytes": "308"
},
{
"name": "Protocol Buffer",
"bytes": "678"
},
{
"name": "TypeScript",
"bytes": "20293816"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.apache.camel</groupId>
<artifactId>components</artifactId>
<version>3.0.0-SNAPSHOT</version>
</parent>
<artifactId>camel-paxlogging</artifactId>
<packaging>jar</packaging>
<name>Camel :: Pax Logging</name>
<description>Camel OSGi PaxLogging support</description>
<properties>
<camel.osgi.export.pkg>org.apache.camel.component.paxlogging</camel.osgi.export.pkg>
<camel.osgi.export.service>org.apache.camel.spi.ComponentResolver;component=paxlogging</camel.osgi.export.service>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-core</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.ops4j.pax.logging</groupId>
<artifactId>pax-logging-api</artifactId>
<version>${pax-logging-version}</version>
</dependency>
<dependency>
<groupId>org.ops4j.pax.logging</groupId>
<artifactId>pax-logging-service</artifactId>
<version>${pax-logging-version}</version>
</dependency>
<dependency>
<groupId>org.osgi</groupId>
<artifactId>org.osgi.core</artifactId>
<scope>provided</scope>
</dependency>
<!-- test dependencies -->
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>
| {
"content_hash": "62ee36e4174bbc823f688064d8b17ed2",
"timestamp": "",
"source": "github",
"line_count": 77,
"max_line_length": 201,
"avg_line_length": 37.03896103896104,
"alnum_prop": 0.6490182328190743,
"repo_name": "kevinearls/camel",
"id": "3ce16047ab0a8f13845358931cef33fe9e9e6557",
"size": "2852",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "components/camel-paxlogging/pom.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Apex",
"bytes": "6519"
},
{
"name": "Batchfile",
"bytes": "6512"
},
{
"name": "CSS",
"bytes": "30373"
},
{
"name": "Elm",
"bytes": "10852"
},
{
"name": "FreeMarker",
"bytes": "11410"
},
{
"name": "Groovy",
"bytes": "54390"
},
{
"name": "HTML",
"bytes": "190929"
},
{
"name": "Java",
"bytes": "70990879"
},
{
"name": "JavaScript",
"bytes": "90399"
},
{
"name": "Makefile",
"bytes": "513"
},
{
"name": "Python",
"bytes": "36"
},
{
"name": "Ruby",
"bytes": "4802"
},
{
"name": "Scala",
"bytes": "323982"
},
{
"name": "Shell",
"bytes": "23616"
},
{
"name": "Tcl",
"bytes": "4974"
},
{
"name": "Thrift",
"bytes": "6979"
},
{
"name": "XQuery",
"bytes": "546"
},
{
"name": "XSLT",
"bytes": "285105"
}
],
"symlink_target": ""
} |
'use strict';
test(testCase => {
assert_throws_dom(
'QuotaExceededError',
() => storageFoundation.releaseCapacitySync(10));
}, 'Attempting to release more capacity than available fails.');
| {
"content_hash": "e07e677252f59ea411d26b2640752079",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 64,
"avg_line_length": 28.571428571428573,
"alnum_prop": 0.705,
"repo_name": "chromium/chromium",
"id": "82ba65890b634b74fde17ad7fcd67904912d3d6a",
"size": "304",
"binary": false,
"copies": "19",
"ref": "refs/heads/main",
"path": "third_party/blink/web_tests/external/wpt/native-io/capacity_allocation_sync_failure_handling.tentative.https.any.js",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="html/html; charset=utf-8" />
<title>SimpleDBNumberDomainBytesExceededException Class Reference</title>
<meta id="xcode-display" name="xcode-display" content="render"/>
<link rel="stylesheet" type="text/css" href="../css/styles.css" media="all" />
<link rel="stylesheet" type="text/css" media="print" href="../css/stylesPrint.css" />
<meta name="generator" content="appledoc 2.2 (build 963)" />
</head>
<body>
<header id="top_header">
<div id="library" class="hideInXcode">
<h1><a id="libraryTitle" href="../index.html">AWS SDK for iOS v1.7.1 </a></h1>
<a id="developerHome" href="../index.html">Amazon Web Services, Inc.</a>
</div>
<div id="title" role="banner">
<h1 class="hideInXcode">SimpleDBNumberDomainBytesExceededException Class Reference</h1>
</div>
<ul id="headerButtons" role="toolbar">
<li id="toc_button">
<button aria-label="Show Table of Contents" role="checkbox" class="open" id="table_of_contents"><span class="disclosure"></span>Table of Contents</button>
</li>
<li id="jumpto_button" role="navigation">
<select id="jumpTo">
<option value="top">Jump To…</option>
<option value="overview">Overview</option>
<option value="tasks">Tasks</option>
<option value="properties">Properties</option>
<option value="//api/name/boxUsage"> boxUsage</option>
<option value="instance_methods">Instance Methods</option>
<option value="//api/name/description"> - description</option>
<option value="//api/name/initWithMessage:"> - initWithMessage:</option>
</select>
</li>
</ul>
</header>
<nav id="tocContainer" class="isShowingTOC">
<ul id="toc" role="tree">
<li role="treeitem"><span class="nodisclosure"></span><span class="sectionName"><a href="#overview">Overview</a></span></li>
<li role="treeitem" id="task_treeitem"><span class="nodisclosure"></span><span class="sectionName"><a href="#tasks">Tasks</a></span><ul>
</ul></li>
<li role="treeitem" class="children"><span class="disclosure"></span><span class="sectionName"><a href="#properties">Properties</a></span><ul>
<li><span class="nodisclosure"></span><span class="sectionName"><a href="#//api/name/boxUsage">boxUsage</a></span></li>
</ul></li>
<li role="treeitem" class="children"><span class="disclosure"></span><span class="sectionName"><a href="#instance_methods">Instance Methods</a></span><ul>
<li><span class="nodisclosure"></span><span class="sectionName"><a href="#//api/name/description">description</a></span></li>
<li><span class="nodisclosure"></span><span class="sectionName"><a href="#//api/name/initWithMessage:">initWithMessage:</a></span></li>
</ul></li>
</ul>
</nav>
<article>
<div id="contents" class="isShowingTOC" role="main">
<a title="SimpleDBNumberDomainBytesExceededException Class Reference" name="top"></a>
<div class="main-navigation navigation-top">
<ul>
<li><a href="../index.html">Index</a></li>
<li><a href="../hierarchy.html">Hierarchy</a></li>
</ul>
</div>
<div id="header">
<div class="section-header">
<h1 class="title title-header">SimpleDBNumberDomainBytesExceededException Class Reference</h1>
</div>
</div>
<div id="container">
<div class="section section-specification"><table cellspacing="0"><tbody>
<tr>
<td class="specification-title">Inherits from</td>
<td class="specification-value"><a href="../Classes/AmazonServiceException.html">AmazonServiceException</a> : <a href="../Classes/AmazonClientException.html">AmazonClientException</a> : NSException</td>
</tr><tr>
<td class="specification-title">Declared in</td>
<td class="specification-value">SimpleDBNumberDomainBytesExceededException.h</td>
</tr>
</tbody></table></div>
<div class="section section-overview">
<a title="Overview" name="overview"></a>
<h2 class="subtitle subtitle-overview">Overview</h2>
<p>
Too many bytes in this domain.
</p>
</div>
<div class="section section-tasks">
<a title="Tasks" name="tasks"></a>
<h2 class="subtitle subtitle-tasks">Tasks</h2>
<ul class="task-list">
<li>
<span class="tooltip">
<code><a href="#//api/name/boxUsage"> boxUsage</a></code>
</span>
<span class="task-item-suffix">property</span>
</li><li>
<span class="tooltip">
<code><a href="#//api/name/initWithMessage:">– initWithMessage:</a></code>
</span>
</li><li>
<span class="tooltip">
<code><a href="#//api/name/description">– description</a></code>
</span>
</li>
</ul>
</div>
<div class="section section-methods">
<a title="Properties" name="properties"></a>
<h2 class="subtitle subtitle-methods">Properties</h2>
<div class="section-method">
<a name="//api/name/boxUsage" title="boxUsage"></a>
<h3 class="subsubtitle method-title">boxUsage</h3>
<div class="method-subsection brief-description">
<p>The value of the BoxUsage property for this object.</p>
</div>
<div class="method-subsection method-declaration"><code>@property (nonatomic, retain) NSNumber *boxUsage</code></div>
<div class="method-subsection discussion-section">
<h4 class="method-subtitle">Discussion</h4>
<p>The value of the BoxUsage property for this object.</p>
</div>
<div class="method-subsection declared-in-section">
<h4 class="method-subtitle">Declared In</h4>
<code class="declared-in-ref">SimpleDBNumberDomainBytesExceededException.h</code><br />
</div>
</div>
</div>
<div class="section section-methods">
<a title="Instance Methods" name="instance_methods"></a>
<h2 class="subtitle subtitle-methods">Instance Methods</h2>
<div class="section-method">
<a name="//api/name/description" title="description"></a>
<h3 class="subsubtitle method-title">description</h3>
<div class="method-subsection brief-description">
<p>Returns a string representation of this object; useful for testing and
debugging.</p>
</div>
<div class="method-subsection method-declaration"><code>- (NSString *)description</code></div>
<div class="method-subsection return">
<h4 class="method-subtitle parameter-title">Return Value</h4>
<p>A string representation of this object.</p>
</div>
<div class="method-subsection discussion-section">
<h4 class="method-subtitle">Discussion</h4>
<p>Returns a string representation of this object; useful for testing and
debugging.</p>
</div>
<div class="method-subsection declared-in-section">
<h4 class="method-subtitle">Declared In</h4>
<code class="declared-in-ref">SimpleDBNumberDomainBytesExceededException.h</code><br />
</div>
</div>
<div class="section-method">
<a name="//api/name/initWithMessage:" title="initWithMessage:"></a>
<h3 class="subsubtitle method-title">initWithMessage:</h3>
<div class="method-subsection brief-description">
<p>Initialize the exception with a message.</p>
</div>
<div class="method-subsection method-declaration"><code>- (id)initWithMessage:(NSString *)<em>message</em></code></div>
<div class="method-subsection arguments-section parameters">
<h4 class="method-subtitle parameter-title">Parameters</h4>
<dl class="argument-def parameter-def">
<dt><em>message</em></dt>
<dd><p>The message.</p></dd>
</dl>
</div>
<div class="method-subsection discussion-section">
<h4 class="method-subtitle">Discussion</h4>
<p>Initialize the exception with a message.</p>
</div>
<div class="method-subsection declared-in-section">
<h4 class="method-subtitle">Declared In</h4>
<code class="declared-in-ref">AmazonClientException.h</code><br />
</div>
</div>
</div>
</div>
<div class="main-navigation navigation-bottom">
<ul>
<li><a href="../index.html">Index</a></li>
<li><a href="../hierarchy.html">Hierarchy</a></li>
</ul>
</div>
<div id="footer"><script src="/urchin.js" type="text/javascript"></script><script type="text/javascript">urchinTracker();</script>
<hr />
<div class="footer-copyright">
<p><span class="copyright">© 2013 Amazon Web Services, Inc.. All rights reserved. (Last updated: 2013-12-12)</span><br />
<span class="generator">Generated by <a href="http://appledoc.gentlebytes.com">appledoc 2.2 (build 963)</a>.</span></p>
</div>
</div>
</div>
</article>
<script type="text/javascript">
function jumpToChange()
{
window.location.hash = this.options[this.selectedIndex].value;
}
function toggleTOC()
{
var contents = document.getElementById('contents');
var tocContainer = document.getElementById('tocContainer');
if (this.getAttribute('class') == 'open')
{
this.setAttribute('class', '');
contents.setAttribute('class', '');
tocContainer.setAttribute('class', '');
window.name = "hideTOC";
}
else
{
this.setAttribute('class', 'open');
contents.setAttribute('class', 'isShowingTOC');
tocContainer.setAttribute('class', 'isShowingTOC');
window.name = "";
}
return false;
}
function toggleTOCEntryChildren(e)
{
e.stopPropagation();
var currentClass = this.getAttribute('class');
if (currentClass == 'children') {
this.setAttribute('class', 'children open');
}
else if (currentClass == 'children open') {
this.setAttribute('class', 'children');
}
return false;
}
function tocEntryClick(e)
{
e.stopPropagation();
return true;
}
function init()
{
var selectElement = document.getElementById('jumpTo');
selectElement.addEventListener('change', jumpToChange, false);
var tocButton = document.getElementById('table_of_contents');
tocButton.addEventListener('click', toggleTOC, false);
var taskTreeItem = document.getElementById('task_treeitem');
if (taskTreeItem.getElementsByTagName('li').length > 0)
{
taskTreeItem.setAttribute('class', 'children');
taskTreeItem.firstChild.setAttribute('class', 'disclosure');
}
var tocList = document.getElementById('toc');
var tocEntries = tocList.getElementsByTagName('li');
for (var i = 0; i < tocEntries.length; i++) {
tocEntries[i].addEventListener('click', toggleTOCEntryChildren, false);
}
var tocLinks = tocList.getElementsByTagName('a');
for (var i = 0; i < tocLinks.length; i++) {
tocLinks[i].addEventListener('click', tocEntryClick, false);
}
if (window.name == "hideTOC") {
toggleTOC.call(tocButton);
}
}
window.onload = init;
// If showing in Xcode, hide the TOC and Header
if (navigator.userAgent.match(/xcode/i)) {
document.getElementById("contents").className = "hideInXcode"
document.getElementById("tocContainer").className = "hideInXcode"
document.getElementById("top_header").className = "hideInXcode"
}
</script>
</body>
</html>
| {
"content_hash": "0a43e45d84b18ae307096d8fdbb75dc3",
"timestamp": "",
"source": "github",
"line_count": 445,
"max_line_length": 203,
"avg_line_length": 25.921348314606742,
"alnum_prop": 0.636237537928045,
"repo_name": "morizotter/AWSCloudWatchSample",
"id": "8d9bea459acff0fcb02eb1ac8e0ccfe91876a572",
"size": "11535",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "aws-ios-sdk-1.7.1/Documentation/html/Classes/SimpleDBNumberDomainBytesExceededException.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C++",
"bytes": "708"
},
{
"name": "CSS",
"bytes": "18960"
},
{
"name": "Objective-C",
"bytes": "10544838"
},
{
"name": "Shell",
"bytes": "3903"
},
{
"name": "TeX",
"bytes": "276926"
}
],
"symlink_target": ""
} |
import * as angular from 'angular';
angular
.module('angular-locker-tests', ['angular-locker'])
.config(['lockerProvider', function config(lockerProvider: angular.locker.ILockerProvider) {
let lockerSettings: angular.locker.ILockerSettings = {
driver: 'session',
namespace: 'myApp',
separator: '.',
eventsEnabled: true,
extend: <any>{}
};
lockerProvider.defaults(lockerSettings);
}])
.controller('LockerController', ['$scope', 'locker', function ($scope: angular.IScope, locker: angular.locker.ILockerService) {
locker.put('someKey', 'someVal');
// put an item into session storage
locker.driver('session').put('sessionKey', ['some', 'session', 'data']);
// add an item within a different namespace
locker.namespace('otherNamespace').put('foo', 'bar');
locker.put('someString', 'anyDataType');
locker.put('someObject', { foo: 'I will be serialized', bar: 'pretty cool eh' });
locker.put('someArray', ['foo', 'bar', 'baz']);
// etc
//Inserts specified key and return value of function
locker.put('someKey', function() {
var obj = { foo: 'bar', bar: 'baz' };
// some other logic
return obj;
});
locker.put('someKey', ['foo', 'bar']);
//The current value will be passed into the function so you can perform logic on the current value, before returning it. e.g.
locker.put('someKey', function(current: any) {
current.push('baz');
return current;
});
locker.get('someKey'); // = ['foo', 'bar', 'baz']
// given locker.get('foo') is not defined
locker.put('foo', function (current: any) {
// current will equal 'bar'
}, 'bar');
//This will add each key/value pair as a separate item in storage
locker.put({
someKey: 'johndoe',
anotherKey: ['some', 'random', 'array'],
boolKey: true
});
locker.add('someKey', 'someVal'); // true or false - whether the item was added or not
// locker.put('fooArray', ['bar', 'baz', 'bob']);
locker.get('fooArray'); // ['bar', 'baz', 'bob']
locker.get('keyDoesNotExist', 'a default value'); // 'a default value'
locker.get(['someKey', 'anotherKey', 'foo']);
/* will return something like...
{
someKey: 'someValue',
anotherKey: true,
foo: 'bar'
}*/
// locker.put('someKey', { foo: 'bar', baz: 'bob' });
locker.pull('someKey', 'defaultVal'); // { foo: 'bar', baz: 'bob' }
// then...
locker.get('someKey', 'defaultVal'); // 'defaultVal'
locker.all();
// or
locker.namespace('somethingElse').all();
locker.count();
// or
locker.namespace('somethingElse').count();
locker.has('someKey'); // true or false
// or
locker.namespace('foo').has('bar');
// e.g.
if (locker.has('user.authToken') ) {
// we're logged in
} else {
// go to login page or something
}
locker.forget('keyToRemove');
// or
locker.driver('session').forget('sessionKey');
// etc..
locker.forget(['keyToRemove', 'anotherKeyToRemove', 'something', 'else']);
locker.clean();
// or
locker.namespace('someOtherNamespace').clean();
locker.empty();
locker.bind($scope, 'foo');
$scope['foo'] = ['bar', 'baz'];
locker.get('foo'); // = ['bar', 'baz']
locker.bind($scope, 'foo', 'someDefault');
$scope['foo']; // = 'someDefault'
locker.get('foo'); // = 'someDefault'
locker.unbind($scope, 'foo');
$scope['foo']; // = undefined
locker.get('foo'); // = undefined
if (! locker.supported()) {
// load a polyfill?
}
}]);
| {
"content_hash": "b92f751c8c0f88786f37d00ec2d95869",
"timestamp": "",
"source": "github",
"line_count": 132,
"max_line_length": 129,
"avg_line_length": 27.818181818181817,
"alnum_prop": 0.5789760348583878,
"repo_name": "use-strict/DefinitelyTyped",
"id": "a82f6a86cbdd65246247c3b55497dd8528cd5782",
"size": "3672",
"binary": false,
"copies": "44",
"ref": "refs/heads/master",
"path": "angular-locker/angular-locker-tests.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "6462"
},
{
"name": "TypeScript",
"bytes": "23589354"
}
],
"symlink_target": ""
} |
package com.hazelcast.client.impl.protocol.task.multimap;
import com.hazelcast.client.impl.protocol.ClientMessage;
import com.hazelcast.client.impl.protocol.codec.MultiMapRemoveEntryCodec;
import com.hazelcast.client.impl.protocol.task.AbstractPartitionMessageTask;
import com.hazelcast.instance.impl.Node;
import com.hazelcast.multimap.impl.MultiMapService;
import com.hazelcast.multimap.impl.operations.RemoveOperation;
import com.hazelcast.internal.nio.Connection;
import com.hazelcast.security.permission.ActionConstants;
import com.hazelcast.security.permission.MultiMapPermission;
import com.hazelcast.spi.impl.operationservice.Operation;
import java.security.Permission;
/**
* Client Protocol Task for handling messages with type ID:
* {@link com.hazelcast.client.impl.protocol.codec.MultiMapMessageType#MULTIMAP_REMOVEENTRY}
*/
public class MultiMapRemoveEntryMessageTask
extends AbstractPartitionMessageTask<MultiMapRemoveEntryCodec.RequestParameters> {
public MultiMapRemoveEntryMessageTask(ClientMessage clientMessage, Node node, Connection connection) {
super(clientMessage, node, connection);
}
@Override
protected Operation prepareOperation() {
return new RemoveOperation(parameters.name, parameters.key, parameters.threadId, parameters.value);
}
@Override
protected MultiMapRemoveEntryCodec.RequestParameters decodeClientMessage(ClientMessage clientMessage) {
return MultiMapRemoveEntryCodec.decodeRequest(clientMessage);
}
@Override
protected ClientMessage encodeResponse(Object response) {
return MultiMapRemoveEntryCodec.encodeResponse((Boolean) response);
}
@Override
public String getServiceName() {
return MultiMapService.SERVICE_NAME;
}
@Override
public Permission getRequiredPermission() {
return new MultiMapPermission(parameters.name, ActionConstants.ACTION_REMOVE);
}
@Override
public String getDistributedObjectName() {
return parameters.name;
}
@Override
public String getMethodName() {
return "remove";
}
@Override
public Object[] getParameters() {
return new Object[]{parameters.key, parameters.value};
}
}
| {
"content_hash": "d9cfaa9a5098e8ce4eb278313f6a971e",
"timestamp": "",
"source": "github",
"line_count": 68,
"max_line_length": 107,
"avg_line_length": 32.911764705882355,
"alnum_prop": 0.7667560321715817,
"repo_name": "mdogan/hazelcast",
"id": "8942973afb8698346b6876324331d610e2c39060",
"size": "2863",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "hazelcast/src/main/java/com/hazelcast/client/impl/protocol/task/multimap/MultiMapRemoveEntryMessageTask.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "1862"
},
{
"name": "C",
"bytes": "3721"
},
{
"name": "Java",
"bytes": "45797218"
},
{
"name": "Shell",
"bytes": "30002"
}
],
"symlink_target": ""
} |
project_path: /web/tools/workbox/_project.yaml
book_path: /web/tools/workbox/_book.yaml
description: The module guide for workbox-sw.
{# wf_blink_components: N/A #}
{# wf_updated_on: 2019-02-01 #}
{# wf_published_on: 2017-11-27 #}
# Workbox {: .page-title }
## What is Workbox SW?
The `workbox-sw` module provide an extremely easy way to get up and running
with the Workbox modules and simplifies the loading of the Workbox modules and
offers some simply helper methods.
You can use `workbox-sw` via our CDN or you use it with a set of workbox files
on your own server.
## Using Workbox SW via CDN
The easiest way to start using this module is via the CDN. You just need to
add the following to your service worker:
<pre class="prettyprint js">
importScripts('{% include "web/tools/workbox/_shared/workbox-sw-cdn-url.html" %}');
</pre>
With this you’ll have the `workbox` namespace in your service worker that will
provide access to all of the Workbox modules.
<pre class="prettyprint js">
workbox.precaching.*
workbox.routing.*
etc
</pre>
There is some magic that happens as you start to use the additional modules.
When you reference a module for the first time, `workbox-sw` will detect this
and load the module before making it available. You can see this happening in
the network tab in DevTools.

These files will be cached by your browser making them available for future
offline use.
## Using Local Workbox Files Instead of CDN
If you don’t want to use the CDN, it’s easy enough to switch to Workbox files
hosted on your own domain.
The simplest approach is to get the files via [`workbox-cli`'s `copyLibraries`
command](/web/tools/workbox/modules/workbox-cli#copylibraries) or from a [GitHub
Release](https://github.com/GoogleChrome/workbox/releases), and then tell
`workbox-sw` where to find these files via the `modulePathPrefix` config option.
If you put the files under `/third_party/workbox/`, you would use them like so:
<pre class="prettyprint js">
importScripts('/third_party/workbox/workbox-sw.js');
workbox.setConfig({
modulePathPrefix: '/third_party/workbox/'
});
</pre>
With this, you’ll use only the local Workbox files.
## Avoid Async Imports
Under the hood, loading new modules for the first time involves calling
[`importScripts()`](https://developer.mozilla.org/en-US/docs/Web/API/WorkerGlobalScope/importScripts)
with the path to the corresponding JavaScript file (either hosted on the CDN, or via a local URL).
In either case, an important restriction applies: the implicit calls to `importScripts()` can only
happen inside of a service worker's `install` handler *or* during the synchronous,
[initial execution](https://stackoverflow.com/questions/38835273) of the service worker script.
In order to avoid violating this restriction, a best practice is to reference the various
`workbox.*` namespaces outside of any event handlers or asynchronous functions.
For example, the following top-level service worker code is fine:
<pre class="prettyprint js">
importScripts('{% include "web/tools/workbox/_shared/workbox-sw-cdn-url.html" %}');
// This will work!
workbox.routing.registerRoute(
new RegExp('\.png$'),
new workbox.strategies.CacheFirst()
);
</pre>
But this code could be a problem if you have not referenced `workbox.strategies` elsewhere in your
service worker:
<pre class="prettyprint js">
importScripts('{% include "web/tools/workbox/_shared/workbox-sw-cdn-url.html" %}');
self.addEventListener('fetch', (event) => {
if (event.request.url.endsWith('.png')) {
// Oops! This causes workbox-strategies.js to be imported inside a fetch handler,
// outside of the initial, synchronous service worker execution.
const cacheFirst = new workbox.strategies.CacheFirst();
event.respondWith(cacheFirst.makeRequest({request: event.request}));
}
});
</pre>
If you need to write code that would otherwise run afoul of this restriction, you can explicitly
trigger the `importScripts()` call outside of the event handler by using the
[`workbox.loadModule()`](/web/tools/workbox/reference-docs/latest/workbox#.loadModule) method:
<pre class="prettyprint js">
importScripts('{% include "web/tools/workbox/_shared/workbox-sw-cdn-url.html" %}');
// This will trigger the importScripts() for workbox.strategies and its dependencies:
workbox.loadModule('workbox-strategies');
self.addEventListener('fetch', (event) => {
if (event.request.url.endsWith('.png')) {
// Referencing workbox.strategies will now work as expected.
const cacheFirst = new workbox.strategies.CacheFirst();
event.respondWith(cacheFirst.makeRequest({request: event.request}));
}
});
</pre>
Alternatively, you can create a reference to the relevant namespaces outside of your event handlers,
and then use that reference later on:
<pre class="prettyprint js">
importScripts('{% include "web/tools/workbox/_shared/workbox-sw-cdn-url.html" %}');
// This will trigger the importScripts() for workbox.strategies and its dependencies:
const {strategies} = workbox;
self.addEventListener('fetch', (event) => {
if (event.request.url.endsWith('.png')) {
// Using the previously-initialized strategies will work as expected.
const cacheFirst = new strategies.CacheFirst();
event.respondWith(cacheFirst.makeRequest({request: event.request}));
}
});
</pre>
Note: Some versions of Chrome do not honor this restriction, and asynchronous calls to
`importScripts()` don't trigger the expected failure. Developers are advised *not* to rely on this
broken behavior. Chrome [plans](https://www.chromestatus.com/feature/5748516353736704) on making
a change to start disallowing this usage, bringing it in line with what other browsers already do.
## Force Use of Debug or Production Builds
All of the Workbox modules come with two builds, a debug build which is
contains logging and additional type checking and a production build which
strips the logging and type checking.
By default, `workbox-sw` will use the debug build for sites on localhost,
but for any other origin it’ll use the production build.
If you want to force debug or production builds you set the `debug` config
option.
<pre class="prettyprint js">
workbox.setConfig({
debug: <true or false>
});
</pre>
| {
"content_hash": "631b063d8493ab723d216f9070338000",
"timestamp": "",
"source": "github",
"line_count": 169,
"max_line_length": 101,
"avg_line_length": 37.49704142011834,
"alnum_prop": 0.7571406028089002,
"repo_name": "samdutton/WebFundamentals",
"id": "38dfe36cf17116866b38552137901d8a0eb140f4",
"size": "6347",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/content/en/tools/workbox/modules/workbox-sw.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "34512"
},
{
"name": "HTML",
"bytes": "3375500"
},
{
"name": "JavaScript",
"bytes": "274741"
},
{
"name": "Python",
"bytes": "256072"
},
{
"name": "Shell",
"bytes": "5080"
},
{
"name": "Smarty",
"bytes": "3872"
}
],
"symlink_target": ""
} |
<?php
namespace App\Command\Mailbox;
use App\Command\Mailbox\ChangePasswordCommand;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
class ChangePasswordCommandSpec extends ObjectBehavior
{
const MAILBOX = 'mail@server.de';
const OLD_PASSWORD = 'verysecret';
const NEW_PASSWORD = '#verysecret#';
function let()
{
$this->beConstructedWith(self::MAILBOX, self::OLD_PASSWORD, self::NEW_PASSWORD);
}
function it_is_initializable()
{
$this->shouldHaveType(ChangePasswordCommand::class);
}
function it_has_a_domain_id()
{
$this->getMailbox()->shouldReturn(self::MAILBOX);
}
function it_has_an_old_password()
{
$this->getOldPassword()->shouldReturn(self::OLD_PASSWORD);
}
function it_has_a_new_password()
{
$this->getNewPassword()->shouldReturn(self::NEW_PASSWORD);
}
function it_has_setters()
{
$this->beConstructedWith(null,null,null);
$this->setMailbox(self::MAILBOX);
$this->setOldPassword(self::OLD_PASSWORD);
$this->setNewPassword(self::NEW_PASSWORD);
$this->getMailbox()->shouldReturn(self::MAILBOX);
$this->getOldPassword()->shouldReturn(self::OLD_PASSWORD);
$this->getNewPassword()->shouldReturn(self::NEW_PASSWORD);
}
}
| {
"content_hash": "473e7e8cc24ac21ee2421643004c0146",
"timestamp": "",
"source": "github",
"line_count": 50,
"max_line_length": 88,
"avg_line_length": 26.28,
"alnum_prop": 0.6491628614916286,
"repo_name": "haus23/server",
"id": "40c428a7c1710361c3c0deb36d3bc49a2469a166",
"size": "1314",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "specs/Command/Mailbox/ChangePasswordCommandSpec.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "426"
},
{
"name": "PHP",
"bytes": "46259"
}
],
"symlink_target": ""
} |
using namespace lldb;
using namespace lldb_private;
// ThreadPlanCallUserExpression: Plan to call a single function
ThreadPlanCallUserExpression::ThreadPlanCallUserExpression(
Thread &thread, Address &function, llvm::ArrayRef<lldb::addr_t> args,
const EvaluateExpressionOptions &options,
lldb::UserExpressionSP &user_expression_sp)
: ThreadPlanCallFunction(thread, function, CompilerType(), args, options),
m_user_expression_sp(user_expression_sp) {
// User expressions are generally "User generated" so we should set them up
// to stop when done.
SetIsMasterPlan(true);
SetOkayToDiscard(false);
}
ThreadPlanCallUserExpression::~ThreadPlanCallUserExpression() {}
void ThreadPlanCallUserExpression::GetDescription(
Stream *s, lldb::DescriptionLevel level) {
if (level == eDescriptionLevelBrief)
s->Printf("User Expression thread plan");
else
ThreadPlanCallFunction::GetDescription(s, level);
}
void ThreadPlanCallUserExpression::DidPush() {
ThreadPlanCallFunction::DidPush();
if (m_user_expression_sp)
m_user_expression_sp->WillStartExecuting();
}
void ThreadPlanCallUserExpression::WillPop() {
ThreadPlanCallFunction::WillPop();
if (m_user_expression_sp)
m_user_expression_sp.reset();
}
bool ThreadPlanCallUserExpression::MischiefManaged() {
Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
if (IsPlanComplete()) {
LLDB_LOGF(log, "ThreadPlanCallFunction(%p): Completed call function plan.",
static_cast<void *>(this));
if (m_manage_materialization && PlanSucceeded() && m_user_expression_sp) {
lldb::addr_t function_stack_top;
lldb::addr_t function_stack_bottom;
lldb::addr_t function_stack_pointer = GetFunctionStackPointer();
function_stack_bottom = function_stack_pointer - HostInfo::GetPageSize();
function_stack_top = function_stack_pointer;
DiagnosticManager diagnostics;
ExecutionContext exe_ctx(GetThread());
m_user_expression_sp->FinalizeJITExecution(
diagnostics, exe_ctx, m_result_var_sp, function_stack_bottom,
function_stack_top);
}
ThreadPlan::MischiefManaged();
return true;
} else {
return false;
}
}
StopInfoSP ThreadPlanCallUserExpression::GetRealStopInfo() {
StopInfoSP stop_info_sp = ThreadPlanCallFunction::GetRealStopInfo();
if (stop_info_sp) {
lldb::addr_t addr = GetStopAddress();
DynamicCheckerFunctions *checkers = m_process.GetDynamicCheckers();
StreamString s;
if (checkers && checkers->DoCheckersExplainStop(addr, s))
stop_info_sp->SetDescription(s.GetData());
}
return stop_info_sp;
}
void ThreadPlanCallUserExpression::DoTakedown(bool success) {
ThreadPlanCallFunction::DoTakedown(success);
m_user_expression_sp->DidFinishExecuting();
}
| {
"content_hash": "6284e5f0b960f366f14dc49a6455d3c2",
"timestamp": "",
"source": "github",
"line_count": 89,
"max_line_length": 79,
"avg_line_length": 31.640449438202246,
"alnum_prop": 0.7276278409090909,
"repo_name": "endlessm/chromium-browser",
"id": "00b01c76d9008a3a7179e1b9f15a0f1a7cec38e9",
"size": "3862",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "third_party/llvm/lldb/source/Target/ThreadPlanCallUserExpression.cpp",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
namespace EyeInTheSky.Tests.Model.StalkNodes
{
using System.Collections;
using EyeInTheSky.Model;
using EyeInTheSky.Model.Interfaces;
using EyeInTheSky.Model.StalkNodes;
using EyeInTheSky.Model.StalkNodes.BaseNodes;
using EyeInTheSky.Tests.Model.StalkNodes.BaseNodes;
using Moq;
using NUnit.Framework;
[TestFixture]
public class NotNodeTest : SingleChildNodeTestBase<NotNode>
{
[Test, TestCaseSource(typeof(NotNodeTest), "TestCases")]
public bool? DualOperatorTest(IStalkNode a)
{
var node = new NotNode();
node.ChildNode = a;
return node.Match(new RecentChange(""), false);
}
private static IEnumerable TestCases
{
get
{
var nullNodeMock = new Mock<IStalkNode>();
nullNodeMock.Setup(x => x.Match(It.IsAny<IRecentChange>())).Returns(null);
yield return new TestCaseData(new TrueNode()).Returns(false);
yield return new TestCaseData(new FalseNode()).Returns(true);
yield return new TestCaseData(nullNodeMock.Object).Returns(null);
}
}
}
} | {
"content_hash": "8a73773db01c69ac34d3c1a3116e43d2",
"timestamp": "",
"source": "github",
"line_count": 37,
"max_line_length": 90,
"avg_line_length": 32.37837837837838,
"alnum_prop": 0.6202003338898163,
"repo_name": "stwalkerster/eyeinthesky",
"id": "0dec72045b83673c239bf0e36666b94f807c1145",
"size": "1200",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "EyeInTheSky.Tests/Model/StalkNodes/NotNodeTest.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "686891"
},
{
"name": "CSS",
"bytes": "42513"
},
{
"name": "HTML",
"bytes": "29445"
},
{
"name": "JavaScript",
"bytes": "101214"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=Edge"/>
<title>Untitled</title>
<!--Adobe Edge Runtime-->
<meta http-equiv="X-UA-Compatible" content="IE=Edge">
<script type="text/javascript" charset="utf-8" src="manage-foreground_edgePreload.js"></script>
<style>
.edgeLoad-EDGE-116472068 { visibility:hidden; }
</style>
<!--Adobe Edge Runtime End-->
</head>
<body style="margin:0;padding:0;">
<div id="Stage" class="EDGE-116472068">
<div id="Stage_error-message_foreground" class="edgeLoad-EDGE-116472068"></div>
<div id="Stage_Athlete" class="edgeLoad-EDGE-116472068">
<div id="Stage_Athlete_foreground_260400"></div>
</div>
<div id="Stage_Athlete_Trigger" class="edgeLoad-EDGE-116472068"></div>
<div id="Stage_Button" class="edgeLoad-EDGE-116472068">
<div id="Stage_Button_learn_more_btn"></div>
</div>
</div>
</body>
</html> | {
"content_hash": "3bd2fed69e08511e5c7cacbf93f85f2d",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 99,
"avg_line_length": 35.62068965517241,
"alnum_prop": 0.6379477250726041,
"repo_name": "gabeshaughnessy/augmentedart",
"id": "64280c3d09724a6dfeb2fe6c486c92886b8be271",
"size": "1033",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "nike-vegas/animation-proofs/manage-foreground.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1015472"
},
{
"name": "HTML",
"bytes": "1440687"
},
{
"name": "JavaScript",
"bytes": "2086917"
},
{
"name": "PHP",
"bytes": "4790190"
},
{
"name": "Ruby",
"bytes": "1969"
},
{
"name": "Shell",
"bytes": "2980"
}
],
"symlink_target": ""
} |
.buddypress .breadcrumbs {display:none;}
.groups .page-title a.button{display:table !important;font-weight:400;line-height:1.532em;margin:10px auto}
.groups .page-title a.button:after{content:''}
#article #buddypress th, #article #buddypress td{line-height:1.352em;padding:10px}
body.activity-permalink #buddypress .activity-content .activity-inner,body.activity-permalink #buddypress .activity-content blockquote{margin-left:0;margin-top:5px}
body.activity-permalink #buddypress .activity-list > li:first-child{padding:3px}
body.activity-permalink #buddypress .activity-list li .activity-content, body.activity-permalink #buddypress div.activity-comments{margin-left:95px;}
body.activity-permalink #buddypress .activity-list li .activity-content{border:none;font-size:100%;line-height:150%;margin-right:0;padding:0}
body.activity-permalink #buddypress .activity-list li.mini .activity-comments{clear:none;margin-top:0}
body.activity-permalink #buddypress div.activity-comments{background:none;width:auto}
body.activity-permalink #buddypress div.activity-comments div.acomment-content{font-size:90%}
body.activity-permalink #buddypress div.activity-comments ul li > ul{margin-top:10px}
body.activity-permalink #buddypress div.activity-comments > ul{padding:0}
body.activity-permalink #buddypress div.activity-meta{margin-bottom:6px}
body.activity-permalink #buddypress li.mini .activity-meta{margin-top:4px}
body.activity-permalink #buddypress ul.activity-list li.has-comments{padding-bottom:0}
body.activity-permalink #buddypress ul.item-list,body.activity-permalink #buddypress ul.item-list li.activity-item{border:0}
body.activity-permalink .activity-avatar{padding:2px;background:#fff;border-radius:100px;}
body.activity-permalink #buddypress .activity-avatar img.avatar{width:76px;height:76px;margin-right:0;}
body.no-js #buddypress #notifications-bulk-management #select-all-notifications,body.no-js #buddypress label[for="message-type-select"],body.no-js #buddypress #message-type-select,body.no-js #buddypress #delete_inbox_messages,body.no-js #buddypress #delete_sentbox_messages,body.no-js #buddypress #messages-bulk-management #select-all-messages{display:none}
body.no-js #buddypress #whats-new-options{height:auto}
body.no-js #buddypress .field-visibility-settings{display:block}
body.no-js #buddypress .field-visibility-settings-toggle,body.no-js #buddypress .field-visibility-settings-close{display:none}
body.no-js #buddypress form#whats-new-form textarea{height:50px}
body.no-js #buddypress div#item-header .js-self-profile-button{display:none}
body.no-js #buddypress div.item-list-tabs ul li.last select{opacity:1}
#buddypress .avatar{border-radius:100%;-webkit-border-radius:100%}
#buddypress .clear{clear:left}
#buddypress input:focus, #buddypress select:focus, #buddypress textarea:focus{outline:0;background:white;}
#buddypress ul.item-list{list-style:none;clear:both;}
#buddypress ul.item-list li{position:relative;list-style:none}
#buddypress ul.item-list li div.item-title,#buddypress ul.item-list li h4{font-weight: bold;}
#buddypress ul.item-list li div.item-title span{color:inherit;font-size:inherit;font-weight:400;line-height:1.785em}
#buddypress ul.item-list li div.item-desc{color:inherit;font-size:inherit;margin:10px 0 0 65px;width:auto;font: 14px/16px Arial;}
#buddypress ul.item-list li.group-no-avatar div.item-desc{margin-left:0}
#buddypress ul.item-list li div.meta{color:#aaa;font-size:70%;margin-top:10px}
#buddypress ul.item-list li h5 span.small{float:right;font-size:80%;font-weight:400}
#buddypress div.pagination{background:transparent;border:none;color:#444;margin:0;position:relative;display:block;float:left;width:100%;padding:0 0 30px 0}
#buddypress div.pagination .pag-count{float:left;margin-left:10px}
#buddypress div.pagination .pagination-links{float:right;margin-right:10px}
#buddypress div.pagination .pagination-links span,#buddypress div.pagination .pagination-links a{font-size:90%;padding:0 5px}
#buddypress div.pagination .pagination-links a:hover{font-weight:700}
#buddypress noscript div.pagination{margin-bottom:15px}
#buddypress #nav-above{display:none}
#buddypress .paged #nav-above{display:block}
#buddypress img.wp-smiley{border:none!important;clear:none!important;float:none!important;margin:0!important;padding:0!important}
#buddypress #activity-stream {margin-top:0}
#buddypress #activity-stream p{margin:0 0 10px 0}
#buddypress div#latest-update{position:relative;overflow:visible;padding-top:12px;padding-bottom:10px;font-style:italic}
#buddypress form#whats-new-form, #buddypress div#invite-list{margin: 0 0 32px 0;color: #5091b2;background: #e9f7fe;border: 1px solid #b6d7e8; padding: 25px; overflow: hidden;}
#buddypress .home-page form#whats-new-form{border-bottom:none;padding-bottom:0}
#buddypress form#whats-new-form #whats-new-avatar{float:left}
#buddypress form#whats-new-form #whats-new-content{margin:10px 0 0 75px;padding:0}
#buddypress form#whats-new-form p.activity-greeting {line-height:inherit;margin-bottom:0;margin-left: 75px;font-weight: 600;font-size: 14px}
#buddypress form#whats-new-form textarea{inset 0 1px 1px 1px rgba(0,0,0,.10) border:none; box-sizing:border-box;color:#555;font-family:inherit;font-size:medium;height:2.2em;line-height:1.4;padding:6px;width:100%}
#buddypress #whats-new-options{height:auto !important;width:100%;overflow:hidden;clear:both;content:"";display:table}
#buddypress form#whats-new-form #whats-new-submit{float:left;margin-top:12px}
#buddypress form#whats-new-form #whats-new-options select#whats-new-post-in {margin-top:10px;background:#fff;width:135px}
#buddypress #whats-new:focus{border-color:#aaa !important;outline-color:transparent;}
#whats-new-post-in-box{float:right;font-size:0}
#buddypress ul.activity-list > li{padding:25px;list-style:none;border: 1px solid #eee;box-shadow: rgba(0,0,0,0.1) 1px 1px 2px; background: #fff; margin: 0 0 22px 0}
#buddypress ul.activity-list li.mini div.activity-meta a{font-size: 10px}
#buddypress .activity-list .activity-avatar{float:left}
#buddypress .activity-list .activity-content{margin:0 0 0 75px}
#buddypress .activity-list .activity-content .activity-header,#buddypress .activity-list .activity-content .comment-header{line-height:1.785em;margin-right:0;color:#999}
#buddypress .activity-list .activity-content .activity-header img.avatar{float:none!important;margin:0 5px !important;vertical-align: middle;}
#buddypress .activity-list li.mini{font-size: 85%}
.activity-list li.mini .activity-avatar img.avatar, .activity-list li.mini .activity-avatar img.FB_profile_pic {height: 30px;margin-left: 25px;width: 30px;}
#buddypress .activity-list li.mini .activity-avatar img.avatar,#buddypress .activity-list li.mini .activity-avatar img.fb_profile_pic{}
#buddypress .activity-permalink .activity-list li.mini .activity-avatar img.avatar,#buddypress .activity-permalink .activity-list li.mini .activity-avatar img.fb_profile_pic{height:auto;margin-left:0;width:auto}
#buddypress .activity-list li .activity-content{position:relative}
#buddypress .activity-list li.mini .activity-content p{margin:0}
#buddypress .activity-list li.mini .activity-comments{clear:both;font-size:120%}
#buddypress .activity-list li .activity-inreplyto{color:#888;font-size:80%}
#buddypress .activity-list li .activity-inreplyto > p{margin:0;display:inline}
#buddypress .activity-list li .activity-inreplyto blockquote,#buddypress .activity-list li .activity-inreplyto div.activity-inner{background:none;border:none;display:inline;margin:0;overflow:hidden;padding:0}
#buddypress .activity-list li.load-more,#buddypress .activity-list li.load-newest{background:none;font-size:110%;margin:0;padding:20px 0 35px 0;text-align:center; box-shadow: none; border: none;}
#buddypress .activity-list li.load-more a {
display: inline-block;
padding: 9px 15px; color: #444; text-align: center; vertical-align: middle; cursor: pointer;
background-color: #ebebeb;
background: -webkit-linear-gradient(top, #fff 1px, #f9f9f9 1px, #ebebeb);
background: linear-gradient(to bottom, #fff 1px, #f9f9f9 1px, #ebebeb);
border: 1px solid #b9bbbd; border-radius: 3px; *zoom: 1;
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.7), 0 1px 2px rgba(0, 0, 0, 0.08);
transition: all 0.4s ease 0s;outline: none;font-size: 14px; font-weight: bold; line-height: 18px; text-decoration: none; }
#buddypress .activity-list li.load-more a:hover {box-shadow:0 -50px 0 0 rgba(255,255,255,0.15) inset;}
#buddypress .activity-list li.loading a{box-shadow: inset 0 6px 12px rgba(218, 218, 218, 0.8), 0 1px 2px rgba(0, 0, 0, 0.09); }
#buddypress .activity-list li.load-newest a{color:#4d4d4d}
#buddypress .activity-meta-justicons{ position: absolute; top: -10px; right: 10px}
#buddypress .activity-meta-justicons a{text-align:center; text-decoration:none; display:inline-block; color:#fff; position:relative; border-radius: 50%;font-size: 0;background-color: #888;height: 28px;width: 28px;padding: 0;line-height: 28px; margin: 0 3px; box-shadow: 0 2px 2px #ddd;}
#buddypress .activity-meta-justicons a:before{font-family: FontAwesome; font-size: 16px}
#buddypress .activity-meta-justicons a.acomment-reply:before, #buddypress .activity-meta-justicons a.acomment-see:before{content: "\f27a"}
#buddypress .activity-meta-justicons a span{background: #cc0000; position: absolute; top: -1px; right: -1px; text-align: center;font-size: 10px;line-height: 12px;padding: 0 3px; border-radius: 8px}
#buddypress .activity-meta-justicons a.fav:before{content: "\f08a"; font-size: 14px}
#buddypress .activity-meta-justicons a.unfav:before{content: "\f004"; font-size: 14px}
#buddypress .activity-meta-justicons a:hover{background: #111}
#buddypress .activity-meta-justicons a.delete-activity:before{content: "\f00d"}
.gmw-fl-activity-map-marker{margin: 0 5px 0 0;}
#buddypress .activity-meta-justicons a.acomment-reply, #buddypress .activity-meta-justicons a.acomment-see {background: #7593d8;}
#buddypress .activity-meta-justicons a.fav, #buddypress .activity-meta-justicons a.unfav {background: #cc0000;}
#buddypress .activity-header a{font-weight: bold;}
#buddypress .activity-list .activity-content blockquote{margin:0px 10px 5px 0;overflow:hidden}
#buddypress .activity-list li.new_forum_post .activity-content .activity-inner,#buddypress .activity-list li.new_forum_topic .activity-content .activity-inner{border-left:2px solid #eaeaea;margin-left:5px;padding-left:10px}
#buddypress .activity-inner > p{word-wrap:break-word}
#buddypress .activity-inner > .activity-inner{margin:0}
#buddypress .activity-inner > blockquote{margin:0}
#buddypress .activity-list .activity-content img.thumbnail{border:2px solid #eee;float:left;margin:0 10px 5px 0}
#buddypress .activity-read-more{margin-left:.6em;white-space:nowrap}
#buddypress div.activity-inner{margin: 0 0 18px 0}
#buddypress div.activity-inner img{margin: 12px 0}
#buddypress div.activity-meta a{color:#444;font-size:11px;font-weight:bold;text-transform:uppercase;margin:0 10px 0 0;background:none;padding: 4px 10px;}
#buddypress div.activity-meta a:hover{color:#333;}
#buddypress div.activity-meta a:hover span, #buddypress #reply-title small a a:hover span{background:#333;}
#buddypress a.activity-time-since{color: rgba(0,39,59,.35);text-decoration:none}
#buddypress a.activity-time-since:hover{color:#333;text-decoration:none}
#buddypress div.activity span.time-since{font-size:80%;display:block}
#buddypress a.bp-primary-action span,#buddypress #reply-title small a span{position:relative;color:#fff;font-size:10px;line-height:10px;font-weight:bold;padding:1px 4px;margin-left:2px;background:#999;border:0;border-radius:0;opacity:1}
#buddypress a.bp-primary-action:hover span,#buddypress #reply-title small a:hover span{background:#555;color:#fff}
#buddypress a.bp-primary-action span:before, #buddypress #reply-title small a span:before{position:absolute;content:" ";left:-3px;top:50%;margin-top:-5px;width:0;height:0;border-style:solid;border-width:5px 5px 5px 0;border-color:transparent #999 transparent transparent;}
#buddypress a.bp-primary-action:hover span:before, #buddypress #reply-title small a:hover span:before{border-color:transparent #5b4141 transparent transparent;}
#buddypress div.activity-comments{margin:0 0 0 75px;overflow:hidden;position:relative;width:auto;clear:both}
#buddypress div.activity-comments > ul{margin-top:20px;padding:0;}
#buddypress div.activity-comments ul,#buddypress div.activity-comments ul li{border:none;list-style:none}
#buddypress div.activity-comments ul{clear:both;}
#buddypress div.activity-comments ul li > ul{margin:20px 0 0 35px;}
#buddypress div.activity-comments div.acomment-avatar img{border-width:1px;float:left;height:25px;margin-right:10px;width:25px}
#buddypress div.activity-comments div.acomment-content{font-size:inherit;margin:5px 0 0 40px}
#buddypress div.acomment-content .time-since,#buddypress div.acomment-content .activity-delete-link,#buddypress div.acomment-content .comment-header{display:none}
#buddypress div.activity-comments div.acomment-meta{font-size:100%; color: rgba(0,39,59,.35);line-height:inherit}
#buddypress div.activity-comments form.ac-form{display:none;padding:10px}
#buddypress div.activity-comments li form.ac-form{margin:0 0 35px 40px;padding:0;clear:both}
#buddypress div.activity-comments form.root{margin-left:0}
#buddypress div.activity-comments div#message{margin-top:15px;margin-bottom:0}
#buddypress div.activity-comments form .ac-textarea textarea{background:#fff;border:1px solid #ddd;margin-bottom:5px;padding:8px}
#buddypress div.activity-comments form .ac-textarea textarea:focus{border-color:#aaa;}
#buddypress div.activity-comments form textarea{border:none;background:transparent;box-shadow:none;outline:none;color:#555;font-family:inherit;font-size:100%;height:60px;padding:0;margin:0;width:100%}
#buddypress div.activity-comments form input{margin-top:5px}
#buddypress div.activity-comments form div.ac-reply-avatar{float:left}
#buddypress div.activity-comments form div.ac-reply-content{color:#888;margin-left:70px;padding-left:15px}
#buddypress div.activity-comments form div.ac-reply-content a{text-decoration:none}
#buddypress div.ac-reply-avatar img{border:1px solid #eee}
#buddypress .acomment-options{margin:0 0 0 38px}
#buddypress .acomment-options a{color:#aaa; font-size: 12px}
#buddypress .acomment-options a:hover{color:inherit}
#bprh-full-header{padding: 50px 20px 30px 20px; position: relative; color: #fff; z-index: 2;}
#bprh-full-header h1{color: #fff; text-shadow: 0 0 1px #999}
#buddypress div#group-dir-search,
#buddypress div#groups-dir-search,
#buddypress div#members-dir-search {float: none;text-align: center;margin: 30px auto; width: 50%}
#search-members-form, #search-groups-form {position: relative;}
#buddypress .dir-search input[type="submit"]{position:absolute; display:inline-block; top:0; right:0; font-size: 15px; line-height: 20px; box-shadow:none !important; padding: 15px 35px; }
#buddypress .dir-search input[type=text] {width: 100%;padding: 15px 120px 15px 15px; font-size: 16px; line-height: 18px; min-width: 280px}
#buddypress .dir-search label.bp-screen-reader-text{display: none;}
#buddypress .groups-members-search input[type="submit"], #buddypress div.message-search input[type="submit"]{display: none;}
#buddypress .groups-members-search input[type=text], #buddypress div.message-search input[type=text]{width: 100%;padding: 10px 50px 10px 10px; font-size: 15px; line-height: 18px; min-width: 280px}
#buddypress .groups-members-search label:after {position: absolute;display: inline-block;top: 10px;right: 12px;content: '\f002';font: normal normal normal 16px/1 fontawesome;line-height: 18px;}
#buddypress div.message-search label{display: none;}
#buddypress .current-member-type{font-style:italic}
#buddypress .dir-form{clear:both}
#buddypress div#message{margin:0 0 35px}
#buddypress #message.info{margin-bottom:0}
#buddypress div#message.updated{clear:both;display:block}
#buddypress div#message p,#sitewide-notice p{position:relative;display:block;font-size:inherit;text-align:center;color:#ad8643;margin:1em 0;padding:1em 4em;box-shadow:0 0 1px rgba(0,0,0,0.35) inset;background:#fbeed5;border:0 !important;}
#buddypress div#message.error p{background-color:#fdc;border:1px solid #a00;clear:left;color:#800}
#buddypress div#message.warning p{background-color:#ffe0af;border:1px solid #ffd087;clear:left;color:#800}
#buddypress div#message.updated p{color:#468847;background:#dff0d8;border:1px solid #591}
#buddypress #pass-strength-result{background-color:#eee;border-color:#ddd;border-style:solid;border-width:1px;display:none;margin:5px 5px 5px 0;padding:5px;text-align:center;width:150px}
#buddypress .standard-form #basic-details-section #pass-strength-result{width:35%}
#buddypress #pass-strength-result.error,#buddypress #pass-strength-result.bad{background-color:#ffb78c;border-color:#ff853c!important;display:block}
#buddypress #pass-strength-result.good{background-color:#ffec8b;border-color:#fc0!important;display:block}
#buddypress #pass-strength-result.short{background-color:#ffa0a0;border-color:#f04040!important;display:block}
#buddypress #pass-strength-result.strong{background-color:#c3ff88;border-color:#8dff1c!important;display:block}
#buddypress div.accept,#buddypress div.reject{float:left;margin-left:10px}
#buddypress ul.button-nav li{float:left;margin:0 10px 10px 0;list-style:none}
#buddypress ul.button-nav li.current a{font-weight:700}
#sitewide-notice #message{left:2%;position:fixed;top:1em;width:96%;z-index:9999}
#sitewide-notice.admin-bar-on #message{top:3.3em}
#sitewide-notice strong{display:block;margin-bottom:-1em}
#buddypress label{font-size: 14px}
#buddypress .drag-drop-buttons label{display: block;}
.bp-user .profile .editfield{margin: 0 0 28px 0}
#buddypress .standard-form > label:first-child{margin-top:0}
#buddypress .standard-form#signup_form div div.error{background:#faa;color:#a00;margin:0 0 10px;padding:6px;width:100%}
#buddypress .standard-form select{width: 100%; padding: 9px; border: 1px solid #ddd}
#buddypress .standard-form input[type=password]{margin-bottom:15px}
#buddypress .standard-form #pass2{margin-top: 10px}
#buddypress .standard-form label:not(.bp-screen-reader-text), #buddypress .standard-form span.label, #buddypress .standard-form legend{display:block;font-weight:700;margin: 15px 0 4px 0;width:auto; font-size: 16px}
#buddypress .standard-form p label,#buddypress .standard-form #invite-list label{font-weight:400;margin:auto}
#buddypress .standard-form label.bp-screen-reader-text{line-height: 14px;display: block; margin:5px 0;}
#buddypress .standard-form div.checkbox label:nth-child(n+2),#buddypress .standard-form div.radio div label{color:#888;font-size:100%;font-weight:400;margin:5px 0 0}
#buddypress .standard-form#sidebar-login-form label{margin-top:5px}
#buddypress .standard-form input[type=text]{width:100%}
#buddypress .standard-form#sidebar-login-form input[type=text],#buddypress .standard-form#sidebar-login-form input[type=password]{padding:4px;width:95%}
#buddypress .standard-form #basic-details-section input[type=password],#buddypress .standard-form #blog-details-section input#signup_blog_url{width:35%}
#buddypress .re-form-input, #buddypress .standard-form#signup_form input[type=text],#buddypress .standard-form#signup_form textarea, #buddypress .standard-form#signup_form input[type=email], #buddypress .standard-form#signup_form input[type=password], #buddypress .standard-form#signup_form input[type=number]{width:100%; box-shadow: inset 0 1px 3px #ddd; font-size: 18px; padding: 12px}
#buddypress .form-allowed-tags, #buddypress #commentform input[type=text],#buddypress #commentform textarea{width: 100%}
#buddypress .re-form-group > label{font-size: 16px}
#buddypress div#signup-avatar img{margin:0 15px 10px 0}
#buddypress .standard-form textarea{width:100%;height:120px}
#buddypress .standard-form textarea#message_content{height:200px}
#buddypress .standard-form#send-reply textarea{width:97.5%}
#buddypress .standard-form p.description{font-size:90%;margin:5px 0}
#buddypress .standard-form div.submit{clear:both;padding:15px 0 0}
#buddypress .standard-form p.submit{margin-bottom:0;padding:15px 0 0}
#buddypress .standard-form#signup_form div.submit input{display:block;padding: 18px 35px; font-size: 20px; float: right;}
#buddypress .standard-form div.radio ul{margin:10px 0 15px 38px;list-style:disc}
#buddypress .standard-form div.radio ul li{margin-bottom:5px}
#buddypress .standard-form a.clear-value{display:block;margin-top:5px;outline:none}
@media (min-width: 768px){
#buddypress .standard-form #basic-details-section,#buddypress .standard-form #blog-details-section,#buddypress .standard-form #profile-details-section{float:left;width:48%}
#buddypress .standard-form #profile-details-section{float:right}
}
#buddypress .standard-form #blog-details-section,#buddypress #notifications-bulk-management{clear:left}
#buddypress a.button,#buddypress input[type=submit],#buddypress input[type=button],#buddypress input[type=reset],#buddypress ul.button-nav li a,#buddypress .generic-button a,#buddypress .comment-reply-link,a.bp-title-button, #buddypress button.submit{
background-color: #fff;
border: 1px solid #999;
color:inherit;font-size:15px;letter-spacing:0;cursor:pointer;outline:none;
padding:8px 16px;text-align:center;text-decoration:none;
font-weight: bold;
box-shadow: 0 1px 1px rgba(0, 0, 0, 0.1);
transition: all 0.4s ease;
line-height: 15px;
text-decoration: none;
display: inline-block;
color: #111;
font-weight: bold;
}
#buddypress input[type=submit], #buddypress input[type=button], #buddypress input[type=reset], #buddypress button.submit{text-transform: uppercase;}
#buddypress .comment-reply-link{padding: 1px 6px}
#buddypress a.button:hover,#buddypress a.button:focus,#buddypress input[type=submit]:hover,#buddypress input[type=button]:hover,#buddypress input[type=reset]:hover,#buddypress ul.button-nav li a:hover,#buddypress ul.button-nav li.current a,#buddypress div.generic-button a:hover,#buddypress .comment-reply-link:hover{box-shadow: inset 0 -100px 0 rgba(255, 255, 255, 0.11);color:inherit;outline:none;}
#rh-header-cover-image .generic-button a.friendship-button, #rh-header-cover-image .generic-button.not-following a{background: #66B22C;border-color: #60AE40; color: #fff !important}
#buddypress .rhbp-grid-loop .generic-button a{font-size: 14px; padding: 5px 10px}
#buddypress form.standard-form .left-menu #invite-list ul{margin:0;list-style:none}
#buddypress form.standard-form .left-menu #invite-list ul li{margin:0 2% 0 0; float: left; list-style: none;}
#buddypress form#send-invite-form{margin-top:20px}
#buddypress form.standard-form .main-column ul#friend-list h4{clear:none}
#buddypress .wp-editor-wrap a.button,#buddypress .wp-editor-wrap button,#buddypress .wp-editor-wrap input[type=submit],#buddypress .wp-editor-wrap input[type=button],#buddypress .wp-editor-wrap input[type=reset]{padding:0 8px 1px}
#buddypress a.loading,#buddypress input.loading{-webkit-animation:loader-pulsate .5s infinite ease-in-out alternate;-moz-animation:loader-pulsate .5s infinite ease-in-out alternate;border-color:#aaa}
@-webkit-keyframes loader-pulsate {
from{border-color:#aaa;-webkit-box-shadow:0 2px 8px #aaa;box-shadow:0 2px 8px #aaa}
to{border-color:#ccc;-webkit-box-shadow:0 2px 4px #f8f8f8;box-shadow:0 2px 4px #f8f8f8}
}
@-moz-keyframes loader-pulsate {
from{border-color:#aaa;-moz-box-shadow:0 2px 8px #aaa;box-shadow:0 2px 8px #aaa}
to{border-color:#ccc;-moz-box-shadow:0 2px 4px #f8f8f8;box-shadow:0 2px 4px #f8f8f8}
}
#buddypress a.loading:hover,#buddypress input.loading:hover{color:#777}
#buddypress form [disabled="disabled"]{}
#buddypress input[type="submit"].pending,#buddypress input[type="button"].pending,#buddypress input[type="reset"].pending,#buddypress input[type="submit"].disabled,#buddypress input[type="button"].disabled,#buddypress input[type="reset"].disabled,#buddypress input[type="submit"][disabled=disabled],#buddypress button.pending,#buddypress button.disabled,#buddypress div.pending a,#buddypress a.disabled{border-color:#eee;cursor:default}
#buddypress input[type="submit"]:hover.pending,#buddypress input[type="button"]:hover.pending,#buddypress input[type="reset"]:hover.pending,#buddypress input[type="submit"]:hover.disabled,#buddypress input[type="button"]:hover.disabled,#buddypress input[type="reset"]:hover.disabled,#buddypress button.pending:hover,#buddypress button.disabled:hover,#buddypress div.pending a:hover,#buddypress a.disabled:hover{border-color:#eee;color:#bbb}
#rtmedia_create_new_album{text-shadow: none;font-size:inherit;padding:10px 20px;color:#fff !important;text-transform:uppercase;height:auto!important;outline:0!important; cursor: pointer;}
#buddypress ul#topic-post-list{margin:0;width:auto}
#buddypress ul#topic-post-list li{padding:15px;position:relative}
#buddypress ul#topic-post-list li.alt{background:#f5f5f5}
#buddypress ul#topic-post-list li div.poster-meta{color:#888;margin-bottom:10px}
#buddypress ul#topic-post-list li div.post-content{margin-left:54px}
#buddypress div.topic-tags{font-size:80%}
#buddypress div.admin-links{color:#888;font-size:80%;position:absolute;top:15px;right:25px}
#buddypress div#topic-meta{margin:0;padding:5px 19px 30px;position:relative}
#buddypress div#topic-meta div.admin-links{right:19px;top:-36px}
#buddypress div#topic-meta h3{margin:5px 0}
#buddypress div#new-topic-post{display:none;margin:20px 0 0;padding:1px 0 0}
#buddypress table.notifications,#buddypress table.notifications-settings,#buddypress table.profile-settings,#buddypress table.profile-fields,#buddypress table.wp-profile-fields,#buddypress table.messages-notices,#buddypress table.forum{width:100%}
#buddypress table.notifications thead tr,#buddypress table.notifications-settings thead tr,#buddypress table.profile-settings thead tr,#buddypress table.profile-fields thead tr,#buddypress table.wp-profile-fields thead tr,#buddypress table.messages-notices thead tr,#buddypress table.forum thead tr{background:#eaeaea}
#buddypress table#message-threads{clear:both;border: 1px solid #eee;}
#buddypress table#message-threads .thread-from .bp-screen-reader-text{padding: 4px 8px;background: #eee;display: inline-block;clear: both;font-size: 80%;line-height: 14px;}
#buddypress table#message-threads .thread-from .activity{display: block; line-height: 14px}
#buddypress table.profile-fields{margin-bottom:20px; border: 1px solid #e5e5e5;}
#buddypress table.profile-fields p{margin:0}
#buddypress table.profile-fields p:last-child{margin-top:0}
#buddypress table.notifications tr td,#buddypress table.notifications-settings tr td,#buddypress table.profile-settings tr td,#buddypress table.profile-fields tr td,#buddypress table.wp-profile-fields tr td,#buddypress table.messages-notices tr td,#buddypress table.forum tr td,#buddypress table.notifications tr th,#buddypress table.notifications-settings tr th,#buddypress table.profile-fields tr th,#buddypress table.wp-profile-fields tr th,#buddypress table.messages-notices tr th,#buddypress table.forum tr th{padding:8px;vertical-align:middle;background-color: #f4f4f4;}
#buddypress #groups-notification-settings{margin-bottom:0}
#buddypress table.profile-settings tr td,#buddypress table.profile-fields tr td{background: #fff; font-size: 95%}
#buddypress table.notifications tr td.label,#buddypress table.notifications-settings tr td.label,#buddypress table.profile-fields tr td.label,#buddypress table.wp-profile-fields tr td.label,#buddypress table.messages-notices tr td.label,#buddypress table.forum tr td.label{border-right:1px solid #eaeaea;font-weight:700;width:25%}
#buddypress #message-threads .thread-info{min-width:40%}
#buddypress table tr td.thread-info p{margin:0}
#buddypress table tr td.thread-info p.thread-excerpt{color:#888;font-size:80%;margin-top:3px}
#buddypress table.forum td{text-align:center}
#buddypress table.notifications tr.alt td,#buddypress table.notifications-settings tr.alt td,#buddypress table.profile-settings tr.alt td,#buddypress table.profile-fields tr.alt td,#buddypress table.wp-profile-fields tr.alt td,#buddypress table.messages-notices tr.alt td,#buddypress table.forum tr.alt td{background:#f5f5f5}
#buddypress table.notification-settings{margin-bottom:20px;text-align:left}
#buddypress table.notifications th.icon,#buddypress table.notifications td:first-child,#buddypress table.notification-settings th.icon,#buddypress table.notification-settings td:first-child{display:none}
#buddypress table.notification-settings th.title, #buddypress table.profile-settings th.title{width:80%;padding:8px; font-weight: bold;}
#buddypress table.profile-settings select{margin: 6px 0; padding: 4px}
#buddypress table.notification-settings .yes,#buddypress table.notification-settings .no{text-align:center;width:40px}
#buddypress table.notification-settings thead{background:#e6e6e6}
#buddypress table.notification-settings tr th{padding:8px;font-weight:600}
#buddypress table.notification-settings td{padding:2px 5px;vertical-align: middle;}
#buddypress table.forum, #buddypress table.messages-notices, #buddypress table.notifications, #buddypress table.notification-settings, #buddypress table.profile-fields, #buddypress table.profile-settings, #buddypress table.wp-profile-fields{width:100%;text-align:left;margin:0 0 20px;clear:both}
#buddypress table.forum tr.sticky td{font-size:110%;background:#fff9db;border-top:1px solid #ffe8c4;border-bottom:1px solid #ffe8c4}
#buddypress table.forum tr.closed td.td-title{padding-left:35px}
#buddypress table.forum td p.topic-text{color:#888;font-size:100%}
#buddypress table.forum tr > td:first-child,#buddypress table.forum tr > th:first-child{padding-left:15px}
#buddypress table.forum tr > td:last-child,#buddypress table.forum tr > th:last-child{padding-right:15px}
#buddypress table.forum tr th#th-title,#buddypress table.forum tr th#th-poster,#buddypress table.forum tr th#th-group,#buddypress table.forum td.td-poster,#buddypress table.forum td.td-group,#buddypress table.forum td.td-title{text-align:left}
#buddypress table.forum tr td.td-title a.topic-title{font-size:110%}
#buddypress table.forum td.td-freshness{white-space:nowrap}
#buddypress table.forum td.td-freshness span.time-since{font-size:11px;font-weight:normal;color:inherit;opacity:0.7}
#buddypress table.forum td.td-freshness span.time-since:before{content:' ';display:block;}
#buddypress table.forum td img.avatar{float:none;margin:0 5px -8px 0}
#buddypress table.forum td.td-poster,#buddypress table.forum td.td-group{min-width:140px}
#buddypress table.forum th#th-title{width:80%}
#buddypress table.forum th#th-freshness{width:25%}
#buddypress table.forum th#th-postcount{width:15%}
#buddypress table.forum p.topic-meta{font-size:80%;margin:5px 0 0}
#buddypress table.forum tr td.label, #buddypress table.messages-notices tr td.label, #buddypress table.notifications tr td.label, #buddypress table.notifications-settings tr td.label, #buddypress table.profile-fields tr td.label, #buddypress table.wp-profile-fields tr td.label{font-weight:normal;color:#555;}
#buddypress .item-body{margin: 0 0 50px 0;}
#buddypress span.activity, #buddypress table tr td.thread-info p.thread-excerpt, .buddypress.widget span.activity{font-size:11px;font-weight:400; line-height: 13px}
#buddypress span.activity, .buddypress.widget span.activity{display:inline-block;color: #bbb;}
#buddypress span.user-nicename{color:#777;display:inline-block;font-size:120%;font-weight:700}
body.groups.single-item .main-side > .title{display: none;}
#rhbp-header-profile-cont{display: table;}
#rh-header-bp-content-wrap{position: absolute;top: 50%;transform: translateY(-50%);left: 0;z-index: 2;width: 100%;padding-top: 20px; padding-bottom: 20px}
#rh-header-bp-avatar{width: 140px; margin: 0 0 20px 0;}
#rh-header-bp-avatar > img{margin: auto; width: 140px; height: 140px;border: solid 4px #FFF; vertical-align: middle; text-align: center; position: relative;display: table-cell; }
#rh-header-bp-avatar, #rh-header-bp-content, #rh-header-bp-content-btns, #rh-bp-profile-stats{display: table-cell; vertical-align: middle;box-sizing: content-box; -webkit-box-sizing: content-box;}
#rh-header-bp-content{padding: 0 32px}
#rh-bp-profile-stats{width: 150px; border: 1px solid #8b8b8b; border-top:none; border-bottom: none; padding: 0 20px;}
#rh-header-bp-content-btns{padding-left: 25px; vertical-align: middle; width: 200px}
#rh-header-bp-content-btns #item-buttons{}
#rh-bp-profile-stats span{float: right;}
#rh-bp-profile-stats div {margin-bottom: 5px;}
#rh-cover-image-container{position:relative;z-index:0}
#rh-nocover-image-container{position:relative;padding: 35px 0 20px 0;}
#rh-header-bp-content-wrap h2 {margin:0 0 10px 0; font-size: 24px;line-height: 26px;}
#rh-header-bp-content-wrap div#item-meta{font-size:1em;color:inherit;}
#rh-header-bp-content-wrap div#item-meta p{margin: 15px 0;}
#rh-header-cover-image{transform-style: preserve-3d;min-height: 280px;background-color:#ffffff;background-position:center center;background-repeat:no-repeat;background-size:cover;border:0;display:block;margin:0;position:relative;width:100%;z-index:1; }
.header-cover-image-mask{width: 100%;height: 100%;position: absolute;top: 0;left: 0;right: 0;bottom: 0;background: -moz-linear-gradient(top,rgba(0,0,0,0.32) 35%,rgba(0,0,0,0.65) 100%);background: -webkit-gradient(linear,left top,left bottom,color-stop(35%,rgba(0,0,0,0.32)),color-stop(100%,rgba(0,0,0,0.65)));background: -webkit-linear-gradient(top,rgba(0,0,0,0.32) 35%,rgba(0,0,0,0.65) 100%);background: -o-linear-gradient(top,rgba(0,0,0,0.32) 35%,rgba(0,0,0,0.65) 100%);background: -ms-linear-gradient(top,rgba(0,0,0,0.32) 35%,rgba(0,0,0,0.65) 100%);background: linear-gradient(to bottom,rgba(0,0,0,0.32) 35%,rgba(0,0,0,0.65) 100%)}
#bprh-full-header-image{min-height: 260px;background:url("../../images/swirl_pattern.png") repeat scroll left top #fff; position:relative;width:100%;z-index:1; }
#rh-item-admins{text-align: right;position: absolute;top: 0;right: 5px;z-index: 5}
#rh-item-admins .admin-groups{float: left;font-size: 70%;margin: 0 4px;}
#buddypress div#item-header div#message.info{line-height:80%}
#buddypress div#item-header ul hr{display:none}
#rh-item-admins .group-list-admins{margin: 8px 6px; float: left;}
#rh-item-admins .group-list-admins ul li{margin:0 2px;list-style:none; display: inline-block;}
#rh-item-admins .group-list-admins ul{float: left;}
#rh-item-admins .group-list-admins img{height:20px;width:20px; vertical-align: middle;}
#buddypress span.highlight{font-size:13px;background:none;padding:0;margin-right:5px;text-decoration:none;}
#rh-cover-image-container #rh-header-bp-content-wrap a, #rh-cover-image-container #rh-header-bp-content-wrap h2, #rh-cover-image-container #rh-header-bp-content-wrap h2 a, #rh-cover-image-container #rh-item-admins .admin-groups{color: #fff}
#rh-cover-image-container #rh-header-bp-content-wrap .generic-button a{color: #111}
#rh-cover-image-container #rh-header-bp-content-wrap{color: #ededed}
#rh-cover-image-container .last-activity-profile, #rh-cover-image-container #rh-bp-profile-stats{color: #ededed}
#rh-cover-image-container .last-activity-profile{font-size: 13px; font-style: italic;}
#rh-header-bp-content-wrap div#item-meta .bp_user_about_details{font-size: 16px}
#rh-cover-image-container #rh-bp-profile-stats{vertical-align: middle;}
#rh-cover-image-container .last-activity-profile span, #rh-cover-image-container #rh-bp-profile-stats span{color: #fff}
#rh-cover-image-container #rh-header-bp-content-wrap div#item-meta p, #rh-cover-image-container #rh-header-bp-content-wrap h2{text-shadow: 0 1px 1px #555;}
#rh-cover-image-container #rh-header-bp-avatar img{box-shadow: 0 1px 3px #777;}
#rh-cover-image-container #rh-item-admins .admin-groups{text-shadow: 0px 0px 3px rgba( 0, 0, 0, 0.8 )}
.rh-profile-achievements{margin: 15px 0}
.bp_user_phone_details{display: inline-block;background: #e9e9e9;padding: 4px 8px;color: #111;text-shadow: none;border-radius: 100px;margin: 0 8px;font-size: 14px;line-height: 14px; vertical-align: top;}
#rh-header-bp-content-btns .generic-button{display: block; margin: 0 0 10px 0;}
#rh-header-bp-content-btns .generic-button a{display: block;}
#rh-header-cover-image .social_icon {display: inline-block;}
#rh-header-cover-image .social_icon .share-link-image{background: transparent; margin: 0 5px;}
#rh-bp-profile-stats .rh-star-ajax strong{color: #ededed}
#rh-bp-profile-stats .rh-star-ajax span {float: none;}
#rh-bp-profile-stats .title_star_ajax .userrating-score{float: right; color: #fff}
#rh-bp-profile-stats .title_star_ajax small{display: none;}
#rh-bp-profile-stats .user-rate{ float: none; margin: 10px 0; }
#item-body h2{margin-top:0;}
.item-list .item-title a{color: #111}
#buddypress #groups-list .hidden{display:inherit!important;visibility:visible!important}
#buddypress #groups-list .item{padding:20px 20px 0; min-height: 120px; overflow: hidden;}
#buddypress #groups-list .item-avatar .member-count {
border:1px solid #fff;display:inline-block;font-size:11px;line-height:17px;padding:0 6px;position:absolute;right:1px;top:1px;color:#fff;background-color:#777
}
#buddypress .rhbp-grid-loop #groups-list .item-title, #buddypress .rhbp-grid-loop #members-list .item-title{font-size:17px;font-weight:700;width:100%}
#buddypress #groups-list .item-desc{margin:10px 0}
#buddypress #groups-list li div.action{position:relative;text-align:center;margin:0;top:inherit;text-transform:uppercase}
#buddypress #groups-list li div.action .generic-button{display:inline-block;margin: 2px 25px;}
#buddypress #group-list li{border-bottom:1px solid #e5e5e5}
#buddypress #group-list div.action .button{height:30px!important;line-height:30px!important;display:inline-block;font-size:11px;text-transform:uppercase}
#buddypress div#item-nav{display:block;width:100%;text-align:center}
#buddypress div#item-nav li{position:relative}
#buddypress div#item-nav li:last-child{border-right:none}
#buddypress div#item-nav ul li.loading a {background-position:88% 50%;}
#buddypress div#item-nav ul li a{padding:15px 20px;font-size:12px;text-transform:uppercase;font-family:inherit;font-weight:400; line-height: 20px}
#buddypress div#item-nav ul li a:hover{color:#555}
#buddypress div#item-nav ul li a:before{font:240% fontawesome;content:"\f13a";display:block;text-align:center;transition:all .2s ease-in-out 0s}
#buddypress div#item-nav ul li a span{position:absolute;top:10px;left:52%;z-index:12}
#buddypress div#item-nav ul #activity-personal-li a:before,#buddypress div#item-nav ul #home-groups-li a:before{content:"\f0ca"}
#buddypress div#item-nav ul #xprofile-personal-li a:before{content:"\f2c3"}
#buddypress div#item-nav ul #notifications-personal-li a:before{content:"\f0a2"}
#buddypress div#item-nav ul #messages-personal-li a:before{content:"\f003"}
#buddypress div#item-nav ul #friends-personal-li a:before, #buddypress div#item-nav ul #members-following-personal-li a:before, #buddypress div#item-nav ul #members-followers-personal-li a:before{content:"\f0c0"}
#buddypress div#item-nav ul #groups-personal-li a:before{content:"\f1c0"}
#buddypress div#item-nav ul #forums-personal-li a:before,#buddypress div#item-nav ul #nav-forum-groups-li a:before{content:"\f0e6"}
#buddypress div#item-nav ul #buddydrive-personal-li a:before,#buddypress div#item-nav ul #nav-buddydrive-groups-li a:before{content:"\f01c"}
#buddypress div#item-nav ul #media-personal-li a:before,#buddypress div#item-nav ul #rtmedia-media-nav-groups-li a:before{content:"\f144"}
#buddypress div#item-nav ul #settings-personal-li a:before,#buddypress div#item-nav ul #admin-groups-li a:before{content:"\f013"}
#buddypress div#item-nav ul #members-groups-li a:before{content:"\f0c0"}
#buddypress div#item-nav ul #invite-groups-li a:before{content:"\f1d8"}
#buddypress div#item-nav ul #achievements-personal-li a:before{content:"\f0a3"}
#buddypress div#item-nav ul #blogs-personal-li a:before{content:"\f24d"}
#buddypress div#item-nav ul #posts-personal-li a:before{content:"\f24d"}
#buddypress div#item-nav ul #products-personal-li a:before{content:"\f290"}
#buddypress div#item-nav ul #articles-personal-li a:before{content:"\f1c2"}
#buddypress div#item-nav ul #location-personal-li a:before, #buddypress div#item-nav ul #nav-gmw-group-location-groups-li a:before {content:"\f041"}
#buddypress div#item-nav ul #orders-personal-li a::before{content:"\f07a"}
#buddypress div#item-nav ul #nav-products-groups-li a:before{content:"\f290";}
#buddypress div#item-nav ul #hiddenposts-personal-li, #buddypress div#item-nav ul #hiddenproducts-personal-li{display: none;}
#buddypress div#item-nav ul li.loading a{background-position:88% 50%}
#xprofile-in-bpprofile li{clear: both;overflow: hidden;padding: 5px 0 5px 10px;line-height: 24px;border-bottom: 1px solid #eee;}
#xprofile-in-bpprofile li:last-child{border: none;}
#rhbp-iconed-menu{background-color: #f1f1f1;background: -webkit-linear-gradient(top, #fff 1px, #f9f9f9 1px, #ebebeb);background: linear-gradient(to bottom, #fff 1px, #f9f9f9 1px, #ebebeb);}
#rhbp-iconed-menu ul{overflow: hidden; margin:0;}
#buddypress #rhbp-iconed-menu div.item-list-tabs{border: none; background: none transparent}
#buddypress div.item-list-tabs ul li {margin: 0;list-style:none; flex: none; float: left;}
#buddypress div.item-list-tabs ul.rhgreedylinks li{float: none;}
#buddypress .activity-list li.loading a:before, .generic-button.loading a:before, #buddypress div.item-list-tabs ul li.loading a:before, #buddypress input[type="submit"].loading:before{font-size:12px; color:#aaa; display:inline-block; content: "\f110" !important; font-family: FontAwesome; -webkit-animation: fa-spin 1s linear infinite; -moz-animation: fa-spin 1s linear infinite; -o-animation: fa-spin 1s linear infinite; animation: fa-spin 1s linear infinite; margin: 0 3px}
#buddypress .generic-button.loading a.friendship-button:before{color: #fff}
#buddypress div.item-list-tabs ul{margin: 0; overflow: hidden; }
#buddypress div.item-list-tabs ul li.last select, #buddypress form#whats-new-form #whats-new-options select, #buddypress form#notifications-bulk-management div.notifications-options-nav select, #buddypress select#messages-select{max-width:185px;padding:5px;border: 1px solid #ddd;color: #777;}
#buddypress div.item-list-tabs ul li a, #buddypress div.item-list-tabs ul li span{display: block;padding: 5px 10px 15px 10px;text-decoration: none;}
#buddypress div.item-list-tabs ul li a{color:#444;transition:all .2s ease-in-out 0s}
#buddypress div.item-list-tabs ul li a:hover{background-color:#fff;color:#111}
#buddypress div.item-list-tabs ul li a span{background:#66B22C;border-radius:10px;border:none;color:#fff;display:inline-block;font-size:11px;line-height:17px;margin-left:4px;padding:0 6px;text-align:center;vertical-align:middle}
#buddypress div.item-list-tabs ul li a span.unread-count{padding:1px 6px;color:#fff}
#buddypress div.item-list-tabs ul li a:hover span{background-color:#666}
#buddypress div.item-list-tabs ul li.feed{display:none}
#buddypress div.item-list-tabs ul li.selected a,#buddypress div.item-list-tabs ul li.current a{background-color: #fff;color: #111;font-weight: bold;}
#buddypress div.item-list-tabs ul li.selected a span,#buddypress div.item-list-tabs ul li.current a span{background-color: #66B22C;border: none;color: #fff;}
#buddypress div.item-list-tabs#object-nav{margin-top:0}
#buddypress div.item-list-tabs#subnav{margin: 0;overflow: hidden}
#buddypress .separate-item-bp-nav div.item-list-tabs#subnav{}
#buddypress div.item-list-tabs#subnav ul li{margin:0 0 25px 0;; float: left;}
#buddypress div.item-list-tabs#subnav ul li.last{float:right;margin: 7px 0 25px 10px}
#buddypress div.item-list-tabs#subnav ul li.last label{height:30px;line-height:30px;margin-right:10px}
#buddypress div.item-list-tabs#subnav ul li a{margin:0 10px 0 0;padding:5px 12px;transition:all .2s ease-in-out 0s}
.no_bg_wrap #buddypress div.item-list-tabs, .no_bg_wrap #buddypress div.item-list-tabs#subnav{ border-color: #c0c0c0 }
#buddypress ul.single-line li{border:none}
#buddypress .rhbp-grid-loop #admins-list li,
#buddypress .rhbp-grid-loop #groups-list li,
#buddypress .rhbp-grid-loop #mods-list li,
#buddypress .rhbp-grid-loop #members-list li,
#buddypress .rhbp-grid-loop #member-list li,
#buddypress .rhbp-grid-loop #friend-list li {
border-top: 1px solid #f4f4f4;
box-shadow: rgba(0,0,0,0.15) 0px 1px 2px;
background: #fff;
}
#buddypress #friend-list .friend-inner-list,
#buddypress #groups-list .group-inner-list,
#buddypress #member-list .member-inner-list,
#buddypress #members-list .member-inner-list {
padding:70px 0 20px;display:inline-block;width:100%;text-align:center;background-position:center top;background-repeat:no-repeat;background-image:linear-gradient(to bottom,rgba(0,0,0,0.08) 120px,rgba(0,0,0,0) 0)
}
.store_member_in_m_loop{font-size: 80%; margin: 0 0 10px 0 }
.store_member_in_m_loop_l{opacity: 0.6}
#buddypress #groups-list .group-no-avatar .group-inner-list{padding-top:120px; }
#buddypress .rhbp-grid-loop #friend-list li .item-avatar img,
#buddypress .rhbp-grid-loop #groups-list li .item-avatar img,
#buddypress .rhbp-grid-loop #member-list li .item-avatar img,
#buddypress .rhbp-grid-loop #members-list li .item-avatar img {
margin:0;border-radius:0;-webkit-border-radius:0
}
#buddypress .rhbp-grid-loop #friend-list li div.item-avatar,
#buddypress .rhbp-grid-loop #groups-list li div.item-avatar,
#buddypress .rhbp-grid-loop #member-list li div.item-avatar,
#buddypress .rhbp-grid-loop #members-list li div.item-avatar {
float:none;position:relative;margin:0 auto;width: 55px;box-shadow: 0 0 1px 0 rgba(0,0,0,0.3), 0 1px 1px 0 rgba(0,0,0,0.1);background:#fff;padding: 2px;border-radius: 2px
}
#buddypress #friend-list .item-title,#buddypress #member-list h5,#buddypress #members-list .item-title{font-weight:bold}
#buddypress #friend-list .item-meta,#buddypress #member-list .item-meta,#buddypress #members-list .item-meta{margin: 0 0 12px 0}
#buddypress #friend-list .update,#buddypress #member-list .update,#buddypress #members-list .update{display:block;width:auto;padding:8px 15px;word-wrap:break-word;font: 14px/16px Arial;}
#buddypress .rhbp-grid-loop #friend-list div.action,#buddypress .rhbp-grid-loop #member-list div.action,#buddypress .rhbp-grid-loop #members-list div.action{clear:both;position:relative;text-align:center;margin: 0 0 18px 0}
#buddypress #friend-list div.action .generic-button,#buddypress #member-list div.action .generic-button,#buddypress #members-list div.action .generic-button{display:inline-block;margin: 2px 25px;}
#buddypress #friend-list div.action .generic-button a,#buddypress #member-list div.action .generic-button a,#buddypress #members-list div.action .generic-button a{}
#buddypress #friend-list div.action .generic-button a.send-message,#buddypress #member-list div.action .generic-button a.send-message,#buddypress #members-list div.action .generic-button a.send-message{border-style:solid;border-width:1px}
#buddypress div.item-avatar .online-status, .members-carousel .online-status{position:absolute;display:inline-block;font-size:12px;top:5px;right:-7px;color:#77b21d;border:3px solid #eee;border-radius:100%;transition:all .2s ease-in-out 0s;background:#eee}
#buddypress .rhbp-grid-loop #friend-list div.item, #buddypress .rhbp-grid-loop #members-list div.item, #buddypress .rhbp-grid-loop #member-list div.item{margin: 10px 0; /*height: 100px;*/ overflow: hidden;}
#buddypress ul#member-list .member-list-content{margin:20px 0}
#buddypress ul#member-list .member-list-content h5{margin:0;}
#buddypress #members-list .update .activity-read-more{display:block;border-top-style:solid;border-top-width:1px;color:#ddd;font-size:11px;height:10px;line-height:20px;margin-top:20px}
#buddypress #members-list .activity-read-more a{padding:0 10px;position:relative;top:9px;text-transform:uppercase}
#buddypress #item-buttons:empty{display:none}
#buddypress table#message-threads tr.unread td .thread-excerpt,#buddypress table#message-threads tr.unread td .activity,#buddypress table#message-threads tr.unread td.thread-options{font-weight:400}
#buddypress table#message-threads tr, #buddypress table#message-threads tr td, #buddypress table#message-threads tr.unread td{color:inherit;background:none;border:0; line-height: 20px;}
#buddypress li span.unread-count,#buddypress tr.unread span.unread-count{background:#b94a48;color:#fff;font-weight:700;font-size:11px;padding:2px 5px}
#buddypress div#message-thread div.message-box{margin:0;padding:15px}
#buddypress div#message-thread div.alt{background:rgba(0,0,0,.03)}
#buddypress div#message-thread p#message-recipients{margin:10px 0 20px}
#buddypress div#message-thread img.avatar{float:left;margin:0 10px 0 0;vertical-align:middle}
#buddypress div#message-thread strong{font-size:100%;margin:0}
#buddypress div#message-thread strong a{text-decoration:none}
#buddypress div#message-thread strong span.activity{margin-top:4px}
#buddypress div#message-thread div.message-metadata{overflow:hidden}
#buddypress div#message-thread div.message-content{margin-left:40px}
#buddypress div#message-thread div.message-options{text-align:right}
#buddypress #message-threads img.avatar{max-width:none}
.message-metadata{position:relative}
.message-star-actions{position:absolute;right:0;top:0}
#buddypress a.message-action-star,#buddypress a.message-action-unstar{border-bottom:0;text-decoration:none;outline:none}
a.message-action-star{opacity:.7}
a.message-action-star:hover{opacity:1}
.message-action-star span.icon:before,.message-action-unstar span.icon:before{font-family:dashicons;font-size:18px}
.message-action-star span.icon:before{color:#aaa;content:"\f154"}
.message-action-unstar span.icon:before{color:#fcdd77;content:"\f155"}
#buddypress div.profile h4{margin-bottom:auto;margin:15px 0}
#buddypress #profile-edit-form ul.button-nav{margin-top:15px}
#buddypress .field-visibility-settings{display:none;margin-top:10px}
#buddypress .current-visibility-level{font-weight:700;font-style:normal}
#buddypress .field-visibility-settings,#buddypress .field-visibility-settings-toggle,#buddypress .field-visibility-settings-notoggle{color:#555; font-size: 85%}
#buddypress .field-visibility-settings-toggle a,#buddypress .field-visibility-settings a{font-size:80%}
body.register #buddypress div.page ul{list-style:none}
#buddypress .standard-form .field-visibility-settings label{margin:0;font-weight:400}
#buddypress .standard-form .settings-input{min-width: 350px}
#buddypress .field-visibility-settings .radio{list-style:none;margin-bottom:0}
#buddypress .field-visibility select{margin:0}
#buddypress .wp-editor-container{border:1px solid #dedede}
#buddypress .html-active button.switch-html{border-bottom-color:transparent;border-bottom-left-radius:0;border-bottom-right-radius:0;background:#f5f5f5}
#buddypress .tmce-active button.switch-tmce{border-bottom-color:transparent;border-bottom-left-radius:0;border-bottom-right-radius:0;background:#f5f5f5}
#buddypress .standard-form .wp-editor-container textarea{width:100%;padding-top:0;padding-bottom:0}
.sidebar-footer #groups-list-options .selected{color:#fff}
#groups-list-options{font-size:12px;text-transform:uppercase;padding-top:0}
#groups-list-options a{font-weight:700}
#groups-list-options .selected{color:#5b4141}
#groups-list{list-style-type:none;padding:0;}
.widget.buddypress #bp-login-widget-form label{display:block;margin:0 0 10px 0; font-size: 14px}
.widget.buddypress #bp-login-widget-form #bp-login-widget-submit{margin-right:10px;padding: 6px 12px;}
.bp-login-widget-user-avatar img.avatar{height:40px;width:40px}
.widget.buddypress .bp-login-widget-user-links > div{padding-left:60px;margin-bottom:0}
.widget.buddypress .bp-login-widget-user-links > div.bp-login-widget-user-link a{font-weight:700}
.bp-widget .item-list li{padding: 25px; overflow: hidden; margin-bottom: 20px; border-top: 1px solid #f4f4f4;
box-shadow: rgba(0,0,0,0.15) 0px 1px 2px; }
.bp-widget .item-list .item-avatar, .bp-login-widget-user-avatar{float: left; width: 55px}
.bp-widget .item-list .item-avatar img{max-width: 55px}
.bp-widget .item-list .item, .bp-widget .item-list .action{margin-left: 70px}
#buddypress .bp-widget .item-list .action a{padding: 5px 10px; font-size: 14px; font-weight: normal;}
.bp-widget .item-list .item-meta{margin: 0}
.buddypress.widget li.vcard, .widget_bp_groups_widget li{padding: 0; overflow: hidden; margin: 0 0 10px 0; box-shadow: none;border: none;}
.buddypress.widget li.vcard .item-avatar, .widget_bp_groups_widget li .item-avatar{float: left; width: 30px}
.buddypress.widget li.vcard .item-avatar img, .widget_bp_groups_widget li .item-avatar img{max-width: 30px}
.buddypress.widget li.vcard .item, .widget_bp_groups_widget .group-has-avatar .item{margin-left: 42px}
.buddypress.widget li.vcard .item-meta{margin: 0}
.buddypress.widget .vendor_store_owner_contactlink{font-size: 14px}
.buddypress.widget .item-options{margin-bottom: 22px}
#buddypress fieldset{margin: 0 0 20px 0;}
.rh-show-current-list li{display: none;}
.rh-show-current-list li.current{display: block;}
.rh-show-current-list li.current a{color: #fff; font-size: 22px; text-decoration: none;}
#groups-directory-form .item-list-tabs:first-child{float: left;}
form#group-settings-form #nav-sortable li, form#group-settings-form #fields-sortable li, form#group-settings-form #pages-sortable li, form#group-settings-form #box_import_set_fields{padding: 15px !important; height: auto !important;border: 1px solid #ddd !important;}
form#group-settings-form #nav-sortable, form#group-settings-form #fields-sortable, form#group-settings-form #pages-sortable{margin: 30px 0 10px 0 !important}
form#group-settings-form hr{margin: 10px 0 30px 0}
form#group-settings-form #save{margin-top:30px;}
#buddypress table.profile-fields tr:nth-child(2n) td{background: #f4f4f4}
.item-title-bpadmin{font-weight: bold; margin-bottom: 6px;line-height: 14px;}
.item-title-bpadmin a{color: #111}
#group-create-body .left-menu .avatar{float: left;margin: 0 25px 25px 25px;}
#item-body .gpage{overflow:hidden; box-shadow: rgba(0,0,0,0.15) 0px 1px 2px;background: white;padding: 20px;position: relative;transition: .2s;border-top: 1px solid #f4f4f4; }
.rehub-register-popup .bp-screen-reader-text{display: block; margin: 5px 0}
body.registration form div#ws-plugin--s2member-custom-reg-fields-4bp-section{clear: right; margin-bottom: 20px}
#profile-details-section ul li{margin: 0 0 10px 0; list-style: none}
#profile-details-section ul{margin: 10px 0;}
body.registration form div#ws-plugin--s2member-custom-reg-fields-4bp-container{margin-right: 0 !important}
div.gmw-map-wrapper{margin-bottom: 20px}
#buddypress ul.rtmedia-list li{background: #fff;margin: 10px !important;padding: 20px !important; box-shadow: 0 0 1px #ccc; text-align: center; float: left;}
#buddypress .rtmedia-list .rtmedia-list-item{box-sizing: content-box; -webkit-box-sizing: content-box;}
#buddypress .rtmedia-gallery-item-actions{top: 0; left: 0; right: 0}
#buddypress .rtmedia-list .rtmedia-item-title h4, #buddypress .rtmedia-list .rtmedia-item-title, #buddypress .rtmedia-list .rtmedia-item-title a{margin: 15px 0 0 0 !important; font-size: 16px !important}
#buddypress div.item-list-tabs#subnav ul li a span{background: #fff; color: #111; box-shadow: 0 1px 2px #ccc;}
.rtmedia-list-item .rtmedia-album-media-count{padding: 0 6px !important; line-height: 17px; font-size: 12px}
.rtmedia-no-media-found{margin-top: 10px; opacity: 0.8; font-size: 14px}
#rtmedia-uploader-form .rtm-plupload-list li, #rtmedia_uploader_filelist li{box-shadow: 0 2px 3px #ccc; background: #f4f4f4 !important}
.rtm-tabs a{background: #fff}
.rtm-field-wrap label{display: block;}
.rtm-field-wrap #description, .rtm-field-wrap input[type="text"]{width: 100%; max-width: 500px; box-shadow: inset 0 1px 3px #ddd;}
.rtm-field-wrap #description{min-height: 180px}
.widget_bp_core_recently_active_widget .item-avatar {float: left;margin: 0 10px 10px 0;}
@media (max-width: 1023px){
#rh-header-bp-content-btns .generic-button a{padding: 13px; margin-bottom: 15px}
#rh-header-bp-content-wrap{display: block; position: relative; bottom: auto; left: auto; top: auto; right: auto; transform: none;}
#rh-header-bp-avatar, #rh-header-bp-content, #rh-header-bp-content-btns, #rh-bp-profile-stats{display: block; text-align: center;padding: 0; margin-bottom: 10px; width: 100%}
#rh-header-bp-avatar{margin: 0 auto 20px auto}
#rh-header-bp-content-btns #item-buttons{float: none; margin: 15px auto}
#rh-bp-profile-stats{text-align: left; border-top:1px solid #ccc;border-bottom:1px solid #ccc; border-left:none; border-right: none; padding: 10px 0;}
}
@media (max-width: 767px){
#buddypress div#group-dir-search, #buddypress div#groups-dir-search, #buddypress div#members-dir-search{width: 90%}
#buddypress div.activity-meta a{margin-bottom: 8px}
#buddypress .dir-search input[type=text]{min-width: 100px}
}
@media only screen and (max-width:480px ) {
#buddypress table#message-threads th{display: none;}
#buddypress table#message-threads tr, #buddypress table#message-threads tr td, #buddypress table#message-threads tr.unread td, #buddypress table#message-threads th.bulk-select-all{display: block;}
#buddypress .standard-form .settings-input{width: 100%}
a.bp-title-button{margin-left:10px}
#buddypress form.standard-form .main-column div.action{position:relative;margin-bottom:1em}
#buddypress form.standard-form .main-column ul#friend-list h4{width:100%}
}
@media only screen and (max-width:320px) {
#buddypress li#groups-order-select{clear:left;float:left}
#buddypress ul.item-list li div.item-desc{clear:left;float:left;margin:10px 0 0;width:auto}
#buddypress li div.item{margin-left:70px;width:auto}
#buddypress ul.item-list li div.meta{margin-top:0}
#buddypress .item-desc p{margin:0 0 10px}
#buddypress div.pagination .pag-count{margin-left:0}
}
@media only screen and (max-width:240px) {
#buddypress li#groups-order-select{float:left}
#buddypress ul.item-list li img.avatar{width:30px;height:auto}
h1 a.bp-title-button{clear:left;float:left;margin:10px 0 20px}
}
/* unknown */
#bp-login-widget-user-login,#bp-login-widget-user-pass{color:#56646f;margin-bottom:14px;padding:6px 10px; width: 100%}
#sidebar-secondary #bp-login-widget-user-login,#sidebar-secondary #bp-login-widget-user-pass{width:156px}
.forgetmenot{margin-bottom:10px}
#members-list-options{font-size:12px;text-transform:uppercase;padding-top:0}
#members-list-options a{font-weight:700; opacity: 0.6}
#members-list-options .selected{opacity: 1}
#members-list{list-style-type:none;padding:0}
#friends-list-options{font-size:12px;text-transform:uppercase;padding-top:0}
#friends-list-options a{font-weight:700}
#friends-list-options .selected{color:#5b4141}
#friends-list{list-style-type:none;margin:0;padding:0}
li.friend-tab img.avatar {margin: 0 4px;}
/* Posts and Deals */
.bp-post-wrapper .wpsm_recent_posts_list .item-small-news {border-bottom: 1px solid #eee;}
.bp-post-wrapper .wpsm_recent_posts_list .temperatur{ padding: 3px 12px 0 0;display: inline-block;font-size: 24px;}
.bp-post-wrapper .wpsm_recent_posts_list h3{font-size: 18px;}
.bp-post-wrapper .wpsm_recent_posts_list .post-meta{font-size: 12px}
.bp-post-wrapper .wpsm_recent_posts_list .post-meta span{margin-right: 10px}
.bp-post-wrapper .wpsm_recent_posts_list .post-meta i{margin-right: 4px}
#buddypress ul.acfb-holder li{margin: 0 0 6px 0}
#buddypress input#send-to-input{clear: both; display: block;}
#buddypress ul.acfb-holder li.friend-tab a{text-decoration: none;}
#buddypress ul.acfb-holder li.friend-tab img{vertical-align: middle;}
.activity-avatar .rh_mycred-users-badges{text-align: right; max-width: 57px}
.activity-avatar .rh_mycred-users-badges img{border-radius: 0; width: 17px; height: 17px; margin-right:2px }
.bp-simple-post-form ul li{list-style: none;}
.bp-simple-post-form #insert-media-button{margin: 0 0 10px 0}
#buddypress .bp-simple-post-form .simple-post-tax-check-list label{margin: 2px 0}
#buddypress .comment-meta a.activity-time-since{color: #aaa}
#item-header #mycred-users-badges, #item-header #mycred-my-rank, #item-header .mycred-balance{display: none;}
#buddypress #member-list li span.rh-user-rank-mc{position: absolute;top: 10px;right: 5px;}
#buddypress #whats-new-submit #aw-whats-new-submit {font-size: 13px;line-height: 18px;padding: 6px 10px;}
#buddypress ul.rtmedia-list li{list-style: none; margin: 0 0 10px 0}
#whats-new-content #rtMedia-start-upload{margin-top: 10px}
#whats-new-form > .rtmedia-container{display: none;}
.rtmedia-activity-text{margin: 0 0 12px 0}
#buddypress .rtmedia-gallery-item-actions a:hover{color: #fff}
#gmw-your-location-wrapper div#your-location-section-inner, #gmw-your-location-wrapper form, #gmw-your-location-wrapper form .gmw-yl-tab-wrapper{padding: 15px !important}
#your-location-section-inner input[type="button"]{margin-top: 15px !important}
#gmw-your-location-wrapper form #gmw-yl-tabs li{list-style: none !important; font-size: 14px}
#gmw-your-location-wrapper form .gmw-yl-tab-wrapper table{background-color: transparent !important;}
#gmw-your-location-wrapper form .gmw-yl-tab-wrapper{background-color: #fff !important; box-sizing: border-box !important;}
#gmw-your-location-wrapper form .gmw-yl-tab-wrapper table tr td{padding: 5px 0 !important}
#gmw-your-location-wrapper form .gmw-yl-tab-wrapper table tr th{text-align: left !important;}
.adress-user-geo{font-size: 84%;background: #f2fbff;padding: 20px 10px;border-top: 1px solid #ddd;padding-top: 10px;line-height: 20px;color: #666;}
#buddypress #members-list.geowp-item-list .member-inner-list{padding-bottom: 90px}
#buddypress #members-list.geowp-item-list .member-inner-list .adress-user-geo{position: absolute; bottom: 0}
.geo-pagination{margin: 15px 0; color: #777; font-size: 90%; overflow: hidden;}
.distance-to-user-geo{margin: 12px 0}
.distance-to-user-geo i{color: #999}
#gmw-your-location-wrapper div#your-location-section {background: #F8F8F8 !important;border: #d8d8d8 solid 1px !important;}
#gmw-your-location-wrapper div#your-location-section p{border-bottom: #d8d8d8 solid 1px !important;}
.editfield p.field-visibility-settings-toggle{margin: 0}
select#bbm-media-privacy{height: auto;}
.whats-new-post-in-box label.bp-screen-reader-text{margin: 0 10px} | {
"content_hash": "cd7268ed67d6508c99e82a2e458f6f7c",
"timestamp": "",
"source": "github",
"line_count": 673,
"max_line_length": 634,
"avg_line_length": 92.4888558692422,
"alnum_prop": 0.7802875732990602,
"repo_name": "gorkemyontem/stardomcity",
"id": "8dd2607dd5b69c4f3b0077fabb77785e0ceee98e",
"size": "62245",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "content/themes/rehub/buddypress/css/buddypress.css",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ApacheConf",
"bytes": "1516"
},
{
"name": "C",
"bytes": "68199"
},
{
"name": "CSS",
"bytes": "6400905"
},
{
"name": "HTML",
"bytes": "345058"
},
{
"name": "JavaScript",
"bytes": "7657121"
},
{
"name": "PHP",
"bytes": "37385978"
},
{
"name": "Roff",
"bytes": "15398"
},
{
"name": "Shell",
"bytes": "1081"
},
{
"name": "TypeScript",
"bytes": "32659"
}
],
"symlink_target": ""
} |
#include <znc/znc.h>
#include <signal.h>
using std::cout;
using std::endl;
using std::set;
#ifdef HAVE_GETOPT_LONG
#include <getopt.h>
#else
#define no_argument 0
#define required_argument 1
#define optional_argument 2
struct option {
const char *a;
int opt;
int *flag;
int val;
};
static inline int getopt_long(int argc, char * const argv[], const char *optstring, const struct option *, int *)
{
return getopt(argc, argv, optstring);
}
#endif
static const struct option g_LongOpts[] = {
{ "help", no_argument, 0, 'h' },
{ "version", no_argument, 0, 'v' },
{ "debug", no_argument, 0, 'D' },
{ "foreground", no_argument, 0, 'f' },
{ "no-color", no_argument, 0, 'n' },
{ "allow-root", no_argument, 0, 'r' },
{ "makeconf", no_argument, 0, 'c' },
{ "makepass", no_argument, 0, 's' },
{ "makepem", no_argument, 0, 'p' },
{ "datadir", required_argument, 0, 'd' },
{ 0, 0, 0, 0 }
};
static void GenerateHelp(const char *appname) {
CUtils::PrintMessage("USAGE: " + CString(appname) + " [options]");
CUtils::PrintMessage("Options are:");
CUtils::PrintMessage("\t-h, --help List available command line options (this page)");
CUtils::PrintMessage("\t-v, --version Output version information and exit");
CUtils::PrintMessage("\t-f, --foreground Don't fork into the background");
CUtils::PrintMessage("\t-D, --debug Output debugging information (Implies -f)");
CUtils::PrintMessage("\t-n, --no-color Don't use escape sequences in the output");
CUtils::PrintMessage("\t-r, --allow-root Don't complain if ZNC is run as root");
CUtils::PrintMessage("\t-c, --makeconf Interactively create a new config");
CUtils::PrintMessage("\t-s, --makepass Generates a password for use in config");
#ifdef HAVE_LIBSSL
CUtils::PrintMessage("\t-p, --makepem Generates a pemfile for use with SSL");
#endif /* HAVE_LIBSSL */
CUtils::PrintMessage("\t-d, --datadir Set a different ZNC repository (default is ~/.znc)");
}
static void die(int sig) {
signal(SIGPIPE, SIG_DFL);
CUtils::PrintMessage("Exiting on SIG [" + CString(sig) + "]");
CZNC::DestroyInstance();
exit(sig);
}
static void signalHandler(int sig) {
switch (sig) {
case SIGHUP:
CUtils::PrintMessage("Caught SIGHUP");
CZNC::Get().SetConfigState(CZNC::ECONFIG_NEED_REHASH);
break;
case SIGUSR1:
CUtils::PrintMessage("Caught SIGUSR1");
CZNC::Get().SetConfigState(CZNC::ECONFIG_NEED_WRITE);
break;
default:
CUtils::PrintMessage("WTF? Signal handler called for a signal it doesn't know?");
}
}
static bool isRoot() {
// User root? If one of these were root, we could switch the others to root, too
return (geteuid() == 0 || getuid() == 0);
}
static void seedPRNG() {
struct timeval tv;
unsigned int seed;
// Try to find a seed which can't be as easily guessed as only time()
if (gettimeofday(&tv, NULL) == 0) {
seed = (unsigned int)tv.tv_sec;
// This is in [0:1e6], which means that roughly 20 bits are
// actually used, let's try to shuffle the high bits.
seed ^= uint32_t((tv.tv_usec << 10) | tv.tv_usec);
} else
seed = (unsigned int)time(NULL);
seed ^= rand();
seed ^= getpid();
srand(seed);
}
int main(int argc, char** argv) {
CString sConfig;
CString sDataDir = "";
seedPRNG();
CDebug::SetStdoutIsTTY(isatty(1));
int iArg, iOptIndex = -1;
bool bMakeConf = false;
bool bMakePass = false;
bool bAllowRoot = false;
bool bForeground = false;
#ifdef ALWAYS_RUN_IN_FOREGROUND
bForeground = true;
#endif
#ifdef HAVE_LIBSSL
bool bMakePem = false;
#endif
while ((iArg = getopt_long(argc, argv, "hvnrcspd:Df", g_LongOpts, &iOptIndex)) != -1) {
switch (iArg) {
case 'h':
GenerateHelp(argv[0]);
return 0;
case 'v':
cout << CZNC::GetTag() << endl;
cout << CZNC::GetCompileOptionsString() << endl;
return 0;
case 'n':
CDebug::SetStdoutIsTTY(false);
break;
case 'r':
bAllowRoot = true;
break;
case 'c':
bMakeConf = true;
break;
case 's':
bMakePass = true;
break;
case 'p':
#ifdef HAVE_LIBSSL
bMakePem = true;
break;
#else
CUtils::PrintError("ZNC is compiled without SSL support.");
return 1;
#endif /* HAVE_LIBSSL */
case 'd':
sDataDir = CString(optarg);
break;
case 'f':
bForeground = true;
break;
case 'D':
bForeground = true;
CDebug::SetDebug(true);
break;
case '?':
default:
GenerateHelp(argv[0]);
return 1;
}
}
if (optind < argc) {
CUtils::PrintError("Specifying a config file as an argument isn't supported anymore.");
CUtils::PrintError("Use --datadir instead.");
return 1;
}
CZNC::CreateInstance();
CZNC* pZNC = &CZNC::Get();
pZNC->InitDirs(((argc) ? argv[0] : ""), sDataDir);
#ifdef HAVE_LIBSSL
if (bMakePem) {
pZNC->WritePemFile();
CZNC::DestroyInstance();
return 0;
}
#endif /* HAVE_LIBSSL */
if (bMakePass) {
CString sSalt;
CUtils::PrintMessage("Type your new password.");
CString sHash = CUtils::GetSaltedHashPass(sSalt);
CUtils::PrintMessage("Kill ZNC process, if it's running.");
CUtils::PrintMessage("Then replace password in the <User> section of your config with this:");
// Not PrintMessage(), to remove [**] from the beginning, to ease copypasting
std::cout << "<Pass password>" << std::endl;
std::cout << "\tMethod = " << CUtils::sDefaultHash << std::endl;
std::cout << "\tHash = " << sHash << std::endl;
std::cout << "\tSalt = " << sSalt << std::endl;
std::cout << "</Pass>" << std::endl;
CUtils::PrintMessage("After that start ZNC again, and you should be able to login with the new password.");
CZNC::DestroyInstance();
return 0;
}
{
set<CModInfo> ssGlobalMods;
set<CModInfo> ssUserMods;
set<CModInfo> ssNetworkMods;
CUtils::PrintAction("Checking for list of available modules");
pZNC->GetModules().GetAvailableMods(ssGlobalMods, CModInfo::GlobalModule);
pZNC->GetModules().GetAvailableMods(ssUserMods, CModInfo::UserModule);
pZNC->GetModules().GetAvailableMods(ssNetworkMods, CModInfo::NetworkModule);
if (ssGlobalMods.empty() && ssUserMods.empty() && ssNetworkMods.empty()) {
CUtils::PrintStatus(false, "");
CUtils::PrintError("No modules found. Perhaps you didn't install ZNC properly?");
CUtils::PrintError("Read http://wiki.znc.in/Installation for instructions.");
if (!CUtils::GetBoolInput("Do you really want to run ZNC without any modules?", false)) {
CZNC::DestroyInstance();
return 1;
}
}
CUtils::PrintStatus(true, "");
}
if (isRoot()) {
CUtils::PrintError("You are running ZNC as root! Don't do that! There are not many valid");
CUtils::PrintError("reasons for this and it can, in theory, cause great damage!");
if (!bAllowRoot) {
CZNC::DestroyInstance();
return 1;
}
CUtils::PrintError("You have been warned.");
CUtils::PrintError("Hit CTRL+C now if you don't want to run ZNC as root.");
CUtils::PrintError("ZNC will start in 30 seconds.");
sleep(30);
}
if (bMakeConf) {
if (!pZNC->WriteNewConfig(sConfig)) {
CZNC::DestroyInstance();
return 0;
}
/* Fall through to normal bootup */
}
CString sConfigError;
if (!pZNC->ParseConfig(sConfig, sConfigError)) {
CUtils::PrintError("Unrecoverable config error.");
CZNC::DestroyInstance();
return 1;
}
if (!pZNC->OnBoot()) {
CUtils::PrintError("Exiting due to module boot errors.");
CZNC::DestroyInstance();
return 1;
}
if (bForeground) {
int iPid = getpid();
CUtils::PrintMessage("Staying open for debugging [pid: " + CString(iPid) + "]");
pZNC->WritePidFile(iPid);
CUtils::PrintMessage(CZNC::GetTag());
} else {
CUtils::PrintAction("Forking into the background");
int iPid = fork();
if (iPid == -1) {
CUtils::PrintStatus(false, strerror(errno));
CZNC::DestroyInstance();
return 1;
}
if (iPid > 0) {
// We are the parent. We are done and will go to bed.
CUtils::PrintStatus(true, "[pid: " + CString(iPid) + "]");
pZNC->WritePidFile(iPid);
CUtils::PrintMessage(CZNC::GetTag());
/* Don't destroy pZNC here or it will delete the pid file. */
return 0;
}
/* fcntl() locks don't necessarily propagate to forked()
* children. Reacquire the lock here. Use the blocking
* call to avoid race condition with parent exiting.
*/
if (!pZNC->WaitForChildLock()) {
CUtils::PrintError("Child was unable to obtain lock on config file.");
CZNC::DestroyInstance();
return 1;
}
// Redirect std in/out/err to /dev/null
close(0); open("/dev/null", O_RDONLY);
close(1); open("/dev/null", O_WRONLY);
close(2); open("/dev/null", O_WRONLY);
CDebug::SetStdoutIsTTY(false);
// We are the child. There is no way we can be a process group
// leader, thus setsid() must succeed.
setsid();
// Now we are in our own process group and session (no
// controlling terminal). We are independent!
}
struct sigaction sa;
sa.sa_flags = 0;
sigemptyset(&sa.sa_mask);
sa.sa_handler = SIG_IGN;
sigaction(SIGPIPE, &sa, (struct sigaction*) NULL);
sa.sa_handler = signalHandler;
sigaction(SIGHUP, &sa, (struct sigaction*) NULL);
sigaction(SIGUSR1, &sa, (struct sigaction*) NULL);
// Once this signal is caught, the signal handler is reset
// to SIG_DFL. This avoids endless loop with signals.
sa.sa_flags = SA_RESETHAND;
sa.sa_handler = die;
sigaction(SIGINT, &sa, (struct sigaction*) NULL);
sigaction(SIGQUIT, &sa, (struct sigaction*) NULL);
sigaction(SIGTERM, &sa, (struct sigaction*) NULL);
int iRet = 0;
try {
pZNC->Loop();
} catch (const CException& e) {
switch (e.GetType()) {
case CException::EX_Shutdown:
iRet = 0;
break;
case CException::EX_Restart: {
// strdup() because GCC is stupid
char *args[] = {
strdup(argv[0]),
strdup("--datadir"),
strdup(pZNC->GetZNCPath().c_str()),
NULL,
NULL,
NULL,
NULL
};
int pos = 3;
if (CDebug::Debug())
args[pos++] = strdup("--debug");
else if (bForeground)
args[pos++] = strdup("--foreground");
if (!CDebug::StdoutIsTTY())
args[pos++] = strdup("--no-color");
if (bAllowRoot)
args[pos++] = strdup("--allow-root");
// The above code adds 3 entries to args tops
// which means the array should be big enough
CZNC::DestroyInstance();
execvp(args[0], args);
CUtils::PrintError("Unable to restart ZNC [" + CString(strerror(errno)) + "]");
} /* Fall through */
default:
iRet = 1;
}
}
CZNC::DestroyInstance();
return iRet;
}
| {
"content_hash": "ba55efbbb8661daddf3d9a1b514bfa5a",
"timestamp": "",
"source": "github",
"line_count": 382,
"max_line_length": 113,
"avg_line_length": 27.468586387434556,
"alnum_prop": 0.644239016487182,
"repo_name": "withinsoft/znc",
"id": "ac9d691f663b8555a9cba3792266debe31de27d0",
"size": "11122",
"binary": false,
"copies": "2",
"ref": "refs/heads/shadownet",
"path": "src/main.cpp",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "41140"
},
{
"name": "C++",
"bytes": "1324419"
},
{
"name": "CSS",
"bytes": "16066"
},
{
"name": "JavaScript",
"bytes": "772"
},
{
"name": "Perl",
"bytes": "33456"
},
{
"name": "Python",
"bytes": "23694"
},
{
"name": "Shell",
"bytes": "4881"
},
{
"name": "Tcl",
"bytes": "9772"
}
],
"symlink_target": ""
} |
package com.ring2park;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* Unit test for simple App.
*/
public class ApplicationTest
extends TestCase
{
/**
* Create the test case
*
* @param testName name of the test case
*/
public ApplicationTest(String testName)
{
super( testName );
}
/**
* @return the suite of tests being tested
*/
public static Test suite()
{
return new TestSuite( ApplicationTest.class );
}
/**
* Rigourous Test :-)
*/
public void testApp()
{
assertTrue( true );
}
}
| {
"content_hash": "083cb5f1b43e5786e5f1d360f8bc558b",
"timestamp": "",
"source": "github",
"line_count": 38,
"max_line_length": 54,
"avg_line_length": 17.42105263157895,
"alnum_prop": 0.5906344410876133,
"repo_name": "akevinlee/simple-webapp",
"id": "01b8ea43407d48198ce7fc1e88e4e5e6483754d2",
"size": "662",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/test/java/com/ring2park/ApplicationTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "1691"
},
{
"name": "HTML",
"bytes": "12006"
},
{
"name": "Java",
"bytes": "6166"
},
{
"name": "JavaScript",
"bytes": "6462"
}
],
"symlink_target": ""
} |
'use strict';
var sinon = require('sinon');
var lets = require('../../.');
var test = require('./test');
exports.testableCallback = sinon.spy(function (stage) {
stage.on('test', test.pluginOnTest);
});
exports.test = lets.plugin(exports.testableCallback);
| {
"content_hash": "52d2620314bccf553f8087898d96a0c5",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 55,
"avg_line_length": 23.727272727272727,
"alnum_prop": 0.6743295019157088,
"repo_name": "letsjs/lets",
"id": "383b9019d1614d45e21cccce70d1fff1d07ae42f",
"size": "261",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/lets/plugin.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "37560"
}
],
"symlink_target": ""
} |
package com.klogicapps.tv.billing;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentSender.SendIntentException;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.RemoteException;
import android.text.TextUtils;
import android.util.Log;
import com.android.vending.billing.IInAppBillingService;
import org.json.JSONException;
import java.util.ArrayList;
import java.util.List;
/**
* Provides convenience methods for in-app billing. You can create one instance of this
* class for your application and use it to process in-app billing operations.
* It provides synchronous (blocking) and asynchronous (non-blocking) methods for
* many common in-app billing operations, as well as automatic signature
* verification.
* <p/>
* After instantiating, you must perform setup in order to start using the object.
* To perform setup, call the {@link #startSetup} method and provide a listener;
* that listener will be notified when setup is complete, after which (and not before)
* you may call other methods.
* <p/>
* After setup is complete, you will typically want to request an inventory of owned
* items and subscriptions. See {@link #queryInventory}, {@link #queryInventoryAsync}
* and related methods.
* <p/>
* When you are done with this object, don't forget to call {@link #dispose}
* to ensure proper cleanup. This object holds a binding to the in-app billing
* service, which will leak unless you dispose of it correctly. If you created
* the object on an Activity's onCreate method, then the recommended
* place to dispose of it is the Activity's onDestroy method.
* <p/>
* A note about threading: When using this object from a background thread, you may
* call the blocking versions of methods; when using from a UI thread, call
* only the asynchronous versions and handle the results via callbacks.
* Also, notice that you can only call one asynchronous operation at a time;
* attempting to start a second asynchronous operation while the first one
* has not yet completed will result in an exception being thrown.
*
* @author Bruno Oliveira (Google)
*/
public class IabHelper {
// Billing response codes
public static final int BILLING_RESPONSE_RESULT_OK = 0;
public static final int BILLING_RESPONSE_RESULT_USER_CANCELED = 1;
public static final int BILLING_RESPONSE_RESULT_BILLING_UNAVAILABLE = 3;
public static final int BILLING_RESPONSE_RESULT_ITEM_UNAVAILABLE = 4;
public static final int BILLING_RESPONSE_RESULT_DEVELOPER_ERROR = 5;
public static final int BILLING_RESPONSE_RESULT_ERROR = 6;
public static final int BILLING_RESPONSE_RESULT_ITEM_ALREADY_OWNED = 7;
public static final int BILLING_RESPONSE_RESULT_ITEM_NOT_OWNED = 8;
// IAB Helper error codes
public static final int IABHELPER_ERROR_BASE = -1000;
public static final int IABHELPER_REMOTE_EXCEPTION = -1001;
public static final int IABHELPER_BAD_RESPONSE = -1002;
public static final int IABHELPER_VERIFICATION_FAILED = -1003;
public static final int IABHELPER_SEND_INTENT_FAILED = -1004;
public static final int IABHELPER_USER_CANCELLED = -1005;
public static final int IABHELPER_UNKNOWN_PURCHASE_RESPONSE = -1006;
public static final int IABHELPER_MISSING_TOKEN = -1007;
public static final int IABHELPER_UNKNOWN_ERROR = -1008;
public static final int IABHELPER_SUBSCRIPTIONS_NOT_AVAILABLE = -1009;
public static final int IABHELPER_INVALID_CONSUMPTION = -1010;
// Keys for the responses from InAppBillingService
public static final String RESPONSE_CODE = "RESPONSE_CODE";
public static final String RESPONSE_GET_SKU_DETAILS_LIST = "DETAILS_LIST";
public static final String RESPONSE_BUY_INTENT = "BUY_INTENT";
public static final String RESPONSE_INAPP_PURCHASE_DATA = "INAPP_PURCHASE_DATA";
public static final String RESPONSE_INAPP_SIGNATURE = "INAPP_DATA_SIGNATURE";
public static final String RESPONSE_INAPP_ITEM_LIST = "INAPP_PURCHASE_ITEM_LIST";
public static final String RESPONSE_INAPP_PURCHASE_DATA_LIST = "INAPP_PURCHASE_DATA_LIST";
public static final String RESPONSE_INAPP_SIGNATURE_LIST = "INAPP_DATA_SIGNATURE_LIST";
public static final String INAPP_CONTINUATION_TOKEN = "INAPP_CONTINUATION_TOKEN";
// Item types
public static final String ITEM_TYPE_INAPP = "inapp";
public static final String ITEM_TYPE_SUBS = "subs";
// some fields on the getSkuDetails response bundle
public static final String GET_SKU_DETAILS_ITEM_LIST = "ITEM_ID_LIST";
public static final String GET_SKU_DETAILS_ITEM_TYPE_LIST = "ITEM_TYPE_LIST";
// Is debug logging enabled?
boolean mDebugLog = false;
String mDebugTag = "IabHelper";
// Is setup done?
boolean mSetupDone = false;
// Has this object been disposed of? (If so, we should ignore callbacks, etc)
boolean mDisposed = false;
// Are subscriptions supported?
boolean mSubscriptionsSupported = false;
// Is an asynchronous operation in progress?
// (only one at a time can be in progress)
boolean mAsyncInProgress = false;
// (for logging/debugging)
// if mAsyncInProgress == true, what asynchronous operation is in progress?
String mAsyncOperation = "";
// Context we were passed during initialization
Context mContext;
// Connection to the service
IInAppBillingService mService;
ServiceConnection mServiceConn;
// The request code used to launch purchase flow
int mRequestCode;
// The item type of the current purchase flow
String mPurchasingItemType;
// Public key for verifying signature, in base64 encoding
String mSignatureBase64 = null;
// The listener registered on launchPurchaseFlow, which we have to call back when
// the purchase finishes
OnIabPurchaseFinishedListener mPurchaseListener;
/**
* Creates an instance. After creation, it will not yet be ready to use. You must perform
* setup by calling {@link #startSetup} and wait for setup to complete. This constructor does not
* block and is safe to call from a UI thread.
*
* @param ctx Your application or Activity context. Needed to bind to the in-app billing service.
* @param base64PublicKey Your application's public key, encoded in base64.
* This is used for verification of purchase signatures. You can find your app's base64-encoded
* public key in your application's page on Google Play Developer Console. Note that this
* is NOT your "developer public key".
*/
public IabHelper(Context ctx, String base64PublicKey) {
mContext = ctx.getApplicationContext();
mSignatureBase64 = base64PublicKey;
logDebug("IAB helper created.");
}
/**
* Returns a human-readable description for the given response code.
*
* @param code The response code
* @return A human-readable string explaining the result code.
* It also includes the result code numerically.
*/
public static String getResponseDesc(int code) {
String[] iab_msgs = ("0:OK/1:User Canceled/2:Unknown/" +
"3:Billing Unavailable/4:Item unavailable/" +
"5:Developer Error/6:Error/7:Item Already Owned/" +
"8:Item not owned").split("/");
String[] iabhelper_msgs = ("0:OK/-1001:Remote exception during initialization/" +
"-1002:Bad response received/" +
"-1003:Purchase signature verification failed/" +
"-1004:Send intent failed/" +
"-1005:User cancelled/" +
"-1006:Unknown purchase response/" +
"-1007:Missing token/" +
"-1008:Unknown error/" +
"-1009:Subscriptions not available/" +
"-1010:Invalid consumption attempt").split("/");
if (code <= IABHELPER_ERROR_BASE) {
int index = IABHELPER_ERROR_BASE - code;
if (index >= 0 && index < iabhelper_msgs.length)
return iabhelper_msgs[index];
else
return String.valueOf(code) + ":Unknown IAB Helper Error";
} else if (code < 0 || code >= iab_msgs.length)
return String.valueOf(code) + ":Unknown";
else
return iab_msgs[code];
}
/**
* Enables or disable debug logging through LogCat.
*/
public void enableDebugLogging(boolean enable, String tag) {
checkNotDisposed();
mDebugLog = enable;
mDebugTag = tag;
}
public void enableDebugLogging(boolean enable) {
checkNotDisposed();
mDebugLog = enable;
}
/**
* Starts the setup process. This will start up the setup process asynchronously.
* You will be notified through the listener when the setup process is complete.
* This method is safe to call from a UI thread.
*
* @param listener The listener to notify when the setup process is complete.
*/
public void startSetup(final OnIabSetupFinishedListener listener) {
// If already set up, can't do it again.
checkNotDisposed();
if (mSetupDone)
throw new IllegalStateException("IAB helper is already set up.");
// Connection to IAB service
logDebug("Starting in-app billing setup.");
mServiceConn = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) {
logDebug("Billing service disconnected.");
mService = null;
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
if (mDisposed)
return;
logDebug("Billing service connected.");
mService = IInAppBillingService.Stub.asInterface(service);
String packageName = mContext.getPackageName();
try {
logDebug("Checking for in-app billing 3 support.");
// check for in-app billing v3 support
int response = mService.isBillingSupported(3, packageName, ITEM_TYPE_INAPP);
if (response != BILLING_RESPONSE_RESULT_OK) {
if (listener != null)
listener.onIabSetupFinished(new IabResult(response, "Error checking for billing v3 support."));
// if in-app purchases aren't supported, neither are subscriptions.
mSubscriptionsSupported = false;
return;
}
logDebug("In-app billing version 3 supported for " + packageName);
// check for v3 subscriptions support
response = mService.isBillingSupported(3, packageName, ITEM_TYPE_SUBS);
if (response == BILLING_RESPONSE_RESULT_OK) {
logDebug("Subscriptions AVAILABLE.");
mSubscriptionsSupported = true;
} else {
logDebug("Subscriptions NOT AVAILABLE. Response: " + response);
}
mSetupDone = true;
} catch (RemoteException e) {
if (listener != null) {
listener.onIabSetupFinished(new IabResult(IABHELPER_REMOTE_EXCEPTION, "RemoteException while setting up in-app billing."));
}
e.printStackTrace();
return;
}
if (listener != null) {
listener.onIabSetupFinished(new IabResult(BILLING_RESPONSE_RESULT_OK, "Setup successful."));
}
}
};
Intent serviceIntent = new Intent("com.android.vending.billing.InAppBillingService.BIND");
serviceIntent.setPackage("com.android.vending");
if (!mContext.getPackageManager().queryIntentServices(serviceIntent, 0).isEmpty()) {
// service available to handle that Intent
mContext.bindService(serviceIntent, mServiceConn, Context.BIND_AUTO_CREATE);
} else {
// no service available to handle that Intent
if (listener != null) {
listener.onIabSetupFinished(new IabResult(BILLING_RESPONSE_RESULT_BILLING_UNAVAILABLE, "Billing service unavailable on device."));
}
}
}
/**
* Dispose of object, releasing resources. It's very important to call this
* method when you are done with this object. It will release any resources
* used by it such as service connections. Naturally, once the object is
* disposed of, it can't be used again.
*/
public void dispose() {
logDebug("Disposing.");
mSetupDone = false;
if (mServiceConn != null) {
logDebug("Unbinding from service.");
if (mContext != null)
mContext.unbindService(mServiceConn);
}
mDisposed = true;
mContext = null;
mServiceConn = null;
mService = null;
mPurchaseListener = null;
}
private void checkNotDisposed() {
if (mDisposed)
throw new IllegalStateException("IabHelper was disposed of, so it cannot be used.");
}
/**
* Returns whether subscriptions are supported.
*/
public boolean subscriptionsSupported() {
checkNotDisposed();
return mSubscriptionsSupported;
}
public void launchPurchaseFlow(Activity act, String sku, int requestCode, OnIabPurchaseFinishedListener listener) {
launchPurchaseFlow(act, sku, requestCode, listener, "");
}
public void launchPurchaseFlow(Activity act, String sku, int requestCode, OnIabPurchaseFinishedListener listener, String extraData) {
launchPurchaseFlow(act, sku, ITEM_TYPE_INAPP, requestCode, listener, extraData);
}
public void launchSubscriptionPurchaseFlow(Activity act, String sku, int requestCode, OnIabPurchaseFinishedListener listener) {
launchSubscriptionPurchaseFlow(act, sku, requestCode, listener, "");
}
public void launchSubscriptionPurchaseFlow(Activity act, String sku, int requestCode, OnIabPurchaseFinishedListener listener, String extraData) {
launchPurchaseFlow(act, sku, ITEM_TYPE_SUBS, requestCode, listener, extraData);
}
/**
* Initiate the UI flow for an in-app purchase. Call this method to initiate an in-app purchase,
* which will involve bringing up the Google Play screen. The calling activity will be paused while
* the user interacts with Google Play, and the result will be delivered via the activity's
* {@link android.app.Activity#onActivityResult} method, at which point you must call
* this object's {@link #handleActivityResult} method to continue the purchase flow. This method
* MUST be called from the UI thread of the Activity.
*
* @param act The calling activity.
* @param sku The sku of the item to purchase.
* @param itemType indicates if it's a product or a subscription (ITEM_TYPE_INAPP or ITEM_TYPE_SUBS)
* @param requestCode A request code (to differentiate from other responses --
* as in {@link android.app.Activity#startActivityForResult}).
* @param listener The listener to notify when the purchase process finishes
* @param extraData Extra data (developer payload), which will be returned with the purchase data
* when the purchase completes. This extra data will be permanently bound to that purchase
* and will always be returned when the purchase is queried.
*/
public void launchPurchaseFlow(Activity act, String sku, String itemType, int requestCode, OnIabPurchaseFinishedListener listener, String extraData) {
checkNotDisposed();
checkSetupDone("launchPurchaseFlow");
flagStartAsync("launchPurchaseFlow");
IabResult result;
if (itemType.equals(ITEM_TYPE_SUBS) && !mSubscriptionsSupported) {
IabResult r = new IabResult(IABHELPER_SUBSCRIPTIONS_NOT_AVAILABLE, "Subscriptions are not available.");
flagEndAsync();
if (listener != null)
listener.onIabPurchaseFinished(r, null);
return;
}
try {
logDebug("Constructing buy intent for " + sku + ", item type: " + itemType);
Bundle buyIntentBundle = mService.getBuyIntent(3, mContext.getPackageName(), sku, itemType, extraData);
int response = getResponseCodeFromBundle(buyIntentBundle);
if (response != BILLING_RESPONSE_RESULT_OK) {
logError("Unable to buy item, Error response: " + getResponseDesc(response));
flagEndAsync();
result = new IabResult(response, "Unable to buy item");
if (listener != null)
listener.onIabPurchaseFinished(result, null);
return;
}
PendingIntent pendingIntent = buyIntentBundle.getParcelable(RESPONSE_BUY_INTENT);
logDebug("Launching buy intent for " + sku + ". Request code: " + requestCode);
mRequestCode = requestCode;
mPurchaseListener = listener;
mPurchasingItemType = itemType;
act.startIntentSenderForResult(pendingIntent.getIntentSender(), requestCode, new Intent(), Integer
.valueOf(0), Integer.valueOf(0), Integer.valueOf(0));
} catch (SendIntentException e) {
logError("SendIntentException while launching purchase flow for sku " + sku);
e.printStackTrace();
flagEndAsync();
result = new IabResult(IABHELPER_SEND_INTENT_FAILED, "Failed to send intent.");
if (listener != null)
listener.onIabPurchaseFinished(result, null);
} catch (RemoteException e) {
logError("RemoteException while launching purchase flow for sku " + sku);
e.printStackTrace();
flagEndAsync();
result = new IabResult(IABHELPER_REMOTE_EXCEPTION, "Remote exception while starting purchase flow");
if (listener != null)
listener.onIabPurchaseFinished(result, null);
}
}
/**
* Handles an activity result that's part of the purchase flow in in-app billing. If you
* are calling {@link #launchPurchaseFlow}, then you must call this method from your
* Activity's {@link android.app.Activity@onActivityResult} method. This method
* MUST be called from the UI thread of the Activity.
*
* @param requestCode The requestCode as you received it.
* @param resultCode The resultCode as you received it.
* @param data The data (Intent) as you received it.
* @return Returns true if the result was related to a purchase flow and was handled;
* false if the result was not related to a purchase, in which case you should
* handle it normally.
*/
public boolean handleActivityResult(int requestCode, int resultCode, Intent data) {
IabResult result;
if (requestCode != mRequestCode)
return false;
checkNotDisposed();
checkSetupDone("handleActivityResult");
// end of async purchase operation that started on launchPurchaseFlow
flagEndAsync();
if (data == null) {
logError("Null data in IAB activity result.");
result = new IabResult(IABHELPER_BAD_RESPONSE, "Null data in IAB result");
if (mPurchaseListener != null)
mPurchaseListener.onIabPurchaseFinished(result, null);
return true;
}
int responseCode = getResponseCodeFromIntent(data);
String purchaseData = data.getStringExtra(RESPONSE_INAPP_PURCHASE_DATA);
String dataSignature = data.getStringExtra(RESPONSE_INAPP_SIGNATURE);
if (resultCode == Activity.RESULT_OK && responseCode == BILLING_RESPONSE_RESULT_OK) {
logDebug("Successful resultcode from purchase activity.");
logDebug("Purchase data: " + purchaseData);
logDebug("Data signature: " + dataSignature);
logDebug("Extras: " + data.getExtras());
logDebug("Expected item type: " + mPurchasingItemType);
if (purchaseData == null || dataSignature == null) {
logError("BUG: either purchaseData or dataSignature is null.");
logDebug("Extras: " + data.getExtras().toString());
result = new IabResult(IABHELPER_UNKNOWN_ERROR, "IAB returned null purchaseData or dataSignature");
if (mPurchaseListener != null)
mPurchaseListener.onIabPurchaseFinished(result, null);
return true;
}
Purchase purchase;
try {
purchase = new Purchase(mPurchasingItemType, purchaseData, dataSignature);
String sku = purchase.getSku();
// Verify signature
if (!Security.verifyPurchase(mSignatureBase64, purchaseData, dataSignature)) {
logError("Purchase signature verification FAILED for sku " + sku);
result = new IabResult(IABHELPER_VERIFICATION_FAILED, "Signature verification failed for sku " + sku);
if (mPurchaseListener != null)
mPurchaseListener.onIabPurchaseFinished(result, purchase);
return true;
}
logDebug("Purchase signature successfully verified.");
} catch (JSONException e) {
logError("Failed to parse purchase data.");
e.printStackTrace();
result = new IabResult(IABHELPER_BAD_RESPONSE, "Failed to parse purchase data.");
if (mPurchaseListener != null)
mPurchaseListener.onIabPurchaseFinished(result, null);
return true;
}
if (mPurchaseListener != null) {
mPurchaseListener.onIabPurchaseFinished(new IabResult(BILLING_RESPONSE_RESULT_OK, "Success"), purchase);
}
} else if (resultCode == Activity.RESULT_OK) {
// result code was OK, but in-app billing response was not OK.
logDebug("Result code was OK but in-app billing response was not OK: " + getResponseDesc(responseCode));
if (mPurchaseListener != null) {
result = new IabResult(responseCode, "Problem purchashing item.");
mPurchaseListener.onIabPurchaseFinished(result, null);
}
} else if (resultCode == Activity.RESULT_CANCELED) {
logDebug("Purchase canceled - Response: " + getResponseDesc(responseCode));
result = new IabResult(IABHELPER_USER_CANCELLED, "User canceled.");
if (mPurchaseListener != null)
mPurchaseListener.onIabPurchaseFinished(result, null);
} else {
logError("Purchase failed. Result code: " + Integer.toString(resultCode) + ". Response: " + getResponseDesc(responseCode));
result = new IabResult(IABHELPER_UNKNOWN_PURCHASE_RESPONSE, "Unknown purchase response.");
if (mPurchaseListener != null)
mPurchaseListener.onIabPurchaseFinished(result, null);
}
return true;
}
public Inventory queryInventory(boolean querySkuDetails, List<String> moreSkus) throws IabException {
return queryInventory(querySkuDetails, moreSkus, null);
}
/**
* Queries the inventory. This will query all owned items from the server, as well as
* information on additional skus, if specified. This method may block or take long to execute.
* Do not call from a UI thread. For that, use the non-blocking version {@link #refreshInventoryAsync}.
*
* @param querySkuDetails if true, SKU details (price, description, etc) will be queried as well
* as purchase information.
* @param moreItemSkus additional PRODUCT skus to query information on, regardless of ownership.
* Ignored if null or if querySkuDetails is false.
* @param moreSubsSkus additional SUBSCRIPTIONS skus to query information on, regardless of ownership.
* Ignored if null or if querySkuDetails is false.
* @throws IabException if a problem occurs while refreshing the inventory.
*/
public Inventory queryInventory(boolean querySkuDetails, List<String> moreItemSkus, List<String> moreSubsSkus) throws IabException {
checkNotDisposed();
checkSetupDone("queryInventory");
try {
Inventory inv = new Inventory();
int r = queryPurchases(inv, ITEM_TYPE_INAPP);
if (r != BILLING_RESPONSE_RESULT_OK) {
throw new IabException(r, "Error refreshing inventory (querying owned items).");
}
if (querySkuDetails) {
r = querySkuDetails(ITEM_TYPE_INAPP, inv, moreItemSkus);
if (r != BILLING_RESPONSE_RESULT_OK) {
throw new IabException(r, "Error refreshing inventory (querying prices of items).");
}
}
// if subscriptions are supported, then also query for subscriptions
if (mSubscriptionsSupported) {
r = queryPurchases(inv, ITEM_TYPE_SUBS);
if (r != BILLING_RESPONSE_RESULT_OK) {
throw new IabException(r, "Error refreshing inventory (querying owned subscriptions).");
}
if (querySkuDetails) {
r = querySkuDetails(ITEM_TYPE_SUBS, inv, moreItemSkus);
if (r != BILLING_RESPONSE_RESULT_OK) {
throw new IabException(r, "Error refreshing inventory (querying prices of subscriptions).");
}
}
}
return inv;
} catch (RemoteException e) {
throw new IabException(IABHELPER_REMOTE_EXCEPTION, "Remote exception while refreshing inventory.", e);
} catch (JSONException e) {
throw new IabException(IABHELPER_BAD_RESPONSE, "Error parsing JSON response while refreshing inventory.", e);
}
}
/**
* Asynchronous wrapper for inventory query. This will perform an inventory
* query as described in {@link #queryInventory}, but will do so asynchronously
* and call back the specified listener upon completion. This method is safe to
* call from a UI thread.
*
* @param querySkuDetails as in {@link #queryInventory}
* @param moreSkus as in {@link #queryInventory}
* @param listener The listener to notify when the refresh operation completes.
*/
public void queryInventoryAsync(final boolean querySkuDetails, final List<String> moreSkus, final QueryInventoryFinishedListener listener) {
final Handler handler = new Handler();
checkNotDisposed();
checkSetupDone("queryInventory");
flagStartAsync("refresh inventory");
(new Thread(new Runnable() {
public void run() {
IabResult result = new IabResult(BILLING_RESPONSE_RESULT_OK, "Inventory refresh successful.");
Inventory inv = null;
try {
inv = queryInventory(querySkuDetails, moreSkus);
} catch (IabException ex) {
result = ex.getResult();
}
flagEndAsync();
final IabResult result_f = result;
final Inventory inv_f = inv;
if (!mDisposed && listener != null) {
handler.post(new Runnable() {
public void run() {
listener.onQueryInventoryFinished(result_f, inv_f);
}
});
}
}
})).start();
}
public void queryInventoryAsync(QueryInventoryFinishedListener listener) {
queryInventoryAsync(true, null, listener);
}
public void queryInventoryAsync(boolean querySkuDetails, QueryInventoryFinishedListener listener) {
queryInventoryAsync(querySkuDetails, null, listener);
}
/**
* Consumes a given in-app product. Consuming can only be done on an item
* that's owned, and as a result of consumption, the user will no longer own it.
* This method may block or take long to return. Do not call from the UI thread.
* For that, see {@link #consumeAsync}.
*
* @param itemInfo The PurchaseInfo that represents the item to consume.
* @throws IabException if there is a problem during consumption.
*/
void consume(Purchase itemInfo) throws IabException {
checkNotDisposed();
checkSetupDone("consume");
if (!itemInfo.mItemType.equals(ITEM_TYPE_INAPP)) {
throw new IabException(IABHELPER_INVALID_CONSUMPTION, "Items of type '" + itemInfo.mItemType + "' can't be consumed.");
}
try {
String token = itemInfo.getToken();
String sku = itemInfo.getSku();
if (token == null || token.equals("")) {
logError("Can't consume " + sku + ". No token.");
throw new IabException(IABHELPER_MISSING_TOKEN, "PurchaseInfo is missing token for sku: " + sku + " " + itemInfo);
}
logDebug("Consuming sku: " + sku + ", token: " + token);
int response = mService.consumePurchase(3, mContext.getPackageName(), token);
if (response == BILLING_RESPONSE_RESULT_OK) {
logDebug("Successfully consumed sku: " + sku);
} else {
logDebug("Error consuming consuming sku " + sku + ". " + getResponseDesc(response));
throw new IabException(response, "Error consuming sku " + sku);
}
} catch (RemoteException e) {
throw new IabException(IABHELPER_REMOTE_EXCEPTION, "Remote exception while consuming. PurchaseInfo: " + itemInfo, e);
}
}
/**
* Asynchronous wrapper to item consumption. Works like {@link #consume}, but
* performs the consumption in the background and notifies completion through
* the provided listener. This method is safe to call from a UI thread.
*
* @param purchase The purchase to be consumed.
* @param listener The listener to notify when the consumption operation finishes.
*/
public void consumeAsync(Purchase purchase, OnConsumeFinishedListener listener) {
checkNotDisposed();
checkSetupDone("consume");
List<Purchase> purchases = new ArrayList<Purchase>();
purchases.add(purchase);
consumeAsyncInternal(purchases, listener, null);
}
/**
* Same as {@link consumeAsync}, but for multiple items at once.
*
* @param purchases The list of PurchaseInfo objects representing the purchases to consume.
* @param listener The listener to notify when the consumption operation finishes.
*/
public void consumeAsync(List<Purchase> purchases, OnConsumeMultiFinishedListener listener) {
checkNotDisposed();
checkSetupDone("consume");
consumeAsyncInternal(purchases, null, listener);
}
// Checks that setup was done; if not, throws an exception.
void checkSetupDone(String operation) {
if (!mSetupDone) {
logError("Illegal state for operation (" + operation + "): IAB helper is not set up.");
throw new IllegalStateException("IAB helper is not set up. Can't perform operation: " + operation);
}
}
// Workaround to bug where sometimes response codes come as Long instead of Integer
int getResponseCodeFromBundle(Bundle b) {
Object o = b.get(RESPONSE_CODE);
if (o == null) {
logDebug("Bundle with null response code, assuming OK (known issue)");
return BILLING_RESPONSE_RESULT_OK;
} else if (o instanceof Integer)
return (Integer) o;
else if (o instanceof Long)
return (int) ((Long) o).longValue();
else {
logError("Unexpected type for bundle response code.");
logError(o.getClass().getName());
throw new RuntimeException("Unexpected type for bundle response code: " + o.getClass()
.getName());
}
}
// Workaround to bug where sometimes response codes come as Long instead of Integer
int getResponseCodeFromIntent(Intent i) {
Object o = i.getExtras().get(RESPONSE_CODE);
if (o == null) {
logError("Intent with no response code, assuming OK (known issue)");
return BILLING_RESPONSE_RESULT_OK;
} else if (o instanceof Integer)
return ((Integer) o).intValue();
else if (o instanceof Long)
return (int) ((Long) o).longValue();
else {
logError("Unexpected type for intent response code.");
logError(o.getClass().getName());
throw new RuntimeException("Unexpected type for intent response code: " + o.getClass()
.getName());
}
}
void flagStartAsync(String operation) {
if (mAsyncInProgress)
throw new IllegalStateException("Can't start async operation (" +
operation + ") because another async operation(" + mAsyncOperation + ") is in progress.");
mAsyncOperation = operation;
mAsyncInProgress = true;
logDebug("Starting async operation: " + operation);
}
void flagEndAsync() {
logDebug("Ending async operation: " + mAsyncOperation);
mAsyncOperation = "";
mAsyncInProgress = false;
}
int queryPurchases(Inventory inv, String itemType) throws JSONException, RemoteException {
// Query purchases
logDebug("Querying owned items, item type: " + itemType);
logDebug("Package name: " + mContext.getPackageName());
boolean verificationFailed = false;
String continueToken = null;
do {
logDebug("Calling getPurchases with continuation token: " + continueToken);
Bundle ownedItems = mService.getPurchases(3, mContext.getPackageName(), itemType, continueToken);
int response = getResponseCodeFromBundle(ownedItems);
logDebug("Owned items response: " + String.valueOf(response));
if (response != BILLING_RESPONSE_RESULT_OK) {
logDebug("getPurchases() failed: " + getResponseDesc(response));
return response;
}
if (!ownedItems.containsKey(RESPONSE_INAPP_ITEM_LIST) || !ownedItems.containsKey(RESPONSE_INAPP_PURCHASE_DATA_LIST) || !ownedItems
.containsKey(RESPONSE_INAPP_SIGNATURE_LIST)) {
logError("Bundle returned from getPurchases() doesn't contain required fields.");
return IABHELPER_BAD_RESPONSE;
}
ArrayList<String> ownedSkus = ownedItems.getStringArrayList(RESPONSE_INAPP_ITEM_LIST);
ArrayList<String> purchaseDataList = ownedItems.getStringArrayList(RESPONSE_INAPP_PURCHASE_DATA_LIST);
ArrayList<String> signatureList = ownedItems.getStringArrayList(RESPONSE_INAPP_SIGNATURE_LIST);
for (int i = 0; i < purchaseDataList.size(); ++i) {
String purchaseData = purchaseDataList.get(i);
String signature = signatureList.get(i);
String sku = ownedSkus.get(i);
if (Security.verifyPurchase(mSignatureBase64, purchaseData, signature)) {
logDebug("Sku is owned: " + sku);
Purchase purchase = new Purchase(itemType, purchaseData, signature);
if (TextUtils.isEmpty(purchase.getToken())) {
logWarn("BUG: empty/null token!");
logDebug("Purchase data: " + purchaseData);
}
// Record ownership and token
inv.addPurchase(purchase);
} else {
logWarn("Purchase signature verification **FAILED**. Not adding item.");
logDebug(" Purchase data: " + purchaseData);
logDebug(" Signature: " + signature);
verificationFailed = true;
}
}
continueToken = ownedItems.getString(INAPP_CONTINUATION_TOKEN);
logDebug("Continuation token: " + continueToken);
} while (!TextUtils.isEmpty(continueToken));
return verificationFailed ? IABHELPER_VERIFICATION_FAILED : BILLING_RESPONSE_RESULT_OK;
}
int querySkuDetails(String itemType, Inventory inv, List<String> moreSkus) throws RemoteException, JSONException {
logDebug("Querying SKU details.");
ArrayList<String> skuList = new ArrayList<String>();
skuList.addAll(inv.getAllOwnedSkus(itemType));
if (moreSkus != null) {
for (String sku : moreSkus) {
if (!skuList.contains(sku)) {
skuList.add(sku);
}
}
}
if (skuList.size() == 0) {
logDebug("queryPrices: nothing to do because there are no SKUs.");
return BILLING_RESPONSE_RESULT_OK;
}
Bundle querySkus = new Bundle();
querySkus.putStringArrayList(GET_SKU_DETAILS_ITEM_LIST, skuList);
Bundle skuDetails = mService.getSkuDetails(3, mContext.getPackageName(), itemType, querySkus);
if (!skuDetails.containsKey(RESPONSE_GET_SKU_DETAILS_LIST)) {
int response = getResponseCodeFromBundle(skuDetails);
if (response != BILLING_RESPONSE_RESULT_OK) {
logDebug("getSkuDetails() failed: " + getResponseDesc(response));
return response;
} else {
logError("getSkuDetails() returned a bundle with neither an error nor a detail list.");
return IABHELPER_BAD_RESPONSE;
}
}
ArrayList<String> responseList = skuDetails.getStringArrayList(RESPONSE_GET_SKU_DETAILS_LIST);
for (String thisResponse : responseList) {
SkuDetails d = new SkuDetails(itemType, thisResponse);
logDebug("Got sku details: " + d);
inv.addSkuDetails(d);
}
return BILLING_RESPONSE_RESULT_OK;
}
void consumeAsyncInternal(final List<Purchase> purchases, final OnConsumeFinishedListener singleListener, final OnConsumeMultiFinishedListener multiListener) {
final Handler handler = new Handler();
flagStartAsync("consume");
(new Thread(new Runnable() {
public void run() {
final List<IabResult> results = new ArrayList<IabResult>();
for (Purchase purchase : purchases) {
try {
consume(purchase);
results.add(new IabResult(BILLING_RESPONSE_RESULT_OK, "Successful consume of sku " + purchase
.getSku()));
} catch (IabException ex) {
results.add(ex.getResult());
}
}
flagEndAsync();
if (!mDisposed && singleListener != null) {
handler.post(new Runnable() {
public void run() {
singleListener.onConsumeFinished(purchases.get(0), results.get(0));
}
});
}
if (!mDisposed && multiListener != null) {
handler.post(new Runnable() {
public void run() {
multiListener.onConsumeMultiFinished(purchases, results);
}
});
}
}
})).start();
}
void logDebug(String msg) {
if (mDebugLog)
Log.d(mDebugTag, msg);
}
void logError(String msg) {
Log.e(mDebugTag, "In-app billing error: " + msg);
}
void logWarn(String msg) {
Log.w(mDebugTag, "In-app billing warning: " + msg);
}
/**
* Callback for setup process. This listener's {@link #onIabSetupFinished} method is called
* when the setup process is complete.
*/
public interface OnIabSetupFinishedListener {
/**
* Called to notify that setup is complete.
*
* @param result The result of the setup process.
*/
public void onIabSetupFinished(IabResult result);
}
/**
* Callback that notifies when a purchase is finished.
*/
public interface OnIabPurchaseFinishedListener {
/**
* Called to notify that an in-app purchase finished. If the purchase was successful,
* then the sku parameter specifies which item was purchased. If the purchase failed,
* the sku and extraData parameters may or may not be null, depending on how far the purchase
* process went.
*
* @param result The result of the purchase.
* @param info The purchase information (null if purchase failed)
*/
public void onIabPurchaseFinished(IabResult result, Purchase info);
}
/**
* Listener that notifies when an inventory query operation completes.
*/
public interface QueryInventoryFinishedListener {
/**
* Called to notify that an inventory query operation completed.
*
* @param result The result of the operation.
* @param inv The inventory.
*/
public void onQueryInventoryFinished(IabResult result, Inventory inv);
}
/**
* Callback that notifies when a consumption operation finishes.
*/
public interface OnConsumeFinishedListener {
/**
* Called to notify that a consumption has finished.
*
* @param purchase The purchase that was (or was to be) consumed.
* @param result The result of the consumption operation.
*/
public void onConsumeFinished(Purchase purchase, IabResult result);
}
/**
* Callback that notifies when a multi-item consumption operation finishes.
*/
public interface OnConsumeMultiFinishedListener {
/**
* Called to notify that a consumption of multiple items has finished.
*
* @param purchases The purchases that were (or were to be) consumed.
* @param results The results of each consumption operation, corresponding to each
* sku.
*/
public void onConsumeMultiFinished(List<Purchase> purchases, List<IabResult> results);
}
}
| {
"content_hash": "796dcdb78c53e50fc25d16a39068cde5",
"timestamp": "",
"source": "github",
"line_count": 939,
"max_line_length": 161,
"avg_line_length": 41.98722044728434,
"alnum_prop": 0.6843453558565413,
"repo_name": "jc6212/Android-UTubeTV",
"id": "0ea146d35773173732e9a088361bbfeeea603fc9",
"size": "40021",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "UTubeTVProject - Eclipse/Utube/src/com/klogicapps/tv/billing/IabHelper.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Groovy",
"bytes": "9237"
},
{
"name": "Java",
"bytes": "2454890"
},
{
"name": "Shell",
"bytes": "3575"
}
],
"symlink_target": ""
} |
package com.severenity.engine.adapters;
import android.content.Context;
import android.databinding.DataBindingUtil;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import com.severenity.R;
import com.severenity.databinding.TeamQuestItemBinding;
import com.severenity.databinding.TeamQuestsGroupBinding;
import com.severenity.entity.quest.team.TeamQuest;
import com.severenity.entity.quest.team.TeamQuestPart;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* Created by Novosad on 5/31/17.
*/
public class TeamQuestsListAdapter extends BaseExpandableListAdapter {
private Context context;
private ArrayList<TeamQuest> teamQuests;
private Map<String, List<TeamQuestPart>> parts;
public TeamQuestsListAdapter(Context context, List<TeamQuest> teamQuests, Map<String, List<TeamQuestPart>> parts) {
this.context = context;
this.teamQuests = new ArrayList<>(teamQuests);
this.parts = parts;
}
@Override
public int getGroupCount() {
return teamQuests.size();
}
@Override
public int getChildrenCount(int groupPosition) {
return parts.get(teamQuests.get(groupPosition).getId()).size();
}
@Override
public Object getGroup(int groupPosition) {
return teamQuests.get(groupPosition);
}
@Override
public Object getChild(int groupPosition, int childPosition) {
return parts.get(teamQuests.get(groupPosition).getId()).get(childPosition);
}
@Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
@Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
@Override
public boolean hasStableIds() {
return false;
}
@Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
TeamQuestsGroupBinding teamQuestsGroupBinding;
if (convertView == null) {
teamQuestsGroupBinding = DataBindingUtil.inflate(
LayoutInflater.from(context), R.layout.team_quests_group, parent, false);
convertView = teamQuestsGroupBinding.getRoot();
} else {
teamQuestsGroupBinding = (TeamQuestsGroupBinding) convertView.getTag();
}
teamQuestsGroupBinding.setTeamQuest(teamQuests.get(groupPosition));
convertView.setTag(teamQuestsGroupBinding);
return convertView;
}
@Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
TeamQuestItemBinding teamQuestItemBinding;
if (convertView == null) {
teamQuestItemBinding = DataBindingUtil.inflate(
LayoutInflater.from(context), R.layout.team_quest_item, parent, false);
convertView = teamQuestItemBinding.getRoot();
} else {
teamQuestItemBinding = (TeamQuestItemBinding) convertView.getTag();
}
teamQuestItemBinding.setTeamQuestPart(parts.get(teamQuests.get(groupPosition).getId()).get(childPosition));
convertView.setTag(teamQuestItemBinding);
return convertView;
}
@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return false;
}
}
| {
"content_hash": "84d2f6576a062a8dccc994cb2cf599ba",
"timestamp": "",
"source": "github",
"line_count": 110,
"max_line_length": 125,
"avg_line_length": 31.37272727272727,
"alnum_prop": 0.7053028107794842,
"repo_name": "OlegNovosad/Severenity",
"id": "bda5c75466bde30d02be662a071e47e766a3dbd0",
"size": "3451",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "app/src/main/java/com/severenity/engine/adapters/TeamQuestsListAdapter.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "14215"
},
{
"name": "C++",
"bytes": "2541918"
},
{
"name": "Java",
"bytes": "524010"
},
{
"name": "Objective-C",
"bytes": "3378261"
},
{
"name": "Objective-C++",
"bytes": "395453"
},
{
"name": "Ruby",
"bytes": "1327"
},
{
"name": "Shell",
"bytes": "107890"
},
{
"name": "Swift",
"bytes": "1404292"
}
],
"symlink_target": ""
} |
.. _multiple_admin_sites:
Working with multiple admin sites
=================================
Introduction
------------
Django supports custom admin sites, and of course you can have as many
admin sites as you want, django-admin-tools provides basic support for
this, you can setup a custom dashboard or menu for each admin site.
Setting up a different dashboard and menu for each admin site instance
----------------------------------------------------------------------
In the following example we will assume that you have two admin site
instances: the default django admin site and a custom admin site of your
own. In your urls, you should have something like this::
from django.conf.urls.defaults import *
from django.contrib import admin
from yourproject.admin import admin_site
admin.autodiscover()
urlpatterns = patterns('',
(r'^admin/', include(admin.site.urls)),
(r'^myadmin/', include(admin_site.urls)),
)
Now to configure your dashboards, you could do::
python manage.py customdashboard django_admin_dashboard.py
python manage.py customdashboard my_admin_dashboard.py
And to tell django-admin-tools to use your custom dashboards depending on
the admin site being used, you just have to add the following to your project
settings file::
ADMIN_TOOLS_INDEX_DASHBOARD = {
'django.contrib.admin.site': 'yourproject.django_admin_dashboard.CustomIndexDashboard',
'yourproject.admin.admin_site': 'yourproject.my_admin_dashboard.CustomIndexDashboard',
}
Note that the same applies for the ``ADMIN_TOOLS_APP_INDEX_DASHBOARD``
settings variable.
Finally do the same thing for menu::
python manage.py custommenu django_admin_menu.py
python manage.py custommenu my_admin_menu.py
And to tell django-admin-tools to use your custom menu depending on
the admin site being used::
ADMIN_TOOLS_MENU = {
'django.contrib.admin.site': 'yourproject.django_admin_menu.CustomMenu',
'yourproject.admin.admin_site': 'yourproject.my_admin_menu.CustomMenu',
}
| {
"content_hash": "011f70bb2a4f007fa4995b6a29a1f924",
"timestamp": "",
"source": "github",
"line_count": 59,
"max_line_length": 95,
"avg_line_length": 34.96610169491525,
"alnum_prop": 0.7033446437227339,
"repo_name": "glowka/django-admin-tools",
"id": "f13b5044c233c5f9e3eee7e61fe2d0df62b53aea",
"size": "2063",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "docs/multiple_admin_sites.rst",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "10073"
},
{
"name": "HTML",
"bytes": "15063"
},
{
"name": "JavaScript",
"bytes": "17013"
},
{
"name": "Python",
"bytes": "135342"
}
],
"symlink_target": ""
} |
Database::Database(std::string path) {
this->in_transaction = false;
this->debug = false;
int status = sqlite3_open(path.c_str(),&db);
if (status!=SQLITE_OK) {
printf("Database::Database sqlite3_open returned error code: %d\n",status);
if (db != nullptr) {
sqlite3_close(db);
db = nullptr;
}
}
sqlite3_stmt* init_ptable;
sqlite3_stmt* init_ftable;
const char* stmt0 = "create table if not exists particles(x real, y real, z real, q real, type text, generation integer)";
const char* stmt1 = "create table if not exists fitness(f real,generation integer)";
status = sqlite3_prepare_v2(db,stmt0,std::strlen(stmt0),&init_ptable,nullptr);
if (status!=SQLITE_OK) {
printf("Database::Database sqlite3_prepare_v2 returned error code: %d\n",status);
}
status = sqlite3_prepare_v2(db,stmt1,std::strlen(stmt1),&init_ftable,nullptr);
if (status!=SQLITE_OK) {
printf("Database::Database sqlite3_prepare_v2 returned error code: %d\n",status);
}
status = sqlite3_step(init_ptable);
if (status!=SQLITE_DONE) printf("init_ptable - sqlite3_step returned error code: %d\n",status);
status = sqlite3_step(init_ftable);
if (status!=SQLITE_DONE) printf("init_ftable - sqlite3_step returned error code: %d\n",status);
status = sqlite3_finalize(init_ptable);
init_ptable = nullptr;
if (status!=SQLITE_OK) printf("init_ptable - sqlite3 NOT OK after sqlite3_finalize\n");
status = sqlite3_finalize(init_ftable);
init_ftable = nullptr;
if (status!=SQLITE_OK) printf("init_ftable - sqlite3 NOT OK after sqlite3_finalize\n");
}
Database::Database(std::string path, bool debug) : Database(path) {
this->debug = debug;
}
Database::Database(Database&& d) {
this->db = d.db;
d.db = nullptr;
}
Database& Database::operator=(Database&& d) {
this->~Database();
new (this) Database(std::move(d));
return (*this);
}
Database::~Database() {
if (!db) return;
end_transaction();
int status = sqlite3_close(db);
if (status==SQLITE_BUSY) {
printf("Database::~Database WARNING! SQLITE_BUSY on close!\n");
} else if (status!=SQLITE_OK) {
printf("Database::~Database sqlite3_close returned error code: %d\n",status);
}
db = nullptr;
printf("Database closed.\n");
}
int Database::getMaxGenerationNumber() {
assert(db && "Database resource is missing!");
sqlite3_stmt* get_max_gen;
const char* stmt = "select max(generation) from particles";
int status = sqlite3_prepare_v2(db,stmt,std::strlen(stmt),&get_max_gen,nullptr);
if (status!=SQLITE_OK) printf("Database::getMaxGenerationNumber sqlite3_prepare_v2 returned error code: %d\n",status);
status = sqlite3_step(get_max_gen);
int generationNumberMax;
if (status==SQLITE_DONE) generationNumberMax = 0;
else if (status!=SQLITE_ROW) printf("Database::getMaxGenerationNumber sqlite3_step failed to return expected row\n");
else generationNumberMax = sqlite3_column_int(get_max_gen,0);
printf("Database::getMaxGenerationNumber returned: %d\n",generationNumberMax);
status = sqlite3_finalize(get_max_gen);
get_max_gen = nullptr;
if (status!=SQLITE_OK) printf("get_max_gen - sqlite3 NOT OK after sqlite3_finalize\n");
return generationNumberMax;
}
int Database::getTotalParticlesInDB() {
assert(db && "Database resource is missing!");
sqlite3_stmt* get_total_particles;
const char* stmt = "select count(*) from particles";
int status = sqlite3_prepare_v2(db,stmt,std::strlen(stmt),&get_total_particles,nullptr);
if (status!=SQLITE_OK) printf("Database::getTotalParticlesInDB sqlite3_prepare_v2 returned error code: %d\n",status);
status = sqlite3_step(get_total_particles);
if (status!=SQLITE_ROW) printf("Database::getTotalParticlesInDB sqlite3_step failed to return expected row\n");
int totalParticles = sqlite3_column_int(get_total_particles,0);
printf("Database::getTotalParticlesInDB returned: %d\n",totalParticles);
status = sqlite3_finalize(get_total_particles);
get_total_particles = nullptr;
if (status!=SQLITE_OK) printf("get_total_particles - sqlite3 NOT OK after sqlite3_finalize\n");
return totalParticles;
}
int Database::countParticlesInGeneration(const int& generationNumber) {
assert(db && "Database resource is missing!");
sqlite3_stmt* count_particles_generation;
const char* stmt = "select count(*) from particles where generation=?";
int status = sqlite3_prepare_v2(db,stmt,std::strlen(stmt),&count_particles_generation,nullptr);
if (status!=SQLITE_OK) printf("Database::countParticlesInGeneration sqlite3_prepare_v2 returned error code: %d\n",status);
status = sqlite3_bind_int(count_particles_generation,1,generationNumber);
if (status!=SQLITE_OK) printf("Database::countParticlesInGeneration sqlite3_bind_int returned error code: %d\n",status);
status = sqlite3_step(count_particles_generation);
if (status!=SQLITE_ROW) printf("Database::countParticlesInGeneration sqlite3_step failed to return expected row\n");
int totalParticles = sqlite3_column_int(count_particles_generation,0);
printf("Database::countParticlesInGeneration returned: %d\n",totalParticles);
status = sqlite3_finalize(count_particles_generation);
count_particles_generation = nullptr;
if (status!=SQLITE_OK) printf("count_particles_generation - sqlite3 NOT OK after sqlite3_finalize\n");
printf("Database::countParticlesInGeneration returning: %d\n",totalParticles);
return totalParticles;
}
Lamina Database::getLaminaParticlesForGeneration(const int& generationNumber) {
assert(db && "Database resource is missing!");
std::vector<LaminaParticle> particles;
sqlite3_stmt* get_lamina_particles_gen;
const char* stmt = "select x,y,z from particles where generation=? and type=?";
const char* type = "Lamina";
int status = sqlite3_prepare_v2(db,stmt,std::strlen(stmt),&get_lamina_particles_gen,nullptr);
if (status!=SQLITE_OK) printf("Database::getLaminaParticlesForGeneration sqlite3_prepare_v2 returned error code: %d\n",status);
status = sqlite3_bind_int(get_lamina_particles_gen,1,generationNumber);
if (status!=SQLITE_OK) printf("Database::getLaminaParticlesForGeneration sqlite_bind_int returned error code: %d\n",status);
status = sqlite3_bind_text(get_lamina_particles_gen,2,type,std::strlen(type),SQLITE_STATIC);
if (status!=SQLITE_OK) printf("Database::getLaminaParticlesForGeneration sqlite_bind_text returned error code: %d\n",status);
status = sqlite3_step(get_lamina_particles_gen);
while (status==SQLITE_ROW) {
double x = sqlite3_column_double(get_lamina_particles_gen,0);
double y = sqlite3_column_double(get_lamina_particles_gen,1);
double z = sqlite3_column_double(get_lamina_particles_gen,2);
particles.push_back(LaminaParticle(x,y,z));
status = sqlite3_step(get_lamina_particles_gen);
}
if (status!=SQLITE_DONE) printf("Database::getLaminaParticlesForGeneration sqlite3_step returned error code: %d\n",status);
status = sqlite3_finalize(get_lamina_particles_gen);
get_lamina_particles_gen = nullptr;
if (status!=SQLITE_OK) printf("get_lamina_particles_gen - sqlite3 NOT OK after sqlite3_finalize\n");
if (debug) printf("Read %d lamina particle(s) from the database.\n",(int)particles.size());
return Lamina(particles);
}
std::vector<LaminaParticle> Database::getAllLaminaParticles() {
assert(db && "Database resource is missing!");
std::vector<LaminaParticle> particles;
sqlite3_stmt* get_lamina_particles;
const char* stmt = "select x,y,z from particles where type=?";
const char* type = "Lamina";
int status = sqlite3_prepare_v2(db,stmt,std::strlen(stmt),&get_lamina_particles,nullptr);
if (status!=SQLITE_OK) printf("Database::getAllLaminaParticles sqlite3_prepare_v2 returned error code: %d\n",status);
status = sqlite3_bind_text(get_lamina_particles,1,type,std::strlen(type),SQLITE_STATIC);
if (status!=SQLITE_OK) printf("Database::getAllLaminaParticles sqlite_bind_text returned error code: %d\n",status);
status = sqlite3_step(get_lamina_particles);
while (status==SQLITE_ROW) {
double x = sqlite3_column_double(get_lamina_particles,0);
double y = sqlite3_column_double(get_lamina_particles,1);
double z = sqlite3_column_double(get_lamina_particles,2);
particles.push_back(LaminaParticle(x,y,z));
status = sqlite3_step(get_lamina_particles);
}
if (status!=SQLITE_DONE) printf("Database::getAllLaminaParticles sqlite3_step returned error code: %d\n",status);
status = sqlite3_finalize(get_lamina_particles);
get_lamina_particles = nullptr;
if (status!=SQLITE_OK) printf("get_lamina_particles - sqlite3 NOT OK after sqlite3_finalize\n");
if (debug) printf("Read %d lamina particle(s) from the database.\n",(int)particles.size());
return particles;
}
Source Database::getSourceParticles() {
assert(db && "Database resource is missing!");
std::vector<SourceParticle> particles;
sqlite3_stmt* get_source_particles;
const char* stmt = "select x,y,z,q from particles where type=?";
const char* type = "Source";
int status = sqlite3_prepare_v2(db,stmt,std::strlen(stmt),&get_source_particles,nullptr);
if (status!=SQLITE_OK) printf("Database::getSourceParticles sqlite3_prepare_v2 returned error code: %d\n",status);
status = sqlite3_bind_text(get_source_particles,1,type,std::strlen(type),SQLITE_STATIC);
if (status!=SQLITE_OK) printf("Database::getSourceParticles sqlite_bind_text returned error code: %d\n",status);
status = sqlite3_step(get_source_particles);
while (status==SQLITE_ROW) {
double x = sqlite3_column_double(get_source_particles,0);
double y = sqlite3_column_double(get_source_particles,1);
double z = sqlite3_column_double(get_source_particles,2);
double q = sqlite3_column_double(get_source_particles,3);
particles.push_back(SourceParticle(x,y,z,q));
status = sqlite3_step(get_source_particles);
}
if (status!=SQLITE_DONE) printf("Database::getSourceParticles sqlite3_step returned error code: %d\n",status);
status = sqlite3_finalize(get_source_particles);
get_source_particles = nullptr;
if (status!=SQLITE_OK) printf("get_source_particles - sqlite3 NOT OK after sqlite3_finalize\n");
if (debug) printf("Read %d system particle(s).\n",(int)particles.size());
return Source(particles);
}
void Database::hold_open_transaction() {
if (in_transaction) return;
assert(db && "Database resource is missing!");
in_transaction = true;
sqlite3_stmt* begin;
const char* stmt = "begin transaction";
int status = sqlite3_prepare_v2(db,stmt,std::strlen(stmt),&begin,nullptr);
if (status!=SQLITE_OK) printf("Database::begin_transaction sqlite3_prepare_v2 returned error code: %d\n",status);
status = sqlite3_step(begin);
if (status!=SQLITE_DONE) printf("Database::begin_transaction sqlite3_step returned unexpected code: %d\n",status);
status = sqlite3_finalize(begin);
begin = nullptr;
if (status!=SQLITE_OK) printf("begin - sqlite3 NOT OK after sqlite3_finalize\n");
}
void Database::end_transaction() {
if (!in_transaction) return;
assert(db && "Database resource is missing!");
in_transaction = false;
sqlite3_stmt* end;
const char* stmt = "end transaction";
int status = sqlite3_prepare_v2(db,stmt,std::strlen(stmt),&end,nullptr);
if (status!=SQLITE_OK) printf("Database::end_transaction sqlite3_prepare_v2 returned error code: %d\n",status);
status = sqlite3_step(end);
if (status!=SQLITE_DONE) printf("Database::end_transaction sqlite3_step returned unexpected code: %d\n",status);
status = sqlite3_finalize(end);
end = nullptr;
if (status!=SQLITE_OK) printf("end - sqlite3 NOT OK after sqlite3_finalize\n");
}
void Database::insertSourceParticles(const Source& source) {
assert(db && "Database resource is missing!");
hold_open_transaction();
sqlite3_stmt* insert_particles;
const char* stmt = "insert into particles values(?,?,?,?,?,?)";
const char* type = "Source";
const int generation = 0;
const std::vector<SourceParticle> particles = source.asVector();
int status = sqlite3_prepare_v2(db,stmt,std::strlen(stmt),&insert_particles,nullptr);
if (status!=SQLITE_OK) printf("Database::insertSourceParticles sqlite3_prepare_v2 returned error code: %d\n",status);
for (auto iter = particles.begin(); iter!=particles.end(); iter++) {
SourceParticle particle = *iter;
status = sqlite3_reset(insert_particles);
if (status!=SQLITE_OK) printf("Database::insertSourceParticles sqlite3_reset returned error code: %d\n",status);
status = sqlite3_clear_bindings(insert_particles);
if (status!=SQLITE_OK) printf("Database::insertSourceParticles sqlite3_clear_bindings returned error code: %d\n",status);
status = sqlite3_bind_double(insert_particles,1,particle.getX());
if (status!=SQLITE_OK) printf("Database::insertSourceParticles sqlite3_bind_double returned error code: %d\n",status);
status = sqlite3_bind_double(insert_particles,2,particle.getY());
if (status!=SQLITE_OK) printf("Database::insertSourceParticles sqlite3_bind_double returned error code: %d\n",status);
status = sqlite3_bind_double(insert_particles,3,particle.getZ());
if (status!=SQLITE_OK) printf("Database::insertSourceParticles sqlite3_bind_double returned error code: %d\n",status);
status = sqlite3_bind_double(insert_particles,4,particle.getQ());
if (status!=SQLITE_OK) printf("Database::insertSourceParticles sqlite3_bind_dbouel returned error code: %d\n",status);
status = sqlite3_bind_text(insert_particles,5,type,std::strlen(type),SQLITE_STATIC);
if (status!=SQLITE_OK) printf("Database::insertSourceParticles sqlite3_bind_text returned error code: %d\n",status);
status = sqlite3_bind_int(insert_particles,6,generation);
if (status!=SQLITE_OK) printf("Database::insertSourceParticles sqlite3_bind_int returned error code: %d\n",status);
status = sqlite3_step(insert_particles);
if (status!=SQLITE_DONE) printf("Database::insertSourceParticles sqlite3_step returned unexpected code: %d\n",status);
}
status = sqlite3_finalize(insert_particles);
insert_particles = nullptr;
if (status!=SQLITE_OK) printf("insert_particles - sqlite3 NOT OK after sqlite3_finalize\n");
if (debug) printf("Wrote %d system particle(s).\n",(int)particles.size());
}
void Database::insertLaminaParticles(const Lamina& lamina,const int& generationNumber) {
assert(db && "Database resource is missing!");
hold_open_transaction();
sqlite3_stmt* insert_particles;
const char* stmt = "insert into particles values(?,?,?,?,?,?)";
const char* type = "Lamina";
const int q = 0;
const std::vector<LaminaParticle> particles = lamina.asVector();
int status = sqlite3_prepare_v2(db,stmt,std::strlen(stmt),&insert_particles,nullptr);
if (status!=SQLITE_OK) printf("Database::insertLaminaParticles sqlite3_prepare_v2 returned error code: %d\n",status);
for (auto iter = particles.begin(); iter!=particles.end(); iter++) {
LaminaParticle particle = *iter;
status = sqlite3_reset(insert_particles);
if (status!=SQLITE_OK) printf("Database::insertLaminaParticles sqlite3_reset returned error code: %d\n",status);
status = sqlite3_clear_bindings(insert_particles);
if (status!=SQLITE_OK) printf("Database::insertLaminaParticles sqlite3_clear_bindings returned error code: %d\n",status);
status = sqlite3_bind_double(insert_particles,1,particle.getX());
if (status!=SQLITE_OK) printf("Database::insertLaminaParticles sqlite3_bind_double returned error code: %d\n",status);
status = sqlite3_bind_double(insert_particles,2,particle.getY());
if (status!=SQLITE_OK) printf("Database::insertLaminaParticles sqlite3_bind_double returned error code: %d\n",status);
status = sqlite3_bind_double(insert_particles,3,particle.getZ());
if (status!=SQLITE_OK) printf("Database::insertLaminaParticles sqlite3_bind_double returned error code: %d\n",status);
status = sqlite3_bind_double(insert_particles,4,q);
if (status!=SQLITE_OK) printf("Database::insertLaminaParticles sqlite3_bind_double returned error code: %d\n",status);
status = sqlite3_bind_text(insert_particles,5,type,std::strlen(type),SQLITE_STATIC);
if (status!=SQLITE_OK) printf("Database::insertLaminaParticles sqlite3_bind_text returned error code: %d\n",status);
status = sqlite3_bind_int(insert_particles,6,generationNumber);
if (status!=SQLITE_OK) printf("Database::insertLaminaParticles sqlite3_bind_int returned error code: %d\n",status);
status = sqlite3_step(insert_particles);
if (status!=SQLITE_DONE) printf("Database::insertLaminaParticles sqlite3_step returned unexpected code: %d\n",status);
}
status = sqlite3_finalize(insert_particles);
insert_particles = nullptr;
if (status!=SQLITE_OK) printf("insert_particles - sqlite3 NOT OK after sqlite3_finalize\n");
if (debug) printf("Wrote %d lamina particle(s).\n",(int)particles.size());
}
void Database::insertFitnessLog(const std::vector<double>& v) {
assert(db && "Database resource is missing!");
hold_open_transaction();
sqlite3_stmt* fitness;
const char* stmt = "insert into fitness values(?,?)";
int generationNumber = 0;
int status = sqlite3_prepare_v2(db,stmt,std::strlen(stmt),&fitness,nullptr);
if (status!=SQLITE_OK) printf("Database::insertFitnessLog sqlite3_prepare_v2 returned error code: %d\n",status);
for (auto iter = v.begin(), end = v.end(); iter!=end; iter++) {
status = sqlite3_reset(fitness);
if (status!=SQLITE_OK) printf("Database::insertFitnessLog sqlite3_reset returned error code: %d\n",status);
status = sqlite3_clear_bindings(fitness);
if (status!=SQLITE_OK) printf("Database::insertFitnessLog sqlite3_clear_bindings returned error code: %d\n",status);
status = sqlite3_bind_double(fitness,1,*iter);
if (status!=SQLITE_OK) printf("Database::insertFitnessLog sqlite3_clear_bindings returned error code: %d\n",status);
status = sqlite3_bind_double(fitness,2,generationNumber++);
if (status!=SQLITE_OK) printf("Database::insertFitnessLog sqlite3_bind_double returned error code: %d\n",status);
status = sqlite3_step(fitness);
if (status!=SQLITE_DONE) printf("Database::insertFitnessLog sqlite3_step returned unexpected code: %d\n",status);
}
status = sqlite3_finalize(fitness);
fitness = nullptr;
if (status!=SQLITE_OK) printf("fitness - sqlite3 NOT OK after sqlite3_finalize\n");
if (debug) printf("Wrote %d fitness log entries.\n",(int)v.size());
}
void Database::vacuum() {
assert(db && "Database resource is missing!");
end_transaction();
sqlite3_stmt* vacuum;
const char* stmt = "vacuum";
int status = sqlite3_prepare_v2(db,stmt,std::strlen(stmt),&vacuum,nullptr);
if (status!=SQLITE_OK) printf("Database::vacuum sqlite3_prepare_v2 returned error code: %d\n",status);
status = sqlite3_step(vacuum);
if (status!=SQLITE_DONE) printf("Database::vacuum sqlite3_step returned unexpected code: %d\n",status);
status = sqlite3_finalize(vacuum);
vacuum = nullptr;
if (status!=SQLITE_OK) printf("vacuum - sqlite3 NOT OK after sqlite3_finalize\n");
}
void Database::clear() {
assert(db && "Database resource is missing!");
hold_open_transaction();
sqlite3_stmt* clear;
std::unique_ptr<char> stmt(new char[200]);
strcpy(stmt.get(),"delete from particles");
int status = sqlite3_prepare_v2(db,stmt.get(),std::strlen(stmt.get()),&clear,nullptr);
if (status!=SQLITE_OK) printf("Database::clear sqlite3_prepare_v2 returned error code: %d\n",status);
status = sqlite3_step(clear);
if (status!=SQLITE_DONE) printf("Database::clear sqlite3_step returned unexpected code: %d\n",status);
status = sqlite3_finalize(clear);
clear = nullptr;
if (status!=SQLITE_OK) printf("clear - sqlite3 NOT OK after sqlite3_finalize\n");
strcpy(stmt.get(),"delete from fitness");
status = sqlite3_prepare_v2(db,stmt.get(),std::strlen(stmt.get()),&clear,nullptr);
if (status!=SQLITE_OK) printf("Database::clear sqlite3_prepare_v2 returned error code: %d\n",status);
status = sqlite3_step(clear);
if (status!=SQLITE_DONE) printf("Database::clear sqlite3_step returned unexpected code: %d\n",status);
status = sqlite3_finalize(clear);
clear = nullptr;
if (status!=SQLITE_OK) printf("clear - sqlite3 NOT OK after sqlite3_finalize\n");
vacuum();
printf("Database wiped!\n");
}
| {
"content_hash": "af0d54dcb510f125f1214547c355017e",
"timestamp": "",
"source": "github",
"line_count": 366,
"max_line_length": 128,
"avg_line_length": 54.43715846994535,
"alnum_prop": 0.7379040353342702,
"repo_name": "henfredemars/Lamina-Project",
"id": "a41becd6c52c8e92b2ecdddf30239c64e2d4262f",
"size": "19956",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/sim/Database.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "6822843"
},
{
"name": "C++",
"bytes": "3515349"
},
{
"name": "CMake",
"bytes": "6203"
},
{
"name": "Groff",
"bytes": "9422"
},
{
"name": "Makefile",
"bytes": "51634"
},
{
"name": "Shell",
"bytes": "342588"
}
],
"symlink_target": ""
} |
using namespace System;
using namespace System::Reflection;
using namespace System::Runtime::CompilerServices;
using namespace System::Runtime::InteropServices;
using namespace System::Security::Permissions;
//
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
//
[assembly:AssemblyTitleAttribute("PcapDotNet.Core")];
[assembly:AssemblyDescriptionAttribute("")];
[assembly:AssemblyConfigurationAttribute("")];
[assembly:AssemblyCompanyAttribute("Pcap.Net")];
[assembly:AssemblyProductAttribute("PcapDotNet.Core")];
[assembly:AssemblyCopyrightAttribute("Copyright (c) 2010")];
[assembly:AssemblyTrademarkAttribute("")];
[assembly:AssemblyCultureAttribute("")];
//
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the value or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly:AssemblyVersionAttribute("0.10.0.*")];
[assembly:AssemblyFileVersionAttribute("0.10.0.0")]
[assembly:ComVisible(false)];
[assembly:CLSCompliantAttribute(true)];
[assembly:SecurityPermission(SecurityAction::RequestMinimum, UnmanagedCode = true)];
| {
"content_hash": "0b6e5a9a3502f1dab14562536df9ca71",
"timestamp": "",
"source": "github",
"line_count": 39,
"max_line_length": 84,
"avg_line_length": 34.56410256410256,
"alnum_prop": 0.7707715133531158,
"repo_name": "okaywang/MyPcap",
"id": "0de6e681fa433eb33046f3d6aed8ab96cb9c1164",
"size": "1348",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "PcapDotNet/src/PcapDotNet.Core/Properties/AssemblyInfo.cpp",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "223064"
},
{
"name": "C#",
"bytes": "2380237"
},
{
"name": "C++",
"bytes": "148171"
},
{
"name": "CSS",
"bytes": "9920"
},
{
"name": "HTML",
"bytes": "2019251"
},
{
"name": "Makefile",
"bytes": "3406"
}
],
"symlink_target": ""
} |
package org.lwjgl.test.openal;
import java.nio.IntBuffer;
import org.lwjgl.BufferUtils;
import org.lwjgl.openal.AL;
import org.lwjgl.openal.ALC10;
/**
*
* This is a test for the ALC part of OpenAL
*
* @author Brian Matzon <brian@matzon.dk>
* @version $Revision: 2983 $
* $Id: ALCTest.java 2983 2008-04-07 18:36:09Z matzon $
*/
public class ALCTest extends BasicTest {
/**
* Creates an instance of ALCTest
*/
public ALCTest() {
super();
}
/**
* Runs the actual test, using supplied arguments
*/
protected void execute(String[] args) {
//error stuff
int lastError = ALC10.ALC_NO_ERROR;
//create attribute list for context creation
IntBuffer buffer = BufferUtils.createIntBuffer(7);
if ((lastError = ALC10.alcGetError(AL.getDevice())) != ALC10.ALC_NO_ERROR) {
System.out.println("ALC Error: " + ALC10.alcGetString(AL.getDevice(), lastError));
System.exit(-1);
}
//query
System.out.println(
"DEFAULT_DEVICE_SPECIFIER: "
+ ALC10.alcGetString(AL.getDevice(), ALC10.ALC_DEFAULT_DEVICE_SPECIFIER));
System.out.println(
"DEVICE_SPECIFIER: " + ALC10.alcGetString(AL.getDevice(), ALC10.ALC_DEVICE_SPECIFIER));
System.out.println("EXTENSIONS: " + ALC10.alcGetString(AL.getDevice(), ALC10.ALC_EXTENSIONS));
//mo query
buffer.rewind();
buffer.position(0);
ALC10.alcGetInteger(AL.getDevice(), ALC10.ALC_MAJOR_VERSION, buffer);
ALC10.alcGetInteger(AL.getDevice(), ALC10.ALC_MINOR_VERSION, (IntBuffer) buffer.position(1));
System.out.println("ALC_MAJOR_VERSION: " + buffer.get(0));
System.out.println("ALC_MINOR_VERSION: " + buffer.get(1));
//no check for ALC_ALL_ATTRIBUTES / ALC_ATTRIBUTES_SIZE since it
//is buggy on win32 - my dev platform
//get an enumerstion value
System.out.println(
"Value of ALC_MAJOR_VERSION: "
+ ALC10.alcGetEnumValue(AL.getDevice(), "ALC_MAJOR_VERSION"));
alExit();
}
/**
* main entry point
*
* @param args String array containing arguments
*/
public static void main(String[] args) {
ALCTest alcTest = new ALCTest();
alcTest.execute(args);
System.exit(0);
}
} | {
"content_hash": "beaebd63c9bb46f03ffbeecf041ab523",
"timestamp": "",
"source": "github",
"line_count": 80,
"max_line_length": 98,
"avg_line_length": 27.375,
"alnum_prop": 0.6616438356164384,
"repo_name": "mk12/mycraft",
"id": "fef55692a640d1dbb08191e2685d900052e2d026",
"size": "3802",
"binary": false,
"copies": "4",
"ref": "refs/heads/main",
"path": "lib/LWJGL/lwjgl-source-2/src/java/org/lwjgl/test/openal/ALCTest.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "1980831"
},
{
"name": "C++",
"bytes": "14305"
},
{
"name": "Java",
"bytes": "7505246"
},
{
"name": "Objective-C",
"bytes": "32654"
}
],
"symlink_target": ""
} |
"""This pip smoke test verifies dependency files exist in the pip package.
This script runs bazel queries to see what python files are required by the
tests and ensures they are in the pip package superset.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import subprocess
os.chdir(os.path.abspath(os.path.join(os.path.dirname(__file__), "../../..")))
PIP_PACKAGE_QUERY_EXPRESSION = (
"deps(//tensorflow/tools/pip_package:build_pip_package)")
def GetBuild(dir_base):
"""Get the list of BUILD file all targets recursively startind at dir_base."""
items = []
for root, _, files in os.walk(dir_base):
for name in files:
if (name == "BUILD" and
root.find("tensorflow/contrib/lite/examples/android") == -1):
items.append("//" + root + ":all")
return items
def BuildPyTestDependencies():
python_targets = GetBuild("tensorflow/python")
contrib_targets = GetBuild("tensorflow/contrib")
tensorboard_targets = GetBuild("tensorflow/contrib/tensorboard")
tensorflow_targets = GetBuild("tensorflow")
# Build list of test targets,
# python + contrib - tensorboard - attr(manual|pno_pip)
targets = " + ".join(python_targets)
for t in contrib_targets:
targets += " + " + t
for t in tensorboard_targets:
targets += " - " + t
targets += ' - attr(tags, "manual|no_pip", %s)' % " + ".join(
tensorflow_targets)
query_kind = "kind(py_test, %s)" % targets
# Skip benchmarks etc.
query_filter = 'filter("^((?!benchmark).)*$", %s)' % query_kind
# Get the dependencies
query_deps = "deps(%s, 1)" % query_filter
return python_targets, query_deps
PYTHON_TARGETS, PY_TEST_QUERY_EXPRESSION = BuildPyTestDependencies()
# Hard-coded blacklist of files if not included in pip package
# TODO(amitpatankar): Clean up blacklist.
BLACKLIST = [
"//tensorflow/python:extra_py_tests_deps",
"//tensorflow/cc/saved_model:saved_model_half_plus_two",
"//tensorflow:no_tensorflow_py_deps",
"//tensorflow/tools/pip_package:win_pip_package_marker",
"//tensorflow/python:test_ops_2",
"//tensorflow/python:tf_optimizer",
"//tensorflow/python:compare_test_proto_py",
"//tensorflow/core:image_testdata",
"//tensorflow/core:lmdb_testdata",
"//tensorflow/core/kernels/cloud:bigquery_reader_ops",
"//tensorflow/python/feature_column:vocabulary_testdata",
"//tensorflow/python:framework/test_file_system.so",
# contrib
"//tensorflow/contrib/session_bundle:session_bundle_half_plus_two",
"//tensorflow/contrib/keras:testing_utils",
"//tensorflow/contrib/lite/experimental/examples/lstm:tflite_lstm",
"//tensorflow/contrib/lite/experimental/examples/lstm:tflite_lstm.py",
"//tensorflow/contrib/lite/experimental/examples/lstm:unidirectional_sequence_lstm_test", # pylint:disable=line-too-long
"//tensorflow/contrib/lite/experimental/examples/lstm:unidirectional_sequence_lstm_test.py", # pylint:disable=line-too-long
"//tensorflow/contrib/lite/python:interpreter",
"//tensorflow/contrib/lite/python:interpreter_test",
"//tensorflow/contrib/lite/python:interpreter.py",
"//tensorflow/contrib/lite/python:interpreter_test.py",
"//tensorflow/contrib/ffmpeg:test_data",
"//tensorflow/contrib/fused_conv:fused_conv2d_bias_activation_op_test_base",
"//tensorflow/contrib/hadoop:test_data",
"//tensorflow/contrib/factorization/examples:mnist",
"//tensorflow/contrib/factorization/examples:mnist.py",
"//tensorflow/contrib/factorization:factorization_py_CYCLIC_DEPENDENCIES_THAT_NEED_TO_GO", # pylint:disable=line-too-long
"//tensorflow/contrib/framework:checkpoint_ops_testdata",
"//tensorflow/contrib/bayesflow:reinforce_simple_example",
"//tensorflow/contrib/bayesflow:examples/reinforce_simple/reinforce_simple_example.py", # pylint:disable=line-too-long
"//tensorflow/contrib/timeseries/examples:predict",
"//tensorflow/contrib/timeseries/examples:multivariate",
"//tensorflow/contrib/timeseries/examples:known_anomaly",
"//tensorflow/contrib/timeseries/examples:data/period_trend.csv", # pylint:disable=line-too-long
"//tensorflow/contrib/timeseries/python/timeseries:test_utils",
"//tensorflow/contrib/timeseries/python/timeseries/state_space_models:test_utils", # pylint:disable=line-too-long
"//tensorflow/contrib/image:sparse_image_warp_test_data",
]
def main():
"""This script runs the pip smoke test.
Raises:
RuntimeError: If any dependencies for py_tests exist in subSet
Prerequisites:
1. Bazel is installed.
2. Running in github repo of tensorflow.
3. Configure has been run.
"""
# pip_package_dependencies_list is the list of included files in pip packages
pip_package_dependencies = subprocess.check_output(
["bazel", "cquery", PIP_PACKAGE_QUERY_EXPRESSION])
pip_package_dependencies_list = pip_package_dependencies.strip().split("\n")
pip_package_dependencies_list = [
x.split()[0] for x in pip_package_dependencies_list
]
print("Pip package superset size: %d" % len(pip_package_dependencies_list))
# tf_py_test_dependencies is the list of dependencies for all python
# tests in tensorflow
tf_py_test_dependencies = subprocess.check_output(
["bazel", "cquery", PY_TEST_QUERY_EXPRESSION])
tf_py_test_dependencies_list = tf_py_test_dependencies.strip().split("\n")
tf_py_test_dependencies_list = [
x.split()[0] for x in tf_py_test_dependencies.strip().split("\n")
]
print("Pytest dependency subset size: %d" % len(tf_py_test_dependencies_list))
missing_dependencies = []
# File extensions and endings to ignore
ignore_extensions = ["_test", "_test.py"]
ignored_files = 0
blacklisted_files = len(BLACKLIST)
# Compare dependencies
for dependency in tf_py_test_dependencies_list:
if dependency and dependency.startswith("//tensorflow"):
ignore = False
# Ignore extensions
if any(dependency.endswith(ext) for ext in ignore_extensions):
ignore = True
ignored_files += 1
# Check if the dependency is in the pip package, the blacklist, or
# should be ignored because of its file extension
if not (ignore or dependency in pip_package_dependencies_list or
dependency in BLACKLIST):
missing_dependencies.append(dependency)
print("Ignored files: %d" % ignored_files)
print("Blacklisted files: %d" % blacklisted_files)
if missing_dependencies:
print("Missing the following dependencies from pip_packages:")
for missing_dependency in missing_dependencies:
print("\nMissing dependency: %s " % missing_dependency)
print("Affected Tests:")
rdep_query = ("rdeps(kind(py_test, %s), %s)" %
(" + ".join(PYTHON_TARGETS), missing_dependency))
affected_tests = subprocess.check_output(["bazel", "cquery", rdep_query])
affected_tests_list = affected_tests.split("\n")[:-2]
print("\n".join(affected_tests_list))
raise RuntimeError("""
One or more added test dependencies are not in the pip package.
If these test dependencies need to be in TensorFlow pip package, please add them to //tensorflow/tools/pip_package/BUILD.
Else either blacklist the dependencies in //tensorflow/tools/pip_package/pip_smoke_test.py
or add no_pip tag to the test.""")
else:
print("TEST PASSED")
if __name__ == "__main__":
main()
| {
"content_hash": "e470f7567a6d76167d2f4f1c37b8a91e",
"timestamp": "",
"source": "github",
"line_count": 178,
"max_line_length": 128,
"avg_line_length": 41.80898876404494,
"alnum_prop": 0.7037086804622413,
"repo_name": "girving/tensorflow",
"id": "45106b35fc2e2c5bb981b178785ebf3089582c4d",
"size": "8131",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tensorflow/tools/pip_package/pip_smoke_test.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "3325"
},
{
"name": "Batchfile",
"bytes": "10132"
},
{
"name": "C",
"bytes": "343258"
},
{
"name": "C#",
"bytes": "8446"
},
{
"name": "C++",
"bytes": "50036869"
},
{
"name": "CMake",
"bytes": "196127"
},
{
"name": "Dockerfile",
"bytes": "36386"
},
{
"name": "Go",
"bytes": "1254086"
},
{
"name": "HTML",
"bytes": "4681865"
},
{
"name": "Java",
"bytes": "867313"
},
{
"name": "Jupyter Notebook",
"bytes": "2604735"
},
{
"name": "LLVM",
"bytes": "6536"
},
{
"name": "Makefile",
"bytes": "58787"
},
{
"name": "Objective-C",
"bytes": "15650"
},
{
"name": "Objective-C++",
"bytes": "99243"
},
{
"name": "PHP",
"bytes": "1357"
},
{
"name": "Perl",
"bytes": "7536"
},
{
"name": "PureBasic",
"bytes": "25356"
},
{
"name": "Python",
"bytes": "42041620"
},
{
"name": "Ruby",
"bytes": "553"
},
{
"name": "Shell",
"bytes": "477299"
},
{
"name": "Smarty",
"bytes": "6976"
}
],
"symlink_target": ""
} |
package com.jeequan.jeepay.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jeequan.jeepay.core.entity.SysLog;
import com.jeequan.jeepay.service.mapper.SysLogMapper;
import org.springframework.stereotype.Service;
/**
* <p>
* 系统操作日志表 服务实现类
* </p>
*
* @author [mybatis plus generator]
* @since 2021-04-27
*/
@Service
public class SysLogService extends ServiceImpl<SysLogMapper, SysLog> {
}
| {
"content_hash": "8f1b2c223abffdf0e353a45ceb58dfd5",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 70,
"avg_line_length": 22.15,
"alnum_prop": 0.7652370203160271,
"repo_name": "jmdhappy/xxpay-master",
"id": "46a1b2f9690603481ddf885b2596f7bd1976cc22",
"size": "1132",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "jeepay-service/src/main/java/com/jeequan/jeepay/service/impl/SysLogService.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "158171"
},
{
"name": "Dockerfile",
"bytes": "938"
},
{
"name": "FreeMarker",
"bytes": "110264"
},
{
"name": "HTML",
"bytes": "9457"
},
{
"name": "Java",
"bytes": "1149779"
},
{
"name": "JavaScript",
"bytes": "604196"
},
{
"name": "Shell",
"bytes": "5503"
},
{
"name": "TSQL",
"bytes": "10858"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<resources>
<resource name="fBasic" type="RESOURCE"/>
<resource name="fMedium" type="RESOURCE"/>
<resource name="fLarge" type="RESOURCE"/>
</resources>
| {
"content_hash": "efc7ae80ac20e1f3652248c589f98de5",
"timestamp": "",
"source": "github",
"line_count": 6,
"max_line_length": 54,
"avg_line_length": 35.5,
"alnum_prop": 0.6807511737089202,
"repo_name": "Widdershin/old-game-maker-games",
"id": "8ea6f6cef580e6c764a3f4d2c7259f31f72aecdd",
"size": "213",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Ludum Dare 20/Fonts/_resources.list.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Game Maker Language",
"bytes": "364836"
},
{
"name": "Python",
"bytes": "1221"
}
],
"symlink_target": ""
} |
_male_start_hi = ['https://media.giphy.com/media/dzaUX7CAG0Ihi/giphy-downsized.gif',
'https://media.giphy.com/media/oJiCqvIqPZE3u/giphy.gif']
_female_start_hi = ['https://media.giphy.com/media/a1QLZUUtCcgyA/giphy-downsized.gif',
'https://media.giphy.com/media/EPJZhOrStSpz2/giphy-downsized.gif']
import random
def get_start_hi(gender):
if gender == "male":
#return random.choice(_male_start_hi)
return _male_start_hi[1]
elif gender == "female":
#return random.choice(_female_start_hi)
return _female_start_hi[1]
else:
return random.choice(_male_start_hi) | {
"content_hash": "7f56036ef04ee2e2b9bdf3cf8b44eddc",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 86,
"avg_line_length": 40.375,
"alnum_prop": 0.6455108359133127,
"repo_name": "mayukh18/BlindChat",
"id": "c8688fee36421aa99493fb5277e4da3899d3b2bc",
"size": "646",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "modules/gifs.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "41"
},
{
"name": "HTML",
"bytes": "3075"
},
{
"name": "Python",
"bytes": "59076"
}
],
"symlink_target": ""
} |
import alt from '../libs/alt';
export default alt.generateActions(
'create', 'update', 'delete',
'attachToLane', 'detachFromLane',
'move'
); | {
"content_hash": "6f4f6d803f1be6c7ce3253b5c951dd81",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 37,
"avg_line_length": 21.857142857142858,
"alnum_prop": 0.6470588235294118,
"repo_name": "jahmaiosullivan/yoorcity",
"id": "defbd402dc0316f8af6bc569ee96338e5b3b8e4d",
"size": "153",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/actions/LaneActions.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1043"
},
{
"name": "HTML",
"bytes": "294"
},
{
"name": "JavaScript",
"bytes": "29820"
}
],
"symlink_target": ""
} |
This design document is a proposal for Dashboard UI user experience that
covers navigation and the way of displaying and interacting with K8s objects.
## Background
Currently Dashboard UI allows users to see and interact with a very limited
subset of Kubernetes resources. For example, it shows Replication Controllers,
while ignoring existence of Replica Sets, Deployments, Daemon Sets, etc.
Additionally, it does not allow for creating or modifying individual
resources, while supporting only application creation (akin to `kubectl run`)
and scaling. For more details see [mockups](mockups/11-11-2015-initial) of
current implementation.
These limitations have been number one source of feature requests and
user complaints (e.g., #564, #524, #509, #510, #232). The core team also
considers solving these limitations as a natural evolution of the UI.
## Problem statement
* Scale the UX to support displaying and editing all current and future
Kubernetes resources (e.g., replica sets, daemon sets, container, nodes,
volumes, secrets, deployments, etc.).
* Scale for the number of objects displayed (currently: cards are suitable for
O(20), desired: show any number of objects).
* Guide users through use-case based views (don't just do API dump).
* Make the UI aware of namespaces and multi-cluster installations.
# Design
The design is based on a few novelties to the UX of Kubernetes Dashboard. This
is:
* introduction of use-case based navigation menu and views
* replacement of free-form cards by tabularized resource lists
* being explicit about Kubernetes resources displayed in the UI
* introduction of action bar for performing all actions on resources
## Navigation
Navigation is realized by left hand side menu. The menu consists of use case
driven categories that group Kubernetes resources. For example, there may be
category called "Apps" which deals with Replication Controllers, Pods,
Deployments, etc., and "Config" which deals with Secrets, Volumes,
Namespaces, etc. The exact definition of categories will happen in a separate
design.

Menu categories may be expanded into raw resource subpages for expert users.

Menu follows standard responsiveness practises where it folds into icons and
hamburger menu when space is limited.

## View templates
This section shows concepts used as templates for all views.
View which does not deal with a resource or a resource list, e.g., landing
page which shows an overview of a cluster. The page consists of, potentially
dismissable, blocks that display data.

Category view which shows lists of resources. In this mockup it is
(not defined yet) "Apps" category which was selected through the
navigation menu.

Action bar replaces floating action button. The reason for this change
is the fact that floating action buttons do not work well on desktop
form factors, which are used by vast majority of our users. On the other
hand, action bars work well on any form factors (desktop, mobile)
and can scale for different actions on different resources.

Details of the resource list block:

While the concept of cards used for displaying resources has some nice
characteristics (like information density) it has been a constant source of
problems. Users and developers complained about many issues: how do you sort
cards? how do you change their order? how do you paginate them? how do you
compare resources against each other? how do you distinct different resources
in a card stream? how do you do bulk operations?
We have identified that in order to solve these problems the cards can evolve
into tabularized list items which can show exactly the same information as
cards. This solution has many advantages, some of which are: pagination,
ordering, bulk actions or visual comparison. Following mockup outlines
the evolution:

Category views link to single resource views which show an unbounded list
of resources of single type (e.g., Replica Sets) and a short summary/
call to action block.

Details of an individual resource instance are shown on a views which displays
its properites and all related objects (e.g., Services that target a Pod).

## Future work
* Make it possible to add/remove columns from resource lists. This is to
accommodate different use cases and needs that different users have. This
can be based on individual user's preference or their profiles. The profiles
may be, e.g., "Debugging", "Release" or "Resource Management".
* Pivot labels into columns. For example, for every replica set in a list
have a column named `env` which displays the value of this label
(e.g., `dev`, `prod`, `test`). The pivot is user configurable.
* Design application menu categories. Tracked in
https://github.com/kubernetes/kubernetes/issues/22687
* Design individual resource lists and detail pages (for, e.g., Pods, Services,
Replica Sets, etc.)
* Advanced resource list filtering that supports label and field matching
* Better handling large number of resources: customized pagination and
section collapsing.
## Concrete pages
This section shows how templates proposed in the "View templates" section
can be applied to real examples.
"Apps" category:

Replication Controller list under "Apps" category:

Pod details overview:

Pod details events:

Pod details logs:

Pod details SSH tab:

Replication Controller details overview:

Replication Controller details events:

## Credits
[Source code](mockups/23-03-2016-scale-and-navigation/dashboard-scale-and-navigation.bmpr)
of the mockups.
Proposed by [@bryk](https://github.com/bryk),
[@cheld](https://github.com/cheld),
[@digitalfishpond](https://github.com/digitalfishpond),
[@floreks](https://github.com/floreks),
[@maciaszczykm](https://github.com/maciaszczykm),
[@olekzabl](https://github.com/olekzabl),
[@zreigz](https://github.com/zreigz) during 23-03-2016 design sprint day
([report](sprints/scale_ux_20160323.md)).
| {
"content_hash": "dcd6dcc8b7fa4f378bb4393784f9cb3f",
"timestamp": "",
"source": "github",
"line_count": 157,
"max_line_length": 112,
"avg_line_length": 47.47770700636943,
"alnum_prop": 0.7899114569358734,
"repo_name": "batikanu/dashboard",
"id": "39a3f6c1d73ca87d04f64e15e32a7038c8963e57",
"size": "7487",
"binary": false,
"copies": "10",
"ref": "refs/heads/master",
"path": "docs/design/navigation-and-scale.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "41506"
},
{
"name": "Go",
"bytes": "153769"
},
{
"name": "HTML",
"bytes": "89948"
},
{
"name": "JavaScript",
"bytes": "479520"
},
{
"name": "Shell",
"bytes": "4365"
}
],
"symlink_target": ""
} |
package app.mosn.zdepthshadowsample.fam;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.Gravity;
import android.widget.ImageView;
import app.mosn.zdepthshadowlayout.ZDepthShadowLayout;
import app.mosn.zdepthshadowlayout.utils.DisplayUtils;
import app.mosn.zdepthshadowsample.R;
public class FloatingActionMenuButton extends ZDepthShadowLayout {
protected int mIconId;
protected int mButtonSizeDp = 40;
protected int mIconSizeDp = 24;
public FloatingActionMenuButton(Context context) {
super(context);
init(null, 0);
}
@Override
protected void init(AttributeSet attrs, int defStyle) {
super.init(attrs, defStyle);
mAttrShape = SHAPE_OVAL;
mAttrZDepth = 2;
mAttrZDepthPaddingLeft = 3;
mAttrZDepthPaddingTop = 3;
mAttrZDepthPaddingRight = 3;
mAttrZDepthPaddingBottom = 3;
mAttrZDepthDoAnimation = true;
mAttrZDepthAnimDuration = 150;
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
// set Button LayoutParams
int buttonSize = DisplayUtils.convertDpToPx(getContext(), mButtonSizeDp);
int iconSize = DisplayUtils.convertDpToPx(getContext(), mIconSizeDp);
setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
// set Background Circle
ImageView bgImage = new ImageView(getContext());
bgImage.setLayoutParams(new LayoutParams(buttonSize, buttonSize));
bgImage.setImageResource(R.drawable.drawable_circle);
addView(bgImage);
// set Icon
Drawable icon = getResources().getDrawable(mIconId);
LayoutParams iconLP = new LayoutParams(iconSize, iconSize);
iconLP.gravity = Gravity.CENTER;
ImageView imageView = new ImageView(getContext());
imageView.setLayoutParams(iconLP);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setImageDrawable(icon);
addView(imageView);
}
protected void setIconId(int iconId) {
mIconId = iconId;
}
}
| {
"content_hash": "c0fa3a76b4c8a9a15f30ec1009e3e7e3",
"timestamp": "",
"source": "github",
"line_count": 70,
"max_line_length": 96,
"avg_line_length": 31.385714285714286,
"alnum_prop": 0.700955848884843,
"repo_name": "peterdocter/ZDepthShadow",
"id": "38aaaf3ea09368f099c188f71c3192fe05a49d1e",
"size": "2197",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "sample/src/main/java/app/mosn/zdepthshadowsample/fam/FloatingActionMenuButton.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "52438"
}
],
"symlink_target": ""
} |
package org.itas.core;
@FunctionalInterface
public interface CallBack<T> {
public void called(T back);
}
| {
"content_hash": "47a23ccac64a512d7ba8e7869fc9937a",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 30,
"avg_line_length": 13.75,
"alnum_prop": 0.7454545454545455,
"repo_name": "liuxing521a/itas-core",
"id": "38a4c10f79549326de4a2e9f0c9931c4ef9a3c29",
"size": "110",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "core/src/main/java/org/itas/core/CallBack.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "1546939"
},
{
"name": "Ragel in Ruby Host",
"bytes": "9540"
}
],
"symlink_target": ""
} |
<?php
namespace Chippyash\Math\Matrix\Special;
use Chippyash\Math\Matrix\NumericMatrix;
use Chippyash\Type\String\StringType;
use Chippyash\Validation\Common\Lambda;
use Chippyash\Validation\Exceptions\InvalidParameterException;
use Chippyash\Validation\Logical\LAnd;
use Chippyash\Validation\Logical\LOr;
use Chippyash\Validation\Pattern\HasTypeMap;
/**
* Zeroes Matrix
* Create a matrix or vector filled with 0
*
* Expects 1 parameter: rows and second optional parameter, cols
* cols defaults to 1 if not specified.
*/
class Zeros extends AbstractSpecial
{
const ERR1 = 'rows parameter must be integer > 0';
const ERR2 = 'rows and cols parameter must be integer > 0';
/**
* Map of argument names
* @var array
*/
protected $map = ['rows', 'cols'];
/**
* @inheritDoc
*/
protected function validateArguments(array $args)
{
$valA1 = new HasTypeMap([
'rows' => 'integer'
]
);
$valA2 = new Lambda(function($args) {
return $args['rows'] > 0 && !array_key_exists('cols', $args);
}, new StringType(self::ERR1));
$valA = new LAnd($valA1, $valA2);
$valB1 = new HasTypeMap([
'rows' => 'integer',
'cols' => 'integer'
]
);
$valB2 = new Lambda(function($args) {
return $args['rows'] > 0 && $args['cols'] > 0;
},
new StringType(self::ERR2)
);
$valB = new LAnd($valB1, $valB2);
$validator = new LOr($valA,$valB);
if (!$validator->isValid($args)) {
throw new InvalidParameterException(implode(':', $validator->getMessages()));
}
}
/**
* @inheritDoc
*/
protected function createMatrix(array $args)
{
$rows = $args['rows'];
$cols = array_key_exists('cols', $args) ? $args['cols'] : 1;
return $this->zeroes($rows, $cols);
}
private function zeroes($rows, $cols)
{
$ret = array_fill(0, $rows, array_fill(0, $cols, 0));
return new NumericMatrix($ret);
}
} | {
"content_hash": "2d12a92ccd1082459f1e7202b26065f1",
"timestamp": "",
"source": "github",
"line_count": 80,
"max_line_length": 89,
"avg_line_length": 26.525,
"alnum_prop": 0.5702167766258247,
"repo_name": "chippyash/Math-Matrix",
"id": "37f6f33d1731b9ec41fb7d65083a5b3c5d26a4dc",
"size": "2250",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Chippyash/Math/Matrix/Special/Zeros.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "PHP",
"bytes": "363333"
},
{
"name": "Shell",
"bytes": "497"
}
],
"symlink_target": ""
} |
name: Bug report
about: Create a report to help us improve
title: ''
labels: bug
assignees: arsi-apli
---
**Describe the bug**
A clear and concise description of what the bug is.
**To Reproduce**
Steps to reproduce the behavior:
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error
**Screenshots**
If applicable, add screenshots to help explain your problem.
* For classPath issue (Code completion) please add a screenshot of Compile, Runtime and Boot classpath:


**IDE log**

* Please enter the System Info from the IDE log to identify yours OS, Java and Apache Netbeans versions.
```
>System Info:
Product Version = Apache NetBeans IDE 11.0 (Build incubator-netbeans-release-404-on-20190319)
Operating System = Linux version 4.19.38-041938-generic running on amd64
Java; VM; Vendor = 11.0.2; Java HotSpot(TM) 64-Bit Server VM 11.0.2+9-LTS; Oracle Corporation
Runtime = Java(TM) SE Runtime Environment 11.0.2+9-LTS
Java Home = /java/jdk-11.0.2
```
* if you find an exception. Include that part of the listing.
**Additional context**
Add any other context about the problem here.
| {
"content_hash": "0913089b7e168bea9337dc45eb6f9309",
"timestamp": "",
"source": "github",
"line_count": 47,
"max_line_length": 105,
"avg_line_length": 31.76595744680851,
"alnum_prop": 0.7160080375083724,
"repo_name": "arsi-apli/NBANDROID-V2",
"id": "b0ad1f7abdc34038d8c9cdd7869691714730e405",
"size": "1497",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": ".github/ISSUE_TEMPLATE/bug_report.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "FreeMarker",
"bytes": "747732"
},
{
"name": "GAP",
"bytes": "9978"
},
{
"name": "GLSL",
"bytes": "632"
},
{
"name": "HTML",
"bytes": "51779"
},
{
"name": "Java",
"bytes": "3770028"
}
],
"symlink_target": ""
} |
package com.segal.mongorest.core.service;
import com.segal.mongorest.core.pojo.BaseDocument;
/**
* Created with IntelliJ IDEA.
* User: Jeff
* Date: 4/17/14
* Time: 12:29 PM
* To change this template use File | Settings | File Templates.
*/
public interface PersistenceListener<T extends BaseDocument> {
void documentAdded(T pojo);
void documentUpdated(T pojo);
void documentDeleted(String id);
}
| {
"content_hash": "b453cfd4544fcd2b632a04a036a0d997",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 64,
"avg_line_length": 20.55,
"alnum_prop": 0.7372262773722628,
"repo_name": "jeffsegal/mongo-rest",
"id": "85e4fa2d226788cb7fc378ada78e841eb379faf2",
"size": "411",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "mongo-rest-persistence/src/main/java/com/segal/mongorest/core/service/PersistenceListener.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "91624"
}
],
"symlink_target": ""
} |
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.minanos</groupId>
<artifactId>minano-parent</artifactId>
<version>0.1.1-SNAPSHOT</version>
<packaging>pom</packaging>
<name>minano-webapp</name>
<url>https://github.com/minanos/minano</url>
<description>minano webapp</description>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
</plugin>
</plugins>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
<compilerArgument>-proc:none</compilerArgument>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>${maven-resources-plugin.version}</version>
</plugin>
</plugins>
</pluginManagement>
</build>
<properties>
<querydsl>3.2.3</querydsl>
<querydsl.version>3.2.3</querydsl.version>
<dozer.version>5.4.0</dozer.version>
<thymeleaf.version>2.1.2.RELEASE</thymeleaf.version>
<thymeleaf-extras-tiles2-version>2.1.0.RELEASE</thymeleaf-extras-tiles2-version>
<thymeleaf-extras-springsecurity3-version>2.1.0.RELEASE</thymeleaf-extras-springsecurity3-version>
<thymeleaf-extras-conditionalcomments-version>2.1.0.RELEASE</thymeleaf-extras-conditionalcomments-version>
<thymeleaf-extras-layout-version>1.2</thymeleaf-extras-layout-version>
<ehcache.version>2.7.4</ehcache.version>
<ehcache-core.version>2.6.6</ehcache-core.version>
<ehcache-jcache.version>1.5.0-0.5</ehcache-jcache.version>
<!-- Spring related -->
<spring.version>4.0.0.RELEASE</spring.version>
<spring-security.version>3.2.0.RELEASE</spring-security.version> <!-- -->
<javassist.version>3.18.1-GA</javassist.version>
<aspectjweaver.version>1.7.4</aspectjweaver.version>
<!-- web -->
<javax.servlet-api.version>3.0.1</javax.servlet-api.version>
<!-- marshalling -->
<jackson.version>2.2.3</jackson.version>
<jaxb-api.version>2.2.11</jaxb-api.version>
<xstream.version>1.4.6</xstream.version>
<!-- commons and utils -->
<commons-lang3.version>3.2</commons-lang3.version>
<guava.version>16.0-rc1</guava.version>
<!-- UNSORTED -->
<commons-codec.version>1.9</commons-codec.version>
<!-- persistence -->
<mysql-connector-java.version>5.1.28</mysql-connector-java.version> <!-- latest version on: 02.01.2014 - http://dev.mysql.com/downloads/connector/j/ -->
<hibernate.version>4.3.0.Final</hibernate.version>
<hibernate-jpamodelgen.version>4.3.0.Final</hibernate-jpamodelgen.version>
<commons-dbcp.version>1.4</commons-dbcp.version>
<querydsl.version>3.3.0</querydsl.version>
<spring-data-jpa.version>1.4.3.RELEASE</spring-data-jpa.version>
<h2.version>1.3.174</h2.version>
<hsqldb.version>2.3.1</hsqldb.version>
<validation-api.version>1.1.0.Final</validation-api.version>
<hibernate-validator.version>5.0.2.Final</hibernate-validator.version>
<!-- logging -->
<org.slf4j.version>1.7.3</org.slf4j.version>
<logback.version>1.0.11</logback.version>
<!-- testing -->
<org.hamcrest.version>1.3</org.hamcrest.version>
<junit.version>4.11</junit.version>
<mockito.version>1.9.5</mockito.version>
<httpcore.version>4.3.1</httpcore.version>
<httpclient.version>4.3.1</httpclient.version>
<rest-assured.version>2.1.0</rest-assured.version>
<!-- maven plugins -->
<maven-surefire-plugin.version>2.16</maven-surefire-plugin.version>
<maven-compiler-plugin.version>3.1</maven-compiler-plugin.version>
<maven-resources-plugin.version>2.6</maven-resources-plugin.version>
<jrebel-maven-plugin.version>1.1.5</jrebel-maven-plugin.version>
<cargo-maven2-plugin.version>1.4.6</cargo-maven2-plugin.version>
</properties>
<repositories>
<repository>
<id>apache-snapshot</id>
<name>Apache Maven Snapshot Repository</name>
<url>https://repository.apache.org/content/groups/snapshots/</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
<repository>
<id>repository.springsource.milestone</id>
<name>SpringSource Milestone Repository</name>
<url>http://repo.springsource.org/milestone</url>
</repository>
</repositories>
<modules>
<module>modules/common-client</module>
<module>modules/common</module>
<module>modules/test</module>
<module>modules/api</module>
<module>modules/runtime</module>
</modules>
<issueManagement>
<url>https://github.com/minanos/minano/issues</url>
<system>GitHub Issues</system>
</issueManagement>
<licenses>
<license>
<name>MIT License</name>
<url>http://www.opensource.org/licenses/mit-license.php</url>
<distribution>repo</distribution>
</license>
</licenses>
<developers>
<developer>
<email>entation@qq.com</email>
<name>Ent ation</name>
<url>https://github.com/entation</url>
<id>entation</id>
</developer>
<developer>
<email>6208317@qq.com</email>
<name>Cheng nuo</name>
<url>https://github.com/im-qq</url>
<id>Chengnuo</id>
</developer>
</developers>
<ciManagement>
<system>Jenkins</system>
<url>https://minano-security.ci.cloudbees.com/</url>
</ciManagement>
<scm>
<connection>scm:git:git://github.com/minanos/minano.git</connection>
<url>scm:git:git://github.com/minanos/minano.git</url>
<developerConnection>scm:git:git://github.com/minanos/minano.git</developerConnection>
</scm>
</project> | {
"content_hash": "06eb2d2c011cf656e9b4ba70ef9f4656",
"timestamp": "",
"source": "github",
"line_count": 205,
"max_line_length": 154,
"avg_line_length": 29.848780487804877,
"alnum_prop": 0.7059977120444517,
"repo_name": "minanos/minano",
"id": "4f02e2ff6c9b82965d4b16b594772f9b210f4b7a",
"size": "6119",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "pom.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "7734"
},
{
"name": "Java",
"bytes": "519199"
},
{
"name": "JavaScript",
"bytes": "371157"
}
],
"symlink_target": ""
} |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("NServiceBus.Redis.AcceptanceTests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("NServiceBus.Redis.AcceptanceTests")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("68e38d2e-b33b-4ddd-972b-f5333c0fda69")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| {
"content_hash": "fa5e1dc0f0051f23161fe2970464ee74",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 84,
"avg_line_length": 39.97222222222222,
"alnum_prop": 0.7498262682418346,
"repo_name": "fabtesta/NServiceBus4.Redis",
"id": "caf2fb15ea72286e38f9cd650b839209698d81c0",
"size": "1442",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/NServiceBus.Redis.AcceptanceTests/Properties/AssemblyInfo.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "52483"
}
],
"symlink_target": ""
} |
const path = require('path');
const fs = require('fs');
const http = require('http');
const WebSocket = require('ws');
const _ = require('lodash');
const express = require('express');
const ejs = require('ejs');
const opener = require('opener');
const mkdir = require('mkdirp');
const { bold } = require('chalk');
const Logger = require('./Logger');
const analyzer = require('./analyzer');
const projectRoot = path.resolve(__dirname, '..');
module.exports = {
startServer,
generateReport,
// deprecated
start: startServer
};
async function startServer(bundleStats, opts) {
const {
port = 8888,
host = '127.0.0.1',
openBrowser = true,
bundleDir = null,
logger = new Logger(),
defaultSizes = 'parsed',
excludeAssets = null
} = opts || {};
const analyzerOpts = { logger, excludeAssets };
let chartData = getChartData(analyzerOpts, bundleStats, bundleDir);
if (!chartData) return;
const app = express();
// Explicitly using our `ejs` dependency to render templates
// Fixes #17
app.engine('ejs', require('ejs').renderFile);
app.set('view engine', 'ejs');
app.set('views', `${projectRoot}/views`);
app.use(express.static(`${projectRoot}/public`));
app.use('/', (req, res) => {
res.render('viewer', {
mode: 'server',
get chartData() { return JSON.stringify(chartData) },
defaultSizes: JSON.stringify(defaultSizes)
});
});
const server = http.createServer(app);
await new Promise(resolve => {
server.listen(port, host, () => {
resolve();
const url = `http://${host}:${server.address().port}`;
logger.info(
`${bold('Webpack Bundle Analyzer')} is started at ${bold(url)}\n` +
`Use ${bold('Ctrl+C')} to close it`
);
if (openBrowser) {
opener(url);
}
});
});
const wss = new WebSocket.Server({ server });
wss.on('connection', ws => {
ws.on('error', err => {
// Ignore network errors like `ECONNRESET`, `EPIPE`, etc.
if (err.errno) return;
logger.info(err.message);
});
});
return {
ws: wss,
http: server,
updateChartData
};
function updateChartData(bundleStats) {
const newChartData = getChartData(analyzerOpts, bundleStats, bundleDir);
if (!newChartData) return;
chartData = newChartData;
wss.clients.forEach(client => {
if (client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify({
event: 'chartDataUpdated',
data: newChartData
}));
}
});
}
}
function generateReport(bundleStats, opts) {
const {
openBrowser = true,
reportFilename = 'report.html',
bundleDir = null,
logger = new Logger(),
defaultSizes = 'parsed',
excludeAssets = null
} = opts || {};
const chartData = getChartData({ logger, excludeAssets }, bundleStats, bundleDir);
if (!chartData) return;
ejs.renderFile(
`${projectRoot}/views/viewer.ejs`,
{
mode: 'static',
chartData: JSON.stringify(chartData),
assetContent: getAssetContent,
defaultSizes: JSON.stringify(defaultSizes)
},
(err, reportHtml) => {
if (err) return logger.error(err);
const reportFilepath = path.resolve(bundleDir || process.cwd(), reportFilename);
mkdir.sync(path.dirname(reportFilepath));
fs.writeFileSync(reportFilepath, reportHtml);
logger.info(
`${bold('Webpack Bundle Analyzer')} saved report to ${bold(reportFilepath)}`
);
if (openBrowser) {
opener(`file://${reportFilepath}`);
}
}
);
}
function getAssetContent(filename) {
return fs.readFileSync(`${projectRoot}/public/${filename}`, 'utf8');
}
function getChartData(analyzerOpts, ...args) {
let chartData;
const { logger } = analyzerOpts;
try {
chartData = analyzer.getViewerData(...args, analyzerOpts);
} catch (err) {
logger.error(`Could't analyze webpack bundle:\n${err}`);
logger.debug(err.stack);
chartData = null;
}
if (_.isPlainObject(chartData) && _.isEmpty(chartData)) {
logger.error("Could't find any javascript bundles in provided stats file");
chartData = null;
}
return chartData;
}
| {
"content_hash": "e1f34aefc22753aceac798408ddb7fc3",
"timestamp": "",
"source": "github",
"line_count": 176,
"max_line_length": 86,
"avg_line_length": 23.835227272727273,
"alnum_prop": 0.6202622169249106,
"repo_name": "zhaoshuxue/document",
"id": "89033a41a07228ebba020e02dc238cc877a32919",
"size": "4195",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "JavaScript/vue/vue-cli2/node_modules/webpack-bundle-analyzer/src/viewer.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "56"
},
{
"name": "CSS",
"bytes": "44449"
},
{
"name": "Dockerfile",
"bytes": "3719"
},
{
"name": "Go",
"bytes": "612"
},
{
"name": "HTML",
"bytes": "63306"
},
{
"name": "Java",
"bytes": "58482"
},
{
"name": "JavaScript",
"bytes": "42036"
},
{
"name": "Python",
"bytes": "23932"
},
{
"name": "Shell",
"bytes": "3789"
},
{
"name": "VBScript",
"bytes": "52"
},
{
"name": "Vue",
"bytes": "2895"
}
],
"symlink_target": ""
} |
<?php
use Laravel\Database\Eloquent\Query;
use Laravel\Database\Eloquent\Relationships\Belongs_To;
use Laravel\Database\Eloquent\Model;
abstract class Base_Model extends Model
{
/**
*
* @var Query
*/
protected $query;
/**
*
* @var Belongs_To
*/
protected $belongsTo;
/**
*
* @var array
*/
protected $rules = array();
/**
*
* @var array
*/
protected $messages = array();
/**
*
* @var array
*/
protected $errors;
/**
* En lugar de ir escribiendo dependencia por dependencia
* (ej.: setCharacterRepository, setQuestRepository, getX, etc.)
* simplemente creamos un array donde las guardamos evitando
* asi tener que re-escribir el mismo codigo :)
*
* @var array
*/
protected $dependencies;
/**
* Asignamos el valor de una dependencia (util para test/mock).
*
* Establecemos este metodo como protected para que la clase
* que lo vaya a utilizar determine los nombres de las dependencias
* y asi evitar problemas a la hora de tener que cambiarlos.
*
* @param string $name
* @param mixed $value
*/
protected function setDependency($name, $value)
{
$this->dependencies[$name] = $value;
}
/**
* Obtenemos una dependencia. En caso de que la misma
* no haya sido asignada, se busca en el contenedor IoC
*
* Establecemos este metodo como protected para que la clase
* que lo vaya a utilizar determine los nombres de las dependencias
* y asi evitar problemas a la hora de tener que cambiarlos.
*
* @param string $name
* @return mixed
*/
protected function getDependency($name)
{
if (! isset($this->dependencies[$name])) {
$this->setDependency($name, \Laravel\IoC::resolve($name));
}
return $this->dependencies[$name];
}
/**
*
* @param Belongs_To $belongsTo
*/
public function setBelongsTo(Belongs_To $belongsTo = null)
{
$this->belongsTo = $belongsTo;
}
public function belongs_to($model, $foreign = null)
{
return ($this->belongsTo) ? $this->belongsTo : parent::belongs_to($model, $foreign);
}
public function fire_global_event($event, $args)
{
Event::fire($event, $args);
}
protected function inject_query($query)
{
return $query;
}
/**
* Its Mocking time!
*
* Cuando no se quiera tocar la base de datos simplemente
* reemplazar la dependencia (Query) con un Mock
*
* @param Query $query
*/
public function setQuery(Query $query = null)
{
$this->query = $query;
}
/**
*
* @return Query
*/
protected function getQuery()
{
return ($this->query) ? $this->query : parent::_query();
}
protected function _query()
{
return $this->inject_query($this->getQuery());
}
public function get_validator($attributes, $rules, $messages = array())
{
return Validator::make($attributes, $rules, $messages);
}
public function validate()
{
$validator = $this->get_validator($this->attributes, $this->rules, $this->messages);
if ($validator->fails()) {
$this->errors = $validator->errors;
return false;
}
return true;
}
public function errors()
{
return $this->errors;
}
public function to_json()
{
return json_encode($this);
}
} | {
"content_hash": "3f9589d4128eeddbbe7d5c38c8e4c5df",
"timestamp": "",
"source": "github",
"line_count": 161,
"max_line_length": 92,
"avg_line_length": 21.993788819875775,
"alnum_prop": 0.5817565659418243,
"repo_name": "Ruk33/AresLands",
"id": "a866cfe410eef7d0208730e1d83fa60a45ed34be",
"size": "3541",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "application/models/base_model.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "114809"
},
{
"name": "Java",
"bytes": "14870"
},
{
"name": "JavaScript",
"bytes": "3789648"
},
{
"name": "PHP",
"bytes": "3124124"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html>
<head>
<title>Promise tests</title>
<meta charset="utf-8">
<link href="/mocha.css" type="text/css" rel="stylesheet">
<script src="/mocha.js" type="text/javascript" onload="mocha.setup('bdd');"></script>
<script src="../../mini-module/mini-module.js" type="text/javascript"></script>
<script src="../mini-promise.js" type="text/javascript" data-module-name="mini-promise"></script>
<script src="./promises-aplus.js" type="text/javascript"></script>
<script src="./promises-static-methods.js" type="text/javascript"></script>
</head>
<body>
<div id="mocha"></div>
<script type="text/javascript">
document.addEventListener('readystatechange', function(event) {
// expect all scripts loaded when ready state is complete
if (document.readyState === "complete") {
mocha.run();
}
});
</script>
</body>
</html>
| {
"content_hash": "695774ad6be6868cfc02ee85ca10ad40",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 101,
"avg_line_length": 36,
"alnum_prop": 0.6185897435897436,
"repo_name": "mikonieminen/mini-promise",
"id": "8c90f3ab83a0f0ac625720798436f5e387b64a0e",
"size": "936",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/index.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "936"
},
{
"name": "JavaScript",
"bytes": "20901"
}
],
"symlink_target": ""
} |
<script>window.pathPrefix="../../";</script><script>window.pathPrefix="../../";</script><script>window.pathPrefix="../../";</script><script>window.pathPrefix="../../";</script><script>window.pathPrefix="../../";</script><script>window.pathPrefix="../../";</script><script>window.pathPrefix="../../";</script><script>window.pathPrefix="../../";</script><!DOCTYPE html>
<html lang="en"></html>
<head><meta name="generator" content="Hexo 3.9.0">
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<link href="../../images/favicon.png" rel="shortcut icon" type="image/png">
<title>DJI Mobile SDK Documentation
</title><link rel="stylesheet" href="../../stylesheets/doc-vendor.css"><link rel="stylesheet" href="../../stylesheets/doc-app.css">
</head>
<body>
<nav id="site-header" class="site-header navbar">
<div class="container">
<div class="navbar-header"><a href="/" class="logo"><img src="../../images/dji-logo@2x.png">Developer</a></div>
<div id="header-navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="/mobile-sdk">Mobile SDK</a></li>
<li><a href="/ux-sdk">UX SDK</a></li>
<li><a href="/onboard-sdk">Onboard SDK</a></li>
<li><a href="/payload-sdk">Payload SDK</a></li>
<li><a href="/windows-sdk">Windows SDK</a></li>
</ul>
<ul v-cloak v-show="!loggedIn" class="nav navbar-nav navbar-right nav-user">
<li><a href="https://account.dji.com/login?appId=dji_sdk&backUrl=https%3A%2F%2Fdeveloper.dji.com%2Fuser&locale=en_US">Login</a></li>
<li><a href="https://account.dji.com/register?appId=dji_sdk&backUrl=https%3A%2F%2Fdeveloper.dji.com%2Fuser&locale=en_US" class="head-cta">Register</a></li>
</ul>
<ul v-cloak v-show="loggedIn" class="nav navbar-nav navbar-right nav-user">
<li class="hovedown"><a href="javascript:void(0);" class="hovedown-toggle"><i class="fa fa-user"></i></a>
<ul class="hovedown-menu hovedown-menu-right">
<li><a href="/user">User Center</a></li>
<li><a href="javascript:void(0);" v-on="click: logout">Logout</a></li>
</ul>
</li>
</ul>
</div>
</div>
</nav>
<div data-offset-top="60" data-spy="affix" class="sub-nav">
<div class="container">
<h1 class="logo">Mobile SDK</h1>
<nav><a href="/mobile-sdk-v4/">Overview</a><a href="/document/544659e8-9dab-4ad8-9414-a31e1c9b89b1">Documentation</a><span class="active hovedown menu-item">API Reference<span class="caret"></span>
<ul class="hovedown-menu">
<li><a href="/api-reference/ios-api/index.html">IOS SDK</a></li>
<li><a href="/api-reference/android-api/index.html">Android SDK</a></li>
<li><a href="/api-reference/ios-uilib-api/index.html">IOS UX SDK</a></li>
<li><a href="/api-reference/android-uilib-api/index.html">Android UX SDK</a></li>
</ul></span><a href="/mobile-sdk-v4/downloads/">Downloads</a><a href="https://sdk-forum.dji.net/hc/en-us">Support</a>
</nav>
</div>
</div>
<div id="documentation-page" class="documentation-page">
<div class="container">
<div class="site-sidebar">
<div class="searcher">
<div id="panel" class="panel panel_tree">
<div class="header">
<div class="search-con">
<label id="search-label" for="search">
</label>
<input id="search" type="text" placeholder="Search" autosave="searchdoc" results="10" autocomplete="off">
<div class="search-icon"></div><a class="clean-search glyphicon glyphicon-remove-circle"></a>
</div>
</div>
<div class="tree">
<ul></ul>
</div>
<div class="result">
<ul></ul>
</div>
</div>
</div>
<div class="nav scrollable js-tree-menu">
<dl>
<dt>Manager Classes
</dt>
<dd><a data-href="../SDKManager/DJISDKManager.html" class="sub-toggle">DJISDKManager<i class="fa fa-angle-down"></i><i class="fa fa-angle-up"></i></a>
<ul class="sub-menu">
<dd><a href="../SDKManager/DJIBluetoothProductConnector.html">DJIBluetoothProductConnector</a>
</dd>
</ul>
</dd>
<dd><a data-href="../KeyManager/DJIKeyManager.html" class="sub-toggle">DJIKeyManager<i class="fa fa-angle-down"></i><i class="fa fa-angle-up"></i></a>
<ul class="sub-menu">
<dd><a data-href="../KeyManager/DJIKey.html" class="sub-toggle">DJIKey<i class="fa fa-angle-down"></i><i class="fa fa-angle-up"></i></a>
<ul class="sub-menu">
<dd><a href="../KeyManager/DJIBatteryKey.html">DJIBatteryKey</a>
</dd>
<dd><a href="../KeyManager/DJICameraKey.html">DJICameraKey</a>
</dd>
<dd><a href="../KeyManager/DJIFlightControllerKey.html">DJIFlightControllerKey</a>
</dd>
<dd><a href="../KeyManager/DJIRadarKey.html">DJIRadarKey</a>
</dd>
<dd><a href="../KeyManager/DJIPayloadKey.html">DJIPayloadKey</a>
</dd>
<dd><a href="../KeyManager/DJIGimbalKey.html">DJIGimbalKey</a>
</dd>
<dd><a href="../KeyManager/DJIProductKey.html">DJIProductKey</a>
</dd>
<dd><a href="../KeyManager/DJIRemoteControllerKey.html">DJIRemoteControllerKey</a>
</dd>
<dd><a href="../KeyManager/DJIHandheldControllerKey.html">DJIHandheldControllerKey</a>
</dd>
<dd><a href="../KeyManager/DJIMissionKey.html">DJIMissionKey</a>
</dd>
<dd><a href="../KeyManager/DJIAirLinkKey.html">DJIAirLinkKey</a>
</dd>
<dd><a href="../KeyManager/DJIAccessoryKey.html">DJIAccessoryKey</a>
</dd>
<dd><a href="../KeyManager/DJILidarKey.html">DJILidarKey</a>
</dd>
<dd><a href="../KeyManager/DJIRTKBaseStationKey.html">DJIRTKBaseStationKey</a>
</dd>
</ul>
</dd>
<dd><a href="../KeyManager/DJIKeyedValue.html">DJIKeyedValue</a>
</dd>
</ul>
</dd>
<dd><a data-href="../FlyZoneManager/DJIFlyZoneManager.html" class="sub-toggle">DJIFlyZoneManager<i class="fa fa-angle-down"></i><i class="fa fa-angle-up"></i></a>
<ul class="sub-menu">
<dd><a href="../FlyZoneManager/DJIFlyZoneManager_DJIUnlockedZoneGroup.html">DJIUnlockedZoneGroup</a>
</dd>
<dd><a data-href="../FlyZoneManager/DJIFlyZoneManager_DJIFlyZoneInformation.html" class="sub-toggle">DJIFlyZoneInformation<i class="fa fa-angle-down"></i><i class="fa fa-angle-up"></i></a>
<ul class="sub-menu">
<dd><a href="../FlyZoneManager/DJIFlyZoneManager_DJISubFlyZoneInformation.html">DJISubFlyZoneInformation</a>
</dd>
</ul>
</dd>
<dd><a href="../FlyZoneManager/DJIFlyZoneManager_DJIIndividualUnlockZone.html">DJICustomUnlockZone</a>
</dd>
<dd><a href="../FlyZoneManager/DJIFlyZoneManager_DJIFlyingSafetyWarningInformation.html">DJIFlyingSafetyWarningInformation</a>
</dd>
<dd><a href="../FlyZoneManager/DJIFlyZoneManager_DJIFlyingSafetySeriousWarningInformation.html">DJIFlyingSafetySeriousWarningInformation</a>
</dd>
<dd><a href="../FlyZoneManager/DJIFlyZoneManager_DJIFlyingSafetyTip.html">DJIFlyingSafetyTip</a>
</dd>
<dd><a href="../FlyZoneManager/DJIFlyZoneManager_DJIFlySafeReturnToHomeInformation.html">DJIFlySafeReturnToHomeInformation</a>
</dd>
<dd><a href="../FlyZoneManager/DJIFlyZoneManager_DJIFlySafeNotification.html">DJIFlySafeNotification</a>
</dd>
</ul>
</dd>
<dd><a href="../AppActivationManager/DJIAppActivationManager.html">DJIAppActivationManager</a>
</dd>
<dd><a href="../UserAccountManager/DJIUserAccountManager.html">DJIUserAccountManager</a>
</dd>
<dd><a href="../DataProtectionManager/DJIDataProtectionManager.html">DJIDataProtectionManager</a>
</dd>
<dd><a data-href="../LDMManager/DJILDMManager.html" class="sub-toggle">DJILDMManager<i class="fa fa-angle-down"></i><i class="fa fa-angle-up"></i></a>
<ul class="sub-menu">
<dd><a href="../LDMManager/DJILDMManager_LDMModule.html">DJILDMModule</a>
</dd>
</ul>
</dd>
<dd><a data-href="../UTMISSManager/DJIUTMISSManager.html" class="sub-toggle">DJIUTMISSManager<i class="fa fa-angle-down"></i><i class="fa fa-angle-up"></i></a>
<ul class="sub-menu">
<dd><a href="../UTMISSManager/DJIUTMISSManager_DJIUTMISSParam.html">DJIUTMISSParam</a>
</dd>
</ul>
</dd>
<dd><a data-href="DJIFlightHubManager.html" class="sub-toggle">DJIFlightHubManager<i class="fa fa-angle-down"></i><i class="fa fa-angle-up"></i></a>
<ul class="sub-menu">
<dd><a href="DJIFlightHubManager_DJIFlightHubOnlineDevice.html">DJIFlightHubOnlineDevice</a>
</dd>
<dd><a href="DJIFlightHubManager_DJIFlightHubBoundDevice.html">DJIFlightHubBoundDevice</a>
</dd>
<dd><a href="DJIFlightHubManager_DJIFlightHubUser.html">DJIFlightHubUser</a>
</dd>
<dd><a href="DJIFlightHubManager_DJIFlightHubTeam.html">DJIFlightHubTeam</a>
</dd>
<dd><a href class="active">DJIFlightHubUpStream</a>
</dd>
<dd><a href="DJIFlightHubManager_DJIFlightHubLiveStream.html">DJIFlightHubLiveStream</a>
</dd>
<dd><a href="DJIFlightHubManager_DJIFlightHubFlightPathNode.html">DJIFlightHubFlightPathNode</a>
</dd>
<dd><a href="DJIFlightHubManager_DJIFlightHubFlightHistoricalDetail.html">DJIFlightHubFlightHistoricalDetail</a>
</dd>
<dd><a href="DJIFlightHubManager_DJIFlightHubStatistics.html">DJIFlightHubStatistics</a>
</dd>
<dd><a href="DJIFlightHubManager_DJIFlightHubHistoricalFlight.html">DJIFlightHubHistoricalFlight</a>
</dd>
<dd><a href="DJIFlightHubManager_DJIFlightHubRealTimeFlightData.html">DJIFlightHubRealTimeFlightData</a>
</dd>
</ul>
</dd>
<dd><a data-href="../UASRemoteIDManager/DJIUASRemoteIDManager.html" class="sub-toggle">DJIUASRemoteIDManager<i class="fa fa-angle-down"></i><i class="fa fa-angle-up"></i></a>
<ul class="sub-menu">
<dd><a href="../UASRemoteIDManager/DJIUASRemoteIDManager_DJIUASRemoteIDStatus.html">DJIUASRemoteIDStatus</a>
</dd>
</ul>
</dd>
<dd><a data-href="../Upgrade/DJIUpgradeManager.html" class="sub-toggle">DJIUpgradeManager<i class="fa fa-angle-down"></i><i class="fa fa-angle-up"></i></a>
<ul class="sub-menu">
<dd><a data-href="../Upgrade/DJIUpgradeManager_DJIUpgradeComponent.html" class="sub-toggle">DJIUpgradeComponent<i class="fa fa-angle-down"></i><i class="fa fa-angle-up"></i></a>
<ul class="sub-menu">
<dd><a href="../Upgrade/DJIUpgradeManager_DJIUpgradeComponent_DJIFirmwareUpgradeProgress.html">DJIFirmwareUpgradeProgress</a>
</dd>
<dd><a href="../Upgrade/DJIUpgradeManager_DJIUpgradeComponent_DJIFirmwareInformation.html">DJIFirmwareInformation</a>
</dd>
</ul>
</dd>
</ul>
</dd>
</dl>
<dl>
<dt>Base Classes
</dt>
<dd><a data-href="../../BaseClasses/DJIBaseProduct.html" class="sub-toggle">DJIBaseProduct<i class="fa fa-angle-down"></i><i class="fa fa-angle-up"></i></a>
<ul class="sub-menu">
<dd><a data-href="../../BaseClasses/DJIVideoFeeder.html" class="sub-toggle">DJIVideoFeeder<i class="fa fa-angle-down"></i><i class="fa fa-angle-up"></i></a>
<ul class="sub-menu">
<dd><a href="../../BaseClasses/DJIVideoFeeder_DJIVideoFeed.html">DJIVideoFeed</a>
</dd>
</ul>
</dd>
</ul>
</dd>
<dd><a href="../BaseComponent/DJIBaseComponent.html">DJIBaseComponent</a>
</dd>
</dl>
<dl>
<dt>Product Classes
</dt>
<dd><a href="../../Products/Aircraft/DJIAircraft.html">DJIAircraft</a>
</dd>
<dd><a href="../../Products/Handheld/DJIHandheld.html">DJIHandheld</a>
</dd>
</dl>
<dl>
<dt>Component Classes
</dt>
<dd><a data-href="../FlightController/DJIFlightController.html" class="sub-toggle">DJIFlightController<i class="fa fa-angle-down"></i><i class="fa fa-angle-up"></i></a>
<ul class="sub-menu">
<dd><a href="../FlightController/DJIFlightController_DJIFlightControllerCurrentState.html">DJIFlightControllerState</a>
</dd>
<dd><a href="../FlightController/DJIFlightController_DJIGravityCenterState.html">DJIGravityCenterState</a>
</dd>
<dd><a href="../FlightController/DJIFlightController_DJIWarningStatusItem.html">DJIWarningStatusItem</a>
</dd>
<dd><a data-href="../Compass/DJICompass.html" class="sub-toggle">DJICompass<i class="fa fa-angle-down"></i><i class="fa fa-angle-up"></i></a>
<ul class="sub-menu">
<dd><a href="../Compass/DJICompass_DJICompassState.html">DJICompassState</a>
</dd>
</ul>
</dd>
<dd><a data-href="../RTK/DJIRTK.html" class="sub-toggle">DJIRTK<i class="fa fa-angle-down"></i><i class="fa fa-angle-up"></i></a>
<ul class="sub-menu">
<dd><a href="../RTK/DJIRTK_DJIRTKBaseStationInformation.html">DJIRTKBaseStationInformation</a>
</dd>
<dd><a href="../RTK/DJIRTK_DJIRTKState.html">DJIRTKState</a>
</dd>
<dd><a data-href="../RTK/DJIRTKNetworkServiceProvider.html" class="sub-toggle">DJIRTKNetworkServiceProvider<i class="fa fa-angle-down"></i><i class="fa fa-angle-up"></i></a>
<ul class="sub-menu">
<dd><a href="../RTK/DJIRTKNetworkServiceProvider_DJIRTKNetworkServiceState.html">DJIRTKNetworkServiceState</a>
</dd>
<dd><a href="../RTK/DJIRTKNetworkServiceProvider_DJIRTKNetworkServicePlan.html">DJIRTKNetworkServicePlan</a>
</dd>
<dd><a href="../RTK/DJIRTKNetworkServiceProvider_DJIRTKNetworkServicePlansState.html">DJIRTKNetworkServicePlansState</a>
</dd>
<dd><a href="../RTK/DJIRTKNetworkServiceProvider_DJIRTKNetworkServiceSettings.html">DJIRTKNetworkServiceSettings</a>
</dd>
<dd><a href="../RTK/DJIRTKNetworkServiceProvider_DJIMutableRTKNetworkServiceSettings.html">DJIMutableRTKNetworkServiceSettings</a>
</dd>
</ul>
</dd>
<dd><a href="../RTK/DJIRTK_DJIRTKReceiverInfo.html">DJIRTKReceiverInfo</a>
</dd>
<dd><a href="../RTK/DJIRTK_DJILocationStandardDeviation.html">DJILocationStandardDeviation</a>
</dd>
</ul>
</dd>
<dd><a href="../LandingGear/DJILandingGear.html">DJILandingGear</a>
</dd>
<dd><a data-href="../IntelligentFlightAssistant/DJIIntelligentFlightAssistant.html" class="sub-toggle">DJIFlightAssistant<i class="fa fa-angle-down"></i><i class="fa fa-angle-up"></i></a>
<ul class="sub-menu">
<dd><a data-href="../VisionDetectionState/DJIVisionDetectionState.html" class="sub-toggle">DJIVisionDetectionState<i class="fa fa-angle-down"></i><i class="fa fa-angle-up"></i></a>
<ul class="sub-menu">
<dd><a href="../VisionDetectionState/DJIVisionDetectionState_DJIVisionDetectionSector.html">DJIObstacleDetectionSector</a>
</dd>
</ul>
</dd>
<dd><a href="../IntelligentFlightAssistant/DJIVisionDetectionState_DJIVisionControlState.html">DJIVisionControlState</a>
</dd>
<dd><a href="../IntelligentFlightAssistant/DJISmartCaptureState.html">DJISmartCaptureState</a>
</dd>
<dd><a href="../IntelligentFlightAssistant/DJIFlightAssistantAvoidanceState.html">DJIFlightAssistantObstacleAvoidanceSensorState</a>
</dd>
<dd><a href="../IntelligentFlightAssistant/DJIFlightAssistantPerceptionState.html">DJIFlightAssistantPerceptionInformation</a>
</dd>
</ul>
</dd>
<dd><a data-href="../Simulator/DJIAccessLocker.html" class="sub-toggle">DJIAccessLocker<i class="fa fa-angle-down"></i><i class="fa fa-angle-up"></i></a>
<ul class="sub-menu">
<dd><a href="../Simulator/DJIAccessLocker_DJIAccessLockerFormattingState.html">DJIAccessLockerFormattingState</a>
</dd>
<dd><a href="../Simulator/DJIAccessLocker_DJIAccessLockerUserAccountInfo.html">DJIAccessLockerUserAccountInfo</a>
</dd>
</ul>
</dd>
<dd><a href="../Radar/DJIRadar.html">DJIRadar</a>
</dd>
<dd><a data-href="../Simulator/DJISimulator.html" class="sub-toggle">DJISimulator<i class="fa fa-angle-down"></i><i class="fa fa-angle-up"></i></a>
<ul class="sub-menu">
<dd><a href="../Simulator/DJISimulator_DJISimulatorState.html">DJISimulatorState</a>
</dd>
</ul>
</dd>
<dd><a data-href="../IMUState/DJIIMUState.html" class="sub-toggle">DJIIMUState<i class="fa fa-angle-down"></i><i class="fa fa-angle-up"></i></a>
<ul class="sub-menu">
<dd><a href="../IMUState/DJIIMUState_DJIIMUMultiOrientationCalibrationHint.html">DJIIMUMultipleOrientationCalibrationHint</a>
</dd>
</ul>
</dd>
<dd><a href="../OnboardSDKDevice/DJIOnboardSDKDevice.html">DJIOnboardSDKDevice</a>
</dd>
<dd><a data-href="../FlightController/DJIAirSenseSystemInformation.html" class="sub-toggle">DJIAirSenseSystemInformation<i class="fa fa-angle-down"></i><i class="fa fa-angle-up"></i></a>
<ul class="sub-menu">
<dd><a href="../FlightController/DJIAirSenseAirplaneState.html">DJIAirSenseAirplaneState</a>
</dd>
</ul>
</dd>
<dd><a href="../FlightController/DJIFlightController_DJIFlightControllerLEDsSettings.html">DJIFlightControllerLEDsSettings</a>
</dd>
<dd><a href="../FlightController/DJIFlightController_DJIMutableFlightControllerLEDsSettings.html">DJIMutableFlightControllerLEDsSettings</a>
</dd>
<dd><a href="../FlightController/DJIFlightController_DJISimulatorWindSpeed.html">DJISimulatorWindSpeed</a>
</dd>
</ul>
</dd>
<dd><a data-href="../Battery/DJIBattery.html" class="sub-toggle">DJIBattery<i class="fa fa-angle-down"></i><i class="fa fa-angle-up"></i></a>
<ul class="sub-menu">
<dd><a data-href="../Battery/DJIBattery_AggregationState.html" class="sub-toggle">DJIBatteryAggregationState<i class="fa fa-angle-down"></i><i class="fa fa-angle-up"></i></a>
<ul class="sub-menu">
<dd><a href="../Battery/DJIBattery_BatteryOverview.html">DJIBatteryOverview</a>
</dd>
</ul>
</dd>
<dd><a href="../Battery/DJIBattery_BatteryState.html">DJIBatteryState</a>
</dd>
<dd><a href="../Battery/DJIBattery_WarningRecord.html">DJIBatteryWarningRecord</a>
</dd>
</ul>
</dd>
<dd><a data-href="../Camera/DJICamera.html" class="sub-toggle">DJICamera<i class="fa fa-angle-down"></i><i class="fa fa-angle-up"></i></a>
<ul class="sub-menu">
<dd><a href="../Camera/DJICamera_DJICameraSystemState.html">DJICameraSystemState</a>
</dd>
<dd><a href="../Camera/DJICamera_DJICameraLensState.html">DJICameraFocusState</a>
</dd>
<dd><a href="../Camera/DJICamera_DJICameraSDCardState.html">DJICameraStorageState</a>
</dd>
<dd><a href="../Camera/DJICamera_DJICameraSSDState.html">DJICameraSSDState</a>
</dd>
<dd><a data-href="../Camera/DJIMediaManager.html" class="sub-toggle">DJIMediaManager<i class="fa fa-angle-down"></i><i class="fa fa-angle-up"></i></a>
<ul class="sub-menu">
<dd><a data-href="../Camera/DJIMediaManager_DJIMedia.html" class="sub-toggle">DJIMediaFile<i class="fa fa-angle-down"></i><i class="fa fa-angle-up"></i></a>
<ul class="sub-menu">
<dd><a href="../Camera/DJIMediaManager_DJIMedia_DJIMediaFile.html">DJIAudioMediaFile</a>
</dd>
</ul>
</dd>
<dd><a href="../Camera/DJIMediaManager_DJIMediaInfo.html">DJIMediaFileInfo</a>
</dd>
<dd><a href="../Camera/DJIMediaManager_VideoPlayback_DJIMediaVideoPlaybackState.html">DJIMediaVideoPlaybackState</a>
</dd>
<dd><a data-href="../Camera/DJIMediaManager_FetchMediaTaskScheduler.html" class="sub-toggle">DJIFetchMediaTaskScheduler<i class="fa fa-angle-down"></i><i class="fa fa-angle-up"></i></a>
<ul class="sub-menu">
<dd><a href="../Camera/DJIMediaManager_DJIFetchMediaTask.html">DJIFetchMediaTask</a>
</dd>
</ul>
</dd>
</ul>
</dd>
<dd><a data-href="../Camera/DJIPlaybackManager.html" class="sub-toggle">DJIPlaybackManager<i class="fa fa-angle-down"></i><i class="fa fa-angle-up"></i></a>
<ul class="sub-menu">
<dd><a href="../Camera/DJIPlaybackManager_DJICameraPlaybackState.html">DJICameraPlaybackState</a>
</dd>
</ul>
</dd>
<dd><a href="../Camera/DJICamera_DJICameraParameters.html">DJICameraCapabilities</a>
</dd>
<dd><a href="../Camera/DJICamera_DJICameraWhiteBalanceInterface.html">DJICameraWhiteBalance</a>
</dd>
<dd><a href="../Camera/DJICamera_DJICameraSSDClipFileNameInterface.html">DJICameraSSDClipFileName</a>
</dd>
<dd><a href="../Camera/DJICamera_DJICameraOriginalPhotoSettings.html">DJICameraOriginalPhotoSettings</a>
</dd>
<dd><a href="../Camera/DJICamera_DJICameraMultispectralStorageSettings.html">DJICameraMultispectralStorageSettings</a>
</dd>
<dd><a href="../Camera/DJICamera_DJIMutableCameraMultispectralStorageSettings.html">DJIMutableCameraMultispectralStorageSettings</a>
</dd>
<dd><a href="../Camera/DJICamera_DJICameraMultispectralExposureState.html">DJICameraMultispectralExposureState</a>
</dd>
<dd><a href="../Camera/DJICamera_DJICameraMultispectralExposureStates.html">DJICameraMultispectralExposureStates</a>
</dd>
<dd><a href="../Camera/DJICamera_DJICameraWatermarkSettings.html">DJICameraWatermarkSettings</a>
</dd>
<dd><a href="../Camera/DJICamera_DJICameraLaserMeasureInformation.html">DJICameraLaserMeasureInformation</a>
</dd>
<dd><a href="../Camera/DJICamera_DJICameraVideoResolutionAndFrameRate.html">DJICameraVideoResolutionAndFrameRate</a>
</dd>
<dd><a href="../Camera/DJICamera_DJICameraStreamSettings.html">DJICameraStreamSettings</a>
</dd>
<dd><a href="../Camera/DJICamera_DJILens.html">DJILens</a>
</dd>
</ul>
</dd>
<dd><a data-href="../Gimbal/DJIGimbal.html" class="sub-toggle">DJIGimbal<i class="fa fa-angle-down"></i><i class="fa fa-angle-up"></i></a>
<ul class="sub-menu">
<dd><a href="../Gimbal/DJIGimbal_GimbalState.html">DJIGimbalState</a>
</dd>
<dd><a href="../Gimbal/DJIGimbal_movementSettingsState.html">DJIGimbalMovementSettings</a>
</dd>
<dd><a href="../Gimbal/DJIGimbal_DJIGimbalRotation.html">DJIGimbalRotation</a>
</dd>
<dd><a href="../Gimbal/DJIGimbal_DJIMultiGimbalConnectionWorkingStatus.html">DJIMultiGimbalConnectionWorkingStatus</a>
</dd>
<dd><a data-href="../Gimbal/DJIGimbal_DJIGimbalBalanceDetectionState.html" class="sub-toggle">DJIGimbalBalanceDetectionState<i class="fa fa-angle-down"></i><i class="fa fa-angle-up"></i></a>
<ul class="sub-menu">
<dd><a href="../Gimbal/DJIGimbal_DJIGimbalDirectionState.html">DJIGimbalDirectionState</a>
</dd>
</ul>
</dd>
<dd><a href="../Gimbal/DJIGimbal_DJIGimbalControlParametersAutoTuningState.html">DJIGimbalControlParametersAutoTuningState</a>
</dd>
<dd><a href="../Gimbal/DJIGimbal_DJIGimbalCoaxialityDetectionState.html">DJIGimbalCoaxialityDetectionState</a>
</dd>
</ul>
</dd>
<dd><a data-href="../AirLink/DJIAirLink.html" class="sub-toggle">DJIAirLink<i class="fa fa-angle-down"></i><i class="fa fa-angle-up"></i></a>
<ul class="sub-menu">
<dd><a data-href="../LBAirLink/DJILBAirLink.html" class="sub-toggle">DJILightbridgeLink<i class="fa fa-angle-down"></i><i class="fa fa-angle-up"></i></a>
<ul class="sub-menu">
<dd><a href="../LBAirLink/DJILBAirLink_DJILBAirLinkChannelInterference.html">DJILightbridgeChannelInterference</a>
</dd>
<dd><a href="../LBAirLink/DJILBAirLink_DJILightbridgeAntennaRSSI.html">DJILightbridgeAntennaRSSI</a>
</dd>
</ul>
</dd>
<dd><a data-href="../OcuSyncLink/DJIOcuSyncLink.html" class="sub-toggle">OcuSyncLink<i class="fa fa-angle-down"></i><i class="fa fa-angle-up"></i></a>
<ul class="sub-menu">
<dd><a href="../OcuSyncLink/DJIOcuSyncLink_DJIOcuSyncFrequencyInterference.html">DJIOcuSyncFrequencyInterference</a>
</dd>
</ul>
</dd>
<dd><a data-href="../WiFiLink/DJIWiFiLink.html" class="sub-toggle">DJIWiFiLink<i class="fa fa-angle-down"></i><i class="fa fa-angle-up"></i></a>
<ul class="sub-menu">
<dd><a href="../WiFiLink/DJIWiFiLink_DJIWiFiChannelInterference.html">DJIWiFiChannelInterference</a>
</dd>
</ul>
</dd>
</ul>
</dd>
<dd><a data-href="../RemoteController/DJIRemoteController.html" class="sub-toggle">DJIRemoteController<i class="fa fa-angle-down"></i><i class="fa fa-angle-up"></i></a>
<ul class="sub-menu">
<dd><a href="../RemoteController/DJIRemoteController_DJIRCGimbalMapping.html">DJIRCGimbalMapping</a>
</dd>
<dd><a href="../RemoteController/DJIRemoteController_DJIRCAircraftMapping.html">DJIRCAircraftMapping</a>
</dd>
<dd><a href="../RemoteController/DJIRemoteController_RCCustomButtonTagParam.html">DJIRCCustomButtonTags</a>
</dd>
<dd><a href="../RemoteController/DJIRemoteController_DJIRCInfo.html">DJIRCInformation</a>
</dd>
<dd><a href="../RemoteController/DJIRemoteController_DJIRCMasterSlaveState.html">DJIRCMasterSlaveState</a>
</dd>
<dd><a href="../RemoteController/DJIRemoteController_DJIRCCredentials.html">DJIRCCredentials</a>
</dd>
<dd><a href="../RemoteController/DJIRemoteController_DJIRCButtonConfiguration.html">DJIRCButtonConfiguration</a>
</dd>
<dd><a href="../RemoteController/DJIRemoteController_DJIMutableRCButtonConfiguration.html">DJIMutableRCButtonConfiguration</a>
</dd>
<dd><a href="../RemoteController/DJIRemoteController_DJIRCCalibrationComponentState.html">DJIRCCalibrationComponentState</a>
</dd>
<dd><a href="../RemoteController/DJIRemoteController_DJIRCCalibrationProgress.html">DJIRCCalibrationProgress</a>
</dd>
<dd><a href="../RemoteController/DJIRemoteController_DJIRCMultiDeviceAggregationState.html">DJIRCMultiDeviceAggregationState</a>
</dd>
</ul>
</dd>
<dd><a data-href="../HandheldController/DJIHandheldController.html" class="sub-toggle">DJIHandheldController<i class="fa fa-angle-down"></i><i class="fa fa-angle-up"></i></a>
<ul class="sub-menu">
<dd><a href="../HandheldController/DJIHandheldController_DJIHandheldControllerHardwareState.html">DJIHandheldControllerHardwareState</a>
</dd>
<dd><a data-href="../HandheldController/DJIHandheldController_DJIHandheldControllerLEDCommand.html" class="sub-toggle">DJIHandheldControllerLEDCommand<i class="fa fa-angle-down"></i><i class="fa fa-angle-up"></i></a>
<ul class="sub-menu">
<dd><a href="../HandheldController/DJIHandheldController_DJIHandheldControllerLEDCommand_DJIHandheldControllerLEDColorPattern.html">DJIHandheldControllerLEDColorPattern</a>
</dd>
</ul>
</dd>
</ul>
</dd>
<dd><a href="../MobileRemoteController/DJIMobileRemoteController.html">DJIMobileRemoteController</a>
</dd>
<dd><a data-href="../Payload/DJIPayload.html" class="sub-toggle">DJIPayload<i class="fa fa-angle-down"></i><i class="fa fa-angle-up"></i></a>
<ul class="sub-menu">
<dd><a href="../Payload/DJIPayload_PayloadWidget.html">DJIPayloadWidget</a>
</dd>
</ul>
</dd>
<dd><a data-href="../Pipeline/DJIPipeline.html" class="sub-toggle">DJIPipeline<i class="fa fa-angle-down"></i><i class="fa fa-angle-up"></i></a>
<ul class="sub-menu">
<dd><a href="../Pipeline/DJIPipelines.html">DJIPipelines</a>
</dd>
</ul>
</dd>
<dd><a data-href="../AccessoryAggregation/DJIAccessoryAggregation.html" class="sub-toggle">DJIAccessoryAggregation<i class="fa fa-angle-down"></i><i class="fa fa-angle-up"></i></a>
<ul class="sub-menu">
<dd><a data-href="../AccessoryAggregation/DJIAccessoryAggregation_DJISpotlight.html" class="sub-toggle">DJISpotlight<i class="fa fa-angle-down"></i><i class="fa fa-angle-up"></i></a>
<ul class="sub-menu">
<dd><a href="../AccessoryAggregation/DJIAccessoryAggregation_DJISpotlight_DJISpotlightState.html">DJISpotlightState</a>
</dd>
</ul>
</dd>
<dd><a href="../AccessoryAggregation/DJIAccessoryAggregation_DJIBeacon.html">DJIBeacon</a>
</dd>
<dd><a data-href="../AccessoryAggregation/DJIAccessoryAggregation_DJISpeaker.html" class="sub-toggle">DJISpeaker<i class="fa fa-angle-down"></i><i class="fa fa-angle-up"></i></a>
<ul class="sub-menu">
<dd><a href="../AccessoryAggregation/DJIAccessoryAggregation_DJISpeaker_DJISpeakerState.html">DJISpeakerState</a>
</dd>
<dd><a href="../AccessoryAggregation/DJIAccessoryAggregation_DJISpeaker_DJIAudioFileInfo.html">DJIAudioFileInfo</a>
</dd>
</ul>
</dd>
<dd><a href="../AccessoryAggregation/DJIAccessoryAggregation_AggregationState.html">DJIAccessoryAggregationState</a>
</dd>
</ul>
</dd>
<dd><a data-href="../RTKBaseStation/DJIRTKBaseStation.html" class="sub-toggle">DJIRTKBaseStation<i class="fa fa-angle-down"></i><i class="fa fa-angle-up"></i></a>
<ul class="sub-menu">
<dd><a href="../RTKBaseStation/DJIRTKBaseStation_DJIRTKBaseStationBatteryState.html">DJIRTKBaseStationBatteryState</a>
</dd>
<dd><a href="../RTKBaseStation/DJIRTKBaseStation_DJIRTKBaseStationState.html">DJIRTKBaseStationState</a>
</dd>
</ul>
</dd>
<dd><a data-href="../Lidar/DJILidar.html" class="sub-toggle">DJILidar<i class="fa fa-angle-down"></i><i class="fa fa-angle-up"></i></a>
<ul class="sub-menu">
<dd><a href="../Lidar/DJILidar_DJILidarCapabilities.html">DJILidarCapabilities</a>
</dd>
<dd><a href="../Lidar/DJILidar_pointCloudLiveViewData.html">DJILidarPointCloudLiveViewData</a>
</dd>
</ul>
</dd>
</dl>
<dl>
<dt>Mission Classes
</dt>
<dd><a href="../Missions/DJIMissionControl.html">DJIMissionControl</a>
</dd>
<dd><a data-href="../Missions/DJIMissionAction.html" class="sub-toggle">DJIMissionAction<i class="fa fa-angle-down"></i><i class="fa fa-angle-up"></i></a>
<ul class="sub-menu">
<dd><a href="../Missions/DJITakeOffAction.html">DJITakeOffAction</a>
</dd>
<dd><a href="../Missions/DJIAircraftYawAction.html">DJIAircraftYawAction</a>
</dd>
<dd><a href="../Missions/DJIGoToAction.html">DJIGoToAction</a>
</dd>
<dd><a href="../Missions/DJIGoHomeAction.html">DJIGoHomeAction</a>
</dd>
<dd><a href="../Missions/DJIHotpointAction.html">DJIHotpointAction</a>
</dd>
<dd><a href="../Missions/DJIGimbalAttitudeAction.html">DJIGimbalAttitudeAction</a>
</dd>
<dd><a href="../Missions/DJIRecordVideoAction.html">DJIRecordVideoAction</a>
</dd>
<dd><a href="../Missions/DJIShootPhotoAction.html">DJIShootPhotoAction</a>
</dd>
<dd><a href="../Missions/DJILandAction.html">DJILandAction</a>
</dd>
</ul>
</dd>
<dd><a data-href="../Missions/DJIMissionTrigger.html" class="sub-toggle">DJIMissionTrigger<i class="fa fa-angle-down"></i><i class="fa fa-angle-up"></i></a>
<ul class="sub-menu">
<dd><a href="../Missions/DJIMissionTrigger_DJIBatteryLevelMissionTrigger.html">DJIBatteryLevelMissionTrigger</a>
</dd>
<dd><a href="../Missions/DJIMissionTrigger_DJIWaypointReachedMissionTrigger.html">DJIWaypointReachedMissionTrigger</a>
</dd>
<dd><a href="../Missions/DJIMissionTrigger_DJIAircraftLandedMissionTrigger.html">DJIAircraftLandedMissionTrigger</a>
</dd>
</ul>
</dd>
<dd><a data-href="../Missions/DJIWaypointMissionOperator.html" class="sub-toggle">DJIWaypointMissionOperator<i class="fa fa-angle-down"></i><i class="fa fa-angle-up"></i></a>
<ul class="sub-menu">
<dd><a data-href="../Missions/DJIWaypointMission.html" class="sub-toggle">DJIWaypointMission<i class="fa fa-angle-down"></i><i class="fa fa-angle-up"></i></a>
<ul class="sub-menu">
<dd><a data-href="../Missions/DJIWaypoint.html" class="sub-toggle">DJIWaypoint<i class="fa fa-angle-down"></i><i class="fa fa-angle-up"></i></a>
<ul class="sub-menu">
<dd><a href="../Missions/DJIWaypoint_DJIWaypointAction.html">DJIWaypointAction</a>
</dd>
</ul>
</dd>
<dd><a href="../Missions/DJIMutableWaypointMission.html">DJIMutableWaypointMission</a>
</dd>
<dd><a href="../Missions/DJIWaypointMission_DJIWaypointMissionInterruption.html">DJIWaypointMissionInterruption</a>
</dd>
</ul>
</dd>
<dd><a data-href="../Missions/DJIWaypointMissionUploadEvent.html" class="sub-toggle">DJIWaypointMissionUploadEvent<i class="fa fa-angle-down"></i><i class="fa fa-angle-up"></i></a>
<ul class="sub-menu">
<dd><a href="../Missions/DJIWaypointMission_DJIWaypointUploadProgress.html">DJIWaypointUploadProgress</a>
</dd>
</ul>
</dd>
<dd><a data-href="../Missions/DJIWaypointMissionDownloadEvent.html" class="sub-toggle">DJIWaypointMissionDownloadEvent<i class="fa fa-angle-down"></i><i class="fa fa-angle-up"></i></a>
<ul class="sub-menu">
<dd><a href="../Missions/DJIWaypointMission_DJIWaypointDownloadProgress.html">DJIWaypointDownloadProgress</a>
</dd>
</ul>
</dd>
<dd><a data-href="../Missions/DJIWaypointMissionExecutionEvent.html" class="sub-toggle">DJIWaypointMissionExecutionEvent<i class="fa fa-angle-down"></i><i class="fa fa-angle-up"></i></a>
<ul class="sub-menu">
<dd><a href="../Missions/DJIWaypointMission_DJIWaypointExecutionProgress.html">DJIWaypointExecutionProgress</a>
</dd>
</ul>
</dd>
</ul>
</dd>
<dd><a data-href="../Missions/DJIWaypointV2MissionOperator.html" class="sub-toggle">DJIWaypointV2MissionOperator<i class="fa fa-angle-down"></i><i class="fa fa-angle-up"></i></a>
<ul class="sub-menu">
<dd><a data-href="../Missions/DJIWaypointV2Mission.html" class="sub-toggle">DJIWaypointV2Mission<i class="fa fa-angle-down"></i><i class="fa fa-angle-up"></i></a>
<ul class="sub-menu">
<dd><a href="../Missions/DJIMutableWaypointV2Mission.html">DJIMutableWaypointV2Mission</a>
</dd>
<dd><a href="../Missions/DJIWaypointV2.html">DJIWaypointV2</a>
</dd>
</ul>
</dd>
<dd><a href="../Missions/DJIWaypointV2MissionActionExecutionEvent.html">DJIWaypointV2MissionActionExecutionEvent</a>
</dd>
<dd><a href="../Missions/DJIWaypointV2MissionActionDownloadEvent.html">DJIWaypointV2MissionActionDownloadEvent</a>
</dd>
<dd><a href="../Missions/DJIWaypointV2MissionActionUploadEvent.html">DJIWaypointV2MissionActionUploadEvent</a>
</dd>
<dd><a href="../Missions/DJIWaypointV2MissionExecutionEvent.html">DJIWaypointV2MissionExecutionEvent</a>
</dd>
<dd><a href="../Missions/DJIWaypointV2MissionDownloadEvent.html">DJIWaypointV2MissionDownloadEvent</a>
</dd>
<dd><a href="../Missions/DJIWaypointV2MissionUploadEvent.html">DJIWaypointV2MissionUploadEvent</a>
</dd>
<dd><a data-href="../Missions/DJIWaypointV2Action.html" class="sub-toggle">DJIWaypointV2Action<i class="fa fa-angle-down"></i><i class="fa fa-angle-up"></i></a>
<ul class="sub-menu">
<dd><a data-href="../Missions/DJIWaypointV2Action_DJIWaypointV2Actuator.html" class="sub-toggle">DJIWaypointV2Actuator<i class="fa fa-angle-down"></i><i class="fa fa-angle-up"></i></a>
<ul class="sub-menu">
<dd><a data-href="../Missions/DJIWaypointV2Actuator_DJIWaypointV2GimbalActuatorParam.html" class="sub-toggle">DJIWaypointV2GimbalActuatorParam<i class="fa fa-angle-down"></i><i class="fa fa-angle-up"></i></a>
<ul class="sub-menu">
<dd><a data-href="../Missions/DJIWaypointV2GimbalActuatorParam_DJIWaypointV2GimbalPathShootingParam.html" class="sub-toggle">DJIWaypointV2GimbalPathShootingParam<i class="fa fa-angle-down"></i><i class="fa fa-angle-up"></i></a>
<ul class="sub-menu">
<dd><a href="../Missions/DJIWaypointV2GimbalActuatorParam_DJIWaypointV2GimbalPathPointInfo.html">DJIWaypointV2GimbalPathPointInfo</a>
</dd>
<dd><a href="../Missions/DJIWaypointV2GimbalActuatorParam_DJIWaypointV2GimbalStartPathShootingParam.html">DJIWaypointV2GimbalStartPathShootingParam</a>
</dd>
<dd><a href="../Missions/DJIWaypointV2GimbalActuatorParam_DJIWaypointV2GimbalStopPathShootingParam.html">DJIWaypointV2GimbalStopPathShootingParam</a>
</dd>
</ul>
</dd>
</ul>
</dd>
<dd><a data-href="../Missions/DJIWaypointV2Actuator_DJIWaypointV2AircraftControlParam.html" class="sub-toggle">DJIWaypointV2AircraftControlParam<i class="fa fa-angle-down"></i><i class="fa fa-angle-up"></i></a>
<ul class="sub-menu">
<dd><a href="../Missions/DJIWaypointV2AircraftControlParam_DJIWaypointV2AircraftControlFlyingParam.html">DJIWaypointV2AircraftControlFlyingParam</a>
</dd>
<dd><a href="../Missions/DJIWaypointV2AircraftControlParam_DJIWaypointV2AircraftControlRotateHeadingParam.html">DJIWaypointV2AircraftControlRotateHeadingParam</a>
</dd>
</ul>
</dd>
<dd><a href="../Missions/DJIWaypointV2Actuator_PointCloudRecordActuatorParam.html">DJIWaypointV2LidarPointCloudRecordParam</a>
</dd>
<dd><a href="../Missions/DJIWaypointV2Actuator_DJIWaypointV2LidarActuatorParam.html">DJIWaypointV2LidarActuatorParam</a>
</dd>
<dd><a data-href="../Missions/DJIWaypointV2Actuator_DJIWaypointV2CameraActuatorParam.html" class="sub-toggle">DJIWaypointV2CameraActuatorParam<i class="fa fa-angle-down"></i><i class="fa fa-angle-up"></i></a>
<ul class="sub-menu">
<dd><a href="../Missions/DJIWaypointV2CameraActuatorParam_DJIWaypointV2CameraFocalLengthParam.html">DJIWaypointV2CameraFocalLengthParam</a>
</dd>
<dd><a href="../Missions/DJIWaypointV2Actuator_DJIWaypointCameraFocusModeParam.html">DJIWaypointV2CameraFocusModeParam</a>
</dd>
<dd><a data-href="../Missions/DJIWaypointV2CameraActuatorParam_DJIWaypointV2CameraFocusParam.html" class="sub-toggle">DJIWaypointV2CameraFocusParam<i class="fa fa-angle-down"></i><i class="fa fa-angle-up"></i></a>
<ul class="sub-menu">
<dd><a href="../Missions/DJIWaypointV2ActionActuatorParam_DJIWaypointV2CameraFocus_RectangleTargetParam.html">DJIWaypointV2CameraFocusRectangleTargetParam</a>
</dd>
<dd><a href="../Missions/DJIWaypointV2ActionActuatorParam_DJIWaypointV2CameraFocus_PointTargetParam.html">DJIWaypointV2CameraFocusPointTargetParam</a>
</dd>
</ul>
</dd>
<dd><a href="../Missions/DJIWaypointV2Actuator_DJIWaypointCameraCustomNameParam.html">DJIWaypointV2CameraCustomNameParam</a>
</dd>
</ul>
</dd>
</ul>
</dd>
<dd><a data-href="../Missions/DJIWaypointV2Action_DJIWaypointV2Trigger.html" class="sub-toggle">DJIWaypointV2Trigger<i class="fa fa-angle-down"></i><i class="fa fa-angle-up"></i></a>
<ul class="sub-menu">
<dd><a href="../Missions/DJIWaypointV2Trigger_DJIWaypointV2IntervalTriggerParam.html">DJIWaypointV2IntervalTriggerParam</a>
</dd>
<dd><a href="../Missions/DJIWaypointV2Trigger_DJIWaypointV2TrajectoryTriggerParam.html">DJIWaypointV2TrajectoryTriggerParam</a>
</dd>
<dd><a href="../Missions/DJIWaypointV2Trigger_DJIWaypointV2AssociateTriggerParam.html">DJIWaypointV2AssociateTriggerParam</a>
</dd>
<dd><a href="../Missions/DJIWaypointV2Trigger_DJIWaypointV2ReachPointTriggerParam.html">DJIWaypointV2ReachPointTriggerParam</a>
</dd>
</ul>
</dd>
</ul>
</dd>
<dd><a href="../Missions/DJIWaypointV2MissionOperator_DJIWaypointV2UploadProgress.html">DJIWaypointV2UploadProgress</a>
</dd>
<dd><a href="../Missions/DJIWaypointV2MissionOperator_DJIWaypointV2DownloadProgress.html">DJIWaypointV2DownloadProgress</a>
</dd>
<dd><a href="../Missions/DJIWaypointV2MissionOperator_DJIWaypointV2ExecutionProgress.html">DJIWaypointV2ExecutionProgress</a>
</dd>
<dd><a href="../Missions/DJIWaypointV2MissionOperator_DJIWaypointV2ActionUploadProgress.html">DJIWaypointV2ActionUploadProgress</a>
</dd>
<dd><a href="../Missions/DJIWaypointV2MissionOperator_DJIWaypointV2ActionDownloadProgress.html">DJIWaypointV2ActionDownloadProgress</a>
</dd>
<dd><a href="../Missions/DJIWaypointV2MissionOperator_DJIWaypointV2ActionExecutionProgress.html">DJIWaypointV2ActionExecutionProgress</a>
</dd>
</ul>
</dd>
<dd><a data-href="../Missions/DJIFollowMeMissionOperator.html" class="sub-toggle">DJIFollowMeMissionOperator<i class="fa fa-angle-down"></i><i class="fa fa-angle-up"></i></a>
<ul class="sub-menu">
<dd><a href="../Missions/DJIFollowMeMission.html">DJIFollowMeMission</a>
</dd>
<dd><a href="../Missions/DJIFollowMeMissionEvent.html">DJIFollowMeMissionEvent</a>
</dd>
</ul>
</dd>
<dd><a data-href="../Missions/DJIPanoramaMissionOperator.html" class="sub-toggle">DJIPanoramaMissionOperator<i class="fa fa-angle-down"></i><i class="fa fa-angle-up"></i></a>
<ul class="sub-menu">
<dd><a href="../Missions/DJIPanoramaMissionEvent.html">DJIPanoramaMissionEvent</a>
</dd>
<dd><a href="../Missions/DJIPanoramaMission_DJIPanoramaMissionStatus.html">DJIPanoramaMissionExecutionState</a>
</dd>
</ul>
</dd>
<dd><a data-href="../Missions/DJIHotpointMissionOperator.html" class="sub-toggle">DJIHotpointMissionOperator<i class="fa fa-angle-down"></i><i class="fa fa-angle-up"></i></a>
<ul class="sub-menu">
<dd><a href="../Missions/DJIHotPointMission.html">DJIHotpointMission</a>
</dd>
<dd><a href="../Missions/DJIHotpointMissionEvent.html">DJIHotpointMissionEvent</a>
</dd>
</ul>
</dd>
<dd><a data-href="../Missions/DJIIntelligentHotpointMissionOperator.html" class="sub-toggle">DJIIntelligentHotpointMissionOperator<i class="fa fa-angle-down"></i><i class="fa fa-angle-up"></i></a>
<ul class="sub-menu">
<dd><a href="../Missions/DJIIntelligentHotpointMission.html">DJIIntelligentHotpointMission</a>
</dd>
<dd><a href="../Missions/DJIIntelligentHotpointMissionOperator_DJIIntelligentHotpointMissionEvent.html">DJIIntelligentHotpointMissionEvent</a>
</dd>
</ul>
</dd>
<dd><a data-href="../Missions/DJITapFlyMissionOperator.html" class="sub-toggle">DJITapFlyMissionOperator<i class="fa fa-angle-down"></i><i class="fa fa-angle-up"></i></a>
<ul class="sub-menu">
<dd><a data-href="../Missions/DJITapFlyMission.html" class="sub-toggle">DJITapFlyMission<i class="fa fa-angle-down"></i><i class="fa fa-angle-up"></i></a>
<ul class="sub-menu">
<dd><a href="../Missions/DJITapFlyMission_DJITapFlyExecutionState.html">DJITapFlyExecutionState</a>
</dd>
<dd><a href="../Missions/DJITapFlyMission_DJIVector.html">DJISDKVector3D</a>
</dd>
</ul>
</dd>
<dd><a href="../Missions/DJITapFlyMissionEvent.html">DJITapFlyMissionEvent</a>
</dd>
</ul>
</dd>
<dd><a data-href="../Missions/DJIActiveTrackMissionOperator.html" class="sub-toggle">DJIActiveTrackMissionOperator<i class="fa fa-angle-down"></i><i class="fa fa-angle-up"></i></a>
<ul class="sub-menu">
<dd><a data-href="../Missions/DJIActiveTrackMission.html" class="sub-toggle">DJIActiveTrackMission<i class="fa fa-angle-down"></i><i class="fa fa-angle-up"></i></a>
<ul class="sub-menu">
<dd><a href="../Missions/DJIActiveTrackTrackingState.html">DJIActiveTrackTrackingState</a>
</dd>
<dd><a href="../Missions/DJIActiveTrackMission_DJISubjectSensingState.html">DJISubjectSensingState</a>
</dd>
</ul>
</dd>
<dd><a href="../Missions/DJIActiveTrackMissionEvent.html">DJIActiveTrackMissionEvent</a>
</dd>
</ul>
</dd>
<dd><a href="../Mission/DJIMission.html">DJIMission</a>
</dd>
</dl>
<dl>
<dt>Misc Classes
</dt>
<dd><a data-href="../ParamCapability/DJIParamCapability.html" class="sub-toggle">DJIParamCapability<i class="fa fa-angle-down"></i><i class="fa fa-angle-up"></i></a>
<ul class="sub-menu">
<dd><a href="../ParamCapability/DJIParamCapability_DJIParamCapabilityMinMax.html">DJIParamCapabilityMinMax</a>
</dd>
</ul>
</dd>
<dd><a data-href="../SDKError/DJIError.html" class="sub-toggle">NSError<i class="fa fa-angle-down"></i><i class="fa fa-angle-up"></i></a>
<ul class="sub-menu">
<dd><a href="../SDKError/DJIError_DJISDKCacheError.html">NSError</a>
</dd>
</ul>
</dd>
<dd><a data-href="../Diagnostics/DJIDiagnostics.html" class="sub-toggle">DJIDiagnostics<i class="fa fa-angle-down"></i><i class="fa fa-angle-up"></i></a>
<ul class="sub-menu">
<dd><a href="../Diagnostics/DJIDiagnostics_DJIDiagnosticsDeviceHealthInformation.html">DJIDiagnosticsDeviceHealthInformation</a>
</dd>
</ul>
</dd>
<dd><a href="../RemoteLogger/DJIRemoteLogger.html">DJIRemoteLogger</a>
</dd>
</dl>
</div>
</div>
<div class="site-main">
<div class="article"><div class="article"><h1><font color="#AAA">class </font>DJIFlightHubUpStream</h1></div>
<figure class="highlight objc"><table><tr><td class="code"><pre><span class="line"><span class="class"><span class="keyword">@interface</span> <span class="title">DJIFlightHubUpStream</span> : <span class="title">NSObject</span></span></span><br></pre></td></tr></table></figure>
<html><table class="table-supportedby"><tr valign="top"><td width="15%"><font color="#999"><i>Header:</i></font></td><td width="85%"><font color="#999">DJIFlightHubBaseTypes.h</font></td></tr><tr valign="top"><td width="15%"><font color="#999"><i>Inherits From:</i></font></td><td width="85%"><font color="#999"><code>NSObject</code></font></td></tr></table></html>
<h5 id="description">Description:</h5>
<p><font color="#666">This class contains RTMP URL of up stream.</font></p>
<h5 id="class-members">Class Members:</h5>
<div class="api-row" id="djiflighthubmanager_djiflighthubupstream_rtmpurl"><div class="api-col left"></div><div class="api-col middle" style="color:#AAA">property</div><div class="api-col right"><a class="trigger" href="#djiflighthubmanager_djiflighthubupstream_rtmpurl_inline">rtmpURL</a></div></div><div class="inline-doc" id="djiflighthubmanager_djiflighthubupstream_rtmpurl_inline" <blockquote>
<div class="article"><h6><font color="#AAA">property </font>rtmpURL</h6></div>
<figure class="highlight objc"><table><tr><td class="code"><pre><span class="line"><span class="keyword">@property</span> (<span class="keyword">nonatomic</span>, <span class="keyword">readonly</span>) <span class="built_in">NSString</span> *rtmpURL</span><br></pre></td></tr></table></figure>
<html><table class="table-supportedby"><tr valign="top"><td width="15%"><font color="#999"><i>Header:</i></font></td><td width="85%"><font color="#999">DJIFlightHubBaseTypes.h</font></td></tr></table></html>
<h5 id="description-v2">Description:</h5>
<p><font color="#666">Gets up stream RTMP URL of live stream.</font></p>
</div>
</div>
</div>
</div>
<div id="search-modal" class="search-modal modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header"><a href="javascript:;" @click="closeSearch" class="btn-close">×</a>
<h2 class="title">Search Mobile SDK Document
</h2>
<input type="text" v-model="searchInput" @keydown.enter="search">
</div>
<div class="modal-body">
<p v-show="!!searchCount" class="search-count"><span v-cloak>{{searchCount}}</span> Results
</p>
<ul v-show="!!searchCount" class="search-result">
<li v-for="item in searchResult"><a v-bind:href="item.url | docUrl">
<h3 class="title">{{{(item.highlights && item.highlights.title) || item.title}}}</h3>
<p class="content">{{{(item.highlights && item.highlights.content[0]) || item.title}}}</p></a></li>
</ul>
<div v-show="showLoadMore" class="text-center"><a href="javascript:;" @click="loadMoreSearch" class="btn-learn-more">Load More</a></div>
<div v-show="searchLoading" class="text-center">Loading...
</div>
<div v-show="!searchCount && !searchLoading" class="text-center">Not Found
</div>
</div>
</div>
</div>
</div>
</div>
<footer id="site-footer" class="site-footer">
<div class="container">
<div class="foot-nav row">
<nav class="link-list col-xs-2"><span class="title">SDK</span><a href="/mobile-sdk">Mobile SDK</a><a href="/ux-sdk">UX SDK</a><a href="/onboard-sdk">Onboard SDK</a><a href="/payload-sdk">Payload SDK</a><a href="/windows-sdk">Windows SDK</a></nav>
<nav class="link-list col-xs-2"><span class="title">Info</span><a href="/products">Products</a></nav>
<nav class="link-list col-xs-2"><span class="title">Community</span><a href="http://stackoverflow.com/questions/tagged/dji-sdk" target="_blank">Stack Overflow</a><a href="https://www.youtube.com/channel/UCPQwN5xsob8zZGIcDhkYqUA" target="_blank">YouTube</a><a href="https://twitter.com/djidevelopers" target="_blank">Twitter</a></nav>
<nav class="link-list col-xs-2"><span class="title">Contact Us</span><a href="mailto:dev@dji.com"> dev@dji.com</a></nav>
<nav class="link-list col-xs-2"><span class="title">Business Cooperation</span><a href="mailto:dev@dji.com"> dev@dji.com</a></nav>
<nav class="link-list col-xs-2"><span class="title">BILLING</span><a href="mailto:billing-dev@dji.com"> billing-dev@dji.com</a></nav>
</div>
<div class="foot-copyright row">
<div class="col-xs-3 foot-logo"><img src="../../images/dji-logo-foot.png"></div>
<div class="copyright col-xs-7"><span>Copyright © 2019 DJI All Rights Reserved</span><a href="/policies/privacy">Privacy Policy</a><a href="/policies/terms">Terms of Use</a></div>
</div>
</div>
</footer>
<script type="text/javascript">
window.Config = window.config = {
sdk: "mobile-sdk",
locale: "en",
environment: "development",
api_host: ""
};
</script>
<!-- build:js /javascripts/doc-vendor.js-->
<script src="../../javascripts/lib/jquery-2.1.4.min.js" type="text/javascript"></script>
<script src="../../javascripts/lib/bootstrap.js" type="text/javascript"></script>
<script src="../../javascripts/lib/vue.min.js" type="text/javascript"></script>
<!-- endbuild-->
<!-- build:js /javascripts/doc-app.js-->
<script src="../../javascripts/util/cookie.js" type="text/javascript"></script>
<script src="../../javascripts/util/url-manager.js" type="text/javascript"></script>
<script src="../../javascripts/util/ajax-manager.js" type="text/javascript"></script>
<script src="../../javascripts/base/footer.js" type="text/javascript"></script>
<script src="../../javascripts/base/header.js" type="text/javascript"></script>
<script src="../../javascripts/util/searcher.js" type="text/javascript"></script>
<script src="../../javascripts/search_index.js" type="text/javascript"></script>
<script src="../../javascripts/searchdoc.js" type="text/javascript"></script>
<script src="../../javascripts/api.js" type="text/javascript"></script>
<!-- endbuild-->
<script type="text/javascript">
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','http://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-43055594-1', 'auto');
ga('send', 'pageview');
</script>
</body> | {
"content_hash": "caea74e0ea8dceea58a5e3d648a56ec4",
"timestamp": "",
"source": "github",
"line_count": 902,
"max_line_length": 398,
"avg_line_length": 77.66407982261642,
"alnum_prop": 0.4929981585371076,
"repo_name": "dji-sdk/Mobile-SDK-Doc",
"id": "b30cc7245df6d78faa4464548cda53c8ff5c12fb",
"size": "70055",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "api-reference/ios-api/Components/FlightHubManager/DJIFlightHubManager_DJIFlightHubUpStream.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1016971"
},
{
"name": "HTML",
"bytes": "112517595"
},
{
"name": "JavaScript",
"bytes": "962076"
},
{
"name": "Pug",
"bytes": "10504"
},
{
"name": "SCSS",
"bytes": "303141"
}
],
"symlink_target": ""
} |
ENAME=$0
usage()
{
cat << EOF
Usage: $ENAME OPTION
-x Clean git repository before preparing release
EOF
}
while getopts "x" opt; do
case "$opt" in
x )
git clean -ffdx
;;
? )
usage
exit 1
;;
esac
done
logfile=${PWD}/release.$(date +%y-%m-%d-%T).log
echo "Logging to ${logfile}"
# TODO: Handle tagging?
# Ensure these all have a similar and sane timestamp to
# prevent autotools from trying to rebuild portions wrongly
touch configure.ac aclocal.m4 configure Makefile.am Makefile.in
if [ ! -e ./configure ]; then
echo "Configure missing. Did you bootstrap?"
fi
config_opts=""
if ./configure --help | grep -- --enable-maintainer-mode > /dev/null; then
config_opts+=" --enable-maintainer-mode";
fi
echo "Running configure with options '${config_opts}'"
if ! ./configure $config_opts >> ${logfile} 2>&1; then
echo "Configuration failed. Aborting"
exit 1
fi
if [ ! -e Makefile ]; then
echo "Makefile missing. Aborting"
exit 1
fi
echo "Running make distcheck"
make distcheck >> ${logfile} 2>&1
if [ $? != 0 ]; then
echo "make distcheck failed. Aborting"
exit 1
fi
# Extract out the name of the tarball from the log.
# There is probably a saner method to do this.
tarballs=$(awk '
/^=+$/ && doprint == 1 { exit 0 }
doprint == 1 { print $0 }
$0 ~ /archives ready for distribution/ { doprint = 1 }
' ${logfile})
if [ "x${tarballs}" == "x" ]; then
echo "Failed to build and verify tarballs"
exit 1
fi
echo "Found tarballs: ${tarballs}"
# Generate some popular checksums for the tarball
for tarball in ${tarballs}; do
for sum in sha256 md5; do
echo "Generating ${tarball}.${sum}"
${sum}sum ${tarball} > ${tarball}.${sum}
done
done
# TODO: Support signing these releases
exit 0
| {
"content_hash": "55ed33990c4cd6e1bd132a9dd9d2d32a",
"timestamp": "",
"source": "github",
"line_count": 87,
"max_line_length": 74,
"avg_line_length": 20.20689655172414,
"alnum_prop": 0.6581342434584755,
"repo_name": "paflib/paflib",
"id": "be19538e6d3e4f5a1a457688cf2def7604bfbd00",
"size": "1771",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "make-release.sh",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "38336"
},
{
"name": "C",
"bytes": "114040"
},
{
"name": "C++",
"bytes": "4941"
},
{
"name": "M4",
"bytes": "5518"
},
{
"name": "Makefile",
"bytes": "208371"
},
{
"name": "Roff",
"bytes": "23066"
},
{
"name": "Shell",
"bytes": "391530"
}
],
"symlink_target": ""
} |
package endpoints
import (
"fmt"
"net/http"
gpath "path"
"reflect"
"sort"
"strings"
"time"
"unicode"
restful "github.com/emicklei/go-restful"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/conversion"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apiserver/pkg/admission"
"k8s.io/apiserver/pkg/endpoints/discovery"
"k8s.io/apiserver/pkg/endpoints/handlers"
"k8s.io/apiserver/pkg/endpoints/handlers/fieldmanager"
"k8s.io/apiserver/pkg/endpoints/handlers/negotiation"
"k8s.io/apiserver/pkg/endpoints/metrics"
"k8s.io/apiserver/pkg/features"
"k8s.io/apiserver/pkg/registry/rest"
utilfeature "k8s.io/apiserver/pkg/util/feature"
)
const (
ROUTE_META_GVK = "x-kubernetes-group-version-kind"
ROUTE_META_ACTION = "x-kubernetes-action"
)
type APIInstaller struct {
group *APIGroupVersion
prefix string // Path prefix where API resources are to be registered.
minRequestTimeout time.Duration
}
// Struct capturing information about an action ("GET", "POST", "WATCH", "PROXY", etc).
type action struct {
Verb string // Verb identifying the action ("GET", "POST", "WATCH", "PROXY", etc).
Path string // The path of the action
Params []*restful.Parameter // List of parameters associated with the action.
Namer handlers.ScopeNamer
AllNamespaces bool // true iff the action is namespaced but works on aggregate result for all namespaces
}
// An interface to see if one storage supports override its default verb for monitoring
type StorageMetricsOverride interface {
// OverrideMetricsVerb gives a storage object an opportunity to override the verb reported to the metrics endpoint
OverrideMetricsVerb(oldVerb string) (newVerb string)
}
// An interface to see if an object supports swagger documentation as a method
type documentable interface {
SwaggerDoc() map[string]string
}
// toDiscoveryKubeVerb maps an action.Verb to the logical kube verb, used for discovery
var toDiscoveryKubeVerb = map[string]string{
"CONNECT": "", // do not list in discovery.
"DELETE": "delete",
"DELETECOLLECTION": "deletecollection",
"GET": "get",
"LIST": "list",
"PATCH": "patch",
"POST": "create",
"PROXY": "proxy",
"PUT": "update",
"WATCH": "watch",
"WATCHLIST": "watch",
}
// Install handlers for API resources.
func (a *APIInstaller) Install() ([]metav1.APIResource, *restful.WebService, []error) {
var apiResources []metav1.APIResource
var errors []error
ws := a.newWebService()
// Register the paths in a deterministic (sorted) order to get a deterministic swagger spec.
paths := make([]string, len(a.group.Storage))
var i int = 0
for path := range a.group.Storage {
paths[i] = path
i++
}
sort.Strings(paths)
for _, path := range paths {
apiResource, err := a.registerResourceHandlers(path, a.group.Storage[path], ws)
if err != nil {
errors = append(errors, fmt.Errorf("error in registering resource: %s, %v", path, err))
}
if apiResource != nil {
apiResources = append(apiResources, *apiResource)
}
}
return apiResources, ws, errors
}
// newWebService creates a new restful webservice with the api installer's prefix and version.
func (a *APIInstaller) newWebService() *restful.WebService {
ws := new(restful.WebService)
ws.Path(a.prefix)
// a.prefix contains "prefix/group/version"
ws.Doc("API at " + a.prefix)
// Backwards compatibility, we accepted objects with empty content-type at V1.
// If we stop using go-restful, we can default empty content-type to application/json on an
// endpoint by endpoint basis
ws.Consumes("*/*")
mediaTypes, streamMediaTypes := negotiation.MediaTypesForSerializer(a.group.Serializer)
ws.Produces(append(mediaTypes, streamMediaTypes...)...)
ws.ApiVersion(a.group.GroupVersion.String())
return ws
}
// calculate the storage gvk, the gvk objects are converted to before persisted to the etcd.
func getStorageVersionKind(storageVersioner runtime.GroupVersioner, storage rest.Storage, typer runtime.ObjectTyper) (schema.GroupVersionKind, error) {
object := storage.New()
fqKinds, _, err := typer.ObjectKinds(object)
if err != nil {
return schema.GroupVersionKind{}, err
}
gvk, ok := storageVersioner.KindForGroupVersionKinds(fqKinds)
if !ok {
return schema.GroupVersionKind{}, fmt.Errorf("cannot find the storage version kind for %v", reflect.TypeOf(object))
}
return gvk, nil
}
// GetResourceKind returns the external group version kind registered for the given storage
// object. If the storage object is a subresource and has an override supplied for it, it returns
// the group version kind supplied in the override.
func GetResourceKind(groupVersion schema.GroupVersion, storage rest.Storage, typer runtime.ObjectTyper) (schema.GroupVersionKind, error) {
// Let the storage tell us exactly what GVK it has
if gvkProvider, ok := storage.(rest.GroupVersionKindProvider); ok {
return gvkProvider.GroupVersionKind(groupVersion), nil
}
object := storage.New()
fqKinds, _, err := typer.ObjectKinds(object)
if err != nil {
return schema.GroupVersionKind{}, err
}
// a given go type can have multiple potential fully qualified kinds. Find the one that corresponds with the group
// we're trying to register here
fqKindToRegister := schema.GroupVersionKind{}
for _, fqKind := range fqKinds {
if fqKind.Group == groupVersion.Group {
fqKindToRegister = groupVersion.WithKind(fqKind.Kind)
break
}
}
if fqKindToRegister.Empty() {
return schema.GroupVersionKind{}, fmt.Errorf("unable to locate fully qualified kind for %v: found %v when registering for %v", reflect.TypeOf(object), fqKinds, groupVersion)
}
// group is guaranteed to match based on the check above
return fqKindToRegister, nil
}
func (a *APIInstaller) registerResourceHandlers(path string, storage rest.Storage, ws *restful.WebService) (*metav1.APIResource, error) {
admit := a.group.Admit
optionsExternalVersion := a.group.GroupVersion
if a.group.OptionsExternalVersion != nil {
optionsExternalVersion = *a.group.OptionsExternalVersion
}
resource, subresource, err := splitSubresource(path)
if err != nil {
return nil, err
}
group, version := a.group.GroupVersion.Group, a.group.GroupVersion.Version
fqKindToRegister, err := GetResourceKind(a.group.GroupVersion, storage, a.group.Typer)
if err != nil {
return nil, err
}
versionedPtr, err := a.group.Creater.New(fqKindToRegister)
if err != nil {
return nil, err
}
defaultVersionedObject := indirectArbitraryPointer(versionedPtr)
kind := fqKindToRegister.Kind
isSubresource := len(subresource) > 0
// If there is a subresource, namespace scoping is defined by the parent resource
namespaceScoped := true
if isSubresource {
parentStorage, ok := a.group.Storage[resource]
if !ok {
return nil, fmt.Errorf("missing parent storage: %q", resource)
}
scoper, ok := parentStorage.(rest.Scoper)
if !ok {
return nil, fmt.Errorf("%q must implement scoper", resource)
}
namespaceScoped = scoper.NamespaceScoped()
} else {
scoper, ok := storage.(rest.Scoper)
if !ok {
return nil, fmt.Errorf("%q must implement scoper", resource)
}
namespaceScoped = scoper.NamespaceScoped()
}
// what verbs are supported by the storage, used to know what verbs we support per path
creater, isCreater := storage.(rest.Creater)
namedCreater, isNamedCreater := storage.(rest.NamedCreater)
lister, isLister := storage.(rest.Lister)
getter, isGetter := storage.(rest.Getter)
getterWithOptions, isGetterWithOptions := storage.(rest.GetterWithOptions)
gracefulDeleter, isGracefulDeleter := storage.(rest.GracefulDeleter)
collectionDeleter, isCollectionDeleter := storage.(rest.CollectionDeleter)
updater, isUpdater := storage.(rest.Updater)
patcher, isPatcher := storage.(rest.Patcher)
watcher, isWatcher := storage.(rest.Watcher)
connecter, isConnecter := storage.(rest.Connecter)
storageMeta, isMetadata := storage.(rest.StorageMetadata)
storageVersionProvider, isStorageVersionProvider := storage.(rest.StorageVersionProvider)
if !isMetadata {
storageMeta = defaultStorageMetadata{}
}
exporter, isExporter := storage.(rest.Exporter)
if !isExporter {
exporter = nil
}
versionedExportOptions, err := a.group.Creater.New(optionsExternalVersion.WithKind("ExportOptions"))
if err != nil {
return nil, err
}
if isNamedCreater {
isCreater = true
}
var versionedList interface{}
if isLister {
list := lister.NewList()
listGVKs, _, err := a.group.Typer.ObjectKinds(list)
if err != nil {
return nil, err
}
versionedListPtr, err := a.group.Creater.New(a.group.GroupVersion.WithKind(listGVKs[0].Kind))
if err != nil {
return nil, err
}
versionedList = indirectArbitraryPointer(versionedListPtr)
}
versionedListOptions, err := a.group.Creater.New(optionsExternalVersion.WithKind("ListOptions"))
if err != nil {
return nil, err
}
versionedCreateOptions, err := a.group.Creater.New(optionsExternalVersion.WithKind("CreateOptions"))
if err != nil {
return nil, err
}
versionedPatchOptions, err := a.group.Creater.New(optionsExternalVersion.WithKind("PatchOptions"))
if err != nil {
return nil, err
}
versionedUpdateOptions, err := a.group.Creater.New(optionsExternalVersion.WithKind("UpdateOptions"))
if err != nil {
return nil, err
}
var versionedDeleteOptions runtime.Object
var versionedDeleterObject interface{}
if isGracefulDeleter {
versionedDeleteOptions, err = a.group.Creater.New(optionsExternalVersion.WithKind("DeleteOptions"))
if err != nil {
return nil, err
}
versionedDeleterObject = indirectArbitraryPointer(versionedDeleteOptions)
}
versionedStatusPtr, err := a.group.Creater.New(optionsExternalVersion.WithKind("Status"))
if err != nil {
return nil, err
}
versionedStatus := indirectArbitraryPointer(versionedStatusPtr)
var (
getOptions runtime.Object
versionedGetOptions runtime.Object
getOptionsInternalKind schema.GroupVersionKind
getSubpath bool
)
if isGetterWithOptions {
getOptions, getSubpath, _ = getterWithOptions.NewGetOptions()
getOptionsInternalKinds, _, err := a.group.Typer.ObjectKinds(getOptions)
if err != nil {
return nil, err
}
getOptionsInternalKind = getOptionsInternalKinds[0]
versionedGetOptions, err = a.group.Creater.New(a.group.GroupVersion.WithKind(getOptionsInternalKind.Kind))
if err != nil {
versionedGetOptions, err = a.group.Creater.New(optionsExternalVersion.WithKind(getOptionsInternalKind.Kind))
if err != nil {
return nil, err
}
}
isGetter = true
}
var versionedWatchEvent interface{}
if isWatcher {
versionedWatchEventPtr, err := a.group.Creater.New(a.group.GroupVersion.WithKind("WatchEvent"))
if err != nil {
return nil, err
}
versionedWatchEvent = indirectArbitraryPointer(versionedWatchEventPtr)
}
var (
connectOptions runtime.Object
versionedConnectOptions runtime.Object
connectOptionsInternalKind schema.GroupVersionKind
connectSubpath bool
)
if isConnecter {
connectOptions, connectSubpath, _ = connecter.NewConnectOptions()
if connectOptions != nil {
connectOptionsInternalKinds, _, err := a.group.Typer.ObjectKinds(connectOptions)
if err != nil {
return nil, err
}
connectOptionsInternalKind = connectOptionsInternalKinds[0]
versionedConnectOptions, err = a.group.Creater.New(a.group.GroupVersion.WithKind(connectOptionsInternalKind.Kind))
if err != nil {
versionedConnectOptions, err = a.group.Creater.New(optionsExternalVersion.WithKind(connectOptionsInternalKind.Kind))
if err != nil {
return nil, err
}
}
}
}
allowWatchList := isWatcher && isLister // watching on lists is allowed only for kinds that support both watch and list.
nameParam := ws.PathParameter("name", "name of the "+kind).DataType("string")
pathParam := ws.PathParameter("path", "path to the resource").DataType("string")
params := []*restful.Parameter{}
actions := []action{}
var resourceKind string
kindProvider, ok := storage.(rest.KindProvider)
if ok {
resourceKind = kindProvider.Kind()
} else {
resourceKind = kind
}
tableProvider, _ := storage.(rest.TableConvertor)
var apiResource metav1.APIResource
if utilfeature.DefaultFeatureGate.Enabled(features.StorageVersionHash) &&
isStorageVersionProvider &&
storageVersionProvider.StorageVersion() != nil {
versioner := storageVersionProvider.StorageVersion()
gvk, err := getStorageVersionKind(versioner, storage, a.group.Typer)
if err != nil {
return nil, err
}
apiResource.StorageVersionHash = discovery.StorageVersionHash(gvk.Group, gvk.Version, gvk.Kind)
}
// Get the list of actions for the given scope.
switch {
case !namespaceScoped:
// Handle non-namespace scoped resources like nodes.
resourcePath := resource
resourceParams := params
itemPath := resourcePath + "/{name}"
nameParams := append(params, nameParam)
proxyParams := append(nameParams, pathParam)
suffix := ""
if isSubresource {
suffix = "/" + subresource
itemPath = itemPath + suffix
resourcePath = itemPath
resourceParams = nameParams
}
apiResource.Name = path
apiResource.Namespaced = false
apiResource.Kind = resourceKind
namer := handlers.ContextBasedNaming{
SelfLinker: a.group.Linker,
ClusterScoped: true,
SelfLinkPathPrefix: gpath.Join(a.prefix, resource) + "/",
SelfLinkPathSuffix: suffix,
}
// Handler for standard REST verbs (GET, PUT, POST and DELETE).
// Add actions at the resource path: /api/apiVersion/resource
actions = appendIf(actions, action{"LIST", resourcePath, resourceParams, namer, false}, isLister)
actions = appendIf(actions, action{"POST", resourcePath, resourceParams, namer, false}, isCreater)
actions = appendIf(actions, action{"DELETECOLLECTION", resourcePath, resourceParams, namer, false}, isCollectionDeleter)
// DEPRECATED in 1.11
actions = appendIf(actions, action{"WATCHLIST", "watch/" + resourcePath, resourceParams, namer, false}, allowWatchList)
// Add actions at the item path: /api/apiVersion/resource/{name}
actions = appendIf(actions, action{"GET", itemPath, nameParams, namer, false}, isGetter)
if getSubpath {
actions = appendIf(actions, action{"GET", itemPath + "/{path:*}", proxyParams, namer, false}, isGetter)
}
actions = appendIf(actions, action{"PUT", itemPath, nameParams, namer, false}, isUpdater)
actions = appendIf(actions, action{"PATCH", itemPath, nameParams, namer, false}, isPatcher)
actions = appendIf(actions, action{"DELETE", itemPath, nameParams, namer, false}, isGracefulDeleter)
// DEPRECATED in 1.11
actions = appendIf(actions, action{"WATCH", "watch/" + itemPath, nameParams, namer, false}, isWatcher)
actions = appendIf(actions, action{"CONNECT", itemPath, nameParams, namer, false}, isConnecter)
actions = appendIf(actions, action{"CONNECT", itemPath + "/{path:*}", proxyParams, namer, false}, isConnecter && connectSubpath)
default:
namespaceParamName := "namespaces"
// Handler for standard REST verbs (GET, PUT, POST and DELETE).
namespaceParam := ws.PathParameter("namespace", "object name and auth scope, such as for teams and projects").DataType("string")
namespacedPath := namespaceParamName + "/{namespace}/" + resource
namespaceParams := []*restful.Parameter{namespaceParam}
resourcePath := namespacedPath
resourceParams := namespaceParams
itemPath := namespacedPath + "/{name}"
nameParams := append(namespaceParams, nameParam)
proxyParams := append(nameParams, pathParam)
itemPathSuffix := ""
if isSubresource {
itemPathSuffix = "/" + subresource
itemPath = itemPath + itemPathSuffix
resourcePath = itemPath
resourceParams = nameParams
}
apiResource.Name = path
apiResource.Namespaced = true
apiResource.Kind = resourceKind
namer := handlers.ContextBasedNaming{
SelfLinker: a.group.Linker,
ClusterScoped: false,
SelfLinkPathPrefix: gpath.Join(a.prefix, namespaceParamName) + "/",
SelfLinkPathSuffix: itemPathSuffix,
}
actions = appendIf(actions, action{"LIST", resourcePath, resourceParams, namer, false}, isLister)
actions = appendIf(actions, action{"POST", resourcePath, resourceParams, namer, false}, isCreater)
actions = appendIf(actions, action{"DELETECOLLECTION", resourcePath, resourceParams, namer, false}, isCollectionDeleter)
// DEPRECATED in 1.11
actions = appendIf(actions, action{"WATCHLIST", "watch/" + resourcePath, resourceParams, namer, false}, allowWatchList)
actions = appendIf(actions, action{"GET", itemPath, nameParams, namer, false}, isGetter)
if getSubpath {
actions = appendIf(actions, action{"GET", itemPath + "/{path:*}", proxyParams, namer, false}, isGetter)
}
actions = appendIf(actions, action{"PUT", itemPath, nameParams, namer, false}, isUpdater)
actions = appendIf(actions, action{"PATCH", itemPath, nameParams, namer, false}, isPatcher)
actions = appendIf(actions, action{"DELETE", itemPath, nameParams, namer, false}, isGracefulDeleter)
// DEPRECATED in 1.11
actions = appendIf(actions, action{"WATCH", "watch/" + itemPath, nameParams, namer, false}, isWatcher)
actions = appendIf(actions, action{"CONNECT", itemPath, nameParams, namer, false}, isConnecter)
actions = appendIf(actions, action{"CONNECT", itemPath + "/{path:*}", proxyParams, namer, false}, isConnecter && connectSubpath)
// list or post across namespace.
// For ex: LIST all pods in all namespaces by sending a LIST request at /api/apiVersion/pods.
// TODO: more strongly type whether a resource allows these actions on "all namespaces" (bulk delete)
if !isSubresource {
actions = appendIf(actions, action{"LIST", resource, params, namer, true}, isLister)
// DEPRECATED in 1.11
actions = appendIf(actions, action{"WATCHLIST", "watch/" + resource, params, namer, true}, allowWatchList)
}
}
// Create Routes for the actions.
// TODO: Add status documentation using Returns()
// Errors (see api/errors/errors.go as well as go-restful router):
// http.StatusNotFound, http.StatusMethodNotAllowed,
// http.StatusUnsupportedMediaType, http.StatusNotAcceptable,
// http.StatusBadRequest, http.StatusUnauthorized, http.StatusForbidden,
// http.StatusRequestTimeout, http.StatusConflict, http.StatusPreconditionFailed,
// http.StatusUnprocessableEntity, http.StatusInternalServerError,
// http.StatusServiceUnavailable
// and api error codes
// Note that if we specify a versioned Status object here, we may need to
// create one for the tests, also
// Success:
// http.StatusOK, http.StatusCreated, http.StatusAccepted, http.StatusNoContent
//
// test/integration/auth_test.go is currently the most comprehensive status code test
for _, s := range a.group.Serializer.SupportedMediaTypes() {
if len(s.MediaTypeSubType) == 0 || len(s.MediaTypeType) == 0 {
return nil, fmt.Errorf("all serializers in the group Serializer must have MediaTypeType and MediaTypeSubType set: %s", s.MediaType)
}
}
mediaTypes, streamMediaTypes := negotiation.MediaTypesForSerializer(a.group.Serializer)
allMediaTypes := append(mediaTypes, streamMediaTypes...)
ws.Produces(allMediaTypes...)
kubeVerbs := map[string]struct{}{}
reqScope := handlers.RequestScope{
Serializer: a.group.Serializer,
ParameterCodec: a.group.ParameterCodec,
Creater: a.group.Creater,
Convertor: a.group.Convertor,
Defaulter: a.group.Defaulter,
Typer: a.group.Typer,
UnsafeConvertor: a.group.UnsafeConvertor,
Authorizer: a.group.Authorizer,
EquivalentResourceMapper: a.group.EquivalentResourceRegistry,
// TODO: Check for the interface on storage
TableConvertor: tableProvider,
// TODO: This seems wrong for cross-group subresources. It makes an assumption that a subresource and its parent are in the same group version. Revisit this.
Resource: a.group.GroupVersion.WithResource(resource),
Subresource: subresource,
Kind: fqKindToRegister,
HubGroupVersion: schema.GroupVersion{Group: fqKindToRegister.Group, Version: runtime.APIVersionInternal},
MetaGroupVersion: metav1.SchemeGroupVersion,
MaxRequestBodyBytes: a.group.MaxRequestBodyBytes,
}
if a.group.MetaGroupVersion != nil {
reqScope.MetaGroupVersion = *a.group.MetaGroupVersion
}
if a.group.OpenAPIModels != nil && utilfeature.DefaultFeatureGate.Enabled(features.ServerSideApply) {
fm, err := fieldmanager.NewFieldManager(
a.group.OpenAPIModels,
a.group.UnsafeConvertor,
a.group.Defaulter,
fqKindToRegister.GroupVersion(),
reqScope.HubGroupVersion,
)
if err != nil {
return nil, fmt.Errorf("failed to create field manager: %v", err)
}
fm = fieldmanager.NewSkipNonAppliedManager(fm, a.group.Creater, fqKindToRegister)
reqScope.FieldManager = fm
}
for _, action := range actions {
producedObject := storageMeta.ProducesObject(action.Verb)
if producedObject == nil {
producedObject = defaultVersionedObject
}
reqScope.Namer = action.Namer
requestScope := "cluster"
var namespaced string
var operationSuffix string
if apiResource.Namespaced {
requestScope = "namespace"
namespaced = "Namespaced"
}
if strings.HasSuffix(action.Path, "/{path:*}") {
requestScope = "resource"
operationSuffix = operationSuffix + "WithPath"
}
if action.AllNamespaces {
requestScope = "cluster"
operationSuffix = operationSuffix + "ForAllNamespaces"
namespaced = ""
}
if kubeVerb, found := toDiscoveryKubeVerb[action.Verb]; found {
if len(kubeVerb) != 0 {
kubeVerbs[kubeVerb] = struct{}{}
}
} else {
return nil, fmt.Errorf("unknown action verb for discovery: %s", action.Verb)
}
routes := []*restful.RouteBuilder{}
// If there is a subresource, kind should be the parent's kind.
if isSubresource {
parentStorage, ok := a.group.Storage[resource]
if !ok {
return nil, fmt.Errorf("missing parent storage: %q", resource)
}
fqParentKind, err := GetResourceKind(a.group.GroupVersion, parentStorage, a.group.Typer)
if err != nil {
return nil, err
}
kind = fqParentKind.Kind
}
verbOverrider, needOverride := storage.(StorageMetricsOverride)
switch action.Verb {
case "GET": // Get a resource.
var handler restful.RouteFunction
if isGetterWithOptions {
handler = restfulGetResourceWithOptions(getterWithOptions, reqScope, isSubresource)
} else {
handler = restfulGetResource(getter, exporter, reqScope)
}
if needOverride {
// need change the reported verb
handler = metrics.InstrumentRouteFunc(verbOverrider.OverrideMetricsVerb(action.Verb), group, version, resource, subresource, requestScope, metrics.APIServerComponent, handler)
} else {
handler = metrics.InstrumentRouteFunc(action.Verb, group, version, resource, subresource, requestScope, metrics.APIServerComponent, handler)
}
doc := "read the specified " + kind
if isSubresource {
doc = "read " + subresource + " of the specified " + kind
}
route := ws.GET(action.Path).To(handler).
Doc(doc).
Param(ws.QueryParameter("pretty", "If 'true', then the output is pretty printed.")).
Operation("read"+namespaced+kind+strings.Title(subresource)+operationSuffix).
Produces(append(storageMeta.ProducesMIMETypes(action.Verb), mediaTypes...)...).
Returns(http.StatusOK, "OK", producedObject).
Writes(producedObject)
if isGetterWithOptions {
if err := AddObjectParams(ws, route, versionedGetOptions); err != nil {
return nil, err
}
}
if isExporter {
if err := AddObjectParams(ws, route, versionedExportOptions); err != nil {
return nil, err
}
}
addParams(route, action.Params)
routes = append(routes, route)
case "LIST": // List all resources of a kind.
doc := "list objects of kind " + kind
if isSubresource {
doc = "list " + subresource + " of objects of kind " + kind
}
handler := metrics.InstrumentRouteFunc(action.Verb, group, version, resource, subresource, requestScope, metrics.APIServerComponent, restfulListResource(lister, watcher, reqScope, false, a.minRequestTimeout))
route := ws.GET(action.Path).To(handler).
Doc(doc).
Param(ws.QueryParameter("pretty", "If 'true', then the output is pretty printed.")).
Operation("list"+namespaced+kind+strings.Title(subresource)+operationSuffix).
Produces(append(storageMeta.ProducesMIMETypes(action.Verb), allMediaTypes...)...).
Returns(http.StatusOK, "OK", versionedList).
Writes(versionedList)
if err := AddObjectParams(ws, route, versionedListOptions); err != nil {
return nil, err
}
switch {
case isLister && isWatcher:
doc := "list or watch objects of kind " + kind
if isSubresource {
doc = "list or watch " + subresource + " of objects of kind " + kind
}
route.Doc(doc)
case isWatcher:
doc := "watch objects of kind " + kind
if isSubresource {
doc = "watch " + subresource + "of objects of kind " + kind
}
route.Doc(doc)
}
addParams(route, action.Params)
routes = append(routes, route)
case "PUT": // Update a resource.
doc := "replace the specified " + kind
if isSubresource {
doc = "replace " + subresource + " of the specified " + kind
}
handler := metrics.InstrumentRouteFunc(action.Verb, group, version, resource, subresource, requestScope, metrics.APIServerComponent, restfulUpdateResource(updater, reqScope, admit))
route := ws.PUT(action.Path).To(handler).
Doc(doc).
Param(ws.QueryParameter("pretty", "If 'true', then the output is pretty printed.")).
Operation("replace"+namespaced+kind+strings.Title(subresource)+operationSuffix).
Produces(append(storageMeta.ProducesMIMETypes(action.Verb), mediaTypes...)...).
Returns(http.StatusOK, "OK", producedObject).
// TODO: in some cases, the API may return a v1.Status instead of the versioned object
// but currently go-restful can't handle multiple different objects being returned.
Returns(http.StatusCreated, "Created", producedObject).
Reads(defaultVersionedObject).
Writes(producedObject)
if err := AddObjectParams(ws, route, versionedUpdateOptions); err != nil {
return nil, err
}
addParams(route, action.Params)
routes = append(routes, route)
case "PATCH": // Partially update a resource
doc := "partially update the specified " + kind
if isSubresource {
doc = "partially update " + subresource + " of the specified " + kind
}
supportedTypes := []string{
string(types.JSONPatchType),
string(types.MergePatchType),
string(types.StrategicMergePatchType),
}
if utilfeature.DefaultFeatureGate.Enabled(features.ServerSideApply) {
supportedTypes = append(supportedTypes, string(types.ApplyPatchType))
}
handler := metrics.InstrumentRouteFunc(action.Verb, group, version, resource, subresource, requestScope, metrics.APIServerComponent, restfulPatchResource(patcher, reqScope, admit, supportedTypes))
route := ws.PATCH(action.Path).To(handler).
Doc(doc).
Param(ws.QueryParameter("pretty", "If 'true', then the output is pretty printed.")).
Consumes(supportedTypes...).
Operation("patch"+namespaced+kind+strings.Title(subresource)+operationSuffix).
Produces(append(storageMeta.ProducesMIMETypes(action.Verb), mediaTypes...)...).
Returns(http.StatusOK, "OK", producedObject).
Reads(metav1.Patch{}).
Writes(producedObject)
if err := AddObjectParams(ws, route, versionedPatchOptions); err != nil {
return nil, err
}
addParams(route, action.Params)
routes = append(routes, route)
case "POST": // Create a resource.
var handler restful.RouteFunction
if isNamedCreater {
handler = restfulCreateNamedResource(namedCreater, reqScope, admit)
} else {
handler = restfulCreateResource(creater, reqScope, admit)
}
handler = metrics.InstrumentRouteFunc(action.Verb, group, version, resource, subresource, requestScope, metrics.APIServerComponent, handler)
article := GetArticleForNoun(kind, " ")
doc := "create" + article + kind
if isSubresource {
doc = "create " + subresource + " of" + article + kind
}
route := ws.POST(action.Path).To(handler).
Doc(doc).
Param(ws.QueryParameter("pretty", "If 'true', then the output is pretty printed.")).
Operation("create"+namespaced+kind+strings.Title(subresource)+operationSuffix).
Produces(append(storageMeta.ProducesMIMETypes(action.Verb), mediaTypes...)...).
Returns(http.StatusOK, "OK", producedObject).
// TODO: in some cases, the API may return a v1.Status instead of the versioned object
// but currently go-restful can't handle multiple different objects being returned.
Returns(http.StatusCreated, "Created", producedObject).
Returns(http.StatusAccepted, "Accepted", producedObject).
Reads(defaultVersionedObject).
Writes(producedObject)
if err := AddObjectParams(ws, route, versionedCreateOptions); err != nil {
return nil, err
}
addParams(route, action.Params)
routes = append(routes, route)
case "DELETE": // Delete a resource.
article := GetArticleForNoun(kind, " ")
doc := "delete" + article + kind
if isSubresource {
doc = "delete " + subresource + " of" + article + kind
}
handler := metrics.InstrumentRouteFunc(action.Verb, group, version, resource, subresource, requestScope, metrics.APIServerComponent, restfulDeleteResource(gracefulDeleter, isGracefulDeleter, reqScope, admit))
route := ws.DELETE(action.Path).To(handler).
Doc(doc).
Param(ws.QueryParameter("pretty", "If 'true', then the output is pretty printed.")).
Operation("delete"+namespaced+kind+strings.Title(subresource)+operationSuffix).
Produces(append(storageMeta.ProducesMIMETypes(action.Verb), mediaTypes...)...).
Writes(versionedStatus).
Returns(http.StatusOK, "OK", versionedStatus).
Returns(http.StatusAccepted, "Accepted", versionedStatus)
if isGracefulDeleter {
route.Reads(versionedDeleterObject)
route.ParameterNamed("body").Required(false)
if err := AddObjectParams(ws, route, versionedDeleteOptions); err != nil {
return nil, err
}
}
addParams(route, action.Params)
routes = append(routes, route)
case "DELETECOLLECTION":
doc := "delete collection of " + kind
if isSubresource {
doc = "delete collection of " + subresource + " of a " + kind
}
handler := metrics.InstrumentRouteFunc(action.Verb, group, version, resource, subresource, requestScope, metrics.APIServerComponent, restfulDeleteCollection(collectionDeleter, isCollectionDeleter, reqScope, admit))
route := ws.DELETE(action.Path).To(handler).
Doc(doc).
Param(ws.QueryParameter("pretty", "If 'true', then the output is pretty printed.")).
Operation("deletecollection"+namespaced+kind+strings.Title(subresource)+operationSuffix).
Produces(append(storageMeta.ProducesMIMETypes(action.Verb), mediaTypes...)...).
Writes(versionedStatus).
Returns(http.StatusOK, "OK", versionedStatus)
if isCollectionDeleter {
route.Reads(versionedDeleterObject)
route.ParameterNamed("body").Required(false)
if err := AddObjectParams(ws, route, versionedDeleteOptions); err != nil {
return nil, err
}
}
if err := AddObjectParams(ws, route, versionedListOptions); err != nil {
return nil, err
}
addParams(route, action.Params)
routes = append(routes, route)
// deprecated in 1.11
case "WATCH": // Watch a resource.
doc := "watch changes to an object of kind " + kind
if isSubresource {
doc = "watch changes to " + subresource + " of an object of kind " + kind
}
doc += ". deprecated: use the 'watch' parameter with a list operation instead, filtered to a single item with the 'fieldSelector' parameter."
handler := metrics.InstrumentRouteFunc(action.Verb, group, version, resource, subresource, requestScope, metrics.APIServerComponent, restfulListResource(lister, watcher, reqScope, true, a.minRequestTimeout))
route := ws.GET(action.Path).To(handler).
Doc(doc).
Param(ws.QueryParameter("pretty", "If 'true', then the output is pretty printed.")).
Operation("watch"+namespaced+kind+strings.Title(subresource)+operationSuffix).
Produces(allMediaTypes...).
Returns(http.StatusOK, "OK", versionedWatchEvent).
Writes(versionedWatchEvent)
if err := AddObjectParams(ws, route, versionedListOptions); err != nil {
return nil, err
}
addParams(route, action.Params)
routes = append(routes, route)
// deprecated in 1.11
case "WATCHLIST": // Watch all resources of a kind.
doc := "watch individual changes to a list of " + kind
if isSubresource {
doc = "watch individual changes to a list of " + subresource + " of " + kind
}
doc += ". deprecated: use the 'watch' parameter with a list operation instead."
handler := metrics.InstrumentRouteFunc(action.Verb, group, version, resource, subresource, requestScope, metrics.APIServerComponent, restfulListResource(lister, watcher, reqScope, true, a.minRequestTimeout))
route := ws.GET(action.Path).To(handler).
Doc(doc).
Param(ws.QueryParameter("pretty", "If 'true', then the output is pretty printed.")).
Operation("watch"+namespaced+kind+strings.Title(subresource)+"List"+operationSuffix).
Produces(allMediaTypes...).
Returns(http.StatusOK, "OK", versionedWatchEvent).
Writes(versionedWatchEvent)
if err := AddObjectParams(ws, route, versionedListOptions); err != nil {
return nil, err
}
addParams(route, action.Params)
routes = append(routes, route)
case "CONNECT":
for _, method := range connecter.ConnectMethods() {
connectProducedObject := storageMeta.ProducesObject(method)
if connectProducedObject == nil {
connectProducedObject = "string"
}
doc := "connect " + method + " requests to " + kind
if isSubresource {
doc = "connect " + method + " requests to " + subresource + " of " + kind
}
handler := metrics.InstrumentRouteFunc(action.Verb, group, version, resource, subresource, requestScope, metrics.APIServerComponent, restfulConnectResource(connecter, reqScope, admit, path, isSubresource))
route := ws.Method(method).Path(action.Path).
To(handler).
Doc(doc).
Operation("connect" + strings.Title(strings.ToLower(method)) + namespaced + kind + strings.Title(subresource) + operationSuffix).
Produces("*/*").
Consumes("*/*").
Writes(connectProducedObject)
if versionedConnectOptions != nil {
if err := AddObjectParams(ws, route, versionedConnectOptions); err != nil {
return nil, err
}
}
addParams(route, action.Params)
routes = append(routes, route)
// transform ConnectMethods to kube verbs
if kubeVerb, found := toDiscoveryKubeVerb[method]; found {
if len(kubeVerb) != 0 {
kubeVerbs[kubeVerb] = struct{}{}
}
}
}
default:
return nil, fmt.Errorf("unrecognized action verb: %s", action.Verb)
}
for _, route := range routes {
route.Metadata(ROUTE_META_GVK, metav1.GroupVersionKind{
Group: reqScope.Kind.Group,
Version: reqScope.Kind.Version,
Kind: reqScope.Kind.Kind,
})
route.Metadata(ROUTE_META_ACTION, strings.ToLower(action.Verb))
ws.Route(route)
}
// Note: update GetAuthorizerAttributes() when adding a custom handler.
}
apiResource.Verbs = make([]string, 0, len(kubeVerbs))
for kubeVerb := range kubeVerbs {
apiResource.Verbs = append(apiResource.Verbs, kubeVerb)
}
sort.Strings(apiResource.Verbs)
if shortNamesProvider, ok := storage.(rest.ShortNamesProvider); ok {
apiResource.ShortNames = shortNamesProvider.ShortNames()
}
if categoriesProvider, ok := storage.(rest.CategoriesProvider); ok {
apiResource.Categories = categoriesProvider.Categories()
}
if gvkProvider, ok := storage.(rest.GroupVersionKindProvider); ok {
gvk := gvkProvider.GroupVersionKind(a.group.GroupVersion)
apiResource.Group = gvk.Group
apiResource.Version = gvk.Version
apiResource.Kind = gvk.Kind
}
// Record the existence of the GVR and the corresponding GVK
a.group.EquivalentResourceRegistry.RegisterKindFor(reqScope.Resource, reqScope.Subresource, fqKindToRegister)
return &apiResource, nil
}
// indirectArbitraryPointer returns *ptrToObject for an arbitrary pointer
func indirectArbitraryPointer(ptrToObject interface{}) interface{} {
return reflect.Indirect(reflect.ValueOf(ptrToObject)).Interface()
}
func appendIf(actions []action, a action, shouldAppend bool) []action {
if shouldAppend {
actions = append(actions, a)
}
return actions
}
func addParams(route *restful.RouteBuilder, params []*restful.Parameter) {
for _, param := range params {
route.Param(param)
}
}
// AddObjectParams converts a runtime.Object into a set of go-restful Param() definitions on the route.
// The object must be a pointer to a struct; only fields at the top level of the struct that are not
// themselves interfaces or structs are used; only fields with a json tag that is non empty (the standard
// Go JSON behavior for omitting a field) become query parameters. The name of the query parameter is
// the JSON field name. If a description struct tag is set on the field, that description is used on the
// query parameter. In essence, it converts a standard JSON top level object into a query param schema.
func AddObjectParams(ws *restful.WebService, route *restful.RouteBuilder, obj interface{}) error {
sv, err := conversion.EnforcePtr(obj)
if err != nil {
return err
}
st := sv.Type()
switch st.Kind() {
case reflect.Struct:
for i := 0; i < st.NumField(); i++ {
name := st.Field(i).Name
sf, ok := st.FieldByName(name)
if !ok {
continue
}
switch sf.Type.Kind() {
case reflect.Interface, reflect.Struct:
case reflect.Ptr:
// TODO: This is a hack to let metav1.Time through. This needs to be fixed in a more generic way eventually. bug #36191
if (sf.Type.Elem().Kind() == reflect.Interface || sf.Type.Elem().Kind() == reflect.Struct) && strings.TrimPrefix(sf.Type.String(), "*") != "metav1.Time" {
continue
}
fallthrough
default:
jsonTag := sf.Tag.Get("json")
if len(jsonTag) == 0 {
continue
}
jsonName := strings.SplitN(jsonTag, ",", 2)[0]
if len(jsonName) == 0 {
continue
}
var desc string
if docable, ok := obj.(documentable); ok {
desc = docable.SwaggerDoc()[jsonName]
}
route.Param(ws.QueryParameter(jsonName, desc).DataType(typeToJSON(sf.Type.String())))
}
}
}
return nil
}
// TODO: this is incomplete, expand as needed.
// Convert the name of a golang type to the name of a JSON type
func typeToJSON(typeName string) string {
switch typeName {
case "bool", "*bool":
return "boolean"
case "uint8", "*uint8", "int", "*int", "int32", "*int32", "int64", "*int64", "uint32", "*uint32", "uint64", "*uint64":
return "integer"
case "float64", "*float64", "float32", "*float32":
return "number"
case "metav1.Time", "*metav1.Time":
return "string"
case "byte", "*byte":
return "string"
case "v1.DeletionPropagation", "*v1.DeletionPropagation":
return "string"
// TODO: Fix these when go-restful supports a way to specify an array query param:
// https://github.com/emicklei/go-restful/issues/225
case "[]string", "[]*string":
return "string"
case "[]int32", "[]*int32":
return "integer"
default:
return typeName
}
}
// defaultStorageMetadata provides default answers to rest.StorageMetadata.
type defaultStorageMetadata struct{}
// defaultStorageMetadata implements rest.StorageMetadata
var _ rest.StorageMetadata = defaultStorageMetadata{}
func (defaultStorageMetadata) ProducesMIMETypes(verb string) []string {
return nil
}
func (defaultStorageMetadata) ProducesObject(verb string) interface{} {
return nil
}
// splitSubresource checks if the given storage path is the path of a subresource and returns
// the resource and subresource components.
func splitSubresource(path string) (string, string, error) {
var resource, subresource string
switch parts := strings.Split(path, "/"); len(parts) {
case 2:
resource, subresource = parts[0], parts[1]
case 1:
resource = parts[0]
default:
// TODO: support deeper paths
return "", "", fmt.Errorf("api_installer allows only one or two segment paths (resource or resource/subresource)")
}
return resource, subresource, nil
}
// GetArticleForNoun returns the article needed for the given noun.
func GetArticleForNoun(noun string, padding string) string {
if noun[len(noun)-2:] != "ss" && noun[len(noun)-1:] == "s" {
// Plurals don't have an article.
// Don't catch words like class
return fmt.Sprintf("%v", padding)
}
article := "a"
if isVowel(rune(noun[0])) {
article = "an"
}
return fmt.Sprintf("%s%s%s", padding, article, padding)
}
// isVowel returns true if the rune is a vowel (case insensitive).
func isVowel(c rune) bool {
vowels := []rune{'a', 'e', 'i', 'o', 'u'}
for _, value := range vowels {
if value == unicode.ToLower(c) {
return true
}
}
return false
}
func restfulListResource(r rest.Lister, rw rest.Watcher, scope handlers.RequestScope, forceWatch bool, minRequestTimeout time.Duration) restful.RouteFunction {
return func(req *restful.Request, res *restful.Response) {
handlers.ListResource(r, rw, &scope, forceWatch, minRequestTimeout)(res.ResponseWriter, req.Request)
}
}
func restfulCreateNamedResource(r rest.NamedCreater, scope handlers.RequestScope, admit admission.Interface) restful.RouteFunction {
return func(req *restful.Request, res *restful.Response) {
handlers.CreateNamedResource(r, &scope, admit)(res.ResponseWriter, req.Request)
}
}
func restfulCreateResource(r rest.Creater, scope handlers.RequestScope, admit admission.Interface) restful.RouteFunction {
return func(req *restful.Request, res *restful.Response) {
handlers.CreateResource(r, &scope, admit)(res.ResponseWriter, req.Request)
}
}
func restfulDeleteResource(r rest.GracefulDeleter, allowsOptions bool, scope handlers.RequestScope, admit admission.Interface) restful.RouteFunction {
return func(req *restful.Request, res *restful.Response) {
handlers.DeleteResource(r, allowsOptions, &scope, admit)(res.ResponseWriter, req.Request)
}
}
func restfulDeleteCollection(r rest.CollectionDeleter, checkBody bool, scope handlers.RequestScope, admit admission.Interface) restful.RouteFunction {
return func(req *restful.Request, res *restful.Response) {
handlers.DeleteCollection(r, checkBody, &scope, admit)(res.ResponseWriter, req.Request)
}
}
func restfulUpdateResource(r rest.Updater, scope handlers.RequestScope, admit admission.Interface) restful.RouteFunction {
return func(req *restful.Request, res *restful.Response) {
handlers.UpdateResource(r, &scope, admit)(res.ResponseWriter, req.Request)
}
}
func restfulPatchResource(r rest.Patcher, scope handlers.RequestScope, admit admission.Interface, supportedTypes []string) restful.RouteFunction {
return func(req *restful.Request, res *restful.Response) {
handlers.PatchResource(r, &scope, admit, supportedTypes)(res.ResponseWriter, req.Request)
}
}
func restfulGetResource(r rest.Getter, e rest.Exporter, scope handlers.RequestScope) restful.RouteFunction {
return func(req *restful.Request, res *restful.Response) {
handlers.GetResource(r, e, &scope)(res.ResponseWriter, req.Request)
}
}
func restfulGetResourceWithOptions(r rest.GetterWithOptions, scope handlers.RequestScope, isSubresource bool) restful.RouteFunction {
return func(req *restful.Request, res *restful.Response) {
handlers.GetResourceWithOptions(r, &scope, isSubresource)(res.ResponseWriter, req.Request)
}
}
func restfulConnectResource(connecter rest.Connecter, scope handlers.RequestScope, admit admission.Interface, restPath string, isSubresource bool) restful.RouteFunction {
return func(req *restful.Request, res *restful.Response) {
handlers.ConnectResource(connecter, &scope, admit, restPath, isSubresource)(res.ResponseWriter, req.Request)
}
}
| {
"content_hash": "037446f55c4f7f69dbe86270ff45e49b",
"timestamp": "",
"source": "github",
"line_count": 1126,
"max_line_length": 217,
"avg_line_length": 39.227353463587924,
"alnum_prop": 0.7228661987774507,
"repo_name": "jennybuckley/kubernetes",
"id": "6996f79082b5bf72fbf98d7785a34444f2273328",
"size": "44739",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "staging/src/k8s.io/apiserver/pkg/endpoints/installer.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "2840"
},
{
"name": "Dockerfile",
"bytes": "52103"
},
{
"name": "Go",
"bytes": "50576685"
},
{
"name": "HTML",
"bytes": "38"
},
{
"name": "Lua",
"bytes": "17200"
},
{
"name": "Makefile",
"bytes": "67444"
},
{
"name": "PowerShell",
"bytes": "101623"
},
{
"name": "Python",
"bytes": "3394248"
},
{
"name": "Ruby",
"bytes": "430"
},
{
"name": "Shell",
"bytes": "1579516"
},
{
"name": "sed",
"bytes": "12268"
}
],
"symlink_target": ""
} |
var JSC = require("jscheck");
var assert = require("chai").assert;
var _ = require("lodash");
var getTestUtils = require("../TestUtils.js");
module.exports = function(config) {
var Immutable = config.implementation;
var TestUtils = getTestUtils(Immutable);
var check = TestUtils.check;
function getPathComponent() {
// It's very convenient to use lodash.set, but it has funky behaviour
// with numeric keys.
var s = JSC.string()().replace(/[^\w]/g, '_');
return /^\d+$/.test(s) ? s + 'a' : s;
}
describe("#set", function() {
xit("sets a property by name", function () {
check(100, [TestUtils.ComplexObjectSpecifier()], function(ob) {
var immutable = Immutable(ob);
var mutable = _.assign({}, ob);
var prop = getPathComponent();
var value = JSC.any()();
TestUtils.assertJsonEqual(
Immutable.set(immutable, prop, value),
_.set(mutable, prop, value)
);
});
});
xit("sets a property by name with deep compare if provided the deep flag", function () {
check(100, [TestUtils.ComplexObjectSpecifier()], function(ob) {
var immutable = Immutable(ob);
var mutable = _.assign({}, ob);
var prop = getPathComponent();
var value;
do {
value = JSC.any()();
} while (TestUtils.isDeepEqual(value, immutable[prop]));
var resultImmutable = Immutable.set(immutable, prop, value, {deep: true});
var resultMutable = _.set(mutable, prop, value);
TestUtils.assertJsonEqual(
resultImmutable,
resultMutable
);
assert.notEqual(
immutable,
resultImmutable
);
assert.equal(
Immutable.set(resultImmutable, prop, value, {deep: true}),
resultImmutable
);
});
});
it("static method continues to work after overriding the instance method", function() {
var I = Immutable.static;
var immutable;
immutable = I({set: 'string'});
TestUtils.assertJsonEqual(immutable, {set: 'string'});
immutable = I({});
immutable = I.set(immutable, 'set', 'string');
TestUtils.assertJsonEqual(immutable, {set: 'string'});
immutable = I.set(immutable, 'new_key', 'new_data');
TestUtils.assertJsonEqual(immutable, {set: 'string', new_key: 'new_data'});
});
it("supports non-static syntax", function() {
var obj = Immutable({});
obj = obj.set('test', 'test');
TestUtils.assertJsonEqual(obj, {test: 'test'});
});
});
describe("#setIn", function() {
xit("sets a property by path", function () {
check(100, [TestUtils.ComplexObjectSpecifier()], function(ob) {
var immutable = Immutable(ob);
var mutable = _.assign({}, ob);
TestUtils.assertJsonEqual(immutable, mutable);
var path = [], depth = JSC.integer(1, 5)();
for (var j = 0; j < depth; j++) {
path.push(getPathComponent());
}
var value;
do {
value = JSC.any()();
} while (TestUtils.isDeepEqual(value, _.get(immutable, path)));
TestUtils.assertJsonEqual(
Immutable.setIn(immutable, path, value),
_.set(mutable, path, value)
);
});
});
it("handles setting a new object on existing leaf array correctly", function () {
var ob = {foo: []};
var path = ['foo', 0, 'bar'];
var val = 'val';
var immutable = Immutable(ob);
var final = Immutable.setIn(immutable, path, val);
assert.deepEqual(final, {foo: [{bar: 'val'}]});
});
xit("sets a property by path with deep compare if provided the deep flag", function () {
check(100, [TestUtils.ComplexObjectSpecifier()], function(ob) {
var immutable = Immutable(ob);
var mutable = _.assign({}, ob);
var value = JSC.any()();
TestUtils.assertJsonEqual(immutable, mutable);
var path = [], depth = JSC.integer(1, 5)();
for (var j = 0; j < depth; j++) {
path.push(getPathComponent());
}
var resultImmutable = Immutable.setIn(immutable, path, value, {deep: true});
var resultMutable = _.set(mutable, path, value);
TestUtils.assertJsonEqual(
resultImmutable,
resultMutable
);
assert.notEqual(
immutable,
resultImmutable
);
assert.equal(
Immutable.setIn(resultImmutable, path, value, {deep: true}),
resultImmutable
);
});
});
it("static method continues to work after overriding the instance method", function() {
var I = Immutable.static;
var immutable;
immutable = I({setIn: 'string'});
TestUtils.assertJsonEqual(immutable, {setIn: 'string'});
immutable = I({});
immutable = I.setIn(immutable, ['setIn'], 'string');
TestUtils.assertJsonEqual(immutable, {setIn: 'string'});
immutable = I.setIn(immutable, ['new_key'], 'new_data');
TestUtils.assertJsonEqual(immutable, {setIn: 'string', new_key: 'new_data'});
});
it("supports non-static syntax", function() {
var obj = Immutable({});
obj = obj.setIn(['test'], 'test');
TestUtils.assertJsonEqual(obj, {test: 'test'});
});
});
};
| {
"content_hash": "72ed235f57933cc5ae11115113533b30",
"timestamp": "",
"source": "github",
"line_count": 173,
"max_line_length": 92,
"avg_line_length": 31.09826589595376,
"alnum_prop": 0.5691449814126394,
"repo_name": "rtfeldman/seamless-immutable",
"id": "88be1e23838ca4af08d77027cd80276d5f988afe",
"size": "5380",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "test/ImmutableObject/test-set.js",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "JavaScript",
"bytes": "156973"
}
],
"symlink_target": ""
} |
<?php
namespace spec\Humdir\Core\Usecase\Customer;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
class DeleteSpec extends ObjectBehavior
{
/**
* @param Humdir\Core\Data\Customer $customer
* @param Humdir\Core\Usecase\Customer\Delete\Repository $customer_delete
*/
function let($customer, $customer_delete)
{
$data = array(
'customer' => $customer
);
$repositories = array(
'customer_delete' => $customer_delete
);
$this->beConstructedWith($data, $repositories);
}
function it_is_initializable()
{
$this->shouldHaveType('Humdir\Core\Usecase\Customer\Delete');
}
function it_fetches_the_interactor()
{
$this->fetch()->shouldHaveType('Humdir\Core\Usecase\Customer\Delete\Interactor');
}
}
| {
"content_hash": "4c199fb0f72c916b32306eb358b00418",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 89,
"avg_line_length": 23.13888888888889,
"alnum_prop": 0.6278511404561825,
"repo_name": "Moult/humdir",
"id": "aba29df1869ea5beb87bd24c82e950a191b9d0c8",
"size": "833",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "spec/Humdir/Core/Usecase/Customer/DeleteSpec.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "43968"
}
],
"symlink_target": ""
} |
import anyTest, { TestInterface } from 'ava';
import { StyleCollection, lyl } from './parse';
import { mergeThemes } from './style-utils';
const test = anyTest as TestInterface<Context>;
class Context { }
test.before(t => {
t.context = new Context();
});
test('merge theme StyleCollection with StyleTemplate', t => {
const themeA = {
a: new StyleCollection(),
b: new StyleCollection(lyl `{
color: red
}`)
};
const themeB = {
a: lyl `{
color: red
}`,
b: lyl `{
background-color: #000000
}`
};
const themeC = {
b: new StyleCollection(lyl `{
color: #000
}`),
};
const themeD = {
b: lyl `{
background: #fff
}`,
};
mergeThemes(themeA, themeB);
t.is(
themeA.a.css('.y'),
'.y{color:red;}'
);
t.is(
themeA.b.css('.y'),
'.y{color:red;}.y{background-color:#000000;}'
);
t.is(
mergeThemes({}, themeA, themeB, themeC, themeD).b.css('.y'),
'.y{color:#000;}.y{background:#fff;}'
);
t.true(mergeThemes({}, themeA, themeB, themeC, themeD).b instanceof StyleCollection);
t.true(mergeThemes({}, themeA, themeB, themeC, themeD).a instanceof StyleCollection);
});
| {
"content_hash": "77bc82e881a0f5cc92533eb5ee330de2",
"timestamp": "",
"source": "github",
"line_count": 57,
"max_line_length": 87,
"avg_line_length": 20.80701754385965,
"alnum_prop": 0.5809443507588533,
"repo_name": "Aviella/Alyle-UI",
"id": "ebc039f62a0a5b372fda3a0d60f51968b8b2a0f9",
"size": "1186",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/lib/src/parse.test.ts",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
module DataMapper
# WebSync extensions to DataMapper properties.
class Property
# A stub class representing a postgres BYTEA. This is only used so
# DataMapper will create it in the schema.
class BetterBlob < Object
# A stub load method.
#
# @param value [String] the value to load
# @return [nil]
def load(value)
nil
end
# A stub dump method.
#
# @param value [String] the value to dump
# @return [nil]
def dump(value)
nil
end
end
end # class Property
module Migrations
# WebSync extensions to the DataMapper postgres adapter.
module PostgresAdapter
# WebSync extensions to the DataMapper postgres adapter class methods.
# Adds in BetterBlob.
module ClassMethods
# Types for PostgreSQL databases.
#
# @return [Hash] types for PostgreSQL databases.
#
# @api private
def type_map
precision = Property::Numeric.precision
scale = Property::Decimal.scale
super.merge(
Property::BetterBlob => { :primitive => 'BYTEA' },
Property::Binary => { :primitive => 'BYTEA' },
BigDecimal => { :primitive => 'NUMERIC', :precision => precision, :scale => scale },
Float => { :primitive => 'DOUBLE PRECISION' }
).freeze
end
end
end
end
end # module DataMapper
| {
"content_hash": "8bc627ab95cb8a9343c9b1694e514a7e",
"timestamp": "",
"source": "github",
"line_count": 49,
"max_line_length": 111,
"avg_line_length": 31.979591836734695,
"alnum_prop": 0.5398851308232291,
"repo_name": "hhqqnu/WebSync",
"id": "3728cd7d2f5e3148c0254aabf98db5c609b7cc19",
"size": "1602",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "lib/datamapper_extensions.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "52947"
},
{
"name": "HTML",
"bytes": "66295"
},
{
"name": "JavaScript",
"bytes": "1454144"
},
{
"name": "Nginx",
"bytes": "862"
},
{
"name": "Ruby",
"bytes": "119537"
},
{
"name": "Shell",
"bytes": "699"
}
],
"symlink_target": ""
} |
const int FREEDESKTOP_NOTIFICATION_ICON_SIZE = 128;
Notificator::Notificator(const QString &programName, QSystemTrayIcon *trayicon, QWidget *parent):
QObject(parent),
parent(parent),
programName(programName),
mode(None),
trayIcon(trayicon)
#ifdef USE_DBUS
,interface(0)
#endif
{
if(trayicon && trayicon->supportsMessages())
{
mode = QSystemTray;
}
#ifdef USE_DBUS
interface = new QDBusInterface("org.freedesktop.Notifications",
"/org/freedesktop/Notifications", "org.freedesktop.Notifications");
if(interface->isValid())
{
mode = Freedesktop;
}
#endif
#ifdef Q_OS_MAC
// Check if Growl is installed (based on Qt's tray icon implementation)
CFURLRef cfurl;
OSStatus status = LSGetApplicationForInfo(kLSUnknownType, kLSUnknownCreator, CFSTR("growlTicket"), kLSRolesAll, 0, &cfurl);
if (status != kLSApplicationNotFoundErr) {
CFBundleRef bundle = CFBundleCreate(0, cfurl);
if (CFStringCompare(CFBundleGetIdentifier(bundle), CFSTR("com.Growl.GrowlHelperApp"), kCFCompareCaseInsensitive | kCFCompareBackwards) == kCFCompareEqualTo) {
if (CFStringHasSuffix(CFURLGetString(cfurl), CFSTR("/Growl.app/")))
mode = Growl13;
else
mode = Growl12;
}
CFRelease(cfurl);
CFRelease(bundle);
}
#endif
}
Notificator::~Notificator()
{
#ifdef USE_DBUS
delete interface;
#endif
}
#ifdef USE_DBUS
// Loosely based on http://www.qtcentre.org/archive/index.php/t-25879.html
class FreedesktopImage
{
public:
FreedesktopImage() {}
FreedesktopImage(const QImage &img);
static int metaType();
// Image to variant that can be marshalled over DBus
static QVariant toVariant(const QImage &img);
private:
int width, height, stride;
bool hasAlpha;
int channels;
int bitsPerSample;
QByteArray image;
friend QDBusArgument &operator<<(QDBusArgument &a, const FreedesktopImage &i);
friend const QDBusArgument &operator>>(const QDBusArgument &a, FreedesktopImage &i);
};
Q_DECLARE_METATYPE(FreedesktopImage);
// Image configuration settings
const int CHANNELS = 4;
const int BYTES_PER_PIXEL = 4;
const int BITS_PER_SAMPLE = 8;
FreedesktopImage::FreedesktopImage(const QImage &img):
width(img.width()),
height(img.height()),
stride(img.width() * BYTES_PER_PIXEL),
hasAlpha(true),
channels(CHANNELS),
bitsPerSample(BITS_PER_SAMPLE)
{
// Convert 00xAARRGGBB to RGBA bytewise (endian-independent) format
QImage tmp = img.convertToFormat(QImage::Format_ARGB32);
const uint32_t *data = reinterpret_cast<const uint32_t*>(tmp.bits());
unsigned int num_pixels = width * height;
image.resize(num_pixels * BYTES_PER_PIXEL);
for(unsigned int ptr = 0; ptr < num_pixels; ++ptr)
{
image[ptr*BYTES_PER_PIXEL+0] = data[ptr] >> 16; // R
image[ptr*BYTES_PER_PIXEL+1] = data[ptr] >> 8; // G
image[ptr*BYTES_PER_PIXEL+2] = data[ptr]; // B
image[ptr*BYTES_PER_PIXEL+3] = data[ptr] >> 24; // A
}
}
QDBusArgument &operator<<(QDBusArgument &a, const FreedesktopImage &i)
{
a.beginStructure();
a << i.width << i.height << i.stride << i.hasAlpha << i.bitsPerSample << i.channels << i.image;
a.endStructure();
return a;
}
const QDBusArgument &operator>>(const QDBusArgument &a, FreedesktopImage &i)
{
a.beginStructure();
a >> i.width >> i.height >> i.stride >> i.hasAlpha >> i.bitsPerSample >> i.channels >> i.image;
a.endStructure();
return a;
}
int FreedesktopImage::metaType()
{
return qDBusRegisterMetaType<FreedesktopImage>();
}
QVariant FreedesktopImage::toVariant(const QImage &img)
{
FreedesktopImage fimg(img);
return QVariant(FreedesktopImage::metaType(), &fimg);
}
void Notificator::notifyDBus(Class cls, const QString &title, const QString &text, const QIcon &icon, int millisTimeout)
{
Q_UNUSED(cls);
// Arguments for DBus call:
QList<QVariant> args;
// Program Name:
args.append(programName);
// Unique ID of this notification type:
args.append(0U);
// Application Icon, empty string
args.append(QString());
// Summary
args.append(title);
// Body
args.append(text);
// Actions (none, actions are deprecated)
QStringList actions;
args.append(actions);
// Hints
QVariantMap hints;
// If no icon specified, set icon based on class
QIcon tmpicon;
if(icon.isNull())
{
QStyle::StandardPixmap sicon = QStyle::SP_MessageBoxQuestion;
switch(cls)
{
case Information: sicon = QStyle::SP_MessageBoxInformation; break;
case Warning: sicon = QStyle::SP_MessageBoxWarning; break;
case Critical: sicon = QStyle::SP_MessageBoxCritical; break;
default: break;
}
tmpicon = QApplication::style()->standardIcon(sicon);
}
else
{
tmpicon = icon;
}
hints["icon_data"] = FreedesktopImage::toVariant(tmpicon.pixmap(FREEDESKTOP_NOTIFICATION_ICON_SIZE).toImage());
args.append(hints);
// Timeout (in msec)
args.append(millisTimeout);
// "Fire and forget"
interface->callWithArgumentList(QDBus::NoBlock, "Notify", args);
}
#endif
void Notificator::notifySystray(Class cls, const QString &title, const QString &text, const QIcon &icon, int millisTimeout)
{
Q_UNUSED(icon);
QSystemTrayIcon::MessageIcon sicon = QSystemTrayIcon::NoIcon;
switch(cls) // Set icon based on class
{
case Information: sicon = QSystemTrayIcon::Information; break;
case Warning: sicon = QSystemTrayIcon::Warning; break;
case Critical: sicon = QSystemTrayIcon::Critical; break;
}
trayIcon->showMessage(title, text, sicon, millisTimeout);
}
// Based on Qt's tray icon implementation
#ifdef Q_OS_MAC
void Notificator::notifyGrowl(Class cls, const QString &title, const QString &text, const QIcon &icon)
{
const QString script(
"tell application \"%5\"\n"
" set the allNotificationsList to {\"Notification\"}\n" // -- Make a list of all the notification types (all)
" set the enabledNotificationsList to {\"Notification\"}\n" // -- Make a list of the notifications (enabled)
" register as application \"%1\" all notifications allNotificationsList default notifications enabledNotificationsList\n" // -- Register our script with Growl
" notify with name \"Notification\" title \"%2\" description \"%3\" application name \"%1\"%4\n" // -- Send a Notification
"end tell"
);
QString notificationApp(QApplication::applicationName());
if (notificationApp.isEmpty())
notificationApp = "Application";
QPixmap notificationIconPixmap;
if (icon.isNull()) { // If no icon specified, set icon based on class
QStyle::StandardPixmap sicon = QStyle::SP_MessageBoxQuestion;
switch (cls)
{
case Information: sicon = QStyle::SP_MessageBoxInformation; break;
case Warning: sicon = QStyle::SP_MessageBoxWarning; break;
case Critical: sicon = QStyle::SP_MessageBoxCritical; break;
}
notificationIconPixmap = QApplication::style()->standardPixmap(sicon);
}
else {
QSize size = icon.actualSize(QSize(48, 48));
notificationIconPixmap = icon.pixmap(size);
}
QString notificationIcon;
QTemporaryFile notificationIconFile;
if (!notificationIconPixmap.isNull() && notificationIconFile.open()) {
QImageWriter writer(¬ificationIconFile, "PNG");
if (writer.write(notificationIconPixmap.toImage()))
notificationIcon = QString(" image from location \"file://%1\"").arg(notificationIconFile.fileName());
}
QString quotedTitle(title), quotedText(text);
quotedTitle.replace("\\", "\\\\").replace("\"", "\\");
quotedText.replace("\\", "\\\\").replace("\"", "\\");
QString growlApp(this->mode == Notificator::Growl13 ? "Growl" : "GrowlHelperApp");
}
#endif
void Notificator::notify(Class cls, const QString &title, const QString &text, const QIcon &icon, int millisTimeout)
{
switch(mode)
{
#ifdef USE_DBUS
case Freedesktop:
notifyDBus(cls, title, text, icon, millisTimeout);
break;
#endif
case QSystemTray:
notifySystray(cls, title, text, icon, millisTimeout);
break;
#ifdef Q_OS_MAC
case Growl12:
case Growl13:
notifyGrowl(cls, title, text, icon);
break;
#endif
default:
if(cls == Critical)
{
// Fall back to old fashioned pop-up dialog if critical and no other notification available
QMessageBox::critical(parent, title, text, QMessageBox::Ok, QMessageBox::Ok);
}
break;
}
}
| {
"content_hash": "ac559b436d212d8dc29b21ab78df7b60",
"timestamp": "",
"source": "github",
"line_count": 277,
"max_line_length": 167,
"avg_line_length": 31.63898916967509,
"alnum_prop": 0.6617982656321314,
"repo_name": "MystiCoin/MystiCoin",
"id": "b9d2bd0182f4456dc32138291256d5ce8c381218",
"size": "9244",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "src/qt/notificator.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "51312"
},
{
"name": "C",
"bytes": "706676"
},
{
"name": "C++",
"bytes": "2483185"
},
{
"name": "CSS",
"bytes": "1127"
},
{
"name": "HTML",
"bytes": "50615"
},
{
"name": "Makefile",
"bytes": "11970"
},
{
"name": "NSIS",
"bytes": "5914"
},
{
"name": "Objective-C",
"bytes": "858"
},
{
"name": "Objective-C++",
"bytes": "3536"
},
{
"name": "Python",
"bytes": "2819"
},
{
"name": "QMake",
"bytes": "15451"
},
{
"name": "Shell",
"bytes": "8201"
}
],
"symlink_target": ""
} |
<TS language="zh_HK" version="2.1">
<context>
<name>AddressBookPage</name>
</context>
<context>
<name>AddressTableModel</name>
</context>
<context>
<name>AskPassphraseDialog</name>
</context>
<context>
<name>MonetaGUI</name>
</context>
<context>
<name>ClientModel</name>
</context>
<context>
<name>CoinControlDialog</name>
</context>
<context>
<name>EditAddressDialog</name>
</context>
<context>
<name>FreespaceChecker</name>
</context>
<context>
<name>HelpMessageDialog</name>
</context>
<context>
<name>Intro</name>
</context>
<context>
<name>OpenURIDialog</name>
</context>
<context>
<name>OptionsDialog</name>
</context>
<context>
<name>OverviewPage</name>
</context>
<context>
<name>PaymentServer</name>
</context>
<context>
<name>PeerTableModel</name>
</context>
<context>
<name>QObject</name>
</context>
<context>
<name>QRImageWidget</name>
</context>
<context>
<name>RPCConsole</name>
</context>
<context>
<name>ReceiveCoinsDialog</name>
</context>
<context>
<name>ReceiveRequestDialog</name>
</context>
<context>
<name>RecentRequestsTableModel</name>
</context>
<context>
<name>SendCoinsDialog</name>
</context>
<context>
<name>SendCoinsEntry</name>
</context>
<context>
<name>ShutdownWindow</name>
</context>
<context>
<name>SignVerifyMessageDialog</name>
</context>
<context>
<name>SplashScreen</name>
</context>
<context>
<name>TrafficGraphWidget</name>
</context>
<context>
<name>TransactionDesc</name>
</context>
<context>
<name>TransactionDescDialog</name>
</context>
<context>
<name>TransactionTableModel</name>
</context>
<context>
<name>TransactionView</name>
</context>
<context>
<name>UnitDisplayStatusBarControl</name>
</context>
<context>
<name>WalletFrame</name>
</context>
<context>
<name>WalletModel</name>
</context>
<context>
<name>WalletView</name>
</context>
<context>
<name>moneta-core</name>
</context>
</TS> | {
"content_hash": "85696aca7fb242289b263c4a29243253",
"timestamp": "",
"source": "github",
"line_count": 110,
"max_line_length": 44,
"avg_line_length": 19.336363636363636,
"alnum_prop": 0.6365773389750823,
"repo_name": "habibmasuro/moneta-0.10.0",
"id": "2d6141b4bbc210ac08b7f970e743b217df4b9409",
"size": "2127",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "src/qt/locale/moneta_zh_HK.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "7639"
},
{
"name": "Batchfile",
"bytes": "570"
},
{
"name": "C",
"bytes": "344750"
},
{
"name": "C++",
"bytes": "3685223"
},
{
"name": "CSS",
"bytes": "1127"
},
{
"name": "Groff",
"bytes": "17983"
},
{
"name": "HTML",
"bytes": "50621"
},
{
"name": "Java",
"bytes": "2099"
},
{
"name": "Makefile",
"bytes": "61678"
},
{
"name": "Objective-C",
"bytes": "2020"
},
{
"name": "Objective-C++",
"bytes": "7244"
},
{
"name": "Protocol Buffer",
"bytes": "2304"
},
{
"name": "Python",
"bytes": "211715"
},
{
"name": "QMake",
"bytes": "2018"
},
{
"name": "Shell",
"bytes": "42211"
}
],
"symlink_target": ""
} |
<?xml version='1.0' encoding='UTF-8'?>
<faces-config xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd"
version="2.2">
<!-- ========== Application Wide Features ================================ -->
<application>
<resource-bundle>
<base-name>
javaeetutorial.dukesbookstore.web.messages.Messages
</base-name>
<var>bundle</var>
</resource-bundle>
<locale-config>
<default-locale>en</default-locale>
<supported-locale>de</supported-locale>
<supported-locale>es</supported-locale>
<supported-locale>fr</supported-locale>
</locale-config>
</application>
<!-- ========== Managed Beans ============================================ -->
<!-- =================== Initialize Image Map Hotspot Data ============== -->
<managed-bean eager="true">
<description>
Causes the default VariableResolver implementation to instantiate the
managed bean Book201 of the class components.model.ImageArea in application
scope if the bean does not already exist in any scope, and initialize the
shape, alt, and coords properties with the values specified by the
managed-property elements.
</description>
<managed-bean-name>Book201</managed-bean-name>
<managed-bean-class>javaeetutorial.dukesbookstore.model.ImageArea</managed-bean-class>
<managed-bean-scope>application</managed-bean-scope>
<managed-property>
<description>
Initializes the shape property of the managed bean Book201 with the value
rect.
</description>
<property-name>shape</property-name>
<value>rect</value>
</managed-property>
<managed-property>
<description>
Initializes the alt property of the managed bean Book201 with the value
Duke.
</description>
<property-name>alt</property-name>
<value>Duke</value>
</managed-property>
<managed-property>
<description>
Initializes the coords property of the managed bean Book201 with the value
specified by the value element.
</description>
<property-name>coords</property-name>
<value>67,23,212,268</value>
</managed-property>
</managed-bean>
<managed-bean eager="true">
<description>
Causes the default VariableResolver implementation to instantiate the
managed bean Book202 of the class components.model.ImageArea in application
scope if the bean does not already exist in any scope, and initialize the
shape, alt, and coords properties with the values specified by the
managed-property elements.
</description>
<managed-bean-name>Book202</managed-bean-name>
<managed-bean-class>javaeetutorial.dukesbookstore.model.ImageArea</managed-bean-class>
<managed-bean-scope>application</managed-bean-scope>
<managed-property>
<description>
Initializes the shape property of the managed bean Book202 with the value
rect.
</description>
<property-name>shape</property-name>
<value>rect</value>
</managed-property>
<managed-property>
<description>
Initializes the alt property of the managed bean Book202 with the value
Jeeves.
</description>
<property-name>alt</property-name>
<value>Jeeves</value>
</managed-property>
<managed-property>
<description>
Initializes the coords property of the managed bean Book202 with the value
specified by the value element.
</description>
<property-name>coords</property-name>
<value>337,23,480,268</value>
</managed-property>
</managed-bean>
<managed-bean eager="true">
<description>
Causes the default VariableResolver implementation to instantiate the
managed bean Book203 of the class components.model.ImageArea in application
scope if the bean does not already exist in any scope, and initialize the
shape, alt, and coords properties with the values specified by the
managed-property elements.
</description>
<managed-bean-name>Book203</managed-bean-name>
<managed-bean-class>javaeetutorial.dukesbookstore.model.ImageArea</managed-bean-class>
<managed-bean-scope>application</managed-bean-scope>
<managed-property>
<description>
Initializes the shape property of the managed bean Book203 with the value
rect.
</description>
<property-name>shape</property-name>
<value>rect</value>
</managed-property>
<managed-property>
<description>
Initializes the alt property of the managed bean Book203 with the value
Masterson.
</description>
<property-name>alt</property-name>
<value>Masterson</value>
</managed-property>
<managed-property>
<description>
Initializes the coords property of the managed bean Book203 with the value
specified by the value element.
</description>
<property-name>coords</property-name>
<value>605,23,747,268</value>
</managed-property>
</managed-bean>
<managed-bean eager="true">
<description>
Causes the default VariableResolver implementation to instantiate the
managed bean Book205 of the class components.model.ImageArea in application
scope if the bean does not already exist in any scope, and initialize the
shape, alt, and coords properties with the values specified by the
managed-property elements.
</description>
<managed-bean-name>Book205</managed-bean-name>
<managed-bean-class>javaeetutorial.dukesbookstore.model.ImageArea</managed-bean-class>
<managed-bean-scope>application</managed-bean-scope>
<managed-property>
<description>
Initializes the shape property of the managed bean Book205 with the value
rect.
</description>
<property-name>shape</property-name>
<value>rect</value>
</managed-property>
<managed-property>
<description>
Initializes the alt property of the managed bean Book205 with the value
Novation.
</description>
<property-name>alt</property-name>
<value>Novation</value>
</managed-property>
<managed-property>
<description>
Initializes the coords property of the managed bean Book205 with the value
specified by the value element.
</description>
<property-name>coords</property-name>
<value>69,323,210,569</value>
</managed-property>
</managed-bean>
<managed-bean eager="true">
<description>
Causes the default VariableResolver implementation to instantiate the
managed bean Book206 of the class components.model.ImageArea in application
scope if the bean does not already exist in any scope, and initialize the
shape, alt, and coords properties with the values specified by the
managed-property elements.
</description>
<managed-bean-name>Book206</managed-bean-name>
<managed-bean-class>javaeetutorial.dukesbookstore.model.ImageArea</managed-bean-class>
<managed-bean-scope>application</managed-bean-scope>
<managed-property>
<description>
Initializes the shape property of the managed bean Book206 with the value
rect.
</description>
<property-name>shape</property-name>
<value>rect</value>
</managed-property>
<managed-property>
<description>
Initializes the alt property of the managed bean Book206 with the value
Thrilled.
</description>
<property-name>alt</property-name>
<value>Thrilled</value>
</managed-property>
<managed-property>
<description>
Initializes the coords property of the managed bean Book206 with the value
specified by the value element.
</description>
<property-name>coords</property-name>
<value>337,323,479,569</value>
</managed-property>
</managed-bean>
<managed-bean eager="true">
<description>
Causes the default VariableResolver implementation to instantiate the
managed bean Book207 of the class components.model.ImageArea in application
scope if the bean does not already exist in any scope, and initialize the
shape, alt, and coords properties with the values specified by the
managed-property elements.
</description>
<managed-bean-name>Book207</managed-bean-name>
<managed-bean-class>javaeetutorial.dukesbookstore.model.ImageArea</managed-bean-class>
<managed-bean-scope>application</managed-bean-scope>
<managed-property>
<description>
Initializes the shape property of the managed bean Book207 with the value
rect.
</description>
<property-name>shape</property-name>
<value>rect</value>
</managed-property>
<managed-property>
<description>
Initializes the alt property of the managed bean Book207 with the value
Coding.
</description>
<property-name>alt</property-name>
<value>Coding</value>
</managed-property>
<managed-property>
<description>
Initializes the coords property of the managed bean Book207 with the value
specified by the value element.
</description>
<property-name>coords</property-name>
<value>604,323,748,569</value>
</managed-property>
</managed-bean>
</faces-config>
| {
"content_hash": "bfc52cee1fdfa805fb3d832d5ecc5af9",
"timestamp": "",
"source": "github",
"line_count": 249,
"max_line_length": 128,
"avg_line_length": 43.68273092369478,
"alnum_prop": 0.5945573227912108,
"repo_name": "paulnguyen/cmpe279",
"id": "a7d1e923d1b6873c282995759c8ad61979a7047c",
"size": "10877",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "modules/module10/case-studies/dukes-bookstore/src/main/webapp/WEB-INF/faces-config.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "49547"
},
{
"name": "C",
"bytes": "210374"
},
{
"name": "C#",
"bytes": "1614"
},
{
"name": "CSS",
"bytes": "126587"
},
{
"name": "HTML",
"bytes": "2152007"
},
{
"name": "Java",
"bytes": "6777451"
},
{
"name": "JavaScript",
"bytes": "201780"
},
{
"name": "Makefile",
"bytes": "4405"
},
{
"name": "PLSQL",
"bytes": "7899"
},
{
"name": "Shell",
"bytes": "26618"
},
{
"name": "XSLT",
"bytes": "10737"
}
],
"symlink_target": ""
} |
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="theme-color" content="#1b1b1b"/>
<title>raincloud</title>
</head>
<body>
<div id="app-container"></div>
<script src="/js/bundle.js"></script>
</body>
</html>
| {
"content_hash": "2e78d65eb3180be301f53de8be4a9372",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 72,
"avg_line_length": 26.571428571428573,
"alnum_prop": 0.6532258064516129,
"repo_name": "Pamplemaus/raincloud",
"id": "3654565e05c2ac2819450e70488b57ce8cd5e3e2",
"size": "372",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "public/index.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "5049"
},
{
"name": "HTML",
"bytes": "372"
},
{
"name": "JavaScript",
"bytes": "12069"
}
],
"symlink_target": ""
} |
<<<<<<< HEAD
<?php
/**
Get the contact lists in your account.
**/
require_once 'inc/BMEAPI.class.php';
require_once 'inc/config.php'; //contains username & password
$api = new BMEAPI($username, $password, $apiURL);
if ($api->errorCode){
// an error occurred while logging in
echo "code:".$api->errorCode."\n";
echo "msg :".$api->errorMessage."\n";
die();
}
$emailID="info@mark.com";
$retval = $api->listSearchContacts($emailID);
if (!$retval){
echo "Error!";
echo "\n\tCode=".$api->errorCode;
echo "\n\tMsg=".$api->errorMessage."\n";
} else {
echo sizeof($retval)." Lists Returned:\n";
echo "<table>";
echo "<tr><td> </td><td>List ID</td><td> Name </td></tr>";
foreach($retval as $listData){
echo "<tr>";
echo "<td>".$listData['sequence']."</td><td>".$listData['id']."</td>";
echo "<td>".$listData['listname']."</td>";
echo "</tr>";
}
echo "</table>";
}
?>
=======
<?php
/**
Get the contact lists in your account.
**/
require_once 'inc/BMEAPI.class.php';
require_once 'inc/config.php'; //contains username & password
$api = new BMEAPI($username, $password, $apiURL);
if ($api->errorCode){
// an error occurred while logging in
echo "code:".$api->errorCode."\n";
echo "msg :".$api->errorMessage."\n";
die();
}
$emailID="info@mark.com";
$retval = $api->listSearchContacts($emailID);
if (!$retval){
echo "Error!";
echo "\n\tCode=".$api->errorCode;
echo "\n\tMsg=".$api->errorMessage."\n";
} else {
echo sizeof($retval)." Lists Returned:\n";
echo "<table>";
echo "<tr><td> </td><td>List ID</td><td> Name </td></tr>";
foreach($retval as $listData){
echo "<tr>";
echo "<td>".$listData['sequence']."</td><td>".$listData['id']."</td>";
echo "<td>".$listData['listname']."</td>";
echo "</tr>";
}
echo "</table>";
}
?>
>>>>>>> 250a993699aa8885e23578fdfcdb6d486f7dbfae
| {
"content_hash": "89b4f316145799e8161ffcdf88d708dc",
"timestamp": "",
"source": "github",
"line_count": 75,
"max_line_length": 74,
"avg_line_length": 24.69333333333333,
"alnum_prop": 0.593952483801296,
"repo_name": "amirws/em-1",
"id": "fd43d903221a9e795681d2fd00bdd919c18e8f44",
"size": "1852",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "vendor/ZF2/library/Benchmark/bmeapi_listSearchContacts.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "79624"
},
{
"name": "JavaScript",
"bytes": "291591"
},
{
"name": "PHP",
"bytes": "350417"
}
],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.