repo_name
stringlengths 4
116
| path
stringlengths 3
942
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
aaronryden/DefinitelyTyped | types/signature_pad/signature_pad-tests.ts | 1313 | import SignaturePad from 'signature_pad';
/* TEST 1 - Basic structure and usage */
function BasicTest() {
const canvas = document.querySelector('canvas');
const signaturePad = new SignaturePad(canvas);
// Returns signature image as data URL
signaturePad.toDataURL();
// Returns signature image as data URL using the given media type
signaturePad.toDataURL('image/jpeg');
// Returns an array of point groups that define the signature
signaturePad.toData();
// Draws signature image from data URL
signaturePad.fromDataURL('data:image/png;base64,iVBORw0K...');
// Clears the canvas
signaturePad.clear();
// Returns true if canvas is empty, otherwise returns false
signaturePad.isEmpty();
}
/* TEST 2 - You can set options during initialization: */
function SetDuringInit() {
const canvas = document.querySelector('canvas');
const signaturePad = new SignaturePad(canvas, {
minWidth: 5,
maxWidth: 10,
penColor: 'rgb(66, 133, 244)'
});
}
/* TEST 3 - or during runtime: */
function RuntimeChange() {
const canvas = document.querySelector('canvas');
const signaturePad = new SignaturePad(canvas);
signaturePad.minWidth = 5;
signaturePad.maxWidth = 10;
signaturePad.penColor = 'rgb(66, 133, 244)';
}
| mit |
alejo8591/cyav | unidad-4/testappavantel3/plugins/org.apache.cordova.network-information/src/firefoxos/NetworkProxy.js | 2982 | /*
*
* 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.
*
*/
/*
Network API overview: http://dvcs.w3.org/hg/dap/raw-file/tip/network-api/Overview.html
*/
var cordova = require('cordova');
module.exports = {
var connection = navigator.connection || navigator.mozConnection || navigator.webkitConnection;
getConnectionInfo: function (win, fail, args) {
/*
bandwidth of type double, readonly
The user agent must set the value of the bandwidth attribute to:
0 if the user is currently offline;
Infinity if the bandwidth is unknown;
an estimation of the current bandwidth in MB/s (Megabytes per seconds) available for communication with the browsing context active document's domain.
*/
win(connection.bandwidth);
},
isMetered: function (win, fail, args) {
/*
readonly attribute boolean metered
A connection is metered when the user's connection is subject to a limitation from his Internet Service Provider strong enough to request web applications to be careful with the bandwidth usage.
What is a metered connection is voluntarily left to the user agent to judge. It would not be possible to give an exhaustive list of limitations considered strong enough to flag the connection as metered and even if doable, some limitations can be considered strong or weak depending on the context.
Examples of metered connections are mobile connections with a small bandwidth quota or connections with a pay-per use plan.
The user agent MUST set the value of the metered attribute to true if the connection with the browsing context active document's domain is metered and false otherwise. If the implementation is not able to know the status of the connection or if the user is offline, the value MUST be set to false.
If unable to know if a connection is metered, a user agent could ask the user about the status of his current connection.
*/
win(connection.metered);
}
};
require("cordova/firefoxos/commandProxy").add("Network", module.exports); | mit |
vano00/todo | fuel/core/tests/testcase.php | 399 | <?php
/**
* Part of the Fuel framework.
*
* @package Fuel
* @version 1.7
* @author Fuel Development Team
* @license MIT License
* @copyright 2010 - 2015 Fuel Development Team
* @link http://fuelphp.com
*/
namespace Fuel\Core;
/**
* Testcase class tests
*
* @group Core
* @group Testcase
*/
class Test_Testcase extends TestCase
{
public function test_foo() {}
}
| mit |
dmaticzka/bioconda-recipes | recipes/sweepfinder2/build.sh | 142 | #!/bin/bash
export C_INCLUDE_PATH=${PREFIX}/include
export LIBRARY_PATH=${PREFIX}/lib
make
mkdir -p $PREFIX/bin
cp SweepFinder2 $PREFIX/bin
| mit |
penberg/linux | block/blk-pm.c | 6864 | // SPDX-License-Identifier: GPL-2.0
#include <linux/blk-mq.h>
#include <linux/blk-pm.h>
#include <linux/blkdev.h>
#include <linux/pm_runtime.h>
#include "blk-mq.h"
#include "blk-mq-tag.h"
/**
* blk_pm_runtime_init - Block layer runtime PM initialization routine
* @q: the queue of the device
* @dev: the device the queue belongs to
*
* Description:
* Initialize runtime-PM-related fields for @q and start auto suspend for
* @dev. Drivers that want to take advantage of request-based runtime PM
* should call this function after @dev has been initialized, and its
* request queue @q has been allocated, and runtime PM for it can not happen
* yet(either due to disabled/forbidden or its usage_count > 0). In most
* cases, driver should call this function before any I/O has taken place.
*
* This function takes care of setting up using auto suspend for the device,
* the autosuspend delay is set to -1 to make runtime suspend impossible
* until an updated value is either set by user or by driver. Drivers do
* not need to touch other autosuspend settings.
*
* The block layer runtime PM is request based, so only works for drivers
* that use request as their IO unit instead of those directly use bio's.
*/
void blk_pm_runtime_init(struct request_queue *q, struct device *dev)
{
q->dev = dev;
q->rpm_status = RPM_ACTIVE;
pm_runtime_set_autosuspend_delay(q->dev, -1);
pm_runtime_use_autosuspend(q->dev);
}
EXPORT_SYMBOL(blk_pm_runtime_init);
/**
* blk_pre_runtime_suspend - Pre runtime suspend check
* @q: the queue of the device
*
* Description:
* This function will check if runtime suspend is allowed for the device
* by examining if there are any requests pending in the queue. If there
* are requests pending, the device can not be runtime suspended; otherwise,
* the queue's status will be updated to SUSPENDING and the driver can
* proceed to suspend the device.
*
* For the not allowed case, we mark last busy for the device so that
* runtime PM core will try to autosuspend it some time later.
*
* This function should be called near the start of the device's
* runtime_suspend callback.
*
* Return:
* 0 - OK to runtime suspend the device
* -EBUSY - Device should not be runtime suspended
*/
int blk_pre_runtime_suspend(struct request_queue *q)
{
int ret = 0;
if (!q->dev)
return ret;
WARN_ON_ONCE(q->rpm_status != RPM_ACTIVE);
/*
* Increase the pm_only counter before checking whether any
* non-PM blk_queue_enter() calls are in progress to avoid that any
* new non-PM blk_queue_enter() calls succeed before the pm_only
* counter is decreased again.
*/
blk_set_pm_only(q);
ret = -EBUSY;
/* Switch q_usage_counter from per-cpu to atomic mode. */
blk_freeze_queue_start(q);
/*
* Wait until atomic mode has been reached. Since that
* involves calling call_rcu(), it is guaranteed that later
* blk_queue_enter() calls see the pm-only state. See also
* http://lwn.net/Articles/573497/.
*/
percpu_ref_switch_to_atomic_sync(&q->q_usage_counter);
if (percpu_ref_is_zero(&q->q_usage_counter))
ret = 0;
/* Switch q_usage_counter back to per-cpu mode. */
blk_mq_unfreeze_queue(q);
spin_lock_irq(&q->queue_lock);
if (ret < 0)
pm_runtime_mark_last_busy(q->dev);
else
q->rpm_status = RPM_SUSPENDING;
spin_unlock_irq(&q->queue_lock);
if (ret)
blk_clear_pm_only(q);
return ret;
}
EXPORT_SYMBOL(blk_pre_runtime_suspend);
/**
* blk_post_runtime_suspend - Post runtime suspend processing
* @q: the queue of the device
* @err: return value of the device's runtime_suspend function
*
* Description:
* Update the queue's runtime status according to the return value of the
* device's runtime suspend function and mark last busy for the device so
* that PM core will try to auto suspend the device at a later time.
*
* This function should be called near the end of the device's
* runtime_suspend callback.
*/
void blk_post_runtime_suspend(struct request_queue *q, int err)
{
if (!q->dev)
return;
spin_lock_irq(&q->queue_lock);
if (!err) {
q->rpm_status = RPM_SUSPENDED;
} else {
q->rpm_status = RPM_ACTIVE;
pm_runtime_mark_last_busy(q->dev);
}
spin_unlock_irq(&q->queue_lock);
if (err)
blk_clear_pm_only(q);
}
EXPORT_SYMBOL(blk_post_runtime_suspend);
/**
* blk_pre_runtime_resume - Pre runtime resume processing
* @q: the queue of the device
*
* Description:
* Update the queue's runtime status to RESUMING in preparation for the
* runtime resume of the device.
*
* This function should be called near the start of the device's
* runtime_resume callback.
*/
void blk_pre_runtime_resume(struct request_queue *q)
{
if (!q->dev)
return;
spin_lock_irq(&q->queue_lock);
q->rpm_status = RPM_RESUMING;
spin_unlock_irq(&q->queue_lock);
}
EXPORT_SYMBOL(blk_pre_runtime_resume);
/**
* blk_post_runtime_resume - Post runtime resume processing
* @q: the queue of the device
* @err: return value of the device's runtime_resume function
*
* Description:
* Update the queue's runtime status according to the return value of the
* device's runtime_resume function. If the resume was successful, call
* blk_set_runtime_active() to do the real work of restarting the queue.
*
* This function should be called near the end of the device's
* runtime_resume callback.
*/
void blk_post_runtime_resume(struct request_queue *q, int err)
{
if (!q->dev)
return;
if (!err) {
blk_set_runtime_active(q);
} else {
spin_lock_irq(&q->queue_lock);
q->rpm_status = RPM_SUSPENDED;
spin_unlock_irq(&q->queue_lock);
}
}
EXPORT_SYMBOL(blk_post_runtime_resume);
/**
* blk_set_runtime_active - Force runtime status of the queue to be active
* @q: the queue of the device
*
* If the device is left runtime suspended during system suspend the resume
* hook typically resumes the device and corrects runtime status
* accordingly. However, that does not affect the queue runtime PM status
* which is still "suspended". This prevents processing requests from the
* queue.
*
* This function can be used in driver's resume hook to correct queue
* runtime PM status and re-enable peeking requests from the queue. It
* should be called before first request is added to the queue.
*
* This function is also called by blk_post_runtime_resume() for successful
* runtime resumes. It does everything necessary to restart the queue.
*/
void blk_set_runtime_active(struct request_queue *q)
{
int old_status;
if (!q->dev)
return;
spin_lock_irq(&q->queue_lock);
old_status = q->rpm_status;
q->rpm_status = RPM_ACTIVE;
pm_runtime_mark_last_busy(q->dev);
pm_request_autosuspend(q->dev);
spin_unlock_irq(&q->queue_lock);
if (old_status != RPM_ACTIVE)
blk_clear_pm_only(q);
}
EXPORT_SYMBOL(blk_set_runtime_active);
| gpl-2.0 |
mdxy2010/forlinux-ok6410 | u-boot15/arch/powerpc/cpu/ppc4xx/denali_spd_ddr2.c | 39820 | /*
* arch/powerpc/cpu/ppc4xx/denali_spd_ddr2.c
* This SPD SDRAM detection code supports AMCC PPC44x CPUs with a Denali-core
* DDR2 controller, specifically the 440EPx/GRx.
*
* (C) Copyright 2007-2008
* Larry Johnson, [email protected].
*
* Based primarily on arch/powerpc/cpu/ppc4xx/4xx_spd_ddr2.c, which is...
*
* (C) Copyright 2007
* Stefan Roese, DENX Software Engineering, [email protected].
*
* COPYRIGHT AMCC CORPORATION 2004
*
* SPDX-License-Identifier: GPL-2.0+
*/
/* define DEBUG for debugging output (obviously ;-)) */
#if 0
#define DEBUG
#endif
#include <common.h>
#include <command.h>
#include <asm/ppc4xx.h>
#include <i2c.h>
#include <asm/io.h>
#include <asm/processor.h>
#include <asm/mmu.h>
#include <asm/cache.h>
#if defined(CONFIG_SPD_EEPROM) && \
(defined(CONFIG_440EPX) || defined(CONFIG_440GRX))
/*-----------------------------------------------------------------------------+
* Defines
*-----------------------------------------------------------------------------*/
#define MAXDIMMS 2
#define MAXRANKS 2
#define ONE_BILLION 1000000000
#define MULDIV64(m1, m2, d) (u32)(((u64)(m1) * (u64)(m2)) / (u64)(d))
#define DLL_DQS_DELAY 0x19
#define DLL_DQS_BYPASS 0x0B
#define DQS_OUT_SHIFT 0x7F
/*
* This DDR2 setup code can dynamically setup the TLB entries for the DDR2 memory
* region. Right now the cache should still be disabled in U-Boot because of the
* EMAC driver, that need it's buffer descriptor to be located in non cached
* memory.
*
* If at some time this restriction doesn't apply anymore, just define
* CONFIG_4xx_DCACHE in the board config file and this code should setup
* everything correctly.
*/
#if defined(CONFIG_4xx_DCACHE)
#define MY_TLB_WORD2_I_ENABLE 0 /* enable caching on SDRAM */
#else
#define MY_TLB_WORD2_I_ENABLE TLB_WORD2_I_ENABLE /* disable caching on SDRAM */
#endif
/*-----------------------------------------------------------------------------+
* Prototypes
*-----------------------------------------------------------------------------*/
extern int denali_wait_for_dlllock(void);
extern void denali_core_search_data_eye(void);
extern void dcbz_area(u32 start_address, u32 num_bytes);
/*
* Board-specific Platform code can reimplement spd_ddr_init_hang () if needed
*/
void __spd_ddr_init_hang(void)
{
hang();
}
void spd_ddr_init_hang(void)
__attribute__ ((weak, alias("__spd_ddr_init_hang")));
#if defined(DEBUG)
static void print_mcsr(void)
{
printf("MCSR = 0x%08X\n", mfspr(SPRN_MCSR));
}
static void denali_sdram_register_dump(void)
{
unsigned int sdram_data;
printf("\n Register Dump:\n");
mfsdram(DDR0_00, sdram_data);
printf(" DDR0_00 = 0x%08X", sdram_data);
mfsdram(DDR0_01, sdram_data);
printf(" DDR0_01 = 0x%08X\n", sdram_data);
mfsdram(DDR0_02, sdram_data);
printf(" DDR0_02 = 0x%08X", sdram_data);
mfsdram(DDR0_03, sdram_data);
printf(" DDR0_03 = 0x%08X\n", sdram_data);
mfsdram(DDR0_04, sdram_data);
printf(" DDR0_04 = 0x%08X", sdram_data);
mfsdram(DDR0_05, sdram_data);
printf(" DDR0_05 = 0x%08X\n", sdram_data);
mfsdram(DDR0_06, sdram_data);
printf(" DDR0_06 = 0x%08X", sdram_data);
mfsdram(DDR0_07, sdram_data);
printf(" DDR0_07 = 0x%08X\n", sdram_data);
mfsdram(DDR0_08, sdram_data);
printf(" DDR0_08 = 0x%08X", sdram_data);
mfsdram(DDR0_09, sdram_data);
printf(" DDR0_09 = 0x%08X\n", sdram_data);
mfsdram(DDR0_10, sdram_data);
printf(" DDR0_10 = 0x%08X", sdram_data);
mfsdram(DDR0_11, sdram_data);
printf(" DDR0_11 = 0x%08X\n", sdram_data);
mfsdram(DDR0_12, sdram_data);
printf(" DDR0_12 = 0x%08X", sdram_data);
mfsdram(DDR0_14, sdram_data);
printf(" DDR0_14 = 0x%08X\n", sdram_data);
mfsdram(DDR0_17, sdram_data);
printf(" DDR0_17 = 0x%08X", sdram_data);
mfsdram(DDR0_18, sdram_data);
printf(" DDR0_18 = 0x%08X\n", sdram_data);
mfsdram(DDR0_19, sdram_data);
printf(" DDR0_19 = 0x%08X", sdram_data);
mfsdram(DDR0_20, sdram_data);
printf(" DDR0_20 = 0x%08X\n", sdram_data);
mfsdram(DDR0_21, sdram_data);
printf(" DDR0_21 = 0x%08X", sdram_data);
mfsdram(DDR0_22, sdram_data);
printf(" DDR0_22 = 0x%08X\n", sdram_data);
mfsdram(DDR0_23, sdram_data);
printf(" DDR0_23 = 0x%08X", sdram_data);
mfsdram(DDR0_24, sdram_data);
printf(" DDR0_24 = 0x%08X\n", sdram_data);
mfsdram(DDR0_25, sdram_data);
printf(" DDR0_25 = 0x%08X", sdram_data);
mfsdram(DDR0_26, sdram_data);
printf(" DDR0_26 = 0x%08X\n", sdram_data);
mfsdram(DDR0_27, sdram_data);
printf(" DDR0_27 = 0x%08X", sdram_data);
mfsdram(DDR0_28, sdram_data);
printf(" DDR0_28 = 0x%08X\n", sdram_data);
mfsdram(DDR0_31, sdram_data);
printf(" DDR0_31 = 0x%08X", sdram_data);
mfsdram(DDR0_32, sdram_data);
printf(" DDR0_32 = 0x%08X\n", sdram_data);
mfsdram(DDR0_33, sdram_data);
printf(" DDR0_33 = 0x%08X", sdram_data);
mfsdram(DDR0_34, sdram_data);
printf(" DDR0_34 = 0x%08X\n", sdram_data);
mfsdram(DDR0_35, sdram_data);
printf(" DDR0_35 = 0x%08X", sdram_data);
mfsdram(DDR0_36, sdram_data);
printf(" DDR0_36 = 0x%08X\n", sdram_data);
mfsdram(DDR0_37, sdram_data);
printf(" DDR0_37 = 0x%08X", sdram_data);
mfsdram(DDR0_38, sdram_data);
printf(" DDR0_38 = 0x%08X\n", sdram_data);
mfsdram(DDR0_39, sdram_data);
printf(" DDR0_39 = 0x%08X", sdram_data);
mfsdram(DDR0_40, sdram_data);
printf(" DDR0_40 = 0x%08X\n", sdram_data);
mfsdram(DDR0_41, sdram_data);
printf(" DDR0_41 = 0x%08X", sdram_data);
mfsdram(DDR0_42, sdram_data);
printf(" DDR0_42 = 0x%08X\n", sdram_data);
mfsdram(DDR0_43, sdram_data);
printf(" DDR0_43 = 0x%08X", sdram_data);
mfsdram(DDR0_44, sdram_data);
printf(" DDR0_44 = 0x%08X\n", sdram_data);
}
#else
static inline void denali_sdram_register_dump(void)
{
}
inline static void print_mcsr(void)
{
}
#endif /* defined(DEBUG) */
static int is_ecc_enabled(void)
{
u32 val;
mfsdram(DDR0_22, val);
return 0x3 == DDR0_22_CTRL_RAW_DECODE(val);
}
static unsigned char spd_read(u8 chip, unsigned int addr)
{
u8 data[2];
if (0 != i2c_probe(chip) || 0 != i2c_read(chip, addr, 1, data, 1)) {
debug("spd_read(0x%02X, 0x%02X) failed\n", chip, addr);
return 0;
}
debug("spd_read(0x%02X, 0x%02X) returned 0x%02X\n",
chip, addr, data[0]);
return data[0];
}
static unsigned long get_tcyc(unsigned char reg)
{
/*
* Byte 9, et al: Cycle time for CAS Latency=X, is split into two
* nibbles: the higher order nibble (bits 4-7) designates the cycle time
* to a granularity of 1ns; the value presented by the lower order
* nibble (bits 0-3) has a granularity of .1ns and is added to the value
* designated by the higher nibble. In addition, four lines of the lower
* order nibble are assigned to support +.25, +.33, +.66, and +.75.
*/
unsigned char subfield_b = reg & 0x0F;
switch (subfield_b & 0x0F) {
case 0x0:
case 0x1:
case 0x2:
case 0x3:
case 0x4:
case 0x5:
case 0x6:
case 0x7:
case 0x8:
case 0x9:
return 1000 * (reg >> 4) + 100 * subfield_b;
case 0xA:
return 1000 * (reg >> 4) + 250;
case 0xB:
return 1000 * (reg >> 4) + 333;
case 0xC:
return 1000 * (reg >> 4) + 667;
case 0xD:
return 1000 * (reg >> 4) + 750;
}
return 0;
}
/*------------------------------------------------------------------
* Find the installed DIMMs, make sure that the are DDR2, and fill
* in the dimm_ranks array. Then dimm_ranks[dimm_num] > 0 iff the
* DIMM and dimm_num is present.
* Note: Because there are only two chip-select lines, it is assumed
* that a board with a single socket can support two ranks on that
* socket, while a board with two sockets can support only one rank
* on each socket.
*-----------------------------------------------------------------*/
static void get_spd_info(unsigned long dimm_ranks[],
unsigned long *ranks,
unsigned char const iic0_dimm_addr[],
unsigned long num_dimm_banks)
{
unsigned long dimm_num;
unsigned long dimm_found = false;
unsigned long const max_ranks_per_dimm = (1 == num_dimm_banks) ? 2 : 1;
unsigned char num_of_bytes;
unsigned char total_size;
*ranks = 0;
for (dimm_num = 0; dimm_num < num_dimm_banks; dimm_num++) {
num_of_bytes = 0;
total_size = 0;
num_of_bytes = spd_read(iic0_dimm_addr[dimm_num], 0);
total_size = spd_read(iic0_dimm_addr[dimm_num], 1);
if ((num_of_bytes != 0) && (total_size != 0)) {
unsigned char const dimm_type =
spd_read(iic0_dimm_addr[dimm_num], 2);
unsigned long ranks_on_dimm =
(spd_read(iic0_dimm_addr[dimm_num], 5) & 0x07) + 1;
if (8 != dimm_type) {
switch (dimm_type) {
case 1:
printf("ERROR: Standard Fast Page Mode "
"DRAM DIMM");
break;
case 2:
printf("ERROR: EDO DIMM");
break;
case 3:
printf("ERROR: Pipelined Nibble DIMM");
break;
case 4:
printf("ERROR: SDRAM DIMM");
break;
case 5:
printf("ERROR: Multiplexed ROM DIMM");
break;
case 6:
printf("ERROR: SGRAM DIMM");
break;
case 7:
printf("ERROR: DDR1 DIMM");
break;
default:
printf("ERROR: Unknown DIMM (type %d)",
(unsigned int)dimm_type);
break;
}
printf(" detected in slot %lu.\n", dimm_num);
printf("Only DDR2 SDRAM DIMMs are supported."
"\n");
printf("Replace the module with a DDR2 DIMM."
"\n\n");
spd_ddr_init_hang();
}
dimm_found = true;
debug("DIMM slot %lu: populated with %lu-rank DDR2 DIMM"
"\n", dimm_num, ranks_on_dimm);
if (ranks_on_dimm > max_ranks_per_dimm) {
printf("WARNING: DRAM DIMM in slot %lu has %lu "
"ranks.\n", dimm_num, ranks_on_dimm);
if (1 == max_ranks_per_dimm) {
printf("Only one rank will be used.\n");
} else {
printf
("Only two ranks will be used.\n");
}
ranks_on_dimm = max_ranks_per_dimm;
}
dimm_ranks[dimm_num] = ranks_on_dimm;
*ranks += ranks_on_dimm;
} else {
dimm_ranks[dimm_num] = 0;
debug("DIMM slot %lu: Not populated\n", dimm_num);
}
}
if (dimm_found == false) {
printf("ERROR: No memory installed.\n");
printf("Install at least one DDR2 DIMM.\n\n");
spd_ddr_init_hang();
}
debug("Total number of ranks = %ld\n", *ranks);
}
/*------------------------------------------------------------------
* For the memory DIMMs installed, this routine verifies that
* frequency previously calculated is supported.
*-----------------------------------------------------------------*/
static void check_frequency(unsigned long *dimm_ranks,
unsigned char const iic0_dimm_addr[],
unsigned long num_dimm_banks,
unsigned long sdram_freq)
{
unsigned long dimm_num;
unsigned long cycle_time;
unsigned long calc_cycle_time;
/*
* calc_cycle_time is calculated from DDR frequency set by board/chip
* and is expressed in picoseconds to match the way DIMM cycle time is
* calculated below.
*/
calc_cycle_time = MULDIV64(ONE_BILLION, 1000, sdram_freq);
for (dimm_num = 0; dimm_num < num_dimm_banks; dimm_num++) {
if (dimm_ranks[dimm_num]) {
cycle_time =
get_tcyc(spd_read(iic0_dimm_addr[dimm_num], 9));
debug("cycle_time=%ld ps\n", cycle_time);
if (cycle_time > (calc_cycle_time + 10)) {
/*
* the provided sdram cycle_time is too small
* for the available DIMM cycle_time. The
* additionnal 10ps is here to accept a small
* incertainty.
*/
printf
("ERROR: DRAM DIMM detected with cycle_time %d ps in "
"slot %d \n while calculated cycle time is %d ps.\n",
(unsigned int)cycle_time,
(unsigned int)dimm_num,
(unsigned int)calc_cycle_time);
printf
("Replace the DIMM, or change DDR frequency via "
"strapping bits.\n\n");
spd_ddr_init_hang();
}
}
}
}
/*------------------------------------------------------------------
* This routine gets size information for the installed memory
* DIMMs.
*-----------------------------------------------------------------*/
static void get_dimm_size(unsigned long dimm_ranks[],
unsigned char const iic0_dimm_addr[],
unsigned long num_dimm_banks,
unsigned long *const rows,
unsigned long *const banks,
unsigned long *const cols, unsigned long *const width)
{
unsigned long dimm_num;
*rows = 0;
*banks = 0;
*cols = 0;
*width = 0;
for (dimm_num = 0; dimm_num < num_dimm_banks; dimm_num++) {
if (dimm_ranks[dimm_num]) {
unsigned long t;
/* Rows */
t = spd_read(iic0_dimm_addr[dimm_num], 3);
if (0 == *rows) {
*rows = t;
} else if (t != *rows) {
printf("ERROR: DRAM DIMM modules do not all "
"have the same number of rows.\n\n");
spd_ddr_init_hang();
}
/* Banks */
t = spd_read(iic0_dimm_addr[dimm_num], 17);
if (0 == *banks) {
*banks = t;
} else if (t != *banks) {
printf("ERROR: DRAM DIMM modules do not all "
"have the same number of banks.\n\n");
spd_ddr_init_hang();
}
/* Columns */
t = spd_read(iic0_dimm_addr[dimm_num], 4);
if (0 == *cols) {
*cols = t;
} else if (t != *cols) {
printf("ERROR: DRAM DIMM modules do not all "
"have the same number of columns.\n\n");
spd_ddr_init_hang();
}
/* Data width */
t = spd_read(iic0_dimm_addr[dimm_num], 6);
if (0 == *width) {
*width = t;
} else if (t != *width) {
printf("ERROR: DRAM DIMM modules do not all "
"have the same data width.\n\n");
spd_ddr_init_hang();
}
}
}
debug("Number of rows = %ld\n", *rows);
debug("Number of columns = %ld\n", *cols);
debug("Number of banks = %ld\n", *banks);
debug("Data width = %ld\n", *width);
if (*rows > 14) {
printf("ERROR: DRAM DIMM modules have %lu address rows.\n",
*rows);
printf("Only modules with 14 or fewer rows are supported.\n\n");
spd_ddr_init_hang();
}
if (4 != *banks && 8 != *banks) {
printf("ERROR: DRAM DIMM modules have %lu banks.\n", *banks);
printf("Only modules with 4 or 8 banks are supported.\n\n");
spd_ddr_init_hang();
}
if (*cols > 12) {
printf("ERROR: DRAM DIMM modules have %lu address columns.\n",
*cols);
printf("Only modules with 12 or fewer columns are "
"supported.\n\n");
spd_ddr_init_hang();
}
if (32 != *width && 40 != *width && 64 != *width && 72 != *width) {
printf("ERROR: DRAM DIMM modules have a width of %lu bit.\n",
*width);
printf("Only modules with widths of 32, 40, 64, and 72 bits "
"are supported.\n\n");
spd_ddr_init_hang();
}
}
/*------------------------------------------------------------------
* Only 1.8V modules are supported. This routine verifies this.
*-----------------------------------------------------------------*/
static void check_voltage_type(unsigned long dimm_ranks[],
unsigned char const iic0_dimm_addr[],
unsigned long num_dimm_banks)
{
unsigned long dimm_num;
unsigned long voltage_type;
for (dimm_num = 0; dimm_num < num_dimm_banks; dimm_num++) {
if (dimm_ranks[dimm_num]) {
voltage_type = spd_read(iic0_dimm_addr[dimm_num], 8);
if (0x05 != voltage_type) { /* 1.8V for DDR2 */
printf("ERROR: Slot %lu provides 1.8V for DDR2 "
"DIMMs.\n", dimm_num);
switch (voltage_type) {
case 0x00:
printf("This DIMM is 5.0 Volt/TTL.\n");
break;
case 0x01:
printf("This DIMM is LVTTL.\n");
break;
case 0x02:
printf("This DIMM is 1.5 Volt.\n");
break;
case 0x03:
printf("This DIMM is 3.3 Volt/TTL.\n");
break;
case 0x04:
printf("This DIMM is 2.5 Volt.\n");
break;
default:
printf("This DIMM is an unknown "
"voltage.\n");
break;
}
printf("Replace it with a 1.8V DDR2 DIMM.\n\n");
spd_ddr_init_hang();
}
}
}
}
static void program_ddr0_03(unsigned long dimm_ranks[],
unsigned char const iic0_dimm_addr[],
unsigned long num_dimm_banks,
unsigned long sdram_freq,
unsigned long rows, unsigned long *cas_latency)
{
unsigned long dimm_num;
unsigned long cas_index;
unsigned long cycle_2_0_clk;
unsigned long cycle_3_0_clk;
unsigned long cycle_4_0_clk;
unsigned long cycle_5_0_clk;
unsigned long max_2_0_tcyc_ps = 100;
unsigned long max_3_0_tcyc_ps = 100;
unsigned long max_4_0_tcyc_ps = 100;
unsigned long max_5_0_tcyc_ps = 100;
unsigned char cas_available = 0x3C; /* value for DDR2 */
u32 ddr0_03 = DDR0_03_BSTLEN_ENCODE(0x2) | DDR0_03_INITAREF_ENCODE(0x2);
unsigned int const tcyc_addr[3] = { 9, 23, 25 };
/*------------------------------------------------------------------
* Get the board configuration info.
*-----------------------------------------------------------------*/
debug("sdram_freq = %ld\n", sdram_freq);
/*------------------------------------------------------------------
* Handle the timing. We need to find the worst case timing of all
* the dimm modules installed.
*-----------------------------------------------------------------*/
/* loop through all the DIMM slots on the board */
for (dimm_num = 0; dimm_num < num_dimm_banks; dimm_num++) {
/* If a dimm is installed in a particular slot ... */
if (dimm_ranks[dimm_num]) {
unsigned char const cas_bit =
spd_read(iic0_dimm_addr[dimm_num], 18);
unsigned char cas_mask;
cas_available &= cas_bit;
for (cas_mask = 0x80; cas_mask; cas_mask >>= 1) {
if (cas_bit & cas_mask)
break;
}
debug("cas_bit (SPD byte 18) = %02X, cas_mask = %02X\n",
cas_bit, cas_mask);
for (cas_index = 0; cas_index < 3;
cas_mask >>= 1, cas_index++) {
unsigned long cycle_time_ps;
if (!(cas_available & cas_mask)) {
continue;
}
cycle_time_ps =
get_tcyc(spd_read(iic0_dimm_addr[dimm_num],
tcyc_addr[cas_index]));
debug("cas_index = %ld: cycle_time_ps = %ld\n",
cas_index, cycle_time_ps);
/*
* DDR2 devices use the following bitmask for CAS latency:
* Bit 7 6 5 4 3 2 1 0
* TBD 6.0 5.0 4.0 3.0 2.0 TBD TBD
*/
switch (cas_mask) {
case 0x20:
max_5_0_tcyc_ps =
max(max_5_0_tcyc_ps, cycle_time_ps);
break;
case 0x10:
max_4_0_tcyc_ps =
max(max_4_0_tcyc_ps, cycle_time_ps);
break;
case 0x08:
max_3_0_tcyc_ps =
max(max_3_0_tcyc_ps, cycle_time_ps);
break;
case 0x04:
max_2_0_tcyc_ps =
max(max_2_0_tcyc_ps, cycle_time_ps);
break;
}
}
}
}
debug("cas_available (bit map) = 0x%02X\n", cas_available);
/*------------------------------------------------------------------
* Set the SDRAM mode, SDRAM_MMODE
*-----------------------------------------------------------------*/
/* add 10 here because of rounding problems */
cycle_2_0_clk = MULDIV64(ONE_BILLION, 1000, max_2_0_tcyc_ps) + 10;
cycle_3_0_clk = MULDIV64(ONE_BILLION, 1000, max_3_0_tcyc_ps) + 10;
cycle_4_0_clk = MULDIV64(ONE_BILLION, 1000, max_4_0_tcyc_ps) + 10;
cycle_5_0_clk = MULDIV64(ONE_BILLION, 1000, max_5_0_tcyc_ps) + 10;
debug("cycle_2_0_clk = %ld\n", cycle_2_0_clk);
debug("cycle_3_0_clk = %ld\n", cycle_3_0_clk);
debug("cycle_4_0_clk = %ld\n", cycle_4_0_clk);
debug("cycle_5_0_clk = %ld\n", cycle_5_0_clk);
if ((cas_available & 0x04) && (sdram_freq <= cycle_2_0_clk)) {
*cas_latency = 2;
ddr0_03 |= DDR0_03_CASLAT_ENCODE(0x2) |
DDR0_03_CASLAT_LIN_ENCODE(0x4);
} else if ((cas_available & 0x08) && (sdram_freq <= cycle_3_0_clk)) {
*cas_latency = 3;
ddr0_03 |= DDR0_03_CASLAT_ENCODE(0x3) |
DDR0_03_CASLAT_LIN_ENCODE(0x6);
} else if ((cas_available & 0x10) && (sdram_freq <= cycle_4_0_clk)) {
*cas_latency = 4;
ddr0_03 |= DDR0_03_CASLAT_ENCODE(0x4) |
DDR0_03_CASLAT_LIN_ENCODE(0x8);
} else if ((cas_available & 0x20) && (sdram_freq <= cycle_5_0_clk)) {
*cas_latency = 5;
ddr0_03 |= DDR0_03_CASLAT_ENCODE(0x5) |
DDR0_03_CASLAT_LIN_ENCODE(0xA);
} else {
printf("ERROR: Cannot find a supported CAS latency with the "
"installed DIMMs.\n");
printf("Only DDR2 DIMMs with CAS latencies of 2.0, 3.0, 4.0, "
"and 5.0 are supported.\n");
printf("Make sure the PLB speed is within the supported range "
"of the DIMMs.\n");
printf("sdram_freq=%ld cycle2=%ld cycle3=%ld cycle4=%ld "
"cycle5=%ld\n\n", sdram_freq, cycle_2_0_clk,
cycle_3_0_clk, cycle_4_0_clk, cycle_5_0_clk);
spd_ddr_init_hang();
}
debug("CAS latency = %ld\n", *cas_latency);
mtsdram(DDR0_03, ddr0_03);
}
static void program_ddr0_04(unsigned long dimm_ranks[],
unsigned char const iic0_dimm_addr[],
unsigned long num_dimm_banks,
unsigned long sdram_freq)
{
unsigned long dimm_num;
unsigned long t_rc_ps = 0;
unsigned long t_rrd_ps = 0;
unsigned long t_rtp_ps = 0;
unsigned long t_rc_clk;
unsigned long t_rrd_clk;
unsigned long t_rtp_clk;
/*------------------------------------------------------------------
* Handle the timing. We need to find the worst case timing of all
* the dimm modules installed.
*-----------------------------------------------------------------*/
/* loop through all the DIMM slots on the board */
for (dimm_num = 0; dimm_num < num_dimm_banks; dimm_num++) {
/* If a dimm is installed in a particular slot ... */
if (dimm_ranks[dimm_num]) {
unsigned long ps;
/* tRC */
ps = 1000 * spd_read(iic0_dimm_addr[dimm_num], 41);
switch (spd_read(iic0_dimm_addr[dimm_num], 40) >> 4) {
case 0x1:
ps += 250;
break;
case 0x2:
ps += 333;
break;
case 0x3:
ps += 500;
break;
case 0x4:
ps += 667;
break;
case 0x5:
ps += 750;
break;
}
t_rc_ps = max(t_rc_ps, ps);
/* tRRD */
ps = 250 * spd_read(iic0_dimm_addr[dimm_num], 28);
t_rrd_ps = max(t_rrd_ps, ps);
/* tRTP */
ps = 250 * spd_read(iic0_dimm_addr[dimm_num], 38);
t_rtp_ps = max(t_rtp_ps, ps);
}
}
debug("t_rc_ps = %ld\n", t_rc_ps);
t_rc_clk = (MULDIV64(sdram_freq, t_rc_ps, ONE_BILLION) + 999) / 1000;
debug("t_rrd_ps = %ld\n", t_rrd_ps);
t_rrd_clk = (MULDIV64(sdram_freq, t_rrd_ps, ONE_BILLION) + 999) / 1000;
debug("t_rtp_ps = %ld\n", t_rtp_ps);
t_rtp_clk = (MULDIV64(sdram_freq, t_rtp_ps, ONE_BILLION) + 999) / 1000;
mtsdram(DDR0_04, DDR0_04_TRC_ENCODE(t_rc_clk) |
DDR0_04_TRRD_ENCODE(t_rrd_clk) |
DDR0_04_TRTP_ENCODE(t_rtp_clk));
}
static void program_ddr0_05(unsigned long dimm_ranks[],
unsigned char const iic0_dimm_addr[],
unsigned long num_dimm_banks,
unsigned long sdram_freq)
{
unsigned long dimm_num;
unsigned long t_rp_ps = 0;
unsigned long t_ras_ps = 0;
unsigned long t_rp_clk;
unsigned long t_ras_clk;
u32 ddr0_05 = DDR0_05_TMRD_ENCODE(0x2) | DDR0_05_TEMRS_ENCODE(0x2);
/*------------------------------------------------------------------
* Handle the timing. We need to find the worst case timing of all
* the dimm modules installed.
*-----------------------------------------------------------------*/
/* loop through all the DIMM slots on the board */
for (dimm_num = 0; dimm_num < num_dimm_banks; dimm_num++) {
/* If a dimm is installed in a particular slot ... */
if (dimm_ranks[dimm_num]) {
unsigned long ps;
/* tRP */
ps = 250 * spd_read(iic0_dimm_addr[dimm_num], 27);
t_rp_ps = max(t_rp_ps, ps);
/* tRAS */
ps = 1000 * spd_read(iic0_dimm_addr[dimm_num], 30);
t_ras_ps = max(t_ras_ps, ps);
}
}
debug("t_rp_ps = %ld\n", t_rp_ps);
t_rp_clk = (MULDIV64(sdram_freq, t_rp_ps, ONE_BILLION) + 999) / 1000;
debug("t_ras_ps = %ld\n", t_ras_ps);
t_ras_clk = (MULDIV64(sdram_freq, t_ras_ps, ONE_BILLION) + 999) / 1000;
mtsdram(DDR0_05, ddr0_05 | DDR0_05_TRP_ENCODE(t_rp_clk) |
DDR0_05_TRAS_MIN_ENCODE(t_ras_clk));
}
static void program_ddr0_06(unsigned long dimm_ranks[],
unsigned char const iic0_dimm_addr[],
unsigned long num_dimm_banks,
unsigned long sdram_freq)
{
unsigned long dimm_num;
unsigned char spd_40;
unsigned long t_wtr_ps = 0;
unsigned long t_rfc_ps = 0;
unsigned long t_wtr_clk;
unsigned long t_rfc_clk;
u32 ddr0_06 =
DDR0_06_WRITEINTERP_ENCODE(0x1) | DDR0_06_TDLL_ENCODE(200);
/*------------------------------------------------------------------
* Handle the timing. We need to find the worst case timing of all
* the dimm modules installed.
*-----------------------------------------------------------------*/
/* loop through all the DIMM slots on the board */
for (dimm_num = 0; dimm_num < num_dimm_banks; dimm_num++) {
/* If a dimm is installed in a particular slot ... */
if (dimm_ranks[dimm_num]) {
unsigned long ps;
/* tWTR */
ps = 250 * spd_read(iic0_dimm_addr[dimm_num], 37);
t_wtr_ps = max(t_wtr_ps, ps);
/* tRFC */
ps = 1000 * spd_read(iic0_dimm_addr[dimm_num], 42);
spd_40 = spd_read(iic0_dimm_addr[dimm_num], 40);
ps += 256000 * (spd_40 & 0x01);
switch ((spd_40 & 0x0E) >> 1) {
case 0x1:
ps += 250;
break;
case 0x2:
ps += 333;
break;
case 0x3:
ps += 500;
break;
case 0x4:
ps += 667;
break;
case 0x5:
ps += 750;
break;
}
t_rfc_ps = max(t_rfc_ps, ps);
}
}
debug("t_wtr_ps = %ld\n", t_wtr_ps);
t_wtr_clk = (MULDIV64(sdram_freq, t_wtr_ps, ONE_BILLION) + 999) / 1000;
debug("t_rfc_ps = %ld\n", t_rfc_ps);
t_rfc_clk = (MULDIV64(sdram_freq, t_rfc_ps, ONE_BILLION) + 999) / 1000;
mtsdram(DDR0_06, ddr0_06 | DDR0_06_TWTR_ENCODE(t_wtr_clk) |
DDR0_06_TRFC_ENCODE(t_rfc_clk));
}
static void program_ddr0_10(unsigned long dimm_ranks[], unsigned long ranks)
{
unsigned long csmap;
if (2 == ranks) {
/* Both chip selects in use */
csmap = 0x03;
} else {
/* One chip select in use */
csmap = (1 == dimm_ranks[0]) ? 0x1 : 0x2;
}
mtsdram(DDR0_10, DDR0_10_WRITE_MODEREG_ENCODE(0x0) |
DDR0_10_CS_MAP_ENCODE(csmap) |
DDR0_10_OCD_ADJUST_PUP_CS_0_ENCODE(0));
}
static void program_ddr0_11(unsigned long sdram_freq)
{
unsigned long const t_xsnr_ps = 200000; /* 200 ns */
unsigned long t_xsnr_clk;
debug("t_xsnr_ps = %ld\n", t_xsnr_ps);
t_xsnr_clk =
(MULDIV64(sdram_freq, t_xsnr_ps, ONE_BILLION) + 999) / 1000;
mtsdram(DDR0_11, DDR0_11_SREFRESH_ENCODE(0) |
DDR0_11_TXSNR_ENCODE(t_xsnr_clk) | DDR0_11_TXSR_ENCODE(200));
}
static void program_ddr0_22(unsigned long dimm_ranks[],
unsigned char const iic0_dimm_addr[],
unsigned long num_dimm_banks, unsigned long width)
{
#if defined(CONFIG_DDR_ECC)
unsigned long dimm_num;
unsigned long ecc_available = width >= 64;
u32 ddr0_22 = DDR0_22_DQS_OUT_SHIFT_BYPASS_ENCODE(0x26) |
DDR0_22_DQS_OUT_SHIFT_ENCODE(DQS_OUT_SHIFT) |
DDR0_22_DLL_DQS_BYPASS_8_ENCODE(DLL_DQS_BYPASS);
/* loop through all the DIMM slots on the board */
for (dimm_num = 0; dimm_num < num_dimm_banks; dimm_num++) {
/* If a dimm is installed in a particular slot ... */
if (dimm_ranks[dimm_num]) {
/* Check for ECC */
if (0 == (spd_read(iic0_dimm_addr[dimm_num], 11) &
0x02)) {
ecc_available = false;
}
}
}
if (ecc_available) {
debug("ECC found on all DIMMs present\n");
mtsdram(DDR0_22, ddr0_22 | DDR0_22_CTRL_RAW_ENCODE(0x3));
} else {
debug("ECC not found on some or all DIMMs present\n");
mtsdram(DDR0_22, ddr0_22 | DDR0_22_CTRL_RAW_ENCODE(0x0));
}
#else
mtsdram(DDR0_22, DDR0_22_CTRL_RAW_ENCODE(0x0) |
DDR0_22_DQS_OUT_SHIFT_BYPASS_ENCODE(0x26) |
DDR0_22_DQS_OUT_SHIFT_ENCODE(DQS_OUT_SHIFT) |
DDR0_22_DLL_DQS_BYPASS_8_ENCODE(DLL_DQS_BYPASS));
#endif /* defined(CONFIG_DDR_ECC) */
}
static void program_ddr0_24(unsigned long ranks)
{
u32 ddr0_24 = DDR0_24_RTT_PAD_TERMINATION_ENCODE(0x1) | /* 75 ohm */
DDR0_24_ODT_RD_MAP_CS1_ENCODE(0x0);
if (2 == ranks) {
/* Both chip selects in use */
ddr0_24 |= DDR0_24_ODT_WR_MAP_CS1_ENCODE(0x1) |
DDR0_24_ODT_WR_MAP_CS0_ENCODE(0x2);
} else {
/* One chip select in use */
/* One of the two fields added to ddr0_24 is a "don't care" */
ddr0_24 |= DDR0_24_ODT_WR_MAP_CS1_ENCODE(0x2) |
DDR0_24_ODT_WR_MAP_CS0_ENCODE(0x1);
}
mtsdram(DDR0_24, ddr0_24);
}
static void program_ddr0_26(unsigned long sdram_freq)
{
unsigned long const t_ref_ps = 7800000; /* 7.8 us. refresh */
/* TODO: check definition of tRAS_MAX */
unsigned long const t_ras_max_ps = 9 * t_ref_ps;
unsigned long t_ras_max_clk;
unsigned long t_ref_clk;
/* Round down t_ras_max_clk and t_ref_clk */
debug("t_ras_max_ps = %ld\n", t_ras_max_ps);
t_ras_max_clk = MULDIV64(sdram_freq, t_ras_max_ps, ONE_BILLION) / 1000;
debug("t_ref_ps = %ld\n", t_ref_ps);
t_ref_clk = MULDIV64(sdram_freq, t_ref_ps, ONE_BILLION) / 1000;
mtsdram(DDR0_26, DDR0_26_TRAS_MAX_ENCODE(t_ras_max_clk) |
DDR0_26_TREF_ENCODE(t_ref_clk));
}
static void program_ddr0_27(unsigned long sdram_freq)
{
unsigned long const t_init_ps = 200000000; /* 200 us. init */
unsigned long t_init_clk;
debug("t_init_ps = %ld\n", t_init_ps);
t_init_clk =
(MULDIV64(sdram_freq, t_init_ps, ONE_BILLION) + 999) / 1000;
mtsdram(DDR0_27, DDR0_27_EMRS_DATA_ENCODE(0x0000) |
DDR0_27_TINIT_ENCODE(t_init_clk));
}
static void program_ddr0_43(unsigned long dimm_ranks[],
unsigned char const iic0_dimm_addr[],
unsigned long num_dimm_banks,
unsigned long sdram_freq,
unsigned long cols, unsigned long banks)
{
unsigned long dimm_num;
unsigned long t_wr_ps = 0;
unsigned long t_wr_clk;
u32 ddr0_43 = DDR0_43_APREBIT_ENCODE(10) |
DDR0_43_COLUMN_SIZE_ENCODE(12 - cols) |
DDR0_43_EIGHT_BANK_MODE_ENCODE(8 == banks ? 1 : 0);
/*------------------------------------------------------------------
* Handle the timing. We need to find the worst case timing of all
* the dimm modules installed.
*-----------------------------------------------------------------*/
/* loop through all the DIMM slots on the board */
for (dimm_num = 0; dimm_num < num_dimm_banks; dimm_num++) {
/* If a dimm is installed in a particular slot ... */
if (dimm_ranks[dimm_num]) {
unsigned long ps;
ps = 250 * spd_read(iic0_dimm_addr[dimm_num], 36);
t_wr_ps = max(t_wr_ps, ps);
}
}
debug("t_wr_ps = %ld\n", t_wr_ps);
t_wr_clk = (MULDIV64(sdram_freq, t_wr_ps, ONE_BILLION) + 999) / 1000;
mtsdram(DDR0_43, ddr0_43 | DDR0_43_TWR_ENCODE(t_wr_clk));
}
static void program_ddr0_44(unsigned long dimm_ranks[],
unsigned char const iic0_dimm_addr[],
unsigned long num_dimm_banks,
unsigned long sdram_freq)
{
unsigned long dimm_num;
unsigned long t_rcd_ps = 0;
unsigned long t_rcd_clk;
/*------------------------------------------------------------------
* Handle the timing. We need to find the worst case timing of all
* the dimm modules installed.
*-----------------------------------------------------------------*/
/* loop through all the DIMM slots on the board */
for (dimm_num = 0; dimm_num < num_dimm_banks; dimm_num++) {
/* If a dimm is installed in a particular slot ... */
if (dimm_ranks[dimm_num]) {
unsigned long ps;
ps = 250 * spd_read(iic0_dimm_addr[dimm_num], 29);
t_rcd_ps = max(t_rcd_ps, ps);
}
}
debug("t_rcd_ps = %ld\n", t_rcd_ps);
t_rcd_clk = (MULDIV64(sdram_freq, t_rcd_ps, ONE_BILLION) + 999) / 1000;
mtsdram(DDR0_44, DDR0_44_TRCD_ENCODE(t_rcd_clk));
}
/*-----------------------------------------------------------------------------+
* initdram. Initializes the 440EPx/GPx DDR SDRAM controller.
* Note: This routine runs from flash with a stack set up in the chip's
* sram space. It is important that the routine does not require .sbss, .bss or
* .data sections. It also cannot call routines that require these sections.
*-----------------------------------------------------------------------------*/
/*-----------------------------------------------------------------------------
* Function: initdram
* Description: Configures SDRAM memory banks for DDR operation.
* Auto Memory Configuration option reads the DDR SDRAM EEPROMs
* via the IIC bus and then configures the DDR SDRAM memory
* banks appropriately. If Auto Memory Configuration is
* not used, it is assumed that no DIMM is plugged
*-----------------------------------------------------------------------------*/
phys_size_t initdram(int board_type)
{
unsigned char const iic0_dimm_addr[] = SPD_EEPROM_ADDRESS;
unsigned long dimm_ranks[MAXDIMMS];
unsigned long ranks;
unsigned long rows;
unsigned long banks;
unsigned long cols;
unsigned long width;
unsigned long const sdram_freq = get_bus_freq(0);
unsigned long const num_dimm_banks = sizeof(iic0_dimm_addr); /* on board dimm banks */
unsigned long cas_latency = 0; /* to quiet initialization warning */
unsigned long dram_size;
debug("\nEntering initdram()\n");
/*------------------------------------------------------------------
* Stop the DDR-SDRAM controller.
*-----------------------------------------------------------------*/
mtsdram(DDR0_02, DDR0_02_START_ENCODE(0));
/*
* Make sure I2C controller is initialized
* before continuing.
*/
/* switch to correct I2C bus */
i2c_set_bus_num(CONFIG_SYS_SPD_BUS_NUM);
/*------------------------------------------------------------------
* Clear out the serial presence detect buffers.
* Perform IIC reads from the dimm. Fill in the spds.
* Check to see if the dimm slots are populated
*-----------------------------------------------------------------*/
get_spd_info(dimm_ranks, &ranks, iic0_dimm_addr, num_dimm_banks);
/*------------------------------------------------------------------
* Check the frequency supported for the dimms plugged.
*-----------------------------------------------------------------*/
check_frequency(dimm_ranks, iic0_dimm_addr, num_dimm_banks, sdram_freq);
/*------------------------------------------------------------------
* Check and get size information.
*-----------------------------------------------------------------*/
get_dimm_size(dimm_ranks, iic0_dimm_addr, num_dimm_banks, &rows, &banks,
&cols, &width);
/*------------------------------------------------------------------
* Check the voltage type for the dimms plugged.
*-----------------------------------------------------------------*/
check_voltage_type(dimm_ranks, iic0_dimm_addr, num_dimm_banks);
/*------------------------------------------------------------------
* Program registers for SDRAM controller.
*-----------------------------------------------------------------*/
mtsdram(DDR0_00, DDR0_00_DLL_INCREMENT_ENCODE(0x19) |
DDR0_00_DLL_START_POINT_DECODE(0x0A));
mtsdram(DDR0_01, DDR0_01_PLB0_DB_CS_LOWER_ENCODE(0x01) |
DDR0_01_PLB0_DB_CS_UPPER_ENCODE(0x00) |
DDR0_01_INT_MASK_ENCODE(0xFF));
program_ddr0_03(dimm_ranks, iic0_dimm_addr, num_dimm_banks, sdram_freq,
rows, &cas_latency);
program_ddr0_04(dimm_ranks, iic0_dimm_addr, num_dimm_banks, sdram_freq);
program_ddr0_05(dimm_ranks, iic0_dimm_addr, num_dimm_banks, sdram_freq);
program_ddr0_06(dimm_ranks, iic0_dimm_addr, num_dimm_banks, sdram_freq);
/*
* TODO: tFAW not found in SPD. Value of 13 taken from Sequoia
* board SDRAM, but may be overly conservative.
*/
mtsdram(DDR0_07, DDR0_07_NO_CMD_INIT_ENCODE(0) |
DDR0_07_TFAW_ENCODE(13) |
DDR0_07_AUTO_REFRESH_MODE_ENCODE(1) |
DDR0_07_AREFRESH_ENCODE(0));
mtsdram(DDR0_08, DDR0_08_WRLAT_ENCODE(cas_latency - 1) |
DDR0_08_TCPD_ENCODE(200) | DDR0_08_DQS_N_EN_ENCODE(0) |
DDR0_08_DDRII_ENCODE(1));
mtsdram(DDR0_09, DDR0_09_OCD_ADJUST_PDN_CS_0_ENCODE(0x00) |
DDR0_09_RTT_0_ENCODE(0x1) |
DDR0_09_WR_DQS_SHIFT_BYPASS_ENCODE(0x1D) |
DDR0_09_WR_DQS_SHIFT_ENCODE(DQS_OUT_SHIFT - 0x20));
program_ddr0_10(dimm_ranks, ranks);
program_ddr0_11(sdram_freq);
mtsdram(DDR0_12, DDR0_12_TCKE_ENCODE(3));
mtsdram(DDR0_14, DDR0_14_DLL_BYPASS_MODE_ENCODE(0) |
DDR0_14_REDUC_ENCODE(width <= 40 ? 1 : 0) |
DDR0_14_REG_DIMM_ENABLE_ENCODE(0));
mtsdram(DDR0_17, DDR0_17_DLL_DQS_DELAY_0_ENCODE(DLL_DQS_DELAY));
mtsdram(DDR0_18, DDR0_18_DLL_DQS_DELAY_4_ENCODE(DLL_DQS_DELAY) |
DDR0_18_DLL_DQS_DELAY_3_ENCODE(DLL_DQS_DELAY) |
DDR0_18_DLL_DQS_DELAY_2_ENCODE(DLL_DQS_DELAY) |
DDR0_18_DLL_DQS_DELAY_1_ENCODE(DLL_DQS_DELAY));
mtsdram(DDR0_19, DDR0_19_DLL_DQS_DELAY_8_ENCODE(DLL_DQS_DELAY) |
DDR0_19_DLL_DQS_DELAY_7_ENCODE(DLL_DQS_DELAY) |
DDR0_19_DLL_DQS_DELAY_6_ENCODE(DLL_DQS_DELAY) |
DDR0_19_DLL_DQS_DELAY_5_ENCODE(DLL_DQS_DELAY));
mtsdram(DDR0_20, DDR0_20_DLL_DQS_BYPASS_3_ENCODE(DLL_DQS_BYPASS) |
DDR0_20_DLL_DQS_BYPASS_2_ENCODE(DLL_DQS_BYPASS) |
DDR0_20_DLL_DQS_BYPASS_1_ENCODE(DLL_DQS_BYPASS) |
DDR0_20_DLL_DQS_BYPASS_0_ENCODE(DLL_DQS_BYPASS));
mtsdram(DDR0_21, DDR0_21_DLL_DQS_BYPASS_7_ENCODE(DLL_DQS_BYPASS) |
DDR0_21_DLL_DQS_BYPASS_6_ENCODE(DLL_DQS_BYPASS) |
DDR0_21_DLL_DQS_BYPASS_5_ENCODE(DLL_DQS_BYPASS) |
DDR0_21_DLL_DQS_BYPASS_4_ENCODE(DLL_DQS_BYPASS));
program_ddr0_22(dimm_ranks, iic0_dimm_addr, num_dimm_banks, width);
mtsdram(DDR0_23, DDR0_23_ODT_RD_MAP_CS0_ENCODE(0x0) |
DDR0_23_FWC_ENCODE(0));
program_ddr0_24(ranks);
program_ddr0_26(sdram_freq);
program_ddr0_27(sdram_freq);
mtsdram(DDR0_28, DDR0_28_EMRS3_DATA_ENCODE(0x0000) |
DDR0_28_EMRS2_DATA_ENCODE(0x0000));
mtsdram(DDR0_31, DDR0_31_XOR_CHECK_BITS_ENCODE(0x0000));
mtsdram(DDR0_42, DDR0_42_ADDR_PINS_ENCODE(14 - rows) |
DDR0_42_CASLAT_LIN_GATE_ENCODE(2 * cas_latency));
program_ddr0_43(dimm_ranks, iic0_dimm_addr, num_dimm_banks, sdram_freq,
cols, banks);
program_ddr0_44(dimm_ranks, iic0_dimm_addr, num_dimm_banks, sdram_freq);
denali_sdram_register_dump();
dram_size = (width >= 64) ? 8 : 4;
dram_size *= 1 << cols;
dram_size *= banks;
dram_size *= 1 << rows;
dram_size *= ranks;
debug("dram_size = %lu\n", dram_size);
/* Start the SDRAM controler */
mtsdram(DDR0_02, DDR0_02_START_ENCODE(1));
denali_wait_for_dlllock();
#if defined(CONFIG_DDR_DATA_EYE)
/*
* Map the first 1 MiB of memory in the TLB, and perform the data eye
* search.
*/
program_tlb(0, CONFIG_SYS_SDRAM_BASE, TLB_1MB_SIZE, TLB_WORD2_I_ENABLE);
denali_core_search_data_eye();
denali_sdram_register_dump();
remove_tlb(CONFIG_SYS_SDRAM_BASE, TLB_1MB_SIZE);
#endif
#if defined(CONFIG_ZERO_SDRAM) || defined(CONFIG_DDR_ECC)
program_tlb(0, CONFIG_SYS_SDRAM_BASE, dram_size, 0);
sync();
/* Zero the memory */
debug("Zeroing SDRAM...");
#if defined(CONFIG_SYS_MEM_TOP_HIDE)
dcbz_area(CONFIG_SYS_SDRAM_BASE, dram_size - CONFIG_SYS_MEM_TOP_HIDE);
#else
#error Please define CONFIG_SYS_MEM_TOP_HIDE (see README) in your board config file
#endif
/* Write modified dcache lines back to memory */
clean_dcache_range(CONFIG_SYS_SDRAM_BASE, CONFIG_SYS_SDRAM_BASE + dram_size - CONFIG_SYS_MEM_TOP_HIDE);
debug("Completed\n");
sync();
remove_tlb(CONFIG_SYS_SDRAM_BASE, dram_size);
#if defined(CONFIG_DDR_ECC)
/*
* If ECC is enabled, clear and enable interrupts
*/
if (is_ecc_enabled()) {
u32 val;
sync();
/* Clear error status */
mfsdram(DDR0_00, val);
mtsdram(DDR0_00, val | DDR0_00_INT_ACK_ALL);
/* Set 'int_mask' parameter to functionnal value */
mfsdram(DDR0_01, val);
mtsdram(DDR0_01, (val & ~DDR0_01_INT_MASK_MASK) |
DDR0_01_INT_MASK_ALL_OFF);
#if defined(CONFIG_DDR_DATA_EYE)
/*
* Running denali_core_search_data_eye() when ECC is enabled
* causes non-ECC machine checks. This clears them.
*/
print_mcsr();
mtspr(SPRN_MCSR, mfspr(SPRN_MCSR));
print_mcsr();
#endif
sync();
}
#endif /* defined(CONFIG_DDR_ECC) */
#endif /* defined(CONFIG_ZERO_SDRAM) || defined(CONFIG_DDR_ECC) */
program_tlb(0, CONFIG_SYS_SDRAM_BASE, dram_size, MY_TLB_WORD2_I_ENABLE);
return dram_size;
}
void board_add_ram_info(int use_default)
{
u32 val;
printf(" (ECC");
if (!is_ecc_enabled()) {
printf(" not");
}
printf(" enabled, %ld MHz", (2 * get_bus_freq(0)) / 1000000);
mfsdram(DDR0_03, val);
printf(", CL%d)", DDR0_03_CASLAT_LIN_DECODE(val) >> 1);
}
#endif /* CONFIG_SPD_EEPROM */
| gpl-2.0 |
rhuitl/uClinux | user/pppd/solaris/ppp_comp_mod.c | 2348 | /*
* ppp_comp_mod.c - modload support for PPP compression STREAMS module.
*
* Copyright (c) 1994 Paul Mackerras. All rights reserved.
*
* 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. The name(s) of the authors of this software must not be used to
* endorse or promote products derived from this software without
* prior written permission.
*
* 4. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by Paul Mackerras
* <[email protected]>".
*
* THE AUTHORS OF THIS SOFTWARE DISCLAIM ALL WARRANTIES WITH REGARD TO
* THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS, IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY
* SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
* AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
* OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* $Id: ppp_comp_mod.c,v 1.2 2002/12/06 09:49:16 paulus Exp $
*/
/*
* This file is used under Solaris 2.
*/
#include <sys/types.h>
#include <sys/param.h>
#include <sys/conf.h>
#include <sys/modctl.h>
#include <sys/sunddi.h>
extern struct streamtab ppp_compinfo;
static struct fmodsw fsw = {
"ppp_comp",
&ppp_compinfo,
D_NEW | D_MP | D_MTQPAIR
};
extern struct mod_ops mod_strmodops;
static struct modlstrmod modlstrmod = {
&mod_strmodops,
"PPP compression module",
&fsw
};
static struct modlinkage modlinkage = {
MODREV_1,
(void *) &modlstrmod,
NULL
};
/*
* Entry points for modloading.
*/
int
_init(void)
{
return mod_install(&modlinkage);
}
int
_fini(void)
{
return mod_remove(&modlinkage);
}
int
_info(mip)
struct modinfo *mip;
{
return mod_info(&modlinkage, mip);
}
| gpl-2.0 |
s20121035/rk3288_android5.1_repo | external/chromium_org/chrome/browser/ui/panels/panel_mouse_watcher_unittest.cc | 2240 | // Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/memory/scoped_ptr.h"
#include "base/message_loop/message_loop.h"
#include "chrome/browser/ui/panels/panel_mouse_watcher.h"
#include "chrome/browser/ui/panels/panel_mouse_watcher_observer.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/gfx/point.h"
class TestMouseObserver : public PanelMouseWatcherObserver {
public:
TestMouseObserver() : mouse_movements_(0) {}
// Overridden from PanelMouseWatcherObserver:
virtual void OnMouseMove(const gfx::Point& mouse_position) OVERRIDE {
++mouse_movements_;
}
int mouse_movements_;
};
class PanelMouseWatcherTest : public testing::Test {
};
TEST_F(PanelMouseWatcherTest, StartStopWatching) {
base::MessageLoopForUI loop;
scoped_ptr<PanelMouseWatcher> watcher(PanelMouseWatcher::Create());
EXPECT_FALSE(watcher->IsActive());
scoped_ptr<TestMouseObserver> user1(new TestMouseObserver());
scoped_ptr<TestMouseObserver> user2(new TestMouseObserver());
// No observers.
watcher->NotifyMouseMovement(gfx::Point(42, 101));
EXPECT_EQ(0, user1->mouse_movements_);
EXPECT_EQ(0, user2->mouse_movements_);
// Only one mouse observer.
watcher->AddObserver(user1.get());
EXPECT_TRUE(watcher->IsActive());
watcher->NotifyMouseMovement(gfx::Point(42, 101));
EXPECT_GE(user1->mouse_movements_, 1);
EXPECT_EQ(0, user2->mouse_movements_);
watcher->RemoveObserver(user1.get());
EXPECT_FALSE(watcher->IsActive());
// More than one mouse observer.
watcher->AddObserver(user1.get());
EXPECT_TRUE(watcher->IsActive());
watcher->AddObserver(user2.get());
watcher->NotifyMouseMovement(gfx::Point(101, 42));
EXPECT_GE(user1->mouse_movements_, 2);
EXPECT_GE(user2->mouse_movements_, 1);
// Back to one observer.
watcher->RemoveObserver(user1.get());
EXPECT_TRUE(watcher->IsActive());
int saved_count = user1->mouse_movements_;
watcher->NotifyMouseMovement(gfx::Point(1, 2));
EXPECT_EQ(saved_count, user1->mouse_movements_);
EXPECT_GE(user2->mouse_movements_, 2);
watcher->RemoveObserver(user2.get());
EXPECT_FALSE(watcher->IsActive());
}
| gpl-3.0 |
mikedlowis-prototypes/albase | source/kernel/drivers/clk/shmobile/renesas-cpg-mssr.c | 13874 | /*
* Renesas Clock Pulse Generator / Module Standby and Software Reset
*
* Copyright (C) 2015 Glider bvba
*
* Based on clk-mstp.c, clk-rcar-gen2.c, and clk-rcar-gen3.c
*
* Copyright (C) 2013 Ideas On Board SPRL
* Copyright (C) 2015 Renesas Electronics Corp.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 2 of the License.
*/
#include <linux/clk.h>
#include <linux/clk-provider.h>
#include <linux/device.h>
#include <linux/init.h>
#include <linux/mod_devicetable.h>
#include <linux/module.h>
#include <linux/of_address.h>
#include <linux/of_device.h>
#include <linux/platform_device.h>
#include <linux/pm_clock.h>
#include <linux/pm_domain.h>
#include <linux/slab.h>
#include <dt-bindings/clock/renesas-cpg-mssr.h>
#include "renesas-cpg-mssr.h"
#include "clk-div6.h"
#ifdef DEBUG
#define WARN_DEBUG(x) do { } while (0)
#else
#define WARN_DEBUG(x) WARN_ON(x)
#endif
/*
* Module Standby and Software Reset register offets.
*
* If the registers exist, these are valid for SH-Mobile, R-Mobile,
* R-Car Gen 2, and R-Car Gen 3.
* These are NOT valid for R-Car Gen1 and RZ/A1!
*/
/*
* Module Stop Status Register offsets
*/
static const u16 mstpsr[] = {
0x030, 0x038, 0x040, 0x048, 0x04C, 0x03C, 0x1C0, 0x1C4,
0x9A0, 0x9A4, 0x9A8, 0x9AC,
};
#define MSTPSR(i) mstpsr[i]
/*
* System Module Stop Control Register offsets
*/
static const u16 smstpcr[] = {
0x130, 0x134, 0x138, 0x13C, 0x140, 0x144, 0x148, 0x14C,
0x990, 0x994, 0x998, 0x99C,
};
#define SMSTPCR(i) smstpcr[i]
/*
* Software Reset Register offsets
*/
static const u16 srcr[] = {
0x0A0, 0x0A8, 0x0B0, 0x0B8, 0x0BC, 0x0C4, 0x1C8, 0x1CC,
0x920, 0x924, 0x928, 0x92C,
};
#define SRCR(i) srcr[i]
/* Realtime Module Stop Control Register offsets */
#define RMSTPCR(i) (smstpcr[i] - 0x20)
/* Modem Module Stop Control Register offsets (r8a73a4) */
#define MMSTPCR(i) (smstpcr[i] + 0x20)
/* Software Reset Clearing Register offsets */
#define SRSTCLR(i) (0x940 + (i) * 4)
/**
* Clock Pulse Generator / Module Standby and Software Reset Private Data
*
* @dev: CPG/MSSR device
* @base: CPG/MSSR register block base address
* @mstp_lock: protects writes to SMSTPCR
* @clks: Array containing all Core and Module Clocks
* @num_core_clks: Number of Core Clocks in clks[]
* @num_mod_clks: Number of Module Clocks in clks[]
* @last_dt_core_clk: ID of the last Core Clock exported to DT
*/
struct cpg_mssr_priv {
struct device *dev;
void __iomem *base;
spinlock_t mstp_lock;
struct clk **clks;
unsigned int num_core_clks;
unsigned int num_mod_clks;
unsigned int last_dt_core_clk;
};
/**
* struct mstp_clock - MSTP gating clock
* @hw: handle between common and hardware-specific interfaces
* @index: MSTP clock number
* @priv: CPG/MSSR private data
*/
struct mstp_clock {
struct clk_hw hw;
u32 index;
struct cpg_mssr_priv *priv;
};
#define to_mstp_clock(_hw) container_of(_hw, struct mstp_clock, hw)
static int cpg_mstp_clock_endisable(struct clk_hw *hw, bool enable)
{
struct mstp_clock *clock = to_mstp_clock(hw);
struct cpg_mssr_priv *priv = clock->priv;
unsigned int reg = clock->index / 32;
unsigned int bit = clock->index % 32;
struct device *dev = priv->dev;
u32 bitmask = BIT(bit);
unsigned long flags;
unsigned int i;
u32 value;
dev_dbg(dev, "MSTP %u%02u/%pC %s\n", reg, bit, hw->clk,
enable ? "ON" : "OFF");
spin_lock_irqsave(&priv->mstp_lock, flags);
value = clk_readl(priv->base + SMSTPCR(reg));
if (enable)
value &= ~bitmask;
else
value |= bitmask;
clk_writel(value, priv->base + SMSTPCR(reg));
spin_unlock_irqrestore(&priv->mstp_lock, flags);
if (!enable)
return 0;
for (i = 1000; i > 0; --i) {
if (!(clk_readl(priv->base + MSTPSR(reg)) &
bitmask))
break;
cpu_relax();
}
if (!i) {
dev_err(dev, "Failed to enable SMSTP %p[%d]\n",
priv->base + SMSTPCR(reg), bit);
return -ETIMEDOUT;
}
return 0;
}
static int cpg_mstp_clock_enable(struct clk_hw *hw)
{
return cpg_mstp_clock_endisable(hw, true);
}
static void cpg_mstp_clock_disable(struct clk_hw *hw)
{
cpg_mstp_clock_endisable(hw, false);
}
static int cpg_mstp_clock_is_enabled(struct clk_hw *hw)
{
struct mstp_clock *clock = to_mstp_clock(hw);
struct cpg_mssr_priv *priv = clock->priv;
u32 value;
value = clk_readl(priv->base + MSTPSR(clock->index / 32));
return !(value & BIT(clock->index % 32));
}
static const struct clk_ops cpg_mstp_clock_ops = {
.enable = cpg_mstp_clock_enable,
.disable = cpg_mstp_clock_disable,
.is_enabled = cpg_mstp_clock_is_enabled,
};
static
struct clk *cpg_mssr_clk_src_twocell_get(struct of_phandle_args *clkspec,
void *data)
{
unsigned int clkidx = clkspec->args[1];
struct cpg_mssr_priv *priv = data;
struct device *dev = priv->dev;
unsigned int idx;
const char *type;
struct clk *clk;
switch (clkspec->args[0]) {
case CPG_CORE:
type = "core";
if (clkidx > priv->last_dt_core_clk) {
dev_err(dev, "Invalid %s clock index %u\n", type,
clkidx);
return ERR_PTR(-EINVAL);
}
clk = priv->clks[clkidx];
break;
case CPG_MOD:
type = "module";
idx = MOD_CLK_PACK(clkidx);
if (clkidx % 100 > 31 || idx >= priv->num_mod_clks) {
dev_err(dev, "Invalid %s clock index %u\n", type,
clkidx);
return ERR_PTR(-EINVAL);
}
clk = priv->clks[priv->num_core_clks + idx];
break;
default:
dev_err(dev, "Invalid CPG clock type %u\n", clkspec->args[0]);
return ERR_PTR(-EINVAL);
}
if (IS_ERR(clk))
dev_err(dev, "Cannot get %s clock %u: %ld", type, clkidx,
PTR_ERR(clk));
else
dev_dbg(dev, "clock (%u, %u) is %pC at %pCr Hz\n",
clkspec->args[0], clkspec->args[1], clk, clk);
return clk;
}
static void __init cpg_mssr_register_core_clk(const struct cpg_core_clk *core,
const struct cpg_mssr_info *info,
struct cpg_mssr_priv *priv)
{
struct clk *clk = NULL, *parent;
struct device *dev = priv->dev;
unsigned int id = core->id;
const char *parent_name;
WARN_DEBUG(id >= priv->num_core_clks);
WARN_DEBUG(PTR_ERR(priv->clks[id]) != -ENOENT);
switch (core->type) {
case CLK_TYPE_IN:
clk = of_clk_get_by_name(priv->dev->of_node, core->name);
break;
case CLK_TYPE_FF:
case CLK_TYPE_DIV6P1:
WARN_DEBUG(core->parent >= priv->num_core_clks);
parent = priv->clks[core->parent];
if (IS_ERR(parent)) {
clk = parent;
goto fail;
}
parent_name = __clk_get_name(parent);
if (core->type == CLK_TYPE_FF) {
clk = clk_register_fixed_factor(NULL, core->name,
parent_name, 0,
core->mult, core->div);
} else {
clk = cpg_div6_register(core->name, 1, &parent_name,
priv->base + core->offset);
}
break;
default:
if (info->cpg_clk_register)
clk = info->cpg_clk_register(dev, core, info,
priv->clks, priv->base);
else
dev_err(dev, "%s has unsupported core clock type %u\n",
core->name, core->type);
break;
}
if (IS_ERR_OR_NULL(clk))
goto fail;
dev_dbg(dev, "Core clock %pC at %pCr Hz\n", clk, clk);
priv->clks[id] = clk;
return;
fail:
dev_err(dev, "Failed to register %s clock %s: %ld\n", "core,",
core->name, PTR_ERR(clk));
}
static void __init cpg_mssr_register_mod_clk(const struct mssr_mod_clk *mod,
const struct cpg_mssr_info *info,
struct cpg_mssr_priv *priv)
{
struct mstp_clock *clock = NULL;
struct device *dev = priv->dev;
unsigned int id = mod->id;
struct clk_init_data init;
struct clk *parent, *clk;
const char *parent_name;
unsigned int i;
WARN_DEBUG(id < priv->num_core_clks);
WARN_DEBUG(id >= priv->num_core_clks + priv->num_mod_clks);
WARN_DEBUG(mod->parent >= priv->num_core_clks + priv->num_mod_clks);
WARN_DEBUG(PTR_ERR(priv->clks[id]) != -ENOENT);
parent = priv->clks[mod->parent];
if (IS_ERR(parent)) {
clk = parent;
goto fail;
}
clock = kzalloc(sizeof(*clock), GFP_KERNEL);
if (!clock) {
clk = ERR_PTR(-ENOMEM);
goto fail;
}
init.name = mod->name;
init.ops = &cpg_mstp_clock_ops;
init.flags = CLK_IS_BASIC | CLK_SET_RATE_PARENT;
for (i = 0; i < info->num_crit_mod_clks; i++)
if (id == info->crit_mod_clks[i]) {
#ifdef CLK_ENABLE_HAND_OFF
dev_dbg(dev, "MSTP %s setting CLK_ENABLE_HAND_OFF\n",
mod->name);
init.flags |= CLK_ENABLE_HAND_OFF;
break;
#else
dev_dbg(dev, "Ignoring MSTP %s to prevent disabling\n",
mod->name);
return;
#endif
}
parent_name = __clk_get_name(parent);
init.parent_names = &parent_name;
init.num_parents = 1;
clock->index = id - priv->num_core_clks;
clock->priv = priv;
clock->hw.init = &init;
clk = clk_register(NULL, &clock->hw);
if (IS_ERR(clk))
goto fail;
dev_dbg(dev, "Module clock %pC at %pCr Hz\n", clk, clk);
priv->clks[id] = clk;
return;
fail:
dev_err(dev, "Failed to register %s clock %s: %ld\n", "module,",
mod->name, PTR_ERR(clk));
kfree(clock);
}
#ifdef CONFIG_PM_GENERIC_DOMAINS_OF
struct cpg_mssr_clk_domain {
struct generic_pm_domain genpd;
struct device_node *np;
unsigned int num_core_pm_clks;
unsigned int core_pm_clks[0];
};
static bool cpg_mssr_is_pm_clk(const struct of_phandle_args *clkspec,
struct cpg_mssr_clk_domain *pd)
{
unsigned int i;
if (clkspec->np != pd->np || clkspec->args_count != 2)
return false;
switch (clkspec->args[0]) {
case CPG_CORE:
for (i = 0; i < pd->num_core_pm_clks; i++)
if (clkspec->args[1] == pd->core_pm_clks[i])
return true;
return false;
case CPG_MOD:
return true;
default:
return false;
}
}
static int cpg_mssr_attach_dev(struct generic_pm_domain *genpd,
struct device *dev)
{
struct cpg_mssr_clk_domain *pd =
container_of(genpd, struct cpg_mssr_clk_domain, genpd);
struct device_node *np = dev->of_node;
struct of_phandle_args clkspec;
struct clk *clk;
int i = 0;
int error;
while (!of_parse_phandle_with_args(np, "clocks", "#clock-cells", i,
&clkspec)) {
if (cpg_mssr_is_pm_clk(&clkspec, pd))
goto found;
of_node_put(clkspec.np);
i++;
}
return 0;
found:
clk = of_clk_get_from_provider(&clkspec);
of_node_put(clkspec.np);
if (IS_ERR(clk))
return PTR_ERR(clk);
error = pm_clk_create(dev);
if (error) {
dev_err(dev, "pm_clk_create failed %d\n", error);
goto fail_put;
}
error = pm_clk_add_clk(dev, clk);
if (error) {
dev_err(dev, "pm_clk_add_clk %pC failed %d\n", clk, error);
goto fail_destroy;
}
return 0;
fail_destroy:
pm_clk_destroy(dev);
fail_put:
clk_put(clk);
return error;
}
static void cpg_mssr_detach_dev(struct generic_pm_domain *genpd,
struct device *dev)
{
if (!list_empty(&dev->power.subsys_data->clock_list))
pm_clk_destroy(dev);
}
static int __init cpg_mssr_add_clk_domain(struct device *dev,
const unsigned int *core_pm_clks,
unsigned int num_core_pm_clks)
{
struct device_node *np = dev->of_node;
struct generic_pm_domain *genpd;
struct cpg_mssr_clk_domain *pd;
size_t pm_size = num_core_pm_clks * sizeof(core_pm_clks[0]);
pd = devm_kzalloc(dev, sizeof(*pd) + pm_size, GFP_KERNEL);
if (!pd)
return -ENOMEM;
pd->np = np;
pd->num_core_pm_clks = num_core_pm_clks;
memcpy(pd->core_pm_clks, core_pm_clks, pm_size);
genpd = &pd->genpd;
genpd->name = np->name;
genpd->flags = GENPD_FLAG_PM_CLK;
pm_genpd_init(genpd, &simple_qos_governor, false);
genpd->attach_dev = cpg_mssr_attach_dev;
genpd->detach_dev = cpg_mssr_detach_dev;
of_genpd_add_provider_simple(np, genpd);
return 0;
}
#else
static inline int cpg_mssr_add_clk_domain(struct device *dev,
const unsigned int *core_pm_clks,
unsigned int num_core_pm_clks)
{
return 0;
}
#endif /* !CONFIG_PM_GENERIC_DOMAINS_OF */
static const struct of_device_id cpg_mssr_match[] = {
#ifdef CONFIG_ARCH_R8A7795
{
.compatible = "renesas,r8a7795-cpg-mssr",
.data = &r8a7795_cpg_mssr_info,
},
#endif
{ /* sentinel */ }
};
static void cpg_mssr_del_clk_provider(void *data)
{
of_clk_del_provider(data);
}
static int __init cpg_mssr_probe(struct platform_device *pdev)
{
struct device *dev = &pdev->dev;
struct device_node *np = dev->of_node;
const struct cpg_mssr_info *info;
struct cpg_mssr_priv *priv;
unsigned int nclks, i;
struct resource *res;
struct clk **clks;
int error;
info = of_match_node(cpg_mssr_match, np)->data;
if (info->init) {
error = info->init(dev);
if (error)
return error;
}
priv = devm_kzalloc(dev, sizeof(*priv), GFP_KERNEL);
if (!priv)
return -ENOMEM;
priv->dev = dev;
spin_lock_init(&priv->mstp_lock);
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
priv->base = devm_ioremap_resource(dev, res);
if (IS_ERR(priv->base))
return PTR_ERR(priv->base);
nclks = info->num_total_core_clks + info->num_hw_mod_clks;
clks = devm_kmalloc_array(dev, nclks, sizeof(*clks), GFP_KERNEL);
if (!clks)
return -ENOMEM;
priv->clks = clks;
priv->num_core_clks = info->num_total_core_clks;
priv->num_mod_clks = info->num_hw_mod_clks;
priv->last_dt_core_clk = info->last_dt_core_clk;
for (i = 0; i < nclks; i++)
clks[i] = ERR_PTR(-ENOENT);
for (i = 0; i < info->num_core_clks; i++)
cpg_mssr_register_core_clk(&info->core_clks[i], info, priv);
for (i = 0; i < info->num_mod_clks; i++)
cpg_mssr_register_mod_clk(&info->mod_clks[i], info, priv);
error = of_clk_add_provider(np, cpg_mssr_clk_src_twocell_get, priv);
if (error)
return error;
devm_add_action(dev, cpg_mssr_del_clk_provider, np);
error = cpg_mssr_add_clk_domain(dev, info->core_pm_clks,
info->num_core_pm_clks);
if (error)
return error;
return 0;
}
static struct platform_driver cpg_mssr_driver = {
.driver = {
.name = "renesas-cpg-mssr",
.of_match_table = cpg_mssr_match,
},
};
static int __init cpg_mssr_init(void)
{
return platform_driver_probe(&cpg_mssr_driver, cpg_mssr_probe);
}
subsys_initcall(cpg_mssr_init);
MODULE_DESCRIPTION("Renesas CPG/MSSR Driver");
MODULE_LICENSE("GPL v2");
| bsd-2-clause |
kiwi89/cdnjs | ajax/libs/bagjs/1.0.0/bag.js | 24235 | /*
* bag.js - js/css/other loader + kv storage
*
* Copyright 2013-2014 Vitaly Puzrin
* https://github.com/nodeca/bag.js
*
* License MIT
*/
/*global define*/
(function (root, factory) {
'use strict';
if (typeof define === 'function' && define.amd) {
define(factory);
} else if (typeof module === 'object' && typeof module.exports === 'object') {
module.exports = factory();
} else {
root.Bag = factory();
}
} (this, function () {
'use strict';
var head = document.head || document.getElementsByTagName('head')[0];
//////////////////////////////////////////////////////////////////////////////
// helpers
function _nope() { return; }
function _isString(obj) {
return Object.prototype.toString.call(obj) === '[object String]';
}
var _isArray = Array.isArray || function isArray(obj) {
return Object.prototype.toString.call(obj) === '[object Array]';
};
function _isFunction(obj) {
return Object.prototype.toString.call(obj) === '[object Function]';
}
function _each(obj, iterator) {
if (_isArray(obj)) {
if (obj.forEach) {
return obj.forEach(iterator);
}
for (var i = 0; i < obj.length; i++) {
iterator(obj[i], i, obj);
}
} else {
for (var k in obj) {
if (Object.prototype.hasOwnProperty.call(obj, k)) {
iterator(obj[k], k);
}
}
}
}
function _default(obj, src) {
// extend obj with src properties if not exists;
_each(src, function (val, key) {
if (!obj[key]) { obj[key] = src[key]; }
});
}
function _asyncEach(arr, iterator, callback) {
callback = callback || _nope;
if (!arr.length) { return callback(); }
var completed = 0;
_each(arr, function (x) {
iterator(x, function (err) {
if (err) {
callback(err);
callback = _nope;
} else {
completed += 1;
if (completed >= arr.length) {
callback();
}
}
});
});
}
//////////////////////////////////////////////////////////////////////////////
// Adapters for Store class
function DomStorage(namespace) {
var self = this;
var _ns = namespace + '__';
var _storage = localStorage;
this.init = function (callback) {
callback();
};
this.remove = function (key, callback) {
callback = callback || _nope;
_storage.removeItem(_ns + key);
callback();
};
this.set = function (key, value, expire, callback) {
var obj = {
value: value,
expire: expire
};
var err;
try {
_storage.setItem(_ns + key, JSON.stringify(obj));
} catch (e) {
// On quota error try to reset storage & try again.
// Just remove all keys, without conditions, no optimizations needed.
if (e.name.toUpperCase().indexOf('QUOTA') >= 0) {
try {
_each(_storage, function (val, name) {
var k = name.split(_ns)[1];
if (k) { self.remove(k); }
});
_storage.setItem(_ns + key, JSON.stringify(obj));
} catch (e2) {
err = e2;
}
} else {
err = e;
}
}
callback(err);
};
this.get = function (key, raw, callback) {
if (_isFunction(raw)) {
callback = raw;
raw = false;
}
var err, data;
try {
data = JSON.parse(_storage.getItem(_ns + key));
data = raw ? data : data.value;
} catch (e) {
err = new Error('Can\'t read key: ' + key);
}
callback(err, data);
};
this.clear = function (expiredOnly, callback) {
var now = +new Date();
_each(_storage, function (val, name) {
var key = name.split(_ns)[1];
if (!key) { return; }
if (!expiredOnly) {
self.remove(key);
return;
}
var raw;
self.get(key, true, function (__, data) {
raw = data; // can use this hack, because get is sync;
});
if (raw && (raw.expire > 0) && ((raw.expire - now) < 0)) {
self.remove(key);
}
});
callback();
};
}
DomStorage.prototype.exists = function () {
try {
localStorage.setItem('__ls_test__', '__ls_test__');
localStorage.removeItem('__ls_test__');
return true;
} catch (e) {
return false;
}
};
function WebSql(namespace) {
var db;
this.init = function (callback) {
db = window.openDatabase(namespace, '1.0', 'bag.js db', 2e5);
if (!db) { return callback('Can\'t open webdql database'); }
db.transaction(function (tx) {
tx.executeSql(
'CREATE TABLE IF NOT EXISTS kv (key TEXT PRIMARY KEY, value TEXT, expire INTEGER KEY)',
[],
function () { return callback(); },
function (tx, err) { return callback(err); }
);
});
};
this.remove = function (key, callback) {
callback = callback || _nope;
db.transaction(function (tx) {
tx.executeSql(
'DELETE FROM kv WHERE key = ?',
[ key ],
function () { return callback(); },
function (tx, err) { return callback(err); }
);
});
};
this.set = function (key, value, expire, callback) {
db.transaction(function (tx) {
tx.executeSql(
'INSERT OR REPLACE INTO kv (key, value, expire) VALUES (?, ?, ?)',
[ key, JSON.stringify(value), expire ],
function () { return callback(); },
function (tx, err) { return callback(err); }
);
});
};
this.get = function (key, callback) {
db.readTransaction(function (tx) {
tx.executeSql(
'SELECT value FROM kv WHERE key = ?',
[ key ],
function (tx, result) {
if (result.rows.length === 0) {
return callback(new Error('key not found: ' + key));
}
var value = result.rows.item(0).value;
var err, data;
try {
data = JSON.parse(value);
} catch (e) {
err = new Error('Can\'t unserialise data: ' + value);
}
callback(err, data);
},
function (tx, err) { return callback(err); }
);
});
};
this.clear = function (expiredOnly, callback) {
db.transaction(function (tx) {
if (expiredOnly) {
tx.executeSql(
'DELETE FROM kv WHERE expire > 0 AND expire < ?',
[ +new Date() ],
function () { return callback(); },
function (tx, err) { return callback(err); }
);
} else {
db.transaction(function (tx) {
tx.executeSql(
'DELETE FROM kv',
[],
function () { return callback(); },
function (tx, err) { return callback(err); }
);
});
}
});
};
}
WebSql.prototype.exists = function () {
return (!!window.openDatabase);
};
function Idb(namespace) {
var db;
this.init = function (callback) {
var idb = this.idb = window.indexedDB; /* || window.webkitIndexedDB ||
window.mozIndexedDB || window.msIndexedDB;*/
var req = idb.open(namespace, 2 /*version*/);
req.onsuccess = function (e) {
db = e.target.result;
callback();
};
req.onblocked = function (e) {
callback(new Error('IndexedDB blocked. ' + e.target.errorCode));
};
req.onerror = function (e) {
callback(new Error('IndexedDB opening error. ' + e.target.errorCode));
};
req.onupgradeneeded = function (e) {
db = e.target.result;
if (db.objectStoreNames.contains('kv')) {
db.deleteObjectStore('kv');
}
var store = db.createObjectStore('kv', { keyPath: 'key' });
store.createIndex('expire', 'expire', { unique: false });
};
};
this.remove = function (key, callback) {
var tx = db.transaction('kv', 'readwrite');
tx.oncomplete = function () { callback(); };
tx.onerror = tx.onabort = function (e) { callback(new Error('Key remove error: ', e.target)); };
// IE 8 not allow to use reserved keywords as functions. More info:
// http://tiffanybbrown.com/2013/09/10/expected-identifier-bug-in-internet-explorer-8/
tx.objectStore('kv')['delete'](key).onerror = function () { tx.abort(); };
};
this.set = function (key, value, expire, callback) {
var tx = db.transaction('kv', 'readwrite');
tx.oncomplete = function () { callback(); };
tx.onerror = tx.onabort = function (e) { callback(new Error('Key set error: ', e.target)); };
tx.objectStore('kv').put({
key: key,
value: value,
expire: expire
}).onerror = function () { tx.abort(); };
};
this.get = function (key, callback) {
var err, result;
var tx = db.transaction('kv');
tx.oncomplete = function () { callback(err, result); };
tx.onerror = tx.onabort = function (e) { callback(new Error('Key get error: ', e.target)); };
tx.objectStore('kv').get(key).onsuccess = function (e) {
if (e.target.result) {
result = e.target.result.value;
} else {
err = new Error('key not found: ' + key);
}
};
};
this.clear = function (expiredOnly, callback) {
var keyrange = window.IDBKeyRange; /* ||
window.webkitIDBKeyRange || window.msIDBKeyRange;*/
var tx, store;
tx = db.transaction('kv', 'readwrite');
store = tx.objectStore('kv');
tx.oncomplete = function () { callback(); };
tx.onerror = tx.onabort = function (e) { callback(new Error('Clear error: ', e.target)); };
if (expiredOnly) {
var cursor = store.index('expire').openCursor(keyrange.bound(1, +new Date()));
cursor.onsuccess = function (e) {
var _cursor = e.target.result;
if (_cursor) {
// IE 8 not allow to use reserved keywords as functions (`delete` and `continue`). More info:
// http://tiffanybbrown.com/2013/09/10/expected-identifier-bug-in-internet-explorer-8/
store['delete'](_cursor.primaryKey).onerror = function () { tx.abort(); };
_cursor['continue']();
}
};
} else {
// Just clear everything
tx.objectStore('kv').clear().onerror = function () { tx.abort(); };
}
};
}
Idb.prototype.exists = function () {
var db = window.indexedDB /*||
window.webkitIndexedDB ||
window.mozIndexedDB ||
window.msIndexedDB*/;
if (!db) {
return false;
}
// Check outdated idb implementations, where `onupgradeneede` event doesn't work,
// see https://github.com/pouchdb/pouchdb/issues/1207 for more details
var dbName = '__idb_test__';
var result = db.open(dbName, 1).onupgradeneeded === null;
if (db.deleteDatabase) {
db.deleteDatabase(dbName);
}
return result;
};
/////////////////////////////////////////////////////////////////////////////
// key/value storage with expiration
var storeAdapters = {
indexeddb: Idb,
websql: WebSql,
localstorage: DomStorage
};
// namespace - db name or similar
// storesList - array of allowed adapter names to use
//
function Storage(namespace, storesList) {
var self = this;
var db = null;
// States of db init singletone process
// 'done' / 'progress' / 'failed' / undefined
var initState;
var initStack = [];
_each(storesList, function (name) {
// do storage names case insensitive
name = name.toLowerCase();
if (!storeAdapters[name]) {
throw new Error('Wrong storage adapter name: ' + name, storesList);
}
if (storeAdapters[name].prototype.exists() && !db) {
db = new storeAdapters[name](namespace);
return false; // terminate search on first success
}
});
if (!db) {
/* eslint-disable no-console */
// If no adaprets - don't make error for correct fallback.
// Just log that we continue work without storing results.
if (typeof console !== 'undefined' && console.log) {
console.log('None of requested storages available: ' + storesList);
}
/* eslint-enable no-console */
}
this.init = function (callback) {
if (!db) {
callback(new Error('No available db'));
return;
}
if (initState === 'done') {
callback();
return;
}
if (initState === 'progress') {
initStack.push(callback);
return;
}
initStack.push(callback);
initState = 'progress';
db.init(function (err) {
initState = !err ? 'done' : 'failed';
_each(initStack, function (cb) {
cb(err);
});
initStack = [];
// Clear expired. A bit dirty without callback,
// but we don't care until clear compleete
if (!err) { self.clear(true); }
});
};
this.set = function (key, value, expire, callback) {
if (_isFunction(expire)) {
callback = expire;
expire = null;
}
callback = callback || _nope;
expire = expire ? +(new Date()) + (expire * 1000) : 0;
this.init(function (err) {
if (err) { return callback(err); }
db.set(key, value, expire, callback);
});
};
this.get = function (key, callback) {
this.init(function (err) {
if (err) { return callback(err); }
db.get(key, callback);
});
};
this.remove = function (key, callback) {
callback = callback || _nope;
this.init(function (err) {
if (err) { return callback(err); }
db.remove(key, callback);
});
};
this.clear = function (expiredOnly, callback) {
if (_isFunction(expiredOnly)) {
callback = expiredOnly;
expiredOnly = false;
}
callback = callback || _nope;
this.init(function (err) {
if (err) { return callback(err); }
db.clear(expiredOnly, callback);
});
};
}
//////////////////////////////////////////////////////////////////////////////
// Bag class implementation
function Bag(options) {
if (!(this instanceof Bag)) { return new Bag(options); }
var self = this;
options = options || {};
this.prefix = options.prefix || 'bag';
this.timeout = options.timeout || 20; // 20 seconds
this.expire = options.expire || 30 * 24; // 30 days
this.isValidItem = options.isValidItem || null;
this.stores = _isArray(options.stores) ? options.stores : [ 'indexeddb', 'websql', 'localstorage' ];
var storage = null;
this._queue = [];
this._chained = false;
this._createStorage = function () {
if (!storage) { storage = new Storage(self.prefix, self.stores); }
};
function getUrl(url, callback) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
callback(null, {
content: xhr.responseText,
type: xhr.getResponseHeader('content-type')
});
callback = _nope;
} else {
callback(new Error('Can\'t open url ' + url +
(xhr.status ? xhr.statusText + ' (' + xhr.status + ')' : '')));
callback = _nope;
}
}
};
setTimeout(function () {
if (xhr.readyState < 4) {
xhr.abort();
callback(new Error('Timeout'));
callback = _nope;
}
}, self.timeout * 1000);
xhr.send();
}
function createCacheObj(obj, response) {
var cacheObj = {};
_each([ 'url', 'key', 'unique' ], function (key) {
if (obj[key]) { cacheObj[key] = obj[key]; }
});
var now = +new Date();
cacheObj.data = response.content;
cacheObj.originalType = response.type;
cacheObj.type = obj.type || response.type;
cacheObj.stamp = now;
return cacheObj;
}
function saveUrl(obj, callback) {
getUrl(obj.url_real, function (err, result) {
if (err) { return callback(err); }
var delay = (obj.expire || self.expire) * 60 * 60; // in seconds
var cached = createCacheObj(obj, result);
self.set(obj.key, cached, delay, function () {
// Don't check error - have to return data anyway
_default(obj, cached);
callback(null, obj);
});
});
}
function isCacheValid(cached, obj) {
return !cached ||
cached.expire - +new Date() < 0 ||
obj.unique !== cached.unique ||
obj.url !== cached.url ||
(self.isValidItem && !self.isValidItem(cached, obj));
}
function fetch(obj, callback) {
if (!obj.url) { return callback(); }
obj.key = (obj.key || obj.url);
self.get(obj.key, function (err_cache, cached) {
// Check error only on forced fetch from cache
if (err_cache && obj.cached) {
callback(err_cache);
return;
}
// if can't get object from store, then just load it from web.
obj.execute = (obj.execute !== false);
var shouldFetch = !!err_cache || isCacheValid(cached, obj);
// If don't have to load new date - return one from cache
if (!obj.live && !shouldFetch) {
obj.type = obj.type || cached.originalType;
_default(obj, cached);
callback(null, obj);
return;
}
// calculate loading url
obj.url_real = obj.url;
if (obj.unique) {
// set parameter to prevent browser cache
obj.url_real = obj.url + ((obj.url.indexOf('?') > 0) ? '&' : '?') + 'bag-unique=' + obj.unique;
}
saveUrl(obj, function (err_load) {
if (err_cache && err_load) {
callback(err_load);
return;
}
if (err_load) {
obj.type = obj.type || cached.originalType;
_default(obj, cached);
callback(null, obj);
return;
}
callback(null, obj);
});
});
}
////////////////////////////////////////////////////////////////////////////
// helpers to set absolute sourcemap url
/* eslint-disable max-len */
var sourceMappingRe = /(?:^([ \t]*\/\/[@|#][ \t]+sourceMappingURL=)(.+?)([ \t]*)$)|(?:^([ \t]*\/\*[@#][ \t]+sourceMappingURL=)(.+?)([ \t]*\*\/[ \t])*$)/mg;
/* eslint-enable max-len */
function parse_url(url) {
var pattern = new RegExp('^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?');
var matches = url.match(pattern);
return {
scheme: matches[2],
authority: matches[4],
path: matches[5],
query: matches[7],
fragment: matches[9]
};
}
function patchMappingUrl(obj) {
var refUrl = parse_url(obj.url);
var done = false;
var res = obj.data.replace(sourceMappingRe, function (match, p1, p2, p3, p4, p5, p6) {
if (!match) { return null; }
done = true;
// select matched group of params
if (!p1) { p1 = p4; p2 = p5; p3 = p6; }
var mapUrl = parse_url(p2);
var scheme = (mapUrl.scheme ? mapUrl.scheme : refUrl.scheme) || window.location.protocol.slice(0, -1);
var authority = (mapUrl.authority ? mapUrl.authority : refUrl.authority) || window.location.host;
/* eslint-disable max-len */
var path = mapUrl.path[0] === '/' ? mapUrl.path : refUrl.path.split('/').slice(0, -1).join('/') + '/' + mapUrl.path;
/* eslint-enable max-len */
return p1 + (scheme + '://' + authority + path) + p3;
});
return done ? res : '';
}
////////////////////////////////////////////////////////////////////////////
var handlers = {
'application/javascript': function injectScript(obj) {
var script = document.createElement('script'), txt;
// try to change sourcemap address to absolute
txt = patchMappingUrl(obj);
if (!txt) {
// or add script name for dev tools
txt = obj.data + '\n//# sourceURL=' + obj.url;
}
// Have to use .text, since we support IE8,
// which won't allow appending to a script
script.text = txt;
head.appendChild(script);
return;
},
'text/css': function injectStyle(obj) {
var style = document.createElement('style'), txt;
// try to change sourcemap address to absolute
txt = patchMappingUrl(obj);
if (!txt) {
// or add stylesheet script name for dev tools
txt = obj.data + '\n/*# sourceURL=' + obj.url + ' */';
}
// Needed to enable `style.styleSheet` in IE
style.setAttribute('type', 'text/css');
if (style.styleSheet) {
// We should append style element to DOM before assign css text to
// workaround IE bugs with `@import` and `@font-face`.
// https://github.com/andrewwakeling/ie-css-bugs
head.appendChild(style);
style.styleSheet.cssText = txt; // IE method
} else {
style.appendChild(document.createTextNode(txt)); // others
head.appendChild(style);
}
return;
}
};
function execute(obj) {
if (!obj.type) { return; }
// Cut off encoding if exists:
// application/javascript; charset=UTF-8
var handlerName = obj.type.split(';')[0];
// Fix outdated mime types if needed, to use single handler
if (handlerName === 'application/x-javascript' || handlerName === 'text/javascript') {
handlerName = 'application/javascript';
}
if (handlers[handlerName]) {
handlers[handlerName](obj);
}
return;
}
////////////////////////////////////////////////////////////////////////////
//
// Public methods
//
this.require = function (resources, callback) {
var queue = self._queue;
if (_isFunction(resources)) {
callback = resources;
resources = null;
}
if (resources) {
var res = _isArray(resources) ? resources : [ resources ];
// convert string urls to structures
// and push to queue
_each(res, function (r, i) {
if (_isString(r)) { res[i] = { url: r }; }
queue.push(res[i]);
});
}
self._createStorage();
if (!callback) {
self._chained = true;
return self;
}
_asyncEach(queue, fetch, function (err) {
if (err) {
// cleanup
self._chained = false;
self._queue = [];
callback(err);
return;
}
_each(queue, function (obj) {
if (obj.execute) {
execute(obj);
}
});
// return content only, if one need fuul info -
// check input object, that will be extended.
var replies = [];
_each(queue, function (r) { replies.push(r.data); });
var result = (_isArray(resources) || self._chained) ? replies : replies[0];
// cleanup
self._chained = false;
self._queue = [];
callback(null, result);
});
};
// Create proxy methods (init store then subcall)
_each([ 'remove', 'get', 'set', 'clear' ], function (method) {
self[method] = function () {
self._createStorage();
storage[method].apply(storage, arguments);
};
});
this.addHandler = function (types, handler) {
types = _isArray(types) ? types : [ types ];
_each(types, function (type) { handlers[type] = handler; });
};
this.removeHandler = function (types) {
self.addHandler(types/*, undefined*/);
};
}
return Bag;
}));
| mit |
zjh171/gcc | libstdc++-v3/testsuite/23_containers/unordered_map/debug/iterator_self_move_assign_neg.cc | 1039 | // Copyright (C) 2012-2015 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library is free
// software; you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the
// Free Software Foundation; either version 3, or (at your option)
// any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this library; see the file COPYING3. If not see
// <http://www.gnu.org/licenses/>.
//
// { dg-require-debug-mode "" }
// { dg-options "-std=gnu++11" }
// { dg-do run { xfail *-*-* } }
#include <unordered_map>
void test01()
{
std::unordered_map<int, int> um1;
auto it1 = um1.begin();
it1 = std::move(it1);
}
int main()
{
test01();
return 0;
}
| gpl-2.0 |
puppeh/gcc-6502 | libstdc++-v3/testsuite/ext/throw_allocator/variadic_construct.cc | 1330 | // { dg-options "-std=gnu++11" }
// 2007-10-26 Paolo Carlini <[email protected]>
// Copyright (C) 2007-2015 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library is free
// software; you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the
// Free Software Foundation; either version 3, or (at your option)
// any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this library; see the file COPYING3. If not see
// <http://www.gnu.org/licenses/>.
// { dg-require-time "" }
#include <ext/throw_allocator.h>
#include <utility>
#include <testsuite_hooks.h>
void test01()
{
bool test __attribute__((unused)) = true;
typedef std::pair<int, char> pair_type;
__gnu_cxx::throw_allocator_random<pair_type> alloc1;
pair_type* ptp1 = alloc1.allocate(1);
alloc1.construct(ptp1, 3, 'a');
VERIFY( ptp1->first == 3 );
VERIFY( ptp1->second == 'a' );
alloc1.deallocate(ptp1, 1);
}
int main()
{
test01();
return 0;
}
| gpl-2.0 |
AdaLovelance/lxcGrsecKernels | linux-3.14.37/drivers/of/base.c | 52795 | /*
* Procedures for creating, accessing and interpreting the device tree.
*
* Paul Mackerras August 1996.
* Copyright (C) 1996-2005 Paul Mackerras.
*
* Adapted for 64bit PowerPC by Dave Engebretsen and Peter Bergner.
* {engebret|bergner}@us.ibm.com
*
* Adapted for sparc and sparc64 by David S. Miller [email protected]
*
* Reconsolidated from arch/x/kernel/prom.c by Stephen Rothwell and
* Grant Likely.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*/
#include <linux/ctype.h>
#include <linux/cpu.h>
#include <linux/module.h>
#include <linux/of.h>
#include <linux/spinlock.h>
#include <linux/slab.h>
#include <linux/proc_fs.h>
#include "of_private.h"
LIST_HEAD(aliases_lookup);
struct device_node *of_allnodes;
EXPORT_SYMBOL(of_allnodes);
struct device_node *of_chosen;
struct device_node *of_aliases;
static struct device_node *of_stdout;
DEFINE_MUTEX(of_aliases_mutex);
/* use when traversing tree through the allnext, child, sibling,
* or parent members of struct device_node.
*/
DEFINE_RAW_SPINLOCK(devtree_lock);
int of_n_addr_cells(struct device_node *np)
{
const __be32 *ip;
do {
if (np->parent)
np = np->parent;
ip = of_get_property(np, "#address-cells", NULL);
if (ip)
return be32_to_cpup(ip);
} while (np->parent);
/* No #address-cells property for the root node */
return OF_ROOT_NODE_ADDR_CELLS_DEFAULT;
}
EXPORT_SYMBOL(of_n_addr_cells);
int of_n_size_cells(struct device_node *np)
{
const __be32 *ip;
do {
if (np->parent)
np = np->parent;
ip = of_get_property(np, "#size-cells", NULL);
if (ip)
return be32_to_cpup(ip);
} while (np->parent);
/* No #size-cells property for the root node */
return OF_ROOT_NODE_SIZE_CELLS_DEFAULT;
}
EXPORT_SYMBOL(of_n_size_cells);
#ifdef CONFIG_NUMA
int __weak of_node_to_nid(struct device_node *np)
{
return numa_node_id();
}
#endif
#if defined(CONFIG_OF_DYNAMIC)
/**
* of_node_get - Increment refcount of a node
* @node: Node to inc refcount, NULL is supported to
* simplify writing of callers
*
* Returns node.
*/
struct device_node *of_node_get(struct device_node *node)
{
if (node)
kref_get(&node->kref);
return node;
}
EXPORT_SYMBOL(of_node_get);
static inline struct device_node *kref_to_device_node(struct kref *kref)
{
return container_of(kref, struct device_node, kref);
}
/**
* of_node_release - release a dynamically allocated node
* @kref: kref element of the node to be released
*
* In of_node_put() this function is passed to kref_put()
* as the destructor.
*/
static void of_node_release(struct kref *kref)
{
struct device_node *node = kref_to_device_node(kref);
struct property *prop = node->properties;
/* We should never be releasing nodes that haven't been detached. */
if (!of_node_check_flag(node, OF_DETACHED)) {
pr_err("ERROR: Bad of_node_put() on %s\n", node->full_name);
dump_stack();
kref_init(&node->kref);
return;
}
if (!of_node_check_flag(node, OF_DYNAMIC))
return;
while (prop) {
struct property *next = prop->next;
kfree(prop->name);
kfree(prop->value);
kfree(prop);
prop = next;
if (!prop) {
prop = node->deadprops;
node->deadprops = NULL;
}
}
kfree(node->full_name);
kfree(node->data);
kfree(node);
}
/**
* of_node_put - Decrement refcount of a node
* @node: Node to dec refcount, NULL is supported to
* simplify writing of callers
*
*/
void of_node_put(struct device_node *node)
{
if (node)
kref_put(&node->kref, of_node_release);
}
EXPORT_SYMBOL(of_node_put);
#endif /* CONFIG_OF_DYNAMIC */
static struct property *__of_find_property(const struct device_node *np,
const char *name, int *lenp)
{
struct property *pp;
if (!np)
return NULL;
for (pp = np->properties; pp; pp = pp->next) {
if (of_prop_cmp(pp->name, name) == 0) {
if (lenp)
*lenp = pp->length;
break;
}
}
return pp;
}
struct property *of_find_property(const struct device_node *np,
const char *name,
int *lenp)
{
struct property *pp;
unsigned long flags;
raw_spin_lock_irqsave(&devtree_lock, flags);
pp = __of_find_property(np, name, lenp);
raw_spin_unlock_irqrestore(&devtree_lock, flags);
return pp;
}
EXPORT_SYMBOL(of_find_property);
/**
* of_find_all_nodes - Get next node in global list
* @prev: Previous node or NULL to start iteration
* of_node_put() will be called on it
*
* Returns a node pointer with refcount incremented, use
* of_node_put() on it when done.
*/
struct device_node *of_find_all_nodes(struct device_node *prev)
{
struct device_node *np;
unsigned long flags;
raw_spin_lock_irqsave(&devtree_lock, flags);
np = prev ? prev->allnext : of_allnodes;
for (; np != NULL; np = np->allnext)
if (of_node_get(np))
break;
of_node_put(prev);
raw_spin_unlock_irqrestore(&devtree_lock, flags);
return np;
}
EXPORT_SYMBOL(of_find_all_nodes);
/*
* Find a property with a given name for a given node
* and return the value.
*/
static const void *__of_get_property(const struct device_node *np,
const char *name, int *lenp)
{
struct property *pp = __of_find_property(np, name, lenp);
return pp ? pp->value : NULL;
}
/*
* Find a property with a given name for a given node
* and return the value.
*/
const void *of_get_property(const struct device_node *np, const char *name,
int *lenp)
{
struct property *pp = of_find_property(np, name, lenp);
return pp ? pp->value : NULL;
}
EXPORT_SYMBOL(of_get_property);
/*
* arch_match_cpu_phys_id - Match the given logical CPU and physical id
*
* @cpu: logical cpu index of a core/thread
* @phys_id: physical identifier of a core/thread
*
* CPU logical to physical index mapping is architecture specific.
* However this __weak function provides a default match of physical
* id to logical cpu index. phys_id provided here is usually values read
* from the device tree which must match the hardware internal registers.
*
* Returns true if the physical identifier and the logical cpu index
* correspond to the same core/thread, false otherwise.
*/
bool __weak arch_match_cpu_phys_id(int cpu, u64 phys_id)
{
return (u32)phys_id == cpu;
}
/**
* Checks if the given "prop_name" property holds the physical id of the
* core/thread corresponding to the logical cpu 'cpu'. If 'thread' is not
* NULL, local thread number within the core is returned in it.
*/
static bool __of_find_n_match_cpu_property(struct device_node *cpun,
const char *prop_name, int cpu, unsigned int *thread)
{
const __be32 *cell;
int ac, prop_len, tid;
u64 hwid;
ac = of_n_addr_cells(cpun);
cell = of_get_property(cpun, prop_name, &prop_len);
if (!cell || !ac)
return false;
prop_len /= sizeof(*cell) * ac;
for (tid = 0; tid < prop_len; tid++) {
hwid = of_read_number(cell, ac);
if (arch_match_cpu_phys_id(cpu, hwid)) {
if (thread)
*thread = tid;
return true;
}
cell += ac;
}
return false;
}
/*
* arch_find_n_match_cpu_physical_id - See if the given device node is
* for the cpu corresponding to logical cpu 'cpu'. Return true if so,
* else false. If 'thread' is non-NULL, the local thread number within the
* core is returned in it.
*/
bool __weak arch_find_n_match_cpu_physical_id(struct device_node *cpun,
int cpu, unsigned int *thread)
{
/* Check for non-standard "ibm,ppc-interrupt-server#s" property
* for thread ids on PowerPC. If it doesn't exist fallback to
* standard "reg" property.
*/
if (IS_ENABLED(CONFIG_PPC) &&
__of_find_n_match_cpu_property(cpun,
"ibm,ppc-interrupt-server#s",
cpu, thread))
return true;
if (__of_find_n_match_cpu_property(cpun, "reg", cpu, thread))
return true;
return false;
}
/**
* of_get_cpu_node - Get device node associated with the given logical CPU
*
* @cpu: CPU number(logical index) for which device node is required
* @thread: if not NULL, local thread number within the physical core is
* returned
*
* The main purpose of this function is to retrieve the device node for the
* given logical CPU index. It should be used to initialize the of_node in
* cpu device. Once of_node in cpu device is populated, all the further
* references can use that instead.
*
* CPU logical to physical index mapping is architecture specific and is built
* before booting secondary cores. This function uses arch_match_cpu_phys_id
* which can be overridden by architecture specific implementation.
*
* Returns a node pointer for the logical cpu if found, else NULL.
*/
struct device_node *of_get_cpu_node(int cpu, unsigned int *thread)
{
struct device_node *cpun;
for_each_node_by_type(cpun, "cpu") {
if (arch_find_n_match_cpu_physical_id(cpun, cpu, thread))
return cpun;
}
return NULL;
}
EXPORT_SYMBOL(of_get_cpu_node);
/**
* __of_device_is_compatible() - Check if the node matches given constraints
* @device: pointer to node
* @compat: required compatible string, NULL or "" for any match
* @type: required device_type value, NULL or "" for any match
* @name: required node name, NULL or "" for any match
*
* Checks if the given @compat, @type and @name strings match the
* properties of the given @device. A constraints can be skipped by
* passing NULL or an empty string as the constraint.
*
* Returns 0 for no match, and a positive integer on match. The return
* value is a relative score with larger values indicating better
* matches. The score is weighted for the most specific compatible value
* to get the highest score. Matching type is next, followed by matching
* name. Practically speaking, this results in the following priority
* order for matches:
*
* 1. specific compatible && type && name
* 2. specific compatible && type
* 3. specific compatible && name
* 4. specific compatible
* 5. general compatible && type && name
* 6. general compatible && type
* 7. general compatible && name
* 8. general compatible
* 9. type && name
* 10. type
* 11. name
*/
static int __of_device_is_compatible(const struct device_node *device,
const char *compat, const char *type, const char *name)
{
struct property *prop;
const char *cp;
int index = 0, score = 0;
/* Compatible match has highest priority */
if (compat && compat[0]) {
prop = __of_find_property(device, "compatible", NULL);
for (cp = of_prop_next_string(prop, NULL); cp;
cp = of_prop_next_string(prop, cp), index++) {
if (of_compat_cmp(cp, compat, strlen(compat)) == 0) {
score = INT_MAX/2 - (index << 2);
break;
}
}
if (!score)
return 0;
}
/* Matching type is better than matching name */
if (type && type[0]) {
if (!device->type || of_node_cmp(type, device->type))
return 0;
score += 2;
}
/* Matching name is a bit better than not */
if (name && name[0]) {
if (!device->name || of_node_cmp(name, device->name))
return 0;
score++;
}
return score;
}
/** Checks if the given "compat" string matches one of the strings in
* the device's "compatible" property
*/
int of_device_is_compatible(const struct device_node *device,
const char *compat)
{
unsigned long flags;
int res;
raw_spin_lock_irqsave(&devtree_lock, flags);
res = __of_device_is_compatible(device, compat, NULL, NULL);
raw_spin_unlock_irqrestore(&devtree_lock, flags);
return res;
}
EXPORT_SYMBOL(of_device_is_compatible);
/**
* of_machine_is_compatible - Test root of device tree for a given compatible value
* @compat: compatible string to look for in root node's compatible property.
*
* Returns true if the root node has the given value in its
* compatible property.
*/
int of_machine_is_compatible(const char *compat)
{
struct device_node *root;
int rc = 0;
root = of_find_node_by_path("/");
if (root) {
rc = of_device_is_compatible(root, compat);
of_node_put(root);
}
return rc;
}
EXPORT_SYMBOL(of_machine_is_compatible);
/**
* __of_device_is_available - check if a device is available for use
*
* @device: Node to check for availability, with locks already held
*
* Returns 1 if the status property is absent or set to "okay" or "ok",
* 0 otherwise
*/
static int __of_device_is_available(const struct device_node *device)
{
const char *status;
int statlen;
if (!device)
return 0;
status = __of_get_property(device, "status", &statlen);
if (status == NULL)
return 1;
if (statlen > 0) {
if (!strcmp(status, "okay") || !strcmp(status, "ok"))
return 1;
}
return 0;
}
/**
* of_device_is_available - check if a device is available for use
*
* @device: Node to check for availability
*
* Returns 1 if the status property is absent or set to "okay" or "ok",
* 0 otherwise
*/
int of_device_is_available(const struct device_node *device)
{
unsigned long flags;
int res;
raw_spin_lock_irqsave(&devtree_lock, flags);
res = __of_device_is_available(device);
raw_spin_unlock_irqrestore(&devtree_lock, flags);
return res;
}
EXPORT_SYMBOL(of_device_is_available);
/**
* of_get_parent - Get a node's parent if any
* @node: Node to get parent
*
* Returns a node pointer with refcount incremented, use
* of_node_put() on it when done.
*/
struct device_node *of_get_parent(const struct device_node *node)
{
struct device_node *np;
unsigned long flags;
if (!node)
return NULL;
raw_spin_lock_irqsave(&devtree_lock, flags);
np = of_node_get(node->parent);
raw_spin_unlock_irqrestore(&devtree_lock, flags);
return np;
}
EXPORT_SYMBOL(of_get_parent);
/**
* of_get_next_parent - Iterate to a node's parent
* @node: Node to get parent of
*
* This is like of_get_parent() except that it drops the
* refcount on the passed node, making it suitable for iterating
* through a node's parents.
*
* Returns a node pointer with refcount incremented, use
* of_node_put() on it when done.
*/
struct device_node *of_get_next_parent(struct device_node *node)
{
struct device_node *parent;
unsigned long flags;
if (!node)
return NULL;
raw_spin_lock_irqsave(&devtree_lock, flags);
parent = of_node_get(node->parent);
of_node_put(node);
raw_spin_unlock_irqrestore(&devtree_lock, flags);
return parent;
}
EXPORT_SYMBOL(of_get_next_parent);
/**
* of_get_next_child - Iterate a node childs
* @node: parent node
* @prev: previous child of the parent node, or NULL to get first
*
* Returns a node pointer with refcount incremented, use
* of_node_put() on it when done.
*/
struct device_node *of_get_next_child(const struct device_node *node,
struct device_node *prev)
{
struct device_node *next;
unsigned long flags;
raw_spin_lock_irqsave(&devtree_lock, flags);
next = prev ? prev->sibling : node->child;
for (; next; next = next->sibling)
if (of_node_get(next))
break;
of_node_put(prev);
raw_spin_unlock_irqrestore(&devtree_lock, flags);
return next;
}
EXPORT_SYMBOL(of_get_next_child);
/**
* of_get_next_available_child - Find the next available child node
* @node: parent node
* @prev: previous child of the parent node, or NULL to get first
*
* This function is like of_get_next_child(), except that it
* automatically skips any disabled nodes (i.e. status = "disabled").
*/
struct device_node *of_get_next_available_child(const struct device_node *node,
struct device_node *prev)
{
struct device_node *next;
unsigned long flags;
raw_spin_lock_irqsave(&devtree_lock, flags);
next = prev ? prev->sibling : node->child;
for (; next; next = next->sibling) {
if (!__of_device_is_available(next))
continue;
if (of_node_get(next))
break;
}
of_node_put(prev);
raw_spin_unlock_irqrestore(&devtree_lock, flags);
return next;
}
EXPORT_SYMBOL(of_get_next_available_child);
/**
* of_get_child_by_name - Find the child node by name for a given parent
* @node: parent node
* @name: child name to look for.
*
* This function looks for child node for given matching name
*
* Returns a node pointer if found, with refcount incremented, use
* of_node_put() on it when done.
* Returns NULL if node is not found.
*/
struct device_node *of_get_child_by_name(const struct device_node *node,
const char *name)
{
struct device_node *child;
for_each_child_of_node(node, child)
if (child->name && (of_node_cmp(child->name, name) == 0))
break;
return child;
}
EXPORT_SYMBOL(of_get_child_by_name);
/**
* of_find_node_by_path - Find a node matching a full OF path
* @path: The full path to match
*
* Returns a node pointer with refcount incremented, use
* of_node_put() on it when done.
*/
struct device_node *of_find_node_by_path(const char *path)
{
struct device_node *np = of_allnodes;
unsigned long flags;
raw_spin_lock_irqsave(&devtree_lock, flags);
for (; np; np = np->allnext) {
if (np->full_name && (of_node_cmp(np->full_name, path) == 0)
&& of_node_get(np))
break;
}
raw_spin_unlock_irqrestore(&devtree_lock, flags);
return np;
}
EXPORT_SYMBOL(of_find_node_by_path);
/**
* of_find_node_by_name - Find a node by its "name" property
* @from: The node to start searching from or NULL, the node
* you pass will not be searched, only the next one
* will; typically, you pass what the previous call
* returned. of_node_put() will be called on it
* @name: The name string to match against
*
* Returns a node pointer with refcount incremented, use
* of_node_put() on it when done.
*/
struct device_node *of_find_node_by_name(struct device_node *from,
const char *name)
{
struct device_node *np;
unsigned long flags;
raw_spin_lock_irqsave(&devtree_lock, flags);
np = from ? from->allnext : of_allnodes;
for (; np; np = np->allnext)
if (np->name && (of_node_cmp(np->name, name) == 0)
&& of_node_get(np))
break;
of_node_put(from);
raw_spin_unlock_irqrestore(&devtree_lock, flags);
return np;
}
EXPORT_SYMBOL(of_find_node_by_name);
/**
* of_find_node_by_type - Find a node by its "device_type" property
* @from: The node to start searching from, or NULL to start searching
* the entire device tree. The node you pass will not be
* searched, only the next one will; typically, you pass
* what the previous call returned. of_node_put() will be
* called on from for you.
* @type: The type string to match against
*
* Returns a node pointer with refcount incremented, use
* of_node_put() on it when done.
*/
struct device_node *of_find_node_by_type(struct device_node *from,
const char *type)
{
struct device_node *np;
unsigned long flags;
raw_spin_lock_irqsave(&devtree_lock, flags);
np = from ? from->allnext : of_allnodes;
for (; np; np = np->allnext)
if (np->type && (of_node_cmp(np->type, type) == 0)
&& of_node_get(np))
break;
of_node_put(from);
raw_spin_unlock_irqrestore(&devtree_lock, flags);
return np;
}
EXPORT_SYMBOL(of_find_node_by_type);
/**
* of_find_compatible_node - Find a node based on type and one of the
* tokens in its "compatible" property
* @from: The node to start searching from or NULL, the node
* you pass will not be searched, only the next one
* will; typically, you pass what the previous call
* returned. of_node_put() will be called on it
* @type: The type string to match "device_type" or NULL to ignore
* @compatible: The string to match to one of the tokens in the device
* "compatible" list.
*
* Returns a node pointer with refcount incremented, use
* of_node_put() on it when done.
*/
struct device_node *of_find_compatible_node(struct device_node *from,
const char *type, const char *compatible)
{
struct device_node *np;
unsigned long flags;
raw_spin_lock_irqsave(&devtree_lock, flags);
np = from ? from->allnext : of_allnodes;
for (; np; np = np->allnext) {
if (__of_device_is_compatible(np, compatible, type, NULL) &&
of_node_get(np))
break;
}
of_node_put(from);
raw_spin_unlock_irqrestore(&devtree_lock, flags);
return np;
}
EXPORT_SYMBOL(of_find_compatible_node);
/**
* of_find_node_with_property - Find a node which has a property with
* the given name.
* @from: The node to start searching from or NULL, the node
* you pass will not be searched, only the next one
* will; typically, you pass what the previous call
* returned. of_node_put() will be called on it
* @prop_name: The name of the property to look for.
*
* Returns a node pointer with refcount incremented, use
* of_node_put() on it when done.
*/
struct device_node *of_find_node_with_property(struct device_node *from,
const char *prop_name)
{
struct device_node *np;
struct property *pp;
unsigned long flags;
raw_spin_lock_irqsave(&devtree_lock, flags);
np = from ? from->allnext : of_allnodes;
for (; np; np = np->allnext) {
for (pp = np->properties; pp; pp = pp->next) {
if (of_prop_cmp(pp->name, prop_name) == 0) {
of_node_get(np);
goto out;
}
}
}
out:
of_node_put(from);
raw_spin_unlock_irqrestore(&devtree_lock, flags);
return np;
}
EXPORT_SYMBOL(of_find_node_with_property);
static
const struct of_device_id *__of_match_node(const struct of_device_id *matches,
const struct device_node *node)
{
const struct of_device_id *best_match = NULL;
int score, best_score = 0;
if (!matches)
return NULL;
for (; matches->name[0] || matches->type[0] || matches->compatible[0]; matches++) {
score = __of_device_is_compatible(node, matches->compatible,
matches->type, matches->name);
if (score > best_score) {
best_match = matches;
best_score = score;
}
}
return best_match;
}
/**
* of_match_node - Tell if an device_node has a matching of_match structure
* @matches: array of of device match structures to search in
* @node: the of device structure to match against
*
* Low level utility function used by device matching.
*/
const struct of_device_id *of_match_node(const struct of_device_id *matches,
const struct device_node *node)
{
const struct of_device_id *match;
unsigned long flags;
raw_spin_lock_irqsave(&devtree_lock, flags);
match = __of_match_node(matches, node);
raw_spin_unlock_irqrestore(&devtree_lock, flags);
return match;
}
EXPORT_SYMBOL(of_match_node);
/**
* of_find_matching_node_and_match - Find a node based on an of_device_id
* match table.
* @from: The node to start searching from or NULL, the node
* you pass will not be searched, only the next one
* will; typically, you pass what the previous call
* returned. of_node_put() will be called on it
* @matches: array of of device match structures to search in
* @match Updated to point at the matches entry which matched
*
* Returns a node pointer with refcount incremented, use
* of_node_put() on it when done.
*/
struct device_node *of_find_matching_node_and_match(struct device_node *from,
const struct of_device_id *matches,
const struct of_device_id **match)
{
struct device_node *np;
const struct of_device_id *m;
unsigned long flags;
if (match)
*match = NULL;
raw_spin_lock_irqsave(&devtree_lock, flags);
np = from ? from->allnext : of_allnodes;
for (; np; np = np->allnext) {
m = __of_match_node(matches, np);
if (m && of_node_get(np)) {
if (match)
*match = m;
break;
}
}
of_node_put(from);
raw_spin_unlock_irqrestore(&devtree_lock, flags);
return np;
}
EXPORT_SYMBOL(of_find_matching_node_and_match);
/**
* of_modalias_node - Lookup appropriate modalias for a device node
* @node: pointer to a device tree node
* @modalias: Pointer to buffer that modalias value will be copied into
* @len: Length of modalias value
*
* Based on the value of the compatible property, this routine will attempt
* to choose an appropriate modalias value for a particular device tree node.
* It does this by stripping the manufacturer prefix (as delimited by a ',')
* from the first entry in the compatible list property.
*
* This routine returns 0 on success, <0 on failure.
*/
int of_modalias_node(struct device_node *node, char *modalias, int len)
{
const char *compatible, *p;
int cplen;
compatible = of_get_property(node, "compatible", &cplen);
if (!compatible || strlen(compatible) > cplen)
return -ENODEV;
p = strchr(compatible, ',');
strlcpy(modalias, p ? p + 1 : compatible, len);
return 0;
}
EXPORT_SYMBOL_GPL(of_modalias_node);
/**
* of_find_node_by_phandle - Find a node given a phandle
* @handle: phandle of the node to find
*
* Returns a node pointer with refcount incremented, use
* of_node_put() on it when done.
*/
struct device_node *of_find_node_by_phandle(phandle handle)
{
struct device_node *np;
unsigned long flags;
raw_spin_lock_irqsave(&devtree_lock, flags);
for (np = of_allnodes; np; np = np->allnext)
if (np->phandle == handle)
break;
of_node_get(np);
raw_spin_unlock_irqrestore(&devtree_lock, flags);
return np;
}
EXPORT_SYMBOL(of_find_node_by_phandle);
/**
* of_find_property_value_of_size
*
* @np: device node from which the property value is to be read.
* @propname: name of the property to be searched.
* @len: requested length of property value
*
* Search for a property in a device node and valid the requested size.
* Returns the property value on success, -EINVAL if the property does not
* exist, -ENODATA if property does not have a value, and -EOVERFLOW if the
* property data isn't large enough.
*
*/
static void *of_find_property_value_of_size(const struct device_node *np,
const char *propname, u32 len)
{
struct property *prop = of_find_property(np, propname, NULL);
if (!prop)
return ERR_PTR(-EINVAL);
if (!prop->value)
return ERR_PTR(-ENODATA);
if (len > prop->length)
return ERR_PTR(-EOVERFLOW);
return prop->value;
}
/**
* of_property_read_u32_index - Find and read a u32 from a multi-value property.
*
* @np: device node from which the property value is to be read.
* @propname: name of the property to be searched.
* @index: index of the u32 in the list of values
* @out_value: pointer to return value, modified only if no error.
*
* Search for a property in a device node and read nth 32-bit value from
* it. Returns 0 on success, -EINVAL if the property does not exist,
* -ENODATA if property does not have a value, and -EOVERFLOW if the
* property data isn't large enough.
*
* The out_value is modified only if a valid u32 value can be decoded.
*/
int of_property_read_u32_index(const struct device_node *np,
const char *propname,
u32 index, u32 *out_value)
{
const u32 *val = of_find_property_value_of_size(np, propname,
((index + 1) * sizeof(*out_value)));
if (IS_ERR(val))
return PTR_ERR(val);
*out_value = be32_to_cpup(((__be32 *)val) + index);
return 0;
}
EXPORT_SYMBOL_GPL(of_property_read_u32_index);
/**
* of_property_read_u8_array - Find and read an array of u8 from a property.
*
* @np: device node from which the property value is to be read.
* @propname: name of the property to be searched.
* @out_values: pointer to return value, modified only if return value is 0.
* @sz: number of array elements to read
*
* Search for a property in a device node and read 8-bit value(s) from
* it. Returns 0 on success, -EINVAL if the property does not exist,
* -ENODATA if property does not have a value, and -EOVERFLOW if the
* property data isn't large enough.
*
* dts entry of array should be like:
* property = /bits/ 8 <0x50 0x60 0x70>;
*
* The out_values is modified only if a valid u8 value can be decoded.
*/
int of_property_read_u8_array(const struct device_node *np,
const char *propname, u8 *out_values, size_t sz)
{
const u8 *val = of_find_property_value_of_size(np, propname,
(sz * sizeof(*out_values)));
if (IS_ERR(val))
return PTR_ERR(val);
while (sz--)
*out_values++ = *val++;
return 0;
}
EXPORT_SYMBOL_GPL(of_property_read_u8_array);
/**
* of_property_read_u16_array - Find and read an array of u16 from a property.
*
* @np: device node from which the property value is to be read.
* @propname: name of the property to be searched.
* @out_values: pointer to return value, modified only if return value is 0.
* @sz: number of array elements to read
*
* Search for a property in a device node and read 16-bit value(s) from
* it. Returns 0 on success, -EINVAL if the property does not exist,
* -ENODATA if property does not have a value, and -EOVERFLOW if the
* property data isn't large enough.
*
* dts entry of array should be like:
* property = /bits/ 16 <0x5000 0x6000 0x7000>;
*
* The out_values is modified only if a valid u16 value can be decoded.
*/
int of_property_read_u16_array(const struct device_node *np,
const char *propname, u16 *out_values, size_t sz)
{
const __be16 *val = of_find_property_value_of_size(np, propname,
(sz * sizeof(*out_values)));
if (IS_ERR(val))
return PTR_ERR(val);
while (sz--)
*out_values++ = be16_to_cpup(val++);
return 0;
}
EXPORT_SYMBOL_GPL(of_property_read_u16_array);
/**
* of_property_read_u32_array - Find and read an array of 32 bit integers
* from a property.
*
* @np: device node from which the property value is to be read.
* @propname: name of the property to be searched.
* @out_values: pointer to return value, modified only if return value is 0.
* @sz: number of array elements to read
*
* Search for a property in a device node and read 32-bit value(s) from
* it. Returns 0 on success, -EINVAL if the property does not exist,
* -ENODATA if property does not have a value, and -EOVERFLOW if the
* property data isn't large enough.
*
* The out_values is modified only if a valid u32 value can be decoded.
*/
int of_property_read_u32_array(const struct device_node *np,
const char *propname, u32 *out_values,
size_t sz)
{
const __be32 *val = of_find_property_value_of_size(np, propname,
(sz * sizeof(*out_values)));
if (IS_ERR(val))
return PTR_ERR(val);
while (sz--)
*out_values++ = be32_to_cpup(val++);
return 0;
}
EXPORT_SYMBOL_GPL(of_property_read_u32_array);
/**
* of_property_read_u64 - Find and read a 64 bit integer from a property
* @np: device node from which the property value is to be read.
* @propname: name of the property to be searched.
* @out_value: pointer to return value, modified only if return value is 0.
*
* Search for a property in a device node and read a 64-bit value from
* it. Returns 0 on success, -EINVAL if the property does not exist,
* -ENODATA if property does not have a value, and -EOVERFLOW if the
* property data isn't large enough.
*
* The out_value is modified only if a valid u64 value can be decoded.
*/
int of_property_read_u64(const struct device_node *np, const char *propname,
u64 *out_value)
{
const __be32 *val = of_find_property_value_of_size(np, propname,
sizeof(*out_value));
if (IS_ERR(val))
return PTR_ERR(val);
*out_value = of_read_number(val, 2);
return 0;
}
EXPORT_SYMBOL_GPL(of_property_read_u64);
/**
* of_property_read_string - Find and read a string from a property
* @np: device node from which the property value is to be read.
* @propname: name of the property to be searched.
* @out_string: pointer to null terminated return string, modified only if
* return value is 0.
*
* Search for a property in a device tree node and retrieve a null
* terminated string value (pointer to data, not a copy). Returns 0 on
* success, -EINVAL if the property does not exist, -ENODATA if property
* does not have a value, and -EILSEQ if the string is not null-terminated
* within the length of the property data.
*
* The out_string pointer is modified only if a valid string can be decoded.
*/
int of_property_read_string(struct device_node *np, const char *propname,
const char **out_string)
{
struct property *prop = of_find_property(np, propname, NULL);
if (!prop)
return -EINVAL;
if (!prop->value)
return -ENODATA;
if (strnlen(prop->value, prop->length) >= prop->length)
return -EILSEQ;
*out_string = prop->value;
return 0;
}
EXPORT_SYMBOL_GPL(of_property_read_string);
/**
* of_property_match_string() - Find string in a list and return index
* @np: pointer to node containing string list property
* @propname: string list property name
* @string: pointer to string to search for in string list
*
* This function searches a string list property and returns the index
* of a specific string value.
*/
int of_property_match_string(struct device_node *np, const char *propname,
const char *string)
{
struct property *prop = of_find_property(np, propname, NULL);
size_t l;
int i;
const char *p, *end;
if (!prop)
return -EINVAL;
if (!prop->value)
return -ENODATA;
p = prop->value;
end = p + prop->length;
for (i = 0; p < end; i++, p += l) {
l = strnlen(p, end - p) + 1;
if (p + l > end)
return -EILSEQ;
pr_debug("comparing %s with %s\n", string, p);
if (strcmp(string, p) == 0)
return i; /* Found it; return index */
}
return -ENODATA;
}
EXPORT_SYMBOL_GPL(of_property_match_string);
/**
* of_property_read_string_util() - Utility helper for parsing string properties
* @np: device node from which the property value is to be read.
* @propname: name of the property to be searched.
* @out_strs: output array of string pointers.
* @sz: number of array elements to read.
* @skip: Number of strings to skip over at beginning of list.
*
* Don't call this function directly. It is a utility helper for the
* of_property_read_string*() family of functions.
*/
int of_property_read_string_helper(struct device_node *np, const char *propname,
const char **out_strs, size_t sz, int skip)
{
struct property *prop = of_find_property(np, propname, NULL);
int l = 0, i = 0;
const char *p, *end;
if (!prop)
return -EINVAL;
if (!prop->value)
return -ENODATA;
p = prop->value;
end = p + prop->length;
for (i = 0; p < end && (!out_strs || i < skip + sz); i++, p += l) {
l = strnlen(p, end - p) + 1;
if (p + l > end)
return -EILSEQ;
if (out_strs && i >= skip)
*out_strs++ = p;
}
i -= skip;
return i <= 0 ? -ENODATA : i;
}
EXPORT_SYMBOL_GPL(of_property_read_string_helper);
void of_print_phandle_args(const char *msg, const struct of_phandle_args *args)
{
int i;
printk("%s %s", msg, of_node_full_name(args->np));
for (i = 0; i < args->args_count; i++)
printk(i ? ",%08x" : ":%08x", args->args[i]);
printk("\n");
}
static int __of_parse_phandle_with_args(const struct device_node *np,
const char *list_name,
const char *cells_name,
int cell_count, int index,
struct of_phandle_args *out_args)
{
const __be32 *list, *list_end;
int rc = 0, size, cur_index = 0;
uint32_t count = 0;
struct device_node *node = NULL;
phandle phandle;
/* Retrieve the phandle list property */
list = of_get_property(np, list_name, &size);
if (!list)
return -ENOENT;
list_end = list + size / sizeof(*list);
/* Loop over the phandles until all the requested entry is found */
while (list < list_end) {
rc = -EINVAL;
count = 0;
/*
* If phandle is 0, then it is an empty entry with no
* arguments. Skip forward to the next entry.
*/
phandle = be32_to_cpup(list++);
if (phandle) {
/*
* Find the provider node and parse the #*-cells
* property to determine the argument length.
*
* This is not needed if the cell count is hard-coded
* (i.e. cells_name not set, but cell_count is set),
* except when we're going to return the found node
* below.
*/
if (cells_name || cur_index == index) {
node = of_find_node_by_phandle(phandle);
if (!node) {
pr_err("%s: could not find phandle\n",
np->full_name);
goto err;
}
}
if (cells_name) {
if (of_property_read_u32(node, cells_name,
&count)) {
pr_err("%s: could not get %s for %s\n",
np->full_name, cells_name,
node->full_name);
goto err;
}
} else {
count = cell_count;
}
/*
* Make sure that the arguments actually fit in the
* remaining property data length
*/
if (list + count > list_end) {
pr_err("%s: arguments longer than property\n",
np->full_name);
goto err;
}
}
/*
* All of the error cases above bail out of the loop, so at
* this point, the parsing is successful. If the requested
* index matches, then fill the out_args structure and return,
* or return -ENOENT for an empty entry.
*/
rc = -ENOENT;
if (cur_index == index) {
if (!phandle)
goto err;
if (out_args) {
int i;
if (WARN_ON(count > MAX_PHANDLE_ARGS))
count = MAX_PHANDLE_ARGS;
out_args->np = node;
out_args->args_count = count;
for (i = 0; i < count; i++)
out_args->args[i] = be32_to_cpup(list++);
} else {
of_node_put(node);
}
/* Found it! return success */
return 0;
}
of_node_put(node);
node = NULL;
list += count;
cur_index++;
}
/*
* Unlock node before returning result; will be one of:
* -ENOENT : index is for empty phandle
* -EINVAL : parsing error on data
* [1..n] : Number of phandle (count mode; when index = -1)
*/
rc = index < 0 ? cur_index : -ENOENT;
err:
if (node)
of_node_put(node);
return rc;
}
/**
* of_parse_phandle - Resolve a phandle property to a device_node pointer
* @np: Pointer to device node holding phandle property
* @phandle_name: Name of property holding a phandle value
* @index: For properties holding a table of phandles, this is the index into
* the table
*
* Returns the device_node pointer with refcount incremented. Use
* of_node_put() on it when done.
*/
struct device_node *of_parse_phandle(const struct device_node *np,
const char *phandle_name, int index)
{
struct of_phandle_args args;
if (index < 0)
return NULL;
if (__of_parse_phandle_with_args(np, phandle_name, NULL, 0,
index, &args))
return NULL;
return args.np;
}
EXPORT_SYMBOL(of_parse_phandle);
/**
* of_parse_phandle_with_args() - Find a node pointed by phandle in a list
* @np: pointer to a device tree node containing a list
* @list_name: property name that contains a list
* @cells_name: property name that specifies phandles' arguments count
* @index: index of a phandle to parse out
* @out_args: optional pointer to output arguments structure (will be filled)
*
* This function is useful to parse lists of phandles and their arguments.
* Returns 0 on success and fills out_args, on error returns appropriate
* errno value.
*
* Caller is responsible to call of_node_put() on the returned out_args->node
* pointer.
*
* Example:
*
* phandle1: node1 {
* #list-cells = <2>;
* }
*
* phandle2: node2 {
* #list-cells = <1>;
* }
*
* node3 {
* list = <&phandle1 1 2 &phandle2 3>;
* }
*
* To get a device_node of the `node2' node you may call this:
* of_parse_phandle_with_args(node3, "list", "#list-cells", 1, &args);
*/
int of_parse_phandle_with_args(const struct device_node *np, const char *list_name,
const char *cells_name, int index,
struct of_phandle_args *out_args)
{
if (index < 0)
return -EINVAL;
return __of_parse_phandle_with_args(np, list_name, cells_name, 0,
index, out_args);
}
EXPORT_SYMBOL(of_parse_phandle_with_args);
/**
* of_parse_phandle_with_fixed_args() - Find a node pointed by phandle in a list
* @np: pointer to a device tree node containing a list
* @list_name: property name that contains a list
* @cell_count: number of argument cells following the phandle
* @index: index of a phandle to parse out
* @out_args: optional pointer to output arguments structure (will be filled)
*
* This function is useful to parse lists of phandles and their arguments.
* Returns 0 on success and fills out_args, on error returns appropriate
* errno value.
*
* Caller is responsible to call of_node_put() on the returned out_args->node
* pointer.
*
* Example:
*
* phandle1: node1 {
* }
*
* phandle2: node2 {
* }
*
* node3 {
* list = <&phandle1 0 2 &phandle2 2 3>;
* }
*
* To get a device_node of the `node2' node you may call this:
* of_parse_phandle_with_fixed_args(node3, "list", 2, 1, &args);
*/
int of_parse_phandle_with_fixed_args(const struct device_node *np,
const char *list_name, int cell_count,
int index, struct of_phandle_args *out_args)
{
if (index < 0)
return -EINVAL;
return __of_parse_phandle_with_args(np, list_name, NULL, cell_count,
index, out_args);
}
EXPORT_SYMBOL(of_parse_phandle_with_fixed_args);
/**
* of_count_phandle_with_args() - Find the number of phandles references in a property
* @np: pointer to a device tree node containing a list
* @list_name: property name that contains a list
* @cells_name: property name that specifies phandles' arguments count
*
* Returns the number of phandle + argument tuples within a property. It
* is a typical pattern to encode a list of phandle and variable
* arguments into a single property. The number of arguments is encoded
* by a property in the phandle-target node. For example, a gpios
* property would contain a list of GPIO specifies consisting of a
* phandle and 1 or more arguments. The number of arguments are
* determined by the #gpio-cells property in the node pointed to by the
* phandle.
*/
int of_count_phandle_with_args(const struct device_node *np, const char *list_name,
const char *cells_name)
{
return __of_parse_phandle_with_args(np, list_name, cells_name, 0, -1,
NULL);
}
EXPORT_SYMBOL(of_count_phandle_with_args);
#if defined(CONFIG_OF_DYNAMIC)
static int of_property_notify(int action, struct device_node *np,
struct property *prop)
{
struct of_prop_reconfig pr;
pr.dn = np;
pr.prop = prop;
return of_reconfig_notify(action, &pr);
}
#else
static int of_property_notify(int action, struct device_node *np,
struct property *prop)
{
return 0;
}
#endif
/**
* of_add_property - Add a property to a node
*/
int of_add_property(struct device_node *np, struct property *prop)
{
struct property **next;
unsigned long flags;
int rc;
rc = of_property_notify(OF_RECONFIG_ADD_PROPERTY, np, prop);
if (rc)
return rc;
prop->next = NULL;
raw_spin_lock_irqsave(&devtree_lock, flags);
next = &np->properties;
while (*next) {
if (strcmp(prop->name, (*next)->name) == 0) {
/* duplicate ! don't insert it */
raw_spin_unlock_irqrestore(&devtree_lock, flags);
return -1;
}
next = &(*next)->next;
}
*next = prop;
raw_spin_unlock_irqrestore(&devtree_lock, flags);
#ifdef CONFIG_PROC_DEVICETREE
/* try to add to proc as well if it was initialized */
if (np->pde)
proc_device_tree_add_prop(np->pde, prop);
#endif /* CONFIG_PROC_DEVICETREE */
return 0;
}
/**
* of_remove_property - Remove a property from a node.
*
* Note that we don't actually remove it, since we have given out
* who-knows-how-many pointers to the data using get-property.
* Instead we just move the property to the "dead properties"
* list, so it won't be found any more.
*/
int of_remove_property(struct device_node *np, struct property *prop)
{
struct property **next;
unsigned long flags;
int found = 0;
int rc;
rc = of_property_notify(OF_RECONFIG_REMOVE_PROPERTY, np, prop);
if (rc)
return rc;
raw_spin_lock_irqsave(&devtree_lock, flags);
next = &np->properties;
while (*next) {
if (*next == prop) {
/* found the node */
*next = prop->next;
prop->next = np->deadprops;
np->deadprops = prop;
found = 1;
break;
}
next = &(*next)->next;
}
raw_spin_unlock_irqrestore(&devtree_lock, flags);
if (!found)
return -ENODEV;
#ifdef CONFIG_PROC_DEVICETREE
/* try to remove the proc node as well */
if (np->pde)
proc_device_tree_remove_prop(np->pde, prop);
#endif /* CONFIG_PROC_DEVICETREE */
return 0;
}
/*
* of_update_property - Update a property in a node, if the property does
* not exist, add it.
*
* Note that we don't actually remove it, since we have given out
* who-knows-how-many pointers to the data using get-property.
* Instead we just move the property to the "dead properties" list,
* and add the new property to the property list
*/
int of_update_property(struct device_node *np, struct property *newprop)
{
struct property **next, *oldprop;
unsigned long flags;
int rc, found = 0;
rc = of_property_notify(OF_RECONFIG_UPDATE_PROPERTY, np, newprop);
if (rc)
return rc;
if (!newprop->name)
return -EINVAL;
oldprop = of_find_property(np, newprop->name, NULL);
if (!oldprop)
return of_add_property(np, newprop);
raw_spin_lock_irqsave(&devtree_lock, flags);
next = &np->properties;
while (*next) {
if (*next == oldprop) {
/* found the node */
newprop->next = oldprop->next;
*next = newprop;
oldprop->next = np->deadprops;
np->deadprops = oldprop;
found = 1;
break;
}
next = &(*next)->next;
}
raw_spin_unlock_irqrestore(&devtree_lock, flags);
if (!found)
return -ENODEV;
#ifdef CONFIG_PROC_DEVICETREE
/* try to add to proc as well if it was initialized */
if (np->pde)
proc_device_tree_update_prop(np->pde, newprop, oldprop);
#endif /* CONFIG_PROC_DEVICETREE */
return 0;
}
#if defined(CONFIG_OF_DYNAMIC)
/*
* Support for dynamic device trees.
*
* On some platforms, the device tree can be manipulated at runtime.
* The routines in this section support adding, removing and changing
* device tree nodes.
*/
static BLOCKING_NOTIFIER_HEAD(of_reconfig_chain);
int of_reconfig_notifier_register(struct notifier_block *nb)
{
return blocking_notifier_chain_register(&of_reconfig_chain, nb);
}
EXPORT_SYMBOL_GPL(of_reconfig_notifier_register);
int of_reconfig_notifier_unregister(struct notifier_block *nb)
{
return blocking_notifier_chain_unregister(&of_reconfig_chain, nb);
}
EXPORT_SYMBOL_GPL(of_reconfig_notifier_unregister);
int of_reconfig_notify(unsigned long action, void *p)
{
int rc;
rc = blocking_notifier_call_chain(&of_reconfig_chain, action, p);
return notifier_to_errno(rc);
}
#ifdef CONFIG_PROC_DEVICETREE
static void of_add_proc_dt_entry(struct device_node *dn)
{
struct proc_dir_entry *ent;
ent = proc_mkdir(strrchr(dn->full_name, '/') + 1, dn->parent->pde);
if (ent)
proc_device_tree_add_node(dn, ent);
}
#else
static void of_add_proc_dt_entry(struct device_node *dn)
{
return;
}
#endif
/**
* of_attach_node - Plug a device node into the tree and global list.
*/
int of_attach_node(struct device_node *np)
{
unsigned long flags;
int rc;
rc = of_reconfig_notify(OF_RECONFIG_ATTACH_NODE, np);
if (rc)
return rc;
raw_spin_lock_irqsave(&devtree_lock, flags);
np->sibling = np->parent->child;
np->allnext = of_allnodes;
np->parent->child = np;
of_allnodes = np;
raw_spin_unlock_irqrestore(&devtree_lock, flags);
of_add_proc_dt_entry(np);
return 0;
}
#ifdef CONFIG_PROC_DEVICETREE
static void of_remove_proc_dt_entry(struct device_node *dn)
{
proc_remove(dn->pde);
}
#else
static void of_remove_proc_dt_entry(struct device_node *dn)
{
return;
}
#endif
/**
* of_detach_node - "Unplug" a node from the device tree.
*
* The caller must hold a reference to the node. The memory associated with
* the node is not freed until its refcount goes to zero.
*/
int of_detach_node(struct device_node *np)
{
struct device_node *parent;
unsigned long flags;
int rc = 0;
rc = of_reconfig_notify(OF_RECONFIG_DETACH_NODE, np);
if (rc)
return rc;
raw_spin_lock_irqsave(&devtree_lock, flags);
if (of_node_check_flag(np, OF_DETACHED)) {
/* someone already detached it */
raw_spin_unlock_irqrestore(&devtree_lock, flags);
return rc;
}
parent = np->parent;
if (!parent) {
raw_spin_unlock_irqrestore(&devtree_lock, flags);
return rc;
}
if (of_allnodes == np)
of_allnodes = np->allnext;
else {
struct device_node *prev;
for (prev = of_allnodes;
prev->allnext != np;
prev = prev->allnext)
;
prev->allnext = np->allnext;
}
if (parent->child == np)
parent->child = np->sibling;
else {
struct device_node *prevsib;
for (prevsib = np->parent->child;
prevsib->sibling != np;
prevsib = prevsib->sibling)
;
prevsib->sibling = np->sibling;
}
of_node_set_flag(np, OF_DETACHED);
raw_spin_unlock_irqrestore(&devtree_lock, flags);
of_remove_proc_dt_entry(np);
return rc;
}
#endif /* defined(CONFIG_OF_DYNAMIC) */
static void of_alias_add(struct alias_prop *ap, struct device_node *np,
int id, const char *stem, int stem_len)
{
ap->np = np;
ap->id = id;
strncpy(ap->stem, stem, stem_len);
ap->stem[stem_len] = 0;
list_add_tail(&ap->link, &aliases_lookup);
pr_debug("adding DT alias:%s: stem=%s id=%i node=%s\n",
ap->alias, ap->stem, ap->id, of_node_full_name(np));
}
/**
* of_alias_scan - Scan all properties of 'aliases' node
*
* The function scans all the properties of 'aliases' node and populate
* the the global lookup table with the properties. It returns the
* number of alias_prop found, or error code in error case.
*
* @dt_alloc: An allocator that provides a virtual address to memory
* for the resulting tree
*/
void of_alias_scan(void * (*dt_alloc)(u64 size, u64 align))
{
struct property *pp;
of_chosen = of_find_node_by_path("/chosen");
if (of_chosen == NULL)
of_chosen = of_find_node_by_path("/chosen@0");
if (of_chosen) {
const char *name;
name = of_get_property(of_chosen, "linux,stdout-path", NULL);
if (name)
of_stdout = of_find_node_by_path(name);
}
of_aliases = of_find_node_by_path("/aliases");
if (!of_aliases)
return;
for_each_property_of_node(of_aliases, pp) {
const char *start = pp->name;
const char *end = start + strlen(start);
struct device_node *np;
struct alias_prop *ap;
int id, len;
/* Skip those we do not want to proceed */
if (!strcmp(pp->name, "name") ||
!strcmp(pp->name, "phandle") ||
!strcmp(pp->name, "linux,phandle"))
continue;
np = of_find_node_by_path(pp->value);
if (!np)
continue;
/* walk the alias backwards to extract the id and work out
* the 'stem' string */
while (isdigit(*(end-1)) && end > start)
end--;
len = end - start;
if (kstrtoint(end, 10, &id) < 0)
continue;
/* Allocate an alias_prop with enough space for the stem */
ap = dt_alloc(sizeof(*ap) + len + 1, 4);
if (!ap)
continue;
memset(ap, 0, sizeof(*ap) + len + 1);
ap->alias = start;
of_alias_add(ap, np, id, start, len);
}
}
/**
* of_alias_get_id - Get alias id for the given device_node
* @np: Pointer to the given device_node
* @stem: Alias stem of the given device_node
*
* The function travels the lookup table to get alias id for the given
* device_node and alias stem. It returns the alias id if find it.
*/
int of_alias_get_id(struct device_node *np, const char *stem)
{
struct alias_prop *app;
int id = -ENODEV;
mutex_lock(&of_aliases_mutex);
list_for_each_entry(app, &aliases_lookup, link) {
if (strcmp(app->stem, stem) != 0)
continue;
if (np == app->np) {
id = app->id;
break;
}
}
mutex_unlock(&of_aliases_mutex);
return id;
}
EXPORT_SYMBOL_GPL(of_alias_get_id);
const __be32 *of_prop_next_u32(struct property *prop, const __be32 *cur,
u32 *pu)
{
const void *curv = cur;
if (!prop)
return NULL;
if (!cur) {
curv = prop->value;
goto out_val;
}
curv += sizeof(*cur);
if (curv >= prop->value + prop->length)
return NULL;
out_val:
*pu = be32_to_cpup(curv);
return curv;
}
EXPORT_SYMBOL_GPL(of_prop_next_u32);
const char *of_prop_next_string(struct property *prop, const char *cur)
{
const void *curv = cur;
if (!prop)
return NULL;
if (!cur)
return prop->value;
curv += strlen(cur) + 1;
if (curv >= prop->value + prop->length)
return NULL;
return curv;
}
EXPORT_SYMBOL_GPL(of_prop_next_string);
/**
* of_device_is_stdout_path - check if a device node matches the
* linux,stdout-path property
*
* Check if this device node matches the linux,stdout-path property
* in the chosen node. return true if yes, false otherwise.
*/
int of_device_is_stdout_path(struct device_node *dn)
{
if (!of_stdout)
return false;
return of_stdout == dn;
}
EXPORT_SYMBOL_GPL(of_device_is_stdout_path);
/**
* of_find_next_cache_node - Find a node's subsidiary cache
* @np: node of type "cpu" or "cache"
*
* Returns a node pointer with refcount incremented, use
* of_node_put() on it when done. Caller should hold a reference
* to np.
*/
struct device_node *of_find_next_cache_node(const struct device_node *np)
{
struct device_node *child;
const phandle *handle;
handle = of_get_property(np, "l2-cache", NULL);
if (!handle)
handle = of_get_property(np, "next-level-cache", NULL);
if (handle)
return of_find_node_by_phandle(be32_to_cpup(handle));
/* OF on pmac has nodes instead of properties named "l2-cache"
* beneath CPU nodes.
*/
if (!strcmp(np->type, "cpu"))
for_each_child_of_node(np, child)
if (!strcmp(child->type, "cache"))
return child;
return NULL;
}
| gpl-2.0 |
consulo/consulo-apache-subversion | src/main/java/org/jetbrains/idea/svn/SvnCopiesRefreshManager.java | 1939 | /*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.idea.svn;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.util.RequestsMerger;
import com.intellij.util.Consumer;
import com.intellij.util.concurrency.Semaphore;
public class SvnCopiesRefreshManager {
private final RequestsMerger myRequestsMerger;
private final Semaphore mySemaphore;
private Runnable myMappingCallback;
public SvnCopiesRefreshManager(final SvnFileUrlMappingImpl mapping) {
mySemaphore = new Semaphore();
// svn mappings refresh inside also uses asynchronous pass -> we need to pass callback that will ping our "single-threaded" executor here
myMappingCallback = new Runnable() {
@Override
public void run() {
mySemaphore.up();
}
};
myRequestsMerger = new RequestsMerger(new Runnable() {
@Override
public void run() {
mySemaphore.down();
mapping.realRefresh(myMappingCallback);
mySemaphore.waitFor();
}
}, new Consumer<Runnable>() {
public void consume(final Runnable runnable) {
ApplicationManager.getApplication().executeOnPooledThread(runnable);
}
});
}
public void asynchRequest() {
myRequestsMerger.request();
}
public void waitRefresh(final Runnable runnable) {
myRequestsMerger.waitRefresh(runnable);
}
}
| apache-2.0 |
LauriM/PropellerEngine | thirdparty/Bullet/src/Bullet3Collision/BroadPhaseCollision/b3DynamicBvh.cpp | 36826 | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2013 Erwin Coumans http://bulletphysics.org
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
///b3DynamicBvh implementation by Nathanael Presson
#include "b3DynamicBvh.h"
//
typedef b3AlignedObjectArray<b3DbvtNode*> b3NodeArray;
typedef b3AlignedObjectArray<const b3DbvtNode*> b3ConstNodeArray;
//
struct b3DbvtNodeEnumerator : b3DynamicBvh::ICollide
{
b3ConstNodeArray nodes;
void Process(const b3DbvtNode* n) { nodes.push_back(n); }
};
//
static B3_DBVT_INLINE int b3IndexOf(const b3DbvtNode* node)
{
return(node->parent->childs[1]==node);
}
//
static B3_DBVT_INLINE b3DbvtVolume b3Merge( const b3DbvtVolume& a,
const b3DbvtVolume& b)
{
#if (B3_DBVT_MERGE_IMPL==B3_DBVT_IMPL_SSE)
B3_ATTRIBUTE_ALIGNED16(char locals[sizeof(b3DbvtAabbMm)]);
b3DbvtVolume& res=*(b3DbvtVolume*)locals;
#else
b3DbvtVolume res;
#endif
b3Merge(a,b,res);
return(res);
}
// volume+edge lengths
static B3_DBVT_INLINE b3Scalar b3Size(const b3DbvtVolume& a)
{
const b3Vector3 edges=a.Lengths();
return( edges.x*edges.y*edges.z+
edges.x+edges.y+edges.z);
}
//
static void b3GetMaxDepth(const b3DbvtNode* node,int depth,int& maxdepth)
{
if(node->isinternal())
{
b3GetMaxDepth(node->childs[0],depth+1,maxdepth);
b3GetMaxDepth(node->childs[1],depth+1,maxdepth);
} else maxdepth=b3Max(maxdepth,depth);
}
//
static B3_DBVT_INLINE void b3DeleteNode( b3DynamicBvh* pdbvt,
b3DbvtNode* node)
{
b3AlignedFree(pdbvt->m_free);
pdbvt->m_free=node;
}
//
static void b3RecurseDeleteNode( b3DynamicBvh* pdbvt,
b3DbvtNode* node)
{
if(!node->isleaf())
{
b3RecurseDeleteNode(pdbvt,node->childs[0]);
b3RecurseDeleteNode(pdbvt,node->childs[1]);
}
if(node==pdbvt->m_root) pdbvt->m_root=0;
b3DeleteNode(pdbvt,node);
}
//
static B3_DBVT_INLINE b3DbvtNode* b3CreateNode( b3DynamicBvh* pdbvt,
b3DbvtNode* parent,
void* data)
{
b3DbvtNode* node;
if(pdbvt->m_free)
{ node=pdbvt->m_free;pdbvt->m_free=0; }
else
{ node=new(b3AlignedAlloc(sizeof(b3DbvtNode),16)) b3DbvtNode(); }
node->parent = parent;
node->data = data;
node->childs[1] = 0;
return(node);
}
//
static B3_DBVT_INLINE b3DbvtNode* b3CreateNode( b3DynamicBvh* pdbvt,
b3DbvtNode* parent,
const b3DbvtVolume& volume,
void* data)
{
b3DbvtNode* node=b3CreateNode(pdbvt,parent,data);
node->volume=volume;
return(node);
}
//
static B3_DBVT_INLINE b3DbvtNode* b3CreateNode( b3DynamicBvh* pdbvt,
b3DbvtNode* parent,
const b3DbvtVolume& volume0,
const b3DbvtVolume& volume1,
void* data)
{
b3DbvtNode* node=b3CreateNode(pdbvt,parent,data);
b3Merge(volume0,volume1,node->volume);
return(node);
}
//
static void b3InsertLeaf( b3DynamicBvh* pdbvt,
b3DbvtNode* root,
b3DbvtNode* leaf)
{
if(!pdbvt->m_root)
{
pdbvt->m_root = leaf;
leaf->parent = 0;
}
else
{
if(!root->isleaf())
{
do {
root=root->childs[b3Select( leaf->volume,
root->childs[0]->volume,
root->childs[1]->volume)];
} while(!root->isleaf());
}
b3DbvtNode* prev=root->parent;
b3DbvtNode* node=b3CreateNode(pdbvt,prev,leaf->volume,root->volume,0);
if(prev)
{
prev->childs[b3IndexOf(root)] = node;
node->childs[0] = root;root->parent=node;
node->childs[1] = leaf;leaf->parent=node;
do {
if(!prev->volume.Contain(node->volume))
b3Merge(prev->childs[0]->volume,prev->childs[1]->volume,prev->volume);
else
break;
node=prev;
} while(0!=(prev=node->parent));
}
else
{
node->childs[0] = root;root->parent=node;
node->childs[1] = leaf;leaf->parent=node;
pdbvt->m_root = node;
}
}
}
//
static b3DbvtNode* b3RemoveLeaf( b3DynamicBvh* pdbvt,
b3DbvtNode* leaf)
{
if(leaf==pdbvt->m_root)
{
pdbvt->m_root=0;
return(0);
}
else
{
b3DbvtNode* parent=leaf->parent;
b3DbvtNode* prev=parent->parent;
b3DbvtNode* sibling=parent->childs[1-b3IndexOf(leaf)];
if(prev)
{
prev->childs[b3IndexOf(parent)]=sibling;
sibling->parent=prev;
b3DeleteNode(pdbvt,parent);
while(prev)
{
const b3DbvtVolume pb=prev->volume;
b3Merge(prev->childs[0]->volume,prev->childs[1]->volume,prev->volume);
if(b3NotEqual(pb,prev->volume))
{
prev=prev->parent;
} else break;
}
return(prev?prev:pdbvt->m_root);
}
else
{
pdbvt->m_root=sibling;
sibling->parent=0;
b3DeleteNode(pdbvt,parent);
return(pdbvt->m_root);
}
}
}
//
static void b3FetchLeaves(b3DynamicBvh* pdbvt,
b3DbvtNode* root,
b3NodeArray& leaves,
int depth=-1)
{
if(root->isinternal()&&depth)
{
b3FetchLeaves(pdbvt,root->childs[0],leaves,depth-1);
b3FetchLeaves(pdbvt,root->childs[1],leaves,depth-1);
b3DeleteNode(pdbvt,root);
}
else
{
leaves.push_back(root);
}
}
//
static void b3Split( const b3NodeArray& leaves,
b3NodeArray& left,
b3NodeArray& right,
const b3Vector3& org,
const b3Vector3& axis)
{
left.resize(0);
right.resize(0);
for(int i=0,ni=leaves.size();i<ni;++i)
{
if(b3Dot(axis,leaves[i]->volume.Center()-org)<0)
left.push_back(leaves[i]);
else
right.push_back(leaves[i]);
}
}
//
static b3DbvtVolume b3Bounds( const b3NodeArray& leaves)
{
#if B3_DBVT_MERGE_IMPL==B3_DBVT_IMPL_SSE
B3_ATTRIBUTE_ALIGNED16(char locals[sizeof(b3DbvtVolume)]);
b3DbvtVolume& volume=*(b3DbvtVolume*)locals;
volume=leaves[0]->volume;
#else
b3DbvtVolume volume=leaves[0]->volume;
#endif
for(int i=1,ni=leaves.size();i<ni;++i)
{
b3Merge(volume,leaves[i]->volume,volume);
}
return(volume);
}
//
static void b3BottomUp( b3DynamicBvh* pdbvt,
b3NodeArray& leaves)
{
while(leaves.size()>1)
{
b3Scalar minsize=B3_INFINITY;
int minidx[2]={-1,-1};
for(int i=0;i<leaves.size();++i)
{
for(int j=i+1;j<leaves.size();++j)
{
const b3Scalar sz=b3Size(b3Merge(leaves[i]->volume,leaves[j]->volume));
if(sz<minsize)
{
minsize = sz;
minidx[0] = i;
minidx[1] = j;
}
}
}
b3DbvtNode* n[] = {leaves[minidx[0]],leaves[minidx[1]]};
b3DbvtNode* p = b3CreateNode(pdbvt,0,n[0]->volume,n[1]->volume,0);
p->childs[0] = n[0];
p->childs[1] = n[1];
n[0]->parent = p;
n[1]->parent = p;
leaves[minidx[0]] = p;
leaves.swap(minidx[1],leaves.size()-1);
leaves.pop_back();
}
}
//
static b3DbvtNode* b3TopDown(b3DynamicBvh* pdbvt,
b3NodeArray& leaves,
int bu_treshold)
{
static const b3Vector3 axis[]={b3MakeVector3(1,0,0),
b3MakeVector3(0,1,0),
b3MakeVector3(0,0,1)};
if(leaves.size()>1)
{
if(leaves.size()>bu_treshold)
{
const b3DbvtVolume vol=b3Bounds(leaves);
const b3Vector3 org=vol.Center();
b3NodeArray sets[2];
int bestaxis=-1;
int bestmidp=leaves.size();
int splitcount[3][2]={{0,0},{0,0},{0,0}};
int i;
for( i=0;i<leaves.size();++i)
{
const b3Vector3 x=leaves[i]->volume.Center()-org;
for(int j=0;j<3;++j)
{
++splitcount[j][b3Dot(x,axis[j])>0?1:0];
}
}
for( i=0;i<3;++i)
{
if((splitcount[i][0]>0)&&(splitcount[i][1]>0))
{
const int midp=(int)b3Fabs(b3Scalar(splitcount[i][0]-splitcount[i][1]));
if(midp<bestmidp)
{
bestaxis=i;
bestmidp=midp;
}
}
}
if(bestaxis>=0)
{
sets[0].reserve(splitcount[bestaxis][0]);
sets[1].reserve(splitcount[bestaxis][1]);
b3Split(leaves,sets[0],sets[1],org,axis[bestaxis]);
}
else
{
sets[0].reserve(leaves.size()/2+1);
sets[1].reserve(leaves.size()/2);
for(int i=0,ni=leaves.size();i<ni;++i)
{
sets[i&1].push_back(leaves[i]);
}
}
b3DbvtNode* node=b3CreateNode(pdbvt,0,vol,0);
node->childs[0]=b3TopDown(pdbvt,sets[0],bu_treshold);
node->childs[1]=b3TopDown(pdbvt,sets[1],bu_treshold);
node->childs[0]->parent=node;
node->childs[1]->parent=node;
return(node);
}
else
{
b3BottomUp(pdbvt,leaves);
return(leaves[0]);
}
}
return(leaves[0]);
}
//
static B3_DBVT_INLINE b3DbvtNode* b3Sort(b3DbvtNode* n,b3DbvtNode*& r)
{
b3DbvtNode* p=n->parent;
b3Assert(n->isinternal());
if(p>n)
{
const int i=b3IndexOf(n);
const int j=1-i;
b3DbvtNode* s=p->childs[j];
b3DbvtNode* q=p->parent;
b3Assert(n==p->childs[i]);
if(q) q->childs[b3IndexOf(p)]=n; else r=n;
s->parent=n;
p->parent=n;
n->parent=q;
p->childs[0]=n->childs[0];
p->childs[1]=n->childs[1];
n->childs[0]->parent=p;
n->childs[1]->parent=p;
n->childs[i]=p;
n->childs[j]=s;
b3Swap(p->volume,n->volume);
return(p);
}
return(n);
}
#if 0
static B3_DBVT_INLINE b3DbvtNode* walkup(b3DbvtNode* n,int count)
{
while(n&&(count--)) n=n->parent;
return(n);
}
#endif
//
// Api
//
//
b3DynamicBvh::b3DynamicBvh()
{
m_root = 0;
m_free = 0;
m_lkhd = -1;
m_leaves = 0;
m_opath = 0;
}
//
b3DynamicBvh::~b3DynamicBvh()
{
clear();
}
//
void b3DynamicBvh::clear()
{
if(m_root)
b3RecurseDeleteNode(this,m_root);
b3AlignedFree(m_free);
m_free=0;
m_lkhd = -1;
m_stkStack.clear();
m_opath = 0;
}
//
void b3DynamicBvh::optimizeBottomUp()
{
if(m_root)
{
b3NodeArray leaves;
leaves.reserve(m_leaves);
b3FetchLeaves(this,m_root,leaves);
b3BottomUp(this,leaves);
m_root=leaves[0];
}
}
//
void b3DynamicBvh::optimizeTopDown(int bu_treshold)
{
if(m_root)
{
b3NodeArray leaves;
leaves.reserve(m_leaves);
b3FetchLeaves(this,m_root,leaves);
m_root=b3TopDown(this,leaves,bu_treshold);
}
}
//
void b3DynamicBvh::optimizeIncremental(int passes)
{
if(passes<0) passes=m_leaves;
if(m_root&&(passes>0))
{
do {
b3DbvtNode* node=m_root;
unsigned bit=0;
while(node->isinternal())
{
node=b3Sort(node,m_root)->childs[(m_opath>>bit)&1];
bit=(bit+1)&(sizeof(unsigned)*8-1);
}
update(node);
++m_opath;
} while(--passes);
}
}
//
b3DbvtNode* b3DynamicBvh::insert(const b3DbvtVolume& volume,void* data)
{
b3DbvtNode* leaf=b3CreateNode(this,0,volume,data);
b3InsertLeaf(this,m_root,leaf);
++m_leaves;
return(leaf);
}
//
void b3DynamicBvh::update(b3DbvtNode* leaf,int lookahead)
{
b3DbvtNode* root=b3RemoveLeaf(this,leaf);
if(root)
{
if(lookahead>=0)
{
for(int i=0;(i<lookahead)&&root->parent;++i)
{
root=root->parent;
}
} else root=m_root;
}
b3InsertLeaf(this,root,leaf);
}
//
void b3DynamicBvh::update(b3DbvtNode* leaf,b3DbvtVolume& volume)
{
b3DbvtNode* root=b3RemoveLeaf(this,leaf);
if(root)
{
if(m_lkhd>=0)
{
for(int i=0;(i<m_lkhd)&&root->parent;++i)
{
root=root->parent;
}
} else root=m_root;
}
leaf->volume=volume;
b3InsertLeaf(this,root,leaf);
}
//
bool b3DynamicBvh::update(b3DbvtNode* leaf,b3DbvtVolume& volume,const b3Vector3& velocity,b3Scalar margin)
{
if(leaf->volume.Contain(volume)) return(false);
volume.Expand(b3MakeVector3(margin,margin,margin));
volume.SignedExpand(velocity);
update(leaf,volume);
return(true);
}
//
bool b3DynamicBvh::update(b3DbvtNode* leaf,b3DbvtVolume& volume,const b3Vector3& velocity)
{
if(leaf->volume.Contain(volume)) return(false);
volume.SignedExpand(velocity);
update(leaf,volume);
return(true);
}
//
bool b3DynamicBvh::update(b3DbvtNode* leaf,b3DbvtVolume& volume,b3Scalar margin)
{
if(leaf->volume.Contain(volume)) return(false);
volume.Expand(b3MakeVector3(margin,margin,margin));
update(leaf,volume);
return(true);
}
//
void b3DynamicBvh::remove(b3DbvtNode* leaf)
{
b3RemoveLeaf(this,leaf);
b3DeleteNode(this,leaf);
--m_leaves;
}
//
void b3DynamicBvh::write(IWriter* iwriter) const
{
b3DbvtNodeEnumerator nodes;
nodes.nodes.reserve(m_leaves*2);
enumNodes(m_root,nodes);
iwriter->Prepare(m_root,nodes.nodes.size());
for(int i=0;i<nodes.nodes.size();++i)
{
const b3DbvtNode* n=nodes.nodes[i];
int p=-1;
if(n->parent) p=nodes.nodes.findLinearSearch(n->parent);
if(n->isinternal())
{
const int c0=nodes.nodes.findLinearSearch(n->childs[0]);
const int c1=nodes.nodes.findLinearSearch(n->childs[1]);
iwriter->WriteNode(n,i,p,c0,c1);
}
else
{
iwriter->WriteLeaf(n,i,p);
}
}
}
//
void b3DynamicBvh::clone(b3DynamicBvh& dest,IClone* iclone) const
{
dest.clear();
if(m_root!=0)
{
b3AlignedObjectArray<sStkCLN> stack;
stack.reserve(m_leaves);
stack.push_back(sStkCLN(m_root,0));
do {
const int i=stack.size()-1;
const sStkCLN e=stack[i];
b3DbvtNode* n=b3CreateNode(&dest,e.parent,e.node->volume,e.node->data);
stack.pop_back();
if(e.parent!=0)
e.parent->childs[i&1]=n;
else
dest.m_root=n;
if(e.node->isinternal())
{
stack.push_back(sStkCLN(e.node->childs[0],n));
stack.push_back(sStkCLN(e.node->childs[1],n));
}
else
{
iclone->CloneLeaf(n);
}
} while(stack.size()>0);
}
}
//
int b3DynamicBvh::maxdepth(const b3DbvtNode* node)
{
int depth=0;
if(node) b3GetMaxDepth(node,1,depth);
return(depth);
}
//
int b3DynamicBvh::countLeaves(const b3DbvtNode* node)
{
if(node->isinternal())
return(countLeaves(node->childs[0])+countLeaves(node->childs[1]));
else
return(1);
}
//
void b3DynamicBvh::extractLeaves(const b3DbvtNode* node,b3AlignedObjectArray<const b3DbvtNode*>& leaves)
{
if(node->isinternal())
{
extractLeaves(node->childs[0],leaves);
extractLeaves(node->childs[1],leaves);
}
else
{
leaves.push_back(node);
}
}
//
#if B3_DBVT_ENABLE_BENCHMARK
#include <stdio.h>
#include <stdlib.h>
/*
q6600,2.4ghz
/Ox /Ob2 /Oi /Ot /I "." /I "..\.." /I "..\..\src" /D "NDEBUG" /D "_LIB" /D "_WINDOWS" /D "_CRT_SECURE_NO_DEPRECATE" /D "_CRT_NONSTDC_NO_DEPRECATE" /D "WIN32"
/GF /FD /MT /GS- /Gy /arch:SSE2 /Zc:wchar_t- /Fp"..\..\out\release8\build\libbulletcollision\libbulletcollision.pch"
/Fo"..\..\out\release8\build\libbulletcollision\\"
/Fd"..\..\out\release8\build\libbulletcollision\bulletcollision.pdb"
/W3 /nologo /c /Wp64 /Zi /errorReport:prompt
Benchmarking dbvt...
World scale: 100.000000
Extents base: 1.000000
Extents range: 4.000000
Leaves: 8192
sizeof(b3DbvtVolume): 32 bytes
sizeof(b3DbvtNode): 44 bytes
[1] b3DbvtVolume intersections: 3499 ms (-1%)
[2] b3DbvtVolume merges: 1934 ms (0%)
[3] b3DynamicBvh::collideTT: 5485 ms (-21%)
[4] b3DynamicBvh::collideTT self: 2814 ms (-20%)
[5] b3DynamicBvh::collideTT xform: 7379 ms (-1%)
[6] b3DynamicBvh::collideTT xform,self: 7270 ms (-2%)
[7] b3DynamicBvh::rayTest: 6314 ms (0%),(332143 r/s)
[8] insert/remove: 2093 ms (0%),(1001983 ir/s)
[9] updates (teleport): 1879 ms (-3%),(1116100 u/s)
[10] updates (jitter): 1244 ms (-4%),(1685813 u/s)
[11] optimize (incremental): 2514 ms (0%),(1668000 o/s)
[12] b3DbvtVolume notequal: 3659 ms (0%)
[13] culling(OCL+fullsort): 2218 ms (0%),(461 t/s)
[14] culling(OCL+qsort): 3688 ms (5%),(2221 t/s)
[15] culling(KDOP+qsort): 1139 ms (-1%),(7192 t/s)
[16] insert/remove batch(256): 5092 ms (0%),(823704 bir/s)
[17] b3DbvtVolume select: 3419 ms (0%)
*/
struct b3DbvtBenchmark
{
struct NilPolicy : b3DynamicBvh::ICollide
{
NilPolicy() : m_pcount(0),m_depth(-B3_INFINITY),m_checksort(true) {}
void Process(const b3DbvtNode*,const b3DbvtNode*) { ++m_pcount; }
void Process(const b3DbvtNode*) { ++m_pcount; }
void Process(const b3DbvtNode*,b3Scalar depth)
{
++m_pcount;
if(m_checksort)
{ if(depth>=m_depth) m_depth=depth; else printf("wrong depth: %f (should be >= %f)\r\n",depth,m_depth); }
}
int m_pcount;
b3Scalar m_depth;
bool m_checksort;
};
struct P14 : b3DynamicBvh::ICollide
{
struct Node
{
const b3DbvtNode* leaf;
b3Scalar depth;
};
void Process(const b3DbvtNode* leaf,b3Scalar depth)
{
Node n;
n.leaf = leaf;
n.depth = depth;
}
static int sortfnc(const Node& a,const Node& b)
{
if(a.depth<b.depth) return(+1);
if(a.depth>b.depth) return(-1);
return(0);
}
b3AlignedObjectArray<Node> m_nodes;
};
struct P15 : b3DynamicBvh::ICollide
{
struct Node
{
const b3DbvtNode* leaf;
b3Scalar depth;
};
void Process(const b3DbvtNode* leaf)
{
Node n;
n.leaf = leaf;
n.depth = dot(leaf->volume.Center(),m_axis);
}
static int sortfnc(const Node& a,const Node& b)
{
if(a.depth<b.depth) return(+1);
if(a.depth>b.depth) return(-1);
return(0);
}
b3AlignedObjectArray<Node> m_nodes;
b3Vector3 m_axis;
};
static b3Scalar RandUnit()
{
return(rand()/(b3Scalar)RAND_MAX);
}
static b3Vector3 RandVector3()
{
return(b3Vector3(RandUnit(),RandUnit(),RandUnit()));
}
static b3Vector3 RandVector3(b3Scalar cs)
{
return(RandVector3()*cs-b3Vector3(cs,cs,cs)/2);
}
static b3DbvtVolume RandVolume(b3Scalar cs,b3Scalar eb,b3Scalar es)
{
return(b3DbvtVolume::FromCE(RandVector3(cs),b3Vector3(eb,eb,eb)+RandVector3()*es));
}
static b3Transform RandTransform(b3Scalar cs)
{
b3Transform t;
t.setOrigin(RandVector3(cs));
t.setRotation(b3Quaternion(RandUnit()*B3_PI*2,RandUnit()*B3_PI*2,RandUnit()*B3_PI*2).normalized());
return(t);
}
static void RandTree(b3Scalar cs,b3Scalar eb,b3Scalar es,int leaves,b3DynamicBvh& dbvt)
{
dbvt.clear();
for(int i=0;i<leaves;++i)
{
dbvt.insert(RandVolume(cs,eb,es),0);
}
}
};
void b3DynamicBvh::benchmark()
{
static const b3Scalar cfgVolumeCenterScale = 100;
static const b3Scalar cfgVolumeExentsBase = 1;
static const b3Scalar cfgVolumeExentsScale = 4;
static const int cfgLeaves = 8192;
static const bool cfgEnable = true;
//[1] b3DbvtVolume intersections
bool cfgBenchmark1_Enable = cfgEnable;
static const int cfgBenchmark1_Iterations = 8;
static const int cfgBenchmark1_Reference = 3499;
//[2] b3DbvtVolume merges
bool cfgBenchmark2_Enable = cfgEnable;
static const int cfgBenchmark2_Iterations = 4;
static const int cfgBenchmark2_Reference = 1945;
//[3] b3DynamicBvh::collideTT
bool cfgBenchmark3_Enable = cfgEnable;
static const int cfgBenchmark3_Iterations = 512;
static const int cfgBenchmark3_Reference = 5485;
//[4] b3DynamicBvh::collideTT self
bool cfgBenchmark4_Enable = cfgEnable;
static const int cfgBenchmark4_Iterations = 512;
static const int cfgBenchmark4_Reference = 2814;
//[5] b3DynamicBvh::collideTT xform
bool cfgBenchmark5_Enable = cfgEnable;
static const int cfgBenchmark5_Iterations = 512;
static const b3Scalar cfgBenchmark5_OffsetScale = 2;
static const int cfgBenchmark5_Reference = 7379;
//[6] b3DynamicBvh::collideTT xform,self
bool cfgBenchmark6_Enable = cfgEnable;
static const int cfgBenchmark6_Iterations = 512;
static const b3Scalar cfgBenchmark6_OffsetScale = 2;
static const int cfgBenchmark6_Reference = 7270;
//[7] b3DynamicBvh::rayTest
bool cfgBenchmark7_Enable = cfgEnable;
static const int cfgBenchmark7_Passes = 32;
static const int cfgBenchmark7_Iterations = 65536;
static const int cfgBenchmark7_Reference = 6307;
//[8] insert/remove
bool cfgBenchmark8_Enable = cfgEnable;
static const int cfgBenchmark8_Passes = 32;
static const int cfgBenchmark8_Iterations = 65536;
static const int cfgBenchmark8_Reference = 2105;
//[9] updates (teleport)
bool cfgBenchmark9_Enable = cfgEnable;
static const int cfgBenchmark9_Passes = 32;
static const int cfgBenchmark9_Iterations = 65536;
static const int cfgBenchmark9_Reference = 1879;
//[10] updates (jitter)
bool cfgBenchmark10_Enable = cfgEnable;
static const b3Scalar cfgBenchmark10_Scale = cfgVolumeCenterScale/10000;
static const int cfgBenchmark10_Passes = 32;
static const int cfgBenchmark10_Iterations = 65536;
static const int cfgBenchmark10_Reference = 1244;
//[11] optimize (incremental)
bool cfgBenchmark11_Enable = cfgEnable;
static const int cfgBenchmark11_Passes = 64;
static const int cfgBenchmark11_Iterations = 65536;
static const int cfgBenchmark11_Reference = 2510;
//[12] b3DbvtVolume notequal
bool cfgBenchmark12_Enable = cfgEnable;
static const int cfgBenchmark12_Iterations = 32;
static const int cfgBenchmark12_Reference = 3677;
//[13] culling(OCL+fullsort)
bool cfgBenchmark13_Enable = cfgEnable;
static const int cfgBenchmark13_Iterations = 1024;
static const int cfgBenchmark13_Reference = 2231;
//[14] culling(OCL+qsort)
bool cfgBenchmark14_Enable = cfgEnable;
static const int cfgBenchmark14_Iterations = 8192;
static const int cfgBenchmark14_Reference = 3500;
//[15] culling(KDOP+qsort)
bool cfgBenchmark15_Enable = cfgEnable;
static const int cfgBenchmark15_Iterations = 8192;
static const int cfgBenchmark15_Reference = 1151;
//[16] insert/remove batch
bool cfgBenchmark16_Enable = cfgEnable;
static const int cfgBenchmark16_BatchCount = 256;
static const int cfgBenchmark16_Passes = 16384;
static const int cfgBenchmark16_Reference = 5138;
//[17] select
bool cfgBenchmark17_Enable = cfgEnable;
static const int cfgBenchmark17_Iterations = 4;
static const int cfgBenchmark17_Reference = 3390;
b3Clock wallclock;
printf("Benchmarking dbvt...\r\n");
printf("\tWorld scale: %f\r\n",cfgVolumeCenterScale);
printf("\tExtents base: %f\r\n",cfgVolumeExentsBase);
printf("\tExtents range: %f\r\n",cfgVolumeExentsScale);
printf("\tLeaves: %u\r\n",cfgLeaves);
printf("\tsizeof(b3DbvtVolume): %u bytes\r\n",sizeof(b3DbvtVolume));
printf("\tsizeof(b3DbvtNode): %u bytes\r\n",sizeof(b3DbvtNode));
if(cfgBenchmark1_Enable)
{// Benchmark 1
srand(380843);
b3AlignedObjectArray<b3DbvtVolume> volumes;
b3AlignedObjectArray<bool> results;
volumes.resize(cfgLeaves);
results.resize(cfgLeaves);
for(int i=0;i<cfgLeaves;++i)
{
volumes[i]=b3DbvtBenchmark::RandVolume(cfgVolumeCenterScale,cfgVolumeExentsBase,cfgVolumeExentsScale);
}
printf("[1] b3DbvtVolume intersections: ");
wallclock.reset();
for(int i=0;i<cfgBenchmark1_Iterations;++i)
{
for(int j=0;j<cfgLeaves;++j)
{
for(int k=0;k<cfgLeaves;++k)
{
results[k]=Intersect(volumes[j],volumes[k]);
}
}
}
const int time=(int)wallclock.getTimeMilliseconds();
printf("%u ms (%i%%)\r\n",time,(time-cfgBenchmark1_Reference)*100/time);
}
if(cfgBenchmark2_Enable)
{// Benchmark 2
srand(380843);
b3AlignedObjectArray<b3DbvtVolume> volumes;
b3AlignedObjectArray<b3DbvtVolume> results;
volumes.resize(cfgLeaves);
results.resize(cfgLeaves);
for(int i=0;i<cfgLeaves;++i)
{
volumes[i]=b3DbvtBenchmark::RandVolume(cfgVolumeCenterScale,cfgVolumeExentsBase,cfgVolumeExentsScale);
}
printf("[2] b3DbvtVolume merges: ");
wallclock.reset();
for(int i=0;i<cfgBenchmark2_Iterations;++i)
{
for(int j=0;j<cfgLeaves;++j)
{
for(int k=0;k<cfgLeaves;++k)
{
Merge(volumes[j],volumes[k],results[k]);
}
}
}
const int time=(int)wallclock.getTimeMilliseconds();
printf("%u ms (%i%%)\r\n",time,(time-cfgBenchmark2_Reference)*100/time);
}
if(cfgBenchmark3_Enable)
{// Benchmark 3
srand(380843);
b3DynamicBvh dbvt[2];
b3DbvtBenchmark::NilPolicy policy;
b3DbvtBenchmark::RandTree(cfgVolumeCenterScale,cfgVolumeExentsBase,cfgVolumeExentsScale,cfgLeaves,dbvt[0]);
b3DbvtBenchmark::RandTree(cfgVolumeCenterScale,cfgVolumeExentsBase,cfgVolumeExentsScale,cfgLeaves,dbvt[1]);
dbvt[0].optimizeTopDown();
dbvt[1].optimizeTopDown();
printf("[3] b3DynamicBvh::collideTT: ");
wallclock.reset();
for(int i=0;i<cfgBenchmark3_Iterations;++i)
{
b3DynamicBvh::collideTT(dbvt[0].m_root,dbvt[1].m_root,policy);
}
const int time=(int)wallclock.getTimeMilliseconds();
printf("%u ms (%i%%)\r\n",time,(time-cfgBenchmark3_Reference)*100/time);
}
if(cfgBenchmark4_Enable)
{// Benchmark 4
srand(380843);
b3DynamicBvh dbvt;
b3DbvtBenchmark::NilPolicy policy;
b3DbvtBenchmark::RandTree(cfgVolumeCenterScale,cfgVolumeExentsBase,cfgVolumeExentsScale,cfgLeaves,dbvt);
dbvt.optimizeTopDown();
printf("[4] b3DynamicBvh::collideTT self: ");
wallclock.reset();
for(int i=0;i<cfgBenchmark4_Iterations;++i)
{
b3DynamicBvh::collideTT(dbvt.m_root,dbvt.m_root,policy);
}
const int time=(int)wallclock.getTimeMilliseconds();
printf("%u ms (%i%%)\r\n",time,(time-cfgBenchmark4_Reference)*100/time);
}
if(cfgBenchmark5_Enable)
{// Benchmark 5
srand(380843);
b3DynamicBvh dbvt[2];
b3AlignedObjectArray<b3Transform> transforms;
b3DbvtBenchmark::NilPolicy policy;
transforms.resize(cfgBenchmark5_Iterations);
for(int i=0;i<transforms.size();++i)
{
transforms[i]=b3DbvtBenchmark::RandTransform(cfgVolumeCenterScale*cfgBenchmark5_OffsetScale);
}
b3DbvtBenchmark::RandTree(cfgVolumeCenterScale,cfgVolumeExentsBase,cfgVolumeExentsScale,cfgLeaves,dbvt[0]);
b3DbvtBenchmark::RandTree(cfgVolumeCenterScale,cfgVolumeExentsBase,cfgVolumeExentsScale,cfgLeaves,dbvt[1]);
dbvt[0].optimizeTopDown();
dbvt[1].optimizeTopDown();
printf("[5] b3DynamicBvh::collideTT xform: ");
wallclock.reset();
for(int i=0;i<cfgBenchmark5_Iterations;++i)
{
b3DynamicBvh::collideTT(dbvt[0].m_root,dbvt[1].m_root,transforms[i],policy);
}
const int time=(int)wallclock.getTimeMilliseconds();
printf("%u ms (%i%%)\r\n",time,(time-cfgBenchmark5_Reference)*100/time);
}
if(cfgBenchmark6_Enable)
{// Benchmark 6
srand(380843);
b3DynamicBvh dbvt;
b3AlignedObjectArray<b3Transform> transforms;
b3DbvtBenchmark::NilPolicy policy;
transforms.resize(cfgBenchmark6_Iterations);
for(int i=0;i<transforms.size();++i)
{
transforms[i]=b3DbvtBenchmark::RandTransform(cfgVolumeCenterScale*cfgBenchmark6_OffsetScale);
}
b3DbvtBenchmark::RandTree(cfgVolumeCenterScale,cfgVolumeExentsBase,cfgVolumeExentsScale,cfgLeaves,dbvt);
dbvt.optimizeTopDown();
printf("[6] b3DynamicBvh::collideTT xform,self: ");
wallclock.reset();
for(int i=0;i<cfgBenchmark6_Iterations;++i)
{
b3DynamicBvh::collideTT(dbvt.m_root,dbvt.m_root,transforms[i],policy);
}
const int time=(int)wallclock.getTimeMilliseconds();
printf("%u ms (%i%%)\r\n",time,(time-cfgBenchmark6_Reference)*100/time);
}
if(cfgBenchmark7_Enable)
{// Benchmark 7
srand(380843);
b3DynamicBvh dbvt;
b3AlignedObjectArray<b3Vector3> rayorg;
b3AlignedObjectArray<b3Vector3> raydir;
b3DbvtBenchmark::NilPolicy policy;
rayorg.resize(cfgBenchmark7_Iterations);
raydir.resize(cfgBenchmark7_Iterations);
for(int i=0;i<rayorg.size();++i)
{
rayorg[i]=b3DbvtBenchmark::RandVector3(cfgVolumeCenterScale*2);
raydir[i]=b3DbvtBenchmark::RandVector3(cfgVolumeCenterScale*2);
}
b3DbvtBenchmark::RandTree(cfgVolumeCenterScale,cfgVolumeExentsBase,cfgVolumeExentsScale,cfgLeaves,dbvt);
dbvt.optimizeTopDown();
printf("[7] b3DynamicBvh::rayTest: ");
wallclock.reset();
for(int i=0;i<cfgBenchmark7_Passes;++i)
{
for(int j=0;j<cfgBenchmark7_Iterations;++j)
{
b3DynamicBvh::rayTest(dbvt.m_root,rayorg[j],rayorg[j]+raydir[j],policy);
}
}
const int time=(int)wallclock.getTimeMilliseconds();
unsigned rays=cfgBenchmark7_Passes*cfgBenchmark7_Iterations;
printf("%u ms (%i%%),(%u r/s)\r\n",time,(time-cfgBenchmark7_Reference)*100/time,(rays*1000)/time);
}
if(cfgBenchmark8_Enable)
{// Benchmark 8
srand(380843);
b3DynamicBvh dbvt;
b3DbvtBenchmark::RandTree(cfgVolumeCenterScale,cfgVolumeExentsBase,cfgVolumeExentsScale,cfgLeaves,dbvt);
dbvt.optimizeTopDown();
printf("[8] insert/remove: ");
wallclock.reset();
for(int i=0;i<cfgBenchmark8_Passes;++i)
{
for(int j=0;j<cfgBenchmark8_Iterations;++j)
{
dbvt.remove(dbvt.insert(b3DbvtBenchmark::RandVolume(cfgVolumeCenterScale,cfgVolumeExentsBase,cfgVolumeExentsScale),0));
}
}
const int time=(int)wallclock.getTimeMilliseconds();
const int ir=cfgBenchmark8_Passes*cfgBenchmark8_Iterations;
printf("%u ms (%i%%),(%u ir/s)\r\n",time,(time-cfgBenchmark8_Reference)*100/time,ir*1000/time);
}
if(cfgBenchmark9_Enable)
{// Benchmark 9
srand(380843);
b3DynamicBvh dbvt;
b3AlignedObjectArray<const b3DbvtNode*> leaves;
b3DbvtBenchmark::RandTree(cfgVolumeCenterScale,cfgVolumeExentsBase,cfgVolumeExentsScale,cfgLeaves,dbvt);
dbvt.optimizeTopDown();
dbvt.extractLeaves(dbvt.m_root,leaves);
printf("[9] updates (teleport): ");
wallclock.reset();
for(int i=0;i<cfgBenchmark9_Passes;++i)
{
for(int j=0;j<cfgBenchmark9_Iterations;++j)
{
dbvt.update(const_cast<b3DbvtNode*>(leaves[rand()%cfgLeaves]),
b3DbvtBenchmark::RandVolume(cfgVolumeCenterScale,cfgVolumeExentsBase,cfgVolumeExentsScale));
}
}
const int time=(int)wallclock.getTimeMilliseconds();
const int up=cfgBenchmark9_Passes*cfgBenchmark9_Iterations;
printf("%u ms (%i%%),(%u u/s)\r\n",time,(time-cfgBenchmark9_Reference)*100/time,up*1000/time);
}
if(cfgBenchmark10_Enable)
{// Benchmark 10
srand(380843);
b3DynamicBvh dbvt;
b3AlignedObjectArray<const b3DbvtNode*> leaves;
b3AlignedObjectArray<b3Vector3> vectors;
vectors.resize(cfgBenchmark10_Iterations);
for(int i=0;i<vectors.size();++i)
{
vectors[i]=(b3DbvtBenchmark::RandVector3()*2-b3Vector3(1,1,1))*cfgBenchmark10_Scale;
}
b3DbvtBenchmark::RandTree(cfgVolumeCenterScale,cfgVolumeExentsBase,cfgVolumeExentsScale,cfgLeaves,dbvt);
dbvt.optimizeTopDown();
dbvt.extractLeaves(dbvt.m_root,leaves);
printf("[10] updates (jitter): ");
wallclock.reset();
for(int i=0;i<cfgBenchmark10_Passes;++i)
{
for(int j=0;j<cfgBenchmark10_Iterations;++j)
{
const b3Vector3& d=vectors[j];
b3DbvtNode* l=const_cast<b3DbvtNode*>(leaves[rand()%cfgLeaves]);
b3DbvtVolume v=b3DbvtVolume::FromMM(l->volume.Mins()+d,l->volume.Maxs()+d);
dbvt.update(l,v);
}
}
const int time=(int)wallclock.getTimeMilliseconds();
const int up=cfgBenchmark10_Passes*cfgBenchmark10_Iterations;
printf("%u ms (%i%%),(%u u/s)\r\n",time,(time-cfgBenchmark10_Reference)*100/time,up*1000/time);
}
if(cfgBenchmark11_Enable)
{// Benchmark 11
srand(380843);
b3DynamicBvh dbvt;
b3DbvtBenchmark::RandTree(cfgVolumeCenterScale,cfgVolumeExentsBase,cfgVolumeExentsScale,cfgLeaves,dbvt);
dbvt.optimizeTopDown();
printf("[11] optimize (incremental): ");
wallclock.reset();
for(int i=0;i<cfgBenchmark11_Passes;++i)
{
dbvt.optimizeIncremental(cfgBenchmark11_Iterations);
}
const int time=(int)wallclock.getTimeMilliseconds();
const int op=cfgBenchmark11_Passes*cfgBenchmark11_Iterations;
printf("%u ms (%i%%),(%u o/s)\r\n",time,(time-cfgBenchmark11_Reference)*100/time,op/time*1000);
}
if(cfgBenchmark12_Enable)
{// Benchmark 12
srand(380843);
b3AlignedObjectArray<b3DbvtVolume> volumes;
b3AlignedObjectArray<bool> results;
volumes.resize(cfgLeaves);
results.resize(cfgLeaves);
for(int i=0;i<cfgLeaves;++i)
{
volumes[i]=b3DbvtBenchmark::RandVolume(cfgVolumeCenterScale,cfgVolumeExentsBase,cfgVolumeExentsScale);
}
printf("[12] b3DbvtVolume notequal: ");
wallclock.reset();
for(int i=0;i<cfgBenchmark12_Iterations;++i)
{
for(int j=0;j<cfgLeaves;++j)
{
for(int k=0;k<cfgLeaves;++k)
{
results[k]=NotEqual(volumes[j],volumes[k]);
}
}
}
const int time=(int)wallclock.getTimeMilliseconds();
printf("%u ms (%i%%)\r\n",time,(time-cfgBenchmark12_Reference)*100/time);
}
if(cfgBenchmark13_Enable)
{// Benchmark 13
srand(380843);
b3DynamicBvh dbvt;
b3AlignedObjectArray<b3Vector3> vectors;
b3DbvtBenchmark::NilPolicy policy;
vectors.resize(cfgBenchmark13_Iterations);
for(int i=0;i<vectors.size();++i)
{
vectors[i]=(b3DbvtBenchmark::RandVector3()*2-b3Vector3(1,1,1)).normalized();
}
b3DbvtBenchmark::RandTree(cfgVolumeCenterScale,cfgVolumeExentsBase,cfgVolumeExentsScale,cfgLeaves,dbvt);
dbvt.optimizeTopDown();
printf("[13] culling(OCL+fullsort): ");
wallclock.reset();
for(int i=0;i<cfgBenchmark13_Iterations;++i)
{
static const b3Scalar offset=0;
policy.m_depth=-B3_INFINITY;
dbvt.collideOCL(dbvt.m_root,&vectors[i],&offset,vectors[i],1,policy);
}
const int time=(int)wallclock.getTimeMilliseconds();
const int t=cfgBenchmark13_Iterations;
printf("%u ms (%i%%),(%u t/s)\r\n",time,(time-cfgBenchmark13_Reference)*100/time,(t*1000)/time);
}
if(cfgBenchmark14_Enable)
{// Benchmark 14
srand(380843);
b3DynamicBvh dbvt;
b3AlignedObjectArray<b3Vector3> vectors;
b3DbvtBenchmark::P14 policy;
vectors.resize(cfgBenchmark14_Iterations);
for(int i=0;i<vectors.size();++i)
{
vectors[i]=(b3DbvtBenchmark::RandVector3()*2-b3Vector3(1,1,1)).normalized();
}
b3DbvtBenchmark::RandTree(cfgVolumeCenterScale,cfgVolumeExentsBase,cfgVolumeExentsScale,cfgLeaves,dbvt);
dbvt.optimizeTopDown();
policy.m_nodes.reserve(cfgLeaves);
printf("[14] culling(OCL+qsort): ");
wallclock.reset();
for(int i=0;i<cfgBenchmark14_Iterations;++i)
{
static const b3Scalar offset=0;
policy.m_nodes.resize(0);
dbvt.collideOCL(dbvt.m_root,&vectors[i],&offset,vectors[i],1,policy,false);
policy.m_nodes.quickSort(b3DbvtBenchmark::P14::sortfnc);
}
const int time=(int)wallclock.getTimeMilliseconds();
const int t=cfgBenchmark14_Iterations;
printf("%u ms (%i%%),(%u t/s)\r\n",time,(time-cfgBenchmark14_Reference)*100/time,(t*1000)/time);
}
if(cfgBenchmark15_Enable)
{// Benchmark 15
srand(380843);
b3DynamicBvh dbvt;
b3AlignedObjectArray<b3Vector3> vectors;
b3DbvtBenchmark::P15 policy;
vectors.resize(cfgBenchmark15_Iterations);
for(int i=0;i<vectors.size();++i)
{
vectors[i]=(b3DbvtBenchmark::RandVector3()*2-b3Vector3(1,1,1)).normalized();
}
b3DbvtBenchmark::RandTree(cfgVolumeCenterScale,cfgVolumeExentsBase,cfgVolumeExentsScale,cfgLeaves,dbvt);
dbvt.optimizeTopDown();
policy.m_nodes.reserve(cfgLeaves);
printf("[15] culling(KDOP+qsort): ");
wallclock.reset();
for(int i=0;i<cfgBenchmark15_Iterations;++i)
{
static const b3Scalar offset=0;
policy.m_nodes.resize(0);
policy.m_axis=vectors[i];
dbvt.collideKDOP(dbvt.m_root,&vectors[i],&offset,1,policy);
policy.m_nodes.quickSort(b3DbvtBenchmark::P15::sortfnc);
}
const int time=(int)wallclock.getTimeMilliseconds();
const int t=cfgBenchmark15_Iterations;
printf("%u ms (%i%%),(%u t/s)\r\n",time,(time-cfgBenchmark15_Reference)*100/time,(t*1000)/time);
}
if(cfgBenchmark16_Enable)
{// Benchmark 16
srand(380843);
b3DynamicBvh dbvt;
b3AlignedObjectArray<b3DbvtNode*> batch;
b3DbvtBenchmark::RandTree(cfgVolumeCenterScale,cfgVolumeExentsBase,cfgVolumeExentsScale,cfgLeaves,dbvt);
dbvt.optimizeTopDown();
batch.reserve(cfgBenchmark16_BatchCount);
printf("[16] insert/remove batch(%u): ",cfgBenchmark16_BatchCount);
wallclock.reset();
for(int i=0;i<cfgBenchmark16_Passes;++i)
{
for(int j=0;j<cfgBenchmark16_BatchCount;++j)
{
batch.push_back(dbvt.insert(b3DbvtBenchmark::RandVolume(cfgVolumeCenterScale,cfgVolumeExentsBase,cfgVolumeExentsScale),0));
}
for(int j=0;j<cfgBenchmark16_BatchCount;++j)
{
dbvt.remove(batch[j]);
}
batch.resize(0);
}
const int time=(int)wallclock.getTimeMilliseconds();
const int ir=cfgBenchmark16_Passes*cfgBenchmark16_BatchCount;
printf("%u ms (%i%%),(%u bir/s)\r\n",time,(time-cfgBenchmark16_Reference)*100/time,int(ir*1000.0/time));
}
if(cfgBenchmark17_Enable)
{// Benchmark 17
srand(380843);
b3AlignedObjectArray<b3DbvtVolume> volumes;
b3AlignedObjectArray<int> results;
b3AlignedObjectArray<int> indices;
volumes.resize(cfgLeaves);
results.resize(cfgLeaves);
indices.resize(cfgLeaves);
for(int i=0;i<cfgLeaves;++i)
{
indices[i]=i;
volumes[i]=b3DbvtBenchmark::RandVolume(cfgVolumeCenterScale,cfgVolumeExentsBase,cfgVolumeExentsScale);
}
for(int i=0;i<cfgLeaves;++i)
{
b3Swap(indices[i],indices[rand()%cfgLeaves]);
}
printf("[17] b3DbvtVolume select: ");
wallclock.reset();
for(int i=0;i<cfgBenchmark17_Iterations;++i)
{
for(int j=0;j<cfgLeaves;++j)
{
for(int k=0;k<cfgLeaves;++k)
{
const int idx=indices[k];
results[idx]=Select(volumes[idx],volumes[j],volumes[k]);
}
}
}
const int time=(int)wallclock.getTimeMilliseconds();
printf("%u ms (%i%%)\r\n",time,(time-cfgBenchmark17_Reference)*100/time);
}
printf("\r\n\r\n");
}
#endif
| bsd-2-clause |
redmunds/cdnjs | ajax/libs/cropperjs/0.4.0/cropper.js | 83381 | /*!
* Cropper v0.4.0
* https://github.com/fengyuanchen/cropperjs
*
* Copyright (c) 2015 Fengyuan Chen
* Released under the MIT license
*
* Date: 2015-12-02T06:35:32.008Z
*/
(function (global, factory) {
if (typeof module === 'object' && typeof module.exports === 'object') {
module.exports = global.document ? factory(global, true) : function (w) {
if (!w.document) {
throw new Error('Cropper requires a window with a document');
}
return factory(w);
};
} else {
factory(global);
}
})(typeof window !== 'undefined' ? window : this, function (window, noGlobal) {
'use strict';
// Globals
var document = window.document;
var location = window.location;
// Constants
var NAMESPACE = 'cropper';
// Classes
var CLASS_MODAL = 'cropper-modal';
var CLASS_HIDE = 'cropper-hide';
var CLASS_HIDDEN = 'cropper-hidden';
var CLASS_INVISIBLE = 'cropper-invisible';
var CLASS_MOVE = 'cropper-move';
var CLASS_CROP = 'cropper-crop';
var CLASS_DISABLED = 'cropper-disabled';
var CLASS_BG = 'cropper-bg';
// Events
var EVENT_MOUSE_DOWN = 'mousedown touchstart pointerdown MSPointerDown';
var EVENT_MOUSE_MOVE = 'mousemove touchmove pointermove MSPointerMove';
var EVENT_MOUSE_UP = 'mouseup touchend touchcancel pointerup pointercancel MSPointerUp MSPointerCancel';
var EVENT_WHEEL = 'wheel mousewheel DOMMouseScroll';
var EVENT_DBLCLICK = 'dblclick';
var EVENT_RESIZE = 'resize';
var EVENT_ERROR = 'error';
var EVENT_LOAD = 'load';
// RegExps
var REGEXP_ACTIONS = /^(e|w|s|n|se|sw|ne|nw|all|crop|move|zoom)$/;
var REGEXP_SPACES = /\s+/;
var REGEXP_TRIM = /^\s+(.*)\s+^/;
// Data
var DATA_PREVIEW = 'preview';
var DATA_ACTION = 'action';
// Actions
var ACTION_EAST = 'e';
var ACTION_WEST = 'w';
var ACTION_SOUTH = 's';
var ACTION_NORTH = 'n';
var ACTION_SOUTH_EAST = 'se';
var ACTION_SOUTH_WEST = 'sw';
var ACTION_NORTH_EAST = 'ne';
var ACTION_NORTH_WEST = 'nw';
var ACTION_ALL = 'all';
var ACTION_CROP = 'crop';
var ACTION_MOVE = 'move';
var ACTION_ZOOM = 'zoom';
var ACTION_NONE = 'none';
// Supports
var SUPPORT_CANVAS = !!document.createElement('canvas').getContext;
// Maths
var num = Number;
var min = Math.min;
var max = Math.max;
var abs = Math.abs;
var sin = Math.sin;
var cos = Math.cos;
var sqrt = Math.sqrt;
var round = Math.round;
var floor = Math.floor;
// Prototype
var prototype = {
version: '0.4.0'
};
// Utilities
var EMPTY_OBJECT = {};
var toString = EMPTY_OBJECT.toString;
var hasOwnProperty = EMPTY_OBJECT.hasOwnProperty;
function typeOf(obj) {
return toString.call(obj).slice(8, -1).toLowerCase();
}
function isString(str) {
return typeof str === 'string';
}
function isNumber(num) {
return typeof num === 'number' && !isNaN(num);
}
function isUndefined(obj) {
return typeof obj === 'undefined';
}
function isObject(obj) {
return typeof obj === 'object' && obj !== null;
}
function isPlainObject(obj) {
var constructor;
var prototype;
if (!isObject(obj)) {
return false;
}
try {
constructor = obj.constructor;
prototype = constructor.prototype;
return constructor && prototype && hasOwnProperty.call(prototype, 'isPrototypeOf');
} catch (e) {
return false;
}
}
function isFunction(fn) {
return typeOf(fn) === 'function';
}
function isArray(arr) {
return Array.isArray ? Array.isArray(arr) : typeOf(arr) === 'array';
}
function toArray(obj, offset) {
var args = [];
// This is necessary for IE8
if (isNumber(offset)) {
args.push(offset);
}
return args.slice.apply(obj, args);
}
function inArray(value, arr) {
var index = -1;
each(arr, function (n, i) {
if (n === value) {
index = i;
return false;
}
});
return index;
}
function trim(str) {
if (!isString(str)) {
str = String(str);
}
if (str.trim) {
str = str.trim();
} else {
str = str.replace(REGEXP_TRIM, '$1');
}
return str;
}
function each(obj, callback) {
var length;
var i;
if (obj && isFunction(callback)) {
if (isArray(obj) || isNumber(obj.length)/* array-like */) {
for (i = 0, length = obj.length; i < length; i++) {
if (callback.call(obj, obj[i], i, obj) === false) {
break;
}
}
} else if (isObject(obj)) {
for (i in obj) {
if (hasOwnProperty.call(obj, i)) {
if (callback.call(obj, obj[i], i, obj) === false) {
break;
}
}
}
}
}
return obj;
}
function extend(obj) {
var args = toArray(arguments);
if (args.length > 1) {
args.shift();
}
each(args, function (arg) {
each(arg, function (prop, i) {
obj[i] = prop;
});
});
return obj;
}
function proxy(fn, context) {
var args = toArray(arguments, 2);
return function () {
return fn.apply(context, args.concat(toArray(arguments)));
};
}
function parseClass(className) {
return trim(className).split(REGEXP_SPACES);
}
function hasClass(element, value) {
return element.className.indexOf(value) > -1;
}
function addClass(element, value) {
var classes;
if (isNumber(element.length)) {
return each(element, function (elem) {
addClass(elem, value);
});
}
classes = parseClass(element.className);
each(parseClass(value), function (n) {
if (inArray(n, classes) < 0) {
classes.push(n);
}
});
element.className = classes.join(' ');
}
function removeClass(element, value) {
var classes;
if (isNumber(element.length)) {
return each(element, function (elem) {
removeClass(elem, value);
});
}
classes = parseClass(element.className);
each(parseClass(value), function (n, i) {
if ((i = inArray(n, classes)) > -1) {
classes.splice(i, 1);
}
});
element.className = classes.join(' ');
}
function toggleClass(element, value, added) {
return added ? addClass(element, value) : removeClass(element, value);
}
function getData(element, name) {
if (isObject(element[name])) {
return element[name];
} else if (element.dataset) {
return element.dataset[name];
} else {
return element.getAttribute('data-' + name);
}
}
function setData(element, name, data) {
if (isObject(data) && isUndefined(element[name])) {
element[name] = data;
} else if (element.dataset) {
element.dataset[name] = data;
} else {
element.setAttribute('data-' + name, data);
}
}
function removeData(element, name) {
if (isObject(element[name])) {
delete element[name];
} else if (element.dataset) {
delete element.dataset[name];
} else {
element.removeAttribute('data-' + name);
}
}
function addListener(element, type, handler) {
var types;
if (!isFunction(handler)) {
return;
}
types = trim(type).split(REGEXP_SPACES);
if (types.length > 1) {
return each(types, function (type) {
addListener(element, type, handler);
});
}
if (element.addEventListener) {
element.addEventListener(type, handler, false);
} else if (element.attachEvent) {
element.attachEvent('on' + type, handler);
}
}
function removeListener(element, type, handler) {
var types;
if (!isFunction(handler)) {
return;
}
types = trim(type).split(REGEXP_SPACES);
if (types.length > 1) {
return each(types, function (type) {
removeListener(element, type, handler);
});
}
if (element.removeEventListener) {
element.removeEventListener(type, handler, false);
} else if (element.detachEvent) {
element.detachEvent('on' + type, handler);
}
}
function preventDefault(e) {
if (e) {
if (e.preventDefault) {
e.preventDefault();
} else {
e.returnValue = false;
}
}
}
function getEvent(event) {
var e = event || window.event;
var doc;
// Fix target property (IE8)
if (!e.target) {
e.target = e.srcElement || document;
}
if (!isNumber(e.pageX)) {
doc = document.documentElement;
e.pageX = e.clientX + (window.scrollX || doc && doc.scrollLeft || 0) - (doc && doc.clientLeft || 0);
e.pageY = e.clientY + (window.scrollY || doc && doc.scrollTop || 0) - (doc && doc.clientTop || 0);
}
return e;
}
function getOffset(element) {
var doc = document.documentElement;
var box = element.getBoundingClientRect();
return {
left: box.left + (window.scrollX || doc && doc.scrollLeft || 0) - (doc && doc.clientLeft || 0),
top: box.top + (window.scrollY || doc && doc.scrollTop || 0) - (doc && doc.clientTop || 0)
};
}
function querySelector(element, selector) {
return element.querySelector(selector);
}
function querySelectorAll(element, selector) {
return element.querySelectorAll(selector);
}
function insertBefore(element, elem) {
element.parentNode.insertBefore(elem, element);
}
function appendChild(element, elem) {
element.appendChild(elem);
}
function removeChild(element) {
element.parentNode.removeChild(element);
}
function empty(element) {
while (element.firstChild) {
element.removeChild(element.firstChild);
}
}
function isCrossOriginURL(url) {
var parts = url.match(/^(https?:)\/\/([^\:\/\?#]+):?(\d*)/i);
return parts && (
parts[1] !== location.protocol ||
parts[2] !== location.hostname ||
parts[3] !== location.port
);
}
function setCrossOrigin(image, crossOrigin) {
if (crossOrigin) {
image.crossOrigin = crossOrigin;
}
}
function addTimestamp(url) {
var timestamp = 'timestamp=' + (new Date()).getTime();
return (url + (url.indexOf('?') === -1 ? '?' : '&') + timestamp);
}
function getImageSize(image, callback) {
var newImage;
// Modern browsers
if (image.naturalWidth) {
return callback(image.naturalWidth, image.naturalHeight);
}
// IE8: Don't use `new Image()` here
newImage = document.createElement('img');
newImage.onload = function () {
callback(this.width, this.height);
};
newImage.src = image.src;
}
function getTransform(options) {
var transforms = [];
var rotate = options.rotate;
var scaleX = options.scaleX;
var scaleY = options.scaleY;
if (isNumber(rotate)) {
transforms.push('rotate(' + rotate + 'deg)');
}
if (isNumber(scaleX) && isNumber(scaleY)) {
transforms.push('scale(' + scaleX + ',' + scaleY + ')');
}
return transforms.length ? transforms.join(' ') : 'none';
}
function getRotatedSizes(data, isReversed) {
var deg = abs(data.degree) % 180;
var arc = (deg > 90 ? (180 - deg) : deg) * Math.PI / 180;
var sinArc = sin(arc);
var cosArc = cos(arc);
var width = data.width;
var height = data.height;
var aspectRatio = data.aspectRatio;
var newWidth;
var newHeight;
if (!isReversed) {
newWidth = width * cosArc + height * sinArc;
newHeight = width * sinArc + height * cosArc;
} else {
newWidth = width / (cosArc + sinArc / aspectRatio);
newHeight = newWidth / aspectRatio;
}
return {
width: newWidth,
height: newHeight
};
}
function getSourceCanvas(image, data) {
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
var x = 0;
var y = 0;
var width = data.naturalWidth;
var height = data.naturalHeight;
var rotate = data.rotate;
var scaleX = data.scaleX;
var scaleY = data.scaleY;
var scalable = isNumber(scaleX) && isNumber(scaleY) && (scaleX !== 1 || scaleY !== 1);
var rotatable = isNumber(rotate) && rotate !== 0;
var advanced = rotatable || scalable;
var canvasWidth = width;
var canvasHeight = height;
var translateX;
var translateY;
var rotated;
if (scalable) {
translateX = width / 2;
translateY = height / 2;
}
if (rotatable) {
rotated = getRotatedSizes({
width: width,
height: height,
degree: rotate
});
canvasWidth = rotated.width;
canvasHeight = rotated.height;
translateX = rotated.width / 2;
translateY = rotated.height / 2;
}
canvas.width = canvasWidth;
canvas.height = canvasHeight;
if (advanced) {
x = -width / 2;
y = -height / 2;
context.save();
context.translate(translateX, translateY);
}
if (rotatable) {
context.rotate(rotate * Math.PI / 180);
}
// Should call `scale` after rotated
if (scalable) {
context.scale(scaleX, scaleY);
}
context.drawImage(image, floor(x), floor(y), floor(width), floor(height));
if (advanced) {
context.restore();
}
return canvas;
}
function Cropper(element, options) {
this.element = element;
this.options = extend({}, Cropper.DEFAULTS, isPlainObject(options) && options);
this.isLoaded = false;
this.isBuilt = false;
this.isCompleted = false;
this.isRotated = false;
this.isCropped = false;
this.isDisabled = false;
this.isReplaced = false;
this.isLimited = false;
this.isImg = false;
this.originalUrl = '';
this.crossOrigin = '';
this.canvasData = null;
this.cropBoxData = null;
this.previews = null;
this.init();
}
extend(prototype, {
init: function () {
var element = this.element;
var tagName = element.tagName.toLowerCase();
var url;
if (getData(element, NAMESPACE)) {
return;
}
setData(element, NAMESPACE, this);
if (tagName === 'img') {
this.isImg = true;
// e.g.: "img/picture.jpg"
this.originalUrl = url = element.getAttribute('src');
// Stop when it's a blank image
if (!url) {
return;
}
// e.g.: "http://example.com/img/picture.jpg"
url = element.src;
} else if (tagName === 'canvas' && SUPPORT_CANVAS) {
url = element.toDataURL();
}
this.load(url);
},
load: function (url) {
var options = this.options;
var element = this.element;
var crossOrigin;
var bustCacheUrl;
var image;
var start;
var stop;
if (!url) {
return;
}
this.url = url;
if (isFunction(options.build) && options.build.call(element) === false) {
return;
}
if (options.checkCrossOrigin && isCrossOriginURL(url)) {
crossOrigin = element.crossOrigin;
if (!crossOrigin) {
crossOrigin = 'anonymous';
bustCacheUrl = addTimestamp(url);
}
}
this.crossOrigin = crossOrigin;
image = document.createElement('img');
setCrossOrigin(image, crossOrigin);
image.src = bustCacheUrl || url;
this.image = image;
this._start = start = proxy(this.start, this);
this._stop = stop = proxy(this.stop, this);
if (this.isImg) {
if (element.complete) {
this.start();
} else {
addListener(element, EVENT_LOAD, start);
}
} else {
addListener(image, EVENT_LOAD, start);
addListener(image, EVENT_ERROR, stop);
addClass(image, CLASS_HIDE);
insertBefore(element, image);
}
},
start: function (event) {
var image = this.isImg ? this.element : this.image;
if (event) {
removeListener(image, EVENT_LOAD, this._start);
removeListener(image, EVENT_ERROR, this._stop);
}
getImageSize(image, proxy(function (naturalWidth, naturalHeight) {
this.imageData = {
naturalWidth: naturalWidth,
naturalHeight: naturalHeight,
aspectRatio: naturalWidth / naturalHeight
};
this.isLoaded = true;
this.build();
}, this));
},
stop: function () {
var image = this.image;
removeListener(image, EVENT_LOAD, this._start);
removeListener(image, EVENT_ERROR, this._stop);
removeChild(image);
this.image = null;
}
});
extend(prototype, {
build: function () {
var options = this.options;
var element = this.element;
var image = this.image;
var template;
var cropper;
var canvas;
var dragBox;
var cropBox;
var face;
if (!this.isLoaded) {
return;
}
// Unbuild first when replace
if (this.isBuilt) {
this.unbuild();
}
template = document.createElement('div');
template.innerHTML = Cropper.TEMPLATE;
// Create cropper elements
this.container = element.parentNode;
this.cropper = cropper = querySelector(template, '.cropper-container');
this.canvas = canvas = querySelector(cropper, '.cropper-canvas');
this.dragBox = dragBox = querySelector(cropper, '.cropper-drag-box');
this.cropBox = cropBox = querySelector(cropper, '.cropper-crop-box');
this.viewBox = querySelector(cropper, '.cropper-view-box');
this.face = face = querySelector(cropBox, '.cropper-face');
appendChild(canvas, image);
// Hide the original image
addClass(element, CLASS_HIDDEN);
insertBefore(element, cropper);
// Show the image if is hidden
if (!this.isImg) {
removeClass(image, CLASS_HIDE);
}
this.initPreview();
this.bind();
options.aspectRatio = max(0, options.aspectRatio) || NaN;
options.viewMode = max(0, min(3, round(options.viewMode))) || 0;
if (options.autoCrop) {
this.isCropped = true;
if (options.modal) {
addClass(dragBox, CLASS_MODAL);
}
} else {
addClass(cropBox, CLASS_HIDDEN);
}
if (!options.guides) {
addClass(querySelectorAll(cropBox, '.cropper-dashed'), CLASS_HIDDEN);
}
if (!options.center) {
addClass(querySelector(cropBox, '.cropper-center'), CLASS_HIDDEN);
}
if (options.background) {
addClass(cropper, CLASS_BG);
}
if (!options.highlight) {
addClass(face, CLASS_INVISIBLE);
}
if (options.cropBoxMovable) {
addClass(face, CLASS_MOVE);
setData(face, DATA_ACTION, ACTION_ALL);
}
if (!options.cropBoxResizable) {
addClass(querySelectorAll(cropBox, '.cropper-line'), CLASS_HIDDEN);
addClass(querySelectorAll(cropBox, '.cropper-point'), CLASS_HIDDEN);
}
this.setDragMode(options.dragMode);
this.render();
this.isBuilt = true;
this.setData(options.data);
// Call the built asynchronously to keep "image.cropper" is defined
setTimeout(proxy(function () {
if (isFunction(options.built)) {
options.built.call(element);
}
if (isFunction(options.crop)) {
options.crop.call(element, this.getData());
}
this.isCompleted = true;
}, this), 0);
},
unbuild: function () {
if (!this.isBuilt) {
return;
}
this.isBuilt = false;
this.initialImageData = null;
// Clear `initialCanvasData` is necessary when replace
this.initialCanvasData = null;
this.initialCropBoxData = null;
this.containerData = null;
this.canvasData = null;
// Clear `cropBoxData` is necessary when replace
this.cropBoxData = null;
this.unbind();
this.resetPreview();
this.previews = null;
this.viewBox = null;
this.cropBox = null;
this.dragBox = null;
this.canvas = null;
this.container = null;
removeChild(this.cropper);
this.cropper = null;
}
});
extend(prototype, {
render: function () {
this.initContainer();
this.initCanvas();
this.initCropBox();
this.renderCanvas();
if (this.isCropped) {
this.renderCropBox();
}
},
initContainer: function () {
var options = this.options;
var element = this.element;
var container = this.container;
var cropper = this.cropper;
var containerData;
addClass(cropper, CLASS_HIDDEN);
removeClass(element, CLASS_HIDDEN);
this.containerData = containerData = {
width: max(container.offsetWidth, num(options.minContainerWidth) || 200),
height: max(container.offsetHeight, num(options.minContainerHeight) || 100)
};
cropper.style.cssText = (
'width:' + containerData.width + 'px;' +
'height:' + containerData.height + 'px;'
);
addClass(element, CLASS_HIDDEN);
removeClass(cropper, CLASS_HIDDEN);
},
// Canvas (image wrapper)
initCanvas: function () {
var viewMode = this.options.viewMode;
var containerData = this.containerData;
var containerWidth = containerData.width;
var containerHeight = containerData.height;
var imageData = this.imageData;
var aspectRatio = imageData.aspectRatio;
var canvasData = {
naturalWidth: imageData.naturalWidth,
naturalHeight: imageData.naturalHeight,
aspectRatio: aspectRatio,
width: containerWidth,
height: containerHeight
};
if (containerHeight * aspectRatio > containerWidth) {
if (viewMode === 3) {
canvasData.width = containerHeight * aspectRatio;
} else {
canvasData.height = containerWidth / aspectRatio;
}
} else {
if (viewMode === 3) {
canvasData.height = containerWidth / aspectRatio;
} else {
canvasData.width = containerHeight * aspectRatio;
}
}
canvasData.oldLeft = canvasData.left = (containerWidth - canvasData.width) / 2;
canvasData.oldTop = canvasData.top = (containerHeight - canvasData.height) / 2;
this.canvasData = canvasData;
this.isLimited = (viewMode === 1 || viewMode === 2);
this.limitCanvas(true, true);
this.initialImageData = extend({}, imageData);
this.initialCanvasData = extend({}, canvasData);
},
limitCanvas: function (isSizeLimited, isPositionLimited) {
var options = this.options;
var viewMode = options.viewMode;
var containerData = this.containerData;
var containerWidth = containerData.width;
var containerHeight = containerData.height;
var canvasData = this.canvasData;
var aspectRatio = canvasData.aspectRatio;
var cropBoxData = this.cropBoxData;
var isCropped = this.isCropped && cropBoxData;
var minCanvasWidth;
var minCanvasHeight;
var newCanvasLeft;
var newCanvasTop;
if (isSizeLimited) {
minCanvasWidth = num(options.minCanvasWidth) || 0;
minCanvasHeight = num(options.minCanvasHeight) || 0;
if (viewMode) {
if (viewMode > 1) {
minCanvasWidth = max(minCanvasWidth, containerWidth);
minCanvasHeight = max(minCanvasHeight, containerHeight);
if (viewMode === 3) {
if (minCanvasHeight * aspectRatio > minCanvasWidth) {
minCanvasWidth = minCanvasHeight * aspectRatio;
} else {
minCanvasHeight = minCanvasWidth / aspectRatio;
}
}
} else {
if (minCanvasWidth) {
minCanvasWidth = max(minCanvasWidth, isCropped ? cropBoxData.width : 0);
} else if (minCanvasHeight) {
minCanvasHeight = max(minCanvasHeight, isCropped ? cropBoxData.height : 0);
} else if (isCropped) {
minCanvasWidth = cropBoxData.width;
minCanvasHeight = cropBoxData.height;
if (minCanvasHeight * aspectRatio > minCanvasWidth) {
minCanvasWidth = minCanvasHeight * aspectRatio;
} else {
minCanvasHeight = minCanvasWidth / aspectRatio;
}
}
}
}
if (minCanvasWidth && minCanvasHeight) {
if (minCanvasHeight * aspectRatio > minCanvasWidth) {
minCanvasHeight = minCanvasWidth / aspectRatio;
} else {
minCanvasWidth = minCanvasHeight * aspectRatio;
}
} else if (minCanvasWidth) {
minCanvasHeight = minCanvasWidth / aspectRatio;
} else if (minCanvasHeight) {
minCanvasWidth = minCanvasHeight * aspectRatio;
}
canvasData.minWidth = minCanvasWidth;
canvasData.minHeight = minCanvasHeight;
canvasData.maxWidth = Infinity;
canvasData.maxHeight = Infinity;
}
if (isPositionLimited) {
if (viewMode) {
newCanvasLeft = containerWidth - canvasData.width;
newCanvasTop = containerHeight - canvasData.height;
canvasData.minLeft = min(0, newCanvasLeft);
canvasData.minTop = min(0, newCanvasTop);
canvasData.maxLeft = max(0, newCanvasLeft);
canvasData.maxTop = max(0, newCanvasTop);
if (isCropped && this.isLimited) {
canvasData.minLeft = min(
cropBoxData.left,
cropBoxData.left + cropBoxData.width - canvasData.width
);
canvasData.minTop = min(
cropBoxData.top,
cropBoxData.top + cropBoxData.height - canvasData.height
);
canvasData.maxLeft = cropBoxData.left;
canvasData.maxTop = cropBoxData.top;
if (viewMode === 2) {
if (canvasData.width >= containerWidth) {
canvasData.minLeft = min(0, newCanvasLeft);
canvasData.maxLeft = max(0, newCanvasLeft);
}
if (canvasData.height >= containerHeight) {
canvasData.minTop = min(0, newCanvasTop);
canvasData.maxTop = max(0, newCanvasTop);
}
}
}
} else {
canvasData.minLeft = -canvasData.width;
canvasData.minTop = -canvasData.height;
canvasData.maxLeft = containerWidth;
canvasData.maxTop = containerHeight;
}
}
},
renderCanvas: function (isChanged) {
var canvasData = this.canvasData;
var imageData = this.imageData;
var rotate = imageData.rotate;
var naturalWidth = imageData.naturalWidth;
var naturalHeight = imageData.naturalHeight;
var aspectRatio;
var rotatedData;
if (this.isRotated) {
this.isRotated = false;
// Computes rotated sizes with image sizes
rotatedData = getRotatedSizes({
width: imageData.width,
height: imageData.height,
degree: rotate
});
aspectRatio = rotatedData.width / rotatedData.height;
if (aspectRatio !== canvasData.aspectRatio) {
canvasData.left -= (rotatedData.width - canvasData.width) / 2;
canvasData.top -= (rotatedData.height - canvasData.height) / 2;
canvasData.width = rotatedData.width;
canvasData.height = rotatedData.height;
canvasData.aspectRatio = aspectRatio;
canvasData.naturalWidth = naturalWidth;
canvasData.naturalHeight = naturalHeight;
// Computes rotated sizes with natural image sizes
if (rotate % 180) {
rotatedData = getRotatedSizes({
width: naturalWidth,
height: naturalHeight,
degree: rotate
});
canvasData.naturalWidth = rotatedData.width;
canvasData.naturalHeight = rotatedData.height;
}
this.limitCanvas(true, false);
}
}
if (canvasData.width > canvasData.maxWidth || canvasData.width < canvasData.minWidth) {
canvasData.left = canvasData.oldLeft;
}
if (canvasData.height > canvasData.maxHeight || canvasData.height < canvasData.minHeight) {
canvasData.top = canvasData.oldTop;
}
canvasData.width = min(
max(canvasData.width, canvasData.minWidth),
canvasData.maxWidth
);
canvasData.height = min(
max(canvasData.height, canvasData.minHeight),
canvasData.maxHeight
);
this.limitCanvas(false, true);
canvasData.oldLeft = canvasData.left = min(
max(canvasData.left, canvasData.minLeft),
canvasData.maxLeft
);
canvasData.oldTop = canvasData.top = min(
max(canvasData.top, canvasData.minTop),
canvasData.maxTop
);
this.canvas.style.cssText = (
'width:' + canvasData.width + 'px;' +
'height:' + canvasData.height + 'px;' +
'left:' + canvasData.left + 'px;' +
'top:' + canvasData.top + 'px;'
);
this.renderImage();
if (this.isCropped && this.isLimited) {
this.limitCropBox(true, true);
}
if (isChanged) {
this.output();
}
},
renderImage: function (isChanged) {
var canvasData = this.canvasData;
var imageData = this.imageData;
var reversedData;
var transform;
if (imageData.rotate) {
reversedData = getRotatedSizes({
width: canvasData.width,
height: canvasData.height,
degree: imageData.rotate,
aspectRatio: imageData.aspectRatio
}, true);
}
extend(imageData, reversedData ? {
width: reversedData.width,
height: reversedData.height,
left: (canvasData.width - reversedData.width) / 2,
top: (canvasData.height - reversedData.height) / 2
} : {
width: canvasData.width,
height: canvasData.height,
left: 0,
top: 0
});
transform = getTransform(imageData);
this.image.style.cssText = (
'width:' + imageData.width + 'px;' +
'height:' + imageData.height + 'px;' +
'margin-left:' + imageData.left + 'px;' +
'margin-top:' + imageData.top + 'px;' +
'-webkit-transform:' + transform + ';' +
'-ms-transform:' + transform + ';' +
'transform:' + transform + ';'
);
if (isChanged) {
this.output();
}
},
initCropBox: function () {
var options = this.options;
var aspectRatio = options.aspectRatio;
var autoCropArea = num(options.autoCropArea) || 0.8;
var canvasData = this.canvasData;
var cropBoxData = {
width: canvasData.width,
height: canvasData.height
};
if (aspectRatio) {
if (canvasData.height * aspectRatio > canvasData.width) {
cropBoxData.height = cropBoxData.width / aspectRatio;
} else {
cropBoxData.width = cropBoxData.height * aspectRatio;
}
}
this.cropBoxData = cropBoxData;
this.limitCropBox(true, true);
// Initialize auto crop area
cropBoxData.width = min(
max(cropBoxData.width, cropBoxData.minWidth),
cropBoxData.maxWidth
);
cropBoxData.height = min(
max(cropBoxData.height, cropBoxData.minHeight),
cropBoxData.maxHeight
);
// The width/height of auto crop area must large than "minWidth/Height"
cropBoxData.width = max(
cropBoxData.minWidth,
cropBoxData.width * autoCropArea
);
cropBoxData.height = max(
cropBoxData.minHeight,
cropBoxData.height * autoCropArea
);
cropBoxData.oldLeft = cropBoxData.left = canvasData.left + (canvasData.width - cropBoxData.width) / 2;
cropBoxData.oldTop = cropBoxData.top = canvasData.top + (canvasData.height - cropBoxData.height) / 2;
this.initialCropBoxData = extend({}, cropBoxData);
},
limitCropBox: function (isSizeLimited, isPositionLimited) {
var options = this.options;
var aspectRatio = options.aspectRatio;
var containerData = this.containerData;
var containerWidth = containerData.width;
var containerHeight = containerData.height;
var canvasData = this.canvasData;
var cropBoxData = this.cropBoxData;
var isLimited = this.isLimited;
var minCropBoxWidth;
var minCropBoxHeight;
var maxCropBoxWidth;
var maxCropBoxHeight;
if (isSizeLimited) {
minCropBoxWidth = num(options.minCropBoxWidth) || 0;
minCropBoxHeight = num(options.minCropBoxHeight) || 0;
// The min/maxCropBoxWidth/Height must be less than containerWidth/Height
minCropBoxWidth = min(minCropBoxWidth, containerWidth);
minCropBoxHeight = min(minCropBoxHeight, containerHeight);
maxCropBoxWidth = min(containerWidth, isLimited ? canvasData.width : containerWidth);
maxCropBoxHeight = min(containerHeight, isLimited ? canvasData.height : containerHeight);
if (aspectRatio) {
if (minCropBoxWidth && minCropBoxHeight) {
if (minCropBoxHeight * aspectRatio > minCropBoxWidth) {
minCropBoxHeight = minCropBoxWidth / aspectRatio;
} else {
minCropBoxWidth = minCropBoxHeight * aspectRatio;
}
} else if (minCropBoxWidth) {
minCropBoxHeight = minCropBoxWidth / aspectRatio;
} else if (minCropBoxHeight) {
minCropBoxWidth = minCropBoxHeight * aspectRatio;
}
if (maxCropBoxHeight * aspectRatio > maxCropBoxWidth) {
maxCropBoxHeight = maxCropBoxWidth / aspectRatio;
} else {
maxCropBoxWidth = maxCropBoxHeight * aspectRatio;
}
}
// The minWidth/Height must be less than maxWidth/Height
cropBoxData.minWidth = min(minCropBoxWidth, maxCropBoxWidth);
cropBoxData.minHeight = min(minCropBoxHeight, maxCropBoxHeight);
cropBoxData.maxWidth = maxCropBoxWidth;
cropBoxData.maxHeight = maxCropBoxHeight;
}
if (isPositionLimited) {
if (isLimited) {
cropBoxData.minLeft = max(0, canvasData.left);
cropBoxData.minTop = max(0, canvasData.top);
cropBoxData.maxLeft = min(containerWidth, canvasData.left + canvasData.width) - cropBoxData.width;
cropBoxData.maxTop = min(containerHeight, canvasData.top + canvasData.height) - cropBoxData.height;
} else {
cropBoxData.minLeft = 0;
cropBoxData.minTop = 0;
cropBoxData.maxLeft = containerWidth - cropBoxData.width;
cropBoxData.maxTop = containerHeight - cropBoxData.height;
}
}
},
renderCropBox: function () {
var options = this.options;
var containerData = this.containerData;
var containerWidth = containerData.width;
var containerHeight = containerData.height;
var cropBoxData = this.cropBoxData;
if (cropBoxData.width > cropBoxData.maxWidth || cropBoxData.width < cropBoxData.minWidth) {
cropBoxData.left = cropBoxData.oldLeft;
}
if (cropBoxData.height > cropBoxData.maxHeight || cropBoxData.height < cropBoxData.minHeight) {
cropBoxData.top = cropBoxData.oldTop;
}
cropBoxData.width = min(
max(cropBoxData.width, cropBoxData.minWidth),
cropBoxData.maxWidth
);
cropBoxData.height = min(
max(cropBoxData.height, cropBoxData.minHeight),
cropBoxData.maxHeight
);
this.limitCropBox(false, true);
cropBoxData.oldLeft = cropBoxData.left = min(
max(cropBoxData.left, cropBoxData.minLeft),
cropBoxData.maxLeft
);
cropBoxData.oldTop = cropBoxData.top = min(
max(cropBoxData.top, cropBoxData.minTop),
cropBoxData.maxTop
);
if (options.movable && options.cropBoxDataMovable) {
// Turn to move the canvas when the crop box is equal to the container
setData(this.face, DATA_ACTION, (cropBoxData.width === containerWidth && cropBoxData.height === containerHeight) ? ACTION_MOVE : ACTION_ALL);
}
this.cropBox.style.cssText = (
'width:' + cropBoxData.width + 'px;' +
'height:' + cropBoxData.height + 'px;' +
'left:' + cropBoxData.left + 'px;' +
'top:' + cropBoxData.top + 'px;'
);
if (this.isCropped && this.isLimited) {
this.limitCanvas(true, true);
}
if (!this.isDisabled) {
this.output();
}
},
output: function () {
var options = this.options;
this.preview();
if (this.isCompleted && isFunction(options.crop)) {
options.crop.call(this.element, this.getData());
}
}
});
extend(prototype, {
initPreview: function () {
var preview = this.options.preview;
var image = document.createElement('img');
var crossOrigin = this.crossOrigin;
var url = this.url;
var previews;
setCrossOrigin(image, crossOrigin);
image.src = url;
appendChild(this.viewBox, image);
if (!preview) {
return;
}
this.previews = previews = querySelectorAll(document, preview);
each(previews, function (element) {
var image = document.createElement('img');
// Save the original size for recover
setData(element, DATA_PREVIEW, {
width: element.offsetWidth,
height: element.offsetHeight,
html: element.innerHTML
});
setCrossOrigin(image, crossOrigin);
image.src = url;
/**
* Override img element styles
* Add `display:block` to avoid margin top issue
* Add `height:auto` to override `height` attribute on IE8
* (Occur only when margin-top <= -height)
*/
image.style.cssText = (
'display:block;width:100%;height:auto;' +
'min-width:0!important;min-height:0!important;' +
'max-width:none!important;max-height:none!important;' +
'image-orientation:0deg!important;"'
);
empty(element);
appendChild(element, image);
});
},
resetPreview: function () {
each(this.previews, function (element) {
var data = getData(element, DATA_PREVIEW);
element.style.width = data.width + 'px';
element.style.height = data.height + 'px';
element.innerHTML = data.html;
removeData(element, DATA_PREVIEW);
});
},
preview: function () {
var imageData = this.imageData;
var canvasData = this.canvasData;
var cropBoxData = this.cropBoxData;
var cropBoxWidth = cropBoxData.width;
var cropBoxHeight = cropBoxData.height;
var width = imageData.width;
var height = imageData.height;
var left = cropBoxData.left - canvasData.left - imageData.left;
var top = cropBoxData.top - canvasData.top - imageData.top;
var transform = getTransform(imageData);
if (!this.isCropped || this.isDisabled) {
return;
}
querySelector(this.viewBox, 'img').style.cssText = (
'width:' + width + 'px;' +
'height:' + height + 'px;' +
'margin-left:' + -left + 'px;' +
'margin-top:' + -top + 'px;' +
'-webkit-transform:' + transform + ';' +
'-ms-transform:' + transform + ';' +
'transform:' + transform + ';'
);
each(this.previews, function (element) {
var imageStyle = querySelector(element, 'img').style;
var data = getData(element, DATA_PREVIEW);
var originalWidth = data.width;
var originalHeight = data.height;
var newWidth = originalWidth;
var newHeight = originalHeight;
var ratio = 1;
if (cropBoxWidth) {
ratio = originalWidth / cropBoxWidth;
newHeight = cropBoxHeight * ratio;
}
if (cropBoxHeight && newHeight > originalHeight) {
ratio = originalHeight / cropBoxHeight;
newWidth = cropBoxWidth * ratio;
newHeight = originalHeight;
}
element.style.width = newWidth + 'px';
element.style.height = newHeight + 'px';
imageStyle.width = width * ratio + 'px';
imageStyle.height = height * ratio + 'px';
imageStyle.marginLeft = -left * ratio + 'px';
imageStyle.marginTop = -top * ratio + 'px';
imageStyle.WebkitTransform = transform;
imageStyle.msTransform = transform;
imageStyle.transform = transform;
});
}
});
extend(prototype, {
bind: function () {
var options = this.options;
var cropper = this.cropper;
addListener(cropper, EVENT_MOUSE_DOWN, proxy(this.cropStart, this));
if (options.zoomable && options.zoomOnWheel) {
addListener(cropper, EVENT_WHEEL, proxy(this.wheel, this));
}
if (options.toggleDragModeOnDblclick) {
addListener(cropper, EVENT_DBLCLICK, proxy(this.dblclick, this));
}
addListener(document, EVENT_MOUSE_MOVE, (this._cropMove = proxy(this.cropMove, this)));
addListener(document, EVENT_MOUSE_UP, (this._cropEnd = proxy(this.cropEnd, this)));
if (options.responsive) {
addListener(window, EVENT_RESIZE, (this._resize = proxy(this.resize, this)));
}
},
unbind: function () {
var options = this.options;
var cropper = this.cropper;
removeListener(cropper, EVENT_MOUSE_DOWN, this.cropStart);
if (options.zoomable && options.zoomOnWheel) {
removeListener(cropper, EVENT_WHEEL, this.wheel);
}
if (options.toggleDragModeOnDblclick) {
removeListener(cropper, EVENT_DBLCLICK, this.dblclick);
}
removeListener(document, EVENT_MOUSE_MOVE, this._cropMove);
removeListener(document, EVENT_MOUSE_UP, this._cropEnd);
if (options.responsive) {
removeListener(window, EVENT_RESIZE, this._resize);
}
}
});
extend(prototype, {
resize: function () {
var restore = this.options.restore;
var container = this.container;
var containerData = this.containerData;
var canvasData;
var cropBoxData;
var ratio;
// Check `container` is necessary for IE8
if (this.isDisabled || !containerData) {
return;
}
ratio = container.offsetWidth / containerData.width;
// Resize when width changed or height changed
if (ratio !== 1 || container.offsetHeight !== containerData.height) {
if (restore) {
canvasData = this.getCanvasData();
cropBoxData = this.getCropBoxData();
}
this.render();
if (restore) {
this.setCanvasData(each(canvasData, function (n, i) {
canvasData[i] = n * ratio;
}));
this.setCropBoxData(each(cropBoxData, function (n, i) {
cropBoxData[i] = n * ratio;
}));
}
}
},
dblclick: function () {
if (this.isDisabled) {
return;
}
this.setDragMode(hasClass(this.dragBox, CLASS_CROP) ? ACTION_MOVE : ACTION_CROP);
},
wheel: function (event) {
var e = getEvent(event);
var ratio = num(this.options.wheelZoomRatio) || 0.1;
var delta = 1;
if (this.isDisabled) {
return;
}
preventDefault(e);
if (e.deltaY) {
delta = e.deltaY > 0 ? 1 : -1;
} else if (e.wheelDelta) {
delta = -e.wheelDelta / 120;
} else if (e.detail) {
delta = e.detail > 0 ? 1 : -1;
}
this.zoom(-delta * ratio, e);
},
cropStart: function (event) {
var options = this.options;
var e = getEvent(event);
var touches = e.touches;
var touchesLength;
var touch;
var action;
if (this.isDisabled) {
return;
}
if (touches) {
touchesLength = touches.length;
if (touchesLength > 1) {
if (options.zoomable && options.zoomOnTouch && touchesLength === 2) {
touch = touches[1];
this.startX2 = touch.pageX;
this.startY2 = touch.pageY;
action = ACTION_ZOOM;
} else {
return;
}
}
touch = touches[0];
}
action = action || getData(e.target, DATA_ACTION);
if (REGEXP_ACTIONS.test(action)) {
if (isFunction(options.cropstart) && options.cropstart.call(this.element, {
originalEvent: e,
action: action
}) === false) {
return;
}
preventDefault(e);
this.action = action;
this.cropping = false;
this.startX = touch ? touch.pageX : e.pageX;
this.startY = touch ? touch.pageY : e.pageY;
if (action === ACTION_CROP) {
this.cropping = true;
addClass(this.dragBox, CLASS_MODAL);
}
}
},
cropMove: function (event) {
var options = this.options;
var e = getEvent(event);
var touches = e.touches;
var action = this.action;
var touchesLength;
var touch;
if (this.isDisabled) {
return;
}
if (touches) {
touchesLength = touches.length;
if (touchesLength > 1) {
if (options.zoomable && options.zoomOnTouch && touchesLength === 2) {
touch = touches[1];
this.endX2 = touch.pageX;
this.endY2 = touch.pageY;
} else {
return;
}
}
touch = touches[0];
}
if (action) {
if (isFunction(options.cropmove) && options.cropmove.call(this.element, {
originalEvent: e,
action: action
}) === false) {
return;
}
preventDefault(e);
this.endX = touch ? touch.pageX : e.pageX;
this.endY = touch ? touch.pageY : e.pageY;
this.change(e.shiftKey, action === ACTION_ZOOM ? e : null);
}
},
cropEnd: function (event) {
var options = this.options;
var e = getEvent(event);
var action = this.action;
if (this.isDisabled) {
return;
}
if (action) {
preventDefault(e);
if (this.cropping) {
this.cropping = false;
toggleClass(this.dragBox, CLASS_MODAL, this.isCropped && options.modal);
}
this.action = '';
if (isFunction(options.cropend)) {
options.cropend.call(this.element, {
originalEvent: e,
action: action
});
}
}
}
});
extend(prototype, {
change: function (shiftKey, originalEvent) {
var options = this.options;
var aspectRatio = options.aspectRatio;
var action = this.action;
var containerData = this.containerData;
var canvasData = this.canvasData;
var cropBoxData = this.cropBoxData;
var width = cropBoxData.width;
var height = cropBoxData.height;
var left = cropBoxData.left;
var top = cropBoxData.top;
var right = left + width;
var bottom = top + height;
var minLeft = 0;
var minTop = 0;
var maxWidth = containerData.width;
var maxHeight = containerData.height;
var renderable = true;
var offset;
var range;
// Locking aspect ratio in "free mode" by holding shift key
if (!aspectRatio && shiftKey) {
aspectRatio = width && height ? width / height : 1;
}
if (this.isLimited) {
minLeft = cropBoxData.minLeft;
minTop = cropBoxData.minTop;
maxWidth = minLeft + min(containerData.width, canvasData.width);
maxHeight = minTop + min(containerData.height, canvasData.height);
}
range = {
x: this.endX - this.startX,
y: this.endY - this.startY
};
if (aspectRatio) {
range.X = range.y * aspectRatio;
range.Y = range.x / aspectRatio;
}
switch (action) {
// Move crop box
case ACTION_ALL:
left += range.x;
top += range.y;
break;
// Resize crop box
case ACTION_EAST:
if (range.x >= 0 && (right >= maxWidth || aspectRatio &&
(top <= minTop || bottom >= maxHeight))) {
renderable = false;
break;
}
width += range.x;
if (aspectRatio) {
height = width / aspectRatio;
top -= range.Y / 2;
}
if (width < 0) {
action = ACTION_WEST;
width = 0;
}
break;
case ACTION_NORTH:
if (range.y <= 0 && (top <= minTop || aspectRatio &&
(left <= minLeft || right >= maxWidth))) {
renderable = false;
break;
}
height -= range.y;
top += range.y;
if (aspectRatio) {
width = height * aspectRatio;
left += range.X / 2;
}
if (height < 0) {
action = ACTION_SOUTH;
height = 0;
}
break;
case ACTION_WEST:
if (range.x <= 0 && (left <= minLeft || aspectRatio &&
(top <= minTop || bottom >= maxHeight))) {
renderable = false;
break;
}
width -= range.x;
left += range.x;
if (aspectRatio) {
height = width / aspectRatio;
top += range.Y / 2;
}
if (width < 0) {
action = ACTION_EAST;
width = 0;
}
break;
case ACTION_SOUTH:
if (range.y >= 0 && (bottom >= maxHeight || aspectRatio &&
(left <= minLeft || right >= maxWidth))) {
renderable = false;
break;
}
height += range.y;
if (aspectRatio) {
width = height * aspectRatio;
left -= range.X / 2;
}
if (height < 0) {
action = ACTION_NORTH;
height = 0;
}
break;
case ACTION_NORTH_EAST:
if (aspectRatio) {
if (range.y <= 0 && (top <= minTop || right >= maxWidth)) {
renderable = false;
break;
}
height -= range.y;
top += range.y;
width = height * aspectRatio;
} else {
if (range.x >= 0) {
if (right < maxWidth) {
width += range.x;
} else if (range.y <= 0 && top <= minTop) {
renderable = false;
}
} else {
width += range.x;
}
if (range.y <= 0) {
if (top > minTop) {
height -= range.y;
top += range.y;
}
} else {
height -= range.y;
top += range.y;
}
}
if (width < 0 && height < 0) {
action = ACTION_SOUTH_WEST;
height = 0;
width = 0;
} else if (width < 0) {
action = ACTION_NORTH_WEST;
width = 0;
} else if (height < 0) {
action = ACTION_SOUTH_EAST;
height = 0;
}
break;
case ACTION_NORTH_WEST:
if (aspectRatio) {
if (range.y <= 0 && (top <= minTop || left <= minLeft)) {
renderable = false;
break;
}
height -= range.y;
top += range.y;
width = height * aspectRatio;
left += range.X;
} else {
if (range.x <= 0) {
if (left > minLeft) {
width -= range.x;
left += range.x;
} else if (range.y <= 0 && top <= minTop) {
renderable = false;
}
} else {
width -= range.x;
left += range.x;
}
if (range.y <= 0) {
if (top > minTop) {
height -= range.y;
top += range.y;
}
} else {
height -= range.y;
top += range.y;
}
}
if (width < 0 && height < 0) {
action = ACTION_SOUTH_EAST;
height = 0;
width = 0;
} else if (width < 0) {
action = ACTION_NORTH_EAST;
width = 0;
} else if (height < 0) {
action = ACTION_SOUTH_WEST;
height = 0;
}
break;
case ACTION_SOUTH_WEST:
if (aspectRatio) {
if (range.x <= 0 && (left <= minLeft || bottom >= maxHeight)) {
renderable = false;
break;
}
width -= range.x;
left += range.x;
height = width / aspectRatio;
} else {
if (range.x <= 0) {
if (left > minLeft) {
width -= range.x;
left += range.x;
} else if (range.y >= 0 && bottom >= maxHeight) {
renderable = false;
}
} else {
width -= range.x;
left += range.x;
}
if (range.y >= 0) {
if (bottom < maxHeight) {
height += range.y;
}
} else {
height += range.y;
}
}
if (width < 0 && height < 0) {
action = ACTION_NORTH_EAST;
height = 0;
width = 0;
} else if (width < 0) {
action = ACTION_SOUTH_EAST;
width = 0;
} else if (height < 0) {
action = ACTION_NORTH_WEST;
height = 0;
}
break;
case ACTION_SOUTH_EAST:
if (aspectRatio) {
if (range.x >= 0 && (right >= maxWidth || bottom >= maxHeight)) {
renderable = false;
break;
}
width += range.x;
height = width / aspectRatio;
} else {
if (range.x >= 0) {
if (right < maxWidth) {
width += range.x;
} else if (range.y >= 0 && bottom >= maxHeight) {
renderable = false;
}
} else {
width += range.x;
}
if (range.y >= 0) {
if (bottom < maxHeight) {
height += range.y;
}
} else {
height += range.y;
}
}
if (width < 0 && height < 0) {
action = ACTION_NORTH_WEST;
height = 0;
width = 0;
} else if (width < 0) {
action = ACTION_SOUTH_WEST;
width = 0;
} else if (height < 0) {
action = ACTION_NORTH_EAST;
height = 0;
}
break;
// Move canvas
case ACTION_MOVE:
this.move(range.x, range.y);
renderable = false;
break;
// Zoom canvas
case ACTION_ZOOM:
this.zoom((function (x1, y1, x2, y2) {
var z1 = sqrt(x1 * x1 + y1 * y1);
var z2 = sqrt(x2 * x2 + y2 * y2);
return (z2 - z1) / z1;
})(
abs(this.startX - this.startX2),
abs(this.startY - this.startY2),
abs(this.endX - this.endX2),
abs(this.endY - this.endY2)
), originalEvent);
this.startX2 = this.endX2;
this.startY2 = this.endY2;
renderable = false;
break;
// Create crop box
case ACTION_CROP:
if (!range.x || !range.y) {
renderable = false;
break;
}
offset = getOffset(this.cropper);
left = this.startX - offset.left;
top = this.startY - offset.top;
width = cropBoxData.minWidth;
height = cropBoxData.minHeight;
if (range.x > 0) {
action = range.y > 0 ? ACTION_SOUTH_EAST : ACTION_NORTH_EAST;
} else if (range.x < 0) {
left -= width;
action = range.y > 0 ? ACTION_SOUTH_WEST : ACTION_NORTH_WEST;
}
if (range.y < 0) {
top -= height;
}
// Show the crop box if is hidden
if (!this.isCropped) {
removeClass(this.cropBox, CLASS_HIDDEN);
this.isCropped = true;
if (this.isLimited) {
this.limitCropBox(true, true);
}
}
break;
// No default
}
if (renderable) {
cropBoxData.width = width;
cropBoxData.height = height;
cropBoxData.left = left;
cropBoxData.top = top;
this.action = action;
this.renderCropBox();
}
// Override
this.startX = this.endX;
this.startY = this.endY;
}
});
extend(prototype, {
// Show the crop box manually
crop: function () {
if (this.isBuilt && !this.isDisabled) {
if (!this.isCropped) {
this.isCropped = true;
this.limitCropBox(true, true);
if (this.options.modal) {
addClass(this.dragBox, CLASS_MODAL);
}
removeClass(this.cropBox, CLASS_HIDDEN);
}
this.setCropBoxData(this.initialCropBoxData);
}
return this;
},
// Reset the image and crop box to their initial states
reset: function () {
if (this.isBuilt && !this.isDisabled) {
this.imageData = extend({}, this.initialImageData);
this.canvasData = extend({}, this.initialCanvasData);
this.cropBoxData = extend({}, this.initialCropBoxData);
this.renderCanvas();
if (this.isCropped) {
this.renderCropBox();
}
}
return this;
},
// Clear the crop box
clear: function () {
if (this.isCropped && !this.isDisabled) {
extend(this.cropBoxData, {
left: 0,
top: 0,
width: 0,
height: 0
});
this.isCropped = false;
this.renderCropBox();
this.limitCanvas();
// Render canvas after crop box rendered
this.renderCanvas();
removeClass(this.dragBox, CLASS_MODAL);
addClass(this.cropBox, CLASS_HIDDEN);
}
return this;
},
/**
* Replace the image's src and rebuild the cropper
*
* @param {String} url
*/
replace: function (url) {
if (!this.isDisabled && url) {
if (this.isImg) {
this.isReplaced = true;
this.element.src = url;
}
// Clear previous data
this.options.data = null;
this.load(url);
}
return this;
},
// Enable (unfreeze) the cropper
enable: function () {
if (this.isBuilt) {
this.isDisabled = false;
removeClass(this.cropper, CLASS_DISABLED);
}
return this;
},
// Disable (freeze) the cropper
disable: function () {
if (this.isBuilt) {
this.isDisabled = true;
addClass(this.cropper, CLASS_DISABLED);
}
return this;
},
// Destroy the cropper and remove the instance from the image
destroy: function () {
var element = this.element;
var image = this.image;
if (this.isLoaded) {
if (this.isImg && this.isReplaced) {
element.src = this.originalUrl;
}
this.unbuild();
removeClass(element, CLASS_HIDDEN);
} else {
if (this.isImg) {
element.off(EVENT_LOAD, this.start);
} else if (image) {
removeChild(image);
}
}
removeData(element, NAMESPACE);
return this;
},
/**
* Move the canvas with relative offsets
*
* @param {Number} offsetX
* @param {Number} offsetY (optional)
*/
move: function (offsetX, offsetY) {
var canvasData = this.canvasData;
return this.moveTo(
isUndefined(offsetX) ? offsetX : canvasData.left + num(offsetX),
isUndefined(offsetY) ? offsetY : canvasData.top + num(offsetY)
);
},
/**
* Move the canvas to an absolute point
*
* @param {Number} x
* @param {Number} y (optional)
*/
moveTo: function (x, y) {
var canvasData = this.canvasData;
var isChanged = false;
// If "y" is not present, its default value is "x"
if (isUndefined(y)) {
y = x;
}
x = num(x);
y = num(y);
if (this.isBuilt && !this.isDisabled && this.options.movable) {
if (isNumber(x)) {
canvasData.left = x;
isChanged = true;
}
if (isNumber(y)) {
canvasData.top = y;
isChanged = true;
}
if (isChanged) {
this.renderCanvas(true);
}
}
return this;
},
/**
* Zoom the canvas with a relative ratio
*
* @param {Number} ratio
* @param {Event} _originalEvent (private)
*/
zoom: function (ratio, _originalEvent) {
var canvasData = this.canvasData;
ratio = num(ratio);
if (ratio < 0) {
ratio = 1 / (1 - ratio);
} else {
ratio = 1 + ratio;
}
return this.zoomTo(canvasData.width * ratio / canvasData.naturalWidth, _originalEvent);
},
/**
* Zoom the canvas to an absolute ratio
*
* @param {Number} ratio
* @param {Event} _originalEvent (private)
*/
zoomTo: function (ratio, _originalEvent) {
var options = this.options;
var canvasData = this.canvasData;
var width = canvasData.width;
var height = canvasData.height;
var naturalWidth = canvasData.naturalWidth;
var naturalHeight = canvasData.naturalHeight;
var newWidth;
var newHeight;
ratio = num(ratio);
if (ratio >= 0 && this.isBuilt && !this.isDisabled && options.zoomable) {
newWidth = naturalWidth * ratio;
newHeight = naturalHeight * ratio;
if (isFunction(options.zoom) && options.zoom.call(this.element, {
originalEvent: _originalEvent,
oldRatio: width / naturalWidth,
ratio: newWidth / naturalWidth
}) === false) {
return this;
}
canvasData.left -= (newWidth - width) / 2;
canvasData.top -= (newHeight - height) / 2;
canvasData.width = newWidth;
canvasData.height = newHeight;
this.renderCanvas(true);
}
return this;
},
/**
* Rotate the canvas with a relative degree
*
* @param {Number} degree
*/
rotate: function (degree) {
return this.rotateTo((this.imageData.rotate || 0) + num(degree));
},
/**
* Rotate the canvas to an absolute degree
* https://developer.mozilla.org/en-US/docs/Web/CSS/transform-function#rotate()
*
* @param {Number} degree
*/
rotateTo: function (degree) {
degree = num(degree);
if (isNumber(degree) && this.isBuilt && !this.isDisabled && this.options.rotatable) {
this.imageData.rotate = degree % 360;
this.isRotated = true;
this.renderCanvas(true);
}
return this;
},
/**
* Scale the image
* https://developer.mozilla.org/en-US/docs/Web/CSS/transform-function#scale()
*
* @param {Number} scaleX
* @param {Number} scaleY (optional)
*/
scale: function (scaleX, scaleY) {
var imageData = this.imageData;
var isChanged = false;
// If "scaleY" is not present, its default value is "scaleX"
if (isUndefined(scaleY)) {
scaleY = scaleX;
}
scaleX = num(scaleX);
scaleY = num(scaleY);
if (this.isBuilt && !this.isDisabled && this.options.scalable) {
if (isNumber(scaleX)) {
imageData.scaleX = scaleX;
isChanged = true;
}
if (isNumber(scaleY)) {
imageData.scaleY = scaleY;
isChanged = true;
}
if (isChanged) {
this.renderImage(true);
}
}
return this;
},
/**
* Scale the abscissa of the image
*
* @param {Number} scaleX
*/
scaleX: function (scaleX) {
var scaleY = this.imageData.scaleY;
return this.scale(scaleX, isNumber(scaleY) ? scaleY : 1);
},
/**
* Scale the ordinate of the image
*
* @param {Number} scaleY
*/
scaleY: function (scaleY) {
var scaleX = this.imageData.scaleX;
return this.scale(isNumber(scaleX) ? scaleX : 1, scaleY);
},
/**
* Get the cropped area position and size data (base on the original image)
*
* @param {Boolean} isRounded (optional)
* @return {Object} data
*/
getData: function (isRounded) {
var options = this.options;
var imageData = this.imageData;
var canvasData = this.canvasData;
var cropBoxData = this.cropBoxData;
var ratio;
var data;
if (this.isBuilt && this.isCropped) {
data = {
x: cropBoxData.left - canvasData.left,
y: cropBoxData.top - canvasData.top,
width: cropBoxData.width,
height: cropBoxData.height
};
ratio = imageData.width / imageData.naturalWidth;
each(data, function (n, i) {
n = n / ratio;
data[i] = isRounded ? round(n) : n;
});
} else {
data = {
x: 0,
y: 0,
width: 0,
height: 0
};
}
if (options.rotatable) {
data.rotate = imageData.rotate || 0;
}
if (options.scalable) {
data.scaleX = imageData.scaleX || 1;
data.scaleY = imageData.scaleY || 1;
}
return data;
},
/**
* Set the cropped area position and size with new data
*
* @param {Object} data
*/
setData: function (data) {
var options = this.options;
var imageData = this.imageData;
var canvasData = this.canvasData;
var cropBoxData = {};
var isRotated;
var isScaled;
var ratio;
if (isFunction(data)) {
data = data.call(this.element);
}
if (this.isBuilt && !this.isDisabled && isPlainObject(data)) {
if (options.rotatable) {
if (isNumber(data.rotate) && data.rotate !== imageData.rotate) {
imageData.rotate = data.rotate;
this.isRotated = isRotated = true;
}
}
if (options.scalable) {
if (isNumber(data.scaleX) && data.scaleX !== imageData.scaleX) {
imageData.scaleX = data.scaleX;
isScaled = true;
}
if (isNumber(data.scaleY) && data.scaleY !== imageData.scaleY) {
imageData.scaleY = data.scaleY;
isScaled = true;
}
}
if (isRotated) {
this.renderCanvas();
} else if (isScaled) {
this.renderImage();
}
ratio = imageData.width / imageData.naturalWidth;
if (isNumber(data.x)) {
cropBoxData.left = data.x * ratio + canvasData.left;
}
if (isNumber(data.y)) {
cropBoxData.top = data.y * ratio + canvasData.top;
}
if (isNumber(data.width)) {
cropBoxData.width = data.width * ratio;
}
if (isNumber(data.height)) {
cropBoxData.height = data.height * ratio;
}
this.setCropBoxData(cropBoxData);
}
return this;
},
/**
* Get the container size data
*
* @return {Object} data
*/
getContainerData: function () {
return this.isBuilt ? this.containerData : {};
},
/**
* Get the image position and size data
*
* @return {Object} data
*/
getImageData: function () {
return this.isLoaded ? this.imageData : {};
},
/**
* Get the canvas position and size data
*
* @return {Object} data
*/
getCanvasData: function () {
var canvasData = this.canvasData;
var data = {};
if (this.isBuilt) {
each([
'left',
'top',
'width',
'height',
'naturalWidth',
'naturalHeight'
], function (n) {
data[n] = canvasData[n];
});
}
return data;
},
/**
* Set the canvas position and size with new data
*
* @param {Object} data
*/
setCanvasData: function (data) {
var canvasData = this.canvasData;
var aspectRatio = canvasData.aspectRatio;
if (isFunction(data)) {
data = data.call(this.element);
}
if (this.isBuilt && !this.isDisabled && isPlainObject(data)) {
if (isNumber(data.left)) {
canvasData.left = data.left;
}
if (isNumber(data.top)) {
canvasData.top = data.top;
}
if (isNumber(data.width)) {
canvasData.width = data.width;
canvasData.height = data.width / aspectRatio;
} else if (isNumber(data.height)) {
canvasData.height = data.height;
canvasData.width = data.height * aspectRatio;
}
this.renderCanvas(true);
}
return this;
},
/**
* Get the crop box position and size data
*
* @return {Object} data
*/
getCropBoxData: function () {
var cropBoxData = this.cropBoxData;
var data;
if (this.isBuilt && this.isCropped) {
data = {
left: cropBoxData.left,
top: cropBoxData.top,
width: cropBoxData.width,
height: cropBoxData.height
};
}
return data || {};
},
/**
* Set the crop box position and size with new data
*
* @param {Object} data
*/
setCropBoxData: function (data) {
var cropBoxData = this.cropBoxData;
var aspectRatio = this.options.aspectRatio;
var isWidthChanged;
var isHeightChanged;
if (isFunction(data)) {
data = data.call(this.element);
}
if (this.isBuilt && this.isCropped && !this.isDisabled && isPlainObject(data)) {
if (isNumber(data.left)) {
cropBoxData.left = data.left;
}
if (isNumber(data.top)) {
cropBoxData.top = data.top;
}
if (isNumber(data.width) && data.width !== cropBoxData.width) {
isWidthChanged = true;
cropBoxData.width = data.width;
}
if (isNumber(data.height) && data.height !== cropBoxData.height) {
isHeightChanged = true;
cropBoxData.height = data.height;
}
if (aspectRatio) {
if (isWidthChanged) {
cropBoxData.height = cropBoxData.width / aspectRatio;
} else if (isHeightChanged) {
cropBoxData.width = cropBoxData.height * aspectRatio;
}
}
this.renderCropBox();
}
return this;
},
/**
* Get a canvas drawn the cropped image
*
* @param {Object} options (optional)
* @return {HTMLCanvasElement} canvas
*/
getCroppedCanvas: function (options) {
var originalWidth;
var originalHeight;
var canvasWidth;
var canvasHeight;
var scaledWidth;
var scaledHeight;
var scaledRatio;
var aspectRatio;
var canvas;
var context;
var data;
if (!this.isBuilt || !this.isCropped || !SUPPORT_CANVAS) {
return;
}
if (!isPlainObject(options)) {
options = {};
}
data = this.getData();
originalWidth = data.width;
originalHeight = data.height;
aspectRatio = originalWidth / originalHeight;
if (isPlainObject(options)) {
scaledWidth = options.width;
scaledHeight = options.height;
if (scaledWidth) {
scaledHeight = scaledWidth / aspectRatio;
scaledRatio = scaledWidth / originalWidth;
} else if (scaledHeight) {
scaledWidth = scaledHeight * aspectRatio;
scaledRatio = scaledHeight / originalHeight;
}
}
// The canvas element will use `Math.floor` on a float number, so round first
canvasWidth = round(scaledWidth || originalWidth);
canvasHeight = round(scaledHeight || originalHeight);
canvas = document.createElement('canvas');
canvas.width = canvasWidth;
canvas.height = canvasHeight;
context = canvas.getContext('2d');
if (options.fillColor) {
context.fillStyle = options.fillColor;
context.fillRect(0, 0, canvasWidth, canvasHeight);
}
// https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D.drawImage
context.drawImage.apply(context, (function () {
var source = getSourceCanvas(this.image, this.imageData);
var sourceWidth = source.width;
var sourceHeight = source.height;
var args = [source];
// Source canvas
var srcX = data.x;
var srcY = data.y;
var srcWidth;
var srcHeight;
// Destination canvas
var dstX;
var dstY;
var dstWidth;
var dstHeight;
if (srcX <= -originalWidth || srcX > sourceWidth) {
srcX = srcWidth = dstX = dstWidth = 0;
} else if (srcX <= 0) {
dstX = -srcX;
srcX = 0;
srcWidth = dstWidth = min(sourceWidth, originalWidth + srcX);
} else if (srcX <= sourceWidth) {
dstX = 0;
srcWidth = dstWidth = min(originalWidth, sourceWidth - srcX);
}
if (srcWidth <= 0 || srcY <= -originalHeight || srcY > sourceHeight) {
srcY = srcHeight = dstY = dstHeight = 0;
} else if (srcY <= 0) {
dstY = -srcY;
srcY = 0;
srcHeight = dstHeight = min(sourceHeight, originalHeight + srcY);
} else if (srcY <= sourceHeight) {
dstY = 0;
srcHeight = dstHeight = min(originalHeight, sourceHeight - srcY);
}
args.push(floor(srcX), floor(srcY), floor(srcWidth), floor(srcHeight));
// Scale destination sizes
if (scaledRatio) {
dstX *= scaledRatio;
dstY *= scaledRatio;
dstWidth *= scaledRatio;
dstHeight *= scaledRatio;
}
// Avoid "IndexSizeError" in IE and Firefox
if (dstWidth > 0 && dstHeight > 0) {
args.push(floor(dstX), floor(dstY), floor(dstWidth), floor(dstHeight));
}
return args;
}).call(this));
return canvas;
},
/**
* Change the aspect ratio of the crop box
*
* @param {Number} aspectRatio
*/
setAspectRatio: function (aspectRatio) {
var options = this.options;
if (!this.isDisabled && !isUndefined(aspectRatio)) {
// 0 -> NaN
options.aspectRatio = max(0, aspectRatio) || NaN;
if (this.isBuilt) {
this.initCropBox();
if (this.isCropped) {
this.renderCropBox();
}
}
}
return this;
},
/**
* Change the drag mode
*
* @param {String} mode (optional)
*/
setDragMode: function (mode) {
var options = this.options;
var dragBox = this.dragBox;
var face = this.face;
var croppable;
var movable;
if (this.isLoaded && !this.isDisabled) {
croppable = mode === ACTION_CROP;
movable = options.movable && mode === ACTION_MOVE;
mode = (croppable || movable) ? mode : ACTION_NONE;
setData(dragBox, DATA_ACTION, mode);
toggleClass(dragBox, CLASS_CROP, croppable);
toggleClass(dragBox, CLASS_MOVE, movable);
if (!options.cropBoxMovable) {
// Sync drag mode to crop box when it is not movable
setData(face, DATA_ACTION, mode);
toggleClass(face, CLASS_CROP, croppable);
toggleClass(face, CLASS_MOVE, movable);
}
}
return this;
}
});
extend(Cropper.prototype, prototype);
Cropper.DEFAULTS = {
// Define the view mode of the cropper
viewMode: 0, // 0, 1, 2, 3
// Define the dragging mode of the cropper
dragMode: 'crop', // 'crop', 'move' or 'none'
// Define the aspect ratio of the crop box
aspectRatio: NaN,
// An object with the previous cropping result data
data: null,
// A selector for adding extra containers to preview
preview: '',
// Re-render the cropper when resize the window
responsive: true,
// Restore the cropped area after resize the window
restore: true,
// Check if the target image is cross origin
checkCrossOrigin: true,
// Show the black modal
modal: true,
// Show the dashed lines for guiding
guides: true,
// Show the center indicator for guiding
center: true,
// Show the white modal to highlight the crop box
highlight: true,
// Show the grid background
background: true,
// Enable to crop the image automatically when initialize
autoCrop: true,
// Define the percentage of automatic cropping area when initializes
autoCropArea: 0.8,
// Enable to move the image
movable: true,
// Enable to rotate the image
rotatable: true,
// Enable to scale the image
scalable: true,
// Enable to zoom the image
zoomable: true,
// Enable to zoom the image by dragging touch
zoomOnTouch: true,
// Enable to zoom the image by wheeling mouse
zoomOnWheel: true,
// Define zoom ratio when zoom the image by wheeling mouse
wheelZoomRatio: 0.1,
// Enable to move the crop box
cropBoxMovable: true,
// Enable to resize the crop box
cropBoxResizable: true,
// Toggle drag mode between "crop" and "move" when click twice on the cropper
toggleDragModeOnDblclick: true,
// Size limitation
minCanvasWidth: 0,
minCanvasHeight: 0,
minCropBoxWidth: 0,
minCropBoxHeight: 0,
minContainerWidth: 200,
minContainerHeight: 100,
// Shortcuts of events
build: null,
built: null,
cropstart: null,
cropmove: null,
cropend: null,
crop: null,
zoom: null
};
Cropper.TEMPLATE = (
'<div class="cropper-container">' +
'<div class="cropper-wrap-box">' +
'<div class="cropper-canvas"></div>' +
'</div>' +
'<div class="cropper-drag-box"></div>' +
'<div class="cropper-crop-box">' +
'<span class="cropper-view-box"></span>' +
'<span class="cropper-dashed dashed-h"></span>' +
'<span class="cropper-dashed dashed-v"></span>' +
'<span class="cropper-center"></span>' +
'<span class="cropper-face"></span>' +
'<span class="cropper-line line-e" data-action="e"></span>' +
'<span class="cropper-line line-n" data-action="n"></span>' +
'<span class="cropper-line line-w" data-action="w"></span>' +
'<span class="cropper-line line-s" data-action="s"></span>' +
'<span class="cropper-point point-e" data-action="e"></span>' +
'<span class="cropper-point point-n" data-action="n"></span>' +
'<span class="cropper-point point-w" data-action="w"></span>' +
'<span class="cropper-point point-s" data-action="s"></span>' +
'<span class="cropper-point point-ne" data-action="ne"></span>' +
'<span class="cropper-point point-nw" data-action="nw"></span>' +
'<span class="cropper-point point-sw" data-action="sw"></span>' +
'<span class="cropper-point point-se" data-action="se"></span>' +
'</div>' +
'</div>'
);
var _Cropper = window.Cropper;
Cropper.noConflict = function () {
window.Cropper = _Cropper;
return Cropper;
};
Cropper.setDefaults = function (options) {
extend(Cropper.DEFAULTS, options);
};
if (typeof define === 'function' && define.amd) {
define('cropper', [], function () {
return Cropper;
});
}
if (typeof noGlobal === 'undefined') {
window.Cropper = Cropper;
}
return Cropper;
});
| mit |
zverevalexei/bierman-topology | web/node_modules/bower/node_modules/lodash/internal/createAssigner.js | 984 | var isIterateeCall = require('./isIterateeCall'),
rest = require('../rest');
/**
* Creates a function like `_.assign`.
*
* @private
* @param {Function} assigner The function to assign values.
* @returns {Function} Returns the new assigner function.
*/
function createAssigner(assigner) {
return rest(function(object, sources) {
var index = -1,
length = sources.length,
customizer = length > 1 ? sources[length - 1] : undefined,
guard = length > 2 ? sources[2] : undefined;
customizer = typeof customizer == 'function' ? (length--, customizer) : undefined;
if (guard && isIterateeCall(sources[0], sources[1], guard)) {
customizer = length < 3 ? undefined : customizer;
length = 1;
}
object = Object(object);
while (++index < length) {
var source = sources[index];
if (source) {
assigner(object, source, customizer);
}
}
return object;
});
}
module.exports = createAssigner;
| mit |
cipibad/openrtd_2012 | toolchain_mipsel/include/asm-alpha/kmap_types.h | 503 | #ifndef _ASM_KMAP_TYPES_H
#define _ASM_KMAP_TYPES_H
/* Dummy header just to define km_type. */
#include <linux/config.h>
#ifdef CONFIG_DEBUG_HIGHMEM
# define D(n) __KM_FENCE_##n ,
#else
# define D(n)
#endif
enum km_type {
D(0) KM_BOUNCE_READ,
D(1) KM_SKB_SUNRPC_DATA,
D(2) KM_SKB_DATA_SOFTIRQ,
D(3) KM_USER0,
D(4) KM_USER1,
D(5) KM_BIO_SRC_IRQ,
D(6) KM_BIO_DST_IRQ,
D(7) KM_PTE0,
D(8) KM_PTE1,
D(9) KM_IRQ0,
D(10) KM_IRQ1,
D(11) KM_SOFTIRQ0,
D(12) KM_SOFTIRQ1,
D(13) KM_TYPE_NR
};
#undef D
#endif
| gpl-2.0 |
legoater/skiboot | libstb/crypto/mbedtls/include/mbedtls/platform_util.h | 7436 | /**
* \file platform_util.h
*
* \brief Common and shared functions used by multiple modules in the Mbed TLS
* library.
*/
/*
* Copyright (C) 2018, Arm Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is part of Mbed TLS (https://tls.mbed.org)
*/
#ifndef MBEDTLS_PLATFORM_UTIL_H
#define MBEDTLS_PLATFORM_UTIL_H
#if !defined(MBEDTLS_CONFIG_FILE)
#include "config.h"
#else
#include MBEDTLS_CONFIG_FILE
#endif
#include <stddef.h>
#if defined(MBEDTLS_HAVE_TIME_DATE)
#include "platform_time.h"
#include <time.h>
#endif /* MBEDTLS_HAVE_TIME_DATE */
#ifdef __cplusplus
extern "C" {
#endif
#if defined(MBEDTLS_CHECK_PARAMS)
#if defined(MBEDTLS_PARAM_FAILED)
/** An alternative definition of MBEDTLS_PARAM_FAILED has been set in config.h.
*
* This flag can be used to check whether it is safe to assume that
* MBEDTLS_PARAM_FAILED() will expand to a call to mbedtls_param_failed().
*/
#define MBEDTLS_PARAM_FAILED_ALT
#else /* MBEDTLS_PARAM_FAILED */
#define MBEDTLS_PARAM_FAILED( cond ) \
mbedtls_param_failed( #cond, __FILE__, __LINE__ )
/**
* \brief User supplied callback function for parameter validation failure.
* See #MBEDTLS_CHECK_PARAMS for context.
*
* This function will be called unless an alternative treatement
* is defined through the #MBEDTLS_PARAM_FAILED macro.
*
* This function can return, and the operation will be aborted, or
* alternatively, through use of setjmp()/longjmp() can resume
* execution in the application code.
*
* \param failure_condition The assertion that didn't hold.
* \param file The file where the assertion failed.
* \param line The line in the file where the assertion failed.
*/
void mbedtls_param_failed( const char *failure_condition,
const char *file,
int line );
#endif /* MBEDTLS_PARAM_FAILED */
/* Internal macro meant to be called only from within the library. */
#define MBEDTLS_INTERNAL_VALIDATE_RET( cond, ret ) \
do { \
if( !(cond) ) \
{ \
MBEDTLS_PARAM_FAILED( cond ); \
return( ret ); \
} \
} while( 0 )
/* Internal macro meant to be called only from within the library. */
#define MBEDTLS_INTERNAL_VALIDATE( cond ) \
do { \
if( !(cond) ) \
{ \
MBEDTLS_PARAM_FAILED( cond ); \
return; \
} \
} while( 0 )
#else /* MBEDTLS_CHECK_PARAMS */
/* Internal macros meant to be called only from within the library. */
#define MBEDTLS_INTERNAL_VALIDATE_RET( cond, ret ) do { } while( 0 )
#define MBEDTLS_INTERNAL_VALIDATE( cond ) do { } while( 0 )
#endif /* MBEDTLS_CHECK_PARAMS */
/* Internal helper macros for deprecating API constants. */
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
#if defined(MBEDTLS_DEPRECATED_WARNING)
/* Deliberately don't (yet) export MBEDTLS_DEPRECATED here
* to avoid conflict with other headers which define and use
* it, too. We might want to move all these definitions here at
* some point for uniformity. */
#define MBEDTLS_DEPRECATED __attribute__((deprecated))
MBEDTLS_DEPRECATED typedef char const * mbedtls_deprecated_string_constant_t;
#define MBEDTLS_DEPRECATED_STRING_CONSTANT( VAL ) \
( (mbedtls_deprecated_string_constant_t) ( VAL ) )
MBEDTLS_DEPRECATED typedef int mbedtls_deprecated_numeric_constant_t;
#define MBEDTLS_DEPRECATED_NUMERIC_CONSTANT( VAL ) \
( (mbedtls_deprecated_numeric_constant_t) ( VAL ) )
#undef MBEDTLS_DEPRECATED
#else /* MBEDTLS_DEPRECATED_WARNING */
#define MBEDTLS_DEPRECATED_STRING_CONSTANT( VAL ) VAL
#define MBEDTLS_DEPRECATED_NUMERIC_CONSTANT( VAL ) VAL
#endif /* MBEDTLS_DEPRECATED_WARNING */
#endif /* MBEDTLS_DEPRECATED_REMOVED */
/**
* \brief Securely zeroize a buffer
*
* The function is meant to wipe the data contained in a buffer so
* that it can no longer be recovered even if the program memory
* is later compromised. Call this function on sensitive data
* stored on the stack before returning from a function, and on
* sensitive data stored on the heap before freeing the heap
* object.
*
* It is extremely difficult to guarantee that calls to
* mbedtls_platform_zeroize() are not removed by aggressive
* compiler optimizations in a portable way. For this reason, Mbed
* TLS provides the configuration option
* MBEDTLS_PLATFORM_ZEROIZE_ALT, which allows users to configure
* mbedtls_platform_zeroize() to use a suitable implementation for
* their platform and needs
*
* \param buf Buffer to be zeroized
* \param len Length of the buffer in bytes
*
*/
void mbedtls_platform_zeroize( void *buf, size_t len );
#if defined(MBEDTLS_HAVE_TIME_DATE)
/**
* \brief Platform-specific implementation of gmtime_r()
*
* The function is a thread-safe abstraction that behaves
* similarly to the gmtime_r() function from Unix/POSIX.
*
* Mbed TLS will try to identify the underlying platform and
* make use of an appropriate underlying implementation (e.g.
* gmtime_r() for POSIX and gmtime_s() for Windows). If this is
* not possible, then gmtime() will be used. In this case, calls
* from the library to gmtime() will be guarded by the mutex
* mbedtls_threading_gmtime_mutex if MBEDTLS_THREADING_C is
* enabled. It is recommended that calls from outside the library
* are also guarded by this mutex.
*
* If MBEDTLS_PLATFORM_GMTIME_R_ALT is defined, then Mbed TLS will
* unconditionally use the alternative implementation for
* mbedtls_platform_gmtime_r() supplied by the user at compile time.
*
* \param tt Pointer to an object containing time (in seconds) since the
* epoch to be converted
* \param tm_buf Pointer to an object where the results will be stored
*
* \return Pointer to an object of type struct tm on success, otherwise
* NULL
*/
struct tm *mbedtls_platform_gmtime_r( const mbedtls_time_t *tt,
struct tm *tm_buf );
#endif /* MBEDTLS_HAVE_TIME_DATE */
#ifdef __cplusplus
}
#endif
#endif /* MBEDTLS_PLATFORM_UTIL_H */
| apache-2.0 |
Stackdriver/heapster | vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/batch/internalversion/fake/fake_job.go | 4578 | /*
Copyright The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Code generated by client-gen. DO NOT EDIT.
package fake
import (
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
labels "k8s.io/apimachinery/pkg/labels"
schema "k8s.io/apimachinery/pkg/runtime/schema"
types "k8s.io/apimachinery/pkg/types"
watch "k8s.io/apimachinery/pkg/watch"
testing "k8s.io/client-go/testing"
batch "k8s.io/kubernetes/pkg/apis/batch"
)
// FakeJobs implements JobInterface
type FakeJobs struct {
Fake *FakeBatch
ns string
}
var jobsResource = schema.GroupVersionResource{Group: "batch", Version: "", Resource: "jobs"}
var jobsKind = schema.GroupVersionKind{Group: "batch", Version: "", Kind: "Job"}
// Get takes name of the job, and returns the corresponding job object, and an error if there is any.
func (c *FakeJobs) Get(name string, options v1.GetOptions) (result *batch.Job, err error) {
obj, err := c.Fake.
Invokes(testing.NewGetAction(jobsResource, c.ns, name), &batch.Job{})
if obj == nil {
return nil, err
}
return obj.(*batch.Job), err
}
// List takes label and field selectors, and returns the list of Jobs that match those selectors.
func (c *FakeJobs) List(opts v1.ListOptions) (result *batch.JobList, err error) {
obj, err := c.Fake.
Invokes(testing.NewListAction(jobsResource, jobsKind, c.ns, opts), &batch.JobList{})
if obj == nil {
return nil, err
}
label, _, _ := testing.ExtractFromListOptions(opts)
if label == nil {
label = labels.Everything()
}
list := &batch.JobList{ListMeta: obj.(*batch.JobList).ListMeta}
for _, item := range obj.(*batch.JobList).Items {
if label.Matches(labels.Set(item.Labels)) {
list.Items = append(list.Items, item)
}
}
return list, err
}
// Watch returns a watch.Interface that watches the requested jobs.
func (c *FakeJobs) Watch(opts v1.ListOptions) (watch.Interface, error) {
return c.Fake.
InvokesWatch(testing.NewWatchAction(jobsResource, c.ns, opts))
}
// Create takes the representation of a job and creates it. Returns the server's representation of the job, and an error, if there is any.
func (c *FakeJobs) Create(job *batch.Job) (result *batch.Job, err error) {
obj, err := c.Fake.
Invokes(testing.NewCreateAction(jobsResource, c.ns, job), &batch.Job{})
if obj == nil {
return nil, err
}
return obj.(*batch.Job), err
}
// Update takes the representation of a job and updates it. Returns the server's representation of the job, and an error, if there is any.
func (c *FakeJobs) Update(job *batch.Job) (result *batch.Job, err error) {
obj, err := c.Fake.
Invokes(testing.NewUpdateAction(jobsResource, c.ns, job), &batch.Job{})
if obj == nil {
return nil, err
}
return obj.(*batch.Job), err
}
// UpdateStatus was generated because the type contains a Status member.
// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus().
func (c *FakeJobs) UpdateStatus(job *batch.Job) (*batch.Job, error) {
obj, err := c.Fake.
Invokes(testing.NewUpdateSubresourceAction(jobsResource, "status", c.ns, job), &batch.Job{})
if obj == nil {
return nil, err
}
return obj.(*batch.Job), err
}
// Delete takes name of the job and deletes it. Returns an error if one occurs.
func (c *FakeJobs) Delete(name string, options *v1.DeleteOptions) error {
_, err := c.Fake.
Invokes(testing.NewDeleteAction(jobsResource, c.ns, name), &batch.Job{})
return err
}
// DeleteCollection deletes a collection of objects.
func (c *FakeJobs) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error {
action := testing.NewDeleteCollectionAction(jobsResource, c.ns, listOptions)
_, err := c.Fake.Invokes(action, &batch.JobList{})
return err
}
// Patch applies the patch and returns the patched job.
func (c *FakeJobs) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *batch.Job, err error) {
obj, err := c.Fake.
Invokes(testing.NewPatchSubresourceAction(jobsResource, c.ns, name, pt, data, subresources...), &batch.Job{})
if obj == nil {
return nil, err
}
return obj.(*batch.Job), err
}
| apache-2.0 |
reelsense/homebrew-cask | Casks/gqrx.rb | 1698 | cask 'gqrx' do
version '2.11.5'
sha256 '896cefcb2825840178b6dbfb894b01543b1c8225539e6969052133223a59ffee'
# github.com/csete/gqrx was verified as official when first introduced to the cask
url "https://github.com/csete/gqrx/releases/download/v#{version.major_minor_patch}/Gqrx-#{version}.dmg"
appcast 'https://github.com/csete/gqrx/releases.atom'
name 'Gqrx'
homepage 'http://gqrx.dk/'
app 'Gqrx.app'
binary "#{appdir}/Gqrx.app/Contents/MacOS/airspy_info"
binary "#{appdir}/Gqrx.app/Contents/MacOS/airspy_rx"
binary "#{appdir}/Gqrx.app/Contents/MacOS/airspy_spiflash"
binary "#{appdir}/Gqrx.app/Contents/MacOS/hackrf_cpldjtag"
binary "#{appdir}/Gqrx.app/Contents/MacOS/hackrf_debug"
binary "#{appdir}/Gqrx.app/Contents/MacOS/hackrf_info"
binary "#{appdir}/Gqrx.app/Contents/MacOS/hackrf_spiflash"
binary "#{appdir}/Gqrx.app/Contents/MacOS/hackrf_transfer"
binary "#{appdir}/Gqrx.app/Contents/MacOS/rtl_adsb"
binary "#{appdir}/Gqrx.app/Contents/MacOS/rtl_eeprom"
binary "#{appdir}/Gqrx.app/Contents/MacOS/rtl_fm"
binary "#{appdir}/Gqrx.app/Contents/MacOS/rtl_power"
binary "#{appdir}/Gqrx.app/Contents/MacOS/rtl_sdr"
binary "#{appdir}/Gqrx.app/Contents/MacOS/rtl_tcp"
binary "#{appdir}/Gqrx.app/Contents/MacOS/rtl_test"
binary "#{appdir}/Gqrx.app/Contents/MacOS/SoapySDRUtil", target: 'soapysdrutil'
binary "#{appdir}/Gqrx.app/Contents/MacOS/volk_profile"
# shim script (https://github.com/Homebrew/homebrew-cask/issues/18809)
shimscript = "#{staged_path}/gqrx.wrapper.sh"
binary shimscript, target: 'gqrx'
preflight do
IO.write shimscript, <<~EOS
#!/bin/sh
'#{appdir}/Gqrx.app/Contents/MacOS/gqrx' "$@"
EOS
end
end
| bsd-2-clause |
Jarbu12/Xperia-M-Kernel | kernel/drivers/video/msm/lcdc_wxga.c | 1413 | /* Copyright (c) 2009-2010, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#include "msm_fb.h"
static int __init lcdc_wxga_init(void)
{
int ret;
struct msm_panel_info pinfo;
#ifdef CONFIG_FB_MSM_MDDI_AUTO_DETECT
if (msm_fb_detect_client("lcdc_wxga"))
return 0;
#endif
pinfo.xres = 1280;
pinfo.yres = 720;
MSM_FB_SINGLE_MODE_PANEL(&pinfo);
pinfo.type = LCDC_PANEL;
pinfo.pdest = DISPLAY_1;
pinfo.wait_cycle = 0;
pinfo.bpp = 24;
pinfo.fb_num = 2;
pinfo.clk_rate = 74250000;
pinfo.lcdc.h_back_porch = 124;
pinfo.lcdc.h_front_porch = 110;
pinfo.lcdc.h_pulse_width = 136;
pinfo.lcdc.v_back_porch = 19;
pinfo.lcdc.v_front_porch = 5;
pinfo.lcdc.v_pulse_width = 6;
pinfo.lcdc.border_clr = 0; /* blk */
pinfo.lcdc.underflow_clr = 0xff; /* blue */
pinfo.lcdc.hsync_skew = 0;
ret = lcdc_device_register(&pinfo);
if (ret)
printk(KERN_ERR "%s: failed to register device!\n", __func__);
return ret;
}
module_init(lcdc_wxga_init);
| gpl-3.0 |
krk/coreclr | tests/src/JIT/HardwareIntrinsics/General/Vector128_1/GetAndWithElement.Single.0.cs | 8967 | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\General\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
namespace JIT.HardwareIntrinsics.General
{
public static partial class Program
{
private static void GetAndWithElementSingle0()
{
var test = new VectorGetAndWithElement__GetAndWithElementSingle0();
// Validates basic functionality works
test.RunBasicScenario();
// Validates calling via reflection works
test.RunReflectionScenario();
// Validates that invalid indices throws ArgumentOutOfRangeException
test.RunArgumentOutOfRangeScenario();
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class VectorGetAndWithElement__GetAndWithElementSingle0
{
private static readonly int LargestVectorSize = 16;
private static readonly int ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single);
public bool Succeeded { get; set; } = true;
public void RunBasicScenario(int imm = 0, bool expectedOutOfRangeException = false)
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario));
Single[] values = new Single[ElementCount];
for (int i = 0; i < ElementCount; i++)
{
values[i] = TestLibrary.Generator.GetSingle();
}
Vector128<Single> value = Vector128.Create(values[0], values[1], values[2], values[3]);
bool succeeded = !expectedOutOfRangeException;
try
{
Single result = value.GetElement(imm);
ValidateGetResult(result, values);
}
catch (ArgumentOutOfRangeException)
{
succeeded = expectedOutOfRangeException;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector128<Single.GetElement({imm}): {nameof(RunBasicScenario)} failed to throw ArgumentOutOfRangeException.");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
succeeded = !expectedOutOfRangeException;
Single insertedValue = TestLibrary.Generator.GetSingle();
try
{
Vector128<Single> result2 = value.WithElement(imm, insertedValue);
ValidateWithResult(result2, values, insertedValue);
}
catch (ArgumentOutOfRangeException)
{
succeeded = expectedOutOfRangeException;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector128<Single.WithElement({imm}): {nameof(RunBasicScenario)} failed to throw ArgumentOutOfRangeException.");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
public void RunReflectionScenario(int imm = 0, bool expectedOutOfRangeException = false)
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario));
Single[] values = new Single[ElementCount];
for (int i = 0; i < ElementCount; i++)
{
values[i] = TestLibrary.Generator.GetSingle();
}
Vector128<Single> value = Vector128.Create(values[0], values[1], values[2], values[3]);
bool succeeded = !expectedOutOfRangeException;
try
{
object result = typeof(Vector128)
.GetMethod(nameof(Vector128.GetElement))
.MakeGenericMethod(typeof(Single))
.Invoke(null, new object[] { value, imm });
ValidateGetResult((Single)(result), values);
}
catch (TargetInvocationException e)
{
succeeded = expectedOutOfRangeException
&& e.InnerException is ArgumentOutOfRangeException;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector128<Single.GetElement({imm}): {nameof(RunReflectionScenario)} failed to throw ArgumentOutOfRangeException.");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
succeeded = !expectedOutOfRangeException;
Single insertedValue = TestLibrary.Generator.GetSingle();
try
{
object result2 = typeof(Vector128)
.GetMethod(nameof(Vector128.WithElement))
.MakeGenericMethod(typeof(Single))
.Invoke(null, new object[] { value, imm, insertedValue });
ValidateWithResult((Vector128<Single>)(result2), values, insertedValue);
}
catch (TargetInvocationException e)
{
succeeded = expectedOutOfRangeException
&& e.InnerException is ArgumentOutOfRangeException;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector128<Single.WithElement({imm}): {nameof(RunReflectionScenario)} failed to throw ArgumentOutOfRangeException.");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
public void RunArgumentOutOfRangeScenario()
{
RunBasicScenario(0 - ElementCount, expectedOutOfRangeException: true);
RunBasicScenario(0 + ElementCount, expectedOutOfRangeException: true);
RunReflectionScenario(0 - ElementCount, expectedOutOfRangeException: true);
RunReflectionScenario(0 + ElementCount, expectedOutOfRangeException: true);
}
private void ValidateGetResult(Single result, Single[] values, [CallerMemberName] string method = "")
{
if (result != values[0])
{
Succeeded = false;
TestLibrary.TestFramework.LogInformation($"Vector128<Single.GetElement(0): {method} failed:");
TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})");
TestLibrary.TestFramework.LogInformation($" result: ({result})");
TestLibrary.TestFramework.LogInformation(string.Empty);
}
}
private void ValidateWithResult(Vector128<Single> result, Single[] values, Single insertedValue, [CallerMemberName] string method = "")
{
Single[] resultElements = new Single[ElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref resultElements[0]), result);
ValidateWithResult(resultElements, values, insertedValue, method);
}
private void ValidateWithResult(Single[] result, Single[] values, Single insertedValue, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (int i = 0; i < ElementCount; i++)
{
if ((i != 0) && (result[i] != values[i]))
{
succeeded = false;
break;
}
}
if (result[0] != insertedValue)
{
succeeded = false;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector128<Single.WithElement(0): {method} failed:");
TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})");
TestLibrary.TestFramework.LogInformation($" insert: insertedValue");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| mit |
MrMaidx/godot | thirdparty/freetype/src/cff/cffobjs.c | 35358 | /***************************************************************************/
/* */
/* cffobjs.c */
/* */
/* OpenType objects manager (body). */
/* */
/* Copyright 1996-2016 by */
/* David Turner, Robert Wilhelm, and Werner Lemberg. */
/* */
/* This file is part of the FreeType project, and may only be used, */
/* modified, and distributed under the terms of the FreeType project */
/* license, LICENSE.TXT. By continuing to use, modify, or distribute */
/* this file you indicate that you have read the license and */
/* understand and accept it fully. */
/* */
/***************************************************************************/
#include <ft2build.h>
#include FT_INTERNAL_DEBUG_H
#include FT_INTERNAL_CALC_H
#include FT_INTERNAL_STREAM_H
#include FT_ERRORS_H
#include FT_TRUETYPE_IDS_H
#include FT_TRUETYPE_TAGS_H
#include FT_INTERNAL_SFNT_H
#include FT_CFF_DRIVER_H
#include "cffobjs.h"
#include "cffload.h"
#include "cffcmap.h"
#include "cffpic.h"
#include "cfferrs.h"
/*************************************************************************/
/* */
/* The macro FT_COMPONENT is used in trace mode. It is an implicit */
/* parameter of the FT_TRACE() and FT_ERROR() macros, used to print/log */
/* messages during execution. */
/* */
#undef FT_COMPONENT
#define FT_COMPONENT trace_cffobjs
/*************************************************************************/
/* */
/* SIZE FUNCTIONS */
/* */
/* Note that we store the global hints in the size's `internal' root */
/* field. */
/* */
/*************************************************************************/
static PSH_Globals_Funcs
cff_size_get_globals_funcs( CFF_Size size )
{
CFF_Face face = (CFF_Face)size->root.face;
CFF_Font font = (CFF_Font)face->extra.data;
PSHinter_Service pshinter = font->pshinter;
FT_Module module;
module = FT_Get_Module( size->root.face->driver->root.library,
"pshinter" );
return ( module && pshinter && pshinter->get_globals_funcs )
? pshinter->get_globals_funcs( module )
: 0;
}
FT_LOCAL_DEF( void )
cff_size_done( FT_Size cffsize ) /* CFF_Size */
{
CFF_Size size = (CFF_Size)cffsize;
CFF_Face face = (CFF_Face)size->root.face;
CFF_Font font = (CFF_Font)face->extra.data;
CFF_Internal internal = (CFF_Internal)cffsize->internal;
if ( internal )
{
PSH_Globals_Funcs funcs;
funcs = cff_size_get_globals_funcs( size );
if ( funcs )
{
FT_UInt i;
funcs->destroy( internal->topfont );
for ( i = font->num_subfonts; i > 0; i-- )
funcs->destroy( internal->subfonts[i - 1] );
}
/* `internal' is freed by destroy_size (in ftobjs.c) */
}
}
/* CFF and Type 1 private dictionaries have slightly different */
/* structures; we need to synthesize a Type 1 dictionary on the fly */
static void
cff_make_private_dict( CFF_SubFont subfont,
PS_Private priv )
{
CFF_Private cpriv = &subfont->private_dict;
FT_UInt n, count;
FT_MEM_ZERO( priv, sizeof ( *priv ) );
count = priv->num_blue_values = cpriv->num_blue_values;
for ( n = 0; n < count; n++ )
priv->blue_values[n] = (FT_Short)cpriv->blue_values[n];
count = priv->num_other_blues = cpriv->num_other_blues;
for ( n = 0; n < count; n++ )
priv->other_blues[n] = (FT_Short)cpriv->other_blues[n];
count = priv->num_family_blues = cpriv->num_family_blues;
for ( n = 0; n < count; n++ )
priv->family_blues[n] = (FT_Short)cpriv->family_blues[n];
count = priv->num_family_other_blues = cpriv->num_family_other_blues;
for ( n = 0; n < count; n++ )
priv->family_other_blues[n] = (FT_Short)cpriv->family_other_blues[n];
priv->blue_scale = cpriv->blue_scale;
priv->blue_shift = (FT_Int)cpriv->blue_shift;
priv->blue_fuzz = (FT_Int)cpriv->blue_fuzz;
priv->standard_width[0] = (FT_UShort)cpriv->standard_width;
priv->standard_height[0] = (FT_UShort)cpriv->standard_height;
count = priv->num_snap_widths = cpriv->num_snap_widths;
for ( n = 0; n < count; n++ )
priv->snap_widths[n] = (FT_Short)cpriv->snap_widths[n];
count = priv->num_snap_heights = cpriv->num_snap_heights;
for ( n = 0; n < count; n++ )
priv->snap_heights[n] = (FT_Short)cpriv->snap_heights[n];
priv->force_bold = cpriv->force_bold;
priv->language_group = cpriv->language_group;
priv->lenIV = cpriv->lenIV;
}
FT_LOCAL_DEF( FT_Error )
cff_size_init( FT_Size cffsize ) /* CFF_Size */
{
CFF_Size size = (CFF_Size)cffsize;
FT_Error error = FT_Err_Ok;
PSH_Globals_Funcs funcs = cff_size_get_globals_funcs( size );
if ( funcs )
{
CFF_Face face = (CFF_Face)cffsize->face;
CFF_Font font = (CFF_Font)face->extra.data;
CFF_Internal internal = NULL;
PS_PrivateRec priv;
FT_Memory memory = cffsize->face->memory;
FT_UInt i;
if ( FT_NEW( internal ) )
goto Exit;
cff_make_private_dict( &font->top_font, &priv );
error = funcs->create( cffsize->face->memory, &priv,
&internal->topfont );
if ( error )
goto Exit;
for ( i = font->num_subfonts; i > 0; i-- )
{
CFF_SubFont sub = font->subfonts[i - 1];
cff_make_private_dict( sub, &priv );
error = funcs->create( cffsize->face->memory, &priv,
&internal->subfonts[i - 1] );
if ( error )
goto Exit;
}
cffsize->internal = (FT_Size_Internal)(void*)internal;
}
size->strike_index = 0xFFFFFFFFUL;
Exit:
return error;
}
#ifdef TT_CONFIG_OPTION_EMBEDDED_BITMAPS
FT_LOCAL_DEF( FT_Error )
cff_size_select( FT_Size size,
FT_ULong strike_index )
{
CFF_Size cffsize = (CFF_Size)size;
PSH_Globals_Funcs funcs;
cffsize->strike_index = strike_index;
FT_Select_Metrics( size->face, strike_index );
funcs = cff_size_get_globals_funcs( cffsize );
if ( funcs )
{
CFF_Face face = (CFF_Face)size->face;
CFF_Font font = (CFF_Font)face->extra.data;
CFF_Internal internal = (CFF_Internal)size->internal;
FT_Long top_upm = (FT_Long)font->top_font.font_dict.units_per_em;
FT_UInt i;
funcs->set_scale( internal->topfont,
size->metrics.x_scale, size->metrics.y_scale,
0, 0 );
for ( i = font->num_subfonts; i > 0; i-- )
{
CFF_SubFont sub = font->subfonts[i - 1];
FT_Long sub_upm = (FT_Long)sub->font_dict.units_per_em;
FT_Pos x_scale, y_scale;
if ( top_upm != sub_upm )
{
x_scale = FT_MulDiv( size->metrics.x_scale, top_upm, sub_upm );
y_scale = FT_MulDiv( size->metrics.y_scale, top_upm, sub_upm );
}
else
{
x_scale = size->metrics.x_scale;
y_scale = size->metrics.y_scale;
}
funcs->set_scale( internal->subfonts[i - 1],
x_scale, y_scale, 0, 0 );
}
}
return FT_Err_Ok;
}
#endif /* TT_CONFIG_OPTION_EMBEDDED_BITMAPS */
FT_LOCAL_DEF( FT_Error )
cff_size_request( FT_Size size,
FT_Size_Request req )
{
CFF_Size cffsize = (CFF_Size)size;
PSH_Globals_Funcs funcs;
#ifdef TT_CONFIG_OPTION_EMBEDDED_BITMAPS
if ( FT_HAS_FIXED_SIZES( size->face ) )
{
CFF_Face cffface = (CFF_Face)size->face;
SFNT_Service sfnt = (SFNT_Service)cffface->sfnt;
FT_ULong strike_index;
if ( sfnt->set_sbit_strike( cffface, req, &strike_index ) )
cffsize->strike_index = 0xFFFFFFFFUL;
else
return cff_size_select( size, strike_index );
}
#endif /* TT_CONFIG_OPTION_EMBEDDED_BITMAPS */
FT_Request_Metrics( size->face, req );
funcs = cff_size_get_globals_funcs( cffsize );
if ( funcs )
{
CFF_Face cffface = (CFF_Face)size->face;
CFF_Font font = (CFF_Font)cffface->extra.data;
CFF_Internal internal = (CFF_Internal)size->internal;
FT_Long top_upm = (FT_Long)font->top_font.font_dict.units_per_em;
FT_UInt i;
funcs->set_scale( internal->topfont,
size->metrics.x_scale, size->metrics.y_scale,
0, 0 );
for ( i = font->num_subfonts; i > 0; i-- )
{
CFF_SubFont sub = font->subfonts[i - 1];
FT_Long sub_upm = (FT_Long)sub->font_dict.units_per_em;
FT_Pos x_scale, y_scale;
if ( top_upm != sub_upm )
{
x_scale = FT_MulDiv( size->metrics.x_scale, top_upm, sub_upm );
y_scale = FT_MulDiv( size->metrics.y_scale, top_upm, sub_upm );
}
else
{
x_scale = size->metrics.x_scale;
y_scale = size->metrics.y_scale;
}
funcs->set_scale( internal->subfonts[i - 1],
x_scale, y_scale, 0, 0 );
}
}
return FT_Err_Ok;
}
/*************************************************************************/
/* */
/* SLOT FUNCTIONS */
/* */
/*************************************************************************/
FT_LOCAL_DEF( void )
cff_slot_done( FT_GlyphSlot slot )
{
slot->internal->glyph_hints = NULL;
}
FT_LOCAL_DEF( FT_Error )
cff_slot_init( FT_GlyphSlot slot )
{
CFF_Face face = (CFF_Face)slot->face;
CFF_Font font = (CFF_Font)face->extra.data;
PSHinter_Service pshinter = font->pshinter;
if ( pshinter )
{
FT_Module module;
module = FT_Get_Module( slot->face->driver->root.library,
"pshinter" );
if ( module )
{
T2_Hints_Funcs funcs;
funcs = pshinter->get_t2_funcs( module );
slot->internal->glyph_hints = (void*)funcs;
}
}
return FT_Err_Ok;
}
/*************************************************************************/
/* */
/* FACE FUNCTIONS */
/* */
/*************************************************************************/
static FT_String*
cff_strcpy( FT_Memory memory,
const FT_String* source )
{
FT_Error error;
FT_String* result;
(void)FT_STRDUP( result, source );
FT_UNUSED( error );
return result;
}
/* Strip all subset prefixes of the form `ABCDEF+'. Usually, there */
/* is only one, but font names like `APCOOG+JFABTD+FuturaBQ-Bold' */
/* have been seen in the wild. */
static void
remove_subset_prefix( FT_String* name )
{
FT_Int32 idx = 0;
FT_Int32 length = (FT_Int32)strlen( name ) + 1;
FT_Bool continue_search = 1;
while ( continue_search )
{
if ( length >= 7 && name[6] == '+' )
{
for ( idx = 0; idx < 6; idx++ )
{
/* ASCII uppercase letters */
if ( !( 'A' <= name[idx] && name[idx] <= 'Z' ) )
continue_search = 0;
}
if ( continue_search )
{
for ( idx = 7; idx < length; idx++ )
name[idx - 7] = name[idx];
length -= 7;
}
}
else
continue_search = 0;
}
}
/* Remove the style part from the family name (if present). */
static void
remove_style( FT_String* family_name,
const FT_String* style_name )
{
FT_Int32 family_name_length, style_name_length;
family_name_length = (FT_Int32)strlen( family_name );
style_name_length = (FT_Int32)strlen( style_name );
if ( family_name_length > style_name_length )
{
FT_Int idx;
for ( idx = 1; idx <= style_name_length; ++idx )
{
if ( family_name[family_name_length - idx] !=
style_name[style_name_length - idx] )
break;
}
if ( idx > style_name_length )
{
/* family_name ends with style_name; remove it */
idx = family_name_length - style_name_length - 1;
/* also remove special characters */
/* between real family name and style */
while ( idx > 0 &&
( family_name[idx] == '-' ||
family_name[idx] == ' ' ||
family_name[idx] == '_' ||
family_name[idx] == '+' ) )
--idx;
if ( idx > 0 )
family_name[idx + 1] = '\0';
}
}
}
FT_LOCAL_DEF( FT_Error )
cff_face_init( FT_Stream stream,
FT_Face cffface, /* CFF_Face */
FT_Int face_index,
FT_Int num_params,
FT_Parameter* params )
{
CFF_Face face = (CFF_Face)cffface;
FT_Error error;
SFNT_Service sfnt;
FT_Service_PsCMaps psnames;
PSHinter_Service pshinter;
FT_Bool pure_cff = 1;
FT_Bool sfnt_format = 0;
FT_Library library = cffface->driver->root.library;
sfnt = (SFNT_Service)FT_Get_Module_Interface(
library, "sfnt" );
if ( !sfnt )
{
FT_ERROR(( "cff_face_init: cannot access `sfnt' module\n" ));
error = FT_THROW( Missing_Module );
goto Exit;
}
FT_FACE_FIND_GLOBAL_SERVICE( face, psnames, POSTSCRIPT_CMAPS );
pshinter = (PSHinter_Service)FT_Get_Module_Interface(
library, "pshinter" );
FT_TRACE2(( "CFF driver\n" ));
/* create input stream from resource */
if ( FT_STREAM_SEEK( 0 ) )
goto Exit;
/* check whether we have a valid OpenType file */
error = sfnt->init_face( stream, face, face_index, num_params, params );
if ( !error )
{
if ( face->format_tag != TTAG_OTTO ) /* `OTTO'; OpenType/CFF font */
{
FT_TRACE2(( " not an OpenType/CFF font\n" ));
error = FT_THROW( Unknown_File_Format );
goto Exit;
}
/* if we are performing a simple font format check, exit immediately */
if ( face_index < 0 )
return FT_Err_Ok;
sfnt_format = 1;
/* now, the font can be either an OpenType/CFF font, or an SVG CEF */
/* font; in the latter case it doesn't have a `head' table */
error = face->goto_table( face, TTAG_head, stream, 0 );
if ( !error )
{
pure_cff = 0;
/* load font directory */
error = sfnt->load_face( stream, face, face_index,
num_params, params );
if ( error )
goto Exit;
}
else
{
/* load the `cmap' table explicitly */
error = sfnt->load_cmap( face, stream );
if ( error )
goto Exit;
}
/* now load the CFF part of the file */
error = face->goto_table( face, TTAG_CFF, stream, 0 );
if ( error )
goto Exit;
}
else
{
/* rewind to start of file; we are going to load a pure-CFF font */
if ( FT_STREAM_SEEK( 0 ) )
goto Exit;
error = FT_Err_Ok;
}
/* now load and parse the CFF table in the file */
{
CFF_Font cff = NULL;
CFF_FontRecDict dict;
FT_Memory memory = cffface->memory;
FT_Int32 flags;
FT_UInt i;
if ( FT_NEW( cff ) )
goto Exit;
face->extra.data = cff;
error = cff_font_load( library, stream, face_index, cff, pure_cff );
if ( error )
goto Exit;
/* if we are performing a simple font format check, exit immediately */
/* (this is here for pure CFF) */
if ( face_index < 0 )
{
cffface->num_faces = (FT_Long)cff->num_faces;
return FT_Err_Ok;
}
cff->pshinter = pshinter;
cff->psnames = psnames;
cffface->face_index = face_index & 0xFFFF;
/* Complement the root flags with some interesting information. */
/* Note that this is only necessary for pure CFF and CEF fonts; */
/* SFNT based fonts use the `name' table instead. */
cffface->num_glyphs = (FT_Long)cff->num_glyphs;
dict = &cff->top_font.font_dict;
/* we need the `PSNames' module for CFF and CEF formats */
/* which aren't CID-keyed */
if ( dict->cid_registry == 0xFFFFU && !psnames )
{
FT_ERROR(( "cff_face_init:"
" cannot open CFF & CEF fonts\n"
" "
" without the `PSNames' module\n" ));
error = FT_THROW( Missing_Module );
goto Exit;
}
#ifdef FT_DEBUG_LEVEL_TRACE
{
FT_UInt idx;
FT_String* s;
FT_TRACE4(( "SIDs\n" ));
/* dump string index, including default strings for convenience */
for ( idx = 0; idx <= 390; idx++ )
{
s = cff_index_get_sid_string( cff, idx );
if ( s )
FT_TRACE4(( " %5d %s\n", idx, s ));
}
/* In Multiple Master CFFs, two SIDs hold the Normalize Design */
/* Vector (NDV) and Convert Design Vector (CDV) charstrings, */
/* which may contain NULL bytes in the middle of the data, too. */
/* We thus access `cff->strings' directly. */
for ( idx = 1; idx < cff->num_strings; idx++ )
{
FT_Byte* s1 = cff->strings[idx - 1];
FT_Byte* s2 = cff->strings[idx];
FT_PtrDist s1len = s2 - s1 - 1; /* without the final NULL byte */
FT_PtrDist l;
FT_TRACE4(( " %5d ", idx + 390 ));
for ( l = 0; l < s1len; l++ )
FT_TRACE4(( "%c", s1[l] ));
FT_TRACE4(( "\n" ));
}
/* print last element */
if ( cff->num_strings )
{
FT_Byte* s1 = cff->strings[cff->num_strings - 1];
FT_Byte* s2 = cff->string_pool + cff->string_pool_size;
FT_PtrDist s1len = s2 - s1 - 1;
FT_PtrDist l;
FT_TRACE4(( " %5d ", cff->num_strings + 390 ));
for ( l = 0; l < s1len; l++ )
FT_TRACE4(( "%c", s1[l] ));
FT_TRACE4(( "\n" ));
}
}
#endif /* FT_DEBUG_LEVEL_TRACE */
if ( !dict->has_font_matrix )
dict->units_per_em = pure_cff ? 1000 : face->root.units_per_EM;
/* Normalize the font matrix so that `matrix->yy' is 1; if */
/* it is zero, we use `matrix->yx' instead. The scaling is */
/* done with `units_per_em' then (at this point, it already */
/* contains the scaling factor, but without normalization */
/* of the matrix). */
/* */
/* Note that the offsets must be expressed in integer font */
/* units. */
{
FT_Matrix* matrix = &dict->font_matrix;
FT_Vector* offset = &dict->font_offset;
FT_ULong* upm = &dict->units_per_em;
FT_Fixed temp;
temp = matrix->yy ? FT_ABS( matrix->yy )
: FT_ABS( matrix->yx );
if ( temp != 0x10000L )
{
*upm = (FT_ULong)FT_DivFix( (FT_Long)*upm, temp );
matrix->xx = FT_DivFix( matrix->xx, temp );
matrix->yx = FT_DivFix( matrix->yx, temp );
matrix->xy = FT_DivFix( matrix->xy, temp );
matrix->yy = FT_DivFix( matrix->yy, temp );
offset->x = FT_DivFix( offset->x, temp );
offset->y = FT_DivFix( offset->y, temp );
}
offset->x >>= 16;
offset->y >>= 16;
}
for ( i = cff->num_subfonts; i > 0; i-- )
{
CFF_FontRecDict sub = &cff->subfonts[i - 1]->font_dict;
CFF_FontRecDict top = &cff->top_font.font_dict;
FT_Matrix* matrix;
FT_Vector* offset;
FT_ULong* upm;
FT_Fixed temp;
if ( sub->has_font_matrix )
{
FT_Long scaling;
/* if we have a top-level matrix, */
/* concatenate the subfont matrix */
if ( top->has_font_matrix )
{
if ( top->units_per_em > 1 && sub->units_per_em > 1 )
scaling = (FT_Long)FT_MIN( top->units_per_em,
sub->units_per_em );
else
scaling = 1;
FT_Matrix_Multiply_Scaled( &top->font_matrix,
&sub->font_matrix,
scaling );
FT_Vector_Transform_Scaled( &sub->font_offset,
&top->font_matrix,
scaling );
sub->units_per_em = (FT_ULong)
FT_MulDiv( (FT_Long)sub->units_per_em,
(FT_Long)top->units_per_em,
scaling );
}
}
else
{
sub->font_matrix = top->font_matrix;
sub->font_offset = top->font_offset;
sub->units_per_em = top->units_per_em;
}
matrix = &sub->font_matrix;
offset = &sub->font_offset;
upm = &sub->units_per_em;
temp = matrix->yy ? FT_ABS( matrix->yy )
: FT_ABS( matrix->yx );
if ( temp != 0x10000L )
{
*upm = (FT_ULong)FT_DivFix( (FT_Long)*upm, temp );
matrix->xx = FT_DivFix( matrix->xx, temp );
matrix->yx = FT_DivFix( matrix->yx, temp );
matrix->xy = FT_DivFix( matrix->xy, temp );
matrix->yy = FT_DivFix( matrix->yy, temp );
offset->x = FT_DivFix( offset->x, temp );
offset->y = FT_DivFix( offset->y, temp );
}
offset->x >>= 16;
offset->y >>= 16;
}
if ( pure_cff )
{
char* style_name = NULL;
/* set up num_faces */
cffface->num_faces = (FT_Long)cff->num_faces;
/* compute number of glyphs */
if ( dict->cid_registry != 0xFFFFU )
cffface->num_glyphs = (FT_Long)( cff->charset.max_cid + 1 );
else
cffface->num_glyphs = (FT_Long)cff->charstrings_index.count;
/* set global bbox, as well as EM size */
cffface->bbox.xMin = dict->font_bbox.xMin >> 16;
cffface->bbox.yMin = dict->font_bbox.yMin >> 16;
/* no `U' suffix here to 0xFFFF! */
cffface->bbox.xMax = ( dict->font_bbox.xMax + 0xFFFF ) >> 16;
cffface->bbox.yMax = ( dict->font_bbox.yMax + 0xFFFF ) >> 16;
cffface->units_per_EM = (FT_UShort)( dict->units_per_em );
cffface->ascender = (FT_Short)( cffface->bbox.yMax );
cffface->descender = (FT_Short)( cffface->bbox.yMin );
cffface->height = (FT_Short)( ( cffface->units_per_EM * 12 ) / 10 );
if ( cffface->height < cffface->ascender - cffface->descender )
cffface->height = (FT_Short)( cffface->ascender - cffface->descender );
cffface->underline_position =
(FT_Short)( dict->underline_position >> 16 );
cffface->underline_thickness =
(FT_Short)( dict->underline_thickness >> 16 );
/* retrieve font family & style name */
cffface->family_name = cff_index_get_name(
cff,
(FT_UInt)( face_index & 0xFFFF ) );
if ( cffface->family_name )
{
char* full = cff_index_get_sid_string( cff,
dict->full_name );
char* fullp = full;
char* family = cffface->family_name;
char* family_name = NULL;
remove_subset_prefix( cffface->family_name );
if ( dict->family_name )
{
family_name = cff_index_get_sid_string( cff,
dict->family_name );
if ( family_name )
family = family_name;
}
/* We try to extract the style name from the full name. */
/* We need to ignore spaces and dashes during the search. */
if ( full && family )
{
while ( *fullp )
{
/* skip common characters at the start of both strings */
if ( *fullp == *family )
{
family++;
fullp++;
continue;
}
/* ignore spaces and dashes in full name during comparison */
if ( *fullp == ' ' || *fullp == '-' )
{
fullp++;
continue;
}
/* ignore spaces and dashes in family name during comparison */
if ( *family == ' ' || *family == '-' )
{
family++;
continue;
}
if ( !*family && *fullp )
{
/* The full name begins with the same characters as the */
/* family name, with spaces and dashes removed. In this */
/* case, the remaining string in `fullp' will be used as */
/* the style name. */
style_name = cff_strcpy( memory, fullp );
/* remove the style part from the family name (if present) */
remove_style( cffface->family_name, style_name );
}
break;
}
}
}
else
{
char *cid_font_name =
cff_index_get_sid_string( cff,
dict->cid_font_name );
/* do we have a `/FontName' for a CID-keyed font? */
if ( cid_font_name )
cffface->family_name = cff_strcpy( memory, cid_font_name );
}
if ( style_name )
cffface->style_name = style_name;
else
/* assume "Regular" style if we don't know better */
cffface->style_name = cff_strcpy( memory, (char *)"Regular" );
/*******************************************************************/
/* */
/* Compute face flags. */
/* */
flags = FT_FACE_FLAG_SCALABLE | /* scalable outlines */
FT_FACE_FLAG_HORIZONTAL | /* horizontal data */
FT_FACE_FLAG_HINTER; /* has native hinter */
if ( sfnt_format )
flags |= FT_FACE_FLAG_SFNT;
/* fixed width font? */
if ( dict->is_fixed_pitch )
flags |= FT_FACE_FLAG_FIXED_WIDTH;
/* XXX: WE DO NOT SUPPORT KERNING METRICS IN THE GPOS TABLE FOR NOW */
#if 0
/* kerning available? */
if ( face->kern_pairs )
flags |= FT_FACE_FLAG_KERNING;
#endif
cffface->face_flags |= flags;
/*******************************************************************/
/* */
/* Compute style flags. */
/* */
flags = 0;
if ( dict->italic_angle )
flags |= FT_STYLE_FLAG_ITALIC;
{
char *weight = cff_index_get_sid_string( cff,
dict->weight );
if ( weight )
if ( !ft_strcmp( weight, "Bold" ) ||
!ft_strcmp( weight, "Black" ) )
flags |= FT_STYLE_FLAG_BOLD;
}
/* double check */
if ( !(flags & FT_STYLE_FLAG_BOLD) && cffface->style_name )
if ( !ft_strncmp( cffface->style_name, "Bold", 4 ) ||
!ft_strncmp( cffface->style_name, "Black", 5 ) )
flags |= FT_STYLE_FLAG_BOLD;
cffface->style_flags = flags;
}
#ifndef FT_CONFIG_OPTION_NO_GLYPH_NAMES
/* CID-keyed CFF fonts don't have glyph names -- the SFNT loader */
/* has unset this flag because of the 3.0 `post' table. */
if ( dict->cid_registry == 0xFFFFU )
cffface->face_flags |= FT_FACE_FLAG_GLYPH_NAMES;
#endif
if ( dict->cid_registry != 0xFFFFU && pure_cff )
cffface->face_flags |= FT_FACE_FLAG_CID_KEYED;
/*******************************************************************/
/* */
/* Compute char maps. */
/* */
/* Try to synthesize a Unicode charmap if there is none available */
/* already. If an OpenType font contains a Unicode "cmap", we */
/* will use it, whatever be in the CFF part of the file. */
{
FT_CharMapRec cmaprec;
FT_CharMap cmap;
FT_UInt nn;
CFF_Encoding encoding = &cff->encoding;
for ( nn = 0; nn < (FT_UInt)cffface->num_charmaps; nn++ )
{
cmap = cffface->charmaps[nn];
/* Windows Unicode? */
if ( cmap->platform_id == TT_PLATFORM_MICROSOFT &&
cmap->encoding_id == TT_MS_ID_UNICODE_CS )
goto Skip_Unicode;
/* Apple Unicode platform id? */
if ( cmap->platform_id == TT_PLATFORM_APPLE_UNICODE )
goto Skip_Unicode; /* Apple Unicode */
}
/* since CID-keyed fonts don't contain glyph names, we can't */
/* construct a cmap */
if ( pure_cff && cff->top_font.font_dict.cid_registry != 0xFFFFU )
goto Exit;
/* we didn't find a Unicode charmap -- synthesize one */
cmaprec.face = cffface;
cmaprec.platform_id = TT_PLATFORM_MICROSOFT;
cmaprec.encoding_id = TT_MS_ID_UNICODE_CS;
cmaprec.encoding = FT_ENCODING_UNICODE;
nn = (FT_UInt)cffface->num_charmaps;
error = FT_CMap_New( &CFF_CMAP_UNICODE_CLASS_REC_GET, NULL,
&cmaprec, NULL );
if ( error &&
FT_ERR_NEQ( error, No_Unicode_Glyph_Name ) )
goto Exit;
error = FT_Err_Ok;
/* if no Unicode charmap was previously selected, select this one */
if ( cffface->charmap == NULL && nn != (FT_UInt)cffface->num_charmaps )
cffface->charmap = cffface->charmaps[nn];
Skip_Unicode:
if ( encoding->count > 0 )
{
FT_CMap_Class clazz;
cmaprec.face = cffface;
cmaprec.platform_id = TT_PLATFORM_ADOBE; /* Adobe platform id */
if ( encoding->offset == 0 )
{
cmaprec.encoding_id = TT_ADOBE_ID_STANDARD;
cmaprec.encoding = FT_ENCODING_ADOBE_STANDARD;
clazz = &CFF_CMAP_ENCODING_CLASS_REC_GET;
}
else if ( encoding->offset == 1 )
{
cmaprec.encoding_id = TT_ADOBE_ID_EXPERT;
cmaprec.encoding = FT_ENCODING_ADOBE_EXPERT;
clazz = &CFF_CMAP_ENCODING_CLASS_REC_GET;
}
else
{
cmaprec.encoding_id = TT_ADOBE_ID_CUSTOM;
cmaprec.encoding = FT_ENCODING_ADOBE_CUSTOM;
clazz = &CFF_CMAP_ENCODING_CLASS_REC_GET;
}
error = FT_CMap_New( clazz, NULL, &cmaprec, NULL );
}
}
}
Exit:
return error;
}
FT_LOCAL_DEF( void )
cff_face_done( FT_Face cffface ) /* CFF_Face */
{
CFF_Face face = (CFF_Face)cffface;
FT_Memory memory;
SFNT_Service sfnt;
if ( !face )
return;
memory = cffface->memory;
sfnt = (SFNT_Service)face->sfnt;
if ( sfnt )
sfnt->done_face( face );
{
CFF_Font cff = (CFF_Font)face->extra.data;
if ( cff )
{
cff_font_done( cff );
FT_FREE( face->extra.data );
}
}
}
FT_LOCAL_DEF( FT_Error )
cff_driver_init( FT_Module module ) /* CFF_Driver */
{
CFF_Driver driver = (CFF_Driver)module;
/* set default property values, cf. `ftcffdrv.h' */
#ifdef CFF_CONFIG_OPTION_OLD_ENGINE
driver->hinting_engine = FT_CFF_HINTING_FREETYPE;
#else
driver->hinting_engine = FT_CFF_HINTING_ADOBE;
#endif
driver->no_stem_darkening = TRUE;
driver->darken_params[0] = CFF_CONFIG_OPTION_DARKENING_PARAMETER_X1;
driver->darken_params[1] = CFF_CONFIG_OPTION_DARKENING_PARAMETER_Y1;
driver->darken_params[2] = CFF_CONFIG_OPTION_DARKENING_PARAMETER_X2;
driver->darken_params[3] = CFF_CONFIG_OPTION_DARKENING_PARAMETER_Y2;
driver->darken_params[4] = CFF_CONFIG_OPTION_DARKENING_PARAMETER_X3;
driver->darken_params[5] = CFF_CONFIG_OPTION_DARKENING_PARAMETER_Y3;
driver->darken_params[6] = CFF_CONFIG_OPTION_DARKENING_PARAMETER_X4;
driver->darken_params[7] = CFF_CONFIG_OPTION_DARKENING_PARAMETER_Y4;
return FT_Err_Ok;
}
FT_LOCAL_DEF( void )
cff_driver_done( FT_Module module ) /* CFF_Driver */
{
FT_UNUSED( module );
}
/* END */
| mit |
kmtoki/qmk_firmware | keyboards/handwired/pytest/has_template/templates/keymap.c | 109 | #include QMK_KEYBOARD_H
const uint16_t PROGMEM keymaps[][MATRIX_ROWS][MATRIX_COLS] = {__KEYMAP_GOES_HERE__};
| gpl-2.0 |
stevelord/PR30 | linux-2.6.31/drivers/usb/storage/jumpshot.c | 18639 | /* Driver for Lexar "Jumpshot" Compact Flash reader
*
* jumpshot driver v0.1:
*
* First release
*
* Current development and maintenance by:
* (c) 2000 Jimmie Mayfield ([email protected])
*
* Many thanks to Robert Baruch for the SanDisk SmartMedia reader driver
* which I used as a template for this driver.
*
* Some bugfixes and scatter-gather code by Gregory P. Smith
* ([email protected])
*
* Fix for media change by Joerg Schneider ([email protected])
*
* Developed with the assistance of:
*
* (C) 2002 Alan Stern <[email protected]>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2, or (at your option) any
* later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/*
* This driver attempts to support the Lexar Jumpshot USB CompactFlash
* reader. Like many other USB CompactFlash readers, the Jumpshot contains
* a USB-to-ATA chip.
*
* This driver supports reading and writing. If you're truly paranoid,
* however, you can force the driver into a write-protected state by setting
* the WP enable bits in jumpshot_handle_mode_sense. See the comments
* in that routine.
*/
#include <linux/errno.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <scsi/scsi.h>
#include <scsi/scsi_cmnd.h>
#include "usb.h"
#include "transport.h"
#include "protocol.h"
#include "debug.h"
MODULE_DESCRIPTION("Driver for Lexar \"Jumpshot\" Compact Flash reader");
MODULE_AUTHOR("Jimmie Mayfield <[email protected]>");
MODULE_LICENSE("GPL");
/*
* The table of devices
*/
#define UNUSUAL_DEV(id_vendor, id_product, bcdDeviceMin, bcdDeviceMax, \
vendorName, productName, useProtocol, useTransport, \
initFunction, flags) \
{ USB_DEVICE_VER(id_vendor, id_product, bcdDeviceMin, bcdDeviceMax), \
.driver_info = (flags)|(USB_US_TYPE_STOR<<24) }
struct usb_device_id jumpshot_usb_ids[] = {
# include "unusual_jumpshot.h"
{ } /* Terminating entry */
};
MODULE_DEVICE_TABLE(usb, jumpshot_usb_ids);
#undef UNUSUAL_DEV
/*
* The flags table
*/
#define UNUSUAL_DEV(idVendor, idProduct, bcdDeviceMin, bcdDeviceMax, \
vendor_name, product_name, use_protocol, use_transport, \
init_function, Flags) \
{ \
.vendorName = vendor_name, \
.productName = product_name, \
.useProtocol = use_protocol, \
.useTransport = use_transport, \
.initFunction = init_function, \
}
static struct us_unusual_dev jumpshot_unusual_dev_list[] = {
# include "unusual_jumpshot.h"
{ } /* Terminating entry */
};
#undef UNUSUAL_DEV
struct jumpshot_info {
unsigned long sectors; /* total sector count */
unsigned long ssize; /* sector size in bytes */
/* the following aren't used yet */
unsigned char sense_key;
unsigned long sense_asc; /* additional sense code */
unsigned long sense_ascq; /* additional sense code qualifier */
};
static inline int jumpshot_bulk_read(struct us_data *us,
unsigned char *data,
unsigned int len)
{
if (len == 0)
return USB_STOR_XFER_GOOD;
US_DEBUGP("jumpshot_bulk_read: len = %d\n", len);
return usb_stor_bulk_transfer_buf(us, us->recv_bulk_pipe,
data, len, NULL);
}
static inline int jumpshot_bulk_write(struct us_data *us,
unsigned char *data,
unsigned int len)
{
if (len == 0)
return USB_STOR_XFER_GOOD;
US_DEBUGP("jumpshot_bulk_write: len = %d\n", len);
return usb_stor_bulk_transfer_buf(us, us->send_bulk_pipe,
data, len, NULL);
}
static int jumpshot_get_status(struct us_data *us)
{
int rc;
if (!us)
return USB_STOR_TRANSPORT_ERROR;
// send the setup
rc = usb_stor_ctrl_transfer(us, us->recv_ctrl_pipe,
0, 0xA0, 0, 7, us->iobuf, 1);
if (rc != USB_STOR_XFER_GOOD)
return USB_STOR_TRANSPORT_ERROR;
if (us->iobuf[0] != 0x50) {
US_DEBUGP("jumpshot_get_status: 0x%2x\n",
us->iobuf[0]);
return USB_STOR_TRANSPORT_ERROR;
}
return USB_STOR_TRANSPORT_GOOD;
}
static int jumpshot_read_data(struct us_data *us,
struct jumpshot_info *info,
u32 sector,
u32 sectors)
{
unsigned char *command = us->iobuf;
unsigned char *buffer;
unsigned char thistime;
unsigned int totallen, alloclen;
int len, result;
unsigned int sg_offset = 0;
struct scatterlist *sg = NULL;
// we're working in LBA mode. according to the ATA spec,
// we can support up to 28-bit addressing. I don't know if Jumpshot
// supports beyond 24-bit addressing. It's kind of hard to test
// since it requires > 8GB CF card.
if (sector > 0x0FFFFFFF)
return USB_STOR_TRANSPORT_ERROR;
totallen = sectors * info->ssize;
// Since we don't read more than 64 KB at a time, we have to create
// a bounce buffer and move the data a piece at a time between the
// bounce buffer and the actual transfer buffer.
alloclen = min(totallen, 65536u);
buffer = kmalloc(alloclen, GFP_NOIO);
if (buffer == NULL)
return USB_STOR_TRANSPORT_ERROR;
do {
// loop, never allocate or transfer more than 64k at once
// (min(128k, 255*info->ssize) is the real limit)
len = min(totallen, alloclen);
thistime = (len / info->ssize) & 0xff;
command[0] = 0;
command[1] = thistime;
command[2] = sector & 0xFF;
command[3] = (sector >> 8) & 0xFF;
command[4] = (sector >> 16) & 0xFF;
command[5] = 0xE0 | ((sector >> 24) & 0x0F);
command[6] = 0x20;
// send the setup + command
result = usb_stor_ctrl_transfer(us, us->send_ctrl_pipe,
0, 0x20, 0, 1, command, 7);
if (result != USB_STOR_XFER_GOOD)
goto leave;
// read the result
result = jumpshot_bulk_read(us, buffer, len);
if (result != USB_STOR_XFER_GOOD)
goto leave;
US_DEBUGP("jumpshot_read_data: %d bytes\n", len);
// Store the data in the transfer buffer
usb_stor_access_xfer_buf(buffer, len, us->srb,
&sg, &sg_offset, TO_XFER_BUF);
sector += thistime;
totallen -= len;
} while (totallen > 0);
kfree(buffer);
return USB_STOR_TRANSPORT_GOOD;
leave:
kfree(buffer);
return USB_STOR_TRANSPORT_ERROR;
}
static int jumpshot_write_data(struct us_data *us,
struct jumpshot_info *info,
u32 sector,
u32 sectors)
{
unsigned char *command = us->iobuf;
unsigned char *buffer;
unsigned char thistime;
unsigned int totallen, alloclen;
int len, result, waitcount;
unsigned int sg_offset = 0;
struct scatterlist *sg = NULL;
// we're working in LBA mode. according to the ATA spec,
// we can support up to 28-bit addressing. I don't know if Jumpshot
// supports beyond 24-bit addressing. It's kind of hard to test
// since it requires > 8GB CF card.
//
if (sector > 0x0FFFFFFF)
return USB_STOR_TRANSPORT_ERROR;
totallen = sectors * info->ssize;
// Since we don't write more than 64 KB at a time, we have to create
// a bounce buffer and move the data a piece at a time between the
// bounce buffer and the actual transfer buffer.
alloclen = min(totallen, 65536u);
buffer = kmalloc(alloclen, GFP_NOIO);
if (buffer == NULL)
return USB_STOR_TRANSPORT_ERROR;
do {
// loop, never allocate or transfer more than 64k at once
// (min(128k, 255*info->ssize) is the real limit)
len = min(totallen, alloclen);
thistime = (len / info->ssize) & 0xff;
// Get the data from the transfer buffer
usb_stor_access_xfer_buf(buffer, len, us->srb,
&sg, &sg_offset, FROM_XFER_BUF);
command[0] = 0;
command[1] = thistime;
command[2] = sector & 0xFF;
command[3] = (sector >> 8) & 0xFF;
command[4] = (sector >> 16) & 0xFF;
command[5] = 0xE0 | ((sector >> 24) & 0x0F);
command[6] = 0x30;
// send the setup + command
result = usb_stor_ctrl_transfer(us, us->send_ctrl_pipe,
0, 0x20, 0, 1, command, 7);
if (result != USB_STOR_XFER_GOOD)
goto leave;
// send the data
result = jumpshot_bulk_write(us, buffer, len);
if (result != USB_STOR_XFER_GOOD)
goto leave;
// read the result. apparently the bulk write can complete
// before the jumpshot drive is finished writing. so we loop
// here until we get a good return code
waitcount = 0;
do {
result = jumpshot_get_status(us);
if (result != USB_STOR_TRANSPORT_GOOD) {
// I have not experimented to find the smallest value.
//
msleep(50);
}
} while ((result != USB_STOR_TRANSPORT_GOOD) && (waitcount < 10));
if (result != USB_STOR_TRANSPORT_GOOD)
US_DEBUGP("jumpshot_write_data: Gah! Waitcount = 10. Bad write!?\n");
sector += thistime;
totallen -= len;
} while (totallen > 0);
kfree(buffer);
return result;
leave:
kfree(buffer);
return USB_STOR_TRANSPORT_ERROR;
}
static int jumpshot_id_device(struct us_data *us,
struct jumpshot_info *info)
{
unsigned char *command = us->iobuf;
unsigned char *reply;
int rc;
if (!us || !info)
return USB_STOR_TRANSPORT_ERROR;
command[0] = 0xE0;
command[1] = 0xEC;
reply = kmalloc(512, GFP_NOIO);
if (!reply)
return USB_STOR_TRANSPORT_ERROR;
// send the setup
rc = usb_stor_ctrl_transfer(us, us->send_ctrl_pipe,
0, 0x20, 0, 6, command, 2);
if (rc != USB_STOR_XFER_GOOD) {
US_DEBUGP("jumpshot_id_device: Gah! "
"send_control for read_capacity failed\n");
rc = USB_STOR_TRANSPORT_ERROR;
goto leave;
}
// read the reply
rc = jumpshot_bulk_read(us, reply, 512);
if (rc != USB_STOR_XFER_GOOD) {
rc = USB_STOR_TRANSPORT_ERROR;
goto leave;
}
info->sectors = ((u32)(reply[117]) << 24) |
((u32)(reply[116]) << 16) |
((u32)(reply[115]) << 8) |
((u32)(reply[114]) );
rc = USB_STOR_TRANSPORT_GOOD;
leave:
kfree(reply);
return rc;
}
static int jumpshot_handle_mode_sense(struct us_data *us,
struct scsi_cmnd * srb,
int sense_6)
{
static unsigned char rw_err_page[12] = {
0x1, 0xA, 0x21, 1, 0, 0, 0, 0, 1, 0, 0, 0
};
static unsigned char cache_page[12] = {
0x8, 0xA, 0x1, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
static unsigned char rbac_page[12] = {
0x1B, 0xA, 0, 0x81, 0, 0, 0, 0, 0, 0, 0, 0
};
static unsigned char timer_page[8] = {
0x1C, 0x6, 0, 0, 0, 0
};
unsigned char pc, page_code;
unsigned int i = 0;
struct jumpshot_info *info = (struct jumpshot_info *) (us->extra);
unsigned char *ptr = us->iobuf;
pc = srb->cmnd[2] >> 6;
page_code = srb->cmnd[2] & 0x3F;
switch (pc) {
case 0x0:
US_DEBUGP("jumpshot_handle_mode_sense: Current values\n");
break;
case 0x1:
US_DEBUGP("jumpshot_handle_mode_sense: Changeable values\n");
break;
case 0x2:
US_DEBUGP("jumpshot_handle_mode_sense: Default values\n");
break;
case 0x3:
US_DEBUGP("jumpshot_handle_mode_sense: Saves values\n");
break;
}
memset(ptr, 0, 8);
if (sense_6) {
ptr[2] = 0x00; // WP enable: 0x80
i = 4;
} else {
ptr[3] = 0x00; // WP enable: 0x80
i = 8;
}
switch (page_code) {
case 0x0:
// vendor-specific mode
info->sense_key = 0x05;
info->sense_asc = 0x24;
info->sense_ascq = 0x00;
return USB_STOR_TRANSPORT_FAILED;
case 0x1:
memcpy(ptr + i, rw_err_page, sizeof(rw_err_page));
i += sizeof(rw_err_page);
break;
case 0x8:
memcpy(ptr + i, cache_page, sizeof(cache_page));
i += sizeof(cache_page);
break;
case 0x1B:
memcpy(ptr + i, rbac_page, sizeof(rbac_page));
i += sizeof(rbac_page);
break;
case 0x1C:
memcpy(ptr + i, timer_page, sizeof(timer_page));
i += sizeof(timer_page);
break;
case 0x3F:
memcpy(ptr + i, timer_page, sizeof(timer_page));
i += sizeof(timer_page);
memcpy(ptr + i, rbac_page, sizeof(rbac_page));
i += sizeof(rbac_page);
memcpy(ptr + i, cache_page, sizeof(cache_page));
i += sizeof(cache_page);
memcpy(ptr + i, rw_err_page, sizeof(rw_err_page));
i += sizeof(rw_err_page);
break;
}
if (sense_6)
ptr[0] = i - 1;
else
((__be16 *) ptr)[0] = cpu_to_be16(i - 2);
usb_stor_set_xfer_buf(ptr, i, srb);
return USB_STOR_TRANSPORT_GOOD;
}
static void jumpshot_info_destructor(void *extra)
{
// this routine is a placeholder...
// currently, we don't allocate any extra blocks so we're okay
}
// Transport for the Lexar 'Jumpshot'
//
static int jumpshot_transport(struct scsi_cmnd *srb, struct us_data *us)
{
struct jumpshot_info *info;
int rc;
unsigned long block, blocks;
unsigned char *ptr = us->iobuf;
static unsigned char inquiry_response[8] = {
0x00, 0x80, 0x00, 0x01, 0x1F, 0x00, 0x00, 0x00
};
if (!us->extra) {
us->extra = kzalloc(sizeof(struct jumpshot_info), GFP_NOIO);
if (!us->extra) {
US_DEBUGP("jumpshot_transport: Gah! Can't allocate storage for jumpshot info struct!\n");
return USB_STOR_TRANSPORT_ERROR;
}
us->extra_destructor = jumpshot_info_destructor;
}
info = (struct jumpshot_info *) (us->extra);
if (srb->cmnd[0] == INQUIRY) {
US_DEBUGP("jumpshot_transport: INQUIRY. Returning bogus response.\n");
memcpy(ptr, inquiry_response, sizeof(inquiry_response));
fill_inquiry_response(us, ptr, 36);
return USB_STOR_TRANSPORT_GOOD;
}
if (srb->cmnd[0] == READ_CAPACITY) {
info->ssize = 0x200; // hard coded 512 byte sectors as per ATA spec
rc = jumpshot_get_status(us);
if (rc != USB_STOR_TRANSPORT_GOOD)
return rc;
rc = jumpshot_id_device(us, info);
if (rc != USB_STOR_TRANSPORT_GOOD)
return rc;
US_DEBUGP("jumpshot_transport: READ_CAPACITY: %ld sectors, %ld bytes per sector\n",
info->sectors, info->ssize);
// build the reply
//
((__be32 *) ptr)[0] = cpu_to_be32(info->sectors - 1);
((__be32 *) ptr)[1] = cpu_to_be32(info->ssize);
usb_stor_set_xfer_buf(ptr, 8, srb);
return USB_STOR_TRANSPORT_GOOD;
}
if (srb->cmnd[0] == MODE_SELECT_10) {
US_DEBUGP("jumpshot_transport: Gah! MODE_SELECT_10.\n");
return USB_STOR_TRANSPORT_ERROR;
}
if (srb->cmnd[0] == READ_10) {
block = ((u32)(srb->cmnd[2]) << 24) | ((u32)(srb->cmnd[3]) << 16) |
((u32)(srb->cmnd[4]) << 8) | ((u32)(srb->cmnd[5]));
blocks = ((u32)(srb->cmnd[7]) << 8) | ((u32)(srb->cmnd[8]));
US_DEBUGP("jumpshot_transport: READ_10: read block 0x%04lx count %ld\n", block, blocks);
return jumpshot_read_data(us, info, block, blocks);
}
if (srb->cmnd[0] == READ_12) {
// I don't think we'll ever see a READ_12 but support it anyway...
//
block = ((u32)(srb->cmnd[2]) << 24) | ((u32)(srb->cmnd[3]) << 16) |
((u32)(srb->cmnd[4]) << 8) | ((u32)(srb->cmnd[5]));
blocks = ((u32)(srb->cmnd[6]) << 24) | ((u32)(srb->cmnd[7]) << 16) |
((u32)(srb->cmnd[8]) << 8) | ((u32)(srb->cmnd[9]));
US_DEBUGP("jumpshot_transport: READ_12: read block 0x%04lx count %ld\n", block, blocks);
return jumpshot_read_data(us, info, block, blocks);
}
if (srb->cmnd[0] == WRITE_10) {
block = ((u32)(srb->cmnd[2]) << 24) | ((u32)(srb->cmnd[3]) << 16) |
((u32)(srb->cmnd[4]) << 8) | ((u32)(srb->cmnd[5]));
blocks = ((u32)(srb->cmnd[7]) << 8) | ((u32)(srb->cmnd[8]));
US_DEBUGP("jumpshot_transport: WRITE_10: write block 0x%04lx count %ld\n", block, blocks);
return jumpshot_write_data(us, info, block, blocks);
}
if (srb->cmnd[0] == WRITE_12) {
// I don't think we'll ever see a WRITE_12 but support it anyway...
//
block = ((u32)(srb->cmnd[2]) << 24) | ((u32)(srb->cmnd[3]) << 16) |
((u32)(srb->cmnd[4]) << 8) | ((u32)(srb->cmnd[5]));
blocks = ((u32)(srb->cmnd[6]) << 24) | ((u32)(srb->cmnd[7]) << 16) |
((u32)(srb->cmnd[8]) << 8) | ((u32)(srb->cmnd[9]));
US_DEBUGP("jumpshot_transport: WRITE_12: write block 0x%04lx count %ld\n", block, blocks);
return jumpshot_write_data(us, info, block, blocks);
}
if (srb->cmnd[0] == TEST_UNIT_READY) {
US_DEBUGP("jumpshot_transport: TEST_UNIT_READY.\n");
return jumpshot_get_status(us);
}
if (srb->cmnd[0] == REQUEST_SENSE) {
US_DEBUGP("jumpshot_transport: REQUEST_SENSE.\n");
memset(ptr, 0, 18);
ptr[0] = 0xF0;
ptr[2] = info->sense_key;
ptr[7] = 11;
ptr[12] = info->sense_asc;
ptr[13] = info->sense_ascq;
usb_stor_set_xfer_buf(ptr, 18, srb);
return USB_STOR_TRANSPORT_GOOD;
}
if (srb->cmnd[0] == MODE_SENSE) {
US_DEBUGP("jumpshot_transport: MODE_SENSE_6 detected\n");
return jumpshot_handle_mode_sense(us, srb, 1);
}
if (srb->cmnd[0] == MODE_SENSE_10) {
US_DEBUGP("jumpshot_transport: MODE_SENSE_10 detected\n");
return jumpshot_handle_mode_sense(us, srb, 0);
}
if (srb->cmnd[0] == ALLOW_MEDIUM_REMOVAL) {
// sure. whatever. not like we can stop the user from popping
// the media out of the device (no locking doors, etc)
//
return USB_STOR_TRANSPORT_GOOD;
}
if (srb->cmnd[0] == START_STOP) {
/* this is used by sd.c'check_scsidisk_media_change to detect
media change */
US_DEBUGP("jumpshot_transport: START_STOP.\n");
/* the first jumpshot_id_device after a media change returns
an error (determined experimentally) */
rc = jumpshot_id_device(us, info);
if (rc == USB_STOR_TRANSPORT_GOOD) {
info->sense_key = NO_SENSE;
srb->result = SUCCESS;
} else {
info->sense_key = UNIT_ATTENTION;
srb->result = SAM_STAT_CHECK_CONDITION;
}
return rc;
}
US_DEBUGP("jumpshot_transport: Gah! Unknown command: %d (0x%x)\n",
srb->cmnd[0], srb->cmnd[0]);
info->sense_key = 0x05;
info->sense_asc = 0x20;
info->sense_ascq = 0x00;
return USB_STOR_TRANSPORT_FAILED;
}
static int jumpshot_probe(struct usb_interface *intf,
const struct usb_device_id *id)
{
struct us_data *us;
int result;
result = usb_stor_probe1(&us, intf, id,
(id - jumpshot_usb_ids) + jumpshot_unusual_dev_list);
if (result)
return result;
us->transport_name = "Lexar Jumpshot Control/Bulk";
us->transport = jumpshot_transport;
us->transport_reset = usb_stor_Bulk_reset;
us->max_lun = 1;
result = usb_stor_probe2(us);
return result;
}
static struct usb_driver jumpshot_driver = {
.name = "ums-jumpshot",
.probe = jumpshot_probe,
.disconnect = usb_stor_disconnect,
.suspend = usb_stor_suspend,
.resume = usb_stor_resume,
.reset_resume = usb_stor_reset_resume,
.pre_reset = usb_stor_pre_reset,
.post_reset = usb_stor_post_reset,
.id_table = jumpshot_usb_ids,
.soft_unbind = 1,
};
static int __init jumpshot_init(void)
{
return usb_register(&jumpshot_driver);
}
static void __exit jumpshot_exit(void)
{
usb_deregister(&jumpshot_driver);
}
module_init(jumpshot_init);
module_exit(jumpshot_exit);
| gpl-2.0 |
rperier/linux | net/ax25/ax25_dev.c | 4634 | // SPDX-License-Identifier: GPL-2.0-or-later
/*
*
* Copyright (C) Jonathan Naylor G4KLX ([email protected])
*/
#include <linux/errno.h>
#include <linux/types.h>
#include <linux/socket.h>
#include <linux/slab.h>
#include <linux/in.h>
#include <linux/kernel.h>
#include <linux/timer.h>
#include <linux/string.h>
#include <linux/sockios.h>
#include <linux/net.h>
#include <linux/spinlock.h>
#include <net/ax25.h>
#include <linux/inet.h>
#include <linux/netdevice.h>
#include <linux/if_arp.h>
#include <linux/skbuff.h>
#include <net/sock.h>
#include <linux/uaccess.h>
#include <linux/fcntl.h>
#include <linux/mm.h>
#include <linux/interrupt.h>
#include <linux/init.h>
ax25_dev *ax25_dev_list;
DEFINE_SPINLOCK(ax25_dev_lock);
ax25_dev *ax25_addr_ax25dev(ax25_address *addr)
{
ax25_dev *ax25_dev, *res = NULL;
spin_lock_bh(&ax25_dev_lock);
for (ax25_dev = ax25_dev_list; ax25_dev != NULL; ax25_dev = ax25_dev->next)
if (ax25cmp(addr, (const ax25_address *)ax25_dev->dev->dev_addr) == 0) {
res = ax25_dev;
}
spin_unlock_bh(&ax25_dev_lock);
return res;
}
/*
* This is called when an interface is brought up. These are
* reasonable defaults.
*/
void ax25_dev_device_up(struct net_device *dev)
{
ax25_dev *ax25_dev;
if ((ax25_dev = kzalloc(sizeof(*ax25_dev), GFP_ATOMIC)) == NULL) {
printk(KERN_ERR "AX.25: ax25_dev_device_up - out of memory\n");
return;
}
dev->ax25_ptr = ax25_dev;
ax25_dev->dev = dev;
dev_hold(dev);
ax25_dev->forward = NULL;
ax25_dev->values[AX25_VALUES_IPDEFMODE] = AX25_DEF_IPDEFMODE;
ax25_dev->values[AX25_VALUES_AXDEFMODE] = AX25_DEF_AXDEFMODE;
ax25_dev->values[AX25_VALUES_BACKOFF] = AX25_DEF_BACKOFF;
ax25_dev->values[AX25_VALUES_CONMODE] = AX25_DEF_CONMODE;
ax25_dev->values[AX25_VALUES_WINDOW] = AX25_DEF_WINDOW;
ax25_dev->values[AX25_VALUES_EWINDOW] = AX25_DEF_EWINDOW;
ax25_dev->values[AX25_VALUES_T1] = AX25_DEF_T1;
ax25_dev->values[AX25_VALUES_T2] = AX25_DEF_T2;
ax25_dev->values[AX25_VALUES_T3] = AX25_DEF_T3;
ax25_dev->values[AX25_VALUES_IDLE] = AX25_DEF_IDLE;
ax25_dev->values[AX25_VALUES_N2] = AX25_DEF_N2;
ax25_dev->values[AX25_VALUES_PACLEN] = AX25_DEF_PACLEN;
ax25_dev->values[AX25_VALUES_PROTOCOL] = AX25_DEF_PROTOCOL;
ax25_dev->values[AX25_VALUES_DS_TIMEOUT]= AX25_DEF_DS_TIMEOUT;
#if defined(CONFIG_AX25_DAMA_SLAVE) || defined(CONFIG_AX25_DAMA_MASTER)
ax25_ds_setup_timer(ax25_dev);
#endif
spin_lock_bh(&ax25_dev_lock);
ax25_dev->next = ax25_dev_list;
ax25_dev_list = ax25_dev;
spin_unlock_bh(&ax25_dev_lock);
ax25_register_dev_sysctl(ax25_dev);
}
void ax25_dev_device_down(struct net_device *dev)
{
ax25_dev *s, *ax25_dev;
if ((ax25_dev = ax25_dev_ax25dev(dev)) == NULL)
return;
ax25_unregister_dev_sysctl(ax25_dev);
spin_lock_bh(&ax25_dev_lock);
#ifdef CONFIG_AX25_DAMA_SLAVE
ax25_ds_del_timer(ax25_dev);
#endif
/*
* Remove any packet forwarding that points to this device.
*/
for (s = ax25_dev_list; s != NULL; s = s->next)
if (s->forward == dev)
s->forward = NULL;
if ((s = ax25_dev_list) == ax25_dev) {
ax25_dev_list = s->next;
spin_unlock_bh(&ax25_dev_lock);
dev->ax25_ptr = NULL;
dev_put(dev);
kfree(ax25_dev);
return;
}
while (s != NULL && s->next != NULL) {
if (s->next == ax25_dev) {
s->next = ax25_dev->next;
spin_unlock_bh(&ax25_dev_lock);
dev->ax25_ptr = NULL;
dev_put(dev);
kfree(ax25_dev);
return;
}
s = s->next;
}
spin_unlock_bh(&ax25_dev_lock);
dev->ax25_ptr = NULL;
}
int ax25_fwd_ioctl(unsigned int cmd, struct ax25_fwd_struct *fwd)
{
ax25_dev *ax25_dev, *fwd_dev;
if ((ax25_dev = ax25_addr_ax25dev(&fwd->port_from)) == NULL)
return -EINVAL;
switch (cmd) {
case SIOCAX25ADDFWD:
if ((fwd_dev = ax25_addr_ax25dev(&fwd->port_to)) == NULL)
return -EINVAL;
if (ax25_dev->forward != NULL)
return -EINVAL;
ax25_dev->forward = fwd_dev->dev;
break;
case SIOCAX25DELFWD:
if (ax25_dev->forward == NULL)
return -EINVAL;
ax25_dev->forward = NULL;
break;
default:
return -EINVAL;
}
return 0;
}
struct net_device *ax25_fwd_dev(struct net_device *dev)
{
ax25_dev *ax25_dev;
if ((ax25_dev = ax25_dev_ax25dev(dev)) == NULL)
return dev;
if (ax25_dev->forward == NULL)
return dev;
return ax25_dev->forward;
}
/*
* Free all memory associated with device structures.
*/
void __exit ax25_dev_free(void)
{
ax25_dev *s, *ax25_dev;
spin_lock_bh(&ax25_dev_lock);
ax25_dev = ax25_dev_list;
while (ax25_dev != NULL) {
s = ax25_dev;
dev_put(ax25_dev->dev);
ax25_dev = ax25_dev->next;
kfree(s);
}
ax25_dev_list = NULL;
spin_unlock_bh(&ax25_dev_lock);
}
| gpl-2.0 |
ivan-fedorov/intellij-community | plugins/svn4idea/src/org/jetbrains/idea/svn/svnkit/lowLevel/SVNStoppableInputStream.java | 6260 | /*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.idea.svn.svnkit.lowLevel;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.util.text.StringUtil;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
/**
* Created with IntelliJ IDEA.
* User: Irina.Chernushina
* Date: 7/30/12
* Time: 6:23 PM
*
* SVNLogInputStream is not used, since it does not check available()
*
*/
public class SVNStoppableInputStream extends InputStream {
private final static Logger LOG = Logger.getInstance(SVNStoppableInputStream.class);
private final static String ourCheckAvalilable = "svn.check.available";
private final InputStream myOriginalIs;
private final InputStream myIn;
private boolean myAvailableChecked;
private final boolean myCheckAvailable;
public SVNStoppableInputStream(InputStream original, InputStream in) {
final String property = System.getProperty(ourCheckAvalilable);
myCheckAvailable = ! StringUtil.isEmptyOrSpaces(property) && Boolean.parseBoolean(property);
//myCheckAvailable = Boolean.parseBoolean(property);
myOriginalIs = myCheckAvailable ? digOriginal(original) : original;
myIn = in;
myAvailableChecked = false;
}
private InputStream digOriginal(InputStream original) {
// because of many delegates in the chain possible
InputStream current = original;
try {
while (true) {
final String name = current.getClass().getName();
if ("org.tmatesoft.svn.core.internal.io.dav.http.SpoolFile.SpoolInputStream".equals(name)) {
current = byName(current, "myCurrentInput");
} else if ("org.tmatesoft.svn.core.internal.util.ChunkedInputStream".equals(name)) {
current = byName(current, "myInputStream");
} else if ("org.tmatesoft.svn.core.internal.util.FixedSizeInputStream".equals(name)) {
current = byName(current, "mySource");
} else if (current instanceof BufferedInputStream) {
return createReadingProxy(current);
} else {
// maybe ok class, maybe some unknown proxy
Method[] methods = current.getClass().getDeclaredMethods();
for (Method method : methods) {
if ("available".equals(method.getName())) {
return current;
}
}
return createReadingProxy(current);
}
}
}
catch (NoSuchFieldException e) {
LOG.info(e);
return createReadingProxy(current);
}
catch (IllegalAccessException e) {
LOG.info(e);
return createReadingProxy(current);
}
}
private InputStream createReadingProxy(final InputStream current) {
return new InputStream() {
@Override
public int read() throws IOException {
return current.read();
}
public int read(byte[] b) throws IOException {
return current.read(b);
}
public int read(byte[] b, int off, int len) throws IOException {
return current.read(b, off, len);
}
public long skip(long n) throws IOException {
return current.skip(n);
}
public void close() throws IOException {
current.close();
}
public void mark(int readlimit) {
current.mark(readlimit);
}
public void reset() throws IOException {
current.reset();
}
public boolean markSupported() {
return current.markSupported();
}
@Override
public int available() throws IOException {
return 1;
}
};
}
private InputStream byName(InputStream current, final String name) throws NoSuchFieldException, IllegalAccessException {
final Field input = current.getClass().getDeclaredField(name);
input.setAccessible(true);
current = (InputStream) input.get(current);
return current;
}
@Override
public int read() throws IOException {
waitForAvailable();
return myIn.read();
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
waitForAvailable();
return myIn.read(b, off, len);
}
@Override
public long skip(long n) throws IOException {
if (n <= 0) return 0;
check();
if (available() <= 0) return 0;
return myIn.skip(n);
}
@Override
public int available() throws IOException {
check();
if (! myAvailableChecked) {
int available = myOriginalIs.available();
if (available > 0) {
myAvailableChecked = true;
}
return available;
}
return 1;
}
@Override
public void close() throws IOException {
check();
myIn.close();
}
@Override
public synchronized void mark(int readlimit) {
myIn.mark(readlimit);
}
@Override
public synchronized void reset() throws IOException {
check();
myIn.reset();
}
@Override
public boolean markSupported() {
return myIn.markSupported();
}
private void check() throws IOException {
ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();
if (indicator != null && indicator.isCanceled()) {
throw new IOException("Read request to canceled by user");
}
}
private void waitForAvailable() throws IOException {
if (! myCheckAvailable) return;
final Object lock = new Object();
synchronized (lock) {
while (available() <= 0) {
check();
try {
lock.wait(100);
}
catch (InterruptedException e) {
//
}
}
}
}
}
| apache-2.0 |
jmandawg/camel | components/camel-kura/src/main/java/org/apache/camel/component/kura/KuraRouter.java | 5602 | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.component.kura;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Map;
import org.apache.camel.CamelContext;
import org.apache.camel.ConsumerTemplate;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.core.osgi.OsgiDefaultCamelContext;
import org.apache.camel.model.RoutesDefinition;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.service.cm.Configuration;
import org.osgi.service.cm.ConfigurationAdmin;
import org.osgi.service.component.ComponentContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public abstract class KuraRouter extends RouteBuilder implements BundleActivator {
// Member collaborators
protected final Logger log = LoggerFactory.getLogger(getClass());
protected BundleContext bundleContext;
protected CamelContext camelContext;
protected ProducerTemplate producerTemplate;
protected ConsumerTemplate consumerTemplate;
// Lifecycle
@Override
public void start(BundleContext bundleContext) throws Exception {
try {
this.bundleContext = bundleContext;
log.debug("Initializing bundle {}.", bundleContext.getBundle().getBundleId());
camelContext = createCamelContext();
camelContext.addRoutes(this);
ConfigurationAdmin configurationAdmin = requiredService(ConfigurationAdmin.class);
Configuration camelKuraConfig = configurationAdmin.getConfiguration(camelXmlRoutesPid());
if (camelKuraConfig != null && camelKuraConfig.getProperties() != null) {
Object routePropertyValue = camelKuraConfig.getProperties().get(camelXmlRoutesProperty());
if (routePropertyValue != null) {
InputStream routesXml = new ByteArrayInputStream(routePropertyValue.toString().getBytes());
RoutesDefinition loadedRoutes = camelContext.loadRoutesDefinition(routesXml);
camelContext.addRouteDefinitions(loadedRoutes.getRoutes());
}
}
beforeStart(camelContext);
log.debug("About to start Camel Kura router: {}", getClass().getName());
camelContext.start();
producerTemplate = camelContext.createProducerTemplate();
consumerTemplate = camelContext.createConsumerTemplate();
log.debug("Bundle {} started.", bundleContext.getBundle().getBundleId());
} catch (Throwable e) {
String errorMessage = "Problem when starting Kura module " + getClass().getName() + ":";
log.warn(errorMessage, e);
// Print error to the Kura console.
System.err.println(errorMessage);
e.printStackTrace();
throw e;
}
}
@Override
public void stop(BundleContext bundleContext) throws Exception {
log.debug("Stopping bundle {}.", bundleContext.getBundle().getBundleId());
camelContext.stop();
log.debug("Bundle {} stopped.", bundleContext.getBundle().getBundleId());
}
protected void activate(ComponentContext componentContext, Map<String, Object> properties) throws Exception {
start(componentContext.getBundleContext());
}
protected void deactivate(ComponentContext componentContext) throws Exception {
stop(componentContext.getBundleContext());
}
// Callbacks
@Override
public void configure() throws Exception {
log.debug("No programmatic routes configuration found.");
}
protected CamelContext createCamelContext() {
return new OsgiDefaultCamelContext(bundleContext);
}
protected void beforeStart(CamelContext camelContext) {
log.debug("Empty KuraRouter CamelContext before start configuration - skipping.");
}
// API Helpers
protected <T> T service(Class<T> serviceType) {
ServiceReference reference = bundleContext.getServiceReference(serviceType);
return reference == null ? null : (T) bundleContext.getService(reference);
}
protected <T> T requiredService(Class<T> serviceType) {
ServiceReference reference = bundleContext.getServiceReference(serviceType);
if (reference == null) {
throw new IllegalStateException("Cannot find service: " + serviceType.getName());
}
return (T) bundleContext.getService(reference);
}
// Private helpers
protected String camelXmlRoutesPid() {
return "kura.camel";
}
protected String camelXmlRoutesProperty() {
return "kura.camel." + bundleContext.getBundle().getSymbolicName() + ".route";
}
} | apache-2.0 |
caot/intellij-community | platform/bootstrap/src/com/intellij/ide/WindowsCommandLineProcessor.java | 2035 | /*
* Copyright 2000-2013 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.ide;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* This class is initialized in two classloaders: the bootstrap classloader and the main IDEA classloader. The bootstrap instance
* has ourMirrorClass initialized by the Bootstrap class; it calls the main instance of itself via reflection.
*
* @author yole
*/
@SuppressWarnings("UnusedDeclaration")
public class WindowsCommandLineProcessor {
// The WindowsCommandLineProcessor class which is loaded in the main IDEA (non-bootstrap) classloader.
public static Class ourMirrorClass = null;
public static WindowsCommandLineListener LISTENER = null;
/**
* NOTE: This method is called through JNI by the Windows launcher. Please do not delete or rename it.
*/
public static void processWindowsLauncherCommandLine(final String currentDirectory, final String commandLine) {
if (ourMirrorClass != null) {
try {
Method method = ourMirrorClass.getMethod("processWindowsLauncherCommandLine", String.class, String.class);
method.invoke(null, currentDirectory, commandLine);
}
catch (NoSuchMethodException e) {
}
catch (InvocationTargetException e) {
}
catch (IllegalAccessException e) {
}
}
else {
if (LISTENER != null) {
LISTENER.processWindowsLauncherCommandLine(currentDirectory, commandLine);
}
}
}
}
| apache-2.0 |
yanivefraim/angular2-webpack-starter | test/app/app.e2e.js | 916 | /// <reference path="../../typings/_custom.d.ts" />
/*
* TODO: ES5 for now until I make a webpack plugin for protractor
*/
describe('App', function() {
var subject;
var result;
beforeEach(function() {
browser.get('/');
});
afterEach(function() {
expect(subject).toEqual(result);
});
it('should have a title', function() {
subject = browser.getTitle();
result = 'Angular2 Webpack Starter by @gdi2990 from @AngularClass';
});
it('should have <header>', function() {
subject = element(by.deepCss('app /deep/ header')).isPresent();
result = true;
});
it('should have <main>', function() {
subject = element(by.deepCss('app /deep/ main')).isPresent();
result = true;
});
it('should have <footer>', function() {
subject = element(by.deepCss('app /deep/ footer')).getText();
result = 'WebPack Angular 2 Starter by @AngularClass';
});
});
| mit |
BPI-SINOVOIP/BPI-Mainline-kernel | linux-4.19/include/net/if_inet6.h | 6267 | /*
* inet6 interface/address list definitions
* Linux INET6 implementation
*
* Authors:
* Pedro Roque <[email protected]>
*
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*/
#ifndef _NET_IF_INET6_H
#define _NET_IF_INET6_H
#include <net/snmp.h>
#include <linux/ipv6.h>
#include <linux/refcount.h>
/* inet6_dev.if_flags */
#define IF_RA_OTHERCONF 0x80
#define IF_RA_MANAGED 0x40
#define IF_RA_RCVD 0x20
#define IF_RS_SENT 0x10
#define IF_READY 0x80000000
/* prefix flags */
#define IF_PREFIX_ONLINK 0x01
#define IF_PREFIX_AUTOCONF 0x02
enum {
INET6_IFADDR_STATE_PREDAD,
INET6_IFADDR_STATE_DAD,
INET6_IFADDR_STATE_POSTDAD,
INET6_IFADDR_STATE_ERRDAD,
INET6_IFADDR_STATE_DEAD,
};
struct inet6_ifaddr {
struct in6_addr addr;
__u32 prefix_len;
__u32 rt_priority;
/* In seconds, relative to tstamp. Expiry is at tstamp + HZ * lft. */
__u32 valid_lft;
__u32 prefered_lft;
refcount_t refcnt;
spinlock_t lock;
int state;
__u32 flags;
__u8 dad_probes;
__u8 stable_privacy_retry;
__u16 scope;
__u64 dad_nonce;
unsigned long cstamp; /* created timestamp */
unsigned long tstamp; /* updated timestamp */
struct delayed_work dad_work;
struct inet6_dev *idev;
struct fib6_info *rt;
struct hlist_node addr_lst;
struct list_head if_list;
struct list_head tmp_list;
struct inet6_ifaddr *ifpub;
int regen_count;
bool tokenized;
struct rcu_head rcu;
struct in6_addr peer_addr;
};
struct ip6_sf_socklist {
unsigned int sl_max;
unsigned int sl_count;
struct in6_addr sl_addr[0];
};
#define IP6_SFLSIZE(count) (sizeof(struct ip6_sf_socklist) + \
(count) * sizeof(struct in6_addr))
#define IP6_SFBLOCK 10 /* allocate this many at once */
struct ipv6_mc_socklist {
struct in6_addr addr;
int ifindex;
struct ipv6_mc_socklist __rcu *next;
rwlock_t sflock;
unsigned int sfmode; /* MCAST_{INCLUDE,EXCLUDE} */
struct ip6_sf_socklist *sflist;
struct rcu_head rcu;
};
struct ip6_sf_list {
struct ip6_sf_list *sf_next;
struct in6_addr sf_addr;
unsigned long sf_count[2]; /* include/exclude counts */
unsigned char sf_gsresp; /* include in g & s response? */
unsigned char sf_oldin; /* change state */
unsigned char sf_crcount; /* retrans. left to send */
};
#define MAF_TIMER_RUNNING 0x01
#define MAF_LAST_REPORTER 0x02
#define MAF_LOADED 0x04
#define MAF_NOREPORT 0x08
#define MAF_GSQUERY 0x10
struct ifmcaddr6 {
struct in6_addr mca_addr;
struct inet6_dev *idev;
struct ifmcaddr6 *next;
struct ip6_sf_list *mca_sources;
struct ip6_sf_list *mca_tomb;
unsigned int mca_sfmode;
unsigned char mca_crcount;
unsigned long mca_sfcount[2];
struct timer_list mca_timer;
unsigned int mca_flags;
int mca_users;
refcount_t mca_refcnt;
spinlock_t mca_lock;
unsigned long mca_cstamp;
unsigned long mca_tstamp;
};
/* Anycast stuff */
struct ipv6_ac_socklist {
struct in6_addr acl_addr;
int acl_ifindex;
struct ipv6_ac_socklist *acl_next;
};
struct ifacaddr6 {
struct in6_addr aca_addr;
struct fib6_info *aca_rt;
struct ifacaddr6 *aca_next;
int aca_users;
refcount_t aca_refcnt;
unsigned long aca_cstamp;
unsigned long aca_tstamp;
};
#define IFA_HOST IPV6_ADDR_LOOPBACK
#define IFA_LINK IPV6_ADDR_LINKLOCAL
#define IFA_SITE IPV6_ADDR_SITELOCAL
struct ipv6_devstat {
struct proc_dir_entry *proc_dir_entry;
DEFINE_SNMP_STAT(struct ipstats_mib, ipv6);
DEFINE_SNMP_STAT_ATOMIC(struct icmpv6_mib_device, icmpv6dev);
DEFINE_SNMP_STAT_ATOMIC(struct icmpv6msg_mib_device, icmpv6msgdev);
};
struct inet6_dev {
struct net_device *dev;
struct list_head addr_list;
struct ifmcaddr6 *mc_list;
struct ifmcaddr6 *mc_tomb;
spinlock_t mc_lock;
unsigned char mc_qrv; /* Query Robustness Variable */
unsigned char mc_gq_running;
unsigned char mc_ifc_count;
unsigned char mc_dad_count;
unsigned long mc_v1_seen; /* Max time we stay in MLDv1 mode */
unsigned long mc_qi; /* Query Interval */
unsigned long mc_qri; /* Query Response Interval */
unsigned long mc_maxdelay;
struct timer_list mc_gq_timer; /* general query timer */
struct timer_list mc_ifc_timer; /* interface change timer */
struct timer_list mc_dad_timer; /* dad complete mc timer */
struct ifacaddr6 *ac_list;
rwlock_t lock;
refcount_t refcnt;
__u32 if_flags;
int dead;
u32 desync_factor;
u8 rndid[8];
struct list_head tempaddr_list;
struct in6_addr token;
struct neigh_parms *nd_parms;
struct ipv6_devconf cnf;
struct ipv6_devstat stats;
struct timer_list rs_timer;
__s32 rs_interval; /* in jiffies */
__u8 rs_probes;
unsigned long tstamp; /* ipv6InterfaceTable update timestamp */
struct rcu_head rcu;
};
static inline void ipv6_eth_mc_map(const struct in6_addr *addr, char *buf)
{
/*
* +-------+-------+-------+-------+-------+-------+
* | 33 | 33 | DST13 | DST14 | DST15 | DST16 |
* +-------+-------+-------+-------+-------+-------+
*/
buf[0]= 0x33;
buf[1]= 0x33;
memcpy(buf + 2, &addr->s6_addr32[3], sizeof(__u32));
}
static inline void ipv6_arcnet_mc_map(const struct in6_addr *addr, char *buf)
{
buf[0] = 0x00;
}
static inline void ipv6_ib_mc_map(const struct in6_addr *addr,
const unsigned char *broadcast, char *buf)
{
unsigned char scope = broadcast[5] & 0xF;
buf[0] = 0; /* Reserved */
buf[1] = 0xff; /* Multicast QPN */
buf[2] = 0xff;
buf[3] = 0xff;
buf[4] = 0xff;
buf[5] = 0x10 | scope; /* scope from broadcast address */
buf[6] = 0x60; /* IPv6 signature */
buf[7] = 0x1b;
buf[8] = broadcast[8]; /* P_Key */
buf[9] = broadcast[9];
memcpy(buf + 10, addr->s6_addr + 6, 10);
}
static inline int ipv6_ipgre_mc_map(const struct in6_addr *addr,
const unsigned char *broadcast, char *buf)
{
if ((broadcast[0] | broadcast[1] | broadcast[2] | broadcast[3]) != 0) {
memcpy(buf, broadcast, 4);
} else {
/* v4mapped? */
if ((addr->s6_addr32[0] | addr->s6_addr32[1] |
(addr->s6_addr32[2] ^ htonl(0x0000ffff))) != 0)
return -EINVAL;
memcpy(buf, &addr->s6_addr32[3], 4);
}
return 0;
}
#endif
| gpl-2.0 |
sai9615/MY-kernel-for-grand-I9082 | dragon/arch/arm/plat-kona/include/mach/io.h | 2846 | /************************************************************************************************/
/* */
/* Copyright 2010 Broadcom Corporation */
/* */
/* Unless you and Broadcom execute a separate written software license agreement governing */
/* use of this software, this software is licensed to you under the terms of the GNU */
/* General Public License version 2 (the GPL), available at */
/* */
/* http://www.broadcom.com/licenses/GPLv2.php */
/* */
/* with the following added to such license: */
/* */
/* As a special exception, the copyright holders of this software give you permission to */
/* link this software with independent modules, and to copy and distribute the resulting */
/* executable under terms of your choice, provided that you also meet, for each linked */
/* independent module, the terms and conditions of the license of that module. */
/* An independent module is a module which is not derived from this software. The special */
/* exception does not apply to any modifications of the software. */
/* */
/* Notwithstanding the above, under no circumstances may you combine this software in any */
/* way with any other Broadcom software provided under a license other than the GPL, */
/* without Broadcom's express prior written consent. */
/* */
/************************************************************************************************/
#ifndef __PLAT_KONA_IO_H
#define __PLAT_KONA_IO_H
#define IO_SPACE_LIMIT (0xffffffff)
#define __io(a) __typesafe_io(a)
#define __mem_pci(a) (a)
#ifdef __ASSEMBLER__
#define IOMEM(x) (x)
#else
#define IOMEM(x) ((void __force __iomem *)(x))
#endif
#define VC_DIRECT_ACCESS_BASE 0xC0000000UL
#define ARM_VC_PHYS_ADDR_BASE 0x40000000UL
#define __VC_BUS_TO_ARM_PHYS_ADDR(x) ((x) - (VC_DIRECT_ACCESS_BASE) + (ARM_VC_PHYS_ADDR_BASE))
#endif /*__PLAT_KONA_IO_H */
| gpl-2.0 |
EAVR/EV3.14 | ev3sources/extra/linux-03.20.00.13/drivers/staging/comedi/drivers/cb_pcidda.c | 24587 | /*
comedi/drivers/cb_pcidda.c
This intends to be a driver for the ComputerBoards / MeasurementComputing
PCI-DDA series.
Copyright (C) 2001 Ivan Martinez <[email protected]>
Copyright (C) 2001 Frank Mori Hess <[email protected]>
COMEDI - Linux Control and Measurement Device Interface
Copyright (C) 1997-8 David A. Schleef <[email protected]>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/*
Driver: cb_pcidda
Description: MeasurementComputing PCI-DDA series
Author: Ivan Martinez <[email protected]>, Frank Mori Hess <[email protected]>
Status: Supports 08/16, 04/16, 02/16, 08/12, 04/12, and 02/12
Devices: [Measurement Computing] PCI-DDA08/12 (cb_pcidda), PCI-DDA04/12,
PCI-DDA02/12, PCI-DDA08/16, PCI-DDA04/16, PCI-DDA02/16
Configuration options:
[0] - PCI bus of device (optional)
[1] - PCI slot of device (optional)
If bus/slot is not specified, the first available PCI
device will be used.
Only simple analog output writing is supported.
So far it has only been tested with:
- PCI-DDA08/12
Please report success/failure with other different cards to
<[email protected]>.
*/
#include "../comedidev.h"
#include "comedi_pci.h"
#include "8255.h"
#define PCI_VENDOR_ID_CB 0x1307 /* PCI vendor number of ComputerBoards */
#define N_BOARDS 10 /* Number of boards in cb_pcidda_boards */
#define EEPROM_SIZE 128 /* number of entries in eeprom */
#define MAX_AO_CHANNELS 8 /* maximum number of ao channels for supported boards */
/* PCI-DDA base addresses */
#define DIGITALIO_BADRINDEX 2
/* DIGITAL I/O is pci_dev->resource[2] */
#define DIGITALIO_SIZE 8
/* DIGITAL I/O uses 8 I/O port addresses */
#define DAC_BADRINDEX 3
/* DAC is pci_dev->resource[3] */
/* Digital I/O registers */
#define PORT1A 0 /* PORT 1A DATA */
#define PORT1B 1 /* PORT 1B DATA */
#define PORT1C 2 /* PORT 1C DATA */
#define CONTROL1 3 /* CONTROL REGISTER 1 */
#define PORT2A 4 /* PORT 2A DATA */
#define PORT2B 5 /* PORT 2B DATA */
#define PORT2C 6 /* PORT 2C DATA */
#define CONTROL2 7 /* CONTROL REGISTER 2 */
/* DAC registers */
#define DACONTROL 0 /* D/A CONTROL REGISTER */
#define SU 0000001 /* Simultaneous update enabled */
#define NOSU 0000000 /* Simultaneous update disabled */
#define ENABLEDAC 0000002 /* Enable specified DAC */
#define DISABLEDAC 0000000 /* Disable specified DAC */
#define RANGE2V5 0000000 /* 2.5V */
#define RANGE5V 0000200 /* 5V */
#define RANGE10V 0000300 /* 10V */
#define UNIP 0000400 /* Unipolar outputs */
#define BIP 0000000 /* Bipolar outputs */
#define DACALIBRATION1 4 /* D/A CALIBRATION REGISTER 1 */
/* write bits */
#define SERIAL_IN_BIT 0x1 /* serial data input for eeprom, caldacs, reference dac */
#define CAL_CHANNEL_MASK (0x7 << 1)
#define CAL_CHANNEL_BITS(channel) (((channel) << 1) & CAL_CHANNEL_MASK)
/* read bits */
#define CAL_COUNTER_MASK 0x1f
#define CAL_COUNTER_OVERFLOW_BIT 0x20 /* calibration counter overflow status bit */
#define AO_BELOW_REF_BIT 0x40 /* analog output is less than reference dac voltage */
#define SERIAL_OUT_BIT 0x80 /* serial data out, for reading from eeprom */
#define DACALIBRATION2 6 /* D/A CALIBRATION REGISTER 2 */
#define SELECT_EEPROM_BIT 0x1 /* send serial data in to eeprom */
#define DESELECT_REF_DAC_BIT 0x2 /* don't send serial data to MAX542 reference dac */
#define DESELECT_CALDAC_BIT(n) (0x4 << (n)) /* don't send serial data to caldac n */
#define DUMMY_BIT 0x40 /* manual says to set this bit with no explanation */
#define DADATA 8 /* FIRST D/A DATA REGISTER (0) */
static const struct comedi_lrange cb_pcidda_ranges = {
6,
{
BIP_RANGE(10),
BIP_RANGE(5),
BIP_RANGE(2.5),
UNI_RANGE(10),
UNI_RANGE(5),
UNI_RANGE(2.5),
}
};
/*
* Board descriptions for two imaginary boards. Describing the
* boards in this way is optional, and completely driver-dependent.
* Some drivers use arrays such as this, other do not.
*/
struct cb_pcidda_board {
const char *name;
char status; /* Driver status: */
/*
* 0 - tested
* 1 - manual read, not tested
* 2 - manual not read
*/
unsigned short device_id;
int ao_chans;
int ao_bits;
const struct comedi_lrange *ranges;
};
static const struct cb_pcidda_board cb_pcidda_boards[] = {
{
.name = "pci-dda02/12",
.status = 1,
.device_id = 0x20,
.ao_chans = 2,
.ao_bits = 12,
.ranges = &cb_pcidda_ranges,
},
{
.name = "pci-dda04/12",
.status = 1,
.device_id = 0x21,
.ao_chans = 4,
.ao_bits = 12,
.ranges = &cb_pcidda_ranges,
},
{
.name = "pci-dda08/12",
.status = 0,
.device_id = 0x22,
.ao_chans = 8,
.ao_bits = 12,
.ranges = &cb_pcidda_ranges,
},
{
.name = "pci-dda02/16",
.status = 2,
.device_id = 0x23,
.ao_chans = 2,
.ao_bits = 16,
.ranges = &cb_pcidda_ranges,
},
{
.name = "pci-dda04/16",
.status = 2,
.device_id = 0x24,
.ao_chans = 4,
.ao_bits = 16,
.ranges = &cb_pcidda_ranges,
},
{
.name = "pci-dda08/16",
.status = 0,
.device_id = 0x25,
.ao_chans = 8,
.ao_bits = 16,
.ranges = &cb_pcidda_ranges,
},
};
static DEFINE_PCI_DEVICE_TABLE(cb_pcidda_pci_table) = {
{
PCI_VENDOR_ID_CB, 0x0020, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0}, {
PCI_VENDOR_ID_CB, 0x0021, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0}, {
PCI_VENDOR_ID_CB, 0x0022, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0}, {
PCI_VENDOR_ID_CB, 0x0023, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0}, {
PCI_VENDOR_ID_CB, 0x0024, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0}, {
PCI_VENDOR_ID_CB, 0x0025, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0}, {
0}
};
MODULE_DEVICE_TABLE(pci, cb_pcidda_pci_table);
/*
* Useful for shorthand access to the particular board structure
*/
#define thisboard ((const struct cb_pcidda_board *)dev->board_ptr)
/* this structure is for data unique to this hardware driver. If
several hardware drivers keep similar information in this structure,
feel free to suggest moving the variable to the struct comedi_device struct. */
struct cb_pcidda_private {
int data;
/* would be useful for a PCI device */
struct pci_dev *pci_dev;
unsigned long digitalio;
unsigned long dac;
/* unsigned long control_status; */
/* unsigned long adc_fifo; */
unsigned int dac_cal1_bits; /* bits last written to da calibration register 1 */
unsigned int ao_range[MAX_AO_CHANNELS]; /* current range settings for output channels */
u16 eeprom_data[EEPROM_SIZE]; /* software copy of board's eeprom */
};
/*
* most drivers define the following macro to make it easy to
* access the private structure.
*/
#define devpriv ((struct cb_pcidda_private *)dev->private)
static int cb_pcidda_attach(struct comedi_device *dev,
struct comedi_devconfig *it);
static int cb_pcidda_detach(struct comedi_device *dev);
/* static int cb_pcidda_ai_rinsn(struct comedi_device *dev,struct comedi_subdevice *s,struct comedi_insn *insn,unsigned int *data); */
static int cb_pcidda_ao_winsn(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data);
/* static int cb_pcidda_ai_cmd(struct comedi_device *dev, struct *comedi_subdevice *s);*/
/* static int cb_pcidda_ai_cmdtest(struct comedi_device *dev, struct comedi_subdevice *s, struct comedi_cmd *cmd); */
/* static int cb_pcidda_ns_to_timer(unsigned int *ns,int *round); */
static unsigned int cb_pcidda_serial_in(struct comedi_device *dev);
static void cb_pcidda_serial_out(struct comedi_device *dev, unsigned int value,
unsigned int num_bits);
static unsigned int cb_pcidda_read_eeprom(struct comedi_device *dev,
unsigned int address);
static void cb_pcidda_calibrate(struct comedi_device *dev, unsigned int channel,
unsigned int range);
/*
* The struct comedi_driver structure tells the Comedi core module
* which functions to call to configure/deconfigure (attach/detach)
* the board, and also about the kernel module that contains
* the device code.
*/
static struct comedi_driver driver_cb_pcidda = {
.driver_name = "cb_pcidda",
.module = THIS_MODULE,
.attach = cb_pcidda_attach,
.detach = cb_pcidda_detach,
};
/*
* Attach is called by the Comedi core to configure the driver
* for a particular board.
*/
static int cb_pcidda_attach(struct comedi_device *dev,
struct comedi_devconfig *it)
{
struct comedi_subdevice *s;
struct pci_dev *pcidev;
int index;
printk("comedi%d: cb_pcidda: ", dev->minor);
/*
* Allocate the private structure area.
*/
if (alloc_private(dev, sizeof(struct cb_pcidda_private)) < 0)
return -ENOMEM;
/*
* Probe the device to determine what device in the series it is.
*/
printk("\n");
for (pcidev = pci_get_device(PCI_ANY_ID, PCI_ANY_ID, NULL);
pcidev != NULL;
pcidev = pci_get_device(PCI_ANY_ID, PCI_ANY_ID, pcidev)) {
if (pcidev->vendor == PCI_VENDOR_ID_CB) {
if (it->options[0] || it->options[1]) {
if (pcidev->bus->number != it->options[0] ||
PCI_SLOT(pcidev->devfn) != it->options[1]) {
continue;
}
}
for (index = 0; index < N_BOARDS; index++) {
if (cb_pcidda_boards[index].device_id ==
pcidev->device) {
goto found;
}
}
}
}
if (!pcidev) {
printk
("Not a ComputerBoards/MeasurementComputing card on requested position\n");
return -EIO;
}
found:
devpriv->pci_dev = pcidev;
dev->board_ptr = cb_pcidda_boards + index;
/* "thisboard" macro can be used from here. */
printk("Found %s at requested position\n", thisboard->name);
/*
* Enable PCI device and request regions.
*/
if (comedi_pci_enable(pcidev, thisboard->name)) {
printk
("cb_pcidda: failed to enable PCI device and request regions\n");
return -EIO;
}
/*
* Allocate the I/O ports.
*/
devpriv->digitalio =
pci_resource_start(devpriv->pci_dev, DIGITALIO_BADRINDEX);
devpriv->dac = pci_resource_start(devpriv->pci_dev, DAC_BADRINDEX);
/*
* Warn about the status of the driver.
*/
if (thisboard->status == 2)
printk
("WARNING: DRIVER FOR THIS BOARD NOT CHECKED WITH MANUAL. "
"WORKS ASSUMING FULL COMPATIBILITY WITH PCI-DDA08/12. "
"PLEASE REPORT USAGE TO <[email protected]>.\n");
/*
* Initialize dev->board_name.
*/
dev->board_name = thisboard->name;
/*
* Allocate the subdevice structures.
*/
if (alloc_subdevices(dev, 3) < 0)
return -ENOMEM;
s = dev->subdevices + 0;
/* analog output subdevice */
s->type = COMEDI_SUBD_AO;
s->subdev_flags = SDF_WRITABLE;
s->n_chan = thisboard->ao_chans;
s->maxdata = (1 << thisboard->ao_bits) - 1;
s->range_table = thisboard->ranges;
s->insn_write = cb_pcidda_ao_winsn;
/* s->subdev_flags |= SDF_CMD_READ; */
/* s->do_cmd = cb_pcidda_ai_cmd; */
/* s->do_cmdtest = cb_pcidda_ai_cmdtest; */
/* two 8255 digital io subdevices */
s = dev->subdevices + 1;
subdev_8255_init(dev, s, NULL, devpriv->digitalio);
s = dev->subdevices + 2;
subdev_8255_init(dev, s, NULL, devpriv->digitalio + PORT2A);
printk(" eeprom:");
for (index = 0; index < EEPROM_SIZE; index++) {
devpriv->eeprom_data[index] = cb_pcidda_read_eeprom(dev, index);
printk(" %i:0x%x ", index, devpriv->eeprom_data[index]);
}
printk("\n");
/* set calibrations dacs */
for (index = 0; index < thisboard->ao_chans; index++)
cb_pcidda_calibrate(dev, index, devpriv->ao_range[index]);
return 1;
}
/*
* _detach is called to deconfigure a device. It should deallocate
* resources.
* This function is also called when _attach() fails, so it should be
* careful not to release resources that were not necessarily
* allocated by _attach(). dev->private and dev->subdevices are
* deallocated automatically by the core.
*/
static int cb_pcidda_detach(struct comedi_device *dev)
{
/*
* Deallocate the I/O ports.
*/
if (devpriv) {
if (devpriv->pci_dev) {
if (devpriv->dac) {
comedi_pci_disable(devpriv->pci_dev);
}
pci_dev_put(devpriv->pci_dev);
}
}
/* cleanup 8255 */
if (dev->subdevices) {
subdev_8255_cleanup(dev, dev->subdevices + 1);
subdev_8255_cleanup(dev, dev->subdevices + 2);
}
printk("comedi%d: cb_pcidda: remove\n", dev->minor);
return 0;
}
/*
* I will program this later... ;-)
*/
#if 0
static int cb_pcidda_ai_cmd(struct comedi_device *dev,
struct comedi_subdevice *s)
{
printk("cb_pcidda_ai_cmd\n");
printk("subdev: %d\n", cmd->subdev);
printk("flags: %d\n", cmd->flags);
printk("start_src: %d\n", cmd->start_src);
printk("start_arg: %d\n", cmd->start_arg);
printk("scan_begin_src: %d\n", cmd->scan_begin_src);
printk("convert_src: %d\n", cmd->convert_src);
printk("convert_arg: %d\n", cmd->convert_arg);
printk("scan_end_src: %d\n", cmd->scan_end_src);
printk("scan_end_arg: %d\n", cmd->scan_end_arg);
printk("stop_src: %d\n", cmd->stop_src);
printk("stop_arg: %d\n", cmd->stop_arg);
printk("chanlist_len: %d\n", cmd->chanlist_len);
}
#endif
#if 0
static int cb_pcidda_ai_cmdtest(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_cmd *cmd)
{
int err = 0;
int tmp;
/* cmdtest tests a particular command to see if it is valid.
* Using the cmdtest ioctl, a user can create a valid cmd
* and then have it executes by the cmd ioctl.
*
* cmdtest returns 1,2,3,4 or 0, depending on which tests
* the command passes. */
/* step 1: make sure trigger sources are trivially valid */
tmp = cmd->start_src;
cmd->start_src &= TRIG_NOW;
if (!cmd->start_src || tmp != cmd->start_src)
err++;
tmp = cmd->scan_begin_src;
cmd->scan_begin_src &= TRIG_TIMER | TRIG_EXT;
if (!cmd->scan_begin_src || tmp != cmd->scan_begin_src)
err++;
tmp = cmd->convert_src;
cmd->convert_src &= TRIG_TIMER | TRIG_EXT;
if (!cmd->convert_src || tmp != cmd->convert_src)
err++;
tmp = cmd->scan_end_src;
cmd->scan_end_src &= TRIG_COUNT;
if (!cmd->scan_end_src || tmp != cmd->scan_end_src)
err++;
tmp = cmd->stop_src;
cmd->stop_src &= TRIG_COUNT | TRIG_NONE;
if (!cmd->stop_src || tmp != cmd->stop_src)
err++;
if (err)
return 1;
/* step 2: make sure trigger sources are unique and mutually compatible */
/* note that mutual compatibility is not an issue here */
if (cmd->scan_begin_src != TRIG_TIMER
&& cmd->scan_begin_src != TRIG_EXT)
err++;
if (cmd->convert_src != TRIG_TIMER && cmd->convert_src != TRIG_EXT)
err++;
if (cmd->stop_src != TRIG_TIMER && cmd->stop_src != TRIG_EXT)
err++;
if (err)
return 2;
/* step 3: make sure arguments are trivially compatible */
if (cmd->start_arg != 0) {
cmd->start_arg = 0;
err++;
}
#define MAX_SPEED 10000 /* in nanoseconds */
#define MIN_SPEED 1000000000 /* in nanoseconds */
if (cmd->scan_begin_src == TRIG_TIMER) {
if (cmd->scan_begin_arg < MAX_SPEED) {
cmd->scan_begin_arg = MAX_SPEED;
err++;
}
if (cmd->scan_begin_arg > MIN_SPEED) {
cmd->scan_begin_arg = MIN_SPEED;
err++;
}
} else {
/* external trigger */
/* should be level/edge, hi/lo specification here */
/* should specify multiple external triggers */
if (cmd->scan_begin_arg > 9) {
cmd->scan_begin_arg = 9;
err++;
}
}
if (cmd->convert_src == TRIG_TIMER) {
if (cmd->convert_arg < MAX_SPEED) {
cmd->convert_arg = MAX_SPEED;
err++;
}
if (cmd->convert_arg > MIN_SPEED) {
cmd->convert_arg = MIN_SPEED;
err++;
}
} else {
/* external trigger */
/* see above */
if (cmd->convert_arg > 9) {
cmd->convert_arg = 9;
err++;
}
}
if (cmd->scan_end_arg != cmd->chanlist_len) {
cmd->scan_end_arg = cmd->chanlist_len;
err++;
}
if (cmd->stop_src == TRIG_COUNT) {
if (cmd->stop_arg > 0x00ffffff) {
cmd->stop_arg = 0x00ffffff;
err++;
}
} else {
/* TRIG_NONE */
if (cmd->stop_arg != 0) {
cmd->stop_arg = 0;
err++;
}
}
if (err)
return 3;
/* step 4: fix up any arguments */
if (cmd->scan_begin_src == TRIG_TIMER) {
tmp = cmd->scan_begin_arg;
cb_pcidda_ns_to_timer(&cmd->scan_begin_arg,
cmd->flags & TRIG_ROUND_MASK);
if (tmp != cmd->scan_begin_arg)
err++;
}
if (cmd->convert_src == TRIG_TIMER) {
tmp = cmd->convert_arg;
cb_pcidda_ns_to_timer(&cmd->convert_arg,
cmd->flags & TRIG_ROUND_MASK);
if (tmp != cmd->convert_arg)
err++;
if (cmd->scan_begin_src == TRIG_TIMER &&
cmd->scan_begin_arg <
cmd->convert_arg * cmd->scan_end_arg) {
cmd->scan_begin_arg =
cmd->convert_arg * cmd->scan_end_arg;
err++;
}
}
if (err)
return 4;
return 0;
}
#endif
/* This function doesn't require a particular form, this is just
* what happens to be used in some of the drivers. It should
* convert ns nanoseconds to a counter value suitable for programming
* the device. Also, it should adjust ns so that it cooresponds to
* the actual time that the device will use. */
#if 0
static int cb_pcidda_ns_to_timer(unsigned int *ns, int round)
{
/* trivial timer */
return *ns;
}
#endif
static int cb_pcidda_ao_winsn(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
unsigned int command;
unsigned int channel, range;
channel = CR_CHAN(insn->chanspec);
range = CR_RANGE(insn->chanspec);
/* adjust calibration dacs if range has changed */
if (range != devpriv->ao_range[channel])
cb_pcidda_calibrate(dev, channel, range);
/* output channel configuration */
command = NOSU | ENABLEDAC;
/* output channel range */
switch (range) {
case 0:
command |= BIP | RANGE10V;
break;
case 1:
command |= BIP | RANGE5V;
break;
case 2:
command |= BIP | RANGE2V5;
break;
case 3:
command |= UNIP | RANGE10V;
break;
case 4:
command |= UNIP | RANGE5V;
break;
case 5:
command |= UNIP | RANGE2V5;
break;
};
/* output channel specification */
command |= channel << 2;
outw(command, devpriv->dac + DACONTROL);
/* write data */
outw(data[0], devpriv->dac + DADATA + channel * 2);
/* return the number of samples read/written */
return 1;
}
/* lowlevel read from eeprom */
static unsigned int cb_pcidda_serial_in(struct comedi_device *dev)
{
unsigned int value = 0;
int i;
const int value_width = 16; /* number of bits wide values are */
for (i = 1; i <= value_width; i++) {
/* read bits most significant bit first */
if (inw_p(devpriv->dac + DACALIBRATION1) & SERIAL_OUT_BIT) {
value |= 1 << (value_width - i);
}
}
return value;
}
/* lowlevel write to eeprom/dac */
static void cb_pcidda_serial_out(struct comedi_device *dev, unsigned int value,
unsigned int num_bits)
{
int i;
for (i = 1; i <= num_bits; i++) {
/* send bits most significant bit first */
if (value & (1 << (num_bits - i)))
devpriv->dac_cal1_bits |= SERIAL_IN_BIT;
else
devpriv->dac_cal1_bits &= ~SERIAL_IN_BIT;
outw_p(devpriv->dac_cal1_bits, devpriv->dac + DACALIBRATION1);
}
}
/* reads a 16 bit value from board's eeprom */
static unsigned int cb_pcidda_read_eeprom(struct comedi_device *dev,
unsigned int address)
{
unsigned int i;
unsigned int cal2_bits;
unsigned int value;
const int max_num_caldacs = 4; /* one caldac for every two dac channels */
const int read_instruction = 0x6; /* bits to send to tell eeprom we want to read */
const int instruction_length = 3;
const int address_length = 8;
/* send serial output stream to eeprom */
cal2_bits = SELECT_EEPROM_BIT | DESELECT_REF_DAC_BIT | DUMMY_BIT;
/* deactivate caldacs (one caldac for every two channels) */
for (i = 0; i < max_num_caldacs; i++) {
cal2_bits |= DESELECT_CALDAC_BIT(i);
}
outw_p(cal2_bits, devpriv->dac + DACALIBRATION2);
/* tell eeprom we want to read */
cb_pcidda_serial_out(dev, read_instruction, instruction_length);
/* send address we want to read from */
cb_pcidda_serial_out(dev, address, address_length);
value = cb_pcidda_serial_in(dev);
/* deactivate eeprom */
cal2_bits &= ~SELECT_EEPROM_BIT;
outw_p(cal2_bits, devpriv->dac + DACALIBRATION2);
return value;
}
/* writes to 8 bit calibration dacs */
static void cb_pcidda_write_caldac(struct comedi_device *dev,
unsigned int caldac, unsigned int channel,
unsigned int value)
{
unsigned int cal2_bits;
unsigned int i;
const int num_channel_bits = 3; /* caldacs use 3 bit channel specification */
const int num_caldac_bits = 8; /* 8 bit calibration dacs */
const int max_num_caldacs = 4; /* one caldac for every two dac channels */
/* write 3 bit channel */
cb_pcidda_serial_out(dev, channel, num_channel_bits);
/* write 8 bit caldac value */
cb_pcidda_serial_out(dev, value, num_caldac_bits);
/*
* latch stream into appropriate caldac deselect reference dac
*/
cal2_bits = DESELECT_REF_DAC_BIT | DUMMY_BIT;
/* deactivate caldacs (one caldac for every two channels) */
for (i = 0; i < max_num_caldacs; i++) {
cal2_bits |= DESELECT_CALDAC_BIT(i);
}
/* activate the caldac we want */
cal2_bits &= ~DESELECT_CALDAC_BIT(caldac);
outw_p(cal2_bits, devpriv->dac + DACALIBRATION2);
/* deactivate caldac */
cal2_bits |= DESELECT_CALDAC_BIT(caldac);
outw_p(cal2_bits, devpriv->dac + DACALIBRATION2);
}
/* returns caldac that calibrates given analog out channel */
static unsigned int caldac_number(unsigned int channel)
{
return channel / 2;
}
/* returns caldac channel that provides fine gain for given ao channel */
static unsigned int fine_gain_channel(unsigned int ao_channel)
{
return 4 * (ao_channel % 2);
}
/* returns caldac channel that provides coarse gain for given ao channel */
static unsigned int coarse_gain_channel(unsigned int ao_channel)
{
return 1 + 4 * (ao_channel % 2);
}
/* returns caldac channel that provides coarse offset for given ao channel */
static unsigned int coarse_offset_channel(unsigned int ao_channel)
{
return 2 + 4 * (ao_channel % 2);
}
/* returns caldac channel that provides fine offset for given ao channel */
static unsigned int fine_offset_channel(unsigned int ao_channel)
{
return 3 + 4 * (ao_channel % 2);
}
/* returns eeprom address that provides offset for given ao channel and range */
static unsigned int offset_eeprom_address(unsigned int ao_channel,
unsigned int range)
{
return 0x7 + 2 * range + 12 * ao_channel;
}
/* returns eeprom address that provides gain calibration for given ao channel and range */
static unsigned int gain_eeprom_address(unsigned int ao_channel,
unsigned int range)
{
return 0x8 + 2 * range + 12 * ao_channel;
}
/* returns upper byte of eeprom entry, which gives the coarse adjustment values */
static unsigned int eeprom_coarse_byte(unsigned int word)
{
return (word >> 8) & 0xff;
}
/* returns lower byte of eeprom entry, which gives the fine adjustment values */
static unsigned int eeprom_fine_byte(unsigned int word)
{
return word & 0xff;
}
/* set caldacs to eeprom values for given channel and range */
static void cb_pcidda_calibrate(struct comedi_device *dev, unsigned int channel,
unsigned int range)
{
unsigned int coarse_offset, fine_offset, coarse_gain, fine_gain;
/* remember range so we can tell when we need to readjust calibration */
devpriv->ao_range[channel] = range;
/* get values from eeprom data */
coarse_offset =
eeprom_coarse_byte(devpriv->eeprom_data
[offset_eeprom_address(channel, range)]);
fine_offset =
eeprom_fine_byte(devpriv->eeprom_data
[offset_eeprom_address(channel, range)]);
coarse_gain =
eeprom_coarse_byte(devpriv->eeprom_data
[gain_eeprom_address(channel, range)]);
fine_gain =
eeprom_fine_byte(devpriv->eeprom_data
[gain_eeprom_address(channel, range)]);
/* set caldacs */
cb_pcidda_write_caldac(dev, caldac_number(channel),
coarse_offset_channel(channel), coarse_offset);
cb_pcidda_write_caldac(dev, caldac_number(channel),
fine_offset_channel(channel), fine_offset);
cb_pcidda_write_caldac(dev, caldac_number(channel),
coarse_gain_channel(channel), coarse_gain);
cb_pcidda_write_caldac(dev, caldac_number(channel),
fine_gain_channel(channel), fine_gain);
}
/*
* A convenient macro that defines init_module() and cleanup_module(),
* as necessary.
*/
COMEDI_PCI_INITCLEANUP(driver_cb_pcidda, cb_pcidda_pci_table);
| gpl-2.0 |
Palakis/obs-studio | plugins/win-mf/mf-aac-encoder.hpp | 2383 | #pragma once
#define WIN32_MEAN_AND_LEAN
#include <Windows.h>
#undef WIN32_MEAN_AND_LEAN
#include <mfapi.h>
#include <mfidl.h>
#include <stdint.h>
#include <vector>
#include <util/windows/ComPtr.hpp>
#define MF_LOG(level, format, ...) \
blog(level, "[Media Foundation encoder]: " format, ##__VA_ARGS__)
#define MF_LOG_ENCODER(format_name, encoder, level, format, ...) \
blog(level, "[Media Foundation %s: '%s']: " format, \
format_name, obs_encoder_get_name(encoder), \
##__VA_ARGS__)
namespace MFAAC {
enum Status {
FAILURE,
SUCCESS,
NOT_ACCEPTING,
NEED_MORE_INPUT
};
class Encoder {
public:
Encoder(const obs_encoder_t *encoder, UINT32 bitrate, UINT32 channels,
UINT32 sampleRate, UINT32 bitsPerSample)
: encoder(encoder),
bitrate(bitrate),
channels(channels),
sampleRate(sampleRate),
bitsPerSample(bitsPerSample)
{}
Encoder& operator=(Encoder const&) = delete;
bool Initialize();
bool ProcessInput(UINT8 *data, UINT32 dataLength,
UINT64 pts, MFAAC::Status *status);
bool ProcessOutput(UINT8 **data, UINT32 *dataLength,
UINT64 *pts, MFAAC::Status *status);
bool ExtraData(UINT8 **extraData, UINT32 *extraDataLength);
const obs_encoder_t *ObsEncoder() { return encoder; }
UINT32 Bitrate() { return bitrate; }
UINT32 Channels() { return channels; }
UINT32 SampleRate() { return sampleRate; }
UINT32 BitsPerSample() { return bitsPerSample; }
static const UINT32 FrameSize = 1024;
private:
void InitializeExtraData();
HRESULT CreateMediaTypes(ComPtr<IMFMediaType> &inputType,
ComPtr<IMFMediaType> &outputType);
HRESULT EnsureCapacity(ComPtr<IMFSample> &sample, DWORD length);
HRESULT CreateEmptySample(ComPtr<IMFSample> &sample,
ComPtr<IMFMediaBuffer> &buffer, DWORD length);
private:
const obs_encoder_t *encoder;
const UINT32 bitrate;
const UINT32 channels;
const UINT32 sampleRate;
const UINT32 bitsPerSample;
ComPtr<IMFTransform> transform;
ComPtr<IMFSample> outputSample;
std::vector<BYTE> packetBuffer;
UINT8 extraData[3];
};
static const UINT32 FrameSize = 1024;
UINT32 FindBestBitrateMatch(UINT32 value);
UINT32 FindBestChannelsMatch(UINT32 value);
UINT32 FindBestBitsPerSampleMatch(UINT32 value);
UINT32 FindBestSamplerateMatch(UINT32 value);
bool BitrateValid(UINT32 value);
bool ChannelsValid(UINT32 value);
bool BitsPerSampleValid(UINT32 value);
bool SamplerateValid(UINT32 value);
}
| gpl-2.0 |
sorted2323/msi | testauthorize/report/courseoverview/version.php | 1219 | <?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Version info
*
* @package report
* @subpackage courseoverview
* @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die;
$plugin->version = 2013050100; // The current plugin version (Date: YYYYMMDDXX)
$plugin->requires = 2013050100; // Requires this Moodle version
$plugin->component = 'report_courseoverview'; // Full name of the plugin (used for diagnostics)
| gpl-3.0 |
reasyrf/XBeeMultiTerminal | src/NLog/examples/targets/Configuration API/Mail/Buffered/Example.cs | 1532 | using System;
using NLog;
using NLog.Targets;
using NLog.Targets.Wrappers;
class Example
{
static void Main(string[] args)
{
try
{
NLog.Internal.InternalLogger.LogToConsole = true;
NLog.Internal.InternalLogger.LogLevel = LogLevel.Trace;
Console.WriteLine("Setting up the target...");
MailTarget target = new MailTarget();
target.SmtpServer = "192.168.0.15";
target.From = "[email protected]";
target.To = "[email protected]";
target.Subject = "sample subject";
target.Body = "${message}${newline}";
BufferingTargetWrapper buffer = new BufferingTargetWrapper(target, 5);
NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(buffer, LogLevel.Debug);
Console.WriteLine("Sending...");
Logger logger = LogManager.GetLogger("Example");
logger.Debug("log message 1");
logger.Debug("log message 2");
logger.Debug("log message 3");
logger.Debug("log message 4");
logger.Debug("log message 5");
logger.Debug("log message 6");
logger.Debug("log message 7");
logger.Debug("log message 8");
// this should send 2 mails - one with messages 1..5, the other with messages 6..8
Console.WriteLine("Sent.");
}
catch (Exception ex)
{
Console.WriteLine("EX: {0}", ex);
}
}
}
| gpl-3.0 |
locnx1984/pcl | 3rdparty/flann/Makefile | 643 | VERSION=1.6.11
all:
wget http://people.cs.ubc.ca/~mariusm/uploads/FLANN/flann-${VERSION}-src.zip
unzip flann-${VERSION}-src.zip
#patch -p0 < cpack.patch
cd flann-${VERSION}-src && mkdir -p build && cd build && cmake -DBUILD_C_BINDINGS=false -DBUILD_PYTHON_BINDINGS=false -DBUILD_MATLAB_BINDINGS=false -DCMAKE_BUILD_TYPE=RELEASE -DCMAKE_INSTALL_PREFIX=/usr .. && \
make package && \
if test -e *.exe; \
then cp *.exe ../../; \
fi; \
if test -e *.rpm; \
then cp *.rpm ../../; \
fi; \
if test -e *.deb; \
then cp *.deb ../../; \
fi; \
if test -e *.dmg; \
then cp *.dmg ../../; \
fi;
clean:
rm -rf flann* *~
| bsd-3-clause |
endlessm/chromium-browser | third_party/catapult/third_party/Paste/paste/util/scgiserver.py | 5612 | """
SCGI-->WSGI application proxy, "SWAP".
(Originally written by Titus Brown.)
This lets an SCGI front-end like mod_scgi be used to execute WSGI
application objects. To use it, subclass the SWAP class like so::
class TestAppHandler(swap.SWAP):
def __init__(self, *args, **kwargs):
self.prefix = '/canal'
self.app_obj = TestAppClass
swap.SWAP.__init__(self, *args, **kwargs)
where 'TestAppClass' is the application object from WSGI and '/canal'
is the prefix for what is served by the SCGI Web-server-side process.
Then execute the SCGI handler "as usual" by doing something like this::
scgi_server.SCGIServer(TestAppHandler, port=4000).serve()
and point mod_scgi (or whatever your SCGI front end is) at port 4000.
Kudos to the WSGI folk for writing a nice PEP & the Quixote folk for
writing a nice extensible SCGI server for Python!
"""
import six
import sys
import time
from scgi import scgi_server
def debug(msg):
timestamp = time.strftime("%Y-%m-%d %H:%M:%S",
time.localtime(time.time()))
sys.stderr.write("[%s] %s\n" % (timestamp, msg))
class SWAP(scgi_server.SCGIHandler):
"""
SCGI->WSGI application proxy: let an SCGI server execute WSGI
application objects.
"""
app_obj = None
prefix = None
def __init__(self, *args, **kwargs):
assert self.app_obj, "must set app_obj"
assert self.prefix is not None, "must set prefix"
args = (self,) + args
scgi_server.SCGIHandler.__init__(*args, **kwargs)
def handle_connection(self, conn):
"""
Handle an individual connection.
"""
input = conn.makefile("r")
output = conn.makefile("w")
environ = self.read_env(input)
environ['wsgi.input'] = input
environ['wsgi.errors'] = sys.stderr
environ['wsgi.version'] = (1, 0)
environ['wsgi.multithread'] = False
environ['wsgi.multiprocess'] = True
environ['wsgi.run_once'] = False
# dunno how SCGI does HTTPS signalling; can't test it myself... @CTB
if environ.get('HTTPS','off') in ('on','1'):
environ['wsgi.url_scheme'] = 'https'
else:
environ['wsgi.url_scheme'] = 'http'
## SCGI does some weird environ manglement. We need to set
## SCRIPT_NAME from 'prefix' and then set PATH_INFO from
## REQUEST_URI.
prefix = self.prefix
path = environ['REQUEST_URI'][len(prefix):].split('?', 1)[0]
environ['SCRIPT_NAME'] = prefix
environ['PATH_INFO'] = path
headers_set = []
headers_sent = []
chunks = []
def write(data):
chunks.append(data)
def start_response(status, response_headers, exc_info=None):
if exc_info:
try:
if headers_sent:
# Re-raise original exception if headers sent
six.reraise(exc_info[0], exc_info[1], exc_info[2])
finally:
exc_info = None # avoid dangling circular ref
elif headers_set:
raise AssertionError("Headers already set!")
headers_set[:] = [status, response_headers]
return write
###
result = self.app_obj(environ, start_response)
try:
for data in result:
chunks.append(data)
# Before the first output, send the stored headers
if not headers_set:
# Error -- the app never called start_response
status = '500 Server Error'
response_headers = [('Content-type', 'text/html')]
chunks = ["XXX start_response never called"]
else:
status, response_headers = headers_sent[:] = headers_set
output.write('Status: %s\r\n' % status)
for header in response_headers:
output.write('%s: %s\r\n' % header)
output.write('\r\n')
for data in chunks:
output.write(data)
finally:
if hasattr(result,'close'):
result.close()
# SCGI backends use connection closing to signal 'fini'.
try:
input.close()
output.close()
conn.close()
except IOError as err:
debug("IOError while closing connection ignored: %s" % err)
def serve_application(application, prefix, port=None, host=None, max_children=None):
"""
Serve the specified WSGI application via SCGI proxy.
``application``
The WSGI application to serve.
``prefix``
The prefix for what is served by the SCGI Web-server-side process.
``port``
Optional port to bind the SCGI proxy to. Defaults to SCGIServer's
default port value.
``host``
Optional host to bind the SCGI proxy to. Defaults to SCGIServer's
default host value.
``host``
Optional maximum number of child processes the SCGIServer will
spawn. Defaults to SCGIServer's default max_children value.
"""
class SCGIAppHandler(SWAP):
def __init__ (self, *args, **kwargs):
self.prefix = prefix
self.app_obj = application
SWAP.__init__(self, *args, **kwargs)
kwargs = dict(handler_class=SCGIAppHandler)
for kwarg in ('host', 'port', 'max_children'):
if locals()[kwarg] is not None:
kwargs[kwarg] = locals()[kwarg]
scgi_server.SCGIServer(**kwargs).serve()
| bsd-3-clause |
emelyan1987/FoodDelivery | tests/system/core/Utf8.php | 4412 | <?php
/**
* CodeIgniter
*
* An open source application development framework for PHP
*
* This content is released under the MIT License (MIT)
*
* Copyright (c) 2014 - 2016, British Columbia Institute of Technology
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @package CodeIgniter
* @author EllisLab Dev Team
* @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/)
* @copyright Copyright (c) 2014 - 2016, British Columbia Institute of Technology (http://bcit.ca/)
* @license http://opensource.org/licenses/MIT MIT License
* @link https://codeigniter.com
* @since Version 2.0.0
* @filesource
*/
defined('BASEPATH') OR exit('No direct script access allowed');
/**
* Utf8 Class
*
* Provides support for UTF-8 environments
*
* @package CodeIgniter
* @subpackage Libraries
* @category UTF-8
* @author EllisLab Dev Team
* @link https://codeigniter.com/user_guide/libraries/utf8.html
*/
class CI_Utf8 {
/**
* Class constructor
*
* Determines if UTF-8 support is to be enabled.
*
* @return void
*/
public function __construct()
{
if (
defined('PREG_BAD_UTF8_ERROR') // PCRE must support UTF-8
&& (ICONV_ENABLED === TRUE OR MB_ENABLED === TRUE) // iconv or mbstring must be installed
&& strtoupper(config_item('charset')) === 'UTF-8' // Application charset must be UTF-8
)
{
define('UTF8_ENABLED', TRUE);
log_message('info', 'UTF-8 Support Enabled');
}
else
{
define('UTF8_ENABLED', FALSE);
log_message('info', 'UTF-8 Support Disabled');
}
log_message('info', 'Utf8 Class Initialized');
}
// --------------------------------------------------------------------
/**
* Clean UTF-8 strings
*
* Ensures strings contain only valid UTF-8 characters.
*
* @param string $str String to clean
* @return string
*/
public function clean_string($str)
{
if ($this->is_ascii($str) === FALSE)
{
if (MB_ENABLED)
{
$str = mb_convert_encoding($str, 'UTF-8', 'UTF-8');
}
elseif (ICONV_ENABLED)
{
$str = @iconv('UTF-8', 'UTF-8//IGNORE', $str);
}
}
return $str;
}
// --------------------------------------------------------------------
/**
* Remove ASCII control characters
*
* Removes all ASCII control characters except horizontal tabs,
* line feeds, and carriage returns, as all others can cause
* problems in XML.
*
* @param string $str String to clean
* @return string
*/
public function safe_ascii_for_xml($str)
{
return remove_invisible_characters($str, FALSE);
}
// --------------------------------------------------------------------
/**
* Convert to UTF-8
*
* Attempts to convert a string to UTF-8.
*
* @param string $str Input string
* @param string $encoding Input encoding
* @return string $str encoded in UTF-8 or FALSE on failure
*/
public function convert_to_utf8($str, $encoding)
{
if (MB_ENABLED)
{
return mb_convert_encoding($str, 'UTF-8', $encoding);
}
elseif (ICONV_ENABLED)
{
return @iconv($encoding, 'UTF-8', $str);
}
return FALSE;
}
// --------------------------------------------------------------------
/**
* Is ASCII?
*
* Tests if a string is standard 7-bit ASCII or not.
*
* @param string $str String to check
* @return bool
*/
public function is_ascii($str)
{
return (preg_match('/[^\x00-\x7F]/S', $str) === 0);
}
}
| mit |
demns/todomvc-perf-comparison | todomvc/react/node_modules/reactify/node_modules/react-tools/node_modules/jstransform/visitors/__tests__/type-function-syntax-test.js | 7860 | /**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*jshint evil:true*/
require('mock-modules').autoMockOff();
describe('static type function syntax', function() {
var flowSyntaxVisitors;
var jstransform;
beforeEach(function() {
require('mock-modules').dumpCache();
flowSyntaxVisitors = require('../type-syntax.js').visitorList;
jstransform = require('jstransform');
});
function transform(code, visitors) {
code = code.join('\n');
// We run the flow transform first
code = jstransform.transform(
flowSyntaxVisitors,
code
).code;
if (visitors) {
code = jstransform.transform(
visitors,
code
).code;
}
return code;
}
describe('param type annotations', () => {
it('strips single param annotation', () => {
var code = transform([
'function foo(param1: bool) {',
' return param1;',
'}',
'',
'var bar = function(param1: bool) {',
' return param1;',
'}'
]);
eval(code);
expect(foo(42)).toBe(42);
expect(bar(42)).toBe(42);
});
it('strips multiple param annotations', () => {
var code = transform([
'function foo(param1: bool, param2: number) {',
' return [param1, param2];',
'}',
'',
'var bar = function(param1: bool, param2: number) {',
' return [param1, param2];',
'}'
]);
eval(code);
expect(foo(true, 42)).toEqual([true, 42]);
expect(bar(true, 42)).toEqual([true, 42]);
});
it('strips higher-order param annotations', () => {
var code = transform([
'function foo(param1: (_:bool) => number) {',
' return param1;',
'}',
'',
'var bar = function(param1: (_:bool) => number) {',
' return param1;',
'}'
]);
eval(code);
var callback = function(param) {
return param ? 42 : 0;
};
expect(foo(callback)).toBe(callback);
expect(bar(callback)).toBe(callback);
});
it('strips annotated params next to non-annotated params', () => {
var code = transform([
'function foo(param1, param2: number) {',
' return [param1, param2];',
'}',
'',
'var bar = function(param1, param2: number) {',
' return [param1, param2];',
'}'
]);
eval(code);
expect(foo('p1', 42)).toEqual(['p1', 42]);
expect(bar('p1', 42)).toEqual(['p1', 42]);
});
it('strips annotated params before a rest parameter', () => {
var restParamVisitors =
require('../es6-rest-param-visitors').visitorList;
var code = transform([
'function foo(param1: number, ...args) {',
' return [param1, args];',
'}',
'',
'var bar = function(param1: number, ...args) {',
' return [param1, args];',
'}'
], restParamVisitors);
eval(code);
expect(foo(42, 43, 44)).toEqual([42, [43, 44]]);
expect(bar(42, 43, 44)).toEqual([42, [43, 44]]);
});
it('strips annotated rest parameter', () => {
var restParamVisitors =
require('../es6-rest-param-visitors').visitorList;
var code = transform([
'function foo(param1: number, ...args: Array<number>) {',
' return [param1, args];',
'}',
'',
'var bar = function(param1: number, ...args: Array<number>) {',
' return [param1, args];',
'}'
], restParamVisitors);
eval(code);
expect(foo(42, 43, 44)).toEqual([42, [43, 44]]);
expect(bar(42, 43, 44)).toEqual([42, [43, 44]]);
});
it('strips optional param marker without type annotation', () => {
var code = transform([
'function foo(param1?, param2 ?) {',
' return 42;',
'}'
]);
eval(code);
expect(foo()).toBe(42);
});
it('strips optional param marker with type annotation', () => {
var code = transform([
'function foo(param1?:number, param2 ?: string, param3 ? : bool) {',
' return 42;',
'}'
]);
eval(code);
expect(foo()).toBe(42);
});
});
describe('return type annotations', () => {
it('strips function return types', () => {
var code = transform([
'function foo(param1:number): () => number {',
' return function() { return param1; };',
'}',
'',
'var bar = function(param1:number): () => number {',
' return function() { return param1; };',
'}'
]);
eval(code);
expect(foo(42)()).toBe(42);
expect(bar(42)()).toBe(42);
});
it('strips void return types', () => {
var code = transform([
'function foo(param1): void {',
' param1();',
'}',
'',
'var bar = function(param1): void {',
' param1();',
'}'
]);
eval(code);
var counter = 0;
function testFn() {
counter++;
}
foo(testFn);
expect(counter).toBe(1);
bar(testFn);
expect(counter).toBe(2);
});
it('strips void return types with rest params', () => {
var code = transform(
[
'function foo(param1, ...rest): void {',
' param1();',
'}',
'',
'var bar = function(param1, ...rest): void {',
' param1();',
'}'
],
require('../es6-rest-param-visitors').visitorList
);
eval(code);
var counter = 0;
function testFn() {
counter++;
}
foo(testFn);
expect(counter).toBe(1);
bar(testFn);
expect(counter).toBe(2);
});
it('strips object return types', () => {
var code = transform([
'function foo(param1:number): {num: number} {',
' return {num: param1};',
'}',
'',
'var bar = function(param1:number): {num: number} {',
' return {num: param1};',
'}'
]);
eval(code);
expect(foo(42)).toEqual({num: 42});
expect(bar(42)).toEqual({num: 42});
});
});
describe('parametric type annotation', () => {
it('strips parametric type annotations', () => {
var code = transform([
'function foo<T>(param1) {',
' return param1;',
'}',
'',
'var bar = function<T>(param1) {',
' return param1;',
'}',
]);
eval(code);
expect(foo(42)).toBe(42);
expect(bar(42)).toBe(42);
});
it('strips multi-parameter type annotations', () => {
var restParamVisitors =
require('../es6-rest-param-visitors').visitorList;
var code = transform([
'function foo<T, S>(param1) {',
' return param1;',
'}',
'',
'var bar = function<T,S>(param1) {',
' return param1;',
'}'
], restParamVisitors);
eval(code);
expect(foo(42)).toBe(42);
expect(bar(42)).toBe(42);
});
});
describe('arrow functions', () => {
// TODO: We don't currently support arrow functions, but we should
// soon! The only reason we don't now is because we don't
// need it at this very moment and I'm in a rush to get the
// basics in.
});
});
| mit |
angusty/symfony-study | vendor/Zend/Service/DeveloperGarden/Response/ConferenceCall/GetRunningConferenceResponse.php | 1572 | <?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Service
* @subpackage DeveloperGarden
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
/**
* @see Zend_Service_DeveloperGarden_Response_ConferenceCall_ConferenceCallAbstract
*/
require_once 'Zend/Service/DeveloperGarden/Response/ConferenceCall/ConferenceCallAbstract.php';
/**
* @category Zend
* @package Zend_Service
* @subpackage DeveloperGarden
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @author Marco Kaiser
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Service_DeveloperGarden_Response_ConferenceCall_GetRunningConferenceResponse
extends Zend_Service_DeveloperGarden_Response_ConferenceCall_ConferenceCallAbstract
{
/**
* response data
*
* @var Zend_Service_DeveloperGarden_Response_ConferenceCall_GetRunningConferenceResponseType
*/
public $getRunningConferenceResponse = null;
}
| mit |
animalcreek/linux | drivers/net/phy/bcm7xxx.c | 19188 | /*
* Broadcom BCM7xxx internal transceivers support.
*
* Copyright (C) 2014-2017 Broadcom
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*/
#include <linux/module.h>
#include <linux/phy.h>
#include <linux/delay.h>
#include "bcm-phy-lib.h"
#include <linux/bitops.h>
#include <linux/brcmphy.h>
#include <linux/mdio.h>
/* Broadcom BCM7xxx internal PHY registers */
/* EPHY only register definitions */
#define MII_BCM7XXX_100TX_AUX_CTL 0x10
#define MII_BCM7XXX_100TX_FALSE_CAR 0x13
#define MII_BCM7XXX_100TX_DISC 0x14
#define MII_BCM7XXX_AUX_MODE 0x1d
#define MII_BCM7XXX_64CLK_MDIO BIT(12)
#define MII_BCM7XXX_TEST 0x1f
#define MII_BCM7XXX_SHD_MODE_2 BIT(2)
#define MII_BCM7XXX_SHD_2_ADDR_CTRL 0xe
#define MII_BCM7XXX_SHD_2_CTRL_STAT 0xf
#define MII_BCM7XXX_SHD_2_BIAS_TRIM 0x1a
#define MII_BCM7XXX_SHD_3_AN_EEE_ADV 0x3
#define MII_BCM7XXX_SHD_3_PCS_CTRL_2 0x6
#define MII_BCM7XXX_PCS_CTRL_2_DEF 0x4400
#define MII_BCM7XXX_SHD_3_AN_STAT 0xb
#define MII_BCM7XXX_AN_NULL_MSG_EN BIT(0)
#define MII_BCM7XXX_AN_EEE_EN BIT(1)
#define MII_BCM7XXX_SHD_3_EEE_THRESH 0xe
#define MII_BCM7XXX_EEE_THRESH_DEF 0x50
#define MII_BCM7XXX_SHD_3_TL4 0x23
#define MII_BCM7XXX_TL4_RST_MSK (BIT(2) | BIT(1))
/* 28nm only register definitions */
#define MISC_ADDR(base, channel) base, channel
#define DSP_TAP10 MISC_ADDR(0x0a, 0)
#define PLL_PLLCTRL_1 MISC_ADDR(0x32, 1)
#define PLL_PLLCTRL_2 MISC_ADDR(0x32, 2)
#define PLL_PLLCTRL_4 MISC_ADDR(0x33, 0)
#define AFE_RXCONFIG_0 MISC_ADDR(0x38, 0)
#define AFE_RXCONFIG_1 MISC_ADDR(0x38, 1)
#define AFE_RXCONFIG_2 MISC_ADDR(0x38, 2)
#define AFE_RX_LP_COUNTER MISC_ADDR(0x38, 3)
#define AFE_TX_CONFIG MISC_ADDR(0x39, 0)
#define AFE_VDCA_ICTRL_0 MISC_ADDR(0x39, 1)
#define AFE_VDAC_OTHERS_0 MISC_ADDR(0x39, 3)
#define AFE_HPF_TRIM_OTHERS MISC_ADDR(0x3a, 0)
struct bcm7xxx_phy_priv {
u64 *stats;
};
static void r_rc_cal_reset(struct phy_device *phydev)
{
/* Reset R_CAL/RC_CAL Engine */
bcm_phy_write_exp(phydev, 0x00b0, 0x0010);
/* Disable Reset R_AL/RC_CAL Engine */
bcm_phy_write_exp(phydev, 0x00b0, 0x0000);
}
static int bcm7xxx_28nm_b0_afe_config_init(struct phy_device *phydev)
{
/* Increase VCO range to prevent unlocking problem of PLL at low
* temp
*/
bcm_phy_write_misc(phydev, PLL_PLLCTRL_1, 0x0048);
/* Change Ki to 011 */
bcm_phy_write_misc(phydev, PLL_PLLCTRL_2, 0x021b);
/* Disable loading of TVCO buffer to bandgap, set bandgap trim
* to 111
*/
bcm_phy_write_misc(phydev, PLL_PLLCTRL_4, 0x0e20);
/* Adjust bias current trim by -3 */
bcm_phy_write_misc(phydev, DSP_TAP10, 0x690b);
/* Switch to CORE_BASE1E */
phy_write(phydev, MII_BRCM_CORE_BASE1E, 0xd);
r_rc_cal_reset(phydev);
/* write AFE_RXCONFIG_0 */
bcm_phy_write_misc(phydev, AFE_RXCONFIG_0, 0xeb19);
/* write AFE_RXCONFIG_1 */
bcm_phy_write_misc(phydev, AFE_RXCONFIG_1, 0x9a3f);
/* write AFE_RX_LP_COUNTER */
bcm_phy_write_misc(phydev, AFE_RX_LP_COUNTER, 0x7fc0);
/* write AFE_HPF_TRIM_OTHERS */
bcm_phy_write_misc(phydev, AFE_HPF_TRIM_OTHERS, 0x000b);
/* write AFTE_TX_CONFIG */
bcm_phy_write_misc(phydev, AFE_TX_CONFIG, 0x0800);
return 0;
}
static int bcm7xxx_28nm_d0_afe_config_init(struct phy_device *phydev)
{
/* AFE_RXCONFIG_0 */
bcm_phy_write_misc(phydev, AFE_RXCONFIG_0, 0xeb15);
/* AFE_RXCONFIG_1 */
bcm_phy_write_misc(phydev, AFE_RXCONFIG_1, 0x9b2f);
/* AFE_RXCONFIG_2, set rCal offset for HT=0 code and LT=-2 code */
bcm_phy_write_misc(phydev, AFE_RXCONFIG_2, 0x2003);
/* AFE_RX_LP_COUNTER, set RX bandwidth to maximum */
bcm_phy_write_misc(phydev, AFE_RX_LP_COUNTER, 0x7fc0);
/* AFE_TX_CONFIG, set 100BT Cfeed=011 to improve rise/fall time */
bcm_phy_write_misc(phydev, AFE_TX_CONFIG, 0x431);
/* AFE_VDCA_ICTRL_0, set Iq=1101 instead of 0111 for AB symmetry */
bcm_phy_write_misc(phydev, AFE_VDCA_ICTRL_0, 0xa7da);
/* AFE_VDAC_OTHERS_0, set 1000BT Cidac=010 for all ports */
bcm_phy_write_misc(phydev, AFE_VDAC_OTHERS_0, 0xa020);
/* AFE_HPF_TRIM_OTHERS, set 100Tx/10BT to -4.5% swing and set rCal
* offset for HT=0 code
*/
bcm_phy_write_misc(phydev, AFE_HPF_TRIM_OTHERS, 0x00e3);
/* CORE_BASE1E, force trim to overwrite and set I_ext trim to 0000 */
phy_write(phydev, MII_BRCM_CORE_BASE1E, 0x0010);
/* DSP_TAP10, adjust bias current trim (+0% swing, +0 tick) */
bcm_phy_write_misc(phydev, DSP_TAP10, 0x011b);
/* Reset R_CAL/RC_CAL engine */
r_rc_cal_reset(phydev);
return 0;
}
static int bcm7xxx_28nm_e0_plus_afe_config_init(struct phy_device *phydev)
{
/* AFE_RXCONFIG_1, provide more margin for INL/DNL measurement */
bcm_phy_write_misc(phydev, AFE_RXCONFIG_1, 0x9b2f);
/* AFE_TX_CONFIG, set 100BT Cfeed=011 to improve rise/fall time */
bcm_phy_write_misc(phydev, AFE_TX_CONFIG, 0x431);
/* AFE_VDCA_ICTRL_0, set Iq=1101 instead of 0111 for AB symmetry */
bcm_phy_write_misc(phydev, AFE_VDCA_ICTRL_0, 0xa7da);
/* AFE_HPF_TRIM_OTHERS, set 100Tx/10BT to -4.5% swing and set rCal
* offset for HT=0 code
*/
bcm_phy_write_misc(phydev, AFE_HPF_TRIM_OTHERS, 0x00e3);
/* CORE_BASE1E, force trim to overwrite and set I_ext trim to 0000 */
phy_write(phydev, MII_BRCM_CORE_BASE1E, 0x0010);
/* DSP_TAP10, adjust bias current trim (+0% swing, +0 tick) */
bcm_phy_write_misc(phydev, DSP_TAP10, 0x011b);
/* Reset R_CAL/RC_CAL engine */
r_rc_cal_reset(phydev);
return 0;
}
static int bcm7xxx_28nm_a0_patch_afe_config_init(struct phy_device *phydev)
{
/* +1 RC_CAL codes for RL centering for both LT and HT conditions */
bcm_phy_write_misc(phydev, AFE_RXCONFIG_2, 0xd003);
/* Cut master bias current by 2% to compensate for RC_CAL offset */
bcm_phy_write_misc(phydev, DSP_TAP10, 0x791b);
/* Improve hybrid leakage */
bcm_phy_write_misc(phydev, AFE_HPF_TRIM_OTHERS, 0x10e3);
/* Change rx_on_tune 8 to 0xf */
bcm_phy_write_misc(phydev, 0x21, 0x2, 0x87f6);
/* Change 100Tx EEE bandwidth */
bcm_phy_write_misc(phydev, 0x22, 0x2, 0x017d);
/* Enable ffe zero detection for Vitesse interoperability */
bcm_phy_write_misc(phydev, 0x26, 0x2, 0x0015);
r_rc_cal_reset(phydev);
return 0;
}
static int bcm7xxx_28nm_config_init(struct phy_device *phydev)
{
u8 rev = PHY_BRCM_7XXX_REV(phydev->dev_flags);
u8 patch = PHY_BRCM_7XXX_PATCH(phydev->dev_flags);
u8 count;
int ret = 0;
/* Newer devices have moved the revision information back into a
* standard location in MII_PHYS_ID[23]
*/
if (rev == 0)
rev = phydev->phy_id & ~phydev->drv->phy_id_mask;
pr_info_once("%s: %s PHY revision: 0x%02x, patch: %d\n",
phydev_name(phydev), phydev->drv->name, rev, patch);
/* Dummy read to a register to workaround an issue upon reset where the
* internal inverter may not allow the first MDIO transaction to pass
* the MDIO management controller and make us return 0xffff for such
* reads.
*/
phy_read(phydev, MII_BMSR);
switch (rev) {
case 0xb0:
ret = bcm7xxx_28nm_b0_afe_config_init(phydev);
break;
case 0xd0:
ret = bcm7xxx_28nm_d0_afe_config_init(phydev);
break;
case 0xe0:
case 0xf0:
/* Rev G0 introduces a roll over */
case 0x10:
ret = bcm7xxx_28nm_e0_plus_afe_config_init(phydev);
break;
case 0x01:
ret = bcm7xxx_28nm_a0_patch_afe_config_init(phydev);
break;
default:
break;
}
if (ret)
return ret;
ret = bcm_phy_downshift_get(phydev, &count);
if (ret)
return ret;
/* Only enable EEE if Wirespeed/downshift is disabled */
ret = bcm_phy_set_eee(phydev, count == DOWNSHIFT_DEV_DISABLE);
if (ret)
return ret;
return bcm_phy_enable_apd(phydev, true);
}
static int bcm7xxx_28nm_resume(struct phy_device *phydev)
{
int ret;
/* Re-apply workarounds coming out suspend/resume */
ret = bcm7xxx_28nm_config_init(phydev);
if (ret)
return ret;
/* 28nm Gigabit PHYs come out of reset without any half-duplex
* or "hub" compliant advertised mode, fix that. This does not
* cause any problems with the PHY library since genphy_config_aneg()
* gracefully handles auto-negotiated and forced modes.
*/
return genphy_config_aneg(phydev);
}
static int phy_set_clr_bits(struct phy_device *dev, int location,
int set_mask, int clr_mask)
{
int v, ret;
v = phy_read(dev, location);
if (v < 0)
return v;
v &= ~clr_mask;
v |= set_mask;
ret = phy_write(dev, location, v);
if (ret < 0)
return ret;
return v;
}
static int bcm7xxx_28nm_ephy_01_afe_config_init(struct phy_device *phydev)
{
int ret;
/* set shadow mode 2 */
ret = phy_set_clr_bits(phydev, MII_BCM7XXX_TEST,
MII_BCM7XXX_SHD_MODE_2, 0);
if (ret < 0)
return ret;
/* Set current trim values INT_trim = -1, Ext_trim =0 */
ret = phy_write(phydev, MII_BCM7XXX_SHD_2_BIAS_TRIM, 0x3BE0);
if (ret < 0)
goto reset_shadow_mode;
/* Cal reset */
ret = phy_write(phydev, MII_BCM7XXX_SHD_2_ADDR_CTRL,
MII_BCM7XXX_SHD_3_TL4);
if (ret < 0)
goto reset_shadow_mode;
ret = phy_set_clr_bits(phydev, MII_BCM7XXX_SHD_2_CTRL_STAT,
MII_BCM7XXX_TL4_RST_MSK, 0);
if (ret < 0)
goto reset_shadow_mode;
/* Cal reset disable */
ret = phy_write(phydev, MII_BCM7XXX_SHD_2_ADDR_CTRL,
MII_BCM7XXX_SHD_3_TL4);
if (ret < 0)
goto reset_shadow_mode;
ret = phy_set_clr_bits(phydev, MII_BCM7XXX_SHD_2_CTRL_STAT,
0, MII_BCM7XXX_TL4_RST_MSK);
if (ret < 0)
goto reset_shadow_mode;
reset_shadow_mode:
/* reset shadow mode 2 */
ret = phy_set_clr_bits(phydev, MII_BCM7XXX_TEST, 0,
MII_BCM7XXX_SHD_MODE_2);
if (ret < 0)
return ret;
return 0;
}
/* The 28nm EPHY does not support Clause 45 (MMD) used by bcm-phy-lib */
static int bcm7xxx_28nm_ephy_apd_enable(struct phy_device *phydev)
{
int ret;
/* set shadow mode 1 */
ret = phy_set_clr_bits(phydev, MII_BRCM_FET_BRCMTEST,
MII_BRCM_FET_BT_SRE, 0);
if (ret < 0)
return ret;
/* Enable auto-power down */
ret = phy_set_clr_bits(phydev, MII_BRCM_FET_SHDW_AUXSTAT2,
MII_BRCM_FET_SHDW_AS2_APDE, 0);
if (ret < 0)
return ret;
/* reset shadow mode 1 */
ret = phy_set_clr_bits(phydev, MII_BRCM_FET_BRCMTEST, 0,
MII_BRCM_FET_BT_SRE);
if (ret < 0)
return ret;
return 0;
}
static int bcm7xxx_28nm_ephy_eee_enable(struct phy_device *phydev)
{
int ret;
/* set shadow mode 2 */
ret = phy_set_clr_bits(phydev, MII_BCM7XXX_TEST,
MII_BCM7XXX_SHD_MODE_2, 0);
if (ret < 0)
return ret;
/* Advertise supported modes */
ret = phy_write(phydev, MII_BCM7XXX_SHD_2_ADDR_CTRL,
MII_BCM7XXX_SHD_3_AN_EEE_ADV);
if (ret < 0)
goto reset_shadow_mode;
ret = phy_write(phydev, MII_BCM7XXX_SHD_2_CTRL_STAT,
MDIO_EEE_100TX);
if (ret < 0)
goto reset_shadow_mode;
/* Restore Defaults */
ret = phy_write(phydev, MII_BCM7XXX_SHD_2_ADDR_CTRL,
MII_BCM7XXX_SHD_3_PCS_CTRL_2);
if (ret < 0)
goto reset_shadow_mode;
ret = phy_write(phydev, MII_BCM7XXX_SHD_2_CTRL_STAT,
MII_BCM7XXX_PCS_CTRL_2_DEF);
if (ret < 0)
goto reset_shadow_mode;
ret = phy_write(phydev, MII_BCM7XXX_SHD_2_ADDR_CTRL,
MII_BCM7XXX_SHD_3_EEE_THRESH);
if (ret < 0)
goto reset_shadow_mode;
ret = phy_write(phydev, MII_BCM7XXX_SHD_2_CTRL_STAT,
MII_BCM7XXX_EEE_THRESH_DEF);
if (ret < 0)
goto reset_shadow_mode;
/* Enable EEE autonegotiation */
ret = phy_write(phydev, MII_BCM7XXX_SHD_2_ADDR_CTRL,
MII_BCM7XXX_SHD_3_AN_STAT);
if (ret < 0)
goto reset_shadow_mode;
ret = phy_write(phydev, MII_BCM7XXX_SHD_2_CTRL_STAT,
(MII_BCM7XXX_AN_NULL_MSG_EN | MII_BCM7XXX_AN_EEE_EN));
if (ret < 0)
goto reset_shadow_mode;
reset_shadow_mode:
/* reset shadow mode 2 */
ret = phy_set_clr_bits(phydev, MII_BCM7XXX_TEST, 0,
MII_BCM7XXX_SHD_MODE_2);
if (ret < 0)
return ret;
/* Restart autoneg */
phy_write(phydev, MII_BMCR,
(BMCR_SPEED100 | BMCR_ANENABLE | BMCR_ANRESTART));
return 0;
}
static int bcm7xxx_28nm_ephy_config_init(struct phy_device *phydev)
{
u8 rev = phydev->phy_id & ~phydev->drv->phy_id_mask;
int ret = 0;
pr_info_once("%s: %s PHY revision: 0x%02x\n",
phydev_name(phydev), phydev->drv->name, rev);
/* Dummy read to a register to workaround a possible issue upon reset
* where the internal inverter may not allow the first MDIO transaction
* to pass the MDIO management controller and make us return 0xffff for
* such reads.
*/
phy_read(phydev, MII_BMSR);
/* Apply AFE software work-around if necessary */
if (rev == 0x01) {
ret = bcm7xxx_28nm_ephy_01_afe_config_init(phydev);
if (ret)
return ret;
}
ret = bcm7xxx_28nm_ephy_eee_enable(phydev);
if (ret)
return ret;
return bcm7xxx_28nm_ephy_apd_enable(phydev);
}
static int bcm7xxx_28nm_ephy_resume(struct phy_device *phydev)
{
int ret;
/* Re-apply workarounds coming out suspend/resume */
ret = bcm7xxx_28nm_ephy_config_init(phydev);
if (ret)
return ret;
return genphy_config_aneg(phydev);
}
static int bcm7xxx_config_init(struct phy_device *phydev)
{
int ret;
/* Enable 64 clock MDIO */
phy_write(phydev, MII_BCM7XXX_AUX_MODE, MII_BCM7XXX_64CLK_MDIO);
phy_read(phydev, MII_BCM7XXX_AUX_MODE);
/* set shadow mode 2 */
ret = phy_set_clr_bits(phydev, MII_BCM7XXX_TEST,
MII_BCM7XXX_SHD_MODE_2, MII_BCM7XXX_SHD_MODE_2);
if (ret < 0)
return ret;
/* set iddq_clkbias */
phy_write(phydev, MII_BCM7XXX_100TX_DISC, 0x0F00);
udelay(10);
/* reset iddq_clkbias */
phy_write(phydev, MII_BCM7XXX_100TX_DISC, 0x0C00);
phy_write(phydev, MII_BCM7XXX_100TX_FALSE_CAR, 0x7555);
/* reset shadow mode 2 */
ret = phy_set_clr_bits(phydev, MII_BCM7XXX_TEST, 0, MII_BCM7XXX_SHD_MODE_2);
if (ret < 0)
return ret;
return 0;
}
/* Workaround for putting the PHY in IDDQ mode, required
* for all BCM7XXX 40nm and 65nm PHYs
*/
static int bcm7xxx_suspend(struct phy_device *phydev)
{
int ret;
static const struct bcm7xxx_regs {
int reg;
u16 value;
} bcm7xxx_suspend_cfg[] = {
{ MII_BCM7XXX_TEST, 0x008b },
{ MII_BCM7XXX_100TX_AUX_CTL, 0x01c0 },
{ MII_BCM7XXX_100TX_DISC, 0x7000 },
{ MII_BCM7XXX_TEST, 0x000f },
{ MII_BCM7XXX_100TX_AUX_CTL, 0x20d0 },
{ MII_BCM7XXX_TEST, 0x000b },
};
unsigned int i;
for (i = 0; i < ARRAY_SIZE(bcm7xxx_suspend_cfg); i++) {
ret = phy_write(phydev,
bcm7xxx_suspend_cfg[i].reg,
bcm7xxx_suspend_cfg[i].value);
if (ret)
return ret;
}
return 0;
}
static int bcm7xxx_28nm_get_tunable(struct phy_device *phydev,
struct ethtool_tunable *tuna,
void *data)
{
switch (tuna->id) {
case ETHTOOL_PHY_DOWNSHIFT:
return bcm_phy_downshift_get(phydev, (u8 *)data);
default:
return -EOPNOTSUPP;
}
}
static int bcm7xxx_28nm_set_tunable(struct phy_device *phydev,
struct ethtool_tunable *tuna,
const void *data)
{
u8 count = *(u8 *)data;
int ret;
switch (tuna->id) {
case ETHTOOL_PHY_DOWNSHIFT:
ret = bcm_phy_downshift_set(phydev, count);
break;
default:
return -EOPNOTSUPP;
}
if (ret)
return ret;
/* Disable EEE advertisment since this prevents the PHY
* from successfully linking up, trigger auto-negotiation restart
* to let the MAC decide what to do.
*/
ret = bcm_phy_set_eee(phydev, count == DOWNSHIFT_DEV_DISABLE);
if (ret)
return ret;
return genphy_restart_aneg(phydev);
}
static void bcm7xxx_28nm_get_phy_stats(struct phy_device *phydev,
struct ethtool_stats *stats, u64 *data)
{
struct bcm7xxx_phy_priv *priv = phydev->priv;
bcm_phy_get_stats(phydev, priv->stats, stats, data);
}
static int bcm7xxx_28nm_probe(struct phy_device *phydev)
{
struct bcm7xxx_phy_priv *priv;
priv = devm_kzalloc(&phydev->mdio.dev, sizeof(*priv), GFP_KERNEL);
if (!priv)
return -ENOMEM;
phydev->priv = priv;
priv->stats = devm_kcalloc(&phydev->mdio.dev,
bcm_phy_get_sset_count(phydev), sizeof(u64),
GFP_KERNEL);
if (!priv->stats)
return -ENOMEM;
return 0;
}
#define BCM7XXX_28NM_GPHY(_oui, _name) \
{ \
.phy_id = (_oui), \
.phy_id_mask = 0xfffffff0, \
.name = _name, \
.features = PHY_GBIT_FEATURES, \
.flags = PHY_IS_INTERNAL, \
.config_init = bcm7xxx_28nm_config_init, \
.config_aneg = genphy_config_aneg, \
.read_status = genphy_read_status, \
.resume = bcm7xxx_28nm_resume, \
.get_tunable = bcm7xxx_28nm_get_tunable, \
.set_tunable = bcm7xxx_28nm_set_tunable, \
.get_sset_count = bcm_phy_get_sset_count, \
.get_strings = bcm_phy_get_strings, \
.get_stats = bcm7xxx_28nm_get_phy_stats, \
.probe = bcm7xxx_28nm_probe, \
}
#define BCM7XXX_28NM_EPHY(_oui, _name) \
{ \
.phy_id = (_oui), \
.phy_id_mask = 0xfffffff0, \
.name = _name, \
.features = PHY_BASIC_FEATURES, \
.flags = PHY_IS_INTERNAL, \
.config_init = bcm7xxx_28nm_ephy_config_init, \
.config_aneg = genphy_config_aneg, \
.read_status = genphy_read_status, \
.resume = bcm7xxx_28nm_ephy_resume, \
.get_sset_count = bcm_phy_get_sset_count, \
.get_strings = bcm_phy_get_strings, \
.get_stats = bcm7xxx_28nm_get_phy_stats, \
.probe = bcm7xxx_28nm_probe, \
}
#define BCM7XXX_40NM_EPHY(_oui, _name) \
{ \
.phy_id = (_oui), \
.phy_id_mask = 0xfffffff0, \
.name = _name, \
.features = PHY_BASIC_FEATURES, \
.flags = PHY_IS_INTERNAL, \
.config_init = bcm7xxx_config_init, \
.config_aneg = genphy_config_aneg, \
.read_status = genphy_read_status, \
.suspend = bcm7xxx_suspend, \
.resume = bcm7xxx_config_init, \
}
static struct phy_driver bcm7xxx_driver[] = {
BCM7XXX_28NM_GPHY(PHY_ID_BCM7250, "Broadcom BCM7250"),
BCM7XXX_28NM_EPHY(PHY_ID_BCM7260, "Broadcom BCM7260"),
BCM7XXX_28NM_EPHY(PHY_ID_BCM7268, "Broadcom BCM7268"),
BCM7XXX_28NM_EPHY(PHY_ID_BCM7271, "Broadcom BCM7271"),
BCM7XXX_28NM_GPHY(PHY_ID_BCM7278, "Broadcom BCM7278"),
BCM7XXX_28NM_GPHY(PHY_ID_BCM7364, "Broadcom BCM7364"),
BCM7XXX_28NM_GPHY(PHY_ID_BCM7366, "Broadcom BCM7366"),
BCM7XXX_28NM_GPHY(PHY_ID_BCM74371, "Broadcom BCM74371"),
BCM7XXX_28NM_GPHY(PHY_ID_BCM7439, "Broadcom BCM7439"),
BCM7XXX_28NM_GPHY(PHY_ID_BCM7439_2, "Broadcom BCM7439 (2)"),
BCM7XXX_28NM_GPHY(PHY_ID_BCM7445, "Broadcom BCM7445"),
BCM7XXX_40NM_EPHY(PHY_ID_BCM7346, "Broadcom BCM7346"),
BCM7XXX_40NM_EPHY(PHY_ID_BCM7362, "Broadcom BCM7362"),
BCM7XXX_40NM_EPHY(PHY_ID_BCM7425, "Broadcom BCM7425"),
BCM7XXX_40NM_EPHY(PHY_ID_BCM7429, "Broadcom BCM7429"),
BCM7XXX_40NM_EPHY(PHY_ID_BCM7435, "Broadcom BCM7435"),
};
static struct mdio_device_id __maybe_unused bcm7xxx_tbl[] = {
{ PHY_ID_BCM7250, 0xfffffff0, },
{ PHY_ID_BCM7260, 0xfffffff0, },
{ PHY_ID_BCM7268, 0xfffffff0, },
{ PHY_ID_BCM7271, 0xfffffff0, },
{ PHY_ID_BCM7278, 0xfffffff0, },
{ PHY_ID_BCM7364, 0xfffffff0, },
{ PHY_ID_BCM7366, 0xfffffff0, },
{ PHY_ID_BCM7346, 0xfffffff0, },
{ PHY_ID_BCM7362, 0xfffffff0, },
{ PHY_ID_BCM7425, 0xfffffff0, },
{ PHY_ID_BCM7429, 0xfffffff0, },
{ PHY_ID_BCM74371, 0xfffffff0, },
{ PHY_ID_BCM7439, 0xfffffff0, },
{ PHY_ID_BCM7435, 0xfffffff0, },
{ PHY_ID_BCM7445, 0xfffffff0, },
{ }
};
module_phy_driver(bcm7xxx_driver);
MODULE_DEVICE_TABLE(mdio, bcm7xxx_tbl);
MODULE_DESCRIPTION("Broadcom BCM7xxx internal PHY driver");
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Broadcom Corporation");
| gpl-2.0 |
kv193/buildroot | linux/linux-kernel/arch/arm/mach-at91/board-qil-a9260.c | 6144 | /*
* linux/arch/arm/mach-at91/board-qil-a9260.c
*
* Copyright (C) 2005 SAN People
* Copyright (C) 2006 Atmel
* Copyright (C) 2007 Calao-systems
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/types.h>
#include <linux/gpio.h>
#include <linux/init.h>
#include <linux/mm.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/spi/spi.h>
#include <linux/gpio_keys.h>
#include <linux/input.h>
#include <linux/clk.h>
#include <asm/setup.h>
#include <asm/mach-types.h>
#include <asm/irq.h>
#include <asm/mach/arch.h>
#include <asm/mach/map.h>
#include <asm/mach/irq.h>
#include <mach/hardware.h>
#include <mach/board.h>
#include <mach/at91sam9_smc.h>
#include <mach/at91_shdwc.h>
#include "sam9_smc.h"
#include "generic.h"
static void __init ek_init_early(void)
{
/* Initialize processor: 12.000 MHz crystal */
at91_initialize(12000000);
}
/*
* USB Host port
*/
static struct at91_usbh_data __initdata ek_usbh_data = {
.ports = 2,
.vbus_pin = {-EINVAL, -EINVAL},
.overcurrent_pin= {-EINVAL, -EINVAL},
};
/*
* USB Device port
*/
static struct at91_udc_data __initdata ek_udc_data = {
.vbus_pin = AT91_PIN_PC5,
.pullup_pin = -EINVAL, /* pull-up driven by UDC */
};
/*
* SPI devices.
*/
static struct spi_board_info ek_spi_devices[] = {
#if defined(CONFIG_RTC_DRV_M41T94)
{ /* M41T94 RTC */
.modalias = "m41t94",
.chip_select = 0,
.max_speed_hz = 1 * 1000 * 1000,
.bus_num = 0,
}
#endif
};
/*
* MACB Ethernet device
*/
static struct macb_platform_data __initdata ek_macb_data = {
.phy_irq_pin = AT91_PIN_PA31,
.is_rmii = 1,
};
/*
* NAND flash
*/
static struct mtd_partition __initdata ek_nand_partition[] = {
{
.name = "Uboot & Kernel",
.offset = 0,
.size = SZ_16M,
},
{
.name = "Root FS",
.offset = MTDPART_OFS_NXTBLK,
.size = 120 * SZ_1M,
},
{
.name = "FS",
.offset = MTDPART_OFS_NXTBLK,
.size = 120 * SZ_1M,
},
};
static struct atmel_nand_data __initdata ek_nand_data = {
.ale = 21,
.cle = 22,
.det_pin = -EINVAL,
.rdy_pin = AT91_PIN_PC13,
.enable_pin = AT91_PIN_PC14,
.ecc_mode = NAND_ECC_SOFT,
.on_flash_bbt = 1,
.parts = ek_nand_partition,
.num_parts = ARRAY_SIZE(ek_nand_partition),
};
static struct sam9_smc_config __initdata ek_nand_smc_config = {
.ncs_read_setup = 0,
.nrd_setup = 1,
.ncs_write_setup = 0,
.nwe_setup = 1,
.ncs_read_pulse = 3,
.nrd_pulse = 3,
.ncs_write_pulse = 3,
.nwe_pulse = 3,
.read_cycle = 5,
.write_cycle = 5,
.mode = AT91_SMC_READMODE | AT91_SMC_WRITEMODE | AT91_SMC_EXNWMODE_DISABLE | AT91_SMC_DBW_8,
.tdf_cycles = 2,
};
static void __init ek_add_device_nand(void)
{
/* configure chip-select 3 (NAND) */
sam9_smc_configure(0, 3, &ek_nand_smc_config);
at91_add_device_nand(&ek_nand_data);
}
/*
* MCI (SD/MMC)
*/
static struct at91_mmc_data __initdata ek_mmc_data = {
.slot_b = 0,
.wire4 = 1,
.det_pin = -EINVAL,
.wp_pin = -EINVAL,
.vcc_pin = -EINVAL,
};
/*
* GPIO Buttons
*/
#if defined(CONFIG_KEYBOARD_GPIO) || defined(CONFIG_KEYBOARD_GPIO_MODULE)
static struct gpio_keys_button ek_buttons[] = {
{ /* USER PUSH BUTTON */
.code = KEY_ENTER,
.gpio = AT91_PIN_PB10,
.active_low = 1,
.desc = "user_pb",
.wakeup = 1,
}
};
static struct gpio_keys_platform_data ek_button_data = {
.buttons = ek_buttons,
.nbuttons = ARRAY_SIZE(ek_buttons),
};
static struct platform_device ek_button_device = {
.name = "gpio-keys",
.id = -1,
.num_resources = 0,
.dev = {
.platform_data = &ek_button_data,
}
};
static void __init ek_add_device_buttons(void)
{
at91_set_GPIO_periph(AT91_PIN_PB10, 1); /* user push button, pull up enabled */
at91_set_deglitch(AT91_PIN_PB10, 1);
platform_device_register(&ek_button_device);
}
#else
static void __init ek_add_device_buttons(void) {}
#endif
/*
* LEDs
*/
static struct gpio_led ek_leds[] = {
{ /* user_led (green) */
.name = "user_led",
.gpio = AT91_PIN_PB21,
.active_low = 0,
.default_trigger = "heartbeat",
}
};
static void __init ek_board_init(void)
{
/* Serial */
/* DBGU on ttyS0. (Rx & Tx only) */
at91_register_uart(0, 0, 0);
/* USART0 on ttyS1. (Rx, Tx, CTS, RTS, DTR, DSR, DCD, RI) */
at91_register_uart(AT91SAM9260_ID_US0, 1, ATMEL_UART_CTS | ATMEL_UART_RTS
| ATMEL_UART_DTR | ATMEL_UART_DSR | ATMEL_UART_DCD
| ATMEL_UART_RI);
/* USART1 on ttyS2. (Rx, Tx, CTS, RTS) */
at91_register_uart(AT91SAM9260_ID_US1, 2, ATMEL_UART_CTS | ATMEL_UART_RTS);
/* USART2 on ttyS3. (Rx, Tx, CTS, RTS) */
at91_register_uart(AT91SAM9260_ID_US2, 3, ATMEL_UART_CTS | ATMEL_UART_RTS);
at91_add_device_serial();
/* USB Host */
at91_add_device_usbh(&ek_usbh_data);
/* USB Device */
at91_add_device_udc(&ek_udc_data);
/* SPI */
at91_add_device_spi(ek_spi_devices, ARRAY_SIZE(ek_spi_devices));
/* NAND */
ek_add_device_nand();
/* I2C */
at91_add_device_i2c(NULL, 0);
/* Ethernet */
at91_add_device_eth(&ek_macb_data);
/* MMC */
at91_add_device_mmc(0, &ek_mmc_data);
/* Push Buttons */
ek_add_device_buttons();
/* LEDs */
at91_gpio_leds(ek_leds, ARRAY_SIZE(ek_leds));
/* shutdown controller, wakeup button (5 msec low) */
at91_shdwc_write(AT91_SHDW_MR, AT91_SHDW_CPTWK0_(10) | AT91_SHDW_WKMODE0_LOW
| AT91_SHDW_RTTWKEN);
}
MACHINE_START(QIL_A9260, "CALAO QIL_A9260")
/* Maintainer: calao-systems */
.timer = &at91sam926x_timer,
.map_io = at91_map_io,
.init_early = ek_init_early,
.init_irq = at91_init_irq_default,
.init_machine = ek_board_init,
MACHINE_END
| gpl-2.0 |
varund7726/OwnKernel-bacon | net/ipv6/ip6_output.c | 42808 | /*
* IPv6 output functions
* Linux INET6 implementation
*
* Authors:
* Pedro Roque <[email protected]>
*
* Based on linux/net/ipv4/ip_output.c
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*
* Changes:
* A.N.Kuznetsov : airthmetics in fragmentation.
* extension headers are implemented.
* route changes now work.
* ip6_forward does not confuse sniffers.
* etc.
*
* H. von Brand : Added missing #include <linux/string.h>
* Imran Patel : frag id should be in NBO
* Kazunori MIYAZAWA @USAGI
* : add ip6_append_data and related functions
* for datagram xmit
*/
#include <linux/errno.h>
#include <linux/kernel.h>
#include <linux/string.h>
#include <linux/socket.h>
#include <linux/net.h>
#include <linux/netdevice.h>
#include <linux/if_arp.h>
#include <linux/in6.h>
#include <linux/tcp.h>
#include <linux/route.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/netfilter.h>
#include <linux/netfilter_ipv6.h>
#include <net/sock.h>
#include <net/snmp.h>
#include <net/ipv6.h>
#include <net/ndisc.h>
#include <net/protocol.h>
#include <net/ip6_route.h>
#include <net/addrconf.h>
#include <net/rawv6.h>
#include <net/icmp.h>
#include <net/xfrm.h>
#include <net/checksum.h>
#include <linux/mroute6.h>
int ip6_fragment(struct sk_buff *skb, int (*output)(struct sk_buff *));
int __ip6_local_out(struct sk_buff *skb)
{
int len;
len = skb->len - sizeof(struct ipv6hdr);
if (len > IPV6_MAXPLEN)
len = 0;
ipv6_hdr(skb)->payload_len = htons(len);
return nf_hook(NFPROTO_IPV6, NF_INET_LOCAL_OUT, skb, NULL,
skb_dst(skb)->dev, dst_output);
}
int ip6_local_out(struct sk_buff *skb)
{
int err;
err = __ip6_local_out(skb);
if (likely(err == 1))
err = dst_output(skb);
return err;
}
EXPORT_SYMBOL_GPL(ip6_local_out);
/* dev_loopback_xmit for use with netfilter. */
static int ip6_dev_loopback_xmit(struct sk_buff *newskb)
{
skb_reset_mac_header(newskb);
__skb_pull(newskb, skb_network_offset(newskb));
newskb->pkt_type = PACKET_LOOPBACK;
newskb->ip_summed = CHECKSUM_UNNECESSARY;
WARN_ON(!skb_dst(newskb));
netif_rx_ni(newskb);
return 0;
}
static int ip6_finish_output2(struct sk_buff *skb)
{
struct dst_entry *dst = skb_dst(skb);
struct net_device *dev = dst->dev;
struct neighbour *neigh;
skb->protocol = htons(ETH_P_IPV6);
skb->dev = dev;
if (ipv6_addr_is_multicast(&ipv6_hdr(skb)->daddr)) {
struct inet6_dev *idev = ip6_dst_idev(skb_dst(skb));
if (!(dev->flags & IFF_LOOPBACK) && sk_mc_loop(skb->sk) &&
((mroute6_socket(dev_net(dev), skb) &&
!(IP6CB(skb)->flags & IP6SKB_FORWARDED)) ||
ipv6_chk_mcast_addr(dev, &ipv6_hdr(skb)->daddr,
&ipv6_hdr(skb)->saddr))) {
struct sk_buff *newskb = skb_clone(skb, GFP_ATOMIC);
/* Do not check for IFF_ALLMULTI; multicast routing
is not supported in any case.
*/
if (newskb)
NF_HOOK(NFPROTO_IPV6, NF_INET_POST_ROUTING,
newskb, NULL, newskb->dev,
ip6_dev_loopback_xmit);
if (ipv6_hdr(skb)->hop_limit == 0) {
IP6_INC_STATS(dev_net(dev), idev,
IPSTATS_MIB_OUTDISCARDS);
kfree_skb(skb);
return 0;
}
}
IP6_UPD_PO_STATS(dev_net(dev), idev, IPSTATS_MIB_OUTMCAST,
skb->len);
}
rcu_read_lock();
neigh = dst_get_neighbour_noref(dst);
if (neigh) {
int res = neigh_output(neigh, skb);
rcu_read_unlock();
return res;
}
rcu_read_unlock();
IP6_INC_STATS(dev_net(dst->dev),
ip6_dst_idev(dst), IPSTATS_MIB_OUTNOROUTES);
kfree_skb(skb);
return -EINVAL;
}
static int ip6_finish_output(struct sk_buff *skb)
{
if ((skb->len > ip6_skb_dst_mtu(skb) && !skb_is_gso(skb)) ||
dst_allfrag(skb_dst(skb)))
return ip6_fragment(skb, ip6_finish_output2);
else
return ip6_finish_output2(skb);
}
int ip6_output(struct sk_buff *skb)
{
struct net_device *dev = skb_dst(skb)->dev;
struct inet6_dev *idev = ip6_dst_idev(skb_dst(skb));
if (unlikely(idev->cnf.disable_ipv6)) {
IP6_INC_STATS(dev_net(dev), idev,
IPSTATS_MIB_OUTDISCARDS);
kfree_skb(skb);
return 0;
}
return NF_HOOK_COND(NFPROTO_IPV6, NF_INET_POST_ROUTING, skb, NULL, dev,
ip6_finish_output,
!(IP6CB(skb)->flags & IP6SKB_REROUTED));
}
/*
* xmit an sk_buff (used by TCP, SCTP and DCCP)
*/
int ip6_xmit(struct sock *sk, struct sk_buff *skb, struct flowi6 *fl6,
struct ipv6_txoptions *opt, int tclass)
{
struct net *net = sock_net(sk);
struct ipv6_pinfo *np = inet6_sk(sk);
struct in6_addr *first_hop = &fl6->daddr;
struct dst_entry *dst = skb_dst(skb);
struct ipv6hdr *hdr;
u8 proto = fl6->flowi6_proto;
int seg_len = skb->len;
int hlimit = -1;
u32 mtu;
if (opt) {
unsigned int head_room;
/* First: exthdrs may take lots of space (~8K for now)
MAX_HEADER is not enough.
*/
head_room = opt->opt_nflen + opt->opt_flen;
seg_len += head_room;
head_room += sizeof(struct ipv6hdr) + LL_RESERVED_SPACE(dst->dev);
if (skb_headroom(skb) < head_room) {
struct sk_buff *skb2 = skb_realloc_headroom(skb, head_room);
if (skb2 == NULL) {
IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)),
IPSTATS_MIB_OUTDISCARDS);
kfree_skb(skb);
return -ENOBUFS;
}
kfree_skb(skb);
skb = skb2;
skb_set_owner_w(skb, sk);
}
if (opt->opt_flen)
ipv6_push_frag_opts(skb, opt, &proto);
if (opt->opt_nflen)
ipv6_push_nfrag_opts(skb, opt, &proto, &first_hop);
}
skb_push(skb, sizeof(struct ipv6hdr));
skb_reset_network_header(skb);
hdr = ipv6_hdr(skb);
/*
* Fill in the IPv6 header
*/
if (np)
hlimit = np->hop_limit;
if (hlimit < 0)
hlimit = ip6_dst_hoplimit(dst);
*(__be32 *)hdr = htonl(0x60000000 | (tclass << 20)) | fl6->flowlabel;
hdr->payload_len = htons(seg_len);
hdr->nexthdr = proto;
hdr->hop_limit = hlimit;
hdr->saddr = fl6->saddr;
hdr->daddr = *first_hop;
skb->priority = sk->sk_priority;
skb->mark = sk->sk_mark;
mtu = dst_mtu(dst);
if ((skb->len <= mtu) || skb->local_df || skb_is_gso(skb)) {
IP6_UPD_PO_STATS(net, ip6_dst_idev(skb_dst(skb)),
IPSTATS_MIB_OUT, skb->len);
return NF_HOOK(NFPROTO_IPV6, NF_INET_LOCAL_OUT, skb, NULL,
dst->dev, dst_output);
}
if (net_ratelimit())
printk(KERN_DEBUG "IPv6: sending pkt_too_big to self\n");
skb->dev = dst->dev;
icmpv6_send(skb, ICMPV6_PKT_TOOBIG, 0, mtu);
IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)), IPSTATS_MIB_FRAGFAILS);
kfree_skb(skb);
return -EMSGSIZE;
}
EXPORT_SYMBOL(ip6_xmit);
/*
* To avoid extra problems ND packets are send through this
* routine. It's code duplication but I really want to avoid
* extra checks since ipv6_build_header is used by TCP (which
* is for us performance critical)
*/
int ip6_nd_hdr(struct sock *sk, struct sk_buff *skb, struct net_device *dev,
const struct in6_addr *saddr, const struct in6_addr *daddr,
int proto, int len)
{
struct ipv6_pinfo *np = inet6_sk(sk);
struct ipv6hdr *hdr;
skb->protocol = htons(ETH_P_IPV6);
skb->dev = dev;
skb_reset_network_header(skb);
skb_put(skb, sizeof(struct ipv6hdr));
hdr = ipv6_hdr(skb);
*(__be32*)hdr = htonl(0x60000000);
hdr->payload_len = htons(len);
hdr->nexthdr = proto;
hdr->hop_limit = np->hop_limit;
hdr->saddr = *saddr;
hdr->daddr = *daddr;
return 0;
}
static int ip6_call_ra_chain(struct sk_buff *skb, int sel)
{
struct ip6_ra_chain *ra;
struct sock *last = NULL;
read_lock(&ip6_ra_lock);
for (ra = ip6_ra_chain; ra; ra = ra->next) {
struct sock *sk = ra->sk;
if (sk && ra->sel == sel &&
(!sk->sk_bound_dev_if ||
sk->sk_bound_dev_if == skb->dev->ifindex)) {
if (last) {
struct sk_buff *skb2 = skb_clone(skb, GFP_ATOMIC);
if (skb2)
rawv6_rcv(last, skb2);
}
last = sk;
}
}
if (last) {
rawv6_rcv(last, skb);
read_unlock(&ip6_ra_lock);
return 1;
}
read_unlock(&ip6_ra_lock);
return 0;
}
static int ip6_forward_proxy_check(struct sk_buff *skb)
{
struct ipv6hdr *hdr = ipv6_hdr(skb);
u8 nexthdr = hdr->nexthdr;
__be16 frag_off;
int offset;
if (ipv6_ext_hdr(nexthdr)) {
offset = ipv6_skip_exthdr(skb, sizeof(*hdr), &nexthdr, &frag_off);
if (offset < 0)
return 0;
} else
offset = sizeof(struct ipv6hdr);
if (nexthdr == IPPROTO_ICMPV6) {
struct icmp6hdr *icmp6;
if (!pskb_may_pull(skb, (skb_network_header(skb) +
offset + 1 - skb->data)))
return 0;
icmp6 = (struct icmp6hdr *)(skb_network_header(skb) + offset);
switch (icmp6->icmp6_type) {
case NDISC_ROUTER_SOLICITATION:
case NDISC_ROUTER_ADVERTISEMENT:
case NDISC_NEIGHBOUR_SOLICITATION:
case NDISC_NEIGHBOUR_ADVERTISEMENT:
case NDISC_REDIRECT:
/* For reaction involving unicast neighbor discovery
* message destined to the proxied address, pass it to
* input function.
*/
return 1;
default:
break;
}
}
/*
* The proxying router can't forward traffic sent to a link-local
* address, so signal the sender and discard the packet. This
* behavior is clarified by the MIPv6 specification.
*/
if (ipv6_addr_type(&hdr->daddr) & IPV6_ADDR_LINKLOCAL) {
dst_link_failure(skb);
return -1;
}
return 0;
}
static inline int ip6_forward_finish(struct sk_buff *skb)
{
return dst_output(skb);
}
int ip6_forward(struct sk_buff *skb)
{
struct dst_entry *dst = skb_dst(skb);
struct ipv6hdr *hdr = ipv6_hdr(skb);
struct inet6_skb_parm *opt = IP6CB(skb);
struct net *net = dev_net(dst->dev);
u32 mtu;
if (net->ipv6.devconf_all->forwarding == 0)
goto error;
if (skb_warn_if_lro(skb))
goto drop;
if (!xfrm6_policy_check(NULL, XFRM_POLICY_FWD, skb)) {
IP6_INC_STATS(net, ip6_dst_idev(dst), IPSTATS_MIB_INDISCARDS);
goto drop;
}
if (skb->pkt_type != PACKET_HOST)
goto drop;
skb_forward_csum(skb);
/*
* We DO NOT make any processing on
* RA packets, pushing them to user level AS IS
* without ane WARRANTY that application will be able
* to interpret them. The reason is that we
* cannot make anything clever here.
*
* We are not end-node, so that if packet contains
* AH/ESP, we cannot make anything.
* Defragmentation also would be mistake, RA packets
* cannot be fragmented, because there is no warranty
* that different fragments will go along one path. --ANK
*/
if (opt->ra) {
u8 *ptr = skb_network_header(skb) + opt->ra;
if (ip6_call_ra_chain(skb, (ptr[2]<<8) + ptr[3]))
return 0;
}
/*
* check and decrement ttl
*/
if (hdr->hop_limit <= 1) {
/* Force OUTPUT device used as source address */
skb->dev = dst->dev;
icmpv6_send(skb, ICMPV6_TIME_EXCEED, ICMPV6_EXC_HOPLIMIT, 0);
IP6_INC_STATS_BH(net,
ip6_dst_idev(dst), IPSTATS_MIB_INHDRERRORS);
kfree_skb(skb);
return -ETIMEDOUT;
}
/* XXX: idev->cnf.proxy_ndp? */
if ((net->ipv6.devconf_all->proxy_ndp == 1 &&
pneigh_lookup(&nd_tbl, net, &hdr->daddr, skb->dev, 0))
|| net->ipv6.devconf_all->proxy_ndp >= 2) {
int proxied = ip6_forward_proxy_check(skb);
if (proxied > 0)
return ip6_input(skb);
else if (proxied < 0) {
IP6_INC_STATS(net, ip6_dst_idev(dst),
IPSTATS_MIB_INDISCARDS);
goto drop;
}
}
if (!xfrm6_route_forward(skb)) {
IP6_INC_STATS(net, ip6_dst_idev(dst), IPSTATS_MIB_INDISCARDS);
goto drop;
}
dst = skb_dst(skb);
/* IPv6 specs say nothing about it, but it is clear that we cannot
send redirects to source routed frames.
We don't send redirects to frames decapsulated from IPsec.
*/
if (skb->dev == dst->dev && opt->srcrt == 0 && !skb_sec_path(skb)) {
struct in6_addr *target = NULL;
struct rt6_info *rt;
/*
* incoming and outgoing devices are the same
* send a redirect.
*/
rt = (struct rt6_info *) dst;
if (rt->rt6i_flags & RTF_GATEWAY)
target = &rt->rt6i_gateway;
else
target = &hdr->daddr;
if (!rt->rt6i_peer)
rt6_bind_peer(rt, 1);
/* Limit redirects both by destination (here)
and by source (inside ndisc_send_redirect)
*/
if (inet_peer_xrlim_allow(rt->rt6i_peer, 1*HZ))
ndisc_send_redirect(skb, target);
} else {
int addrtype = ipv6_addr_type(&hdr->saddr);
/* This check is security critical. */
if (addrtype == IPV6_ADDR_ANY ||
addrtype & (IPV6_ADDR_MULTICAST | IPV6_ADDR_LOOPBACK))
goto error;
if (addrtype & IPV6_ADDR_LINKLOCAL) {
icmpv6_send(skb, ICMPV6_DEST_UNREACH,
ICMPV6_NOT_NEIGHBOUR, 0);
goto error;
}
}
mtu = dst_mtu(dst);
if (mtu < IPV6_MIN_MTU)
mtu = IPV6_MIN_MTU;
if (skb->len > mtu && !skb_is_gso(skb)) {
/* Again, force OUTPUT device used as source address */
skb->dev = dst->dev;
icmpv6_send(skb, ICMPV6_PKT_TOOBIG, 0, mtu);
IP6_INC_STATS_BH(net,
ip6_dst_idev(dst), IPSTATS_MIB_INTOOBIGERRORS);
IP6_INC_STATS_BH(net,
ip6_dst_idev(dst), IPSTATS_MIB_FRAGFAILS);
kfree_skb(skb);
return -EMSGSIZE;
}
if (skb_cow(skb, dst->dev->hard_header_len)) {
IP6_INC_STATS(net, ip6_dst_idev(dst), IPSTATS_MIB_OUTDISCARDS);
goto drop;
}
hdr = ipv6_hdr(skb);
/* Mangling hops number delayed to point after skb COW */
hdr->hop_limit--;
IP6_INC_STATS_BH(net, ip6_dst_idev(dst), IPSTATS_MIB_OUTFORWDATAGRAMS);
return NF_HOOK(NFPROTO_IPV6, NF_INET_FORWARD, skb, skb->dev, dst->dev,
ip6_forward_finish);
error:
IP6_INC_STATS_BH(net, ip6_dst_idev(dst), IPSTATS_MIB_INADDRERRORS);
drop:
kfree_skb(skb);
return -EINVAL;
}
static void ip6_copy_metadata(struct sk_buff *to, struct sk_buff *from)
{
to->pkt_type = from->pkt_type;
to->priority = from->priority;
to->protocol = from->protocol;
skb_dst_drop(to);
skb_dst_set(to, dst_clone(skb_dst(from)));
to->dev = from->dev;
to->mark = from->mark;
#ifdef CONFIG_NET_SCHED
to->tc_index = from->tc_index;
#endif
nf_copy(to, from);
#if defined(CONFIG_NETFILTER_XT_TARGET_TRACE) || \
defined(CONFIG_NETFILTER_XT_TARGET_TRACE_MODULE)
to->nf_trace = from->nf_trace;
#endif
skb_copy_secmark(to, from);
}
int ip6_find_1stfragopt(struct sk_buff *skb, u8 **nexthdr)
{
u16 offset = sizeof(struct ipv6hdr);
struct ipv6_opt_hdr *exthdr =
(struct ipv6_opt_hdr *)(ipv6_hdr(skb) + 1);
unsigned int packet_len = skb->tail - skb->network_header;
int found_rhdr = 0;
*nexthdr = &ipv6_hdr(skb)->nexthdr;
while (offset + 1 <= packet_len) {
switch (**nexthdr) {
case NEXTHDR_HOP:
break;
case NEXTHDR_ROUTING:
found_rhdr = 1;
break;
case NEXTHDR_DEST:
#if defined(CONFIG_IPV6_MIP6) || defined(CONFIG_IPV6_MIP6_MODULE)
if (ipv6_find_tlv(skb, offset, IPV6_TLV_HAO) >= 0)
break;
#endif
if (found_rhdr)
return offset;
break;
default :
return offset;
}
offset += ipv6_optlen(exthdr);
*nexthdr = &exthdr->nexthdr;
exthdr = (struct ipv6_opt_hdr *)(skb_network_header(skb) +
offset);
}
return offset;
}
void ipv6_select_ident(struct frag_hdr *fhdr, struct rt6_info *rt)
{
static atomic_t ipv6_fragmentation_id;
int ident;
if (rt && !(rt->dst.flags & DST_NOPEER)) {
struct inet_peer *peer;
if (!rt->rt6i_peer)
rt6_bind_peer(rt, 1);
peer = rt->rt6i_peer;
if (peer) {
fhdr->identification = htonl(inet_getid(peer, 0));
return;
}
}
ident = atomic_inc_return(&ipv6_fragmentation_id);
fhdr->identification = htonl(ident);
}
int ip6_fragment(struct sk_buff *skb, int (*output)(struct sk_buff *))
{
struct sk_buff *frag;
struct rt6_info *rt = (struct rt6_info*)skb_dst(skb);
struct ipv6_pinfo *np = skb->sk ? inet6_sk(skb->sk) : NULL;
struct ipv6hdr *tmp_hdr;
struct frag_hdr *fh;
unsigned int mtu, hlen, left, len;
int hroom, troom;
__be32 frag_id = 0;
int ptr, offset = 0, err=0;
u8 *prevhdr, nexthdr = 0;
struct net *net = dev_net(skb_dst(skb)->dev);
hlen = ip6_find_1stfragopt(skb, &prevhdr);
nexthdr = *prevhdr;
mtu = ip6_skb_dst_mtu(skb);
/* We must not fragment if the socket is set to force MTU discovery
* or if the skb it not generated by a local socket.
*/
if (!skb->local_df && skb->len > mtu) {
skb->dev = skb_dst(skb)->dev;
icmpv6_send(skb, ICMPV6_PKT_TOOBIG, 0, mtu);
IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)),
IPSTATS_MIB_FRAGFAILS);
kfree_skb(skb);
return -EMSGSIZE;
}
if (np && np->frag_size < mtu) {
if (np->frag_size)
mtu = np->frag_size;
}
mtu -= hlen + sizeof(struct frag_hdr);
if (skb_has_frag_list(skb)) {
int first_len = skb_pagelen(skb);
struct sk_buff *frag2;
if (first_len - hlen > mtu ||
((first_len - hlen) & 7) ||
skb_cloned(skb))
goto slow_path;
skb_walk_frags(skb, frag) {
/* Correct geometry. */
if (frag->len > mtu ||
((frag->len & 7) && frag->next) ||
skb_headroom(frag) < hlen)
goto slow_path_clean;
/* Partially cloned skb? */
if (skb_shared(frag))
goto slow_path_clean;
BUG_ON(frag->sk);
if (skb->sk) {
frag->sk = skb->sk;
frag->destructor = sock_wfree;
}
skb->truesize -= frag->truesize;
}
err = 0;
offset = 0;
frag = skb_shinfo(skb)->frag_list;
skb_frag_list_init(skb);
/* BUILD HEADER */
*prevhdr = NEXTHDR_FRAGMENT;
tmp_hdr = kmemdup(skb_network_header(skb), hlen, GFP_ATOMIC);
if (!tmp_hdr) {
IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)),
IPSTATS_MIB_FRAGFAILS);
return -ENOMEM;
}
__skb_pull(skb, hlen);
fh = (struct frag_hdr*)__skb_push(skb, sizeof(struct frag_hdr));
__skb_push(skb, hlen);
skb_reset_network_header(skb);
memcpy(skb_network_header(skb), tmp_hdr, hlen);
ipv6_select_ident(fh, rt);
fh->nexthdr = nexthdr;
fh->reserved = 0;
fh->frag_off = htons(IP6_MF);
frag_id = fh->identification;
first_len = skb_pagelen(skb);
skb->data_len = first_len - skb_headlen(skb);
skb->len = first_len;
ipv6_hdr(skb)->payload_len = htons(first_len -
sizeof(struct ipv6hdr));
dst_hold(&rt->dst);
for (;;) {
/* Prepare header of the next frame,
* before previous one went down. */
if (frag) {
frag->ip_summed = CHECKSUM_NONE;
skb_reset_transport_header(frag);
fh = (struct frag_hdr*)__skb_push(frag, sizeof(struct frag_hdr));
__skb_push(frag, hlen);
skb_reset_network_header(frag);
memcpy(skb_network_header(frag), tmp_hdr,
hlen);
offset += skb->len - hlen - sizeof(struct frag_hdr);
fh->nexthdr = nexthdr;
fh->reserved = 0;
fh->frag_off = htons(offset);
if (frag->next != NULL)
fh->frag_off |= htons(IP6_MF);
fh->identification = frag_id;
ipv6_hdr(frag)->payload_len =
htons(frag->len -
sizeof(struct ipv6hdr));
ip6_copy_metadata(frag, skb);
}
err = output(skb);
if(!err)
IP6_INC_STATS(net, ip6_dst_idev(&rt->dst),
IPSTATS_MIB_FRAGCREATES);
if (err || !frag)
break;
skb = frag;
frag = skb->next;
skb->next = NULL;
}
kfree(tmp_hdr);
if (err == 0) {
IP6_INC_STATS(net, ip6_dst_idev(&rt->dst),
IPSTATS_MIB_FRAGOKS);
dst_release(&rt->dst);
return 0;
}
while (frag) {
skb = frag->next;
kfree_skb(frag);
frag = skb;
}
IP6_INC_STATS(net, ip6_dst_idev(&rt->dst),
IPSTATS_MIB_FRAGFAILS);
dst_release(&rt->dst);
return err;
slow_path_clean:
skb_walk_frags(skb, frag2) {
if (frag2 == frag)
break;
frag2->sk = NULL;
frag2->destructor = NULL;
skb->truesize += frag2->truesize;
}
}
slow_path:
left = skb->len - hlen; /* Space per frame */
ptr = hlen; /* Where to start from */
/*
* Fragment the datagram.
*/
*prevhdr = NEXTHDR_FRAGMENT;
hroom = LL_RESERVED_SPACE(rt->dst.dev);
troom = rt->dst.dev->needed_tailroom;
/*
* Keep copying data until we run out.
*/
while(left > 0) {
len = left;
/* IF: it doesn't fit, use 'mtu' - the data space left */
if (len > mtu)
len = mtu;
/* IF: we are not sending up to and including the packet end
then align the next start on an eight byte boundary */
if (len < left) {
len &= ~7;
}
/*
* Allocate buffer.
*/
if ((frag = alloc_skb(len + hlen + sizeof(struct frag_hdr) +
hroom + troom, GFP_ATOMIC)) == NULL) {
NETDEBUG(KERN_INFO "IPv6: frag: no memory for new fragment!\n");
IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)),
IPSTATS_MIB_FRAGFAILS);
err = -ENOMEM;
goto fail;
}
/*
* Set up data on packet
*/
ip6_copy_metadata(frag, skb);
skb_reserve(frag, hroom);
skb_put(frag, len + hlen + sizeof(struct frag_hdr));
skb_reset_network_header(frag);
fh = (struct frag_hdr *)(skb_network_header(frag) + hlen);
frag->transport_header = (frag->network_header + hlen +
sizeof(struct frag_hdr));
/*
* Charge the memory for the fragment to any owner
* it might possess
*/
if (skb->sk)
skb_set_owner_w(frag, skb->sk);
/*
* Copy the packet header into the new buffer.
*/
skb_copy_from_linear_data(skb, skb_network_header(frag), hlen);
/*
* Build fragment header.
*/
fh->nexthdr = nexthdr;
fh->reserved = 0;
if (!frag_id) {
ipv6_select_ident(fh, rt);
frag_id = fh->identification;
} else
fh->identification = frag_id;
/*
* Copy a block of the IP datagram.
*/
if (skb_copy_bits(skb, ptr, skb_transport_header(frag), len))
BUG();
left -= len;
fh->frag_off = htons(offset);
if (left > 0)
fh->frag_off |= htons(IP6_MF);
ipv6_hdr(frag)->payload_len = htons(frag->len -
sizeof(struct ipv6hdr));
ptr += len;
offset += len;
/*
* Put this fragment into the sending queue.
*/
err = output(frag);
if (err)
goto fail;
IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)),
IPSTATS_MIB_FRAGCREATES);
}
IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)),
IPSTATS_MIB_FRAGOKS);
kfree_skb(skb);
return err;
fail:
IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)),
IPSTATS_MIB_FRAGFAILS);
kfree_skb(skb);
return err;
}
static inline int ip6_rt_check(const struct rt6key *rt_key,
const struct in6_addr *fl_addr,
const struct in6_addr *addr_cache)
{
return (rt_key->plen != 128 || !ipv6_addr_equal(fl_addr, &rt_key->addr)) &&
(addr_cache == NULL || !ipv6_addr_equal(fl_addr, addr_cache));
}
static struct dst_entry *ip6_sk_dst_check(struct sock *sk,
struct dst_entry *dst,
const struct flowi6 *fl6)
{
struct ipv6_pinfo *np = inet6_sk(sk);
struct rt6_info *rt;
if (!dst)
goto out;
if (dst->ops->family != AF_INET6) {
dst_release(dst);
return NULL;
}
rt = (struct rt6_info *)dst;
/* Yes, checking route validity in not connected
* case is not very simple. Take into account,
* that we do not support routing by source, TOS,
* and MSG_DONTROUTE --ANK (980726)
*
* 1. ip6_rt_check(): If route was host route,
* check that cached destination is current.
* If it is network route, we still may
* check its validity using saved pointer
* to the last used address: daddr_cache.
* We do not want to save whole address now,
* (because main consumer of this service
* is tcp, which has not this problem),
* so that the last trick works only on connected
* sockets.
* 2. oif also should be the same.
*/
if (ip6_rt_check(&rt->rt6i_dst, &fl6->daddr, np->daddr_cache) ||
#ifdef CONFIG_IPV6_SUBTREES
ip6_rt_check(&rt->rt6i_src, &fl6->saddr, np->saddr_cache) ||
#endif
(fl6->flowi6_oif && fl6->flowi6_oif != dst->dev->ifindex)) {
dst_release(dst);
dst = NULL;
}
out:
return dst;
}
static int ip6_dst_lookup_tail(struct sock *sk,
struct dst_entry **dst, struct flowi6 *fl6)
{
struct net *net = sock_net(sk);
#ifdef CONFIG_IPV6_OPTIMISTIC_DAD
struct neighbour *n;
#endif
int err;
if (*dst == NULL)
*dst = ip6_route_output(net, sk, fl6);
if ((err = (*dst)->error))
goto out_err_release;
if (ipv6_addr_any(&fl6->saddr)) {
struct rt6_info *rt = (struct rt6_info *) *dst;
err = ip6_route_get_saddr(net, rt, &fl6->daddr,
sk ? inet6_sk(sk)->srcprefs : 0,
&fl6->saddr);
if (err)
goto out_err_release;
}
#ifdef CONFIG_IPV6_OPTIMISTIC_DAD
/*
* Here if the dst entry we've looked up
* has a neighbour entry that is in the INCOMPLETE
* state and the src address from the flow is
* marked as OPTIMISTIC, we release the found
* dst entry and replace it instead with the
* dst entry of the nexthop router
*/
rcu_read_lock();
n = dst_get_neighbour_noref(*dst);
if (n && !(n->nud_state & NUD_VALID)) {
struct inet6_ifaddr *ifp;
struct flowi6 fl_gw6;
int redirect;
rcu_read_unlock();
ifp = ipv6_get_ifaddr(net, &fl6->saddr,
(*dst)->dev, 1);
redirect = (ifp && ifp->flags & IFA_F_OPTIMISTIC);
if (ifp)
in6_ifa_put(ifp);
if (redirect) {
/*
* We need to get the dst entry for the
* default router instead
*/
dst_release(*dst);
memcpy(&fl_gw6, fl6, sizeof(struct flowi6));
memset(&fl_gw6.daddr, 0, sizeof(struct in6_addr));
*dst = ip6_route_output(net, sk, &fl_gw6);
if ((err = (*dst)->error))
goto out_err_release;
}
} else {
rcu_read_unlock();
}
#endif
return 0;
out_err_release:
if (err == -ENETUNREACH)
IP6_INC_STATS_BH(net, NULL, IPSTATS_MIB_OUTNOROUTES);
dst_release(*dst);
*dst = NULL;
return err;
}
/**
* ip6_dst_lookup - perform route lookup on flow
* @sk: socket which provides route info
* @dst: pointer to dst_entry * for result
* @fl6: flow to lookup
*
* This function performs a route lookup on the given flow.
*
* It returns zero on success, or a standard errno code on error.
*/
int ip6_dst_lookup(struct sock *sk, struct dst_entry **dst, struct flowi6 *fl6)
{
*dst = NULL;
return ip6_dst_lookup_tail(sk, dst, fl6);
}
EXPORT_SYMBOL_GPL(ip6_dst_lookup);
/**
* ip6_dst_lookup_flow - perform route lookup on flow with ipsec
* @sk: socket which provides route info
* @fl6: flow to lookup
* @final_dst: final destination address for ipsec lookup
* @can_sleep: we are in a sleepable context
*
* This function performs a route lookup on the given flow.
*
* It returns a valid dst pointer on success, or a pointer encoded
* error code.
*/
struct dst_entry *ip6_dst_lookup_flow(struct sock *sk, struct flowi6 *fl6,
const struct in6_addr *final_dst,
bool can_sleep)
{
struct dst_entry *dst = NULL;
int err;
err = ip6_dst_lookup_tail(sk, &dst, fl6);
if (err)
return ERR_PTR(err);
if (final_dst)
fl6->daddr = *final_dst;
if (can_sleep)
fl6->flowi6_flags |= FLOWI_FLAG_CAN_SLEEP;
return xfrm_lookup(sock_net(sk), dst, flowi6_to_flowi(fl6), sk, 0);
}
EXPORT_SYMBOL_GPL(ip6_dst_lookup_flow);
/**
* ip6_sk_dst_lookup_flow - perform socket cached route lookup on flow
* @sk: socket which provides the dst cache and route info
* @fl6: flow to lookup
* @final_dst: final destination address for ipsec lookup
* @can_sleep: we are in a sleepable context
*
* This function performs a route lookup on the given flow with the
* possibility of using the cached route in the socket if it is valid.
* It will take the socket dst lock when operating on the dst cache.
* As a result, this function can only be used in process context.
*
* It returns a valid dst pointer on success, or a pointer encoded
* error code.
*/
struct dst_entry *ip6_sk_dst_lookup_flow(struct sock *sk, struct flowi6 *fl6,
const struct in6_addr *final_dst,
bool can_sleep)
{
struct dst_entry *dst = sk_dst_check(sk, inet6_sk(sk)->dst_cookie);
int err;
dst = ip6_sk_dst_check(sk, dst, fl6);
err = ip6_dst_lookup_tail(sk, &dst, fl6);
if (err)
return ERR_PTR(err);
if (final_dst)
fl6->daddr = *final_dst;
if (can_sleep)
fl6->flowi6_flags |= FLOWI_FLAG_CAN_SLEEP;
return xfrm_lookup(sock_net(sk), dst, flowi6_to_flowi(fl6), sk, 0);
}
EXPORT_SYMBOL_GPL(ip6_sk_dst_lookup_flow);
static inline int ip6_ufo_append_data(struct sock *sk,
int getfrag(void *from, char *to, int offset, int len,
int odd, struct sk_buff *skb),
void *from, int length, int hh_len, int fragheaderlen,
int transhdrlen, int mtu,unsigned int flags,
struct rt6_info *rt)
{
struct sk_buff *skb;
int err;
/* There is support for UDP large send offload by network
* device, so create one single skb packet containing complete
* udp datagram
*/
if ((skb = skb_peek_tail(&sk->sk_write_queue)) == NULL) {
struct frag_hdr fhdr;
skb = sock_alloc_send_skb(sk,
hh_len + fragheaderlen + transhdrlen + 20,
(flags & MSG_DONTWAIT), &err);
if (skb == NULL)
return err;
/* reserve space for Hardware header */
skb_reserve(skb, hh_len);
/* create space for UDP/IP header */
skb_put(skb,fragheaderlen + transhdrlen);
/* initialize network header pointer */
skb_reset_network_header(skb);
/* initialize protocol header pointer */
skb->transport_header = skb->network_header + fragheaderlen;
skb->ip_summed = CHECKSUM_PARTIAL;
skb->csum = 0;
/* Specify the length of each IPv6 datagram fragment.
* It has to be a multiple of 8.
*/
skb_shinfo(skb)->gso_size = (mtu - fragheaderlen -
sizeof(struct frag_hdr)) & ~7;
skb_shinfo(skb)->gso_type = SKB_GSO_UDP;
ipv6_select_ident(&fhdr, rt);
skb_shinfo(skb)->ip6_frag_id = fhdr.identification;
__skb_queue_tail(&sk->sk_write_queue, skb);
}
return skb_append_datato_frags(sk, skb, getfrag, from,
(length - transhdrlen));
}
static inline struct ipv6_opt_hdr *ip6_opt_dup(struct ipv6_opt_hdr *src,
gfp_t gfp)
{
return src ? kmemdup(src, (src->hdrlen + 1) * 8, gfp) : NULL;
}
static inline struct ipv6_rt_hdr *ip6_rthdr_dup(struct ipv6_rt_hdr *src,
gfp_t gfp)
{
return src ? kmemdup(src, (src->hdrlen + 1) * 8, gfp) : NULL;
}
static void ip6_append_data_mtu(unsigned int *mtu,
int *maxfraglen,
unsigned int fragheaderlen,
struct sk_buff *skb,
struct rt6_info *rt,
unsigned int orig_mtu)
{
if (!(rt->dst.flags & DST_XFRM_TUNNEL)) {
if (skb == NULL) {
/* first fragment, reserve header_len */
*mtu = orig_mtu - rt->dst.header_len;
} else {
/*
* this fragment is not first, the headers
* space is regarded as data space.
*/
*mtu = orig_mtu;
}
*maxfraglen = ((*mtu - fragheaderlen) & ~7)
+ fragheaderlen - sizeof(struct frag_hdr);
}
}
int ip6_append_data(struct sock *sk, int getfrag(void *from, char *to,
int offset, int len, int odd, struct sk_buff *skb),
void *from, int length, int transhdrlen,
int hlimit, int tclass, struct ipv6_txoptions *opt, struct flowi6 *fl6,
struct rt6_info *rt, unsigned int flags, int dontfrag)
{
struct inet_sock *inet = inet_sk(sk);
struct ipv6_pinfo *np = inet6_sk(sk);
struct inet_cork *cork;
struct sk_buff *skb, *skb_prev = NULL;
unsigned int maxfraglen, fragheaderlen, mtu, orig_mtu;
int exthdrlen;
int dst_exthdrlen;
int hh_len;
int copy;
int err;
int offset = 0;
int csummode = CHECKSUM_NONE;
__u8 tx_flags = 0;
if (flags&MSG_PROBE)
return 0;
cork = &inet->cork.base;
if (skb_queue_empty(&sk->sk_write_queue)) {
/*
* setup for corking
*/
if (opt) {
if (WARN_ON(np->cork.opt))
return -EINVAL;
np->cork.opt = kzalloc(opt->tot_len, sk->sk_allocation);
if (unlikely(np->cork.opt == NULL))
return -ENOBUFS;
np->cork.opt->tot_len = opt->tot_len;
np->cork.opt->opt_flen = opt->opt_flen;
np->cork.opt->opt_nflen = opt->opt_nflen;
np->cork.opt->dst0opt = ip6_opt_dup(opt->dst0opt,
sk->sk_allocation);
if (opt->dst0opt && !np->cork.opt->dst0opt)
return -ENOBUFS;
np->cork.opt->dst1opt = ip6_opt_dup(opt->dst1opt,
sk->sk_allocation);
if (opt->dst1opt && !np->cork.opt->dst1opt)
return -ENOBUFS;
np->cork.opt->hopopt = ip6_opt_dup(opt->hopopt,
sk->sk_allocation);
if (opt->hopopt && !np->cork.opt->hopopt)
return -ENOBUFS;
np->cork.opt->srcrt = ip6_rthdr_dup(opt->srcrt,
sk->sk_allocation);
if (opt->srcrt && !np->cork.opt->srcrt)
return -ENOBUFS;
/* need source address above miyazawa*/
}
dst_hold(&rt->dst);
cork->dst = &rt->dst;
inet->cork.fl.u.ip6 = *fl6;
np->cork.hop_limit = hlimit;
np->cork.tclass = tclass;
if (rt->dst.flags & DST_XFRM_TUNNEL)
mtu = np->pmtudisc == IPV6_PMTUDISC_PROBE ?
rt->dst.dev->mtu : dst_mtu(&rt->dst);
else
mtu = np->pmtudisc == IPV6_PMTUDISC_PROBE ?
rt->dst.dev->mtu : dst_mtu(rt->dst.path);
if (np->frag_size < mtu) {
if (np->frag_size)
mtu = np->frag_size;
}
cork->fragsize = mtu;
if (dst_allfrag(rt->dst.path))
cork->flags |= IPCORK_ALLFRAG;
cork->length = 0;
sk->sk_sndmsg_page = NULL;
sk->sk_sndmsg_off = 0;
exthdrlen = (opt ? opt->opt_flen : 0);
length += exthdrlen;
transhdrlen += exthdrlen;
dst_exthdrlen = rt->dst.header_len - rt->rt6i_nfheader_len;
} else {
rt = (struct rt6_info *)cork->dst;
fl6 = &inet->cork.fl.u.ip6;
opt = np->cork.opt;
transhdrlen = 0;
exthdrlen = 0;
dst_exthdrlen = 0;
mtu = cork->fragsize;
}
orig_mtu = mtu;
hh_len = LL_RESERVED_SPACE(rt->dst.dev);
fragheaderlen = sizeof(struct ipv6hdr) + rt->rt6i_nfheader_len +
(opt ? opt->opt_nflen : 0);
maxfraglen = ((mtu - fragheaderlen) & ~7) + fragheaderlen - sizeof(struct frag_hdr);
if (mtu <= sizeof(struct ipv6hdr) + IPV6_MAXPLEN) {
if (cork->length + length > sizeof(struct ipv6hdr) + IPV6_MAXPLEN - fragheaderlen) {
ipv6_local_error(sk, EMSGSIZE, fl6, mtu-exthdrlen);
return -EMSGSIZE;
}
}
/* For UDP, check if TX timestamp is enabled */
if (sk->sk_type == SOCK_DGRAM) {
err = sock_tx_timestamp(sk, &tx_flags);
if (err)
goto error;
}
/*
* Let's try using as much space as possible.
* Use MTU if total length of the message fits into the MTU.
* Otherwise, we need to reserve fragment header and
* fragment alignment (= 8-15 octects, in total).
*
* Note that we may need to "move" the data from the tail of
* of the buffer to the new fragment when we split
* the message.
*
* FIXME: It may be fragmented into multiple chunks
* at once if non-fragmentable extension headers
* are too large.
* --yoshfuji
*/
if ((length > mtu) && dontfrag && (sk->sk_protocol == IPPROTO_UDP ||
sk->sk_protocol == IPPROTO_RAW)) {
ipv6_local_rxpmtu(sk, fl6, mtu-exthdrlen);
return -EMSGSIZE;
}
skb = skb_peek_tail(&sk->sk_write_queue);
cork->length += length;
if (((length > mtu) ||
(skb && skb_has_frags(skb))) &&
(sk->sk_protocol == IPPROTO_UDP) &&
(rt->dst.dev->features & NETIF_F_UFO)) {
err = ip6_ufo_append_data(sk, getfrag, from, length,
hh_len, fragheaderlen,
transhdrlen, mtu, flags, rt);
if (err)
goto error;
return 0;
}
if (!skb)
goto alloc_new_skb;
while (length > 0) {
/* Check if the remaining data fits into current packet. */
copy = (cork->length <= mtu && !(cork->flags & IPCORK_ALLFRAG) ? mtu : maxfraglen) - skb->len;
if (copy < length)
copy = maxfraglen - skb->len;
if (copy <= 0) {
char *data;
unsigned int datalen;
unsigned int fraglen;
unsigned int fraggap;
unsigned int alloclen;
alloc_new_skb:
/* There's no room in the current skb */
if (skb)
fraggap = skb->len - maxfraglen;
else
fraggap = 0;
/* update mtu and maxfraglen if necessary */
if (skb == NULL || skb_prev == NULL)
ip6_append_data_mtu(&mtu, &maxfraglen,
fragheaderlen, skb, rt,
orig_mtu);
skb_prev = skb;
/*
* If remaining data exceeds the mtu,
* we know we need more fragment(s).
*/
datalen = length + fraggap;
if (datalen > (cork->length <= mtu && !(cork->flags & IPCORK_ALLFRAG) ? mtu : maxfraglen) - fragheaderlen)
datalen = maxfraglen - fragheaderlen - rt->dst.trailer_len;
if ((flags & MSG_MORE) &&
!(rt->dst.dev->features&NETIF_F_SG))
alloclen = mtu;
else
alloclen = datalen + fragheaderlen;
alloclen += dst_exthdrlen;
if (datalen != length + fraggap) {
/*
* this is not the last fragment, the trailer
* space is regarded as data space.
*/
datalen += rt->dst.trailer_len;
}
alloclen += rt->dst.trailer_len;
fraglen = datalen + fragheaderlen;
/*
* We just reserve space for fragment header.
* Note: this may be overallocation if the message
* (without MSG_MORE) fits into the MTU.
*/
alloclen += sizeof(struct frag_hdr);
if (transhdrlen) {
skb = sock_alloc_send_skb(sk,
alloclen + hh_len,
(flags & MSG_DONTWAIT), &err);
} else {
skb = NULL;
if (atomic_read(&sk->sk_wmem_alloc) <=
2 * sk->sk_sndbuf)
skb = sock_wmalloc(sk,
alloclen + hh_len, 1,
sk->sk_allocation);
if (unlikely(skb == NULL))
err = -ENOBUFS;
else {
/* Only the initial fragment
* is time stamped.
*/
tx_flags = 0;
}
}
if (skb == NULL)
goto error;
/*
* Fill in the control structures
*/
skb->ip_summed = csummode;
skb->csum = 0;
/* reserve for fragmentation and ipsec header */
skb_reserve(skb, hh_len + sizeof(struct frag_hdr) +
dst_exthdrlen);
if (sk->sk_type == SOCK_DGRAM)
skb_shinfo(skb)->tx_flags = tx_flags;
/*
* Find where to start putting bytes
*/
data = skb_put(skb, fraglen);
skb_set_network_header(skb, exthdrlen);
data += fragheaderlen;
skb->transport_header = (skb->network_header +
fragheaderlen);
if (fraggap) {
skb->csum = skb_copy_and_csum_bits(
skb_prev, maxfraglen,
data + transhdrlen, fraggap, 0);
skb_prev->csum = csum_sub(skb_prev->csum,
skb->csum);
data += fraggap;
pskb_trim_unique(skb_prev, maxfraglen);
}
copy = datalen - transhdrlen - fraggap;
if (copy < 0) {
err = -EINVAL;
kfree_skb(skb);
goto error;
} else if (copy > 0 && getfrag(from, data + transhdrlen, offset, copy, fraggap, skb) < 0) {
err = -EFAULT;
kfree_skb(skb);
goto error;
}
offset += copy;
length -= datalen - fraggap;
transhdrlen = 0;
exthdrlen = 0;
dst_exthdrlen = 0;
csummode = CHECKSUM_NONE;
/*
* Put the packet on the pending queue
*/
__skb_queue_tail(&sk->sk_write_queue, skb);
continue;
}
if (copy > length)
copy = length;
if (!(rt->dst.dev->features&NETIF_F_SG)) {
unsigned int off;
off = skb->len;
if (getfrag(from, skb_put(skb, copy),
offset, copy, off, skb) < 0) {
__skb_trim(skb, off);
err = -EFAULT;
goto error;
}
} else {
int i = skb_shinfo(skb)->nr_frags;
skb_frag_t *frag = &skb_shinfo(skb)->frags[i-1];
struct page *page = sk->sk_sndmsg_page;
int off = sk->sk_sndmsg_off;
unsigned int left;
if (page && (left = PAGE_SIZE - off) > 0) {
if (copy >= left)
copy = left;
if (page != skb_frag_page(frag)) {
if (i == MAX_SKB_FRAGS) {
err = -EMSGSIZE;
goto error;
}
skb_fill_page_desc(skb, i, page, sk->sk_sndmsg_off, 0);
skb_frag_ref(skb, i);
frag = &skb_shinfo(skb)->frags[i];
}
} else if(i < MAX_SKB_FRAGS) {
if (copy > PAGE_SIZE)
copy = PAGE_SIZE;
page = alloc_pages(sk->sk_allocation, 0);
if (page == NULL) {
err = -ENOMEM;
goto error;
}
sk->sk_sndmsg_page = page;
sk->sk_sndmsg_off = 0;
skb_fill_page_desc(skb, i, page, 0, 0);
frag = &skb_shinfo(skb)->frags[i];
} else {
err = -EMSGSIZE;
goto error;
}
if (getfrag(from,
skb_frag_address(frag) + skb_frag_size(frag),
offset, copy, skb->len, skb) < 0) {
err = -EFAULT;
goto error;
}
sk->sk_sndmsg_off += copy;
skb_frag_size_add(frag, copy);
skb->len += copy;
skb->data_len += copy;
skb->truesize += copy;
atomic_add(copy, &sk->sk_wmem_alloc);
}
offset += copy;
length -= copy;
}
return 0;
error:
cork->length -= length;
IP6_INC_STATS(sock_net(sk), rt->rt6i_idev, IPSTATS_MIB_OUTDISCARDS);
return err;
}
static void ip6_cork_release(struct inet_sock *inet, struct ipv6_pinfo *np)
{
if (np->cork.opt) {
kfree(np->cork.opt->dst0opt);
kfree(np->cork.opt->dst1opt);
kfree(np->cork.opt->hopopt);
kfree(np->cork.opt->srcrt);
kfree(np->cork.opt);
np->cork.opt = NULL;
}
if (inet->cork.base.dst) {
dst_release(inet->cork.base.dst);
inet->cork.base.dst = NULL;
inet->cork.base.flags &= ~IPCORK_ALLFRAG;
}
memset(&inet->cork.fl, 0, sizeof(inet->cork.fl));
}
int ip6_push_pending_frames(struct sock *sk)
{
struct sk_buff *skb, *tmp_skb;
struct sk_buff **tail_skb;
struct in6_addr final_dst_buf, *final_dst = &final_dst_buf;
struct inet_sock *inet = inet_sk(sk);
struct ipv6_pinfo *np = inet6_sk(sk);
struct net *net = sock_net(sk);
struct ipv6hdr *hdr;
struct ipv6_txoptions *opt = np->cork.opt;
struct rt6_info *rt = (struct rt6_info *)inet->cork.base.dst;
struct flowi6 *fl6 = &inet->cork.fl.u.ip6;
unsigned char proto = fl6->flowi6_proto;
int err = 0;
if ((skb = __skb_dequeue(&sk->sk_write_queue)) == NULL)
goto out;
tail_skb = &(skb_shinfo(skb)->frag_list);
/* move skb->data to ip header from ext header */
if (skb->data < skb_network_header(skb))
__skb_pull(skb, skb_network_offset(skb));
while ((tmp_skb = __skb_dequeue(&sk->sk_write_queue)) != NULL) {
__skb_pull(tmp_skb, skb_network_header_len(skb));
*tail_skb = tmp_skb;
tail_skb = &(tmp_skb->next);
skb->len += tmp_skb->len;
skb->data_len += tmp_skb->len;
skb->truesize += tmp_skb->truesize;
tmp_skb->destructor = NULL;
tmp_skb->sk = NULL;
}
/* Allow local fragmentation. */
if (np->pmtudisc < IPV6_PMTUDISC_DO)
skb->local_df = 1;
*final_dst = fl6->daddr;
__skb_pull(skb, skb_network_header_len(skb));
if (opt && opt->opt_flen)
ipv6_push_frag_opts(skb, opt, &proto);
if (opt && opt->opt_nflen)
ipv6_push_nfrag_opts(skb, opt, &proto, &final_dst);
skb_push(skb, sizeof(struct ipv6hdr));
skb_reset_network_header(skb);
hdr = ipv6_hdr(skb);
*(__be32*)hdr = fl6->flowlabel |
htonl(0x60000000 | ((int)np->cork.tclass << 20));
hdr->hop_limit = np->cork.hop_limit;
hdr->nexthdr = proto;
hdr->saddr = fl6->saddr;
hdr->daddr = *final_dst;
skb->priority = sk->sk_priority;
skb->mark = sk->sk_mark;
skb_dst_set(skb, dst_clone(&rt->dst));
IP6_UPD_PO_STATS(net, rt->rt6i_idev, IPSTATS_MIB_OUT, skb->len);
if (proto == IPPROTO_ICMPV6) {
struct inet6_dev *idev = ip6_dst_idev(skb_dst(skb));
ICMP6MSGOUT_INC_STATS(net, idev, icmp6_hdr(skb)->icmp6_type);
ICMP6_INC_STATS(net, idev, ICMP6_MIB_OUTMSGS);
}
err = ip6_local_out(skb);
if (err) {
if (err > 0)
err = net_xmit_errno(err);
if (err)
goto error;
}
out:
ip6_cork_release(inet, np);
return err;
error:
IP6_INC_STATS(net, rt->rt6i_idev, IPSTATS_MIB_OUTDISCARDS);
goto out;
}
void ip6_flush_pending_frames(struct sock *sk)
{
struct sk_buff *skb;
while ((skb = __skb_dequeue_tail(&sk->sk_write_queue)) != NULL) {
if (skb_dst(skb))
IP6_INC_STATS(sock_net(sk), ip6_dst_idev(skb_dst(skb)),
IPSTATS_MIB_OUTDISCARDS);
kfree_skb(skb);
}
ip6_cork_release(inet_sk(sk), inet6_sk(sk));
}
| gpl-2.0 |
rhuitl/uClinux | user/samba/source/tdb/common/freelist.c | 9268 | /*
Unix SMB/CIFS implementation.
trivial database library
Copyright (C) Andrew Tridgell 1999-2005
Copyright (C) Paul `Rusty' Russell 2000
Copyright (C) Jeremy Allison 2000-2003
** NOTE! The following LGPL license applies to the tdb
** library. This does NOT imply that all of Samba is released
** under the LGPL
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "tdb_private.h"
/* read a freelist record and check for simple errors */
int rec_free_read(struct tdb_context *tdb, tdb_off_t off, struct list_struct *rec)
{
if (tdb->methods->tdb_read(tdb, off, rec, sizeof(*rec),DOCONV()) == -1)
return -1;
if (rec->magic == TDB_MAGIC) {
/* this happens when a app is showdown while deleting a record - we should
not completely fail when this happens */
TDB_LOG((tdb, TDB_DEBUG_WARNING, "rec_free_read non-free magic 0x%x at offset=%d - fixing\n",
rec->magic, off));
rec->magic = TDB_FREE_MAGIC;
if (tdb->methods->tdb_write(tdb, off, rec, sizeof(*rec)) == -1)
return -1;
}
if (rec->magic != TDB_FREE_MAGIC) {
/* Ensure ecode is set for log fn. */
tdb->ecode = TDB_ERR_CORRUPT;
TDB_LOG((tdb, TDB_DEBUG_WARNING, "rec_free_read bad magic 0x%x at offset=%d\n",
rec->magic, off));
return TDB_ERRCODE(TDB_ERR_CORRUPT, -1);
}
if (tdb->methods->tdb_oob(tdb, rec->next+sizeof(*rec), 0) != 0)
return -1;
return 0;
}
/* Remove an element from the freelist. Must have alloc lock. */
static int remove_from_freelist(struct tdb_context *tdb, tdb_off_t off, tdb_off_t next)
{
tdb_off_t last_ptr, i;
/* read in the freelist top */
last_ptr = FREELIST_TOP;
while (tdb_ofs_read(tdb, last_ptr, &i) != -1 && i != 0) {
if (i == off) {
/* We've found it! */
return tdb_ofs_write(tdb, last_ptr, &next);
}
/* Follow chain (next offset is at start of record) */
last_ptr = i;
}
TDB_LOG((tdb, TDB_DEBUG_FATAL,"remove_from_freelist: not on list at off=%d\n", off));
return TDB_ERRCODE(TDB_ERR_CORRUPT, -1);
}
/* update a record tailer (must hold allocation lock) */
static int update_tailer(struct tdb_context *tdb, tdb_off_t offset,
const struct list_struct *rec)
{
tdb_off_t totalsize;
/* Offset of tailer from record header */
totalsize = sizeof(*rec) + rec->rec_len;
return tdb_ofs_write(tdb, offset + totalsize - sizeof(tdb_off_t),
&totalsize);
}
/* Add an element into the freelist. Merge adjacent records if
neccessary. */
int tdb_free(struct tdb_context *tdb, tdb_off_t offset, struct list_struct *rec)
{
tdb_off_t right, left;
/* Allocation and tailer lock */
if (tdb_lock(tdb, -1, F_WRLCK) != 0)
return -1;
/* set an initial tailer, so if we fail we don't leave a bogus record */
if (update_tailer(tdb, offset, rec) != 0) {
TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_free: update_tailer failed!\n"));
goto fail;
}
/* Look right first (I'm an Australian, dammit) */
right = offset + sizeof(*rec) + rec->rec_len;
if (right + sizeof(*rec) <= tdb->map_size) {
struct list_struct r;
if (tdb->methods->tdb_read(tdb, right, &r, sizeof(r), DOCONV()) == -1) {
TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_free: right read failed at %u\n", right));
goto left;
}
/* If it's free, expand to include it. */
if (r.magic == TDB_FREE_MAGIC) {
if (remove_from_freelist(tdb, right, r.next) == -1) {
TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_free: right free failed at %u\n", right));
goto left;
}
rec->rec_len += sizeof(r) + r.rec_len;
}
}
left:
/* Look left */
left = offset - sizeof(tdb_off_t);
if (left > TDB_DATA_START(tdb->header.hash_size)) {
struct list_struct l;
tdb_off_t leftsize;
/* Read in tailer and jump back to header */
if (tdb_ofs_read(tdb, left, &leftsize) == -1) {
TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_free: left offset read failed at %u\n", left));
goto update;
}
/* it could be uninitialised data */
if (leftsize == 0 || leftsize == TDB_PAD_U32) {
goto update;
}
left = offset - leftsize;
/* Now read in record */
if (tdb->methods->tdb_read(tdb, left, &l, sizeof(l), DOCONV()) == -1) {
TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_free: left read failed at %u (%u)\n", left, leftsize));
goto update;
}
/* If it's free, expand to include it. */
if (l.magic == TDB_FREE_MAGIC) {
if (remove_from_freelist(tdb, left, l.next) == -1) {
TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_free: left free failed at %u\n", left));
goto update;
} else {
offset = left;
rec->rec_len += leftsize;
}
}
}
update:
if (update_tailer(tdb, offset, rec) == -1) {
TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_free: update_tailer failed at %u\n", offset));
goto fail;
}
/* Now, prepend to free list */
rec->magic = TDB_FREE_MAGIC;
if (tdb_ofs_read(tdb, FREELIST_TOP, &rec->next) == -1 ||
tdb_rec_write(tdb, offset, rec) == -1 ||
tdb_ofs_write(tdb, FREELIST_TOP, &offset) == -1) {
TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_free record write failed at offset=%d\n", offset));
goto fail;
}
/* And we're done. */
tdb_unlock(tdb, -1, F_WRLCK);
return 0;
fail:
tdb_unlock(tdb, -1, F_WRLCK);
return -1;
}
/*
the core of tdb_allocate - called when we have decided which
free list entry to use
*/
static tdb_off_t tdb_allocate_ofs(struct tdb_context *tdb, tdb_len_t length, tdb_off_t rec_ptr,
struct list_struct *rec, tdb_off_t last_ptr)
{
struct list_struct newrec;
tdb_off_t newrec_ptr;
memset(&newrec, '\0', sizeof(newrec));
/* found it - now possibly split it up */
if (rec->rec_len > length + MIN_REC_SIZE) {
/* Length of left piece */
length = TDB_ALIGN(length, TDB_ALIGNMENT);
/* Right piece to go on free list */
newrec.rec_len = rec->rec_len - (sizeof(*rec) + length);
newrec_ptr = rec_ptr + sizeof(*rec) + length;
/* And left record is shortened */
rec->rec_len = length;
} else {
newrec_ptr = 0;
}
/* Remove allocated record from the free list */
if (tdb_ofs_write(tdb, last_ptr, &rec->next) == -1) {
return 0;
}
/* Update header: do this before we drop alloc
lock, otherwise tdb_free() might try to
merge with us, thinking we're free.
(Thanks Jeremy Allison). */
rec->magic = TDB_MAGIC;
if (tdb_rec_write(tdb, rec_ptr, rec) == -1) {
return 0;
}
/* Did we create new block? */
if (newrec_ptr) {
/* Update allocated record tailer (we
shortened it). */
if (update_tailer(tdb, rec_ptr, rec) == -1) {
return 0;
}
/* Free new record */
if (tdb_free(tdb, newrec_ptr, &newrec) == -1) {
return 0;
}
}
/* all done - return the new record offset */
return rec_ptr;
}
/* allocate some space from the free list. The offset returned points
to a unconnected list_struct within the database with room for at
least length bytes of total data
0 is returned if the space could not be allocated
*/
tdb_off_t tdb_allocate(struct tdb_context *tdb, tdb_len_t length, struct list_struct *rec)
{
tdb_off_t rec_ptr, last_ptr, newrec_ptr;
struct {
tdb_off_t rec_ptr, last_ptr;
tdb_len_t rec_len;
} bestfit;
if (tdb_lock(tdb, -1, F_WRLCK) == -1)
return 0;
/* Extra bytes required for tailer */
length += sizeof(tdb_off_t);
again:
last_ptr = FREELIST_TOP;
/* read in the freelist top */
if (tdb_ofs_read(tdb, FREELIST_TOP, &rec_ptr) == -1)
goto fail;
bestfit.rec_ptr = 0;
bestfit.last_ptr = 0;
bestfit.rec_len = 0;
/*
this is a best fit allocation strategy. Originally we used
a first fit strategy, but it suffered from massive fragmentation
issues when faced with a slowly increasing record size.
*/
while (rec_ptr) {
if (rec_free_read(tdb, rec_ptr, rec) == -1) {
goto fail;
}
if (rec->rec_len >= length) {
if (bestfit.rec_ptr == 0 ||
rec->rec_len < bestfit.rec_len) {
bestfit.rec_len = rec->rec_len;
bestfit.rec_ptr = rec_ptr;
bestfit.last_ptr = last_ptr;
/* consider a fit to be good enough if
we aren't wasting more than half
the space */
if (bestfit.rec_len < 2*length) {
break;
}
}
}
/* move to the next record */
last_ptr = rec_ptr;
rec_ptr = rec->next;
}
if (bestfit.rec_ptr != 0) {
if (rec_free_read(tdb, bestfit.rec_ptr, rec) == -1) {
goto fail;
}
newrec_ptr = tdb_allocate_ofs(tdb, length, bestfit.rec_ptr, rec, bestfit.last_ptr);
tdb_unlock(tdb, -1, F_WRLCK);
return newrec_ptr;
}
/* we didn't find enough space. See if we can expand the
database and if we can then try again */
if (tdb_expand(tdb, length + sizeof(*rec)) == 0)
goto again;
fail:
tdb_unlock(tdb, -1, F_WRLCK);
return 0;
}
| gpl-2.0 |
FashionFreedom/Seamly2D | share/translations/measurements_p8_it_IT.ts | 231740 | <?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.1" language="it_IT">
<context>
<name>VTranslateMeasurements</name>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="190"/>
<source>height</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation>altezza</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="192"/>
<source>Height: Total</source>
<comment>Full measurement name.</comment>
<translation>Altezza: Total</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="193"/>
<source>Vertical distance from crown of head to floor.</source>
<comment>Full measurement description.</comment>
<translation>Distanza verticale dalla parte superiore della testa al pavimento.</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="197"/>
<source>height_neck_back</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation>altezza_collo_dietro</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="199"/>
<source>Height: Neck Back</source>
<comment>Full measurement name.</comment>
<translation>Altezza: Collo Dietro</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="200"/>
<source>Vertical distance from the Neck Back (cervicale vertebra) to the floor.</source>
<comment>Full measurement description.</comment>
<translation>Distanza verticale da Collo Dietro (vertebra cervicale) al pavimento.</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="204"/>
<source>height_scapula</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation>altezza_scapola</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="206"/>
<source>Height: Scapula</source>
<comment>Full measurement name.</comment>
<translation>Altezza: Scapola</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="207"/>
<source>Vertical distance from the Scapula (Blade point) to the floor.</source>
<comment>Full measurement description.</comment>
<translation>Distanza verticale dalla Scapola (punto più esterno della scapola) al pavimento.</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="211"/>
<source>height_armpit</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation>altezza_ascella</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="213"/>
<source>Height: Armpit</source>
<comment>Full measurement name.</comment>
<translation>Altezza: Ascella</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="214"/>
<source>Vertical distance from the Armpit to the floor.</source>
<comment>Full measurement description.</comment>
<translation>Distanza verticale dall'Ascella al pavimento.</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="218"/>
<source>height_waist_side</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation>altezza_vita_fianco</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="220"/>
<source>Height: Waist Side</source>
<comment>Full measurement name.</comment>
<translation>Altezza: Vita Fianco</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="221"/>
<source>Vertical distance from the Waist Side to the floor.</source>
<comment>Full measurement description.</comment>
<translation>Distanza verticale dal Fianco Vita al pavimento.</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="225"/>
<source>height_hip</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation>altezza_anca</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="227"/>
<source>Height: Hip</source>
<comment>Full measurement name.</comment>
<translation>Altezza: Anca</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="228"/>
<source>Vertical distance from the Hip level to the floor.</source>
<comment>Full measurement description.</comment>
<translation>Distanza verticale dal livello Anca al pavimento.</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="232"/>
<source>height_gluteal_fold</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation>altezza_piega_gluteo</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="234"/>
<source>Height: Gluteal Fold</source>
<comment>Full measurement name.</comment>
<translation>Altezza: Piega Gluteo</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="235"/>
<source>Vertical distance from the Gluteal fold, where the Gluteal muscle meets the top of the back thigh, to the floor.</source>
<comment>Full measurement description.</comment>
<translation>Distanza verticale dalla piega del Gluteo, dove il muscolo del Gluteo incontra la parte superiore della coscia dietro, al pavimento.</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="239"/>
<source>height_knee</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation>altezza_ginocchio</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="241"/>
<source>Height: Knee</source>
<comment>Full measurement name.</comment>
<translation>Altezza: Ginocchio</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="242"/>
<source>Vertical distance from the fold at the back of the Knee to the floor.</source>
<comment>Full measurement description.</comment>
<translation>Distanza verticale dalla piega dietro il ginocchio al pavimento.</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="246"/>
<source>height_calf</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation>altezza_polpaccio</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="248"/>
<source>Height: Calf</source>
<comment>Full measurement name.</comment>
<translation>Altezza: Polpaccio</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="249"/>
<source>Vertical distance from the widest point of the calf to the floor.</source>
<comment>Full measurement description.</comment>
<translation>Distanza verticale dal punto più ampio del polpaccio al pavimento.</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="253"/>
<source>height_ankle_high</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation>altezza_caviglia_alto</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="255"/>
<source>Height: Ankle High</source>
<comment>Full measurement name.</comment>
<translation>Altezza: Caviglia Alta</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="256"/>
<source>Vertical distance from the deepest indentation of the back of the ankle to the floor.</source>
<comment>Full measurement description.</comment>
<translation>Distanza verticale dal rientro più profondo della parte posteriore della caviglia al pavimento .</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="260"/>
<source>height_ankle</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation>altezza_caviglia</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="262"/>
<source>Height: Ankle</source>
<comment>Full measurement name.</comment>
<translation>Altezza: Caviglia</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="263"/>
<source>Vertical distance from point where the front leg meets the foot to the floor.</source>
<comment>Full measurement description.</comment>
<translation>Distanza verticale dal punto dove la gamba di fronte incontra il piede al pavimento.</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="267"/>
<source>height_highhip</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation>altezza_ancasuperiore</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="269"/>
<source>Height: Highhip</source>
<comment>Full measurement name.</comment>
<translation>Altezza: Anca superiore</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="270"/>
<source>Vertical distance from the Highhip level, where front abdomen is most prominent, to the floor.</source>
<comment>Full measurement description.</comment>
<translation>Distanza verticale dal livello superiore Anca, dove l'addome anteriore è più sporgente, al pavimento.</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="274"/>
<source>height_waist_front</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation>altezza_vita_davanti</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="276"/>
<source>Height: Waist Front</source>
<comment>Full measurement name.</comment>
<translation>Altezza: Vita Davanti</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="277"/>
<source>Vertical distance from the Waist Front to the floor.</source>
<comment>Full measurement description.</comment>
<translation>Distanza verticale dalla Vita Davanti al pavimento.</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="281"/>
<source>height_bustpoint</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation>altezza_seno</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="283"/>
<source>Height: Bustpoint</source>
<comment>Full measurement name.</comment>
<translation>Altezza: Seno</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="284"/>
<source>Vertical distance from Bustpoint to the floor.</source>
<comment>Full measurement description.</comment>
<translation>Distanza verticale dal Seno al pavimento.</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="288"/>
<source>height_shoulder_tip</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation>altezza_spalla_punta</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="290"/>
<source>Height: Shoulder Tip</source>
<comment>Full measurement name.</comment>
<translation>Altezza: Punta Spalla</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="291"/>
<source>Vertical distance from the Shoulder Tip to the floor.</source>
<comment>Full measurement description.</comment>
<translation>Distanza verticale dalla Punta della Spalla al pavimento.</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="295"/>
<source>height_neck_front</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation>altezza_collo_fronte</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="297"/>
<source>Height: Neck Front</source>
<comment>Full measurement name.</comment>
<translation>Altezza: Collo Fronte</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="298"/>
<source>Vertical distance from the Neck Front to the floor.</source>
<comment>Full measurement description.</comment>
<translation>Distanza verticale dal Collo Davanti al pavimento.</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="302"/>
<source>height_neck_side</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation>altezza_lato_collo</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="304"/>
<source>Height: Neck Side</source>
<comment>Full measurement name.</comment>
<translation>Altezza: Lato Collo</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="305"/>
<source>Vertical distance from the Neck Side to the floor.</source>
<comment>Full measurement description.</comment>
<translation>Distanza verticale dal Lato Collo al pavimento.</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="309"/>
<source>height_neck_back_to_knee</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation>altezza_collo_dietro_al_ginocchio</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="311"/>
<source>Height: Neck Back to Knee</source>
<comment>Full measurement name.</comment>
<translation>Altezza: Collo Dietro al Ginocchio</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="312"/>
<source>Vertical distance from the Neck Back (cervicale vertebra) to the fold at the back of the knee.</source>
<comment>Full measurement description.</comment>
<translation>Distanza verticale dal Collo Dietro (vertebra cervicale) alla piega dietro del ginocchio.</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="316"/>
<source>height_waist_side_to_knee</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation>altezza_lato_vita_al_ginocchio</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="318"/>
<source>Height: Waist Side to Knee</source>
<comment>Full measurement name.</comment>
<translation>Altezza: Lato Vita al Ginocchio</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="319"/>
<source>Vertical distance from the Waist Side to the fold at the back of the knee.</source>
<comment>Full measurement description.</comment>
<translation>Distanza verticale dal Lato Vita alla piega dietro al ginocchio.</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="324"/>
<source>height_waist_side_to_hip</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation>altezza_lato_vita_al_fianco</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="326"/>
<source>Height: Waist Side to Hip</source>
<comment>Full measurement name.</comment>
<translation>Altezza: Lato Vita al Fianco</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="327"/>
<source>Vertical distance from the Waist Side to the Hip level.</source>
<comment>Full measurement description.</comment>
<translation>Distanza verticale dal Lato Vita al Livello Fianco.</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="331"/>
<source>height_knee_to_ankle</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation>altezza_ginocchio_ad_anca</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="333"/>
<source>Height: Knee to Ankle</source>
<comment>Full measurement name.</comment>
<translation>Altezza: Ginocchio all'Anca</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="334"/>
<source>Vertical distance from the fold at the back of the knee to the point where the front leg meets the top of the foot.</source>
<comment>Full measurement description.</comment>
<translation>Distanza verticale dalla piega dietro del ginocchio al punto dove la parte frontale della gamba incontra la parte superiore del piede.</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="338"/>
<source>height_neck_back_to_waist_side</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation>altezza_collo_dietro_al_lato_vita</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="340"/>
<source>Height: Neck Back to Waist Side</source>
<comment>Full measurement name.</comment>
<translation>Altezza: Collo Dietro al Lato Vita</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="341"/>
<source>Vertical distance from Neck Back to Waist Side. ('Height: Neck Back' - 'Height: Waist Side').</source>
<comment>Full measurement description.</comment>
<translation>Distanza verticale dal Collo Dietro al Lato Vita. ('Altezza:Collo Dietro'-'Altezza:Lato Vita').</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="364"/>
<source>width_shoulder</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation>larghezza_spalla</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="366"/>
<source>Width: Shoulder</source>
<comment>Full measurement name.</comment>
<translation>Larghezza: Spalla</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="367"/>
<source>Horizontal distance from Shoulder Tip to Shoulder Tip.</source>
<comment>Full measurement description.</comment>
<translation>Distanza orizzontale da una Punta della Spalla all'altra Punta della Spalla.</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="371"/>
<source>width_bust</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation>larghezza_busto</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="373"/>
<source>Width: Bust</source>
<comment>Full measurement name.</comment>
<translation>Larghezza: Busto</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="374"/>
<source>Horizontal distance from Bust Side to Bust Side.</source>
<comment>Full measurement description.</comment>
<translation>Distanza orizzontale da Fianco a Fianco del Busto. </translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="378"/>
<source>width_waist</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation>larghezza_vita</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="380"/>
<source>Width: Waist</source>
<comment>Full measurement name.</comment>
<translation>Larghezza: Vita</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="381"/>
<source>Horizontal distance from Waist Side to Waist Side.</source>
<comment>Full measurement description.</comment>
<translation>Distanza orizzontale da Fianco a Fianco della Vita.</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="385"/>
<source>width_hip</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation>larghezza_anca</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="387"/>
<source>Width: Hip</source>
<comment>Full measurement name.</comment>
<translation>Larghezza: Anca</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="388"/>
<source>Horizontal distance from Hip Side to Hip Side.</source>
<comment>Full measurement description.</comment>
<translation>Distanza orizzontale dal Fianco a Fianco dell'Anca.</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="392"/>
<source>width_abdomen_to_hip</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation>larghezza_ventre_a_anca</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="394"/>
<source>Width: Abdomen to Hip</source>
<comment>Full measurement name.</comment>
<translation>Larghezza:Ventre ad Anca</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="395"/>
<source>Horizontal distance from the greatest abdomen prominence to the greatest hip prominence.</source>
<comment>Full measurement description.</comment>
<translation>Distanza orizzontale dal punto più esterno dell'addome fino al punto più prominente dei fianchi.</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="411"/>
<source>indent_neck_back</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation>tacca_collo_dietro</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="413"/>
<source>Indent: Neck Back</source>
<comment>Full measurement name.</comment>
<translation>Tacca: Collo Dietro</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="414"/>
<source>Horizontal distance from Scapula (Blade point) to the Neck Back.</source>
<comment>Full measurement description.</comment>
<translation>Distanza orizzontale tra Scapola (punto più esterno) al Collo Dietro.</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="418"/>
<source>indent_waist_back</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation>tacca_vita_dietro</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="420"/>
<source>Indent: Waist Back</source>
<comment>Full measurement name.</comment>
<translation>Tacca: Vita Dietro</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="421"/>
<source>Horizontal distance between a flat stick, placed to touch Hip and Scapula, and Waist Back.</source>
<comment>Full measurement description.</comment>
<translation>Distanza orizzontale tra un bastoncino piatto, posto a toccare anca e scapola, e vita posteriore.</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="425"/>
<source>indent_ankle_high</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation>tacca_caviglia_alta</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="427"/>
<source>Indent: Ankle High</source>
<comment>Full measurement name.</comment>
<translation>Tacca: Caviglia Alta</translation>
</message>
<message>
<source>Horizontal Distance betwee a flat stick, placed perpendicular to Heel, and the greatest indentation of Ankle.</source>
<comment>Full measurement description.</comment>
<translation type="vanished">Distanza orizzontale tra un bastoncino piatto, posto perpendicolare al tallone e la rientranza più profonda della caviglia.</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="444"/>
<source>hand_palm_length</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation>lunghezza_palmo_mano</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="446"/>
<source>Hand: Palm length</source>
<comment>Full measurement name.</comment>
<translation>Mano: lunghezza palmo</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="447"/>
<source>Length from Wrist line to base of middle finger.</source>
<comment>Full measurement description.</comment>
<translation>Lunghezza dalla linea del polso alla base del dito medio.</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="451"/>
<source>hand_length</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation>lunghezza_mano</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="453"/>
<source>Hand: Length</source>
<comment>Full measurement name.</comment>
<translation>Mano: Lunghezza</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="454"/>
<source>Length from Wrist line to end of middle finger.</source>
<comment>Full measurement description.</comment>
<translation>Lunghezza dalla linea del Polso alla fine del dito medio.</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="458"/>
<source>hand_palm_width</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation>larghezza_palmo_mano</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="460"/>
<source>Hand: Palm width</source>
<comment>Full measurement name.</comment>
<translation>Mano: larghezza Palmo</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="461"/>
<source>Measure where Palm is widest.</source>
<comment>Full measurement description.</comment>
<translation>Misura dove il palmo è più largo.</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="464"/>
<source>hand_palm_circ</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation>circonferenza_palmo_mano</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="466"/>
<source>Hand: Palm circumference</source>
<comment>Full measurement name.</comment>
<translation>Mano: circonferenza Palmo</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="467"/>
<source>Circumference where Palm is widest.</source>
<comment>Full measurement description.</comment>
<translation>Circonferenza dove il palmo è più largo.</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="470"/>
<source>hand_circ</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation>circ_mano</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="472"/>
<source>Hand: Circumference</source>
<comment>Full measurement name.</comment>
<translation>Mano: Circonferenza</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="473"/>
<source>Tuck thumb toward smallest finger, bring fingers close together. Measure circumference around widest part of hand.</source>
<comment>Full measurement description.</comment>
<translation>Piega il pollice verso il dito più piccolo, avvicina le dita. Misura la circonferenza attorno alla parte più larga della mano.</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="489"/>
<source>foot_width</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation>larghezza_piede</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="491"/>
<source>Foot: Width</source>
<comment>Full measurement name.</comment>
<translation>Piede: Larghezza</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="492"/>
<source>Measure at widest part of foot.</source>
<comment>Full measurement description.</comment>
<translation>Misura della parte più larga del piede.</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="495"/>
<source>foot_length</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation>lunghezza_piede</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="497"/>
<source>Foot: Length</source>
<comment>Full measurement name.</comment>
<translation>Piede: Lunghezza</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="498"/>
<source>Measure from back of heel to end of longest toe.</source>
<comment>Full measurement description.</comment>
<translation>Misura dal retro del tallone alla fine del dito del piede più lungo.</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="502"/>
<source>foot_circ</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation>circ_piede</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="504"/>
<source>Foot: Circumference</source>
<comment>Full measurement name.</comment>
<translation>Piede: Circonferenza</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="505"/>
<source>Measure circumference around widest part of foot.</source>
<comment>Full measurement description.</comment>
<translation>Misura circonferenza attorno alla parte del piede più larga.</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="509"/>
<source>foot_instep_circ</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation>collodel_piede_circ</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="511"/>
<source>Foot: Instep circumference</source>
<comment>Full measurement name.</comment>
<translation>Piede: collo del piede circonferenza</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="512"/>
<source>Measure circumference at tallest part of instep.</source>
<comment>Full measurement description.</comment>
<translation>Misura circonferenza alla parte più alta del collo del piede.</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="528"/>
<source>head_circ</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation>testa_circ</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="530"/>
<source>Head: Circumference</source>
<comment>Full measurement name.</comment>
<translation>Testa: Circonferenza</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="531"/>
<source>Measure circumference at largest level of head.</source>
<comment>Full measurement description.</comment>
<translation>Misura circonferenza al punto più largo della testa.</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="535"/>
<source>head_length</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation>lunghezza_testa</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="537"/>
<source>Head: Length</source>
<comment>Full measurement name.</comment>
<translation>Testa: Lunghezza</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="538"/>
<source>Vertical distance from Head Crown to bottom of jaw.</source>
<comment>Full measurement description.</comment>
<translation>Distanza verticale dalla parte più alta della testa al fondo della mascella.</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="542"/>
<source>head_depth</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation>testa_profondità</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="544"/>
<source>Head: Depth</source>
<comment>Full measurement name.</comment>
<translation>Testa: Profondità</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="545"/>
<source>Horizontal distance from front of forehead to back of head.</source>
<comment>Full measurement description.</comment>
<translation>Distanza orizzontale dalla fronte al retro della testa.</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="549"/>
<source>head_width</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation>altezza_larghezza</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="551"/>
<source>Head: Width</source>
<comment>Full measurement name.</comment>
<translation>Testa: Larghezza</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="552"/>
<source>Horizontal distance from Head Side to Head Side, where Head is widest.</source>
<comment>Full measurement description.</comment>
<translation>Distanza orizzontale da lato a lato della testa, dove è più larga.</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="556"/>
<source>head_crown_to_neck_back</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation>sommità_testa_al_collo_dietro</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="558"/>
<source>Head: Crown to Neck Back</source>
<comment>Full measurement name.</comment>
<translation>Testa: Sommità al Collo Dietro</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="559"/>
<source>Vertical distance from Crown to Neck Back. ('Height: Total' - 'Height: Neck Back').</source>
<comment>Full measurement description.</comment>
<translation>Distanza verticale dalla Sommità della testa al Collo Dietro. ('Altezza: Totale' - 'Altezza: Collo Dietro').</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="563"/>
<source>head_chin_to_neck_back</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation>testa_mento_al_collo_dietro</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="565"/>
<source>Head: Chin to Neck Back</source>
<comment>Full measurement name.</comment>
<translation>Testa: Mento al Collo Dietro</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="566"/>
<source>Vertical distance from Chin to Neck Back. ('Height' - 'Height: Neck Back' - 'Head: Length')</source>
<comment>Full measurement description.</comment>
<translation>Distanza verticale dal Mento al Collo Dietro. ('Altezza' - 'Altezza: Collo Dietro' - 'Testa: Lunghezza')</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="583"/>
<source>neck_mid_circ</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation>collo_medio_circ</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="585"/>
<source>Neck circumference, midsection</source>
<comment>Full measurement name.</comment>
<translation>Circonferenza Collo, sezione di mezzo</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="586"/>
<source>Circumference of Neck midsection, about halfway between jaw and torso.</source>
<comment>Full measurement description.</comment>
<translation>Circonferenza della parte media del collo, circa a metà strada tra la mascella e il tronco.</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="590"/>
<source>neck_circ</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation>collo_circ</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="592"/>
<source>Neck circumference</source>
<comment>Full measurement name.</comment>
<translation>Circonferenza collo</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="593"/>
<source>Neck circumference at base of Neck, touching Neck Back, Neck Sides, and Neck Front.</source>
<comment>Full measurement description.</comment>
<translation>Circonferenza collo alla base del Collo, toccando Dietro il Collo, i Lati del Collo e Parte Anteriore del Collo.</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="598"/>
<source>highbust_circ</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation>torace_circ</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="600"/>
<source>Highbust circumference</source>
<comment>Full measurement name.</comment>
<translation>Circonferenza torace</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="601"/>
<source>Circumference at Highbust, following shortest distance between Armfolds across chest, high under armpits.</source>
<comment>Full measurement description.</comment>
<translation>Circonferenza del torace, seguendo la distanza più corta tra le braccia incrociate sul petto, la parte superiore sotto le ascelle.</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="605"/>
<source>bust_circ</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation>busto_circ</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="607"/>
<source>Bust circumference</source>
<comment>Full measurement name.</comment>
<translation>Circonferenza busto</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="608"/>
<source>Circumference around Bust, parallel to floor.</source>
<comment>Full measurement description.</comment>
<translation>Circonferenza attorno al busto, parallelo al pavimento.</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="612"/>
<source>lowbust_circ</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation>basso_torace_circ</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="614"/>
<source>Lowbust circumference</source>
<comment>Full measurement name.</comment>
<translation>Circonferenza basso torace</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="615"/>
<source>Circumference around LowBust under the breasts, parallel to floor.</source>
<comment>Full measurement description.</comment>
<translation>Circonferenza del basso torace sotto il seno, parallela al pavimento</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="619"/>
<source>rib_circ</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation>costola_circ</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="621"/>
<source>Rib circumference</source>
<comment>Full measurement name.</comment>
<translation>Circonferenza costola</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="622"/>
<source>Circumference around Ribs at level of the lowest rib at the side, parallel to floor.</source>
<comment>Full measurement description.</comment>
<translation>Circonferenza attorno alle costole, all'altezza della costola più bassa laterale, parallelo al pavimento.</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="627"/>
<source>waist_circ</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation>vita_circ</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="629"/>
<source>Waist circumference</source>
<comment>Full measurement name.</comment>
<translation>Circonferenza vita</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="635"/>
<source>highhip_circ</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation>fiancoalto_circ</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="637"/>
<source>Highhip circumference</source>
<comment>Full measurement name.</comment>
<translation>Circonferenza parte alta delle anche</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="630"/>
<source>Circumference around Waist, following natural contours. Waists are typically higher in back.</source>
<comment>Full measurement description.</comment>
<translation>Circonferenza attorno alle anche, seguendo il contorno naturale. Le anche di solito sono più alte dietro.</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="345"/>
<source>height_waist_back</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation>altezza_vita_dietro</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="347"/>
<source>Height: Waist Back</source>
<comment>Full measurement name.</comment>
<translation>Altezza: Anca Posteriore</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="348"/>
<source>Vertical height from Waist Back to floor. ('Height: Waist Front'' - 'Leg: Crotch to floor'').</source>
<comment>Full measurement description.</comment>
<translation>Altezza verticale dalla vita dietro al pavimento. ('Altezza: Vita Davanti" - 'Gamba: Cavallo al pavimento").</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="428"/>
<source>Horizontal Distance between a flat stick, placed perpendicular to Heel, and the greatest indentation of Ankle.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="638"/>
<source>Circumference around Highhip, where Abdomen protrusion is greatest, parallel to floor.</source>
<comment>Full measurement description.</comment>
<translation>Circonferenza attorno alle Anche, dove l'Addome sporge maggiormente, parallelo al pavimento.</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="643"/>
<source>hip_circ</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation>anche_circ</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="645"/>
<source>Hip circumference</source>
<comment>Full measurement name.</comment>
<translation>Circonferenza anche</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="646"/>
<source>Circumference around Hip where Hip protrusion is greatest, parallel to floor.</source>
<comment>Full measurement description.</comment>
<translation>Circonferenza fianchi nel punto dove i fianchi sono più larghi, parallela al pavimento</translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="651"/>
<source>neck_arc_f</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="653"/>
<source>Neck arc, front</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="654"/>
<source>From Neck Side to Neck Side through Neck Front.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="658"/>
<source>highbust_arc_f</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="660"/>
<source>Highbust arc, front</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="661"/>
<source>From Highbust Side (Armpit) to HIghbust Side (Armpit) across chest.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="665"/>
<source>bust_arc_f</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="667"/>
<source>Bust arc, front</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="668"/>
<source>From Bust Side to Bust Side across chest.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="672"/>
<source>size</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="674"/>
<source>Size</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="675"/>
<source>Same as bust_arc_f.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="679"/>
<source>lowbust_arc_f</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="681"/>
<source>Lowbust arc, front</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="682"/>
<source>From Lowbust Side to Lowbust Side across front.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="686"/>
<source>rib_arc_f</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="688"/>
<source>Rib arc, front</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="689"/>
<source>From Rib Side to Rib Side, across front.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="693"/>
<source>waist_arc_f</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="695"/>
<source>Waist arc, front</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="696"/>
<source>From Waist Side to Waist Side across front.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="700"/>
<source>highhip_arc_f</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="702"/>
<source>Highhip arc, front</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="703"/>
<source>From Highhip Side to Highhip Side across front.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="707"/>
<source>hip_arc_f</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="709"/>
<source>Hip arc, front</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="710"/>
<source>From Hip Side to Hip Side across Front.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="714"/>
<source>neck_arc_half_f</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="716"/>
<source>Neck arc, front, half</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="717"/>
<source>Half of 'Neck arc, front'. ('Neck arc, front' / 2).</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="721"/>
<source>highbust_arc_half_f</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="723"/>
<source>Highbust arc, front, half</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="724"/>
<source>Half of 'Highbust arc, front'. From Highbust Front to Highbust Side. ('Highbust arc, front' / 2).</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="729"/>
<source>bust_arc_half_f</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="731"/>
<source>Bust arc, front, half</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="732"/>
<source>Half of 'Bust arc, front'. ('Bust arc, front'/2).</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="736"/>
<source>lowbust_arc_half_f</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="738"/>
<source>Lowbust arc, front, half</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="739"/>
<source>Half of 'Lowbust arc, front'. ('Lowbust Arc, front' / 2).</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="743"/>
<source>rib_arc_half_f</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="745"/>
<source>Rib arc, front, half</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="746"/>
<source>Half of 'Rib arc, front'. ('Rib Arc, front' / 2).</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="750"/>
<source>waist_arc_half_f</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="752"/>
<source>Waist arc, front, half</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="753"/>
<source>Half of 'Waist arc, front'. ('Waist arc, front' / 2).</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="757"/>
<source>highhip_arc_half_f</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="759"/>
<source>Highhip arc, front, half</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="760"/>
<source>Half of 'Highhip arc, front'. ('Highhip arc, front' / 2).</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="764"/>
<source>hip_arc_half_f</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="766"/>
<source>Hip arc, front, half</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="767"/>
<source>Half of 'Hip arc, front'. ('Hip arc, front' / 2).</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="771"/>
<source>neck_arc_b</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="773"/>
<source>Neck arc, back</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="774"/>
<source>From Neck Side to Neck Side across back. ('Neck circumference' - 'Neck arc, front').</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="779"/>
<source>highbust_arc_b</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="781"/>
<source>Highbust arc, back</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="782"/>
<source>From Highbust Side to Highbust Side across back. ('Highbust circumference' - 'Highbust arc, front').</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="786"/>
<source>bust_arc_b</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="788"/>
<source>Bust arc, back</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="789"/>
<source>From Bust Side to Bust Side across back. ('Bust circumference' - 'Bust arc, front').</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="794"/>
<source>lowbust_arc_b</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="796"/>
<source>Lowbust arc, back</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="797"/>
<source>From Lowbust Side to Lowbust Side across back. ('Lowbust circumference' - 'Lowbust arc, front').</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="802"/>
<source>rib_arc_b</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="804"/>
<source>Rib arc, back</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="805"/>
<source>From Rib Side to Rib side across back. ('Rib circumference' - 'Rib arc, front').</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="810"/>
<source>waist_arc_b</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="812"/>
<source>Waist arc, back</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="813"/>
<source>From Waist Side to Waist Side across back. ('Waist circumference' - 'Waist arc, front').</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="818"/>
<source>highhip_arc_b</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="820"/>
<source>Highhip arc, back</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="821"/>
<source>From Highhip Side to Highhip Side across back. ('Highhip circumference' - 'Highhip arc, front').</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="826"/>
<source>hip_arc_b</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="828"/>
<source>Hip arc, back</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="829"/>
<source>From Hip Side to Hip Side across back. ('Hip circumference' - 'Hip arc, front').</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="834"/>
<source>neck_arc_half_b</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="836"/>
<source>Neck arc, back, half</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="837"/>
<source>Half of 'Neck arc, back'. ('Neck arc, back' / 2).</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="841"/>
<source>highbust_arc_half_b</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="843"/>
<source>Highbust arc, back, half</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="844"/>
<source>Half of 'Highbust arc, back'. From Highbust Back to Highbust Side. ('Highbust arc, back' / 2).</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="849"/>
<source>bust_arc_half_b</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="851"/>
<source>Bust arc, back, half</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="852"/>
<source>Half of 'Bust arc, back'. ('Bust arc, back' / 2).</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="856"/>
<source>lowbust_arc_half_b</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="858"/>
<source>Lowbust arc, back, half</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="859"/>
<source>Half of 'Lowbust Arc, back'. ('Lowbust arc, back' / 2).</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="863"/>
<source>rib_arc_half_b</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="865"/>
<source>Rib arc, back, half</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="866"/>
<source>Half of 'Rib arc, back'. ('Rib arc, back' / 2).</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="870"/>
<source>waist_arc_half_b</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="872"/>
<source>Waist arc, back, half</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="873"/>
<source>Half of 'Waist arc, back'. ('Waist arc, back' / 2).</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="877"/>
<source>highhip_arc_half_b</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="879"/>
<source>Highhip arc, back, half</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="880"/>
<source>Half of 'Highhip arc, back'. From Highhip Back to Highbust Side. ('Highhip arc, back'/ 2).</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="885"/>
<source>hip_arc_half_b</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="887"/>
<source>Hip arc, back, half</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="888"/>
<source>Half of 'Hip arc, back'. ('Hip arc, back' / 2).</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="892"/>
<source>hip_with_abdomen_arc_f</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="894"/>
<source>Hip arc with Abdomen, front</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="895"/>
<source>Curve stiff paper around front of abdomen, tape_ at sides. Measure from Hip Side to Hip Side over paper across front.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="900"/>
<source>body_armfold_circ</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="902"/>
<source>Body circumference at Armfold level</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="903"/>
<source>Measure around arms and torso at Armfold level.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="907"/>
<source>body_bust_circ</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="909"/>
<source>Body circumference at Bust level</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="910"/>
<source>Measure around arms and torso at Bust level.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="914"/>
<source>body_torso_circ</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="916"/>
<source>Body circumference of full torso</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="917"/>
<source>Circumference around torso from mid-shoulder around crotch back up to mid-shoulder.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="922"/>
<source>hip_circ_with_abdomen</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="924"/>
<source>Hip circumference, including Abdomen</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="925"/>
<source>Measurement at Hip level, including the depth of the Abdomen. (Hip arc, back + Hip arc with abdomen, front).</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="942"/>
<source>neck_front_to_waist_f</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="944"/>
<source>Neck Front to Waist Front</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="945"/>
<source>From Neck Front, over tape_ between Breastpoints, down to Waist Front.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="949"/>
<source>neck_front_to_waist_flat_f</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="951"/>
<source>Neck Front to Waist Front flat</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="952"/>
<source>From Neck Front down between breasts to Waist Front.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="956"/>
<source>armpit_to_waist_side</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="958"/>
<source>Armpit to Waist Side</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="959"/>
<source>From Armpit down to Waist Side.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="962"/>
<source>shoulder_tip_to_waist_side_f</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="964"/>
<source>Shoulder Tip to Waist Side, front</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="965"/>
<source>From Shoulder Tip, curving around Armscye Front, then down to Waist Side.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="969"/>
<source>neck_side_to_waist_f</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="971"/>
<source>Neck Side to Waist level, front</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="972"/>
<source>From Neck Side straight down front to Waist level.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="976"/>
<source>neck_side_to_waist_bustpoint_f</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="978"/>
<source>Neck Side to Waist level, through Bustpoint</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="979"/>
<source>From Neck Side over Bustpoint to Waist level, forming a straight line.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="983"/>
<source>neck_front_to_highbust_f</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="985"/>
<source>Neck Front to Highbust Front</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="986"/>
<source>Neck Front down to Highbust Front.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="989"/>
<source>highbust_to_waist_f</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="991"/>
<source>Highbust Front to Waist Front</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="992"/>
<source>From Highbust Front to Waist Front. Use tape_ to bridge gap between Bustpoints. ('Neck Front to Waist Front' - 'Neck Front to Highbust Front').</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="997"/>
<source>neck_front_to_bust_f</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="999"/>
<source>Neck Front to Bust Front</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1000"/>
<source>From Neck Front down to Bust Front. Requires tape_ to cover gap between Bustpoints.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1005"/>
<source>bust_to_waist_f</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1007"/>
<source>Bust Front to Waist Front</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1008"/>
<source>From Bust Front down to Waist level. ('Neck Front to Waist Front' - 'Neck Front to Bust Front').</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1013"/>
<source>lowbust_to_waist_f</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1015"/>
<source>Lowbust Front to Waist Front</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1016"/>
<source>From Lowbust Front down to Waist Front.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1019"/>
<source>rib_to_waist_side</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1021"/>
<source>Rib Side to Waist Side</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1022"/>
<source>From lowest rib at side down to Waist Side.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1026"/>
<source>shoulder_tip_to_armfold_f</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1028"/>
<source>Shoulder Tip to Armfold Front</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1029"/>
<source>From Shoulder Tip around Armscye down to Armfold Front.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1033"/>
<source>neck_side_to_bust_f</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1035"/>
<source>Neck Side to Bust level, front</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1036"/>
<source>From Neck Side straight down front to Bust level.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1040"/>
<source>neck_side_to_highbust_f</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1042"/>
<source>Neck Side to Highbust level, front</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1043"/>
<source>From Neck Side straight down front to Highbust level.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1047"/>
<source>shoulder_center_to_highbust_f</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1049"/>
<source>Shoulder center to Highbust level, front</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1050"/>
<source>From mid-Shoulder down front to Highbust level, aimed at Bustpoint.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1054"/>
<source>shoulder_tip_to_waist_side_b</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1056"/>
<source>Shoulder Tip to Waist Side, back</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1057"/>
<source>From Shoulder Tip, curving around Armscye Back, then down to Waist Side.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1061"/>
<source>neck_side_to_waist_b</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1063"/>
<source>Neck Side to Waist level, back</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1064"/>
<source>From Neck Side straight down back to Waist level.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1068"/>
<source>neck_back_to_waist_b</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1070"/>
<source>Neck Back to Waist Back</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1071"/>
<source>From Neck Back down to Waist Back.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1074"/>
<source>neck_side_to_waist_scapula_b</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1076"/>
<source>Neck Side to Waist level, through Scapula</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1077"/>
<source>From Neck Side across Scapula down to Waist level, forming a straight line.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1082"/>
<source>neck_back_to_highbust_b</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1084"/>
<source>Neck Back to Highbust Back</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1085"/>
<source>From Neck Back down to Highbust Back.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1088"/>
<source>highbust_to_waist_b</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1090"/>
<source>Highbust Back to Waist Back</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1091"/>
<source>From Highbust Back down to Waist Back. ('Neck Back to Waist Back' - 'Neck Back to Highbust Back').</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1096"/>
<source>neck_back_to_bust_b</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1098"/>
<source>Neck Back to Bust Back</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1099"/>
<source>From Neck Back down to Bust Back.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1102"/>
<source>bust_to_waist_b</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1104"/>
<source>Bust Back to Waist Back</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1105"/>
<source>From Bust Back down to Waist level. ('Neck Back to Waist Back' - 'Neck Back to Bust Back').</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1110"/>
<source>lowbust_to_waist_b</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1112"/>
<source>Lowbust Back to Waist Back</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1113"/>
<source>From Lowbust Back down to Waist Back.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1116"/>
<source>shoulder_tip_to_armfold_b</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1118"/>
<source>Shoulder Tip to Armfold Back</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1119"/>
<source>From Shoulder Tip around Armscye down to Armfold Back.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1123"/>
<source>neck_side_to_bust_b</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1125"/>
<source>Neck Side to Bust level, back</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1126"/>
<source>From Neck Side straight down back to Bust level.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1130"/>
<source>neck_side_to_highbust_b</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1132"/>
<source>Neck Side to Highbust level, back</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1133"/>
<source>From Neck Side straight down back to Highbust level.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1137"/>
<source>shoulder_center_to_highbust_b</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1139"/>
<source>Shoulder center to Highbust level, back</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1140"/>
<source>From mid-Shoulder down back to Highbust level, aimed through Scapula.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1144"/>
<source>waist_to_highhip_f</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1146"/>
<source>Waist Front to Highhip Front</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1147"/>
<source>From Waist Front to Highhip Front.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1150"/>
<source>waist_to_hip_f</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1152"/>
<source>Waist Front to Hip Front</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1153"/>
<source>From Waist Front to Hip Front.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1156"/>
<source>waist_to_highhip_side</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1158"/>
<source>Waist Side to Highhip Side</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1159"/>
<source>From Waist Side to Highhip Side.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1162"/>
<source>waist_to_highhip_b</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1164"/>
<source>Waist Back to Highhip Back</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1165"/>
<source>From Waist Back down to Highhip Back.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1168"/>
<source>waist_to_hip_b</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1170"/>
<source>Waist Back to Hip Back</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1171"/>
<source>From Waist Back down to Hip Back. Requires tape_ to cover the gap between buttocks.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1176"/>
<source>waist_to_hip_side</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1178"/>
<source>Waist Side to Hip Side</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1179"/>
<source>From Waist Side to Hip Side.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1182"/>
<source>shoulder_slope_neck_side_angle</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1184"/>
<source>Shoulder Slope Angle from Neck Side</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1185"/>
<source>Angle formed by line from Neck Side to Shoulder Tip and line from Neck Side parallel to floor.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1190"/>
<source>shoulder_slope_neck_side_length</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1192"/>
<source>Shoulder Slope length from Neck Side</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1193"/>
<source>Vertical distance between Neck Side and Shoulder Tip.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1197"/>
<source>shoulder_slope_neck_back_angle</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1199"/>
<source>Shoulder Slope Angle from Neck Back</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1200"/>
<source>Angle formed by line from Neck Back to Shoulder Tip and line from Neck Back parallel to floor.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1205"/>
<source>shoulder_slope_neck_back_height</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1207"/>
<source>Shoulder Slope length from Neck Back</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1208"/>
<source>Vertical distance between Neck Back and Shoulder Tip.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1212"/>
<source>shoulder_slope_shoulder_tip_angle</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1214"/>
<source>Shoulder Slope Angle from Shoulder Tip</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1216"/>
<source>Angle formed by line from Neck Side to Shoulder Tip and vertical line at Shoulder Tip.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1221"/>
<source>neck_back_to_across_back</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1223"/>
<source>Neck Back to Across Back</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1224"/>
<source>From neck back, down to level of Across Back measurement.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1228"/>
<source>across_back_to_waist_b</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1230"/>
<source>Across Back to Waist back</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1231"/>
<source>From middle of Across Back down to Waist back.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1247"/>
<source>shoulder_length</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1249"/>
<source>Shoulder length</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1250"/>
<source>From Neck Side to Shoulder Tip.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1253"/>
<source>shoulder_tip_to_shoulder_tip_f</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1255"/>
<source>Shoulder Tip to Shoulder Tip, front</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1256"/>
<source>From Shoulder Tip to Shoulder Tip, across front.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1260"/>
<source>across_chest_f</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1262"/>
<source>Across Chest</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1263"/>
<source>From Armscye to Armscye at narrowest width across chest.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1267"/>
<source>armfold_to_armfold_f</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1269"/>
<source>Armfold to Armfold, front</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1270"/>
<source>From Armfold to Armfold, shortest distance between Armfolds, not parallel to floor.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1275"/>
<source>shoulder_tip_to_shoulder_tip_half_f</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1277"/>
<source>Shoulder Tip to Shoulder Tip, front, half</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1278"/>
<source>Half of' Shoulder Tip to Shoulder tip, front'. ('Shoulder Tip to Shoulder Tip, front' / 2).</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1283"/>
<source>across_chest_half_f</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1285"/>
<source>Across Chest, half</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1286"/>
<source>Half of 'Across Chest'. ('Across Chest' / 2).</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1290"/>
<source>shoulder_tip_to_shoulder_tip_b</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1292"/>
<source>Shoulder Tip to Shoulder Tip, back</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1293"/>
<source>From Shoulder Tip to Shoulder Tip, across the back.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1297"/>
<source>across_back_b</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1299"/>
<source>Across Back</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1300"/>
<source>From Armscye to Armscye at the narrowest width of the back.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1304"/>
<source>armfold_to_armfold_b</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1306"/>
<source>Armfold to Armfold, back</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1307"/>
<source>From Armfold to Armfold across the back.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1311"/>
<source>shoulder_tip_to_shoulder_tip_half_b</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1313"/>
<source>Shoulder Tip to Shoulder Tip, back, half</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1314"/>
<source>Half of 'Shoulder Tip to Shoulder Tip, back'. ('Shoulder Tip to Shoulder Tip, back' / 2).</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1319"/>
<source>across_back_half_b</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1321"/>
<source>Across Back, half</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1322"/>
<source>Half of 'Across Back'. ('Across Back' / 2).</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1326"/>
<source>neck_front_to_shoulder_tip_f</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1328"/>
<source>Neck Front to Shoulder Tip</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1329"/>
<source>From Neck Front to Shoulder Tip.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1332"/>
<source>neck_back_to_shoulder_tip_b</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1334"/>
<source>Neck Back to Shoulder Tip</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1335"/>
<source>From Neck Back to Shoulder Tip.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1338"/>
<source>neck_width</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1340"/>
<source>Neck Width</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1341"/>
<source>Measure between the 'legs' of an unclosed necklace or chain draped around the neck.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1358"/>
<source>bustpoint_to_bustpoint</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1360"/>
<source>Bustpoint to Bustpoint</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1361"/>
<source>From Bustpoint to Bustpoint.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1364"/>
<source>bustpoint_to_neck_side</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1366"/>
<source>Bustpoint to Neck Side</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1367"/>
<source>From Neck Side to Bustpoint.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1370"/>
<source>bustpoint_to_lowbust</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1372"/>
<source>Bustpoint to Lowbust</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1373"/>
<source>From Bustpoint down to Lowbust level, following curve of bust or chest.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1377"/>
<source>bustpoint_to_waist</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1379"/>
<source>Bustpoint to Waist level</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1380"/>
<source>From Bustpoint to straight down to Waist level, forming a straight line (not curving along the body).</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1385"/>
<source>bustpoint_to_bustpoint_half</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1387"/>
<source>Bustpoint to Bustpoint, half</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1388"/>
<source>Half of 'Bustpoint to Bustpoint'. ('Bustpoint to Bustpoint' / 2).</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1392"/>
<source>bustpoint_neck_side_to_waist</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1394"/>
<source>Bustpoint, Neck Side to Waist level</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1395"/>
<source>From Neck Side to Bustpoint, then straight down to Waist level. ('Neck Side to Bustpoint' + 'Bustpoint to Waist level').</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1400"/>
<source>bustpoint_to_shoulder_tip</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1402"/>
<source>Bustpoint to Shoulder Tip</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1403"/>
<source>From Bustpoint to Shoulder tip.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1406"/>
<source>bustpoint_to_waist_front</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1408"/>
<source>Bustpoint to Waist Front</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1409"/>
<source>From Bustpoint to Waist Front, in a straight line, not following the curves of the body.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1414"/>
<source>bustpoint_to_bustpoint_halter</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1416"/>
<source>Bustpoint to Bustpoint Halter</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1417"/>
<source>From Bustpoint around Neck Back down to other Bustpoint.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1421"/>
<source>bustpoint_to_shoulder_center</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1423"/>
<source>Bustpoint to Shoulder Center</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1424"/>
<source>From center of Shoulder to Bustpoint.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1439"/>
<source>shoulder_tip_to_waist_front</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1441"/>
<source>Shoulder Tip to Waist Front</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1442"/>
<source>From Shoulder Tip diagonal to Waist Front.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1446"/>
<source>neck_front_to_waist_side</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1448"/>
<source>Neck Front to Waist Side</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1449"/>
<source>From Neck Front diagonal to Waist Side.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1453"/>
<source>neck_side_to_waist_side_f</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1455"/>
<source>Neck Side to Waist Side, front</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1456"/>
<source>From Neck Side diagonal across front to Waist Side.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1460"/>
<source>shoulder_tip_to_waist_back</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1462"/>
<source>Shoulder Tip to Waist Back</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1463"/>
<source>From Shoulder Tip diagonal to Waist Back.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1467"/>
<source>shoulder_tip_to_waist_b_1in_offset</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1469"/>
<source>Shoulder Tip to Waist Back, with 1in (2.54cm) offset</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1471"/>
<source>Mark 1in (2.54cm) outward from Waist Back along Waist level. Measure from Shoulder Tip diagonal to mark.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1475"/>
<source>neck_back_to_waist_side</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1477"/>
<source>Neck Back to Waist Side</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1478"/>
<source>From Neck Back diagonal across back to Waist Side.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1482"/>
<source>neck_side_to_waist_side_b</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1484"/>
<source>Neck Side to Waist Side, back</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1485"/>
<source>From Neck Side diagonal across back to Waist Side.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1489"/>
<source>neck_side_to_armfold_f</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1491"/>
<source>Neck Side to Armfold Front</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1492"/>
<source>From Neck Side diagonal to Armfold Front.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1496"/>
<source>neck_side_to_armpit_f</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1498"/>
<source>Neck Side to Highbust Side, front</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1499"/>
<source>From Neck Side diagonal across front to Highbust Side (Armpit).</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1503"/>
<source>neck_side_to_bust_side_f</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1505"/>
<source>Neck Side to Bust Side, front</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1506"/>
<source>Neck Side diagonal across front to Bust Side.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1510"/>
<source>neck_side_to_armfold_b</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1512"/>
<source>Neck Side to Armfold Back</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1513"/>
<source>From Neck Side diagonal to Armfold Back.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1517"/>
<source>neck_side_to_armpit_b</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1519"/>
<source>Neck Side to Highbust Side, back</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1520"/>
<source>From Neck Side diagonal across back to Highbust Side (Armpit).</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1524"/>
<source>neck_side_to_bust_side_b</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1526"/>
<source>Neck Side to Bust Side, back</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1527"/>
<source>Neck Side diagonal across back to Bust Side.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1543"/>
<source>arm_shoulder_tip_to_wrist_bent</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1545"/>
<source>Arm: Shoulder Tip to Wrist, bent</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1546"/>
<source>Bend Arm, measure from Shoulder Tip around Elbow to radial Wrist bone.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1550"/>
<source>arm_shoulder_tip_to_elbow_bent</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1552"/>
<source>Arm: Shoulder Tip to Elbow, bent</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1553"/>
<source>Bend Arm, measure from Shoulder Tip to Elbow Tip.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1557"/>
<source>arm_elbow_to_wrist_bent</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1559"/>
<source>Arm: Elbow to Wrist, bent</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1560"/>
<source>Elbow tip to wrist. ('Arm: Shoulder Tip to Wrist, bent' - 'Arm: Shoulder Tip to Elbow, bent').</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1566"/>
<source>arm_elbow_circ_bent</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1568"/>
<source>Arm: Elbow circumference, bent</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1569"/>
<source>Elbow circumference, arm is bent.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1572"/>
<source>arm_shoulder_tip_to_wrist</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1574"/>
<source>Arm: Shoulder Tip to Wrist</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1575"/>
<source>From Shoulder Tip to Wrist bone, arm straight.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1579"/>
<source>arm_shoulder_tip_to_elbow</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1581"/>
<source>Arm: Shoulder Tip to Elbow</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1582"/>
<source>From Shoulder tip to Elbow Tip, arm straight.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1586"/>
<source>arm_elbow_to_wrist</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1588"/>
<source>Arm: Elbow to Wrist</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1589"/>
<source>From Elbow to Wrist, arm straight. ('Arm: Shoulder Tip to Wrist' - 'Arm: Shoulder Tip to Elbow').</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1594"/>
<source>arm_armpit_to_wrist</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1596"/>
<source>Arm: Armpit to Wrist, inside</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1597"/>
<source>From Armpit to ulna Wrist bone, arm straight.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1601"/>
<source>arm_armpit_to_elbow</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1603"/>
<source>Arm: Armpit to Elbow, inside</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1604"/>
<source>From Armpit to inner Elbow, arm straight.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1608"/>
<source>arm_elbow_to_wrist_inside</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1610"/>
<source>Arm: Elbow to Wrist, inside</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1611"/>
<source>From inside Elbow to Wrist. ('Arm: Armpit to Wrist, inside' - 'Arm: Armpit to Elbow, inside').</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1616"/>
<source>arm_upper_circ</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1618"/>
<source>Arm: Upper Arm circumference</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1619"/>
<source>Arm circumference at Armpit level.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1622"/>
<source>arm_above_elbow_circ</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1624"/>
<source>Arm: Above Elbow circumference</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1625"/>
<source>Arm circumference at Bicep level.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1628"/>
<source>arm_elbow_circ</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1630"/>
<source>Arm: Elbow circumference</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1631"/>
<source>Elbow circumference, arm straight.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1634"/>
<source>arm_lower_circ</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1636"/>
<source>Arm: Lower Arm circumference</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1637"/>
<source>Arm circumference where lower arm is widest.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1641"/>
<source>arm_wrist_circ</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1643"/>
<source>Arm: Wrist circumference</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1644"/>
<source>Wrist circumference.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1647"/>
<source>arm_shoulder_tip_to_armfold_line</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1649"/>
<source>Arm: Shoulder Tip to Armfold line</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1650"/>
<source>From Shoulder Tip down to Armpit level.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1653"/>
<source>arm_neck_side_to_wrist</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1655"/>
<source>Arm: Neck Side to Wrist</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1656"/>
<source>From Neck Side to Wrist. ('Shoulder Length' + 'Arm: Shoulder Tip to Wrist').</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1661"/>
<source>arm_neck_side_to_finger_tip</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1663"/>
<source>Arm: Neck Side to Finger Tip</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1664"/>
<source>From Neck Side down arm to tip of middle finger. ('Shoulder Length' + 'Arm: Shoulder Tip to Wrist' + 'Hand: Length').</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1670"/>
<source>armscye_circ</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1672"/>
<source>Armscye: Circumference</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1673"/>
<source>Let arm hang at side. Measure Armscye circumference through Shoulder Tip and Armpit.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1678"/>
<source>armscye_length</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1680"/>
<source>Armscye: Length</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1681"/>
<source>Vertical distance from Shoulder Tip to Armpit.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1685"/>
<source>armscye_width</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1687"/>
<source>Armscye: Width</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1688"/>
<source>Horizontal distance between Armscye Front and Armscye Back.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1692"/>
<source>arm_neck_side_to_outer_elbow</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1694"/>
<source>Arm: Neck side to Elbow</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1695"/>
<source>From Neck Side over Shoulder Tip down to Elbow. (Shoulder length + Arm: Shoulder Tip to Elbow).</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1711"/>
<source>leg_crotch_to_floor</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1713"/>
<source>Leg: Crotch to floor</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1714"/>
<source>Stand feet close together. Measure from crotch level (touching body, no extra space) down to floor.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1805"/>
<source>From Waist Side along curve to Hip level then straight down to Knee level. ('Leg: Waist Side to Floor' - 'Height Knee').</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1845"/>
<source>rise_length_side_sitting</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1878"/>
<source>Vertical distance from Waist side down to Crotch level. Use formula (Height: Waist side - Leg: Crotch to floor).</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="2131"/>
<source>This information is pulled from pattern charts in some patternmaking systems, e.g. Winifred P. Aldrich's "Metric Pattern Cutting".</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1719"/>
<source>leg_waist_side_to_floor</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1721"/>
<source>Leg: Waist Side to floor</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1722"/>
<source>From Waist Side along curve to Hip level then straight down to floor.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1726"/>
<source>leg_thigh_upper_circ</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1728"/>
<source>Leg: Thigh Upper circumference</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1729"/>
<source>Thigh circumference at the fullest part of the upper Thigh near the Crotch.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1734"/>
<source>leg_thigh_mid_circ</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1736"/>
<source>Leg: Thigh Middle circumference</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1737"/>
<source>Thigh circumference about halfway between Crotch and Knee.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1741"/>
<source>leg_knee_circ</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1743"/>
<source>Leg: Knee circumference</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1744"/>
<source>Knee circumference with straight leg.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1747"/>
<source>leg_knee_small_circ</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1749"/>
<source>Leg: Knee Small circumference</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1750"/>
<source>Leg circumference just below the knee.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1753"/>
<source>leg_calf_circ</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1755"/>
<source>Leg: Calf circumference</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1756"/>
<source>Calf circumference at the largest part of lower leg.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1760"/>
<source>leg_ankle_high_circ</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1762"/>
<source>Leg: Ankle High circumference</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1763"/>
<source>Ankle circumference where the indentation at the back of the ankle is the deepest.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1768"/>
<source>leg_ankle_circ</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1770"/>
<source>Leg: Ankle circumference</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1771"/>
<source>Ankle circumference where front of leg meets the top of the foot.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1775"/>
<source>leg_knee_circ_bent</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1777"/>
<source>Leg: Knee circumference, bent</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1778"/>
<source>Knee circumference with leg bent.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1781"/>
<source>leg_ankle_diag_circ</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1783"/>
<source>Leg: Ankle diagonal circumference</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1784"/>
<source>Ankle circumference diagonal from top of foot to bottom of heel.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1788"/>
<source>leg_crotch_to_ankle</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1790"/>
<source>Leg: Crotch to Ankle</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1791"/>
<source>From Crotch to Ankle. ('Leg: Crotch to Floor' - 'Height: Ankle').</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1795"/>
<source>leg_waist_side_to_ankle</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1797"/>
<source>Leg: Waist Side to Ankle</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1798"/>
<source>From Waist Side to Ankle. ('Leg: Waist Side to Floor' - 'Height: Ankle').</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1802"/>
<source>leg_waist_side_to_knee</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1804"/>
<source>Leg: Waist Side to Knee</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1822"/>
<source>crotch_length</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1824"/>
<source>Crotch length</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1825"/>
<source>Put tape_ across gap between buttocks at Hip level. Measure from Waist Front down between legs and up to Waist Back.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1829"/>
<source>crotch_length_b</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1831"/>
<source>Crotch length, back</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1832"/>
<source>Put tape_ across gap between buttocks at Hip level. Measure from Waist Back to mid-Crotch, either at the vagina or between testicles and anus).</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1837"/>
<source>crotch_length_f</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1839"/>
<source>Crotch length, front</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1840"/>
<source>From Waist Front to start of vagina or end of testicles. ('Crotch length' - 'Crotch length, back').</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1847"/>
<source>Rise length, side, sitting</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1849"/>
<source>From Waist Side around hip curve down to surface, while seated on hard surface.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1864"/>
<source>Vertical distance from Waist Back to Crotch level. ('Height: Waist Back' - 'Leg: Crotch to Floor')</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1871"/>
<source>Vertical Distance from Waist Front to Crotch level. ('Height: Waist Front' - 'Leg: Crotch to Floor')</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1875"/>
<source>rise_length_side</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1877"/>
<source>Rise length, side</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1854"/>
<source>rise_length_diag</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1856"/>
<source>Rise length, diagonal</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1857"/>
<source>Measure from Waist Side diagonally to a string tied at the top of the leg, seated on a hard surface.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1861"/>
<source>rise_length_b</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1863"/>
<source>Rise length, back</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1868"/>
<source>rise_length_f</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1870"/>
<source>Rise length, front</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1894"/>
<source>neck_back_to_waist_front</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1896"/>
<source>Neck Back to Waist Front</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1897"/>
<source>From Neck Back around Neck Side down to Waist Front.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1901"/>
<source>waist_to_waist_halter</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1903"/>
<source>Waist to Waist Halter, around Neck Back</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1904"/>
<source>From Waist level around Neck Back to Waist level.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1908"/>
<source>waist_natural_circ</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1910"/>
<source>Natural Waist circumference</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1911"/>
<source>Torso circumference at men's natural side Abdominal Obliques indentation, if Oblique indentation isn't found then just below the Navel level.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1916"/>
<source>waist_natural_arc_f</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1918"/>
<source>Natural Waist arc, front</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1919"/>
<source>From Side to Side at the Natural Waist level, across the front.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1923"/>
<source>waist_natural_arc_b</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1925"/>
<source>Natural Waist arc, back</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1926"/>
<source>From Side to Side at Natural Waist level, across the back. Calculate as ( Natural Waist circumference - Natural Waist arc (front) ).</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1930"/>
<source>waist_to_natural_waist_f</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1932"/>
<source>Waist Front to Natural Waist Front</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1933"/>
<source>Length from Waist Front to Natural Waist Front.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1937"/>
<source>waist_to_natural_waist_b</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1939"/>
<source>Waist Back to Natural Waist Back</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1940"/>
<source>Length from Waist Back to Natural Waist Back.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1944"/>
<source>arm_neck_back_to_elbow_bent</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1946"/>
<source>Arm: Neck Back to Elbow, high bend</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1947"/>
<source>Bend Arm with Elbow out, hand in front. Measure from Neck Back to Elbow Tip.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1952"/>
<source>arm_neck_back_to_wrist_bent</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1954"/>
<source>Arm: Neck Back to Wrist, high bend</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1955"/>
<source>Bend Arm with Elbow out, hand in front. Measure from Neck Back to Elbow Tip to Wrist bone.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1959"/>
<source>arm_neck_side_to_elbow_bent</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1961"/>
<source>Arm: Neck Side to Elbow, high bend</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1962"/>
<source>Bend Arm with Elbow out, hand in front. Measure from Neck Side to Elbow Tip.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1966"/>
<source>arm_neck_side_to_wrist_bent</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1968"/>
<source>Arm: Neck Side to Wrist, high bend</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1969"/>
<source>Bend Arm with Elbow out, hand in front. Measure from Neck Side to Elbow Tip to Wrist bone.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1974"/>
<source>arm_across_back_center_to_elbow_bent</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1976"/>
<source>Arm: Across Back Center to Elbow, high bend</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1977"/>
<source>Bend Arm with Elbow out, hand in front. Measure from Middle of Back to Elbow Tip.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1982"/>
<source>arm_across_back_center_to_wrist_bent</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1984"/>
<source>Arm: Across Back Center to Wrist, high bend</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1985"/>
<source>Bend Arm with Elbow out, hand in front. Measure from Middle of Back to Elbow Tip to Wrist bone.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1990"/>
<source>arm_armscye_back_center_to_wrist_bent</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1992"/>
<source>Arm: Armscye Back Center to Wrist, high bend</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1993"/>
<source>Bend Arm with Elbow out, hand in front. Measure from Armscye Back to Elbow Tip.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="2010"/>
<source>neck_back_to_bust_front</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="2012"/>
<source>Neck Back to Bust Front</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="2013"/>
<source>From Neck Back, over Shoulder, to Bust Front.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="2017"/>
<source>neck_back_to_armfold_front</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="2019"/>
<source>Neck Back to Armfold Front</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="2020"/>
<source>From Neck Back over Shoulder to Armfold Front.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="2024"/>
<source>neck_back_to_armfold_front_to_waist_side</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="2026"/>
<source>Neck Back, over Shoulder, to Waist Side</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="2027"/>
<source>From Neck Back, over Shoulder, down chest to Waist Side.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="2031"/>
<source>highbust_back_over_shoulder_to_armfold_front</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="2033"/>
<source>Highbust Back, over Shoulder, to Armfold Front</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="2034"/>
<source>From Highbust Back over Shoulder to Armfold Front.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="2038"/>
<source>highbust_back_over_shoulder_to_waist_front</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="2040"/>
<source>Highbust Back, over Shoulder, to Waist Front</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="2041"/>
<source>From Highbust Back, over Shoulder touching Neck Side, to Waist Front.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="2045"/>
<source>neck_back_to_armfold_front_to_neck_back</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="2047"/>
<source>Neck Back, to Armfold Front, to Neck Back</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="2048"/>
<source>From Neck Back, over Shoulder to Armfold Front, under arm and return to start.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="2053"/>
<source>across_back_center_to_armfold_front_to_across_back_center</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="2055"/>
<source>Across Back Center, circled around Shoulder</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="2056"/>
<source>From center of Across Back, over Shoulder, under Arm, and return to start.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="2061"/>
<source>neck_back_to_armfold_front_to_highbust_back</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="2063"/>
<source>Neck Back, to Armfold Front, to Highbust Back</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="2064"/>
<source>From Neck Back over Shoulder to Armfold Front, under arm to Highbust Back.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="2069"/>
<source>armfold_to_armfold_bust</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="2071"/>
<source>Armfold to Armfold, front, curved through Bust Front</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="2073"/>
<source>Measure in a curve from Armfold Left Front through Bust Front curved back up to Armfold Right Front.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="2077"/>
<source>armfold_to_bust_front</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="2079"/>
<source>Armfold to Bust Front</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="2080"/>
<source>Measure from Armfold Front to Bust Front, shortest distance between the two, as straight as possible.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="2084"/>
<source>highbust_b_over_shoulder_to_highbust_f</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="2086"/>
<source>Highbust Back, over Shoulder, to Highbust level</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="2088"/>
<source>From Highbust Back, over Shoulder, then aim at Bustpoint, stopping measurement at Highbust level.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="2093"/>
<source>armscye_arc</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="2095"/>
<source>Armscye: Arc</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="2096"/>
<source>From Armscye at Across Chest over ShoulderTip to Armscye at Across Back.</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="2112"/>
<source>dart_width_shoulder</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="2114"/>
<source>Dart Width: Shoulder</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="2115"/>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="2123"/>
<source>This information is pulled from pattern charts in some patternmaking systems, e.g. Winifred P. Aldrich's "Metric Pattern Cutting".</source>
<comment>Full measurement description.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="2120"/>
<source>dart_width_bust</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="2122"/>
<source>Dart Width: Bust</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="2128"/>
<source>dart_width_waist</source>
<comment>Name in a formula. Don't use math symbols and space in name!!!!</comment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="2130"/>
<source>Dart Width: Waist</source>
<comment>Full measurement name.</comment>
<translation type="unfinished"></translation>
</message>
</context>
</TS>
| gpl-3.0 |
TheWeatherCompany/terraform | vendor/github.com/hashicorp/go-oracle-terraform/compute/security_applications.go | 5793 | package compute
// SecurityApplicationsClient is a client for the Security Application functions of the Compute API.
type SecurityApplicationsClient struct {
ResourceClient
}
// SecurityApplications obtains a SecurityApplicationsClient which can be used to access to the
// Security Application functions of the Compute API
func (c *Client) SecurityApplications() *SecurityApplicationsClient {
return &SecurityApplicationsClient{
ResourceClient: ResourceClient{
Client: c,
ResourceDescription: "security application",
ContainerPath: "/secapplication/",
ResourceRootPath: "/secapplication",
}}
}
// SecurityApplicationInfo describes an existing security application.
type SecurityApplicationInfo struct {
// A description of the security application.
Description string `json:"description"`
// The TCP or UDP destination port number. This can be a port range, such as 5900-5999 for TCP.
DPort string `json:"dport"`
// The ICMP code.
ICMPCode SecurityApplicationICMPCode `json:"icmpcode"`
// The ICMP type.
ICMPType SecurityApplicationICMPType `json:"icmptype"`
// The three-part name of the Security Application (/Compute-identity_domain/user/object).
Name string `json:"name"`
// The protocol to use.
Protocol SecurityApplicationProtocol `json:"protocol"`
// The Uniform Resource Identifier
URI string `json:"uri"`
}
type SecurityApplicationProtocol string
const (
All SecurityApplicationProtocol = "all"
AH SecurityApplicationProtocol = "ah"
ESP SecurityApplicationProtocol = "esp"
ICMP SecurityApplicationProtocol = "icmp"
ICMPV6 SecurityApplicationProtocol = "icmpv6"
IGMP SecurityApplicationProtocol = "igmp"
IPIP SecurityApplicationProtocol = "ipip"
GRE SecurityApplicationProtocol = "gre"
MPLSIP SecurityApplicationProtocol = "mplsip"
OSPF SecurityApplicationProtocol = "ospf"
PIM SecurityApplicationProtocol = "pim"
RDP SecurityApplicationProtocol = "rdp"
SCTP SecurityApplicationProtocol = "sctp"
TCP SecurityApplicationProtocol = "tcp"
UDP SecurityApplicationProtocol = "udp"
)
type SecurityApplicationICMPCode string
const (
Admin SecurityApplicationICMPCode = "admin"
Df SecurityApplicationICMPCode = "df"
Host SecurityApplicationICMPCode = "host"
Network SecurityApplicationICMPCode = "network"
Port SecurityApplicationICMPCode = "port"
Protocol SecurityApplicationICMPCode = "protocol"
)
type SecurityApplicationICMPType string
const (
Echo SecurityApplicationICMPType = "echo"
Reply SecurityApplicationICMPType = "reply"
TTL SecurityApplicationICMPType = "ttl"
TraceRoute SecurityApplicationICMPType = "traceroute"
Unreachable SecurityApplicationICMPType = "unreachable"
)
func (c *SecurityApplicationsClient) success(result *SecurityApplicationInfo) (*SecurityApplicationInfo, error) {
c.unqualify(&result.Name)
return result, nil
}
// CreateSecurityApplicationInput describes the Security Application to create
type CreateSecurityApplicationInput struct {
// A description of the security application.
// Optional
Description string `json:"description"`
// The TCP or UDP destination port number.
// You can also specify a port range, such as 5900-5999 for TCP.
// This parameter isn't relevant to the icmp protocol.
// Required if the Protocol is TCP or UDP
DPort string `json:"dport"`
// The ICMP code. This parameter is relevant only if you specify ICMP as the protocol.
// If you specify icmp as the protocol and don't specify icmptype or icmpcode, then all ICMP packets are matched.
// Optional
ICMPCode SecurityApplicationICMPCode `json:"icmpcode,omitempty"`
// This parameter is relevant only if you specify ICMP as the protocol.
// If you specify icmp as the protocol and don't specify icmptype or icmpcode, then all ICMP packets are matched.
// Optional
ICMPType SecurityApplicationICMPType `json:"icmptype,omitempty"`
// The three-part name of the Security Application (/Compute-identity_domain/user/object).
// Object names can contain only alphanumeric characters, hyphens, underscores, and periods. Object names are case-sensitive.
// Required
Name string `json:"name"`
// The protocol to use.
// Required
Protocol SecurityApplicationProtocol `json:"protocol"`
}
// CreateSecurityApplication creates a new security application.
func (c *SecurityApplicationsClient) CreateSecurityApplication(input *CreateSecurityApplicationInput) (*SecurityApplicationInfo, error) {
input.Name = c.getQualifiedName(input.Name)
var appInfo SecurityApplicationInfo
if err := c.createResource(&input, &appInfo); err != nil {
return nil, err
}
return c.success(&appInfo)
}
// GetSecurityApplicationInput describes the Security Application to obtain
type GetSecurityApplicationInput struct {
// The three-part name of the Security Application (/Compute-identity_domain/user/object).
// Required
Name string `json:"name"`
}
// GetSecurityApplication retrieves the security application with the given name.
func (c *SecurityApplicationsClient) GetSecurityApplication(input *GetSecurityApplicationInput) (*SecurityApplicationInfo, error) {
var appInfo SecurityApplicationInfo
if err := c.getResource(input.Name, &appInfo); err != nil {
return nil, err
}
return c.success(&appInfo)
}
// DeleteSecurityApplicationInput describes the Security Application to delete
type DeleteSecurityApplicationInput struct {
// The three-part name of the Security Application (/Compute-identity_domain/user/object).
// Required
Name string `json:"name"`
}
// DeleteSecurityApplication deletes the security application with the given name.
func (c *SecurityApplicationsClient) DeleteSecurityApplication(input *DeleteSecurityApplicationInput) error {
return c.deleteResource(input.Name)
}
| mpl-2.0 |
KOala888/GB_kernel | linux_kernel_galaxyplayer-master/drivers/infiniband/ulp/iser/iser_initiator.c | 16024 | /*
* Copyright (c) 2004, 2005, 2006 Voltaire, Inc. All rights reserved.
*
* This software is available to you under a choice of one of two
* licenses. You may choose to be licensed under the terms of the GNU
* General Public License (GPL) Version 2, available from the file
* COPYING in the main directory of this source tree, or the
* OpenIB.org BSD license below:
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer.
*
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/mm.h>
#include <linux/scatterlist.h>
#include <linux/kfifo.h>
#include <scsi/scsi_cmnd.h>
#include <scsi/scsi_host.h>
#include "iscsi_iser.h"
/* Register user buffer memory and initialize passive rdma
* dto descriptor. Total data size is stored in
* iser_task->data[ISER_DIR_IN].data_len
*/
static int iser_prepare_read_cmd(struct iscsi_task *task,
unsigned int edtl)
{
struct iscsi_iser_task *iser_task = task->dd_data;
struct iser_regd_buf *regd_buf;
int err;
struct iser_hdr *hdr = &iser_task->desc.iser_header;
struct iser_data_buf *buf_in = &iser_task->data[ISER_DIR_IN];
err = iser_dma_map_task_data(iser_task,
buf_in,
ISER_DIR_IN,
DMA_FROM_DEVICE);
if (err)
return err;
if (edtl > iser_task->data[ISER_DIR_IN].data_len) {
iser_err("Total data length: %ld, less than EDTL: "
"%d, in READ cmd BHS itt: %d, conn: 0x%p\n",
iser_task->data[ISER_DIR_IN].data_len, edtl,
task->itt, iser_task->iser_conn);
return -EINVAL;
}
err = iser_reg_rdma_mem(iser_task,ISER_DIR_IN);
if (err) {
iser_err("Failed to set up Data-IN RDMA\n");
return err;
}
regd_buf = &iser_task->rdma_regd[ISER_DIR_IN];
hdr->flags |= ISER_RSV;
hdr->read_stag = cpu_to_be32(regd_buf->reg.rkey);
hdr->read_va = cpu_to_be64(regd_buf->reg.va);
iser_dbg("Cmd itt:%d READ tags RKEY:%#.4X VA:%#llX\n",
task->itt, regd_buf->reg.rkey,
(unsigned long long)regd_buf->reg.va);
return 0;
}
/* Register user buffer memory and initialize passive rdma
* dto descriptor. Total data size is stored in
* task->data[ISER_DIR_OUT].data_len
*/
static int
iser_prepare_write_cmd(struct iscsi_task *task,
unsigned int imm_sz,
unsigned int unsol_sz,
unsigned int edtl)
{
struct iscsi_iser_task *iser_task = task->dd_data;
struct iser_regd_buf *regd_buf;
int err;
struct iser_hdr *hdr = &iser_task->desc.iser_header;
struct iser_data_buf *buf_out = &iser_task->data[ISER_DIR_OUT];
struct ib_sge *tx_dsg = &iser_task->desc.tx_sg[1];
err = iser_dma_map_task_data(iser_task,
buf_out,
ISER_DIR_OUT,
DMA_TO_DEVICE);
if (err)
return err;
if (edtl > iser_task->data[ISER_DIR_OUT].data_len) {
iser_err("Total data length: %ld, less than EDTL: %d, "
"in WRITE cmd BHS itt: %d, conn: 0x%p\n",
iser_task->data[ISER_DIR_OUT].data_len,
edtl, task->itt, task->conn);
return -EINVAL;
}
err = iser_reg_rdma_mem(iser_task,ISER_DIR_OUT);
if (err != 0) {
iser_err("Failed to register write cmd RDMA mem\n");
return err;
}
regd_buf = &iser_task->rdma_regd[ISER_DIR_OUT];
if (unsol_sz < edtl) {
hdr->flags |= ISER_WSV;
hdr->write_stag = cpu_to_be32(regd_buf->reg.rkey);
hdr->write_va = cpu_to_be64(regd_buf->reg.va + unsol_sz);
iser_dbg("Cmd itt:%d, WRITE tags, RKEY:%#.4X "
"VA:%#llX + unsol:%d\n",
task->itt, regd_buf->reg.rkey,
(unsigned long long)regd_buf->reg.va, unsol_sz);
}
if (imm_sz > 0) {
iser_dbg("Cmd itt:%d, WRITE, adding imm.data sz: %d\n",
task->itt, imm_sz);
tx_dsg->addr = regd_buf->reg.va;
tx_dsg->length = imm_sz;
tx_dsg->lkey = regd_buf->reg.lkey;
iser_task->desc.num_sge = 2;
}
return 0;
}
/* creates a new tx descriptor and adds header regd buffer */
static void iser_create_send_desc(struct iser_conn *ib_conn,
struct iser_tx_desc *tx_desc)
{
struct iser_device *device = ib_conn->device;
ib_dma_sync_single_for_cpu(device->ib_device,
tx_desc->dma_addr, ISER_HEADERS_LEN, DMA_TO_DEVICE);
memset(&tx_desc->iser_header, 0, sizeof(struct iser_hdr));
tx_desc->iser_header.flags = ISER_VER;
tx_desc->num_sge = 1;
if (tx_desc->tx_sg[0].lkey != device->mr->lkey) {
tx_desc->tx_sg[0].lkey = device->mr->lkey;
iser_dbg("sdesc %p lkey mismatch, fixing\n", tx_desc);
}
}
int iser_alloc_rx_descriptors(struct iser_conn *ib_conn)
{
int i, j;
u64 dma_addr;
struct iser_rx_desc *rx_desc;
struct ib_sge *rx_sg;
struct iser_device *device = ib_conn->device;
ib_conn->rx_descs = kmalloc(ISER_QP_MAX_RECV_DTOS *
sizeof(struct iser_rx_desc), GFP_KERNEL);
if (!ib_conn->rx_descs)
goto rx_desc_alloc_fail;
rx_desc = ib_conn->rx_descs;
for (i = 0; i < ISER_QP_MAX_RECV_DTOS; i++, rx_desc++) {
dma_addr = ib_dma_map_single(device->ib_device, (void *)rx_desc,
ISER_RX_PAYLOAD_SIZE, DMA_FROM_DEVICE);
if (ib_dma_mapping_error(device->ib_device, dma_addr))
goto rx_desc_dma_map_failed;
rx_desc->dma_addr = dma_addr;
rx_sg = &rx_desc->rx_sg;
rx_sg->addr = rx_desc->dma_addr;
rx_sg->length = ISER_RX_PAYLOAD_SIZE;
rx_sg->lkey = device->mr->lkey;
}
ib_conn->rx_desc_head = 0;
return 0;
rx_desc_dma_map_failed:
rx_desc = ib_conn->rx_descs;
for (j = 0; j < i; j++, rx_desc++)
ib_dma_unmap_single(device->ib_device, rx_desc->dma_addr,
ISER_RX_PAYLOAD_SIZE, DMA_FROM_DEVICE);
kfree(ib_conn->rx_descs);
ib_conn->rx_descs = NULL;
rx_desc_alloc_fail:
iser_err("failed allocating rx descriptors / data buffers\n");
return -ENOMEM;
}
void iser_free_rx_descriptors(struct iser_conn *ib_conn)
{
int i;
struct iser_rx_desc *rx_desc;
struct iser_device *device = ib_conn->device;
if (ib_conn->login_buf) {
ib_dma_unmap_single(device->ib_device, ib_conn->login_dma,
ISER_RX_LOGIN_SIZE, DMA_FROM_DEVICE);
kfree(ib_conn->login_buf);
}
if (!ib_conn->rx_descs)
return;
rx_desc = ib_conn->rx_descs;
for (i = 0; i < ISER_QP_MAX_RECV_DTOS; i++, rx_desc++)
ib_dma_unmap_single(device->ib_device, rx_desc->dma_addr,
ISER_RX_PAYLOAD_SIZE, DMA_FROM_DEVICE);
kfree(ib_conn->rx_descs);
}
/**
* iser_conn_set_full_featured_mode - (iSER API)
*/
int iser_conn_set_full_featured_mode(struct iscsi_conn *conn)
{
struct iscsi_iser_conn *iser_conn = conn->dd_data;
iser_dbg("Initially post: %d\n", ISER_MIN_POSTED_RX);
/* Check that there is no posted recv or send buffers left - */
/* they must be consumed during the login phase */
BUG_ON(iser_conn->ib_conn->post_recv_buf_count != 0);
BUG_ON(atomic_read(&iser_conn->ib_conn->post_send_buf_count) != 0);
if (iser_alloc_rx_descriptors(iser_conn->ib_conn))
return -ENOMEM;
/* Initial post receive buffers */
if (iser_post_recvm(iser_conn->ib_conn, ISER_MIN_POSTED_RX))
return -ENOMEM;
return 0;
}
/**
* iser_send_command - send command PDU
*/
int iser_send_command(struct iscsi_conn *conn,
struct iscsi_task *task)
{
struct iscsi_iser_conn *iser_conn = conn->dd_data;
struct iscsi_iser_task *iser_task = task->dd_data;
unsigned long edtl;
int err;
struct iser_data_buf *data_buf;
struct iscsi_cmd *hdr = (struct iscsi_cmd *)task->hdr;
struct scsi_cmnd *sc = task->sc;
struct iser_tx_desc *tx_desc = &iser_task->desc;
edtl = ntohl(hdr->data_length);
/* build the tx desc regd header and add it to the tx desc dto */
tx_desc->type = ISCSI_TX_SCSI_COMMAND;
iser_create_send_desc(iser_conn->ib_conn, tx_desc);
if (hdr->flags & ISCSI_FLAG_CMD_READ)
data_buf = &iser_task->data[ISER_DIR_IN];
else
data_buf = &iser_task->data[ISER_DIR_OUT];
if (scsi_sg_count(sc)) { /* using a scatter list */
data_buf->buf = scsi_sglist(sc);
data_buf->size = scsi_sg_count(sc);
}
data_buf->data_len = scsi_bufflen(sc);
if (hdr->flags & ISCSI_FLAG_CMD_READ) {
err = iser_prepare_read_cmd(task, edtl);
if (err)
goto send_command_error;
}
if (hdr->flags & ISCSI_FLAG_CMD_WRITE) {
err = iser_prepare_write_cmd(task,
task->imm_count,
task->imm_count +
task->unsol_r2t.data_length,
edtl);
if (err)
goto send_command_error;
}
iser_task->status = ISER_TASK_STATUS_STARTED;
err = iser_post_send(iser_conn->ib_conn, tx_desc);
if (!err)
return 0;
send_command_error:
iser_err("conn %p failed task->itt %d err %d\n",conn, task->itt, err);
return err;
}
/**
* iser_send_data_out - send data out PDU
*/
int iser_send_data_out(struct iscsi_conn *conn,
struct iscsi_task *task,
struct iscsi_data *hdr)
{
struct iscsi_iser_conn *iser_conn = conn->dd_data;
struct iscsi_iser_task *iser_task = task->dd_data;
struct iser_tx_desc *tx_desc = NULL;
struct iser_regd_buf *regd_buf;
unsigned long buf_offset;
unsigned long data_seg_len;
uint32_t itt;
int err = 0;
struct ib_sge *tx_dsg;
itt = (__force uint32_t)hdr->itt;
data_seg_len = ntoh24(hdr->dlength);
buf_offset = ntohl(hdr->offset);
iser_dbg("%s itt %d dseg_len %d offset %d\n",
__func__,(int)itt,(int)data_seg_len,(int)buf_offset);
tx_desc = kmem_cache_zalloc(ig.desc_cache, GFP_ATOMIC);
if (tx_desc == NULL) {
iser_err("Failed to alloc desc for post dataout\n");
return -ENOMEM;
}
tx_desc->type = ISCSI_TX_DATAOUT;
tx_desc->iser_header.flags = ISER_VER;
memcpy(&tx_desc->iscsi_header, hdr, sizeof(struct iscsi_hdr));
/* build the tx desc */
iser_initialize_task_headers(task, tx_desc);
regd_buf = &iser_task->rdma_regd[ISER_DIR_OUT];
tx_dsg = &tx_desc->tx_sg[1];
tx_dsg->addr = regd_buf->reg.va + buf_offset;
tx_dsg->length = data_seg_len;
tx_dsg->lkey = regd_buf->reg.lkey;
tx_desc->num_sge = 2;
if (buf_offset + data_seg_len > iser_task->data[ISER_DIR_OUT].data_len) {
iser_err("Offset:%ld & DSL:%ld in Data-Out "
"inconsistent with total len:%ld, itt:%d\n",
buf_offset, data_seg_len,
iser_task->data[ISER_DIR_OUT].data_len, itt);
err = -EINVAL;
goto send_data_out_error;
}
iser_dbg("data-out itt: %d, offset: %ld, sz: %ld\n",
itt, buf_offset, data_seg_len);
err = iser_post_send(iser_conn->ib_conn, tx_desc);
if (!err)
return 0;
send_data_out_error:
kmem_cache_free(ig.desc_cache, tx_desc);
iser_err("conn %p failed err %d\n",conn, err);
return err;
}
int iser_send_control(struct iscsi_conn *conn,
struct iscsi_task *task)
{
struct iscsi_iser_conn *iser_conn = conn->dd_data;
struct iscsi_iser_task *iser_task = task->dd_data;
struct iser_tx_desc *mdesc = &iser_task->desc;
unsigned long data_seg_len;
int err = 0;
struct iser_device *device;
/* build the tx desc regd header and add it to the tx desc dto */
mdesc->type = ISCSI_TX_CONTROL;
iser_create_send_desc(iser_conn->ib_conn, mdesc);
device = iser_conn->ib_conn->device;
data_seg_len = ntoh24(task->hdr->dlength);
if (data_seg_len > 0) {
struct ib_sge *tx_dsg = &mdesc->tx_sg[1];
if (task != conn->login_task) {
iser_err("data present on non login task!!!\n");
goto send_control_error;
}
memcpy(iser_conn->ib_conn->login_buf, task->data,
task->data_count);
tx_dsg->addr = iser_conn->ib_conn->login_dma;
tx_dsg->length = data_seg_len;
tx_dsg->lkey = device->mr->lkey;
mdesc->num_sge = 2;
}
if (task == conn->login_task) {
err = iser_post_recvl(iser_conn->ib_conn);
if (err)
goto send_control_error;
}
err = iser_post_send(iser_conn->ib_conn, mdesc);
if (!err)
return 0;
send_control_error:
iser_err("conn %p failed err %d\n",conn, err);
return err;
}
/**
* iser_rcv_dto_completion - recv DTO completion
*/
void iser_rcv_completion(struct iser_rx_desc *rx_desc,
unsigned long rx_xfer_len,
struct iser_conn *ib_conn)
{
struct iscsi_iser_conn *conn = ib_conn->iser_conn;
struct iscsi_hdr *hdr;
u64 rx_dma;
int rx_buflen, outstanding, count, err;
/* differentiate between login to all other PDUs */
if ((char *)rx_desc == ib_conn->login_buf) {
rx_dma = ib_conn->login_dma;
rx_buflen = ISER_RX_LOGIN_SIZE;
} else {
rx_dma = rx_desc->dma_addr;
rx_buflen = ISER_RX_PAYLOAD_SIZE;
}
ib_dma_sync_single_for_cpu(ib_conn->device->ib_device, rx_dma,
rx_buflen, DMA_FROM_DEVICE);
hdr = &rx_desc->iscsi_header;
iser_dbg("op 0x%x itt 0x%x dlen %d\n", hdr->opcode,
hdr->itt, (int)(rx_xfer_len - ISER_HEADERS_LEN));
iscsi_iser_recv(conn->iscsi_conn, hdr,
rx_desc->data, rx_xfer_len - ISER_HEADERS_LEN);
ib_dma_sync_single_for_device(ib_conn->device->ib_device, rx_dma,
rx_buflen, DMA_FROM_DEVICE);
/* decrementing conn->post_recv_buf_count only --after-- freeing the *
* task eliminates the need to worry on tasks which are completed in *
* parallel to the execution of iser_conn_term. So the code that waits *
* for the posted rx bufs refcount to become zero handles everything */
conn->ib_conn->post_recv_buf_count--;
if (rx_dma == ib_conn->login_dma)
return;
outstanding = ib_conn->post_recv_buf_count;
if (outstanding + ISER_MIN_POSTED_RX <= ISER_QP_MAX_RECV_DTOS) {
count = min(ISER_QP_MAX_RECV_DTOS - outstanding,
ISER_MIN_POSTED_RX);
err = iser_post_recvm(ib_conn, count);
if (err)
iser_err("posting %d rx bufs err %d\n", count, err);
}
}
void iser_snd_completion(struct iser_tx_desc *tx_desc,
struct iser_conn *ib_conn)
{
struct iscsi_task *task;
struct iser_device *device = ib_conn->device;
if (tx_desc->type == ISCSI_TX_DATAOUT) {
ib_dma_unmap_single(device->ib_device, tx_desc->dma_addr,
ISER_HEADERS_LEN, DMA_TO_DEVICE);
kmem_cache_free(ig.desc_cache, tx_desc);
}
atomic_dec(&ib_conn->post_send_buf_count);
if (tx_desc->type == ISCSI_TX_CONTROL) {
/* this arithmetic is legal by libiscsi dd_data allocation */
task = (void *) ((long)(void *)tx_desc -
sizeof(struct iscsi_task));
if (task->hdr->itt == RESERVED_ITT)
iscsi_put_task(task);
}
}
void iser_task_rdma_init(struct iscsi_iser_task *iser_task)
{
iser_task->status = ISER_TASK_STATUS_INIT;
iser_task->dir[ISER_DIR_IN] = 0;
iser_task->dir[ISER_DIR_OUT] = 0;
iser_task->data[ISER_DIR_IN].data_len = 0;
iser_task->data[ISER_DIR_OUT].data_len = 0;
memset(&iser_task->rdma_regd[ISER_DIR_IN], 0,
sizeof(struct iser_regd_buf));
memset(&iser_task->rdma_regd[ISER_DIR_OUT], 0,
sizeof(struct iser_regd_buf));
}
void iser_task_rdma_finalize(struct iscsi_iser_task *iser_task)
{
int is_rdma_aligned = 1;
struct iser_regd_buf *regd;
/* if we were reading, copy back to unaligned sglist,
* anyway dma_unmap and free the copy
*/
if (iser_task->data_copy[ISER_DIR_IN].copy_buf != NULL) {
is_rdma_aligned = 0;
iser_finalize_rdma_unaligned_sg(iser_task, ISER_DIR_IN);
}
if (iser_task->data_copy[ISER_DIR_OUT].copy_buf != NULL) {
is_rdma_aligned = 0;
iser_finalize_rdma_unaligned_sg(iser_task, ISER_DIR_OUT);
}
if (iser_task->dir[ISER_DIR_IN]) {
regd = &iser_task->rdma_regd[ISER_DIR_IN];
if (regd->reg.is_fmr)
iser_unreg_mem(®d->reg);
}
if (iser_task->dir[ISER_DIR_OUT]) {
regd = &iser_task->rdma_regd[ISER_DIR_OUT];
if (regd->reg.is_fmr)
iser_unreg_mem(®d->reg);
}
/* if the data was unaligned, it was already unmapped and then copied */
if (is_rdma_aligned)
iser_dma_unmap_task_data(iser_task);
}
| gpl-2.0 |
KarolKraskiewicz/autoscaler | vertical-pod-autoscaler/vendor/github.com/onsi/gomega/matchers/match_yaml_matcher.go | 2453 | package matchers
import (
"fmt"
"reflect"
"strings"
"github.com/onsi/gomega/format"
"gopkg.in/yaml.v2"
)
type MatchYAMLMatcher struct {
YAMLToMatch interface{}
}
func (matcher *MatchYAMLMatcher) Match(actual interface{}) (success bool, err error) {
actualString, expectedString, err := matcher.toStrings(actual)
if err != nil {
return false, err
}
var aval interface{}
var eval interface{}
if err := yaml.Unmarshal([]byte(actualString), &aval); err != nil {
return false, fmt.Errorf("Actual '%s' should be valid YAML, but it is not.\nUnderlying error:%s", actualString, err)
}
if err := yaml.Unmarshal([]byte(expectedString), &eval); err != nil {
return false, fmt.Errorf("Expected '%s' should be valid YAML, but it is not.\nUnderlying error:%s", expectedString, err)
}
return reflect.DeepEqual(aval, eval), nil
}
func (matcher *MatchYAMLMatcher) FailureMessage(actual interface{}) (message string) {
actualString, expectedString, _ := matcher.toNormalisedStrings(actual)
return format.Message(actualString, "to match YAML of", expectedString)
}
func (matcher *MatchYAMLMatcher) NegatedFailureMessage(actual interface{}) (message string) {
actualString, expectedString, _ := matcher.toNormalisedStrings(actual)
return format.Message(actualString, "not to match YAML of", expectedString)
}
func (matcher *MatchYAMLMatcher) toNormalisedStrings(actual interface{}) (actualFormatted, expectedFormatted string, err error) {
actualString, expectedString, err := matcher.toStrings(actual)
return normalise(actualString), normalise(expectedString), err
}
func normalise(input string) string {
var val interface{}
err := yaml.Unmarshal([]byte(input), &val)
if err != nil {
panic(err) // guarded by Match
}
output, err := yaml.Marshal(val)
if err != nil {
panic(err) // guarded by Unmarshal
}
return strings.TrimSpace(string(output))
}
func (matcher *MatchYAMLMatcher) toStrings(actual interface{}) (actualFormatted, expectedFormatted string, err error) {
actualString, ok := toString(actual)
if !ok {
return "", "", fmt.Errorf("MatchYAMLMatcher matcher requires a string, stringer, or []byte. Got actual:\n%s", format.Object(actual, 1))
}
expectedString, ok := toString(matcher.YAMLToMatch)
if !ok {
return "", "", fmt.Errorf("MatchYAMLMatcher matcher requires a string, stringer, or []byte. Got expected:\n%s", format.Object(matcher.YAMLToMatch, 1))
}
return actualString, expectedString, nil
}
| apache-2.0 |
Naoya-Horiguchi/linux | drivers/usb/storage/transport.c | 44743 | // SPDX-License-Identifier: GPL-2.0+
/*
* Driver for USB Mass Storage compliant devices
*
* Current development and maintenance by:
* (c) 1999-2002 Matthew Dharm ([email protected])
*
* Developed with the assistance of:
* (c) 2000 David L. Brown, Jr. ([email protected])
* (c) 2000 Stephen J. Gowdy ([email protected])
* (c) 2002 Alan Stern <[email protected]>
*
* Initial work by:
* (c) 1999 Michael Gee ([email protected])
*
* This driver is based on the 'USB Mass Storage Class' document. This
* describes in detail the protocol used to communicate with such
* devices. Clearly, the designers had SCSI and ATAPI commands in
* mind when they created this document. The commands are all very
* similar to commands in the SCSI-II and ATAPI specifications.
*
* It is important to note that in a number of cases this class
* exhibits class-specific exemptions from the USB specification.
* Notably the usage of NAK, STALL and ACK differs from the norm, in
* that they are used to communicate wait, failed and OK on commands.
*
* Also, for certain devices, the interrupt endpoint is used to convey
* status of a command.
*/
#include <linux/sched.h>
#include <linux/gfp.h>
#include <linux/errno.h>
#include <linux/export.h>
#include <linux/usb/quirks.h>
#include <scsi/scsi.h>
#include <scsi/scsi_eh.h>
#include <scsi/scsi_device.h>
#include "usb.h"
#include "transport.h"
#include "protocol.h"
#include "scsiglue.h"
#include "debug.h"
#include <linux/blkdev.h>
#include "../../scsi/sd.h"
/***********************************************************************
* Data transfer routines
***********************************************************************/
/*
* This is subtle, so pay attention:
* ---------------------------------
* We're very concerned about races with a command abort. Hanging this code
* is a sure fire way to hang the kernel. (Note that this discussion applies
* only to transactions resulting from a scsi queued-command, since only
* these transactions are subject to a scsi abort. Other transactions, such
* as those occurring during device-specific initialization, must be handled
* by a separate code path.)
*
* The abort function (usb_storage_command_abort() in scsiglue.c) first
* sets the machine state and the ABORTING bit in us->dflags to prevent
* new URBs from being submitted. It then calls usb_stor_stop_transport()
* below, which atomically tests-and-clears the URB_ACTIVE bit in us->dflags
* to see if the current_urb needs to be stopped. Likewise, the SG_ACTIVE
* bit is tested to see if the current_sg scatter-gather request needs to be
* stopped. The timeout callback routine does much the same thing.
*
* When a disconnect occurs, the DISCONNECTING bit in us->dflags is set to
* prevent new URBs from being submitted, and usb_stor_stop_transport() is
* called to stop any ongoing requests.
*
* The submit function first verifies that the submitting is allowed
* (neither ABORTING nor DISCONNECTING bits are set) and that the submit
* completes without errors, and only then sets the URB_ACTIVE bit. This
* prevents the stop_transport() function from trying to cancel the URB
* while the submit call is underway. Next, the submit function must test
* the flags to see if an abort or disconnect occurred during the submission
* or before the URB_ACTIVE bit was set. If so, it's essential to cancel
* the URB if it hasn't been cancelled already (i.e., if the URB_ACTIVE bit
* is still set). Either way, the function must then wait for the URB to
* finish. Note that the URB can still be in progress even after a call to
* usb_unlink_urb() returns.
*
* The idea is that (1) once the ABORTING or DISCONNECTING bit is set,
* either the stop_transport() function or the submitting function
* is guaranteed to call usb_unlink_urb() for an active URB,
* and (2) test_and_clear_bit() prevents usb_unlink_urb() from being
* called more than once or from being called during usb_submit_urb().
*/
/*
* This is the completion handler which will wake us up when an URB
* completes.
*/
static void usb_stor_blocking_completion(struct urb *urb)
{
struct completion *urb_done_ptr = urb->context;
complete(urb_done_ptr);
}
/*
* This is the common part of the URB message submission code
*
* All URBs from the usb-storage driver involved in handling a queued scsi
* command _must_ pass through this function (or something like it) for the
* abort mechanisms to work properly.
*/
static int usb_stor_msg_common(struct us_data *us, int timeout)
{
struct completion urb_done;
long timeleft;
int status;
/* don't submit URBs during abort processing */
if (test_bit(US_FLIDX_ABORTING, &us->dflags))
return -EIO;
/* set up data structures for the wakeup system */
init_completion(&urb_done);
/* fill the common fields in the URB */
us->current_urb->context = &urb_done;
us->current_urb->transfer_flags = 0;
/*
* we assume that if transfer_buffer isn't us->iobuf then it
* hasn't been mapped for DMA. Yes, this is clunky, but it's
* easier than always having the caller tell us whether the
* transfer buffer has already been mapped.
*/
if (us->current_urb->transfer_buffer == us->iobuf)
us->current_urb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
us->current_urb->transfer_dma = us->iobuf_dma;
/* submit the URB */
status = usb_submit_urb(us->current_urb, GFP_NOIO);
if (status) {
/* something went wrong */
return status;
}
/*
* since the URB has been submitted successfully, it's now okay
* to cancel it
*/
set_bit(US_FLIDX_URB_ACTIVE, &us->dflags);
/* did an abort occur during the submission? */
if (test_bit(US_FLIDX_ABORTING, &us->dflags)) {
/* cancel the URB, if it hasn't been cancelled already */
if (test_and_clear_bit(US_FLIDX_URB_ACTIVE, &us->dflags)) {
usb_stor_dbg(us, "-- cancelling URB\n");
usb_unlink_urb(us->current_urb);
}
}
/* wait for the completion of the URB */
timeleft = wait_for_completion_interruptible_timeout(
&urb_done, timeout ? : MAX_SCHEDULE_TIMEOUT);
clear_bit(US_FLIDX_URB_ACTIVE, &us->dflags);
if (timeleft <= 0) {
usb_stor_dbg(us, "%s -- cancelling URB\n",
timeleft == 0 ? "Timeout" : "Signal");
usb_kill_urb(us->current_urb);
}
/* return the URB status */
return us->current_urb->status;
}
/*
* Transfer one control message, with timeouts, and allowing early
* termination. Return codes are usual -Exxx, *not* USB_STOR_XFER_xxx.
*/
int usb_stor_control_msg(struct us_data *us, unsigned int pipe,
u8 request, u8 requesttype, u16 value, u16 index,
void *data, u16 size, int timeout)
{
int status;
usb_stor_dbg(us, "rq=%02x rqtype=%02x value=%04x index=%02x len=%u\n",
request, requesttype, value, index, size);
/* fill in the devrequest structure */
us->cr->bRequestType = requesttype;
us->cr->bRequest = request;
us->cr->wValue = cpu_to_le16(value);
us->cr->wIndex = cpu_to_le16(index);
us->cr->wLength = cpu_to_le16(size);
/* fill and submit the URB */
usb_fill_control_urb(us->current_urb, us->pusb_dev, pipe,
(unsigned char*) us->cr, data, size,
usb_stor_blocking_completion, NULL);
status = usb_stor_msg_common(us, timeout);
/* return the actual length of the data transferred if no error */
if (status == 0)
status = us->current_urb->actual_length;
return status;
}
EXPORT_SYMBOL_GPL(usb_stor_control_msg);
/*
* This is a version of usb_clear_halt() that allows early termination and
* doesn't read the status from the device -- this is because some devices
* crash their internal firmware when the status is requested after a halt.
*
* A definitive list of these 'bad' devices is too difficult to maintain or
* make complete enough to be useful. This problem was first observed on the
* Hagiwara FlashGate DUAL unit. However, bus traces reveal that neither
* MacOS nor Windows checks the status after clearing a halt.
*
* Since many vendors in this space limit their testing to interoperability
* with these two OSes, specification violations like this one are common.
*/
int usb_stor_clear_halt(struct us_data *us, unsigned int pipe)
{
int result;
int endp = usb_pipeendpoint(pipe);
if (usb_pipein (pipe))
endp |= USB_DIR_IN;
result = usb_stor_control_msg(us, us->send_ctrl_pipe,
USB_REQ_CLEAR_FEATURE, USB_RECIP_ENDPOINT,
USB_ENDPOINT_HALT, endp,
NULL, 0, 3*HZ);
if (result >= 0)
usb_reset_endpoint(us->pusb_dev, endp);
usb_stor_dbg(us, "result = %d\n", result);
return result;
}
EXPORT_SYMBOL_GPL(usb_stor_clear_halt);
/*
* Interpret the results of a URB transfer
*
* This function prints appropriate debugging messages, clears halts on
* non-control endpoints, and translates the status to the corresponding
* USB_STOR_XFER_xxx return code.
*/
static int interpret_urb_result(struct us_data *us, unsigned int pipe,
unsigned int length, int result, unsigned int partial)
{
usb_stor_dbg(us, "Status code %d; transferred %u/%u\n",
result, partial, length);
switch (result) {
/* no error code; did we send all the data? */
case 0:
if (partial != length) {
usb_stor_dbg(us, "-- short transfer\n");
return USB_STOR_XFER_SHORT;
}
usb_stor_dbg(us, "-- transfer complete\n");
return USB_STOR_XFER_GOOD;
/* stalled */
case -EPIPE:
/*
* for control endpoints, (used by CB[I]) a stall indicates
* a failed command
*/
if (usb_pipecontrol(pipe)) {
usb_stor_dbg(us, "-- stall on control pipe\n");
return USB_STOR_XFER_STALLED;
}
/* for other sorts of endpoint, clear the stall */
usb_stor_dbg(us, "clearing endpoint halt for pipe 0x%x\n",
pipe);
if (usb_stor_clear_halt(us, pipe) < 0)
return USB_STOR_XFER_ERROR;
return USB_STOR_XFER_STALLED;
/* babble - the device tried to send more than we wanted to read */
case -EOVERFLOW:
usb_stor_dbg(us, "-- babble\n");
return USB_STOR_XFER_LONG;
/* the transfer was cancelled by abort, disconnect, or timeout */
case -ECONNRESET:
usb_stor_dbg(us, "-- transfer cancelled\n");
return USB_STOR_XFER_ERROR;
/* short scatter-gather read transfer */
case -EREMOTEIO:
usb_stor_dbg(us, "-- short read transfer\n");
return USB_STOR_XFER_SHORT;
/* abort or disconnect in progress */
case -EIO:
usb_stor_dbg(us, "-- abort or disconnect in progress\n");
return USB_STOR_XFER_ERROR;
/* the catch-all error case */
default:
usb_stor_dbg(us, "-- unknown error\n");
return USB_STOR_XFER_ERROR;
}
}
/*
* Transfer one control message, without timeouts, but allowing early
* termination. Return codes are USB_STOR_XFER_xxx.
*/
int usb_stor_ctrl_transfer(struct us_data *us, unsigned int pipe,
u8 request, u8 requesttype, u16 value, u16 index,
void *data, u16 size)
{
int result;
usb_stor_dbg(us, "rq=%02x rqtype=%02x value=%04x index=%02x len=%u\n",
request, requesttype, value, index, size);
/* fill in the devrequest structure */
us->cr->bRequestType = requesttype;
us->cr->bRequest = request;
us->cr->wValue = cpu_to_le16(value);
us->cr->wIndex = cpu_to_le16(index);
us->cr->wLength = cpu_to_le16(size);
/* fill and submit the URB */
usb_fill_control_urb(us->current_urb, us->pusb_dev, pipe,
(unsigned char*) us->cr, data, size,
usb_stor_blocking_completion, NULL);
result = usb_stor_msg_common(us, 0);
return interpret_urb_result(us, pipe, size, result,
us->current_urb->actual_length);
}
EXPORT_SYMBOL_GPL(usb_stor_ctrl_transfer);
/*
* Receive one interrupt buffer, without timeouts, but allowing early
* termination. Return codes are USB_STOR_XFER_xxx.
*
* This routine always uses us->recv_intr_pipe as the pipe and
* us->ep_bInterval as the interrupt interval.
*/
static int usb_stor_intr_transfer(struct us_data *us, void *buf,
unsigned int length)
{
int result;
unsigned int pipe = us->recv_intr_pipe;
unsigned int maxp;
usb_stor_dbg(us, "xfer %u bytes\n", length);
/* calculate the max packet size */
maxp = usb_maxpacket(us->pusb_dev, pipe, usb_pipeout(pipe));
if (maxp > length)
maxp = length;
/* fill and submit the URB */
usb_fill_int_urb(us->current_urb, us->pusb_dev, pipe, buf,
maxp, usb_stor_blocking_completion, NULL,
us->ep_bInterval);
result = usb_stor_msg_common(us, 0);
return interpret_urb_result(us, pipe, length, result,
us->current_urb->actual_length);
}
/*
* Transfer one buffer via bulk pipe, without timeouts, but allowing early
* termination. Return codes are USB_STOR_XFER_xxx. If the bulk pipe
* stalls during the transfer, the halt is automatically cleared.
*/
int usb_stor_bulk_transfer_buf(struct us_data *us, unsigned int pipe,
void *buf, unsigned int length, unsigned int *act_len)
{
int result;
usb_stor_dbg(us, "xfer %u bytes\n", length);
/* fill and submit the URB */
usb_fill_bulk_urb(us->current_urb, us->pusb_dev, pipe, buf, length,
usb_stor_blocking_completion, NULL);
result = usb_stor_msg_common(us, 0);
/* store the actual length of the data transferred */
if (act_len)
*act_len = us->current_urb->actual_length;
return interpret_urb_result(us, pipe, length, result,
us->current_urb->actual_length);
}
EXPORT_SYMBOL_GPL(usb_stor_bulk_transfer_buf);
/*
* Transfer a scatter-gather list via bulk transfer
*
* This function does basically the same thing as usb_stor_bulk_transfer_buf()
* above, but it uses the usbcore scatter-gather library.
*/
static int usb_stor_bulk_transfer_sglist(struct us_data *us, unsigned int pipe,
struct scatterlist *sg, int num_sg, unsigned int length,
unsigned int *act_len)
{
int result;
/* don't submit s-g requests during abort processing */
if (test_bit(US_FLIDX_ABORTING, &us->dflags))
goto usb_stor_xfer_error;
/* initialize the scatter-gather request block */
usb_stor_dbg(us, "xfer %u bytes, %d entries\n", length, num_sg);
result = usb_sg_init(&us->current_sg, us->pusb_dev, pipe, 0,
sg, num_sg, length, GFP_NOIO);
if (result) {
usb_stor_dbg(us, "usb_sg_init returned %d\n", result);
goto usb_stor_xfer_error;
}
/*
* since the block has been initialized successfully, it's now
* okay to cancel it
*/
set_bit(US_FLIDX_SG_ACTIVE, &us->dflags);
/* did an abort occur during the submission? */
if (test_bit(US_FLIDX_ABORTING, &us->dflags)) {
/* cancel the request, if it hasn't been cancelled already */
if (test_and_clear_bit(US_FLIDX_SG_ACTIVE, &us->dflags)) {
usb_stor_dbg(us, "-- cancelling sg request\n");
usb_sg_cancel(&us->current_sg);
}
}
/* wait for the completion of the transfer */
usb_sg_wait(&us->current_sg);
clear_bit(US_FLIDX_SG_ACTIVE, &us->dflags);
result = us->current_sg.status;
if (act_len)
*act_len = us->current_sg.bytes;
return interpret_urb_result(us, pipe, length, result,
us->current_sg.bytes);
usb_stor_xfer_error:
if (act_len)
*act_len = 0;
return USB_STOR_XFER_ERROR;
}
/*
* Common used function. Transfer a complete command
* via usb_stor_bulk_transfer_sglist() above. Set cmnd resid
*/
int usb_stor_bulk_srb(struct us_data* us, unsigned int pipe,
struct scsi_cmnd* srb)
{
unsigned int partial;
int result = usb_stor_bulk_transfer_sglist(us, pipe, scsi_sglist(srb),
scsi_sg_count(srb), scsi_bufflen(srb),
&partial);
scsi_set_resid(srb, scsi_bufflen(srb) - partial);
return result;
}
EXPORT_SYMBOL_GPL(usb_stor_bulk_srb);
/*
* Transfer an entire SCSI command's worth of data payload over the bulk
* pipe.
*
* Note that this uses usb_stor_bulk_transfer_buf() and
* usb_stor_bulk_transfer_sglist() to achieve its goals --
* this function simply determines whether we're going to use
* scatter-gather or not, and acts appropriately.
*/
int usb_stor_bulk_transfer_sg(struct us_data* us, unsigned int pipe,
void *buf, unsigned int length_left, int use_sg, int *residual)
{
int result;
unsigned int partial;
/* are we scatter-gathering? */
if (use_sg) {
/* use the usb core scatter-gather primitives */
result = usb_stor_bulk_transfer_sglist(us, pipe,
(struct scatterlist *) buf, use_sg,
length_left, &partial);
length_left -= partial;
} else {
/* no scatter-gather, just make the request */
result = usb_stor_bulk_transfer_buf(us, pipe, buf,
length_left, &partial);
length_left -= partial;
}
/* store the residual and return the error code */
if (residual)
*residual = length_left;
return result;
}
EXPORT_SYMBOL_GPL(usb_stor_bulk_transfer_sg);
/***********************************************************************
* Transport routines
***********************************************************************/
/*
* There are so many devices that report the capacity incorrectly,
* this routine was written to counteract some of the resulting
* problems.
*/
static void last_sector_hacks(struct us_data *us, struct scsi_cmnd *srb)
{
struct gendisk *disk;
struct scsi_disk *sdkp;
u32 sector;
/* To Report "Medium Error: Record Not Found */
static unsigned char record_not_found[18] = {
[0] = 0x70, /* current error */
[2] = MEDIUM_ERROR, /* = 0x03 */
[7] = 0x0a, /* additional length */
[12] = 0x14 /* Record Not Found */
};
/*
* If last-sector problems can't occur, whether because the
* capacity was already decremented or because the device is
* known to report the correct capacity, then we don't need
* to do anything.
*/
if (!us->use_last_sector_hacks)
return;
/* Was this command a READ(10) or a WRITE(10)? */
if (srb->cmnd[0] != READ_10 && srb->cmnd[0] != WRITE_10)
goto done;
/* Did this command access the last sector? */
sector = (srb->cmnd[2] << 24) | (srb->cmnd[3] << 16) |
(srb->cmnd[4] << 8) | (srb->cmnd[5]);
disk = srb->request->rq_disk;
if (!disk)
goto done;
sdkp = scsi_disk(disk);
if (!sdkp)
goto done;
if (sector + 1 != sdkp->capacity)
goto done;
if (srb->result == SAM_STAT_GOOD && scsi_get_resid(srb) == 0) {
/*
* The command succeeded. We know this device doesn't
* have the last-sector bug, so stop checking it.
*/
us->use_last_sector_hacks = 0;
} else {
/*
* The command failed. Allow up to 3 retries in case this
* is some normal sort of failure. After that, assume the
* capacity is wrong and we're trying to access the sector
* beyond the end. Replace the result code and sense data
* with values that will cause the SCSI core to fail the
* command immediately, instead of going into an infinite
* (or even just a very long) retry loop.
*/
if (++us->last_sector_retries < 3)
return;
srb->result = SAM_STAT_CHECK_CONDITION;
memcpy(srb->sense_buffer, record_not_found,
sizeof(record_not_found));
}
done:
/*
* Don't reset the retry counter for TEST UNIT READY commands,
* because they get issued after device resets which might be
* caused by a failed last-sector access.
*/
if (srb->cmnd[0] != TEST_UNIT_READY)
us->last_sector_retries = 0;
}
/*
* Invoke the transport and basic error-handling/recovery methods
*
* This is used by the protocol layers to actually send the message to
* the device and receive the response.
*/
void usb_stor_invoke_transport(struct scsi_cmnd *srb, struct us_data *us)
{
int need_auto_sense;
int result;
/* send the command to the transport layer */
scsi_set_resid(srb, 0);
result = us->transport(srb, us);
/*
* if the command gets aborted by the higher layers, we need to
* short-circuit all other processing
*/
if (test_bit(US_FLIDX_TIMED_OUT, &us->dflags)) {
usb_stor_dbg(us, "-- command was aborted\n");
srb->result = DID_ABORT << 16;
goto Handle_Errors;
}
/* if there is a transport error, reset and don't auto-sense */
if (result == USB_STOR_TRANSPORT_ERROR) {
usb_stor_dbg(us, "-- transport indicates error, resetting\n");
srb->result = DID_ERROR << 16;
goto Handle_Errors;
}
/* if the transport provided its own sense data, don't auto-sense */
if (result == USB_STOR_TRANSPORT_NO_SENSE) {
srb->result = SAM_STAT_CHECK_CONDITION;
last_sector_hacks(us, srb);
return;
}
srb->result = SAM_STAT_GOOD;
/*
* Determine if we need to auto-sense
*
* I normally don't use a flag like this, but it's almost impossible
* to understand what's going on here if I don't.
*/
need_auto_sense = 0;
/*
* If we're running the CB transport, which is incapable
* of determining status on its own, we will auto-sense
* unless the operation involved a data-in transfer. Devices
* can signal most data-in errors by stalling the bulk-in pipe.
*/
if ((us->protocol == USB_PR_CB || us->protocol == USB_PR_DPCM_USB) &&
srb->sc_data_direction != DMA_FROM_DEVICE) {
usb_stor_dbg(us, "-- CB transport device requiring auto-sense\n");
need_auto_sense = 1;
}
/* Some devices (Kindle) require another command after SYNC CACHE */
if ((us->fflags & US_FL_SENSE_AFTER_SYNC) &&
srb->cmnd[0] == SYNCHRONIZE_CACHE) {
usb_stor_dbg(us, "-- sense after SYNC CACHE\n");
need_auto_sense = 1;
}
/*
* If we have a failure, we're going to do a REQUEST_SENSE
* automatically. Note that we differentiate between a command
* "failure" and an "error" in the transport mechanism.
*/
if (result == USB_STOR_TRANSPORT_FAILED) {
usb_stor_dbg(us, "-- transport indicates command failure\n");
need_auto_sense = 1;
}
/*
* Determine if this device is SAT by seeing if the
* command executed successfully. Otherwise we'll have
* to wait for at least one CHECK_CONDITION to determine
* SANE_SENSE support
*/
if (unlikely((srb->cmnd[0] == ATA_16 || srb->cmnd[0] == ATA_12) &&
result == USB_STOR_TRANSPORT_GOOD &&
!(us->fflags & US_FL_SANE_SENSE) &&
!(us->fflags & US_FL_BAD_SENSE) &&
!(srb->cmnd[2] & 0x20))) {
usb_stor_dbg(us, "-- SAT supported, increasing auto-sense\n");
us->fflags |= US_FL_SANE_SENSE;
}
/*
* A short transfer on a command where we don't expect it
* is unusual, but it doesn't mean we need to auto-sense.
*/
if ((scsi_get_resid(srb) > 0) &&
!((srb->cmnd[0] == REQUEST_SENSE) ||
(srb->cmnd[0] == INQUIRY) ||
(srb->cmnd[0] == MODE_SENSE) ||
(srb->cmnd[0] == LOG_SENSE) ||
(srb->cmnd[0] == MODE_SENSE_10))) {
usb_stor_dbg(us, "-- unexpectedly short transfer\n");
}
/* Now, if we need to do the auto-sense, let's do it */
if (need_auto_sense) {
int temp_result;
struct scsi_eh_save ses;
int sense_size = US_SENSE_SIZE;
struct scsi_sense_hdr sshdr;
const u8 *scdd;
u8 fm_ili;
/* device supports and needs bigger sense buffer */
if (us->fflags & US_FL_SANE_SENSE)
sense_size = ~0;
Retry_Sense:
usb_stor_dbg(us, "Issuing auto-REQUEST_SENSE\n");
scsi_eh_prep_cmnd(srb, &ses, NULL, 0, sense_size);
/* FIXME: we must do the protocol translation here */
if (us->subclass == USB_SC_RBC || us->subclass == USB_SC_SCSI ||
us->subclass == USB_SC_CYP_ATACB)
srb->cmd_len = 6;
else
srb->cmd_len = 12;
/* issue the auto-sense command */
scsi_set_resid(srb, 0);
temp_result = us->transport(us->srb, us);
/* let's clean up right away */
scsi_eh_restore_cmnd(srb, &ses);
if (test_bit(US_FLIDX_TIMED_OUT, &us->dflags)) {
usb_stor_dbg(us, "-- auto-sense aborted\n");
srb->result = DID_ABORT << 16;
/* If SANE_SENSE caused this problem, disable it */
if (sense_size != US_SENSE_SIZE) {
us->fflags &= ~US_FL_SANE_SENSE;
us->fflags |= US_FL_BAD_SENSE;
}
goto Handle_Errors;
}
/*
* Some devices claim to support larger sense but fail when
* trying to request it. When a transport failure happens
* using US_FS_SANE_SENSE, we always retry with a standard
* (small) sense request. This fixes some USB GSM modems
*/
if (temp_result == USB_STOR_TRANSPORT_FAILED &&
sense_size != US_SENSE_SIZE) {
usb_stor_dbg(us, "-- auto-sense failure, retry small sense\n");
sense_size = US_SENSE_SIZE;
us->fflags &= ~US_FL_SANE_SENSE;
us->fflags |= US_FL_BAD_SENSE;
goto Retry_Sense;
}
/* Other failures */
if (temp_result != USB_STOR_TRANSPORT_GOOD) {
usb_stor_dbg(us, "-- auto-sense failure\n");
/*
* we skip the reset if this happens to be a
* multi-target device, since failure of an
* auto-sense is perfectly valid
*/
srb->result = DID_ERROR << 16;
if (!(us->fflags & US_FL_SCM_MULT_TARG))
goto Handle_Errors;
return;
}
/*
* If the sense data returned is larger than 18-bytes then we
* assume this device supports requesting more in the future.
* The response code must be 70h through 73h inclusive.
*/
if (srb->sense_buffer[7] > (US_SENSE_SIZE - 8) &&
!(us->fflags & US_FL_SANE_SENSE) &&
!(us->fflags & US_FL_BAD_SENSE) &&
(srb->sense_buffer[0] & 0x7C) == 0x70) {
usb_stor_dbg(us, "-- SANE_SENSE support enabled\n");
us->fflags |= US_FL_SANE_SENSE;
/*
* Indicate to the user that we truncated their sense
* because we didn't know it supported larger sense.
*/
usb_stor_dbg(us, "-- Sense data truncated to %i from %i\n",
US_SENSE_SIZE,
srb->sense_buffer[7] + 8);
srb->sense_buffer[7] = (US_SENSE_SIZE - 8);
}
scsi_normalize_sense(srb->sense_buffer, SCSI_SENSE_BUFFERSIZE,
&sshdr);
usb_stor_dbg(us, "-- Result from auto-sense is %d\n",
temp_result);
usb_stor_dbg(us, "-- code: 0x%x, key: 0x%x, ASC: 0x%x, ASCQ: 0x%x\n",
sshdr.response_code, sshdr.sense_key,
sshdr.asc, sshdr.ascq);
#ifdef CONFIG_USB_STORAGE_DEBUG
usb_stor_show_sense(us, sshdr.sense_key, sshdr.asc, sshdr.ascq);
#endif
/* set the result so the higher layers expect this data */
srb->result = SAM_STAT_CHECK_CONDITION;
scdd = scsi_sense_desc_find(srb->sense_buffer,
SCSI_SENSE_BUFFERSIZE, 4);
fm_ili = (scdd ? scdd[3] : srb->sense_buffer[2]) & 0xA0;
/*
* We often get empty sense data. This could indicate that
* everything worked or that there was an unspecified
* problem. We have to decide which.
*/
if (sshdr.sense_key == 0 && sshdr.asc == 0 && sshdr.ascq == 0 &&
fm_ili == 0) {
/*
* If things are really okay, then let's show that.
* Zero out the sense buffer so the higher layers
* won't realize we did an unsolicited auto-sense.
*/
if (result == USB_STOR_TRANSPORT_GOOD) {
srb->result = SAM_STAT_GOOD;
srb->sense_buffer[0] = 0x0;
}
/*
* ATA-passthru commands use sense data to report
* the command completion status, and often devices
* return Check Condition status when nothing is
* wrong.
*/
else if (srb->cmnd[0] == ATA_16 ||
srb->cmnd[0] == ATA_12) {
/* leave the data alone */
}
/*
* If there was a problem, report an unspecified
* hardware error to prevent the higher layers from
* entering an infinite retry loop.
*/
else {
srb->result = DID_ERROR << 16;
if ((sshdr.response_code & 0x72) == 0x72)
srb->sense_buffer[1] = HARDWARE_ERROR;
else
srb->sense_buffer[2] = HARDWARE_ERROR;
}
}
}
/*
* Some devices don't work or return incorrect data the first
* time they get a READ(10) command, or for the first READ(10)
* after a media change. If the INITIAL_READ10 flag is set,
* keep track of whether READ(10) commands succeed. If the
* previous one succeeded and this one failed, set the REDO_READ10
* flag to force a retry.
*/
if (unlikely((us->fflags & US_FL_INITIAL_READ10) &&
srb->cmnd[0] == READ_10)) {
if (srb->result == SAM_STAT_GOOD) {
set_bit(US_FLIDX_READ10_WORKED, &us->dflags);
} else if (test_bit(US_FLIDX_READ10_WORKED, &us->dflags)) {
clear_bit(US_FLIDX_READ10_WORKED, &us->dflags);
set_bit(US_FLIDX_REDO_READ10, &us->dflags);
}
/*
* Next, if the REDO_READ10 flag is set, return a result
* code that will cause the SCSI core to retry the READ(10)
* command immediately.
*/
if (test_bit(US_FLIDX_REDO_READ10, &us->dflags)) {
clear_bit(US_FLIDX_REDO_READ10, &us->dflags);
srb->result = DID_IMM_RETRY << 16;
srb->sense_buffer[0] = 0;
}
}
/* Did we transfer less than the minimum amount required? */
if ((srb->result == SAM_STAT_GOOD || srb->sense_buffer[2] == 0) &&
scsi_bufflen(srb) - scsi_get_resid(srb) < srb->underflow)
srb->result = DID_ERROR << 16;
last_sector_hacks(us, srb);
return;
/*
* Error and abort processing: try to resynchronize with the device
* by issuing a port reset. If that fails, try a class-specific
* device reset.
*/
Handle_Errors:
/*
* Set the RESETTING bit, and clear the ABORTING bit so that
* the reset may proceed.
*/
scsi_lock(us_to_host(us));
set_bit(US_FLIDX_RESETTING, &us->dflags);
clear_bit(US_FLIDX_ABORTING, &us->dflags);
scsi_unlock(us_to_host(us));
/*
* We must release the device lock because the pre_reset routine
* will want to acquire it.
*/
mutex_unlock(&us->dev_mutex);
result = usb_stor_port_reset(us);
mutex_lock(&us->dev_mutex);
if (result < 0) {
scsi_lock(us_to_host(us));
usb_stor_report_device_reset(us);
scsi_unlock(us_to_host(us));
us->transport_reset(us);
}
clear_bit(US_FLIDX_RESETTING, &us->dflags);
last_sector_hacks(us, srb);
}
/* Stop the current URB transfer */
void usb_stor_stop_transport(struct us_data *us)
{
/*
* If the state machine is blocked waiting for an URB,
* let's wake it up. The test_and_clear_bit() call
* guarantees that if a URB has just been submitted,
* it won't be cancelled more than once.
*/
if (test_and_clear_bit(US_FLIDX_URB_ACTIVE, &us->dflags)) {
usb_stor_dbg(us, "-- cancelling URB\n");
usb_unlink_urb(us->current_urb);
}
/* If we are waiting for a scatter-gather operation, cancel it. */
if (test_and_clear_bit(US_FLIDX_SG_ACTIVE, &us->dflags)) {
usb_stor_dbg(us, "-- cancelling sg request\n");
usb_sg_cancel(&us->current_sg);
}
}
/*
* Control/Bulk and Control/Bulk/Interrupt transport
*/
int usb_stor_CB_transport(struct scsi_cmnd *srb, struct us_data *us)
{
unsigned int transfer_length = scsi_bufflen(srb);
unsigned int pipe = 0;
int result;
/* COMMAND STAGE */
/* let's send the command via the control pipe */
/*
* Command is sometime (f.e. after scsi_eh_prep_cmnd) on the stack.
* Stack may be vmallocated. So no DMA for us. Make a copy.
*/
memcpy(us->iobuf, srb->cmnd, srb->cmd_len);
result = usb_stor_ctrl_transfer(us, us->send_ctrl_pipe,
US_CBI_ADSC,
USB_TYPE_CLASS | USB_RECIP_INTERFACE, 0,
us->ifnum, us->iobuf, srb->cmd_len);
/* check the return code for the command */
usb_stor_dbg(us, "Call to usb_stor_ctrl_transfer() returned %d\n",
result);
/* if we stalled the command, it means command failed */
if (result == USB_STOR_XFER_STALLED) {
return USB_STOR_TRANSPORT_FAILED;
}
/* Uh oh... serious problem here */
if (result != USB_STOR_XFER_GOOD) {
return USB_STOR_TRANSPORT_ERROR;
}
/* DATA STAGE */
/* transfer the data payload for this command, if one exists*/
if (transfer_length) {
pipe = srb->sc_data_direction == DMA_FROM_DEVICE ?
us->recv_bulk_pipe : us->send_bulk_pipe;
result = usb_stor_bulk_srb(us, pipe, srb);
usb_stor_dbg(us, "CBI data stage result is 0x%x\n", result);
/* if we stalled the data transfer it means command failed */
if (result == USB_STOR_XFER_STALLED)
return USB_STOR_TRANSPORT_FAILED;
if (result > USB_STOR_XFER_STALLED)
return USB_STOR_TRANSPORT_ERROR;
}
/* STATUS STAGE */
/*
* NOTE: CB does not have a status stage. Silly, I know. So
* we have to catch this at a higher level.
*/
if (us->protocol != USB_PR_CBI)
return USB_STOR_TRANSPORT_GOOD;
result = usb_stor_intr_transfer(us, us->iobuf, 2);
usb_stor_dbg(us, "Got interrupt data (0x%x, 0x%x)\n",
us->iobuf[0], us->iobuf[1]);
if (result != USB_STOR_XFER_GOOD)
return USB_STOR_TRANSPORT_ERROR;
/*
* UFI gives us ASC and ASCQ, like a request sense
*
* REQUEST_SENSE and INQUIRY don't affect the sense data on UFI
* devices, so we ignore the information for those commands. Note
* that this means we could be ignoring a real error on these
* commands, but that can't be helped.
*/
if (us->subclass == USB_SC_UFI) {
if (srb->cmnd[0] == REQUEST_SENSE ||
srb->cmnd[0] == INQUIRY)
return USB_STOR_TRANSPORT_GOOD;
if (us->iobuf[0])
goto Failed;
return USB_STOR_TRANSPORT_GOOD;
}
/*
* If not UFI, we interpret the data as a result code
* The first byte should always be a 0x0.
*
* Some bogus devices don't follow that rule. They stuff the ASC
* into the first byte -- so if it's non-zero, call it a failure.
*/
if (us->iobuf[0]) {
usb_stor_dbg(us, "CBI IRQ data showed reserved bType 0x%x\n",
us->iobuf[0]);
goto Failed;
}
/* The second byte & 0x0F should be 0x0 for good, otherwise error */
switch (us->iobuf[1] & 0x0F) {
case 0x00:
return USB_STOR_TRANSPORT_GOOD;
case 0x01:
goto Failed;
}
return USB_STOR_TRANSPORT_ERROR;
/*
* the CBI spec requires that the bulk pipe must be cleared
* following any data-in/out command failure (section 2.4.3.1.3)
*/
Failed:
if (pipe)
usb_stor_clear_halt(us, pipe);
return USB_STOR_TRANSPORT_FAILED;
}
EXPORT_SYMBOL_GPL(usb_stor_CB_transport);
/*
* Bulk only transport
*/
/* Determine what the maximum LUN supported is */
int usb_stor_Bulk_max_lun(struct us_data *us)
{
int result;
/* issue the command */
us->iobuf[0] = 0;
result = usb_stor_control_msg(us, us->recv_ctrl_pipe,
US_BULK_GET_MAX_LUN,
USB_DIR_IN | USB_TYPE_CLASS |
USB_RECIP_INTERFACE,
0, us->ifnum, us->iobuf, 1, 10*HZ);
usb_stor_dbg(us, "GetMaxLUN command result is %d, data is %d\n",
result, us->iobuf[0]);
/*
* If we have a successful request, return the result if valid. The
* CBW LUN field is 4 bits wide, so the value reported by the device
* should fit into that.
*/
if (result > 0) {
if (us->iobuf[0] < 16) {
return us->iobuf[0];
} else {
dev_info(&us->pusb_intf->dev,
"Max LUN %d is not valid, using 0 instead",
us->iobuf[0]);
}
}
/*
* Some devices don't like GetMaxLUN. They may STALL the control
* pipe, they may return a zero-length result, they may do nothing at
* all and timeout, or they may fail in even more bizarrely creative
* ways. In these cases the best approach is to use the default
* value: only one LUN.
*/
return 0;
}
int usb_stor_Bulk_transport(struct scsi_cmnd *srb, struct us_data *us)
{
struct bulk_cb_wrap *bcb = (struct bulk_cb_wrap *) us->iobuf;
struct bulk_cs_wrap *bcs = (struct bulk_cs_wrap *) us->iobuf;
unsigned int transfer_length = scsi_bufflen(srb);
unsigned int residue;
int result;
int fake_sense = 0;
unsigned int cswlen;
unsigned int cbwlen = US_BULK_CB_WRAP_LEN;
/* Take care of BULK32 devices; set extra byte to 0 */
if (unlikely(us->fflags & US_FL_BULK32)) {
cbwlen = 32;
us->iobuf[31] = 0;
}
/* set up the command wrapper */
bcb->Signature = cpu_to_le32(US_BULK_CB_SIGN);
bcb->DataTransferLength = cpu_to_le32(transfer_length);
bcb->Flags = srb->sc_data_direction == DMA_FROM_DEVICE ?
US_BULK_FLAG_IN : 0;
bcb->Tag = ++us->tag;
bcb->Lun = srb->device->lun;
if (us->fflags & US_FL_SCM_MULT_TARG)
bcb->Lun |= srb->device->id << 4;
bcb->Length = srb->cmd_len;
/* copy the command payload */
memset(bcb->CDB, 0, sizeof(bcb->CDB));
memcpy(bcb->CDB, srb->cmnd, bcb->Length);
/* send it to out endpoint */
usb_stor_dbg(us, "Bulk Command S 0x%x T 0x%x L %d F %d Trg %d LUN %d CL %d\n",
le32_to_cpu(bcb->Signature), bcb->Tag,
le32_to_cpu(bcb->DataTransferLength), bcb->Flags,
(bcb->Lun >> 4), (bcb->Lun & 0x0F),
bcb->Length);
result = usb_stor_bulk_transfer_buf(us, us->send_bulk_pipe,
bcb, cbwlen, NULL);
usb_stor_dbg(us, "Bulk command transfer result=%d\n", result);
if (result != USB_STOR_XFER_GOOD)
return USB_STOR_TRANSPORT_ERROR;
/* DATA STAGE */
/* send/receive data payload, if there is any */
/*
* Some USB-IDE converter chips need a 100us delay between the
* command phase and the data phase. Some devices need a little
* more than that, probably because of clock rate inaccuracies.
*/
if (unlikely(us->fflags & US_FL_GO_SLOW))
usleep_range(125, 150);
if (transfer_length) {
unsigned int pipe = srb->sc_data_direction == DMA_FROM_DEVICE ?
us->recv_bulk_pipe : us->send_bulk_pipe;
result = usb_stor_bulk_srb(us, pipe, srb);
usb_stor_dbg(us, "Bulk data transfer result 0x%x\n", result);
if (result == USB_STOR_XFER_ERROR)
return USB_STOR_TRANSPORT_ERROR;
/*
* If the device tried to send back more data than the
* amount requested, the spec requires us to transfer
* the CSW anyway. Since there's no point retrying the
* the command, we'll return fake sense data indicating
* Illegal Request, Invalid Field in CDB.
*/
if (result == USB_STOR_XFER_LONG)
fake_sense = 1;
/*
* Sometimes a device will mistakenly skip the data phase
* and go directly to the status phase without sending a
* zero-length packet. If we get a 13-byte response here,
* check whether it really is a CSW.
*/
if (result == USB_STOR_XFER_SHORT &&
srb->sc_data_direction == DMA_FROM_DEVICE &&
transfer_length - scsi_get_resid(srb) ==
US_BULK_CS_WRAP_LEN) {
struct scatterlist *sg = NULL;
unsigned int offset = 0;
if (usb_stor_access_xfer_buf((unsigned char *) bcs,
US_BULK_CS_WRAP_LEN, srb, &sg,
&offset, FROM_XFER_BUF) ==
US_BULK_CS_WRAP_LEN &&
bcs->Signature ==
cpu_to_le32(US_BULK_CS_SIGN)) {
usb_stor_dbg(us, "Device skipped data phase\n");
scsi_set_resid(srb, transfer_length);
goto skipped_data_phase;
}
}
}
/*
* See flow chart on pg 15 of the Bulk Only Transport spec for
* an explanation of how this code works.
*/
/* get CSW for device status */
usb_stor_dbg(us, "Attempting to get CSW...\n");
result = usb_stor_bulk_transfer_buf(us, us->recv_bulk_pipe,
bcs, US_BULK_CS_WRAP_LEN, &cswlen);
/*
* Some broken devices add unnecessary zero-length packets to the
* end of their data transfers. Such packets show up as 0-length
* CSWs. If we encounter such a thing, try to read the CSW again.
*/
if (result == USB_STOR_XFER_SHORT && cswlen == 0) {
usb_stor_dbg(us, "Received 0-length CSW; retrying...\n");
result = usb_stor_bulk_transfer_buf(us, us->recv_bulk_pipe,
bcs, US_BULK_CS_WRAP_LEN, &cswlen);
}
/* did the attempt to read the CSW fail? */
if (result == USB_STOR_XFER_STALLED) {
/* get the status again */
usb_stor_dbg(us, "Attempting to get CSW (2nd try)...\n");
result = usb_stor_bulk_transfer_buf(us, us->recv_bulk_pipe,
bcs, US_BULK_CS_WRAP_LEN, NULL);
}
/* if we still have a failure at this point, we're in trouble */
usb_stor_dbg(us, "Bulk status result = %d\n", result);
if (result != USB_STOR_XFER_GOOD)
return USB_STOR_TRANSPORT_ERROR;
skipped_data_phase:
/* check bulk status */
residue = le32_to_cpu(bcs->Residue);
usb_stor_dbg(us, "Bulk Status S 0x%x T 0x%x R %u Stat 0x%x\n",
le32_to_cpu(bcs->Signature), bcs->Tag,
residue, bcs->Status);
if (!(bcs->Tag == us->tag || (us->fflags & US_FL_BULK_IGNORE_TAG)) ||
bcs->Status > US_BULK_STAT_PHASE) {
usb_stor_dbg(us, "Bulk logical error\n");
return USB_STOR_TRANSPORT_ERROR;
}
/*
* Some broken devices report odd signatures, so we do not check them
* for validity against the spec. We store the first one we see,
* and check subsequent transfers for validity against this signature.
*/
if (!us->bcs_signature) {
us->bcs_signature = bcs->Signature;
if (us->bcs_signature != cpu_to_le32(US_BULK_CS_SIGN))
usb_stor_dbg(us, "Learnt BCS signature 0x%08X\n",
le32_to_cpu(us->bcs_signature));
} else if (bcs->Signature != us->bcs_signature) {
usb_stor_dbg(us, "Signature mismatch: got %08X, expecting %08X\n",
le32_to_cpu(bcs->Signature),
le32_to_cpu(us->bcs_signature));
return USB_STOR_TRANSPORT_ERROR;
}
/*
* try to compute the actual residue, based on how much data
* was really transferred and what the device tells us
*/
if (residue && !(us->fflags & US_FL_IGNORE_RESIDUE)) {
/*
* Heuristically detect devices that generate bogus residues
* by seeing what happens with INQUIRY and READ CAPACITY
* commands.
*/
if (bcs->Status == US_BULK_STAT_OK &&
scsi_get_resid(srb) == 0 &&
((srb->cmnd[0] == INQUIRY &&
transfer_length == 36) ||
(srb->cmnd[0] == READ_CAPACITY &&
transfer_length == 8))) {
us->fflags |= US_FL_IGNORE_RESIDUE;
} else {
residue = min(residue, transfer_length);
scsi_set_resid(srb, max(scsi_get_resid(srb), residue));
}
}
/* based on the status code, we report good or bad */
switch (bcs->Status) {
case US_BULK_STAT_OK:
/* device babbled -- return fake sense data */
if (fake_sense) {
memcpy(srb->sense_buffer,
usb_stor_sense_invalidCDB,
sizeof(usb_stor_sense_invalidCDB));
return USB_STOR_TRANSPORT_NO_SENSE;
}
/* command good -- note that data could be short */
return USB_STOR_TRANSPORT_GOOD;
case US_BULK_STAT_FAIL:
/* command failed */
return USB_STOR_TRANSPORT_FAILED;
case US_BULK_STAT_PHASE:
/*
* phase error -- note that a transport reset will be
* invoked by the invoke_transport() function
*/
return USB_STOR_TRANSPORT_ERROR;
}
/* we should never get here, but if we do, we're in trouble */
return USB_STOR_TRANSPORT_ERROR;
}
EXPORT_SYMBOL_GPL(usb_stor_Bulk_transport);
/***********************************************************************
* Reset routines
***********************************************************************/
/*
* This is the common part of the device reset code.
*
* It's handy that every transport mechanism uses the control endpoint for
* resets.
*
* Basically, we send a reset with a 5-second timeout, so we don't get
* jammed attempting to do the reset.
*/
static int usb_stor_reset_common(struct us_data *us,
u8 request, u8 requesttype,
u16 value, u16 index, void *data, u16 size)
{
int result;
int result2;
if (test_bit(US_FLIDX_DISCONNECTING, &us->dflags)) {
usb_stor_dbg(us, "No reset during disconnect\n");
return -EIO;
}
result = usb_stor_control_msg(us, us->send_ctrl_pipe,
request, requesttype, value, index, data, size,
5*HZ);
if (result < 0) {
usb_stor_dbg(us, "Soft reset failed: %d\n", result);
return result;
}
/*
* Give the device some time to recover from the reset,
* but don't delay disconnect processing.
*/
wait_event_interruptible_timeout(us->delay_wait,
test_bit(US_FLIDX_DISCONNECTING, &us->dflags),
HZ*6);
if (test_bit(US_FLIDX_DISCONNECTING, &us->dflags)) {
usb_stor_dbg(us, "Reset interrupted by disconnect\n");
return -EIO;
}
usb_stor_dbg(us, "Soft reset: clearing bulk-in endpoint halt\n");
result = usb_stor_clear_halt(us, us->recv_bulk_pipe);
usb_stor_dbg(us, "Soft reset: clearing bulk-out endpoint halt\n");
result2 = usb_stor_clear_halt(us, us->send_bulk_pipe);
/* return a result code based on the result of the clear-halts */
if (result >= 0)
result = result2;
if (result < 0)
usb_stor_dbg(us, "Soft reset failed\n");
else
usb_stor_dbg(us, "Soft reset done\n");
return result;
}
/* This issues a CB[I] Reset to the device in question */
#define CB_RESET_CMD_SIZE 12
int usb_stor_CB_reset(struct us_data *us)
{
memset(us->iobuf, 0xFF, CB_RESET_CMD_SIZE);
us->iobuf[0] = SEND_DIAGNOSTIC;
us->iobuf[1] = 4;
return usb_stor_reset_common(us, US_CBI_ADSC,
USB_TYPE_CLASS | USB_RECIP_INTERFACE,
0, us->ifnum, us->iobuf, CB_RESET_CMD_SIZE);
}
EXPORT_SYMBOL_GPL(usb_stor_CB_reset);
/*
* This issues a Bulk-only Reset to the device in question, including
* clearing the subsequent endpoint halts that may occur.
*/
int usb_stor_Bulk_reset(struct us_data *us)
{
return usb_stor_reset_common(us, US_BULK_RESET_REQUEST,
USB_TYPE_CLASS | USB_RECIP_INTERFACE,
0, us->ifnum, NULL, 0);
}
EXPORT_SYMBOL_GPL(usb_stor_Bulk_reset);
/*
* Issue a USB port reset to the device. The caller must not hold
* us->dev_mutex.
*/
int usb_stor_port_reset(struct us_data *us)
{
int result;
/*for these devices we must use the class specific method */
if (us->pusb_dev->quirks & USB_QUIRK_RESET)
return -EPERM;
result = usb_lock_device_for_reset(us->pusb_dev, us->pusb_intf);
if (result < 0)
usb_stor_dbg(us, "unable to lock device for reset: %d\n",
result);
else {
/* Were we disconnected while waiting for the lock? */
if (test_bit(US_FLIDX_DISCONNECTING, &us->dflags)) {
result = -EIO;
usb_stor_dbg(us, "No reset during disconnect\n");
} else {
result = usb_reset_device(us->pusb_dev);
usb_stor_dbg(us, "usb_reset_device returns %d\n",
result);
}
usb_unlock_device(us->pusb_dev);
}
return result;
}
| gpl-2.0 |
jinseokpark6/u-team | Pods/Atlas/Code/Utilities/ATLErrors.h | 1326 | //
// ATLUIErrors.h
// Atlas
//
// Created by Kevin Coleman on 9/26/14.
// Copyright (c) 2015 Layer. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#import <Foundation/Foundation.h>
extern NSString *const ATLErrorDomain;
typedef NS_ENUM(NSUInteger, ATLError) {
ATLErrorUnknownError = 1000,
/* Messaging Errors */
ATLErrorUnauthenticated = 1001,
ATLErrorInvalidMessage = 1002,
ATLErrorTooManyParticipants = 1003,
ATLErrorDataLengthExceedsMaximum = 1004,
ATLErrorMessageAlreadyMarkedAsRead = 1005,
ATLErrorObjectNotSent = 1006,
ATLErrorNoPhotos = 1007
};
| apache-2.0 |
ckaushik/chef | lib/chef/resource/mdadm.rb | 2207 | #
# Author:: Joe Williams (<[email protected]>)
# Author:: Tyler Cloke (<[email protected]>)
# Copyright:: Copyright (c) 2009 Joe Williams
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'chef/resource'
class Chef
class Resource
class Mdadm < Chef::Resource
identity_attr :raid_device
state_attrs :devices, :level, :chunk
default_action :create
allowed_actions :create, :assemble, :stop
def initialize(name, run_context=nil)
super
@chunk = 16
@devices = []
@exists = false
@level = 1
@metadata = "0.90"
@bitmap = nil
@raid_device = name
end
def chunk(arg=nil)
set_or_return(
:chunk,
arg,
:kind_of => [ Integer ]
)
end
def devices(arg=nil)
set_or_return(
:devices,
arg,
:kind_of => [ Array ]
)
end
def exists(arg=nil)
set_or_return(
:exists,
arg,
:kind_of => [ TrueClass, FalseClass ]
)
end
def level(arg=nil)
set_or_return(
:level,
arg,
:kind_of => [ Integer ]
)
end
def metadata(arg=nil)
set_or_return(
:metadata,
arg,
:kind_of => [ String ]
)
end
def bitmap(arg=nil)
set_or_return(
:bitmap,
arg,
:kind_of => [ String ]
)
end
def raid_device(arg=nil)
set_or_return(
:raid_device,
arg,
:kind_of => [ String ]
)
end
end
end
end
| apache-2.0 |
Piicksarn/cdnjs | ajax/libs/forerunnerdb/1.3.50/fdb-core+views.js | 223891 | (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
var Core = _dereq_('../lib/Core'),
View = _dereq_('../lib/View');
if (typeof window !== 'undefined') {
window.ForerunnerDB = Core;
}
module.exports = Core;
},{"../lib/Core":5,"../lib/View":26}],2:[function(_dereq_,module,exports){
"use strict";
/**
* Creates an always-sorted multi-key bucket that allows ForerunnerDB to
* know the index that a document will occupy in an array with minimal
* processing, speeding up things like sorted views.
*/
var Shared = _dereq_('./Shared');
/**
* The active bucket class.
* @param {object} orderBy An order object.
* @constructor
*/
var ActiveBucket = function (orderBy) {
var sortKey;
this._primaryKey = '_id';
this._keyArr = [];
this._data = [];
this._objLookup = {};
this._count = 0;
for (sortKey in orderBy) {
if (orderBy.hasOwnProperty(sortKey)) {
this._keyArr.push({
key: sortKey,
dir: orderBy[sortKey]
});
}
}
};
Shared.addModule('ActiveBucket', ActiveBucket);
Shared.synthesize(ActiveBucket.prototype, 'primaryKey');
Shared.mixin(ActiveBucket.prototype, 'Mixin.Sorting');
/**
* Quicksorts a single document into the passed array and
* returns the index that the document should occupy.
* @param {object} obj The document to calculate index for.
* @param {array} arr The array the document index will be
* calculated for.
* @param {string} item The string key representation of the
* document whose index is being calculated.
* @param {function} fn The comparison function that is used
* to determine if a document is sorted below or above the
* document we are calculating the index for.
* @returns {number} The index the document should occupy.
*/
ActiveBucket.prototype.qs = function (obj, arr, item, fn) {
// If the array is empty then return index zero
if (!arr.length) {
return 0;
}
var lastMidwayIndex = -1,
midwayIndex,
lookupItem,
result,
start = 0,
end = arr.length - 1;
// Loop the data until our range overlaps
while (end >= start) {
// Calculate the midway point (divide and conquer)
midwayIndex = Math.floor((start + end) / 2);
if (lastMidwayIndex === midwayIndex) {
// No more items to scan
break;
}
// Get the item to compare against
lookupItem = arr[midwayIndex];
if (lookupItem !== undefined) {
// Compare items
result = fn(this, obj, item, lookupItem);
if (result > 0) {
start = midwayIndex + 1;
}
if (result < 0) {
end = midwayIndex - 1;
}
}
lastMidwayIndex = midwayIndex;
}
if (result > 0) {
return midwayIndex + 1;
} else {
return midwayIndex;
}
};
/**
* Calculates the sort position of an item against another item.
* @param {object} sorter An object or instance that contains
* sortAsc and sortDesc methods.
* @param {object} obj The document to compare.
* @param {string} a The first key to compare.
* @param {string} b The second key to compare.
* @returns {number} Either 1 for sort a after b or -1 to sort
* a before b.
* @private
*/
ActiveBucket.prototype._sortFunc = function (sorter, obj, a, b) {
var aVals = a.split('.:.'),
bVals = b.split('.:.'),
arr = sorter._keyArr,
count = arr.length,
index,
sortType,
castType;
for (index = 0; index < count; index++) {
sortType = arr[index];
castType = typeof obj[sortType.key];
if (castType === 'number') {
aVals[index] = Number(aVals[index]);
bVals[index] = Number(bVals[index]);
}
// Check for non-equal items
if (aVals[index] !== bVals[index]) {
// Return the sorted items
if (sortType.dir === 1) {
return sorter.sortAsc(aVals[index], bVals[index]);
}
if (sortType.dir === -1) {
return sorter.sortDesc(aVals[index], bVals[index]);
}
}
}
};
/**
* Inserts a document into the active bucket.
* @param {object} obj The document to insert.
* @returns {number} The index the document now occupies.
*/
ActiveBucket.prototype.insert = function (obj) {
var key,
keyIndex;
key = this.documentKey(obj);
keyIndex = this._data.indexOf(key);
if (keyIndex === -1) {
// Insert key
keyIndex = this.qs(obj, this._data, key, this._sortFunc);
this._data.splice(keyIndex, 0, key);
} else {
this._data.splice(keyIndex, 0, key);
}
this._objLookup[obj[this._primaryKey]] = key;
this._count++;
return keyIndex;
};
/**
* Removes a document from the active bucket.
* @param {object} obj The document to remove.
* @returns {boolean} True if the document was removed
* successfully or false if it wasn't found in the active
* bucket.
*/
ActiveBucket.prototype.remove = function (obj) {
var key,
keyIndex;
key = this._objLookup[obj[this._primaryKey]];
if (key) {
keyIndex = this._data.indexOf(key);
if (keyIndex > -1) {
this._data.splice(keyIndex, 1);
delete this._objLookup[obj[this._primaryKey]];
this._count--;
return true;
} else {
return false;
}
}
return false;
};
/**
* Get the index that the passed document currently occupies
* or the index it will occupy if added to the active bucket.
* @param {object} obj The document to get the index for.
* @returns {number} The index.
*/
ActiveBucket.prototype.index = function (obj) {
var key,
keyIndex;
key = this.documentKey(obj);
keyIndex = this._data.indexOf(key);
if (keyIndex === -1) {
// Get key index
keyIndex = this.qs(obj, this._data, key, this._sortFunc);
}
return keyIndex;
};
/**
* The key that represents the passed document.
* @param {object} obj The document to get the key for.
* @returns {string} The document key.
*/
ActiveBucket.prototype.documentKey = function (obj) {
var key = '',
arr = this._keyArr,
count = arr.length,
index,
sortType;
for (index = 0; index < count; index++) {
sortType = arr[index];
if (key) {
key += '.:.';
}
key += obj[sortType.key];
}
// Add the unique identifier on the end of the key
key += '.:.' + obj[this._primaryKey];
return key;
};
/**
* Get the number of documents currently indexed in the active
* bucket instance.
* @returns {number} The number of documents.
*/
ActiveBucket.prototype.count = function () {
return this._count;
};
Shared.finishModule('ActiveBucket');
module.exports = ActiveBucket;
},{"./Shared":25}],3:[function(_dereq_,module,exports){
"use strict";
/**
* The main collection class. Collections store multiple documents and
* can operate on them using the query language to insert, read, update
* and delete.
*/
var Shared,
Db,
Metrics,
KeyValueStore,
Path,
IndexHashMap,
IndexBinaryTree,
Crc,
Overload,
ReactorIO;
Shared = _dereq_('./Shared');
/**
* Collection object used to store data.
* @constructor
*/
var Collection = function (name) {
this.init.apply(this, arguments);
};
Collection.prototype.init = function (name) {
this._primaryKey = '_id';
this._primaryIndex = new KeyValueStore('primary');
this._primaryCrc = new KeyValueStore('primaryCrc');
this._crcLookup = new KeyValueStore('crcLookup');
this._name = name;
this._data = [];
this._metrics = new Metrics();
this._deferQueue = {
insert: [],
update: [],
remove: [],
upsert: []
};
this._deferThreshold = {
insert: 100,
update: 100,
remove: 100,
upsert: 100
};
this._deferTime = {
insert: 1,
update: 1,
remove: 1,
upsert: 1
};
// Set the subset to itself since it is the root collection
this._subsetOf(this);
};
Shared.addModule('Collection', Collection);
Shared.mixin(Collection.prototype, 'Mixin.Common');
Shared.mixin(Collection.prototype, 'Mixin.Events');
Shared.mixin(Collection.prototype, 'Mixin.ChainReactor');
Shared.mixin(Collection.prototype, 'Mixin.CRUD');
Shared.mixin(Collection.prototype, 'Mixin.Constants');
Shared.mixin(Collection.prototype, 'Mixin.Triggers');
Shared.mixin(Collection.prototype, 'Mixin.Sorting');
Shared.mixin(Collection.prototype, 'Mixin.Matching');
Shared.mixin(Collection.prototype, 'Mixin.Updating');
Metrics = _dereq_('./Metrics');
KeyValueStore = _dereq_('./KeyValueStore');
Path = _dereq_('./Path');
IndexHashMap = _dereq_('./IndexHashMap');
IndexBinaryTree = _dereq_('./IndexBinaryTree');
Crc = _dereq_('./Crc');
Db = Shared.modules.Db;
Overload = _dereq_('./Overload');
ReactorIO = _dereq_('./ReactorIO');
/**
* Returns a checksum of a string.
* @param {String} string The string to checksum.
* @return {String} The checksum generated.
*/
Collection.prototype.crc = Crc;
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'state');
/**
* Gets / sets the name of the collection.
* @param {String=} val The name of the collection to set.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'name');
/**
* Get the internal data
* @returns {Array}
*/
Collection.prototype.data = function () {
return this._data;
};
/**
* Drops a collection and all it's stored data from the database.
* @returns {boolean} True on success, false on failure.
*/
Collection.prototype.drop = function (callback) {
var key;
if (this._state !== 'dropped') {
if (this._db && this._db._collection && this._name) {
if (this.debug()) {
console.log('Dropping collection ' + this._name);
}
this._state = 'dropped';
this.emit('drop', this);
delete this._db._collection[this._name];
// Remove any reactor IO chain links
if (this._collate) {
for (key in this._collate) {
if (this._collate.hasOwnProperty(key)) {
this.collateRemove(key);
}
}
}
delete this._primaryKey;
delete this._primaryIndex;
delete this._primaryCrc;
delete this._crcLookup;
delete this._name;
delete this._data;
delete this._metrics;
if (callback) { callback(false, true); }
return true;
}
} else {
if (callback) { callback(false, true); }
return true;
}
if (callback) { callback(false, true); }
return false;
};
/**
* Gets / sets the primary key for this collection.
* @param {String=} keyName The name of the primary key.
* @returns {*}
*/
Collection.prototype.primaryKey = function (keyName) {
if (keyName !== undefined) {
if (this._primaryKey !== keyName) {
this._primaryKey = keyName;
// Set the primary key index primary key
this._primaryIndex.primaryKey(keyName);
// Rebuild the primary key index
this.rebuildPrimaryKeyIndex();
}
return this;
}
return this._primaryKey;
};
/**
* Handles insert events and routes changes to binds and views as required.
* @param {Array} inserted An array of inserted documents.
* @param {Array} failed An array of documents that failed to insert.
* @private
*/
Collection.prototype._onInsert = function (inserted, failed) {
this.emit('insert', inserted, failed);
};
/**
* Handles update events and routes changes to binds and views as required.
* @param {Array} items An array of updated documents.
* @private
*/
Collection.prototype._onUpdate = function (items) {
this.emit('update', items);
};
/**
* Handles remove events and routes changes to binds and views as required.
* @param {Array} items An array of removed documents.
* @private
*/
Collection.prototype._onRemove = function (items) {
this.emit('remove', items);
};
/**
* Gets / sets the db instance this class instance belongs to.
* @param {Db=} db The db instance.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'db', function (db) {
if (db) {
if (this.primaryKey() === '_id') {
// Set primary key to the db's key by default
this.primaryKey(db.primaryKey());
}
}
return this.$super.apply(this, arguments);
});
/**
* Sets the collection's data to the array of documents passed.
* @param data
* @param options Optional options object.
* @param callback Optional callback function.
*/
Collection.prototype.setData = function (data, options, callback) {
if (this._state === 'dropped') {
throw('ForerunnerDB.Collection "' + this.name() + '": Cannot operate in a dropped state!');
}
if (data) {
var op = this._metrics.create('setData');
op.start();
options = this.options(options);
this.preSetData(data, options, callback);
if (options.$decouple) {
data = this.decouple(data);
}
if (!(data instanceof Array)) {
data = [data];
}
op.time('transformIn');
data = this.transformIn(data);
op.time('transformIn');
var oldData = [].concat(this._data);
this._dataReplace(data);
// Update the primary key index
op.time('Rebuild Primary Key Index');
this.rebuildPrimaryKeyIndex(options);
op.time('Rebuild Primary Key Index');
// Rebuild all other indexes
op.time('Rebuild All Other Indexes');
this._rebuildIndexes();
op.time('Rebuild All Other Indexes');
op.time('Resolve chains');
this.chainSend('setData', data, {oldData: oldData});
op.time('Resolve chains');
op.stop();
this.emit('setData', this._data, oldData);
}
if (callback) { callback(false); }
return this;
};
/**
* Drops and rebuilds the primary key index for all documents in the collection.
* @param {Object=} options An optional options object.
* @private
*/
Collection.prototype.rebuildPrimaryKeyIndex = function (options) {
options = options || {
$ensureKeys: undefined,
$violationCheck: undefined
};
var ensureKeys = options && options.$ensureKeys !== undefined ? options.$ensureKeys : true,
violationCheck = options && options.$violationCheck !== undefined ? options.$violationCheck : true,
arr,
arrCount,
arrItem,
pIndex = this._primaryIndex,
crcIndex = this._primaryCrc,
crcLookup = this._crcLookup,
pKey = this._primaryKey,
jString;
// Drop the existing primary index
pIndex.truncate();
crcIndex.truncate();
crcLookup.truncate();
// Loop the data and check for a primary key in each object
arr = this._data;
arrCount = arr.length;
while (arrCount--) {
arrItem = arr[arrCount];
if (ensureKeys) {
// Make sure the item has a primary key
this.ensurePrimaryKey(arrItem);
}
if (violationCheck) {
// Check for primary key violation
if (!pIndex.uniqueSet(arrItem[pKey], arrItem)) {
// Primary key violation
throw('ForerunnerDB.Collection "' + this.name() + '": Call to setData on collection failed because your data violates the primary key unique constraint. One or more documents are using the same primary key: ' + arrItem[this._primaryKey]);
}
} else {
pIndex.set(arrItem[pKey], arrItem);
}
// Generate a CRC string
jString = JSON.stringify(arrItem);
crcIndex.set(arrItem[pKey], jString);
crcLookup.set(jString, arrItem);
}
};
/**
* Checks for a primary key on the document and assigns one if none
* currently exists.
* @param {Object} obj The object to check a primary key against.
* @private
*/
Collection.prototype.ensurePrimaryKey = function (obj) {
if (obj[this._primaryKey] === undefined) {
// Assign a primary key automatically
obj[this._primaryKey] = this.objectId();
}
};
/**
* Clears all data from the collection.
* @returns {Collection}
*/
Collection.prototype.truncate = function () {
if (this._state === 'dropped') {
throw('ForerunnerDB.Collection "' + this.name() + '": Cannot operate in a dropped state!');
}
this.emit('truncate', this._data);
// Clear all the data from the collection
this._data.length = 0;
// Re-create the primary index data
this._primaryIndex = new KeyValueStore('primary');
this._primaryCrc = new KeyValueStore('primaryCrc');
this._crcLookup = new KeyValueStore('crcLookup');
this.deferEmit('change', {type: 'truncate'});
return this;
};
/**
* Modifies an existing document or documents in a collection. This will update
* all matches for 'query' with the data held in 'update'. It will not overwrite
* the matched documents with the update document.
*
* @param {Object} obj The document object to upsert or an array containing
* documents to upsert.
*
* If the document contains a primary key field (based on the collections's primary
* key) then the database will search for an existing document with a matching id.
* If a matching document is found, the document will be updated. Any keys that
* match keys on the existing document will be overwritten with new data. Any keys
* that do not currently exist on the document will be added to the document.
*
* If the document does not contain an id or the id passed does not match an existing
* document, an insert is performed instead. If no id is present a new primary key
* id is provided for the item.
*
* @param {Function=} callback Optional callback method.
* @returns {Object} An object containing two keys, "op" contains either "insert" or
* "update" depending on the type of operation that was performed and "result"
* contains the return data from the operation used.
*/
Collection.prototype.upsert = function (obj, callback) {
if (this._state === 'dropped') {
throw('ForerunnerDB.Collection "' + this.name() + '": Cannot operate in a dropped state!');
}
if (obj) {
var queue = this._deferQueue.upsert,
deferThreshold = this._deferThreshold.upsert;
var returnData = {},
query,
i;
// Determine if the object passed is an array or not
if (obj instanceof Array) {
if (obj.length > deferThreshold) {
// Break up upsert into blocks
this._deferQueue.upsert = queue.concat(obj);
// Fire off the insert queue handler
this.processQueue('upsert', callback);
return {};
} else {
// Loop the array and upsert each item
returnData = [];
for (i = 0; i < obj.length; i++) {
returnData.push(this.upsert(obj[i]));
}
if (callback) { callback(); }
return returnData;
}
}
// Determine if the operation is an insert or an update
if (obj[this._primaryKey]) {
// Check if an object with this primary key already exists
query = {};
query[this._primaryKey] = obj[this._primaryKey];
if (this._primaryIndex.lookup(query)[0]) {
// The document already exists with this id, this operation is an update
returnData.op = 'update';
} else {
// No document with this id exists, this operation is an insert
returnData.op = 'insert';
}
} else {
// The document passed does not contain an id, this operation is an insert
returnData.op = 'insert';
}
switch (returnData.op) {
case 'insert':
returnData.result = this.insert(obj);
break;
case 'update':
returnData.result = this.update(query, obj);
break;
default:
break;
}
return returnData;
} else {
if (callback) { callback(); }
}
return {};
};
/**
* Executes a method against each document that matches query and returns an
* array of documents that may have been modified by the method.
* @param {Object} query The query object.
* @param {Function} func The method that each document is passed to. If this method
* returns false for a particular document it is excluded from the results.
* @param {Object=} options Optional options object.
* @returns {Array}
*/
Collection.prototype.filter = function (query, func, options) {
return (this.find(query, options)).filter(func);
};
/**
* Executes a method against each document that matches query and then executes
* an update based on the return data of the method.
* @param {Object} query The query object.
* @param {Function} func The method that each document is passed to. If this method
* returns false for a particular document it is excluded from the update.
* @param {Object=} options Optional options object passed to the initial find call.
* @returns {Array}
*/
Collection.prototype.filterUpdate = function (query, func, options) {
var items = this.find(query, options),
results = [],
singleItem,
singleQuery,
singleUpdate,
pk = this.primaryKey(),
i;
for (i = 0; i < items.length; i++) {
singleItem = items[i];
singleUpdate = func(singleItem);
if (singleUpdate) {
singleQuery = {};
singleQuery[pk] = singleItem[pk];
results.push(this.update(singleQuery, singleUpdate));
}
}
return results;
};
/**
* Modifies an existing document or documents in a collection. This will update
* all matches for 'query' with the data held in 'update'. It will not overwrite
* the matched documents with the update document.
*
* @param {Object} query The query that must be matched for a document to be
* operated on.
* @param {Object} update The object containing updated key/values. Any keys that
* match keys on the existing document will be overwritten with this data. Any
* keys that do not currently exist on the document will be added to the document.
* @param {Object=} options An options object.
* @returns {Array} The items that were updated.
*/
Collection.prototype.update = function (query, update, options) {
if (this._state === 'dropped') {
throw('ForerunnerDB.Collection "' + this.name() + '": Cannot operate in a dropped state!');
}
// Decouple the update data
update = this.decouple(update);
// Handle transform
update = this.transformIn(update);
if (this.debug()) {
console.log('Updating some collection data for collection "' + this.name() + '"');
}
var self = this,
op = this._metrics.create('update'),
dataSet,
updated,
updateCall = function (originalDoc) {
var newDoc = self.decouple(originalDoc),
triggerOperation,
result;
if (self.willTrigger(self.TYPE_UPDATE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_UPDATE, self.PHASE_AFTER)) {
triggerOperation = {
type: 'update',
query: self.decouple(query),
update: self.decouple(update),
options: self.decouple(options),
op: op
};
// Update newDoc with the update criteria so we know what the data will look
// like AFTER the update is processed
result = self.updateObject(newDoc, triggerOperation.update, triggerOperation.query, triggerOperation.options, '');
if (self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_BEFORE, originalDoc, newDoc) !== false) {
// No triggers complained so let's execute the replacement of the existing
// object with the new one
result = self.updateObject(originalDoc, newDoc, triggerOperation.query, triggerOperation.options, '');
// NOTE: If for some reason we would only like to fire this event if changes are actually going
// to occur on the object from the proposed update then we can add "result &&" to the if
self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_AFTER, originalDoc, newDoc);
} else {
// Trigger cancelled operation so tell result that it was not updated
result = false;
}
} else {
// No triggers complained so let's execute the replacement of the existing
// object with the new one
result = self.updateObject(originalDoc, update, query, options, '');
}
return result;
};
op.start();
op.time('Retrieve documents to update');
dataSet = this.find(query, {$decouple: false});
op.time('Retrieve documents to update');
if (dataSet.length) {
op.time('Update documents');
updated = dataSet.filter(updateCall);
op.time('Update documents');
if (updated.length) {
op.time('Resolve chains');
this.chainSend('update', {
query: query,
update: update,
dataSet: dataSet
}, options);
op.time('Resolve chains');
this._onUpdate(updated);
this.deferEmit('change', {type: 'update', data: updated});
}
}
op.stop();
// TODO: Should we decouple the updated array before return by default?
return updated || [];
};
Collection.prototype._replaceObj = function (currentObj, newObj) {
var i;
// Check if the new document has a different primary key value from the existing one
// Remove item from indexes
this._removeFromIndexes(currentObj);
// Remove existing keys from current object
for (i in currentObj) {
if (currentObj.hasOwnProperty(i)) {
delete currentObj[i];
}
}
// Add new keys to current object
for (i in newObj) {
if (newObj.hasOwnProperty(i)) {
currentObj[i] = newObj[i];
}
}
// Update the item in the primary index
if (!this._insertIntoIndexes(currentObj)) {
throw('ForerunnerDB.Collection "' + this.name() + '": Primary key violation in update! Key violated: ' + currentObj[this._primaryKey]);
}
// Update the object in the collection data
//this._data.splice(this._data.indexOf(currentObj), 1, newObj);
return true;
};
/**
* Helper method to update a document from it's id.
* @param {String} id The id of the document.
* @param {Object} update The object containing the key/values to update to.
* @returns {Array} The items that were updated.
*/
Collection.prototype.updateById = function (id, update) {
var searchObj = {};
searchObj[this._primaryKey] = id;
return this.update(searchObj, update);
};
/**
* Internal method for document updating.
* @param {Object} doc The document to update.
* @param {Object} update The object with key/value pairs to update the document with.
* @param {Object} query The query object that we need to match to perform an update.
* @param {Object} options An options object.
* @param {String} path The current recursive path.
* @param {String} opType The type of update operation to perform, if none is specified
* default is to set new data against matching fields.
* @returns {Boolean} True if the document was updated with new / changed data or
* false if it was not updated because the data was the same.
* @private
*/
Collection.prototype.updateObject = function (doc, update, query, options, path, opType) {
// TODO: This method is long, try to break it into smaller pieces
update = this.decouple(update);
// Clear leading dots from path
path = path || '';
if (path.substr(0, 1) === '.') { path = path.substr(1, path.length -1); }
//var oldDoc = this.decouple(doc),
var updated = false,
recurseUpdated = false,
operation,
tmpArray,
tmpIndex,
tmpCount,
tempIndex,
pathInstance,
sourceIsArray,
updateIsArray,
i;
// Loop each key in the update object
for (i in update) {
if (update.hasOwnProperty(i)) {
// Reset operation flag
operation = false;
// Check if the property starts with a dollar (function)
if (i.substr(0, 1) === '$') {
// Check for commands
switch (i) {
case '$key':
case '$index':
case '$data':
// Ignore some operators
operation = true;
break;
case '$each':
operation = true;
// Loop over the array of updates and run each one
tmpCount = update.$each.length;
for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) {
recurseUpdated = this.updateObject(doc, update.$each[tmpIndex], query, options, path);
if (recurseUpdated) {
updated = true;
}
}
updated = updated || recurseUpdated;
break;
default:
operation = true;
// Now run the operation
recurseUpdated = this.updateObject(doc, update[i], query, options, path, i);
updated = updated || recurseUpdated;
break;
}
}
// Check if the key has a .$ at the end, denoting an array lookup
if (this._isPositionalKey(i)) {
operation = true;
// Modify i to be the name of the field
i = i.substr(0, i.length - 2);
pathInstance = new Path(path + '.' + i);
// Check if the key is an array and has items
if (doc[i] && doc[i] instanceof Array && doc[i].length) {
tmpArray = [];
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
if (this._match(doc[i][tmpIndex], pathInstance.value(query)[0], '', {})) {
tmpArray.push(tmpIndex);
}
}
// Loop the items that matched and update them
for (tmpIndex = 0; tmpIndex < tmpArray.length; tmpIndex++) {
recurseUpdated = this.updateObject(doc[i][tmpArray[tmpIndex]], update[i + '.$'], query, options, path + '.' + i, opType);
updated = updated || recurseUpdated;
}
}
}
if (!operation) {
if (!opType && typeof(update[i]) === 'object') {
if (doc[i] !== null && typeof(doc[i]) === 'object') {
// Check if we are dealing with arrays
sourceIsArray = doc[i] instanceof Array;
updateIsArray = update[i] instanceof Array;
if (sourceIsArray || updateIsArray) {
// Check if the update is an object and the doc is an array
if (!updateIsArray && sourceIsArray) {
// Update is an object, source is an array so match the array items
// with our query object to find the one to update inside this array
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
recurseUpdated = this.updateObject(doc[i][tmpIndex], update[i], query, options, path + '.' + i, opType);
updated = updated || recurseUpdated;
}
} else {
// Either both source and update are arrays or the update is
// an array and the source is not, so set source to update
if (doc[i] !== update[i]) {
this._updateProperty(doc, i, update[i]);
updated = true;
}
}
} else {
// The doc key is an object so traverse the
// update further
recurseUpdated = this.updateObject(doc[i], update[i], query, options, path + '.' + i, opType);
updated = updated || recurseUpdated;
}
} else {
if (doc[i] !== update[i]) {
this._updateProperty(doc, i, update[i]);
updated = true;
}
}
} else {
switch (opType) {
case '$inc':
this._updateIncrement(doc, i, update[i]);
updated = true;
break;
case '$cast':
// Casts a property to the type specified if it is not already
// that type. If the cast is an array or an object and the property
// is not already that type a new array or object is created and
// set to the property, overwriting the previous value
switch (update[i]) {
case 'array':
if (!(doc[i] instanceof Array)) {
// Cast to an array
this._updateProperty(doc, i, update.$data || []);
updated = true;
}
break;
case 'object':
if (!(doc[i] instanceof Object) || (doc[i] instanceof Array)) {
// Cast to an object
this._updateProperty(doc, i, update.$data || {});
updated = true;
}
break;
case 'number':
if (typeof doc[i] !== 'number') {
// Cast to a number
this._updateProperty(doc, i, Number(doc[i]));
updated = true;
}
break;
case 'string':
if (typeof doc[i] !== 'string') {
// Cast to a string
this._updateProperty(doc, i, String(doc[i]));
updated = true;
}
break;
default:
throw('ForerunnerDB.Collection "' + this.name() + '": Cannot update cast to unknown type: ' + update[i]);
}
break;
case '$push':
// Check if the target key is undefined and if so, create an array
if (doc[i] === undefined) {
// Initialise a new array
this._updateProperty(doc, i, []);
}
// Check that the target key is an array
if (doc[i] instanceof Array) {
// Check for a $position modifier with an $each
if (update[i].$position !== undefined && update[i].$each instanceof Array) {
// Grab the position to insert at
tempIndex = update[i].$position;
// Loop the each array and push each item
tmpCount = update[i].$each.length;
for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) {
this._updateSplicePush(doc[i], tempIndex + tmpIndex, update[i].$each[tmpIndex]);
}
} else if (update[i].$each instanceof Array) {
// Do a loop over the each to push multiple items
tmpCount = update[i].$each.length;
for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) {
this._updatePush(doc[i], update[i].$each[tmpIndex]);
}
} else {
// Do a standard push
this._updatePush(doc[i], update[i]);
}
updated = true;
} else {
throw('ForerunnerDB.Collection "' + this.name() + '": Cannot push to a key that is not an array! (' + i + ')');
}
break;
case '$pull':
if (doc[i] instanceof Array) {
tmpArray = [];
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
if (this._match(doc[i][tmpIndex], update[i], '', {})) {
tmpArray.push(tmpIndex);
}
}
tmpCount = tmpArray.length;
// Now loop the pull array and remove items to be pulled
while (tmpCount--) {
this._updatePull(doc[i], tmpArray[tmpCount]);
updated = true;
}
}
break;
case '$pullAll':
if (doc[i] instanceof Array) {
if (update[i] instanceof Array) {
tmpArray = doc[i];
tmpCount = tmpArray.length;
if (tmpCount > 0) {
// Now loop the pull array and remove items to be pulled
while (tmpCount--) {
for (tempIndex = 0; tempIndex < update[i].length; tempIndex++) {
if (tmpArray[tmpCount] === update[i][tempIndex]) {
this._updatePull(doc[i], tmpCount);
tmpCount--;
updated = true;
}
}
if (tmpCount < 0) {
break;
}
}
}
} else {
throw('ForerunnerDB.Collection "' + this.name() + '": Cannot pullAll without being given an array of values to pull! (' + i + ')');
}
}
break;
case '$addToSet':
// Check if the target key is undefined and if so, create an array
if (doc[i] === undefined) {
// Initialise a new array
this._updateProperty(doc, i, []);
}
// Check that the target key is an array
if (doc[i] instanceof Array) {
// Loop the target array and check for existence of item
var targetArr = doc[i],
targetArrIndex,
targetArrCount = targetArr.length,
objHash,
addObj = true,
optionObj = (options && options.$addToSet),
hashMode,
pathSolver;
// Check if we have an options object for our operation
if (update[i].$key) {
hashMode = false;
pathSolver = new Path(update[i].$key);
objHash = pathSolver.value(update[i])[0];
// Remove the key from the object before we add it
delete update[i].$key;
} else if (optionObj && optionObj.key) {
hashMode = false;
pathSolver = new Path(optionObj.key);
objHash = pathSolver.value(update[i])[0];
} else {
objHash = JSON.stringify(update[i]);
hashMode = true;
}
for (targetArrIndex = 0; targetArrIndex < targetArrCount; targetArrIndex++) {
if (hashMode) {
// Check if objects match via a string hash (JSON)
if (JSON.stringify(targetArr[targetArrIndex]) === objHash) {
// The object already exists, don't add it
addObj = false;
break;
}
} else {
// Check if objects match based on the path
if (objHash === pathSolver.value(targetArr[targetArrIndex])[0]) {
// The object already exists, don't add it
addObj = false;
break;
}
}
}
if (addObj) {
this._updatePush(doc[i], update[i]);
updated = true;
}
} else {
throw('ForerunnerDB.Collection "' + this.name() + '": Cannot addToSet on a key that is not an array! (' + i + ')');
}
break;
case '$splicePush':
// Check if the target key is undefined and if so, create an array
if (doc[i] === undefined) {
// Initialise a new array
this._updateProperty(doc, i, []);
}
// Check that the target key is an array
if (doc[i] instanceof Array) {
tempIndex = update.$index;
if (tempIndex !== undefined) {
delete update.$index;
// Check for out of bounds index
if (tempIndex > doc[i].length) {
tempIndex = doc[i].length;
}
this._updateSplicePush(doc[i], tempIndex, update[i]);
updated = true;
} else {
throw('ForerunnerDB.Collection "' + this.name() + '": Cannot splicePush without a $index integer value!');
}
} else {
throw('ForerunnerDB.Collection "' + this.name() + '": Cannot splicePush with a key that is not an array! (' + i + ')');
}
break;
case '$move':
if (doc[i] instanceof Array) {
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
if (this._match(doc[i][tmpIndex], update[i], '', {})) {
var moveToIndex = update.$index;
if (moveToIndex !== undefined) {
delete update.$index;
this._updateSpliceMove(doc[i], tmpIndex, moveToIndex);
updated = true;
} else {
throw('ForerunnerDB.Collection "' + this.name() + '": Cannot move without a $index integer value!');
}
break;
}
}
} else {
throw('ForerunnerDB.Collection "' + this.name() + '": Cannot move on a key that is not an array! (' + i + ')');
}
break;
case '$mul':
this._updateMultiply(doc, i, update[i]);
updated = true;
break;
case '$rename':
this._updateRename(doc, i, update[i]);
updated = true;
break;
case '$overwrite':
this._updateOverwrite(doc, i, update[i]);
updated = true;
break;
case '$unset':
this._updateUnset(doc, i);
updated = true;
break;
case '$clear':
this._updateClear(doc, i);
updated = true;
break;
case '$pop':
if (doc[i] instanceof Array) {
if (this._updatePop(doc[i], update[i])) {
updated = true;
}
} else {
throw('ForerunnerDB.Collection "' + this.name() + '": Cannot pop from a key that is not an array! (' + i + ')');
}
break;
default:
if (doc[i] !== update[i]) {
this._updateProperty(doc, i, update[i]);
updated = true;
}
break;
}
}
}
}
}
return updated;
};
/**
* Determines if the passed key has an array positional mark (a dollar at the end
* of its name).
* @param {String} key The key to check.
* @returns {Boolean} True if it is a positional or false if not.
* @private
*/
Collection.prototype._isPositionalKey = function (key) {
return key.substr(key.length - 2, 2) === '.$';
};
/**
* Removes any documents from the collection that match the search query
* key/values.
* @param {Object} query The query object.
* @param {Object=} options An options object.
* @param {Function=} callback A callback method.
* @returns {Array} An array of the documents that were removed.
*/
Collection.prototype.remove = function (query, options, callback) {
if (this._state === 'dropped') {
throw('ForerunnerDB.Collection "' + this.name() + '": Cannot operate in a dropped state!');
}
var self = this,
dataSet,
index,
arrIndex,
returnArr,
removeMethod,
triggerOperation,
doc,
newDoc;
if (query instanceof Array) {
returnArr = [];
for (arrIndex = 0; arrIndex < query.length; arrIndex++) {
returnArr.push(this.remove(query[arrIndex], {noEmit: true}));
}
if (!options || (options && !options.noEmit)) {
this._onRemove(returnArr);
}
if (callback) { callback(false, returnArr); }
return returnArr;
} else {
dataSet = this.find(query, {$decouple: false});
if (dataSet.length) {
removeMethod = function (dataItem) {
// Remove the item from the collection's indexes
self._removeFromIndexes(dataItem);
// Remove data from internal stores
index = self._data.indexOf(dataItem);
self._dataRemoveAtIndex(index);
};
// Remove the data from the collection
for (var i = 0; i < dataSet.length; i++) {
doc = dataSet[i];
if (self.willTrigger(self.TYPE_REMOVE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_REMOVE, self.PHASE_AFTER)) {
triggerOperation = {
type: 'remove'
};
newDoc = self.decouple(doc);
if (self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_BEFORE, newDoc, newDoc) !== false) {
// The trigger didn't ask to cancel so execute the removal method
removeMethod(doc);
self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_AFTER, newDoc, newDoc);
}
} else {
// No triggers to execute
removeMethod(doc);
}
}
//op.time('Resolve chains');
this.chainSend('remove', {
query: query,
dataSet: dataSet
}, options);
//op.time('Resolve chains');
if (!options || (options && !options.noEmit)) {
this._onRemove(dataSet);
}
this.deferEmit('change', {type: 'remove', data: dataSet});
}
if (callback) { callback(false, dataSet); }
return dataSet;
}
};
/**
* Helper method that removes a document that matches the given id.
* @param {String} id The id of the document to remove.
* @returns {Array} An array of documents that were removed.
*/
Collection.prototype.removeById = function (id) {
var searchObj = {};
searchObj[this._primaryKey] = id;
return this.remove(searchObj);
};
/**
* Queues an event to be fired. This has automatic de-bouncing so that any
* events of the same type that occur within 100 milliseconds of a previous
* one will all be wrapped into a single emit rather than emitting tons of
* events for lots of chained inserts etc.
* @private
*/
Collection.prototype.deferEmit = function () {
var self = this,
args;
if (!this._noEmitDefer && (!this._db || (this._db && !this._db._noEmitDefer))) {
args = arguments;
// Check for an existing timeout
if (this._changeTimeout) {
clearTimeout(this._changeTimeout);
}
// Set a timeout
this._changeTimeout = setTimeout(function () {
if (self.debug()) { console.log('ForerunnerDB.Collection: Emitting ' + args[0]); }
self.emit.apply(self, args);
}, 1);
} else {
this.emit.apply(this, arguments);
}
};
/**
* Processes a deferred action queue.
* @param {String} type The queue name to process.
* @param {Function} callback A method to call when the queue has processed.
*/
Collection.prototype.processQueue = function (type, callback) {
var queue = this._deferQueue[type],
deferThreshold = this._deferThreshold[type],
deferTime = this._deferTime[type];
if (queue.length) {
var self = this,
dataArr;
// Process items up to the threshold
if (queue.length) {
if (queue.length > deferThreshold) {
// Grab items up to the threshold value
dataArr = queue.splice(0, deferThreshold);
} else {
// Grab all the remaining items
dataArr = queue.splice(0, queue.length);
}
this[type](dataArr);
}
// Queue another process
setTimeout(function () {
self.processQueue(type, callback);
}, deferTime);
} else {
if (callback) { callback(); }
}
};
/**
* Inserts a document or array of documents into the collection.
* @param {Object||Array} data Either a document object or array of document
* @param {Number=} index Optional index to insert the record at.
* @param {Function=} callback Optional callback called once action is complete.
* objects to insert into the collection.
*/
Collection.prototype.insert = function (data, index, callback) {
if (this._state === 'dropped') {
throw('ForerunnerDB.Collection "' + this.name() + '": Cannot operate in a dropped state!');
}
if (typeof(index) === 'function') {
callback = index;
index = this._data.length;
} else if (index === undefined) {
index = this._data.length;
}
data = this.transformIn(data);
return this._insertHandle(data, index, callback);
};
/**
* Inserts a document or array of documents into the collection.
* @param {Object||Array} data Either a document object or array of document
* @param {Number=} index Optional index to insert the record at.
* @param {Function=} callback Optional callback called once action is complete.
* objects to insert into the collection.
*/
Collection.prototype._insertHandle = function (data, index, callback) {
var //self = this,
queue = this._deferQueue.insert,
deferThreshold = this._deferThreshold.insert,
//deferTime = this._deferTime.insert,
inserted = [],
failed = [],
insertResult,
i;
if (data instanceof Array) {
// Check if there are more insert items than the insert defer
// threshold, if so, break up inserts so we don't tie up the
// ui or thread
if (data.length > deferThreshold) {
// Break up insert into blocks
this._deferQueue.insert = queue.concat(data);
// Fire off the insert queue handler
this.processQueue('insert', callback);
return;
} else {
// Loop the array and add items
for (i = 0; i < data.length; i++) {
insertResult = this._insert(data[i], index + i);
if (insertResult === true) {
inserted.push(data[i]);
} else {
failed.push({
doc: data[i],
reason: insertResult
});
}
}
}
} else {
// Store the data item
insertResult = this._insert(data, index);
if (insertResult === true) {
inserted.push(data);
} else {
failed.push({
doc: data,
reason: insertResult
});
}
}
//op.time('Resolve chains');
this.chainSend('insert', data, {index: index});
//op.time('Resolve chains');
this._onInsert(inserted, failed);
if (callback) { callback(); }
this.deferEmit('change', {type: 'insert', data: inserted});
return {
inserted: inserted,
failed: failed
};
};
/**
* Internal method to insert a document into the collection. Will
* check for index violations before allowing the document to be inserted.
* @param {Object} doc The document to insert after passing index violation
* tests.
* @param {Number=} index Optional index to insert the document at.
* @returns {Boolean|Object} True on success, false if no document passed,
* or an object containing details about an index violation if one occurred.
* @private
*/
Collection.prototype._insert = function (doc, index) {
if (doc) {
var self = this,
indexViolation,
triggerOperation,
insertMethod,
newDoc;
this.ensurePrimaryKey(doc);
// Check indexes are not going to be broken by the document
indexViolation = this.insertIndexViolation(doc);
insertMethod = function (doc) {
// Add the item to the collection's indexes
self._insertIntoIndexes(doc);
// Check index overflow
if (index > self._data.length) {
index = self._data.length;
}
// Insert the document
self._dataInsertAtIndex(index, doc);
};
if (!indexViolation) {
if (self.willTrigger(self.TYPE_INSERT, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) {
triggerOperation = {
type: 'insert'
};
if (self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_BEFORE, {}, doc) !== false) {
insertMethod(doc);
if (self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) {
// Clone the doc so that the programmer cannot update the internal document
// on the "after" phase trigger
newDoc = self.decouple(doc);
self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_AFTER, {}, newDoc);
}
} else {
// The trigger just wants to cancel the operation
return false;
}
} else {
// No triggers to execute
insertMethod(doc);
}
return true;
} else {
return 'Index violation in index: ' + indexViolation;
}
}
return 'No document passed to insert';
};
/**
* Inserts a document into the internal collection data array at
* Inserts a document into the internal collection data array at
* the specified index.
* @param {number} index The index to insert at.
* @param {object} doc The document to insert.
* @private
*/
Collection.prototype._dataInsertAtIndex = function (index, doc) {
this._data.splice(index, 0, doc);
};
/**
* Removes a document from the internal collection data array at
* the specified index.
* @param {number} index The index to remove from.
* @private
*/
Collection.prototype._dataRemoveAtIndex = function (index) {
this._data.splice(index, 1);
};
/**
* Replaces all data in the collection's internal data array with
* the passed array of data.
* @param {array} data The array of data to replace existing data with.
* @private
*/
Collection.prototype._dataReplace = function (data) {
// Clear the array - using a while loop with pop is by far the
// fastest way to clear an array currently
while (this._data.length) {
this._data.pop();
}
// Append new items to the array
this._data = this._data.concat(data);
};
/**
* Inserts a document into the collection indexes.
* @param {Object} doc The document to insert.
* @private
*/
Collection.prototype._insertIntoIndexes = function (doc) {
var arr = this._indexByName,
arrIndex,
violated,
jString = JSON.stringify(doc);
// Insert to primary key index
violated = this._primaryIndex.uniqueSet(doc[this._primaryKey], doc);
this._primaryCrc.uniqueSet(doc[this._primaryKey], jString);
this._crcLookup.uniqueSet(jString, doc);
// Insert into other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arr[arrIndex].insert(doc);
}
}
return violated;
};
/**
* Removes a document from the collection indexes.
* @param {Object} doc The document to remove.
* @private
*/
Collection.prototype._removeFromIndexes = function (doc) {
var arr = this._indexByName,
arrIndex,
jString = JSON.stringify(doc);
// Remove from primary key index
this._primaryIndex.unSet(doc[this._primaryKey]);
this._primaryCrc.unSet(doc[this._primaryKey]);
this._crcLookup.unSet(jString);
// Remove from other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arr[arrIndex].remove(doc);
}
}
};
/**
* Rebuild collection indexes.
* @private
*/
Collection.prototype._rebuildIndexes = function () {
var arr = this._indexByName,
arrIndex;
// Remove from other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arr[arrIndex].rebuild();
}
}
};
/**
* Returns the index of the document identified by the passed item's primary key.
* @param {Object} item The item whose primary key should be used to lookup.
* @returns {Number} The index the item with the matching primary key is occupying.
*/
Collection.prototype.indexOfDocById = function (item) {
return this._data.indexOf(
this._primaryIndex.get(
item[this._primaryKey]
)
);
};
/**
* Uses the passed query to generate a new collection with results
* matching the query parameters.
*
* @param query
* @param options
* @returns {*}
*/
Collection.prototype.subset = function (query, options) {
var result = this.find(query, options);
return new Collection()
._subsetOf(this)
.primaryKey(this._primaryKey)
.setData(result);
};
/**
* Gets the collection that this collection is a subset of.
* @returns {Collection}
*/
Collection.prototype.subsetOf = function () {
return this.__subsetOf;
};
/**
* Sets the collection that this collection is a subset of.
* @param {Collection} collection The collection to set as the parent of this subset.
* @returns {*} This object for chaining.
* @private
*/
Collection.prototype._subsetOf = function (collection) {
this.__subsetOf = collection;
return this;
};
/**
* Find the distinct values for a specified field across a single collection and
* returns the results in an array.
* @param {String} key The field path to return distinct values for e.g. "person.name".
* @param {Object=} query The query to use to filter the documents used to return values from.
* @param {Object=} options The query options to use when running the query.
* @returns {Array}
*/
Collection.prototype.distinct = function (key, query, options) {
if (this._state === 'dropped') {
throw('ForerunnerDB.Collection "' + this.name() + '": Cannot operate in a dropped state!');
}
var data = this.find(query, options),
pathSolver = new Path(key),
valueUsed = {},
distinctValues = [],
value,
i;
// Loop the data and build array of distinct values
for (i = 0; i < data.length; i++) {
value = pathSolver.value(data[i])[0];
if (value && !valueUsed[value]) {
valueUsed[value] = true;
distinctValues.push(value);
}
}
return distinctValues;
};
/**
* Helper method to find a document by it's id.
* @param {String} id The id of the document.
* @param {Object=} options The options object, allowed keys are sort and limit.
* @returns {Array} The items that were updated.
*/
Collection.prototype.findById = function (id, options) {
var searchObj = {};
searchObj[this._primaryKey] = id;
return this.find(searchObj, options)[0];
};
/**
* Finds all documents that contain the passed string or search object
* regardless of where the string might occur within the document. This
* will match strings from the start, middle or end of the document's
* string (partial match).
* @param search The string to search for. Case sensitive.
* @param options A standard find() options object.
* @returns {Array} An array of documents that matched the search string.
*/
Collection.prototype.peek = function (search, options) {
// Loop all items
var arr = this._data,
arrCount = arr.length,
arrIndex,
arrItem,
tempColl = new Collection(),
typeOfSearch = typeof search;
if (typeOfSearch === 'string') {
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
// Get json representation of object
arrItem = JSON.stringify(arr[arrIndex]);
// Check if string exists in object json
if (arrItem.indexOf(search) > -1) {
// Add this item to the temp collection
tempColl.insert(arr[arrIndex]);
}
}
return tempColl.find({}, options);
} else {
return this.find(search, options);
}
};
/**
* Provides a query plan / operations log for a query.
* @param {Object} query The query to execute.
* @param {Object=} options Optional options object.
* @returns {Object} The query plan.
*/
Collection.prototype.explain = function (query, options) {
var result = this.find(query, options);
return result.__fdbOp._data;
};
/**
* Generates an options object with default values or adds default
* values to a passed object if those values are not currently set
* to anything.
* @param {object=} obj Optional options object to modify.
* @returns {object} The options object.
*/
Collection.prototype.options = function (obj) {
obj = obj || {};
obj.$decouple = obj.$decouple !== undefined ? obj.$decouple : true;
obj.$explain = obj.$explain !== undefined ? obj.$explain : false;
return obj;
};
/**
* Queries the collection based on the query object passed.
* @param {Object} query The query key/values that a document must match in
* order for it to be returned in the result array.
* @param {Object=} options An optional options object.
*
* @returns {Array} The results array from the find operation, containing all
* documents that matched the query.
*/
Collection.prototype.find = function (query, options) {
if (this._state === 'dropped') {
throw('ForerunnerDB.Collection "' + this.name() + '": Cannot operate in a dropped state!');
}
// TODO: This method is quite long, break into smaller pieces
query = query || {};
options = this.options(options);
var op = this._metrics.create('find'),
pk = this.primaryKey(),
self = this,
analysis,
//finalQuery,
scanLength,
requiresTableScan = true,
resultArr,
joinCollectionIndex,
joinIndex,
joinCollection = {},
joinQuery,
joinPath,
joinCollectionName,
joinCollectionInstance,
joinMatch,
joinMatchIndex,
joinSearch,
joinMulti,
joinRequire,
joinFindResults,
resultCollectionName,
resultIndex,
resultRemove = [],
index,
i, j, k,
fieldListOn = [],
fieldListOff = [],
elemMatchPathSolver,
elemMatchSubArr,
elemMatchSpliceArr,
matcherTmpOptions = {},
result,
cursor = {},
matcher = function (doc) {
return self._match(doc, query, 'and', matcherTmpOptions);
};
op.start();
if (query) {
// Get query analysis to execute best optimised code path
op.time('analyseQuery');
analysis = this._analyseQuery(query, options, op);
op.time('analyseQuery');
op.data('analysis', analysis);
if (analysis.hasJoin && analysis.queriesJoin) {
// The query has a join and tries to limit by it's joined data
// Get an instance reference to the join collections
op.time('joinReferences');
for (joinIndex = 0; joinIndex < analysis.joinsOn.length; joinIndex++) {
joinCollectionName = analysis.joinsOn[joinIndex];
joinPath = new Path(analysis.joinQueries[joinCollectionName]);
joinQuery = joinPath.value(query)[0];
joinCollection[analysis.joinsOn[joinIndex]] = this._db.collection(analysis.joinsOn[joinIndex]).subset(joinQuery);
}
op.time('joinReferences');
}
// Check if an index lookup can be used to return this result
if (analysis.indexMatch.length && (!options || (options && !options.$skipIndex))) {
op.data('index.potential', analysis.indexMatch);
op.data('index.used', analysis.indexMatch[0].index);
// Get the data from the index
op.time('indexLookup');
resultArr = analysis.indexMatch[0].lookup;
op.time('indexLookup');
// Check if the index coverage is all keys, if not we still need to table scan it
if (analysis.indexMatch[0].keyData.totalKeyCount === analysis.indexMatch[0].keyData.score) {
// Require a table scan to find relevant documents
requiresTableScan = false;
}
} else {
op.flag('usedIndex', false);
}
if (requiresTableScan) {
if (resultArr && resultArr.length) {
scanLength = resultArr.length;
op.time('tableScan: ' + scanLength);
// Filter the source data and return the result
resultArr = resultArr.filter(matcher);
} else {
// Filter the source data and return the result
scanLength = this._data.length;
op.time('tableScan: ' + scanLength);
resultArr = this._data.filter(matcher);
}
// Order the array if we were passed a sort clause
if (options.$orderBy) {
op.time('sort');
resultArr = this.sort(options.$orderBy, resultArr);
op.time('sort');
}
op.time('tableScan: ' + scanLength);
}
if (options.$page !== undefined && options.$limit !== undefined) {
// Record paging data
cursor.page = options.$page;
cursor.pages = Math.ceil(resultArr.length / options.$limit);
cursor.records = resultArr.length;
// Check if we actually need to apply the paging logic
if (options.$page && options.$limit > 0) {
op.data('cursor', cursor);
// Skip to the page specified based on limit
resultArr.splice(0, options.$page * options.$limit);
}
}
if (options.$skip) {
cursor.skip = options.$skip;
// Skip past the number of records specified
resultArr.splice(0, options.$skip);
op.data('skip', options.$skip);
}
if (options.$limit && resultArr && resultArr.length > options.$limit) {
cursor.limit = options.$limit;
resultArr.length = options.$limit;
op.data('limit', options.$limit);
}
if (options.$decouple) {
// Now decouple the data from the original objects
op.time('decouple');
resultArr = this.decouple(resultArr);
op.time('decouple');
op.data('flag.decouple', true);
}
// Now process any joins on the final data
if (options.$join) {
for (joinCollectionIndex = 0; joinCollectionIndex < options.$join.length; joinCollectionIndex++) {
for (joinCollectionName in options.$join[joinCollectionIndex]) {
if (options.$join[joinCollectionIndex].hasOwnProperty(joinCollectionName)) {
// Set the key to store the join result in to the collection name by default
resultCollectionName = joinCollectionName;
// Get the join collection instance from the DB
joinCollectionInstance = this._db.collection(joinCollectionName);
// Get the match data for the join
joinMatch = options.$join[joinCollectionIndex][joinCollectionName];
// Loop our result data array
for (resultIndex = 0; resultIndex < resultArr.length; resultIndex++) {
// Loop the join conditions and build a search object from them
joinSearch = {};
joinMulti = false;
joinRequire = false;
for (joinMatchIndex in joinMatch) {
if (joinMatch.hasOwnProperty(joinMatchIndex)) {
// Check the join condition name for a special command operator
if (joinMatchIndex.substr(0, 1) === '$') {
// Special command
switch (joinMatchIndex) {
case '$as':
// Rename the collection when stored in the result document
resultCollectionName = joinMatch[joinMatchIndex];
break;
case '$multi':
// Return an array of documents instead of a single matching document
joinMulti = joinMatch[joinMatchIndex];
break;
case '$require':
// Remove the result item if no matching join data is found
joinRequire = joinMatch[joinMatchIndex];
break;
/*default:
// Check for a double-dollar which is a back-reference to the root collection item
if (joinMatchIndex.substr(0, 3) === '$$.') {
// Back reference
// TODO: Support complex joins
}
break;*/
}
} else {
// TODO: Could optimise this by caching path objects
// Get the data to match against and store in the search object
joinSearch[joinMatchIndex] = new Path(joinMatch[joinMatchIndex]).value(resultArr[resultIndex])[0];
}
}
}
// Do a find on the target collection against the match data
joinFindResults = joinCollectionInstance.find(joinSearch);
// Check if we require a joined row to allow the result item
if (!joinRequire || (joinRequire && joinFindResults[0])) {
// Join is not required or condition is met
resultArr[resultIndex][resultCollectionName] = joinMulti === false ? joinFindResults[0] : joinFindResults;
} else {
// Join required but condition not met, add item to removal queue
resultRemove.push(resultArr[resultIndex]);
}
}
}
}
}
op.data('flag.join', true);
}
// Process removal queue
if (resultRemove.length) {
op.time('removalQueue');
for (i = 0; i < resultRemove.length; i++) {
index = resultArr.indexOf(resultRemove[i]);
if (index > -1) {
resultArr.splice(index, 1);
}
}
op.time('removalQueue');
}
if (options.$transform) {
op.time('transform');
for (i = 0; i < resultArr.length; i++) {
resultArr.splice(i, 1, options.$transform(resultArr[i]));
}
op.time('transform');
op.data('flag.transform', true);
}
// Process transforms
if (this._transformEnabled && this._transformOut) {
op.time('transformOut');
resultArr = this.transformOut(resultArr);
op.time('transformOut');
}
op.data('results', resultArr.length);
} else {
resultArr = [];
}
// Generate a list of fields to limit data by
// Each property starts off being enabled by default (= 1) then
// if any property is explicitly specified as 1 then all switch to
// zero except _id.
//
// Any that are explicitly set to zero are switched off.
op.time('scanFields');
for (i in options) {
if (options.hasOwnProperty(i) && i.indexOf('$') !== 0) {
if (options[i] === 1) {
fieldListOn.push(i);
} else if (options[i] === 0) {
fieldListOff.push(i);
}
}
}
op.time('scanFields');
// Limit returned fields by the options data
if (fieldListOn.length || fieldListOff.length) {
op.data('flag.limitFields', true);
op.data('limitFields.on', fieldListOn);
op.data('limitFields.off', fieldListOff);
op.time('limitFields');
// We have explicit fields switched on or off
for (i = 0; i < resultArr.length; i++) {
result = resultArr[i];
for (j in result) {
if (result.hasOwnProperty(j)) {
if (fieldListOn.length) {
// We have explicit fields switched on so remove all fields
// that are not explicitly switched on
// Check if the field name is not the primary key
if (j !== pk) {
if (fieldListOn.indexOf(j) === -1) {
// This field is not in the on list, remove it
delete result[j];
}
}
}
if (fieldListOff.length) {
// We have explicit fields switched off so remove fields
// that are explicitly switched off
if (fieldListOff.indexOf(j) > -1) {
// This field is in the off list, remove it
delete result[j];
}
}
}
}
}
op.time('limitFields');
}
// Now run any projections on the data required
if (options.$elemMatch) {
op.data('flag.elemMatch', true);
op.time('projection-elemMatch');
for (i in options.$elemMatch) {
if (options.$elemMatch.hasOwnProperty(i)) {
elemMatchPathSolver = new Path(i);
// Loop the results array
for (j = 0; j < resultArr.length; j++) {
elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0];
// Check we have a sub-array to loop
if (elemMatchSubArr && elemMatchSubArr.length) {
// Loop the sub-array and check for projection query matches
for (k = 0; k < elemMatchSubArr.length; k++) {
// Check if the current item in the sub-array matches the projection query
if (self._match(elemMatchSubArr[k], options.$elemMatch[i], '', {})) {
// The item matches the projection query so set the sub-array
// to an array that ONLY contains the matching item and then
// exit the loop since we only want to match the first item
elemMatchPathSolver.set(resultArr[j], i, [elemMatchSubArr[k]]);
break;
}
}
}
}
}
}
op.time('projection-elemMatch');
}
if (options.$elemsMatch) {
op.data('flag.elemsMatch', true);
op.time('projection-elemsMatch');
for (i in options.$elemsMatch) {
if (options.$elemsMatch.hasOwnProperty(i)) {
elemMatchPathSolver = new Path(i);
// Loop the results array
for (j = 0; j < resultArr.length; j++) {
elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0];
// Check we have a sub-array to loop
if (elemMatchSubArr && elemMatchSubArr.length) {
elemMatchSpliceArr = [];
// Loop the sub-array and check for projection query matches
for (k = 0; k < elemMatchSubArr.length; k++) {
// Check if the current item in the sub-array matches the projection query
if (self._match(elemMatchSubArr[k], options.$elemsMatch[i], '', {})) {
// The item matches the projection query so add it to the final array
elemMatchSpliceArr.push(elemMatchSubArr[k]);
}
}
// Now set the final sub-array to the matched items
elemMatchPathSolver.set(resultArr[j], i, elemMatchSpliceArr);
}
}
}
}
op.time('projection-elemsMatch');
}
op.stop();
resultArr.__fdbOp = op;
resultArr.$cursor = cursor;
return resultArr;
};
/**
* Returns one document that satisfies the specified query criteria. If multiple
* documents satisfy the query, this method returns the first document to match
* the query.
* @returns {*}
*/
Collection.prototype.findOne = function () {
return (this.find.apply(this, arguments))[0];
};
/**
* Gets the index in the collection data array of the first item matched by
* the passed query object.
* @param {Object} query The query to run to find the item to return the index of.
* @returns {Number}
*/
Collection.prototype.indexOf = function (query) {
var item = this.find(query, {$decouple: false})[0];
if (item) {
return this._data.indexOf(item);
}
};
/**
* Gets / sets the collection transform options.
* @param {Object} obj A collection transform options object.
* @returns {*}
*/
Collection.prototype.transform = function (obj) {
if (obj !== undefined) {
if (typeof obj === "object") {
if (obj.enabled !== undefined) {
this._transformEnabled = obj.enabled;
}
if (obj.dataIn !== undefined) {
this._transformIn = obj.dataIn;
}
if (obj.dataOut !== undefined) {
this._transformOut = obj.dataOut;
}
} else {
this._transformEnabled = obj !== false;
}
return this;
}
return {
enabled: this._transformEnabled,
dataIn: this._transformIn,
dataOut: this._transformOut
};
};
/**
* Transforms data using the set transformIn method.
* @param {Object} data The data to transform.
* @returns {*}
*/
Collection.prototype.transformIn = function (data) {
if (this._transformEnabled && this._transformIn) {
if (data instanceof Array) {
var finalArr = [], i;
for (i = 0; i < data.length; i++) {
finalArr[i] = this._transformIn(data[i]);
}
return finalArr;
} else {
return this._transformIn(data);
}
}
return data;
};
/**
* Transforms data using the set transformOut method.
* @param {Object} data The data to transform.
* @returns {*}
*/
Collection.prototype.transformOut = function (data) {
if (this._transformEnabled && this._transformOut) {
if (data instanceof Array) {
var finalArr = [], i;
for (i = 0; i < data.length; i++) {
finalArr[i] = this._transformOut(data[i]);
}
return finalArr;
} else {
return this._transformOut(data);
}
}
return data;
};
/**
* Sorts an array of documents by the given sort path.
* @param {*} sortObj The keys and orders the array objects should be sorted by.
* @param {Array} arr The array of documents to sort.
* @returns {Array}
*/
Collection.prototype.sort = function (sortObj, arr) {
// Make sure we have an array object
arr = arr || [];
var sortArr = [],
sortKey,
sortSingleObj;
for (sortKey in sortObj) {
if (sortObj.hasOwnProperty(sortKey)) {
sortSingleObj = {};
sortSingleObj[sortKey] = sortObj[sortKey];
sortSingleObj.___fdbKey = sortKey;
sortArr.push(sortSingleObj);
}
}
if (sortArr.length < 2) {
// There is only one sort criteria, do a simple sort and return it
return this._sort(sortObj, arr);
} else {
return this._bucketSort(sortArr, arr);
}
};
/**
* Takes array of sort paths and sorts them into buckets before returning final
* array fully sorted by multi-keys.
* @param keyArr
* @param arr
* @returns {*}
* @private
*/
Collection.prototype._bucketSort = function (keyArr, arr) {
var keyObj = keyArr.shift(),
arrCopy,
buckets,
i,
finalArr = [];
if (keyArr.length > 0) {
// Sort array by bucket key
arr = this._sort(keyObj, arr);
// Split items into buckets
buckets = this.bucket(keyObj.___fdbKey, arr);
// Loop buckets and sort contents
for (i in buckets) {
if (buckets.hasOwnProperty(i)) {
arrCopy = [].concat(keyArr);
finalArr = finalArr.concat(this._bucketSort(arrCopy, buckets[i]));
}
}
return finalArr;
} else {
return this._sort(keyObj, arr);
}
};
/**
* Sorts array by individual sort path.
* @param key
* @param arr
* @returns {Array|*}
* @private
*/
Collection.prototype._sort = function (key, arr) {
var self = this,
sorterMethod,
pathSolver = new Path(),
dataPath = pathSolver.parse(key, true)[0];
pathSolver.path(dataPath.path);
if (dataPath.value === 1) {
// Sort ascending
sorterMethod = function (a, b) {
var valA = pathSolver.value(a)[0],
valB = pathSolver.value(b)[0];
return self.sortAsc(valA, valB);
};
} else if (dataPath.value === -1) {
// Sort descending
sorterMethod = function (a, b) {
var valA = pathSolver.value(a)[0],
valB = pathSolver.value(b)[0];
return self.sortDesc(valA, valB);
};
} else {
throw('ForerunnerDB.Collection "' + this.name() + '": $orderBy clause has invalid direction: ' + dataPath.value + ', accepted values are 1 or -1 for ascending or descending!');
}
return arr.sort(sorterMethod);
};
/**
* Takes an array of objects and returns a new object with the array items
* split into buckets by the passed key.
* @param {String} key The key to split the array into buckets by.
* @param {Array} arr An array of objects.
* @returns {Object}
*/
Collection.prototype.bucket = function (key, arr) {
var i,
buckets = {};
for (i = 0; i < arr.length; i++) {
buckets[arr[i][key]] = buckets[arr[i][key]] || [];
buckets[arr[i][key]].push(arr[i]);
}
return buckets;
};
/**
* Internal method that takes a search query and options and returns an object
* containing details about the query which can be used to optimise the search.
*
* @param query
* @param options
* @param op
* @returns {Object}
* @private
*/
Collection.prototype._analyseQuery = function (query, options, op) {
var analysis = {
queriesOn: [this._name],
indexMatch: [],
hasJoin: false,
queriesJoin: false,
joinQueries: {},
query: query,
options: options
},
joinCollectionIndex,
joinCollectionName,
joinCollections = [],
joinCollectionReferences = [],
queryPath,
index,
indexMatchData,
indexRef,
indexRefName,
indexLookup,
pathSolver,
queryKeyCount,
i;
// Check if the query is a primary key lookup
op.time('checkIndexes');
pathSolver = new Path();
queryKeyCount = pathSolver.countKeys(query);
if (queryKeyCount) {
if (query[this._primaryKey] !== undefined) {
// Return item via primary key possible
op.time('checkIndexMatch: Primary Key');
analysis.indexMatch.push({
lookup: this._primaryIndex.lookup(query, options),
keyData: {
matchedKeys: [this._primaryKey],
totalKeyCount: queryKeyCount,
score: 1
},
index: this._primaryIndex
});
op.time('checkIndexMatch: Primary Key');
}
// Check if an index can speed up the query
for (i in this._indexById) {
if (this._indexById.hasOwnProperty(i)) {
indexRef = this._indexById[i];
indexRefName = indexRef.name();
op.time('checkIndexMatch: ' + indexRefName);
indexMatchData = indexRef.match(query, options);
if (indexMatchData.score > 0) {
// This index can be used, store it
indexLookup = indexRef.lookup(query, options);
analysis.indexMatch.push({
lookup: indexLookup,
keyData: indexMatchData,
index: indexRef
});
}
op.time('checkIndexMatch: ' + indexRefName);
if (indexMatchData.score === queryKeyCount) {
// Found an optimal index, do not check for any more
break;
}
}
}
op.time('checkIndexes');
// Sort array descending on index key count (effectively a measure of relevance to the query)
if (analysis.indexMatch.length > 1) {
op.time('findOptimalIndex');
analysis.indexMatch.sort(function (a, b) {
if (a.keyData.score > b.keyData.score) {
// This index has a higher score than the other
return -1;
}
if (a.keyData.score < b.keyData.score) {
// This index has a lower score than the other
return 1;
}
// The indexes have the same score but can still be compared by the number of records
// they return from the query. The fewer records they return the better so order by
// record count
if (a.keyData.score === b.keyData.score) {
return a.lookup.length - b.lookup.length;
}
});
op.time('findOptimalIndex');
}
}
// Check for join data
if (options.$join) {
analysis.hasJoin = true;
// Loop all join operations
for (joinCollectionIndex = 0; joinCollectionIndex < options.$join.length; joinCollectionIndex++) {
// Loop the join collections and keep a reference to them
for (joinCollectionName in options.$join[joinCollectionIndex]) {
if (options.$join[joinCollectionIndex].hasOwnProperty(joinCollectionName)) {
joinCollections.push(joinCollectionName);
// Check if the join uses an $as operator
if ('$as' in options.$join[joinCollectionIndex][joinCollectionName]) {
joinCollectionReferences.push(options.$join[joinCollectionIndex][joinCollectionName].$as);
} else {
joinCollectionReferences.push(joinCollectionName);
}
}
}
}
// Loop the join collection references and determine if the query references
// any of the collections that are used in the join. If there no queries against
// joined collections the find method can use a code path optimised for this.
// Queries against joined collections requires the joined collections to be filtered
// first and then joined so requires a little more work.
for (index = 0; index < joinCollectionReferences.length; index++) {
// Check if the query references any collection data that the join will create
queryPath = this._queryReferencesCollection(query, joinCollectionReferences[index], '');
if (queryPath) {
analysis.joinQueries[joinCollections[index]] = queryPath;
analysis.queriesJoin = true;
}
}
analysis.joinsOn = joinCollections;
analysis.queriesOn = analysis.queriesOn.concat(joinCollections);
}
return analysis;
};
/**
* Checks if the passed query references this collection.
* @param query
* @param collection
* @param path
* @returns {*}
* @private
*/
Collection.prototype._queryReferencesCollection = function (query, collection, path) {
var i;
for (i in query) {
if (query.hasOwnProperty(i)) {
// Check if this key is a reference match
if (i === collection) {
if (path) { path += '.'; }
return path + i;
} else {
if (typeof(query[i]) === 'object') {
// Recurse
if (path) { path += '.'; }
path += i;
return this._queryReferencesCollection(query[i], collection, path);
}
}
}
}
return false;
};
/**
* Returns the number of documents currently in the collection.
* @returns {Number}
*/
Collection.prototype.count = function (query, options) {
if (!query) {
return this._data.length;
} else {
// Run query and return count
return this.find(query, options).length;
}
};
/**
* Finds sub-documents from the collection's documents.
* @param match
* @param path
* @param subDocQuery
* @param subDocOptions
* @returns {*}
*/
Collection.prototype.findSub = function (match, path, subDocQuery, subDocOptions) {
var pathHandler = new Path(path),
docArr = this.find(match),
docCount = docArr.length,
docIndex,
subDocArr,
subDocCollection = this._db.collection('__FDB_temp_' + this.objectId()),
subDocResults,
resultObj = {
parents: docCount,
subDocTotal: 0,
subDocs: [],
pathFound: false,
err: ''
};
for (docIndex = 0; docIndex < docCount; docIndex++) {
subDocArr = pathHandler.value(docArr[docIndex])[0];
if (subDocArr) {
subDocCollection.setData(subDocArr);
subDocResults = subDocCollection.find(subDocQuery, subDocOptions);
if (subDocOptions.returnFirst && subDocResults.length) {
return subDocResults[0];
}
resultObj.subDocs.push(subDocResults);
resultObj.subDocTotal += subDocResults.length;
resultObj.pathFound = true;
}
}
// Drop the sub-document collection
subDocCollection.drop();
// Check if the call should not return stats, if so return only subDocs array
if (subDocOptions.noStats) {
return resultObj.subDocs;
}
if (!resultObj.pathFound) {
resultObj.err = 'No objects found in the parent documents with a matching path of: ' + path;
}
return resultObj;
};
/**
* Checks that the passed document will not violate any index rules if
* inserted into the collection.
* @param {Object} doc The document to check indexes against.
* @returns {Boolean} Either false (no violation occurred) or true if
* a violation was detected.
*/
Collection.prototype.insertIndexViolation = function (doc) {
var indexViolated,
arr = this._indexByName,
arrIndex,
arrItem;
// Check the item's primary key is not already in use
if (this._primaryIndex.get(doc[this._primaryKey])) {
indexViolated = this._primaryIndex;
} else {
// Check violations of other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arrItem = arr[arrIndex];
if (arrItem.unique()) {
if (arrItem.violation(doc)) {
indexViolated = arrItem;
break;
}
}
}
}
}
return indexViolated ? indexViolated.name() : false;
};
/**
* Creates an index on the specified keys.
* @param {Object} keys The object containing keys to index.
* @param {Object} options An options object.
* @returns {*}
*/
Collection.prototype.ensureIndex = function (keys, options) {
if (this._state === 'dropped') {
throw('ForerunnerDB.Collection "' + this.name() + '": Cannot operate in a dropped state!');
}
this._indexByName = this._indexByName || {};
this._indexById = this._indexById || {};
var index,
time = {
start: new Date().getTime()
};
if (options) {
switch (options.type) {
case 'hashed':
index = new IndexHashMap(keys, options, this);
break;
case 'btree':
index = new IndexBinaryTree(keys, options, this);
break;
default:
// Default
index = new IndexHashMap(keys, options, this);
break;
}
} else {
// Default
index = new IndexHashMap(keys, options, this);
}
// Check the index does not already exist
if (this._indexByName[index.name()]) {
// Index already exists
return {
err: 'Index with that name already exists'
};
}
if (this._indexById[index.id()]) {
// Index already exists
return {
err: 'Index with those keys already exists'
};
}
// Create the index
index.rebuild();
// Add the index
this._indexByName[index.name()] = index;
this._indexById[index.id()] = index;
time.end = new Date().getTime();
time.total = time.end - time.start;
this._lastOp = {
type: 'ensureIndex',
stats: {
time: time
}
};
return {
index: index,
id: index.id(),
name: index.name(),
state: index.state()
};
};
/**
* Gets an index by it's name.
* @param {String} name The name of the index to retreive.
* @returns {*}
*/
Collection.prototype.index = function (name) {
if (this._indexByName) {
return this._indexByName[name];
}
};
/**
* Gets the last reporting operation's details such as run time.
* @returns {Object}
*/
Collection.prototype.lastOp = function () {
return this._metrics.list();
};
/**
* Generates a difference object that contains insert, update and remove arrays
* representing the operations to execute to make this collection have the same
* data as the one passed.
* @param {Collection} collection The collection to diff against.
* @returns {{}}
*/
Collection.prototype.diff = function (collection) {
var diff = {
insert: [],
update: [],
remove: []
};
var pm = this.primaryKey(),
arr,
arrIndex,
arrItem,
arrCount;
// Check if the primary key index of each collection can be utilised
if (pm !== collection.primaryKey()) {
throw('ForerunnerDB.Collection "' + this.name() + '": Collection diffing requires that both collections have the same primary key!');
}
// Use the collection primary key index to do the diff (super-fast)
arr = collection._data;
// Check if we have an array or another collection
while (arr && !(arr instanceof Array)) {
// We don't have an array, assign collection and get data
collection = arr;
arr = collection._data;
}
arrCount = arr.length;
// Loop the collection's data array and check for matching items
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arrItem = arr[arrIndex];
// Check for a matching item in this collection
if (this._primaryIndex.get(arrItem[pm])) {
// Matching item exists, check if the data is the same
if (this._primaryCrc.get(arrItem[pm]) !== collection._primaryCrc.get(arrItem[pm])) {
// The documents exist in both collections but data differs, update required
diff.update.push(arrItem);
}
} else {
// The document is missing from this collection, insert required
diff.insert.push(arrItem);
}
}
// Now loop this collection's data and check for matching items
arr = this._data;
arrCount = arr.length;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arrItem = arr[arrIndex];
if (!collection._primaryIndex.get(arrItem[pm])) {
// The document does not exist in the other collection, remove required
diff.remove.push(arrItem);
}
}
return diff;
};
Collection.prototype.collateAdd = new Overload({
'object, string': function (collection, keyName) {
var self = this;
self.collateAdd(collection, function (packet) {
var obj1,
obj2;
switch (packet.type) {
case 'insert':
obj1 = {
$push: {}
};
obj1.$push[keyName] = self.decouple(packet.data);
self.update({}, obj1);
break;
case 'update':
obj1 = {};
obj2 = {};
obj1[keyName] = packet.data.query;
obj2[keyName + '.$'] = packet.data.update;
self.update(obj1, obj2);
break;
case 'remove':
obj1 = {
$pull: {}
};
obj1.$pull[keyName] = {};
obj1.$pull[keyName][self.primaryKey()] = packet.data.dataSet[0][collection.primaryKey()];
self.update({}, obj1);
break;
default:
}
});
},
'object, function': function (collection, process) {
if (typeof collection === 'string') {
// The collection passed is a name, not a reference so get
// the reference from the name
collection = this._db.collection(collection, {
autoCreate: false,
throwError: false
});
}
if (collection) {
this._collate = this._collate || {};
this._collate[collection.name()] = new ReactorIO(collection, this, process);
return this;
} else {
throw('Cannot collate from a non-existent collection!');
}
}
});
Collection.prototype.collateRemove = function (collection) {
if (typeof collection === 'object') {
// We need to have the name of the collection to remove it
collection = collection.name();
}
if (collection) {
// Drop the reactor IO chain node
this._collate[collection].drop();
// Remove the collection data from the collate object
delete this._collate[collection];
return this;
} else {
throw('No collection name passed to collateRemove() or collection not found!');
}
};
Db.prototype.collection = new Overload({
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @param {Object} options An options object.
* @returns {Collection}
*/
'object': function (options) {
return this.$main.call(this, options);
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @param {String} collectionName The name of the collection.
* @returns {Collection}
*/
'string': function (collectionName) {
return this.$main.call(this, {
name: collectionName
});
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @param {String} collectionName The name of the collection.
* @param {String} primaryKey Optional primary key to specify the primary key field on the collection
* objects. Defaults to "_id".
* @returns {Collection}
*/
'string, string': function (collectionName, primaryKey) {
return this.$main.call(this, {
name: collectionName,
primaryKey: primaryKey
});
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @param {String} collectionName The name of the collection.
* @param {Object} options An options object.
* @returns {Collection}
*/
'string, object': function (collectionName, options) {
options.name = collectionName;
return this.$main.call(this, options);
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @param {String} collectionName The name of the collection.
* @param {String} primaryKey Optional primary key to specify the primary key field on the collection
* objects. Defaults to "_id".
* @param {Object} options An options object.
* @returns {Collection}
*/
'string, string, object': function (collectionName, primaryKey, options) {
options.name = collectionName;
options.primaryKey = primaryKey;
return this.$main.call(this, options);
},
/**
* The main handler method. This get's called by all the other variants and
* handles the actual logic of the overloaded method.
* @param {Object} options An options object.
* @returns {*}
*/
'$main': function (options) {
var name = options.name;
if (name) {
if (!this._collection[name]) {
if (options && options.autoCreate === false) {
if (options && options.throwError !== false) {
throw('ForerunnerDB.Db "' + this.name() + '": Cannot get collection ' + name + ' because it does not exist and auto-create has been disabled!');
}
}
if (this.debug()) {
console.log('Creating collection ' + name);
}
}
this._collection[name] = this._collection[name] || new Collection(name).db(this);
if (options.primaryKey !== undefined) {
this._collection[name].primaryKey(options.primaryKey);
}
return this._collection[name];
} else {
if (!options || (options && options.throwError !== false)) {
throw('ForerunnerDB.Db "' + this.name() + '": Cannot get collection with undefined name!');
}
}
}
});
/**
* Determine if a collection with the passed name already exists.
* @param {String} viewName The name of the collection to check for.
* @returns {boolean}
*/
Db.prototype.collectionExists = function (viewName) {
return Boolean(this._collection[viewName]);
};
/**
* Returns an array of collections the DB currently has.
* @param {String|RegExp=} search The optional search string or regular expression to use
* to match collection names against.
* @returns {Array} An array of objects containing details of each collection
* the database is currently managing.
*/
Db.prototype.collections = function (search) {
var arr = [],
i;
if (search) {
if (!(search instanceof RegExp)) {
// Turn the search into a regular expression
search = new RegExp(search);
}
}
for (i in this._collection) {
if (this._collection.hasOwnProperty(i)) {
if (search) {
if (search.exec(i)) {
arr.push({
name: i,
count: this._collection[i].count()
});
}
} else {
arr.push({
name: i,
count: this._collection[i].count()
});
}
}
}
arr.sort(function (a, b) {
return a.name.localeCompare(b.name);
});
return arr;
};
Shared.finishModule('Collection');
module.exports = Collection;
},{"./Crc":6,"./IndexBinaryTree":8,"./IndexHashMap":9,"./KeyValueStore":10,"./Metrics":11,"./Overload":22,"./Path":23,"./ReactorIO":24,"./Shared":25}],4:[function(_dereq_,module,exports){
"use strict";
// Import external names locally
var Shared,
Db,
DbInit,
Collection;
Shared = _dereq_('./Shared');
var CollectionGroup = function () {
this.init.apply(this, arguments);
};
CollectionGroup.prototype.init = function (name) {
var self = this;
self._name = name;
self._data = new Collection('__FDB__cg_data_' + self._name);
self._collections = [];
self._view = [];
};
Shared.addModule('CollectionGroup', CollectionGroup);
Shared.mixin(CollectionGroup.prototype, 'Mixin.Common');
Shared.mixin(CollectionGroup.prototype, 'Mixin.ChainReactor');
Shared.mixin(CollectionGroup.prototype, 'Mixin.Constants');
Shared.mixin(CollectionGroup.prototype, 'Mixin.Triggers');
Collection = _dereq_('./Collection');
Db = Shared.modules.Db;
DbInit = Shared.modules.Db.prototype.init;
CollectionGroup.prototype.on = function () {
this._data.on.apply(this._data, arguments);
};
CollectionGroup.prototype.off = function () {
this._data.off.apply(this._data, arguments);
};
CollectionGroup.prototype.emit = function () {
this._data.emit.apply(this._data, arguments);
};
/**
* Gets / sets the primary key for this collection group.
* @param {String=} keyName The name of the primary key.
* @returns {*}
*/
CollectionGroup.prototype.primaryKey = function (keyName) {
if (keyName !== undefined) {
this._primaryKey = keyName;
return this;
}
return this._primaryKey;
};
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(CollectionGroup.prototype, 'state');
/**
* Gets / sets the db instance the collection group belongs to.
* @param {Db=} db The db instance.
* @returns {*}
*/
Shared.synthesize(CollectionGroup.prototype, 'db');
CollectionGroup.prototype.addCollection = function (collection) {
if (collection) {
if (this._collections.indexOf(collection) === -1) {
//var self = this;
// Check for compatible primary keys
if (this._collections.length) {
if (this._primaryKey !== collection.primaryKey()) {
throw('ForerunnerDB.CollectionGroup "' + this.name() + '": All collections in a collection group must have the same primary key!');
}
} else {
// Set the primary key to the first collection added
this.primaryKey(collection.primaryKey());
}
// Add the collection
this._collections.push(collection);
collection._groups = collection._groups || [];
collection._groups.push(this);
collection.chain(this);
// Hook the collection's drop event to destroy group data
collection.on('drop', function () {
// Remove collection from any group associations
if (collection._groups && collection._groups.length) {
var groupArr = [],
i;
// Copy the group array because if we call removeCollection on a group
// it will alter the groups array of this collection mid-loop!
for (i = 0; i < collection._groups.length; i++) {
groupArr.push(collection._groups[i]);
}
// Loop any groups we are part of and remove ourselves from them
for (i = 0; i < groupArr.length; i++) {
collection._groups[i].removeCollection(collection);
}
}
delete collection._groups;
});
// Add collection's data
this._data.insert(collection.find());
}
}
return this;
};
CollectionGroup.prototype.removeCollection = function (collection) {
if (collection) {
var collectionIndex = this._collections.indexOf(collection),
groupIndex;
if (collectionIndex !== -1) {
collection.unChain(this);
this._collections.splice(collectionIndex, 1);
collection._groups = collection._groups || [];
groupIndex = collection._groups.indexOf(this);
if (groupIndex !== -1) {
collection._groups.splice(groupIndex, 1);
}
collection.off('drop');
}
if (this._collections.length === 0) {
// Wipe the primary key
delete this._primaryKey;
}
}
return this;
};
CollectionGroup.prototype._chainHandler = function (chainPacket) {
//sender = chainPacket.sender;
switch (chainPacket.type) {
case 'setData':
// Decouple the data to ensure we are working with our own copy
chainPacket.data = this.decouple(chainPacket.data);
// Remove old data
this._data.remove(chainPacket.options.oldData);
// Add new data
this._data.insert(chainPacket.data);
break;
case 'insert':
// Decouple the data to ensure we are working with our own copy
chainPacket.data = this.decouple(chainPacket.data);
// Add new data
this._data.insert(chainPacket.data);
break;
case 'update':
// Update data
this._data.update(chainPacket.data.query, chainPacket.data.update, chainPacket.options);
break;
case 'remove':
this._data.remove(chainPacket.data.query, chainPacket.options);
break;
default:
break;
}
};
CollectionGroup.prototype.insert = function () {
this._collectionsRun('insert', arguments);
};
CollectionGroup.prototype.update = function () {
this._collectionsRun('update', arguments);
};
CollectionGroup.prototype.updateById = function () {
this._collectionsRun('updateById', arguments);
};
CollectionGroup.prototype.remove = function () {
this._collectionsRun('remove', arguments);
};
CollectionGroup.prototype._collectionsRun = function (type, args) {
for (var i = 0; i < this._collections.length; i++) {
this._collections[i][type].apply(this._collections[i], args);
}
};
CollectionGroup.prototype.find = function (query, options) {
return this._data.find(query, options);
};
/**
* Helper method that removes a document that matches the given id.
* @param {String} id The id of the document to remove.
*/
CollectionGroup.prototype.removeById = function (id) {
// Loop the collections in this group and apply the remove
for (var i = 0; i < this._collections.length; i++) {
this._collections[i].removeById(id);
}
};
/**
* Uses the passed query to generate a new collection with results
* matching the query parameters.
*
* @param query
* @param options
* @returns {*}
*/
CollectionGroup.prototype.subset = function (query, options) {
var result = this.find(query, options);
return new Collection()
._subsetOf(this)
.primaryKey(this._primaryKey)
.setData(result);
};
/**
* Drops a collection group from the database.
* @returns {boolean} True on success, false on failure.
*/
CollectionGroup.prototype.drop = function () {
if (this._state !== 'dropped') {
var i,
collArr,
viewArr;
if (this._debug) {
console.log('Dropping collection group ' + this._name);
}
this._state = 'dropped';
if (this._collections && this._collections.length) {
collArr = [].concat(this._collections);
for (i = 0; i < collArr.length; i++) {
this.removeCollection(collArr[i]);
}
}
if (this._view && this._view.length) {
viewArr = [].concat(this._view);
for (i = 0; i < viewArr.length; i++) {
this._removeView(viewArr[i]);
}
}
this.emit('drop', this);
}
return true;
};
// Extend DB to include collection groups
Db.prototype.init = function () {
this._collectionGroup = {};
DbInit.apply(this, arguments);
};
Db.prototype.collectionGroup = function (collectionGroupName) {
if (collectionGroupName) {
this._collectionGroup[collectionGroupName] = this._collectionGroup[collectionGroupName] || new CollectionGroup(collectionGroupName).db(this);
return this._collectionGroup[collectionGroupName];
} else {
// Return an object of collection data
return this._collectionGroup;
}
};
/**
* Returns an array of collection groups the DB currently has.
* @returns {Array} An array of objects containing details of each collection group
* the database is currently managing.
*/
Db.prototype.collectionGroups = function () {
var arr = [],
i;
for (i in this._collectionGroup) {
if (this._collectionGroup.hasOwnProperty(i)) {
arr.push({
name: i
});
}
}
return arr;
};
module.exports = CollectionGroup;
},{"./Collection":3,"./Shared":25}],5:[function(_dereq_,module,exports){
/*
License
Copyright (c) 2015 Irrelon Software Limited
http://www.irrelon.com
http://www.forerunnerdb.com
Please visit the license page to see latest license information:
http://www.forerunnerdb.com/licensing.html
*/
"use strict";
var Shared,
Db,
Metrics,
Overload;
Shared = _dereq_('./Shared');
Overload = _dereq_('./Overload');
/**
* The main ForerunnerDB core object.
* @constructor
*/
var Core = function (name) {
this.init.apply(this, arguments);
};
Core.prototype.init = function () {
this._db = {};
this._debug = {};
};
Core.prototype.moduleLoaded = new Overload({
/**
* Checks if a module has been loaded into the database.
* @param {String} moduleName The name of the module to check for.
* @returns {Boolean} True if the module is loaded, false if not.
*/
'string': function (moduleName) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
return true;
}
return false;
},
/**
* Checks if a module is loaded and if so calls the passed
* callback method.
* @param {String} moduleName The name of the module to check for.
* @param {Function} callback The callback method to call if module is loaded.
*/
'string, function': function (moduleName, callback) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
callback();
}
},
/**
* Checks if a module is loaded and if so calls the passed
* success method, otherwise calls the failure method.
* @param {String} moduleName The name of the module to check for.
* @param {Function} success The callback method to call if module is loaded.
* @param {Function} failure The callback method to call if module not loaded.
*/
'string, function, function': function (moduleName, success, failure) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
failure();
return false;
}
}
success();
}
}
});
/**
* Checks version against the string passed and if it matches (or partially matches)
* then the callback is called.
* @param {String} val The version to check against.
* @param {Function} callback The callback to call if match is true.
* @returns {Boolean}
*/
Core.prototype.version = function (val, callback) {
if (val !== undefined) {
if (Shared.version.indexOf(val) === 0) {
if (callback) { callback(); }
return true;
}
return false;
}
return Shared.version;
};
// Expose moduleLoaded method to non-instantiated object ForerunnerDB
Core.moduleLoaded = Core.prototype.moduleLoaded;
// Expose version method to non-instantiated object ForerunnerDB
Core.version = Core.prototype.version;
// Provide public access to the Shared object
Core.shared = Shared;
Core.prototype.shared = Shared;
Shared.addModule('Core', Core);
Shared.mixin(Core.prototype, 'Mixin.Common');
Shared.mixin(Core.prototype, 'Mixin.Constants');
Db = _dereq_('./Db.js');
Metrics = _dereq_('./Metrics.js');
Core.prototype._isServer = false;
/**
* Returns true if ForerunnerDB is running on a client browser.
* @returns {boolean}
*/
Core.prototype.isClient = function () {
return !this._isServer;
};
/**
* Returns true if ForerunnerDB is running on a server.
* @returns {boolean}
*/
Core.prototype.isServer = function () {
return this._isServer;
};
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a browser.
*/
Core.prototype.isClient = function () {
return !this._isServer;
};
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a server.
*/
Core.prototype.isServer = function () {
return this._isServer;
};
/**
* Added to provide an error message for users who have not seen
* the new instantiation breaking change warning and try to get
* a collection directly from the core instance.
*/
Core.prototype.collection = function () {
throw("ForerunnerDB's instantiation has changed since version 1.3.36 to support multiple database instances. Please see the readme.md file for the minor change you have to make to get your project back up and running, or see the issue related to this change at https://github.com/Irrelon/ForerunnerDB/issues/44");
};
module.exports = Core;
},{"./Db.js":7,"./Metrics.js":11,"./Overload":22,"./Shared":25}],6:[function(_dereq_,module,exports){
"use strict";
var crcTable = (function () {
var crcTable = [],
c, n, k;
for (n = 0; n < 256; n++) {
c = n;
for (k = 0; k < 8; k++) {
c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); // jshint ignore:line
}
crcTable[n] = c;
}
return crcTable;
}());
module.exports = function(str) {
var crc = 0 ^ (-1), // jshint ignore:line
i;
for (i = 0; i < str.length; i++) {
crc = (crc >>> 8) ^ crcTable[(crc ^ str.charCodeAt(i)) & 0xFF]; // jshint ignore:line
}
return (crc ^ (-1)) >>> 0; // jshint ignore:line
};
},{}],7:[function(_dereq_,module,exports){
/*
License
Copyright (c) 2015 Irrelon Software Limited
http://www.irrelon.com
http://www.forerunnerdb.com
Please visit the license page to see latest license information:
http://www.forerunnerdb.com/licensing.html
*/
"use strict";
var Shared,
Core,
Collection,
Metrics,
Crc,
Overload;
Shared = _dereq_('./Shared');
Overload = _dereq_('./Overload');
/**
* The main ForerunnerDB db object.
* @constructor
*/
var Db = function (name) {
this.init.apply(this, arguments);
};
Db.prototype.init = function (name) {
this._primaryKey = '_id';
this._name = name;
this._collection = {};
this._debug = {};
};
Db.prototype.moduleLoaded = new Overload({
/**
* Checks if a module has been loaded into the database.
* @param {String} moduleName The name of the module to check for.
* @returns {Boolean} True if the module is loaded, false if not.
*/
'string': function (moduleName) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
return true;
}
return false;
},
/**
* Checks if a module is loaded and if so calls the passed
* callback method.
* @param {String} moduleName The name of the module to check for.
* @param {Function} callback The callback method to call if module is loaded.
*/
'string, function': function (moduleName, callback) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
callback();
}
},
/**
* Checks if a module is loaded and if so calls the passed
* success method, otherwise calls the failure method.
* @param {String} moduleName The name of the module to check for.
* @param {Function} success The callback method to call if module is loaded.
* @param {Function} failure The callback method to call if module not loaded.
*/
'string, function, function': function (moduleName, success, failure) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
failure();
return false;
}
}
success();
}
}
});
/**
* Checks version against the string passed and if it matches (or partially matches)
* then the callback is called.
* @param {String} val The version to check against.
* @param {Function} callback The callback to call if match is true.
* @returns {Boolean}
*/
Db.prototype.version = function (val, callback) {
if (val !== undefined) {
if (Shared.version.indexOf(val) === 0) {
if (callback) { callback(); }
return true;
}
return false;
}
return Shared.version;
};
// Expose moduleLoaded method to non-instantiated object ForerunnerDB
Db.moduleLoaded = Db.prototype.moduleLoaded;
// Expose version method to non-instantiated object ForerunnerDB
Db.version = Db.prototype.version;
// Provide public access to the Shared object
Db.shared = Shared;
Db.prototype.shared = Shared;
Shared.addModule('Db', Db);
Shared.mixin(Db.prototype, 'Mixin.Common');
Shared.mixin(Db.prototype, 'Mixin.ChainReactor');
Shared.mixin(Db.prototype, 'Mixin.Constants');
Core = Shared.modules.Core;
Collection = _dereq_('./Collection.js');
Metrics = _dereq_('./Metrics.js');
Crc = _dereq_('./Crc.js');
Db.prototype._isServer = false;
/**
* Gets / sets the core object this database belongs to.
*/
Shared.synthesize(Db.prototype, 'core');
/**
* Gets / sets the default primary key for new collections.
* @param {String=} val The name of the primary key to set.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'primaryKey');
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'state');
/**
* Gets / sets the name of the database.
* @param {String=} val The name of the database to set.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'name');
/**
* Returns true if ForerunnerDB is running on a client browser.
* @returns {boolean}
*/
Db.prototype.isClient = function () {
return !this._isServer;
};
/**
* Returns true if ForerunnerDB is running on a server.
* @returns {boolean}
*/
Db.prototype.isServer = function () {
return this._isServer;
};
/**
* Returns a checksum of a string.
* @param {String} string The string to checksum.
* @return {String} The checksum generated.
*/
Db.prototype.crc = Crc;
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a browser.
*/
Db.prototype.isClient = function () {
return !this._isServer;
};
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a server.
*/
Db.prototype.isServer = function () {
return this._isServer;
};
/**
* Converts a normal javascript array of objects into a DB collection.
* @param {Array} arr An array of objects.
* @returns {Collection} A new collection instance with the data set to the
* array passed.
*/
Db.prototype.arrayToCollection = function (arr) {
return new Collection().setData(arr);
};
/**
* Registers an event listener against an event name.
* @param {String} event The name of the event to listen for.
* @param {Function} listener The listener method to call when
* the event is fired.
* @returns {*}
*/
Db.prototype.on = function(event, listener) {
this._listeners = this._listeners || {};
this._listeners[event] = this._listeners[event] || [];
this._listeners[event].push(listener);
return this;
};
/**
* De-registers an event listener from an event name.
* @param {String} event The name of the event to stop listening for.
* @param {Function} listener The listener method passed to on() when
* registering the event listener.
* @returns {*}
*/
Db.prototype.off = function(event, listener) {
if (event in this._listeners) {
var arr = this._listeners[event],
index = arr.indexOf(listener);
if (index > -1) {
arr.splice(index, 1);
}
}
return this;
};
/**
* Emits an event by name with the given data.
* @param {String} event The name of the event to emit.
* @param {*=} data The data to emit with the event.
* @returns {*}
*/
Db.prototype.emit = function(event, data) {
this._listeners = this._listeners || {};
if (event in this._listeners) {
var arr = this._listeners[event],
arrCount = arr.length,
arrIndex;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arr[arrIndex].apply(this, Array.prototype.slice.call(arguments, 1));
}
}
return this;
};
/**
* Find all documents across all collections in the database that match the passed
* string or search object.
* @param search String or search object.
* @returns {Array}
*/
Db.prototype.peek = function (search) {
var i,
coll,
arr = [],
typeOfSearch = typeof search;
// Loop collections
for (i in this._collection) {
if (this._collection.hasOwnProperty(i)) {
coll = this._collection[i];
if (typeOfSearch === 'string') {
arr = arr.concat(coll.peek(search));
} else {
arr = arr.concat(coll.find(search));
}
}
}
return arr;
};
/**
* Find all documents across all collections in the database that match the passed
* string or search object and return them in an object where each key is the name
* of the collection that the document was matched in.
* @param search String or search object.
* @returns {object}
*/
Db.prototype.peekCat = function (search) {
var i,
coll,
cat = {},
arr,
typeOfSearch = typeof search;
// Loop collections
for (i in this._collection) {
if (this._collection.hasOwnProperty(i)) {
coll = this._collection[i];
if (typeOfSearch === 'string') {
arr = coll.peek(search);
if (arr && arr.length) {
cat[coll.name()] = arr;
}
} else {
arr = coll.find(search);
if (arr && arr.length) {
cat[coll.name()] = arr;
}
}
}
}
return cat;
};
Db.prototype.drop = new Overload({
/**
* Drops the database.
*/
'': function () {
if (this._state !== 'dropped') {
var arr = this.collections(),
arrCount = arr.length,
arrIndex;
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop();
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._core._db[this._name];
}
return true;
},
/**
* Drops the database.
* @param {Function} callback Optional callback method.
*/
'function': function (callback) {
if (this._state !== 'dropped') {
var arr = this.collections(),
arrCount = arr.length,
arrIndex,
finishCount = 0,
afterDrop = function () {
finishCount++;
if (finishCount === arrCount) {
if (callback) { callback(); }
}
};
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop(afterDrop);
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._core._db[this._name];
}
return true;
},
/**
* Drops the database.
* @param {Boolean} removePersist Drop persistent storage for this database.
*/
'boolean': function (removePersist) {
if (this._state !== 'dropped') {
var arr = this.collections(),
arrCount = arr.length,
arrIndex;
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop(removePersist);
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._core._db[this._name];
}
return true;
},
/**
* Drops the database.
* @param {Boolean} removePersist Drop persistent storage for this database.
* @param {Function} callback Optional callback method.
*/
'boolean, function': function (removePersist, callback) {
if (this._state !== 'dropped') {
var arr = this.collections(),
arrCount = arr.length,
arrIndex,
finishCount = 0,
afterDrop = function () {
finishCount++;
if (finishCount === arrCount) {
if (callback) { callback(); }
}
};
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop(removePersist, afterDrop);
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._core._db[this._name];
}
return true;
}
});
/**
* Gets a database instance by name.
* @param {String=} name Optional name of the database. If none is provided
* a random name is assigned.
* @returns {Db}
*/
Core.prototype.db = function (name) {
if (!name) {
name = this.objectId();
}
this._db[name] = this._db[name] || new Db(name).core(this);
return this._db[name];
};
/**
* Returns an array of databases that ForerunnerDB currently has.
* @param {String|RegExp=} search The optional search string or regular expression to use
* to match collection names against.
* @returns {Array} An array of objects containing details of each database
* that ForerunnerDB is currently managing.
*/
Core.prototype.databases = function (search) {
var arr = [],
i;
if (search) {
if (!(search instanceof RegExp)) {
// Turn the search into a regular expression
search = new RegExp(search);
}
}
for (i in this._db) {
if (this._db.hasOwnProperty(i)) {
if (search) {
if (search.exec(i)) {
arr.push({
name: i,
collectionCount: this._db[i].collections().length
});
}
} else {
arr.push({
name: i,
collectionCount: this._db[i].collections().length
});
}
}
}
arr.sort(function (a, b) {
return a.name.localeCompare(b.name);
});
return arr;
};
module.exports = Db;
},{"./Collection.js":3,"./Crc.js":6,"./Metrics.js":11,"./Overload":22,"./Shared":25}],8:[function(_dereq_,module,exports){
"use strict";
/*
name
id
rebuild
state
match
lookup
*/
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path'),
btree = function () {};
/**
* The index class used to instantiate hash map indexes that the database can
* use to speed up queries on collections and views.
* @constructor
*/
var IndexBinaryTree = function () {
this.init.apply(this, arguments);
};
IndexBinaryTree.prototype.init = function (keys, options, collection) {
this._btree = new (btree.create(2, this.sortAsc))();
this._size = 0;
this._id = this._itemKeyHash(keys, keys);
this.unique(options && options.unique ? options.unique : false);
if (keys !== undefined) {
this.keys(keys);
}
if (collection !== undefined) {
this.collection(collection);
}
this.name(options && options.name ? options.name : this._id);
};
Shared.addModule('IndexBinaryTree', IndexBinaryTree);
Shared.mixin(IndexBinaryTree.prototype, 'Mixin.ChainReactor');
Shared.mixin(IndexBinaryTree.prototype, 'Mixin.Sorting');
IndexBinaryTree.prototype.id = function () {
return this._id;
};
IndexBinaryTree.prototype.state = function () {
return this._state;
};
IndexBinaryTree.prototype.size = function () {
return this._size;
};
Shared.synthesize(IndexBinaryTree.prototype, 'data');
Shared.synthesize(IndexBinaryTree.prototype, 'name');
Shared.synthesize(IndexBinaryTree.prototype, 'collection');
Shared.synthesize(IndexBinaryTree.prototype, 'type');
Shared.synthesize(IndexBinaryTree.prototype, 'unique');
IndexBinaryTree.prototype.keys = function (val) {
if (val !== undefined) {
this._keys = val;
// Count the keys
this._keyCount = (new Path()).parse(this._keys).length;
return this;
}
return this._keys;
};
IndexBinaryTree.prototype.rebuild = function () {
// Do we have a collection?
if (this._collection) {
// Get sorted data
var collection = this._collection.subset({}, {
$decouple: false,
$orderBy: this._keys
}),
collectionData = collection.find(),
dataIndex,
dataCount = collectionData.length;
// Clear the index data for the index
this._btree = new (btree.create(2, this.sortAsc))();
if (this._unique) {
this._uniqueLookup = {};
}
// Loop the collection data
for (dataIndex = 0; dataIndex < dataCount; dataIndex++) {
this.insert(collectionData[dataIndex]);
}
}
this._state = {
name: this._name,
keys: this._keys,
indexSize: this._size,
built: new Date(),
updated: new Date(),
ok: true
};
};
IndexBinaryTree.prototype.insert = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash,
dataItemHash = this._itemKeyHash(dataItem, this._keys),
keyArr;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
this._uniqueLookup[uniqueHash] = dataItem;
}
// We store multiple items that match a key inside an array
// that is then stored against that key in the tree...
// Check if item exists for this key already
keyArr = this._btree.get(dataItemHash);
// Check if the array exists
if (keyArr === undefined) {
// Generate an array for this key first
keyArr = [];
// Put the new array into the tree under the key
this._btree.put(dataItemHash, keyArr);
}
// Push the item into the array
keyArr.push(dataItem);
this._size++;
};
IndexBinaryTree.prototype.remove = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash,
dataItemHash = this._itemKeyHash(dataItem, this._keys),
keyArr,
itemIndex;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
delete this._uniqueLookup[uniqueHash];
}
// Try and get the array for the item hash key
keyArr = this._btree.get(dataItemHash);
if (keyArr !== undefined) {
// The key array exits, remove the item from the key array
itemIndex = keyArr.indexOf(dataItem);
if (itemIndex > -1) {
// Check the length of the array
if (keyArr.length === 1) {
// This item is the last in the array, just kill the tree entry
this._btree.del(dataItemHash);
} else {
// Remove the item
keyArr.splice(itemIndex, 1);
}
this._size--;
}
}
};
IndexBinaryTree.prototype.violation = function (dataItem) {
// Generate item hash
var uniqueHash = this._itemHash(dataItem, this._keys);
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexBinaryTree.prototype.hashViolation = function (uniqueHash) {
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexBinaryTree.prototype.lookup = function (query) {
return this._data[this._itemHash(query, this._keys)] || [];
};
IndexBinaryTree.prototype.match = function (query, options) {
// Check if the passed query has data in the keys our index
// operates on and if so, is the query sort matching our order
var pathSolver = new Path();
var indexKeyArr = pathSolver.parseArr(this._keys),
queryArr = pathSolver.parseArr(query),
matchedKeys = [],
matchedKeyCount = 0,
i;
// Loop the query array and check the order of keys against the
// index key array to see if this index can be used
for (i = 0; i < indexKeyArr.length; i++) {
if (queryArr[i] === indexKeyArr[i]) {
matchedKeyCount++;
matchedKeys.push(queryArr[i]);
} else {
// Query match failed - this is a hash map index so partial key match won't work
return {
matchedKeys: [],
totalKeyCount: queryArr.length,
score: 0
};
}
}
return {
matchedKeys: matchedKeys,
totalKeyCount: queryArr.length,
score: matchedKeyCount
};
//return pathSolver.countObjectPaths(this._keys, query);
};
IndexBinaryTree.prototype._itemHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.value(item, pathData[k].path).join(':');
}
return hash;
};
IndexBinaryTree.prototype._itemKeyHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.keyValue(item, pathData[k].path);
}
return hash;
};
IndexBinaryTree.prototype._itemHashArr = function (item, keys) {
var path = new Path(),
pathData,
//hash = '',
hashArr = [],
valArr,
i, k, j;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
valArr = path.value(item, pathData[k].path);
for (i = 0; i < valArr.length; i++) {
if (k === 0) {
// Setup the initial hash array
hashArr.push(valArr[i]);
} else {
// Loop the hash array and concat the value to it
for (j = 0; j < hashArr.length; j++) {
hashArr[j] = hashArr[j] + '_' + valArr[i];
}
}
}
}
return hashArr;
};
Shared.finishModule('IndexBinaryTree');
module.exports = IndexBinaryTree;
},{"./Path":23,"./Shared":25}],9:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path');
/**
* The index class used to instantiate hash map indexes that the database can
* use to speed up queries on collections and views.
* @constructor
*/
var IndexHashMap = function () {
this.init.apply(this, arguments);
};
IndexHashMap.prototype.init = function (keys, options, collection) {
this._crossRef = {};
this._size = 0;
this._id = this._itemKeyHash(keys, keys);
this.data({});
this.unique(options && options.unique ? options.unique : false);
if (keys !== undefined) {
this.keys(keys);
}
if (collection !== undefined) {
this.collection(collection);
}
this.name(options && options.name ? options.name : this._id);
};
Shared.addModule('IndexHashMap', IndexHashMap);
Shared.mixin(IndexHashMap.prototype, 'Mixin.ChainReactor');
IndexHashMap.prototype.id = function () {
return this._id;
};
IndexHashMap.prototype.state = function () {
return this._state;
};
IndexHashMap.prototype.size = function () {
return this._size;
};
Shared.synthesize(IndexHashMap.prototype, 'data');
Shared.synthesize(IndexHashMap.prototype, 'name');
Shared.synthesize(IndexHashMap.prototype, 'collection');
Shared.synthesize(IndexHashMap.prototype, 'type');
Shared.synthesize(IndexHashMap.prototype, 'unique');
IndexHashMap.prototype.keys = function (val) {
if (val !== undefined) {
this._keys = val;
// Count the keys
this._keyCount = (new Path()).parse(this._keys).length;
return this;
}
return this._keys;
};
IndexHashMap.prototype.rebuild = function () {
// Do we have a collection?
if (this._collection) {
// Get sorted data
var collection = this._collection.subset({}, {
$decouple: false,
$orderBy: this._keys
}),
collectionData = collection.find(),
dataIndex,
dataCount = collectionData.length;
// Clear the index data for the index
this._data = {};
if (this._unique) {
this._uniqueLookup = {};
}
// Loop the collection data
for (dataIndex = 0; dataIndex < dataCount; dataIndex++) {
this.insert(collectionData[dataIndex]);
}
}
this._state = {
name: this._name,
keys: this._keys,
indexSize: this._size,
built: new Date(),
updated: new Date(),
ok: true
};
};
IndexHashMap.prototype.insert = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash,
itemHashArr,
hashIndex;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
this._uniqueLookup[uniqueHash] = dataItem;
}
// Generate item hash
itemHashArr = this._itemHashArr(dataItem, this._keys);
// Get the path search results and store them
for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) {
this.pushToPathValue(itemHashArr[hashIndex], dataItem);
}
};
IndexHashMap.prototype.remove = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash,
itemHashArr,
hashIndex;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
delete this._uniqueLookup[uniqueHash];
}
// Generate item hash
itemHashArr = this._itemHashArr(dataItem, this._keys);
// Get the path search results and store them
for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) {
this.pullFromPathValue(itemHashArr[hashIndex], dataItem);
}
};
IndexHashMap.prototype.violation = function (dataItem) {
// Generate item hash
var uniqueHash = this._itemHash(dataItem, this._keys);
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexHashMap.prototype.hashViolation = function (uniqueHash) {
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexHashMap.prototype.pushToPathValue = function (hash, obj) {
var pathValArr = this._data[hash] = this._data[hash] || [];
// Make sure we have not already indexed this object at this path/value
if (pathValArr.indexOf(obj) === -1) {
// Index the object
pathValArr.push(obj);
// Record the reference to this object in our index size
this._size++;
// Cross-reference this association for later lookup
this.pushToCrossRef(obj, pathValArr);
}
};
IndexHashMap.prototype.pullFromPathValue = function (hash, obj) {
var pathValArr = this._data[hash],
indexOfObject;
// Make sure we have already indexed this object at this path/value
indexOfObject = pathValArr.indexOf(obj);
if (indexOfObject > -1) {
// Un-index the object
pathValArr.splice(indexOfObject, 1);
// Record the reference to this object in our index size
this._size--;
// Remove object cross-reference
this.pullFromCrossRef(obj, pathValArr);
}
// Check if we should remove the path value array
if (!pathValArr.length) {
// Remove the array
delete this._data[hash];
}
};
IndexHashMap.prototype.pull = function (obj) {
// Get all places the object has been used and remove them
var id = obj[this._collection.primaryKey()],
crossRefArr = this._crossRef[id],
arrIndex,
arrCount = crossRefArr.length,
arrItem;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arrItem = crossRefArr[arrIndex];
// Remove item from this index lookup array
this._pullFromArray(arrItem, obj);
}
// Record the reference to this object in our index size
this._size--;
// Now remove the cross-reference entry for this object
delete this._crossRef[id];
};
IndexHashMap.prototype._pullFromArray = function (arr, obj) {
var arrCount = arr.length;
while (arrCount--) {
if (arr[arrCount] === obj) {
arr.splice(arrCount, 1);
}
}
};
IndexHashMap.prototype.pushToCrossRef = function (obj, pathValArr) {
var id = obj[this._collection.primaryKey()],
crObj;
this._crossRef[id] = this._crossRef[id] || [];
// Check if the cross-reference to the pathVal array already exists
crObj = this._crossRef[id];
if (crObj.indexOf(pathValArr) === -1) {
// Add the cross-reference
crObj.push(pathValArr);
}
};
IndexHashMap.prototype.pullFromCrossRef = function (obj, pathValArr) {
var id = obj[this._collection.primaryKey()];
delete this._crossRef[id];
};
IndexHashMap.prototype.lookup = function (query) {
return this._data[this._itemHash(query, this._keys)] || [];
};
IndexHashMap.prototype.match = function (query, options) {
// Check if the passed query has data in the keys our index
// operates on and if so, is the query sort matching our order
var pathSolver = new Path();
var indexKeyArr = pathSolver.parseArr(this._keys),
queryArr = pathSolver.parseArr(query),
matchedKeys = [],
matchedKeyCount = 0,
i;
// Loop the query array and check the order of keys against the
// index key array to see if this index can be used
for (i = 0; i < indexKeyArr.length; i++) {
if (queryArr[i] === indexKeyArr[i]) {
matchedKeyCount++;
matchedKeys.push(queryArr[i]);
} else {
// Query match failed - this is a hash map index so partial key match won't work
return {
matchedKeys: [],
totalKeyCount: queryArr.length,
score: 0
};
}
}
return {
matchedKeys: matchedKeys,
totalKeyCount: queryArr.length,
score: matchedKeyCount
};
//return pathSolver.countObjectPaths(this._keys, query);
};
IndexHashMap.prototype._itemHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.value(item, pathData[k].path).join(':');
}
return hash;
};
IndexHashMap.prototype._itemKeyHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.keyValue(item, pathData[k].path);
}
return hash;
};
IndexHashMap.prototype._itemHashArr = function (item, keys) {
var path = new Path(),
pathData,
//hash = '',
hashArr = [],
valArr,
i, k, j;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
valArr = path.value(item, pathData[k].path);
for (i = 0; i < valArr.length; i++) {
if (k === 0) {
// Setup the initial hash array
hashArr.push(valArr[i]);
} else {
// Loop the hash array and concat the value to it
for (j = 0; j < hashArr.length; j++) {
hashArr[j] = hashArr[j] + '_' + valArr[i];
}
}
}
}
return hashArr;
};
Shared.finishModule('IndexHashMap');
module.exports = IndexHashMap;
},{"./Path":23,"./Shared":25}],10:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared');
/**
* The key value store class used when storing basic in-memory KV data,
* and can be queried for quick retrieval. Mostly used for collection
* primary key indexes and lookups.
* @param {String=} name Optional KV store name.
* @constructor
*/
var KeyValueStore = function (name) {
this.init.apply(this, arguments);
};
KeyValueStore.prototype.init = function (name) {
this._name = name;
this._data = {};
this._primaryKey = '_id';
};
Shared.addModule('KeyValueStore', KeyValueStore);
Shared.mixin(KeyValueStore.prototype, 'Mixin.ChainReactor');
/**
* Get / set the name of the key/value store.
* @param {String} val The name to set.
* @returns {*}
*/
Shared.synthesize(KeyValueStore.prototype, 'name');
/**
* Get / set the primary key.
* @param {String} key The key to set.
* @returns {*}
*/
KeyValueStore.prototype.primaryKey = function (key) {
if (key !== undefined) {
this._primaryKey = key;
return this;
}
return this._primaryKey;
};
/**
* Removes all data from the store.
* @returns {*}
*/
KeyValueStore.prototype.truncate = function () {
this._data = {};
return this;
};
/**
* Sets data against a key in the store.
* @param {String} key The key to set data for.
* @param {*} value The value to assign to the key.
* @returns {*}
*/
KeyValueStore.prototype.set = function (key, value) {
this._data[key] = value ? value : true;
return this;
};
/**
* Gets data stored for the passed key.
* @param {String} key The key to get data for.
* @returns {*}
*/
KeyValueStore.prototype.get = function (key) {
return this._data[key];
};
/**
* Get / set the primary key.
* @param {*} obj A lookup query, can be a string key, an array of string keys,
* an object with further query clauses or a regular expression that should be
* run against all keys.
* @returns {*}
*/
KeyValueStore.prototype.lookup = function (obj) {
var pKeyVal = obj[this._primaryKey],
arrIndex,
arrCount,
lookupItem,
result;
if (pKeyVal instanceof Array) {
// An array of primary keys, find all matches
arrCount = pKeyVal.length;
result = [];
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
lookupItem = this._data[pKeyVal[arrIndex]];
if (lookupItem) {
result.push(lookupItem);
}
}
return result;
} else if (pKeyVal instanceof RegExp) {
// Create new data
result = [];
for (arrIndex in this._data) {
if (this._data.hasOwnProperty(arrIndex)) {
if (pKeyVal.test(arrIndex)) {
result.push(this._data[arrIndex]);
}
}
}
return result;
} else if (typeof pKeyVal === 'object') {
// The primary key clause is an object, now we have to do some
// more extensive searching
if (pKeyVal.$ne) {
// Create new data
result = [];
for (arrIndex in this._data) {
if (this._data.hasOwnProperty(arrIndex)) {
if (arrIndex !== pKeyVal.$ne) {
result.push(this._data[arrIndex]);
}
}
}
return result;
}
if (pKeyVal.$in && (pKeyVal.$in instanceof Array)) {
// Create new data
result = [];
for (arrIndex in this._data) {
if (this._data.hasOwnProperty(arrIndex)) {
if (pKeyVal.$in.indexOf(arrIndex) > -1) {
result.push(this._data[arrIndex]);
}
}
}
return result;
}
if (pKeyVal.$nin && (pKeyVal.$nin instanceof Array)) {
// Create new data
result = [];
for (arrIndex in this._data) {
if (this._data.hasOwnProperty(arrIndex)) {
if (pKeyVal.$nin.indexOf(arrIndex) === -1) {
result.push(this._data[arrIndex]);
}
}
}
return result;
}
if (pKeyVal.$or && (pKeyVal.$or instanceof Array)) {
// Create new data
result = [];
for (arrIndex = 0; arrIndex < pKeyVal.$or.length; arrIndex++) {
result = result.concat(this.lookup(pKeyVal.$or[arrIndex]));
}
return result;
}
} else {
// Key is a basic lookup from string
lookupItem = this._data[pKeyVal];
if (lookupItem !== undefined) {
return [lookupItem];
} else {
return [];
}
}
};
/**
* Removes data for the given key from the store.
* @param {String} key The key to un-set.
* @returns {*}
*/
KeyValueStore.prototype.unSet = function (key) {
delete this._data[key];
return this;
};
/**
* Sets data for the give key in the store only where the given key
* does not already have a value in the store.
* @param {String} key The key to set data for.
* @param {*} value The value to assign to the key.
* @returns {Boolean} True if data was set or false if data already
* exists for the key.
*/
KeyValueStore.prototype.uniqueSet = function (key, value) {
if (this._data[key] === undefined) {
this._data[key] = value;
return true;
}
return false;
};
Shared.finishModule('KeyValueStore');
module.exports = KeyValueStore;
},{"./Shared":25}],11:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Operation = _dereq_('./Operation');
/**
* The metrics class used to store details about operations.
* @constructor
*/
var Metrics = function () {
this.init.apply(this, arguments);
};
Metrics.prototype.init = function () {
this._data = [];
};
Shared.addModule('Metrics', Metrics);
Shared.mixin(Metrics.prototype, 'Mixin.ChainReactor');
/**
* Creates an operation within the metrics instance and if metrics
* are currently enabled (by calling the start() method) the operation
* is also stored in the metrics log.
* @param {String} name The name of the operation.
* @returns {Operation}
*/
Metrics.prototype.create = function (name) {
var op = new Operation(name);
if (this._enabled) {
this._data.push(op);
}
return op;
};
/**
* Starts logging operations.
* @returns {Metrics}
*/
Metrics.prototype.start = function () {
this._enabled = true;
return this;
};
/**
* Stops logging operations.
* @returns {Metrics}
*/
Metrics.prototype.stop = function () {
this._enabled = false;
return this;
};
/**
* Clears all logged operations.
* @returns {Metrics}
*/
Metrics.prototype.clear = function () {
this._data = [];
return this;
};
/**
* Returns an array of all logged operations.
* @returns {Array}
*/
Metrics.prototype.list = function () {
return this._data;
};
Shared.finishModule('Metrics');
module.exports = Metrics;
},{"./Operation":21,"./Shared":25}],12:[function(_dereq_,module,exports){
"use strict";
var CRUD = {
preSetData: function () {
},
postSetData: function () {
}
};
module.exports = CRUD;
},{}],13:[function(_dereq_,module,exports){
"use strict";
// TODO: Document the methods in this mixin
var ChainReactor = {
chain: function (obj) {
this._chain = this._chain || [];
var index = this._chain.indexOf(obj);
if (index === -1) {
this._chain.push(obj);
}
},
unChain: function (obj) {
if (this._chain) {
var index = this._chain.indexOf(obj);
if (index > -1) {
this._chain.splice(index, 1);
}
}
},
chainSend: function (type, data, options) {
if (this._chain) {
var arr = this._chain,
count = arr.length,
index;
for (index = 0; index < count; index++) {
arr[index].chainReceive(this, type, data, options);
}
}
},
chainReceive: function (sender, type, data, options) {
var chainPacket = {
sender: sender,
type: type,
data: data,
options: options
};
// Fire our internal handler
if (!this._chainHandler || (this._chainHandler && !this._chainHandler(chainPacket))) {
// Propagate the message down the chain
this.chainSend(chainPacket.type, chainPacket.data, chainPacket.options);
}
}
};
module.exports = ChainReactor;
},{}],14:[function(_dereq_,module,exports){
"use strict";
var idCounter = 0,
Overload = _dereq_('./Overload'),
Common;
Common = {
/**
* Gets / sets data in the item store. The store can be used to set and
* retrieve data against a key. Useful for adding arbitrary key/value data
* to a collection / view etc and retrieving it later.
* @param {String|*} key The key under which to store the passed value or
* retrieve the existing stored value.
* @param {*=} val Optional value. If passed will overwrite the existing value
* stored against the specified key if one currently exists.
* @returns {*}
*/
store: function (key, val) {
if (key !== undefined) {
if (val !== undefined) {
// Store the data
this._store = this._store || {};
this._store[key] = val;
return this;
}
if (this._store) {
return this._store[key];
}
}
return undefined;
},
/**
* Removes a previously stored key/value pair from the item store, set previously
* by using the store() method.
* @param {String|*} key The key of the key/value pair to remove;
* @returns {Common} Returns this for chaining.
*/
unStore: function (key) {
if (key !== undefined) {
delete this._store[key];
}
return this;
},
/**
* Returns a non-referenced version of the passed object / array.
* @param {Object} data The object or array to return as a non-referenced version.
* @param {Number=} copies Optional number of copies to produce. If specified, the return
* value will be an array of decoupled objects, each distinct from the other.
* @returns {*}
*/
decouple: function (data, copies) {
if (data !== undefined) {
if (!copies) {
return JSON.parse(JSON.stringify(data));
} else {
var i,
json = JSON.stringify(data),
copyArr = [];
for (i = 0; i < copies; i++) {
copyArr.push(JSON.parse(json));
}
return copyArr;
}
}
return undefined;
},
/**
* Generates a new 16-character hexadecimal unique ID or
* generates a new 16-character hexadecimal ID based on
* the passed string. Will always generate the same ID
* for the same string.
* @param {String=} str A string to generate the ID from.
* @return {String}
*/
objectId: function (str) {
var id,
pow = Math.pow(10, 17);
if (!str) {
idCounter++;
id = (idCounter + (
Math.random() * pow +
Math.random() * pow +
Math.random() * pow +
Math.random() * pow
)).toString(16);
} else {
var val = 0,
count = str.length,
i;
for (i = 0; i < count; i++) {
val += str.charCodeAt(i) * pow;
}
id = val.toString(16);
}
return id;
},
/**
* Gets / sets debug flag that can enable debug message output to the
* console if required.
* @param {Boolean} val The value to set debug flag to.
* @return {Boolean} True if enabled, false otherwise.
*/
/**
* Sets debug flag for a particular type that can enable debug message
* output to the console if required.
* @param {String} type The name of the debug type to set flag for.
* @param {Boolean} val The value to set debug flag to.
* @return {Boolean} True if enabled, false otherwise.
*/
debug: new Overload([
function () {
return this._debug && this._debug.all;
},
function (val) {
if (val !== undefined) {
if (typeof val === 'boolean') {
this._debug = this._debug || {};
this._debug.all = val;
this.chainSend('debug', this._debug);
return this;
} else {
return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[val]) || (this._debug && this._debug.all);
}
}
return this._debug && this._debug.all;
},
function (type, val) {
if (type !== undefined) {
if (val !== undefined) {
this._debug = this._debug || {};
this._debug[type] = val;
this.chainSend('debug', this._debug);
return this;
}
return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[type]);
}
return this._debug && this._debug.all;
}
])
};
module.exports = Common;
},{"./Overload":22}],15:[function(_dereq_,module,exports){
"use strict";
var Constants = {
TYPE_INSERT: 0,
TYPE_UPDATE: 1,
TYPE_REMOVE: 2,
PHASE_BEFORE: 0,
PHASE_AFTER: 1
};
module.exports = Constants;
},{}],16:[function(_dereq_,module,exports){
"use strict";
var Overload = _dereq_('./Overload');
var Events = {
on: new Overload({
/**
* Attach an event listener to the passed event.
* @param {String} event The name of the event to listen for.
* @param {Function} listener The method to call when the event is fired.
*/
'string, function': function (event, listener) {
this._listeners = this._listeners || {};
this._listeners[event] = this._listeners[event] || {};
this._listeners[event]['*'] = this._listeners[event]['*'] || [];
this._listeners[event]['*'].push(listener);
return this;
},
/**
* Attach an event listener to the passed event only if the passed
* id matches the document id for the event being fired.
* @param {String} event The name of the event to listen for.
* @param {*} id The document id to match against.
* @param {Function} listener The method to call when the event is fired.
*/
'string, *, function': function (event, id, listener) {
this._listeners = this._listeners || {};
this._listeners[event] = this._listeners[event] || {};
this._listeners[event][id] = this._listeners[event][id] || [];
this._listeners[event][id].push(listener);
return this;
}
}),
off: new Overload({
'string': function (event) {
if (this._listeners && this._listeners[event] && event in this._listeners) {
delete this._listeners[event];
}
return this;
},
'string, function': function (event, listener) {
var arr,
index;
if (typeof(listener) === 'string') {
if (this._listeners && this._listeners[event] && this._listeners[event][listener]) {
delete this._listeners[event][listener];
}
} else {
if (this._listeners && event in this._listeners) {
arr = this._listeners[event]['*'];
index = arr.indexOf(listener);
if (index > -1) {
arr.splice(index, 1);
}
}
}
return this;
},
'string, *, function': function (event, id, listener) {
if (this._listeners && event in this._listeners && id in this.listeners[event]) {
var arr = this._listeners[event][id],
index = arr.indexOf(listener);
if (index > -1) {
arr.splice(index, 1);
}
}
},
'string, *': function (event, id) {
if (this._listeners && event in this._listeners && id in this._listeners[event]) {
// Kill all listeners for this event id
delete this._listeners[event][id];
}
}
}),
emit: function (event, data) {
this._listeners = this._listeners || {};
if (event in this._listeners) {
var arrIndex,
arrCount;
// Handle global emit
if (this._listeners[event]['*']) {
var arr = this._listeners[event]['*'];
arrCount = arr.length;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arr[arrIndex].apply(this, Array.prototype.slice.call(arguments, 1));
}
}
// Handle individual emit
if (data instanceof Array) {
// Check if the array is an array of objects in the collection
if (data[0] && data[0][this._primaryKey]) {
// Loop the array and check for listeners against the primary key
var listenerIdArr = this._listeners[event],
listenerIdCount,
listenerIdIndex;
arrCount = data.length;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
if (listenerIdArr[data[arrIndex][this._primaryKey]]) {
// Emit for this id
listenerIdCount = listenerIdArr[data[arrIndex][this._primaryKey]].length;
for (listenerIdIndex = 0; listenerIdIndex < listenerIdCount; listenerIdIndex++) {
listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex].apply(this, Array.prototype.slice.call(arguments, 1));
}
}
}
}
}
}
return this;
}
};
module.exports = Events;
},{"./Overload":22}],17:[function(_dereq_,module,exports){
"use strict";
var Matching = {
/**
* Internal method that checks a document against a test object.
* @param {*} source The source object or value to test against.
* @param {*} test The test object or value to test with.
* @param {String=} opToApply The special operation to apply to the test such
* as 'and' or an 'or' operator.
* @param {Object=} options An object containing options to apply to the
* operation such as limiting the fields returned etc.
* @returns {Boolean} True if the test was positive, false on negative.
* @private
*/
_match: function (source, test, opToApply, options) {
// TODO: This method is quite long, break into smaller pieces
var operation,
applyOp,
recurseVal,
tmpIndex,
sourceType = typeof source,
testType = typeof test,
matchedAll = true,
opResult,
substringCache,
i;
options = options || {};
// Check if options currently holds a root query object
if (!options.$rootQuery) {
// Root query not assigned, hold the root query
options.$rootQuery = test;
}
// Check if the comparison data are both strings or numbers
if ((sourceType === 'string' || sourceType === 'number') && (testType === 'string' || testType === 'number')) {
// The source and test data are flat types that do not require recursive searches,
// so just compare them and return the result
if (sourceType === 'number') {
// Number comparison
if (source !== test) {
matchedAll = false;
}
} else {
// String comparison
if (source.localeCompare(test)) {
matchedAll = false;
}
}
} else {
for (i in test) {
if (test.hasOwnProperty(i)) {
// Reset operation flag
operation = false;
substringCache = i.substr(0, 2);
// Check if the property is a comment (ignorable)
if (substringCache === '//') {
// Skip this property
continue;
}
// Check if the property starts with a dollar (function)
if (substringCache.indexOf('$') === 0) {
// Ask the _matchOp method to handle the operation
opResult = this._matchOp(i, source, test[i], options);
// Check the result of the matchOp operation
// If the result is -1 then no operation took place, otherwise the result
// will be a boolean denoting a match (true) or no match (false)
if (opResult > -1) {
if (opResult) {
if (opToApply === 'or') {
return true;
}
} else {
// Set the matchedAll flag to the result of the operation
// because the operation did not return true
matchedAll = opResult;
}
// Record that an operation was handled
operation = true;
}
}
// Check for regex
if (!operation && test[i] instanceof RegExp) {
operation = true;
if (typeof(source) === 'object' && source[i] !== undefined && test[i].test(source[i])) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
}
if (!operation) {
// Check if our query is an object
if (typeof(test[i]) === 'object') {
// Because test[i] is an object, source must also be an object
// Check if our source data we are checking the test query against
// is an object or an array
if (source[i] !== undefined) {
if (source[i] instanceof Array && !(test[i] instanceof Array)) {
// The source data is an array, so check each item until a
// match is found
recurseVal = false;
for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) {
recurseVal = this._match(source[i][tmpIndex], test[i], applyOp, options);
if (recurseVal) {
// One of the array items matched the query so we can
// include this item in the results, so break now
break;
}
}
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else if (!(source[i] instanceof Array) && test[i] instanceof Array) {
// The test key data is an array and the source key data is not so check
// each item in the test key data to see if the source item matches one
// of them. This is effectively an $in search.
recurseVal = false;
for (tmpIndex = 0; tmpIndex < test[i].length; tmpIndex++) {
recurseVal = this._match(source[i], test[i][tmpIndex], applyOp, options);
if (recurseVal) {
// One of the array items matched the query so we can
// include this item in the results, so break now
break;
}
}
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else if (typeof(source) === 'object') {
// Recurse down the object tree
recurseVal = this._match(source[i], test[i], applyOp, options);
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else {
recurseVal = this._match(undefined, test[i], applyOp, options);
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
}
} else {
// First check if the test match is an $exists
if (test[i] && test[i].$exists !== undefined) {
// Push the item through another match recurse
recurseVal = this._match(undefined, test[i], applyOp, options);
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else {
matchedAll = false;
}
}
} else {
// Check if the prop matches our test value
if (source && source[i] === test[i]) {
if (opToApply === 'or') {
return true;
}
} else if (source && source[i] && source[i] instanceof Array && test[i] && typeof(test[i]) !== "object") {
// We are looking for a value inside an array
// The source data is an array, so check each item until a
// match is found
recurseVal = false;
for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) {
recurseVal = this._match(source[i][tmpIndex], test[i], applyOp, options);
if (recurseVal) {
// One of the array items matched the query so we can
// include this item in the results, so break now
break;
}
}
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else {
matchedAll = false;
}
}
}
if (opToApply === 'and' && !matchedAll) {
return false;
}
}
}
}
return matchedAll;
},
/**
* Internal method, performs a matching process against a query operator such as $gt or $nin.
* @param {String} key The property name in the test that matches the operator to perform
* matching against.
* @param {*} source The source data to match the query against.
* @param {*} test The query to match the source against.
* @param {Object=} options An options object.
* @returns {*}
* @private
*/
_matchOp: function (key, source, test, options) {
// Check for commands
switch (key) {
case '$gt':
// Greater than
return source > test;
case '$gte':
// Greater than or equal
return source >= test;
case '$lt':
// Less than
return source < test;
case '$lte':
// Less than or equal
return source <= test;
case '$exists':
// Property exists
return (source === undefined) !== test;
case '$ne': // Not equals
return source != test; // jshint ignore:line
case '$or':
// Match true on ANY check to pass
for (var orIndex = 0; orIndex < test.length; orIndex++) {
if (this._match(source, test[orIndex], 'and', options)) {
return true;
}
}
return false;
case '$and':
// Match true on ALL checks to pass
for (var andIndex = 0; andIndex < test.length; andIndex++) {
if (!this._match(source, test[andIndex], 'and', options)) {
return false;
}
}
return true;
case '$in': // In
// Check that the in test is an array
if (test instanceof Array) {
var inArr = test,
inArrCount = inArr.length,
inArrIndex;
for (inArrIndex = 0; inArrIndex < inArrCount; inArrIndex++) {
if (inArr[inArrIndex] === source) {
return true;
}
}
return false;
} else {
throw('ForerunnerDB.Mixin.Matching "' + this.name() + '": Cannot use an $in operator on a non-array key: ' + key);
}
break;
case '$nin': // Not in
// Check that the not-in test is an array
if (test instanceof Array) {
var notInArr = test,
notInArrCount = notInArr.length,
notInArrIndex;
for (notInArrIndex = 0; notInArrIndex < notInArrCount; notInArrIndex++) {
if (notInArr[notInArrIndex] === source) {
return false;
}
}
return true;
} else {
throw('ForerunnerDB.Mixin.Matching "' + this.name() + '": Cannot use a $nin operator on a non-array key: ' + key);
}
break;
case '$distinct':
// Ensure options holds a distinct lookup
options.$rootQuery['//distinctLookup'] = options.$rootQuery['//distinctLookup'] || {};
for (var distinctProp in test) {
if (test.hasOwnProperty(distinctProp)) {
options.$rootQuery['//distinctLookup'][distinctProp] = options.$rootQuery['//distinctLookup'][distinctProp] || {};
// Check if the options distinct lookup has this field's value
if (options.$rootQuery['//distinctLookup'][distinctProp][source[distinctProp]]) {
// Value is already in use
return false;
} else {
// Set the value in the lookup
options.$rootQuery['//distinctLookup'][distinctProp][source[distinctProp]] = true;
// Allow the item in the results
return true;
}
}
}
break;
}
return -1;
}
};
module.exports = Matching;
},{}],18:[function(_dereq_,module,exports){
"use strict";
var Sorting = {
/**
* Sorts the passed value a against the passed value b ascending.
* @param {*} a The first value to compare.
* @param {*} b The second value to compare.
* @returns {*} 1 if a is sorted after b, -1 if a is sorted before b.
*/
sortAsc: function (a, b) {
if (typeof(a) === 'string' && typeof(b) === 'string') {
return a.localeCompare(b);
} else {
if (a > b) {
return 1;
} else if (a < b) {
return -1;
}
}
return 0;
},
/**
* Sorts the passed value a against the passed value b descending.
* @param {*} a The first value to compare.
* @param {*} b The second value to compare.
* @returns {*} 1 if a is sorted after b, -1 if a is sorted before b.
*/
sortDesc: function (a, b) {
if (typeof(a) === 'string' && typeof(b) === 'string') {
return b.localeCompare(a);
} else {
if (a > b) {
return -1;
} else if (a < b) {
return 1;
}
}
return 0;
}
};
module.exports = Sorting;
},{}],19:[function(_dereq_,module,exports){
"use strict";
var Overload = _dereq_('./Overload');
var Triggers = {
/**
* Add a trigger by id.
* @param {String} id The id of the trigger. This must be unique to the type and
* phase of the trigger. Only one trigger may be added with this id per type and
* phase.
* @param {Number} type The type of operation to apply the trigger to. See
* Mixin.Constants for constants to use.
* @param {Number} phase The phase of an operation to fire the trigger on. See
* Mixin.Constants for constants to use.
* @param {Function} method The method to call when the trigger is fired.
* @returns {boolean} True if the trigger was added successfully, false if not.
*/
addTrigger: function (id, type, phase, method) {
var self = this,
triggerIndex;
// Check if the trigger already exists
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex === -1) {
// The trigger does not exist, create it
self._trigger = self._trigger || {};
self._trigger[type] = self._trigger[type] || {};
self._trigger[type][phase] = self._trigger[type][phase] || [];
self._trigger[type][phase].push({
id: id,
method: method,
enabled: true
});
return true;
}
return false;
},
/**
*
* @param {String} id The id of the trigger to remove.
* @param {Number} type The type of operation to remove the trigger from. See
* Mixin.Constants for constants to use.
* @param {Number} phase The phase of the operation to remove the trigger from.
* See Mixin.Constants for constants to use.
* @returns {boolean} True if removed successfully, false if not.
*/
removeTrigger: function (id, type, phase) {
var self = this,
triggerIndex;
// Check if the trigger already exists
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex > -1) {
// The trigger exists, remove it
self._trigger[type][phase].splice(triggerIndex, 1);
}
return false;
},
enableTrigger: new Overload({
'string': function (id) {
// Alter all triggers of this type
var self = this,
types = self._trigger,
phases,
triggers,
result = false,
i, k, j;
if (types) {
for (j in types) {
if (types.hasOwnProperty(j)) {
phases = types[j];
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set enabled flag
for (k = 0; k < triggers.length; k++) {
if (triggers[k].id === id) {
triggers[k].enabled = true;
result = true;
}
}
}
}
}
}
}
}
return result;
},
'number': function (type) {
// Alter all triggers of this type
var self = this,
phases = self._trigger[type],
triggers,
result = false,
i, k;
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set to enabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = true;
result = true;
}
}
}
}
return result;
},
'number, number': function (type, phase) {
// Alter all triggers of this type and phase
var self = this,
phases = self._trigger[type],
triggers,
result = false,
k;
if (phases) {
triggers = phases[phase];
if (triggers) {
// Loop triggers and set to enabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = true;
result = true;
}
}
}
return result;
},
'string, number, number': function (id, type, phase) {
// Check if the trigger already exists
var self = this,
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex > -1) {
// Update the trigger
self._trigger[type][phase][triggerIndex].enabled = true;
return true;
}
return false;
}
}),
disableTrigger: new Overload({
'string': function (id) {
// Alter all triggers of this type
var self = this,
types = self._trigger,
phases,
triggers,
result = false,
i, k, j;
if (types) {
for (j in types) {
if (types.hasOwnProperty(j)) {
phases = types[j];
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set enabled flag
for (k = 0; k < triggers.length; k++) {
if (triggers[k].id === id) {
triggers[k].enabled = false;
result = true;
}
}
}
}
}
}
}
}
return result;
},
'number': function (type) {
// Alter all triggers of this type
var self = this,
phases = self._trigger[type],
triggers,
result = false,
i, k;
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set to disabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = false;
result = true;
}
}
}
}
return result;
},
'number, number': function (type, phase) {
// Alter all triggers of this type and phase
var self = this,
phases = self._trigger[type],
triggers,
result = false,
k;
if (phases) {
triggers = phases[phase];
if (triggers) {
// Loop triggers and set to disabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = false;
result = true;
}
}
}
return result;
},
'string, number, number': function (id, type, phase) {
// Check if the trigger already exists
var self = this,
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex > -1) {
// Update the trigger
self._trigger[type][phase][triggerIndex].enabled = false;
return true;
}
return false;
}
}),
/**
* Checks if a trigger will fire based on the type and phase provided.
* @param {Number} type The type of operation. See Mixin.Constants for
* constants to use.
* @param {Number} phase The phase of the operation. See Mixin.Constants
* for constants to use.
* @returns {Boolean} True if the trigger will fire, false otherwise.
*/
willTrigger: function (type, phase) {
if (this._trigger && this._trigger[type] && this._trigger[type][phase] && this._trigger[type][phase].length) {
// Check if a trigger in this array is enabled
var arr = this._trigger[type][phase],
i;
for (i = 0; i < arr.length; i++) {
if (arr[i].enabled) {
return true;
}
}
}
return false;
},
/**
* Processes trigger actions based on the operation, type and phase.
* @param {Object} operation Operation data to pass to the trigger.
* @param {Number} type The type of operation. See Mixin.Constants for
* constants to use.
* @param {Number} phase The phase of the operation. See Mixin.Constants
* for constants to use.
* @param {Object} oldDoc The document snapshot before operations are
* carried out against the data.
* @param {Object} newDoc The document snapshot after operations are
* carried out against the data.
* @returns {boolean}
*/
processTrigger: function (operation, type, phase, oldDoc, newDoc) {
var self = this,
triggerArr,
triggerIndex,
triggerCount,
triggerItem,
response;
if (self._trigger && self._trigger[type] && self._trigger[type][phase]) {
triggerArr = self._trigger[type][phase];
triggerCount = triggerArr.length;
for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) {
triggerItem = triggerArr[triggerIndex];
// Check if the trigger is enabled
if (triggerItem.enabled) {
if (this.debug()) {
var typeName,
phaseName;
switch (type) {
case this.TYPE_INSERT:
typeName = 'insert';
break;
case this.TYPE_UPDATE:
typeName = 'update';
break;
case this.TYPE_REMOVE:
typeName = 'remove';
break;
default:
typeName = '';
break;
}
switch (phase) {
case this.PHASE_BEFORE:
phaseName = 'before';
break;
case this.PHASE_AFTER:
phaseName = 'after';
break;
default:
phaseName = '';
break;
}
//console.log('Triggers: Processing trigger "' + id + '" for ' + typeName + ' in phase "' + phaseName + '"');
}
// Run the trigger's method and store the response
response = triggerItem.method.call(self, operation, oldDoc, newDoc);
// Check the response for a non-expected result (anything other than
// undefined, true or false is considered a throwable error)
if (response === false) {
// The trigger wants us to cancel operations
return false;
}
if (response !== undefined && response !== true && response !== false) {
// Trigger responded with error, throw the error
throw('ForerunnerDB.Mixin.Triggers: Trigger error: ' + response);
}
}
}
// Triggers all ran without issue, return a success (true)
return true;
}
},
/**
* Returns the index of a trigger by id based on type and phase.
* @param {String} id The id of the trigger to find the index of.
* @param {Number} type The type of operation. See Mixin.Constants for
* constants to use.
* @param {Number} phase The phase of the operation. See Mixin.Constants
* for constants to use.
* @returns {number}
* @private
*/
_triggerIndexOf: function (id, type, phase) {
var self = this,
triggerArr,
triggerCount,
triggerIndex;
if (self._trigger && self._trigger[type] && self._trigger[type][phase]) {
triggerArr = self._trigger[type][phase];
triggerCount = triggerArr.length;
for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) {
if (triggerArr[triggerIndex].id === id) {
return triggerIndex;
}
}
}
return -1;
}
};
module.exports = Triggers;
},{"./Overload":22}],20:[function(_dereq_,module,exports){
"use strict";
var Updating = {
/**
* Updates a property on an object.
* @param {Object} doc The object whose property is to be updated.
* @param {String} prop The property to update.
* @param {*} val The new value of the property.
* @private
*/
_updateProperty: function (doc, prop, val) {
doc[prop] = val;
if (this.debug()) {
console.log('ForerunnerDB.Mixin.Updating: Setting non-data-bound document property "' + prop + '" for "' + this.name() + '"');
}
},
/**
* Increments a value for a property on a document by the passed number.
* @param {Object} doc The document to modify.
* @param {String} prop The property to modify.
* @param {Number} val The amount to increment by.
* @private
*/
_updateIncrement: function (doc, prop, val) {
doc[prop] += val;
},
/**
* Changes the index of an item in the passed array.
* @param {Array} arr The array to modify.
* @param {Number} indexFrom The index to move the item from.
* @param {Number} indexTo The index to move the item to.
* @private
*/
_updateSpliceMove: function (arr, indexFrom, indexTo) {
arr.splice(indexTo, 0, arr.splice(indexFrom, 1)[0]);
if (this.debug()) {
console.log('ForerunnerDB.Mixin.Updating: Moving non-data-bound document array index from "' + indexFrom + '" to "' + indexTo + '" for "' + this.name() + '"');
}
},
/**
* Inserts an item into the passed array at the specified index.
* @param {Array} arr The array to insert into.
* @param {Number} index The index to insert at.
* @param {Object} doc The document to insert.
* @private
*/
_updateSplicePush: function (arr, index, doc) {
if (arr.length > index) {
arr.splice(index, 0, doc);
} else {
arr.push(doc);
}
},
/**
* Inserts an item at the end of an array.
* @param {Array} arr The array to insert the item into.
* @param {Object} doc The document to insert.
* @private
*/
_updatePush: function (arr, doc) {
arr.push(doc);
},
/**
* Removes an item from the passed array.
* @param {Array} arr The array to modify.
* @param {Number} index The index of the item in the array to remove.
* @private
*/
_updatePull: function (arr, index) {
arr.splice(index, 1);
},
/**
* Multiplies a value for a property on a document by the passed number.
* @param {Object} doc The document to modify.
* @param {String} prop The property to modify.
* @param {Number} val The amount to multiply by.
* @private
*/
_updateMultiply: function (doc, prop, val) {
doc[prop] *= val;
},
/**
* Renames a property on a document to the passed property.
* @param {Object} doc The document to modify.
* @param {String} prop The property to rename.
* @param {Number} val The new property name.
* @private
*/
_updateRename: function (doc, prop, val) {
doc[val] = doc[prop];
delete doc[prop];
},
/**
* Sets a property on a document to the passed value.
* @param {Object} doc The document to modify.
* @param {String} prop The property to delete.
* @param {*} val The new property value.
* @private
*/
_updateOverwrite: function (doc, prop, val) {
doc[prop] = val;
},
/**
* Deletes a property on a document.
* @param {Object} doc The document to modify.
* @param {String} prop The property to delete.
* @private
*/
_updateUnset: function (doc, prop) {
delete doc[prop];
},
/**
* Removes all properties from an object without destroying
* the object instance, thereby maintaining data-bound linking.
* @param {Object} doc The parent object to modify.
* @param {String} prop The name of the child object to clear.
* @private
*/
_updateClear: function (doc, prop) {
var obj = doc[prop],
i;
if (obj && typeof obj === 'object') {
for (i in obj) {
if (obj.hasOwnProperty(i)) {
this._updateUnset(obj, i);
}
}
}
},
/**
* Pops an item from the array stack.
* @param {Object} doc The document to modify.
* @param {Number=} val Optional, if set to 1 will pop, if set to -1 will shift.
* @return {Boolean}
* @private
*/
_updatePop: function (doc, val) {
var updated = false;
if (doc.length > 0) {
if (val === 1) {
doc.pop();
updated = true;
} else if (val === -1) {
doc.shift();
updated = true;
}
}
return updated;
}
};
module.exports = Updating;
},{}],21:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path');
/**
* The operation class, used to store details about an operation being
* performed by the database.
* @param {String} name The name of the operation.
* @constructor
*/
var Operation = function (name) {
this.pathSolver = new Path();
this.counter = 0;
this.init.apply(this, arguments);
};
Operation.prototype.init = function (name) {
this._data = {
operation: name, // The name of the operation executed such as "find", "update" etc
index: {
potential: [], // Indexes that could have potentially been used
used: false // The index that was picked to use
},
steps: [], // The steps taken to generate the query results,
time: {
startMs: 0,
stopMs: 0,
totalMs: 0,
process: {}
},
flag: {}, // An object with flags that denote certain execution paths
log: [] // Any extra data that might be useful such as warnings or helpful hints
};
};
Shared.addModule('Operation', Operation);
Shared.mixin(Operation.prototype, 'Mixin.ChainReactor');
/**
* Starts the operation timer.
*/
Operation.prototype.start = function () {
this._data.time.startMs = new Date().getTime();
};
/**
* Adds an item to the operation log.
* @param {String} event The item to log.
* @returns {*}
*/
Operation.prototype.log = function (event) {
if (event) {
var lastLogTime = this._log.length > 0 ? this._data.log[this._data.log.length - 1].time : 0,
logObj = {
event: event,
time: new Date().getTime(),
delta: 0
};
this._data.log.push(logObj);
if (lastLogTime) {
logObj.delta = logObj.time - lastLogTime;
}
return this;
}
return this._data.log;
};
/**
* Called when starting and ending a timed operation, used to time
* internal calls within an operation's execution.
* @param {String} section An operation name.
* @returns {*}
*/
Operation.prototype.time = function (section) {
if (section !== undefined) {
var process = this._data.time.process,
processObj = process[section] = process[section] || {};
if (!processObj.startMs) {
// Timer started
processObj.startMs = new Date().getTime();
processObj.stepObj = {
name: section
};
this._data.steps.push(processObj.stepObj);
} else {
processObj.stopMs = new Date().getTime();
processObj.totalMs = processObj.stopMs - processObj.startMs;
processObj.stepObj.totalMs = processObj.totalMs;
delete processObj.stepObj;
}
return this;
}
return this._data.time;
};
/**
* Used to set key/value flags during operation execution.
* @param {String} key
* @param {String} val
* @returns {*}
*/
Operation.prototype.flag = function (key, val) {
if (key !== undefined && val !== undefined) {
this._data.flag[key] = val;
} else if (key !== undefined) {
return this._data.flag[key];
} else {
return this._data.flag;
}
};
Operation.prototype.data = function (path, val, noTime) {
if (val !== undefined) {
// Assign value to object path
this.pathSolver.set(this._data, path, val);
return this;
}
return this.pathSolver.get(this._data, path);
};
Operation.prototype.pushData = function (path, val, noTime) {
// Assign value to object path
this.pathSolver.push(this._data, path, val);
};
/**
* Stops the operation timer.
*/
Operation.prototype.stop = function () {
this._data.time.stopMs = new Date().getTime();
this._data.time.totalMs = this._data.time.stopMs - this._data.time.startMs;
};
Shared.finishModule('Operation');
module.exports = Operation;
},{"./Path":23,"./Shared":25}],22:[function(_dereq_,module,exports){
"use strict";
/**
* Allows a method to accept overloaded calls with different parameters controlling
* which passed overload function is called.
* @param {Object} def
* @returns {Function}
* @constructor
*/
var Overload = function (def) {
if (def) {
var self = this,
index,
count,
tmpDef,
defNewKey,
sigIndex,
signatures;
if (!(def instanceof Array)) {
tmpDef = {};
// Def is an object, make sure all prop names are devoid of spaces
for (index in def) {
if (def.hasOwnProperty(index)) {
defNewKey = index.replace(/ /g, '');
// Check if the definition array has a * string in it
if (defNewKey.indexOf('*') === -1) {
// No * found
tmpDef[defNewKey] = def[index];
} else {
// A * was found, generate the different signatures that this
// definition could represent
signatures = this.generateSignaturePermutations(defNewKey);
for (sigIndex = 0; sigIndex < signatures.length; sigIndex++) {
if (!tmpDef[signatures[sigIndex]]) {
tmpDef[signatures[sigIndex]] = def[index];
}
}
}
}
}
def = tmpDef;
}
return function () {
var arr = [],
lookup,
type;
// Check if we are being passed a key/function object or an array of functions
if (def instanceof Array) {
// We were passed an array of functions
count = def.length;
for (index = 0; index < count; index++) {
if (def[index].length === arguments.length) {
return self.callExtend(this, '$main', def, def[index], arguments);
}
}
} else {
// Generate lookup key from arguments
// Copy arguments to an array
for (index = 0; index < arguments.length; index++) {
type = typeof arguments[index];
// Handle detecting arrays
if (type === 'object' && arguments[index] instanceof Array) {
type = 'array';
}
// Handle been presented with a single undefined argument
if (arguments.length === 1 && type === 'undefined') {
break;
}
// Add the type to the argument types array
arr.push(type);
}
lookup = arr.join(',');
// Check for an exact lookup match
if (def[lookup]) {
return self.callExtend(this, '$main', def, def[lookup], arguments);
} else {
for (index = arr.length; index >= 0; index--) {
// Get the closest match
lookup = arr.slice(0, index).join(',');
if (def[lookup + ',...']) {
// Matched against arguments + "any other"
return self.callExtend(this, '$main', def, def[lookup + ',...'], arguments);
}
}
}
}
throw('ForerunnerDB.Overload "' + this.name() + '": Overloaded method does not have a matching signature for the passed arguments: ' + JSON.stringify(arr));
};
}
return function () {};
};
/**
* Generates an array of all the different definition signatures that can be
* created from the passed string with a catch-all wildcard *. E.g. it will
* convert the signature: string,*,string to all potentials:
* string,string,string
* string,number,string
* string,object,string,
* string,function,string,
* string,undefined,string
*
* @param {String} str Signature string with a wildcard in it.
* @returns {Array} An array of signature strings that are generated.
*/
Overload.prototype.generateSignaturePermutations = function (str) {
var signatures = [],
newSignature,
types = ['string', 'object', 'number', 'function', 'undefined'],
index;
if (str.indexOf('*') > -1) {
// There is at least one "any" type, break out into multiple keys
// We could do this at query time with regular expressions but
// would be significantly slower
for (index = 0; index < types.length; index++) {
newSignature = str.replace('*', types[index]);
signatures = signatures.concat(this.generateSignaturePermutations(newSignature));
}
} else {
signatures.push(str);
}
return signatures;
};
Overload.prototype.callExtend = function (context, prop, propContext, func, args) {
var tmp,
ret;
if (context && propContext[prop]) {
tmp = context[prop];
context[prop] = propContext[prop];
ret = func.apply(context, args);
context[prop] = tmp;
return ret;
} else {
return func.apply(context, args);
}
};
module.exports = Overload;
},{}],23:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared');
/**
* Path object used to resolve object paths and retrieve data from
* objects by using paths.
* @param {String=} path The path to assign.
* @constructor
*/
var Path = function (path) {
this.init.apply(this, arguments);
};
Path.prototype.init = function (path) {
if (path) {
this.path(path);
}
};
Shared.addModule('Path', Path);
Shared.mixin(Path.prototype, 'Mixin.ChainReactor');
/**
* Gets / sets the given path for the Path instance.
* @param {String=} path The path to assign.
*/
Path.prototype.path = function (path) {
if (path !== undefined) {
this._path = this.clean(path);
this._pathParts = this._path.split('.');
return this;
}
return this._path;
};
/**
* Tests if the passed object has the paths that are specified and that
* a value exists in those paths.
* @param {Object} testKeys The object describing the paths to test for.
* @param {Object} testObj The object to test paths against.
* @returns {Boolean} True if the object paths exist.
*/
Path.prototype.hasObjectPaths = function (testKeys, testObj) {
var result = true,
i;
for (i in testKeys) {
if (testKeys.hasOwnProperty(i)) {
if (testObj[i] === undefined) {
return false;
}
if (typeof testKeys[i] === 'object') {
// Recurse object
result = this.hasObjectPaths(testKeys[i], testObj[i]);
// Should we exit early?
if (!result) {
return false;
}
}
}
}
return result;
};
/**
* Counts the total number of key endpoints in the passed object.
* @param {Object} testObj The object to count key endpoints for.
* @returns {Number} The number of endpoints.
*/
Path.prototype.countKeys = function (testObj) {
var totalKeys = 0,
i;
for (i in testObj) {
if (testObj.hasOwnProperty(i)) {
if (testObj[i] !== undefined) {
if (typeof testObj[i] !== 'object') {
totalKeys++;
} else {
totalKeys += this.countKeys(testObj[i]);
}
}
}
}
return totalKeys;
};
/**
* Tests if the passed object has the paths that are specified and that
* a value exists in those paths and if so returns the number matched.
* @param {Object} testKeys The object describing the paths to test for.
* @param {Object} testObj The object to test paths against.
* @returns {Object} Stats on the matched keys
*/
Path.prototype.countObjectPaths = function (testKeys, testObj) {
var matchData,
matchedKeys = {},
matchedKeyCount = 0,
totalKeyCount = 0,
i;
for (i in testObj) {
if (testObj.hasOwnProperty(i)) {
if (typeof testObj[i] === 'object') {
// The test / query object key is an object, recurse
matchData = this.countObjectPaths(testKeys[i], testObj[i]);
matchedKeys[i] = matchData.matchedKeys;
totalKeyCount += matchData.totalKeyCount;
matchedKeyCount += matchData.matchedKeyCount;
} else {
// The test / query object has a property that is not an object so add it as a key
totalKeyCount++;
// Check if the test keys also have this key and it is also not an object
if (testKeys && testKeys[i] && typeof testKeys[i] !== 'object') {
matchedKeys[i] = true;
matchedKeyCount++;
} else {
matchedKeys[i] = false;
}
}
}
}
return {
matchedKeys: matchedKeys,
matchedKeyCount: matchedKeyCount,
totalKeyCount: totalKeyCount
};
};
/**
* Takes a non-recursive object and converts the object hierarchy into
* a path string.
* @param {Object} obj The object to parse.
* @param {Boolean=} withValue If true will include a 'value' key in the returned
* object that represents the value the object path points to.
* @returns {Object}
*/
Path.prototype.parse = function (obj, withValue) {
var paths = [],
path = '',
resultData,
i, k;
for (i in obj) {
if (obj.hasOwnProperty(i)) {
// Set the path to the key
path = i;
if (typeof(obj[i]) === 'object') {
if (withValue) {
resultData = this.parse(obj[i], withValue);
for (k = 0; k < resultData.length; k++) {
paths.push({
path: path + '.' + resultData[k].path,
value: resultData[k].value
});
}
} else {
resultData = this.parse(obj[i]);
for (k = 0; k < resultData.length; k++) {
paths.push({
path: path + '.' + resultData[k].path
});
}
}
} else {
if (withValue) {
paths.push({
path: path,
value: obj[i]
});
} else {
paths.push({
path: path
});
}
}
}
}
return paths;
};
/**
* Takes a non-recursive object and converts the object hierarchy into
* an array of path strings that allow you to target all possible paths
* in an object.
*
* @returns {Array}
*/
Path.prototype.parseArr = function (obj, options) {
options = options || {};
return this._parseArr(obj, '', [], options);
};
Path.prototype._parseArr = function (obj, path, paths, options) {
var i,
newPath = '';
path = path || '';
paths = paths || [];
for (i in obj) {
if (obj.hasOwnProperty(i)) {
if (!options.ignore || (options.ignore && !options.ignore.test(i))) {
if (path) {
newPath = path + '.' + i;
} else {
newPath = i;
}
if (typeof(obj[i]) === 'object') {
this._parseArr(obj[i], newPath, paths, options);
} else {
paths.push(newPath);
}
}
}
}
return paths;
};
/**
* Gets the value(s) that the object contains for the currently assigned path string.
* @param {Object} obj The object to evaluate the path against.
* @param {String=} path A path to use instead of the existing one passed in path().
* @returns {Array} An array of values for the given path.
*/
Path.prototype.value = function (obj, path) {
if (obj !== undefined && typeof obj === 'object') {
var pathParts,
arr,
arrCount,
objPart,
objPartParent,
valuesArr = [],
i, k;
if (path !== undefined) {
path = this.clean(path);
pathParts = path.split('.');
}
arr = pathParts || this._pathParts;
arrCount = arr.length;
objPart = obj;
for (i = 0; i < arrCount; i++) {
objPart = objPart[arr[i]];
if (objPartParent instanceof Array) {
// Search inside the array for the next key
for (k = 0; k < objPartParent.length; k++) {
valuesArr = valuesArr.concat(this.value(objPartParent, k + '.' + arr[i]));
}
return valuesArr;
} else {
if (!objPart || typeof(objPart) !== 'object') {
break;
}
}
objPartParent = objPart;
}
return [objPart];
} else {
return [];
}
};
/**
* Sets a value on an object for the specified path.
* @param {Object} obj The object to update.
* @param {String} path The path to update.
* @param {*} val The value to set the object path to.
* @returns {*}
*/
Path.prototype.set = function (obj, path, val) {
if (obj !== undefined && path !== undefined) {
var pathParts,
part;
path = this.clean(path);
pathParts = path.split('.');
part = pathParts.shift();
if (pathParts.length) {
// Generate the path part in the object if it does not already exist
obj[part] = obj[part] || {};
// Recurse
this.set(obj[part], pathParts.join('.'), val);
} else {
// Set the value
obj[part] = val;
}
}
return obj;
};
Path.prototype.get = function (obj, path) {
return this.value(obj, path)[0];
};
/**
* Push a value to an array on an object for the specified path.
* @param {Object} obj The object to update.
* @param {String} path The path to the array to push to.
* @param {*} val The value to push to the array at the object path.
* @returns {*}
*/
Path.prototype.push = function (obj, path, val) {
if (obj !== undefined && path !== undefined) {
var pathParts,
part;
path = this.clean(path);
pathParts = path.split('.');
part = pathParts.shift();
if (pathParts.length) {
// Generate the path part in the object if it does not already exist
obj[part] = obj[part] || {};
// Recurse
this.set(obj[part], pathParts.join('.'), val);
} else {
// Set the value
obj[part] = obj[part] || [];
if (obj[part] instanceof Array) {
obj[part].push(val);
} else {
throw('ForerunnerDB.Path: Cannot push to a path whose endpoint is not an array!');
}
}
}
return obj;
};
/**
* Gets the value(s) that the object contains for the currently assigned path string
* with their associated keys.
* @param {Object} obj The object to evaluate the path against.
* @param {String=} path A path to use instead of the existing one passed in path().
* @returns {Array} An array of values for the given path with the associated key.
*/
Path.prototype.keyValue = function (obj, path) {
var pathParts,
arr,
arrCount,
objPart,
objPartParent,
objPartHash,
i;
if (path !== undefined) {
path = this.clean(path);
pathParts = path.split('.');
}
arr = pathParts || this._pathParts;
arrCount = arr.length;
objPart = obj;
for (i = 0; i < arrCount; i++) {
objPart = objPart[arr[i]];
if (!objPart || typeof(objPart) !== 'object') {
objPartHash = arr[i] + ':' + objPart;
break;
}
objPartParent = objPart;
}
return objPartHash;
};
/**
* Removes leading period (.) from string and returns it.
* @param {String} str The string to clean.
* @returns {*}
*/
Path.prototype.clean = function (str) {
if (str.substr(0, 1) === '.') {
str = str.substr(1, str.length -1);
}
return str;
};
Shared.finishModule('Path');
module.exports = Path;
},{"./Shared":25}],24:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared');
var ReactorIO = function (reactorIn, reactorOut, reactorProcess) {
if (reactorIn && reactorOut && reactorProcess) {
this._reactorIn = reactorIn;
this._reactorOut = reactorOut;
this._chainHandler = reactorProcess;
if (!reactorIn.chain || !reactorOut.chainReceive) {
throw('ForerunnerDB.ReactorIO: ReactorIO requires passed in and out objects to implement the ChainReactor mixin!');
}
// Register the reactorIO with the input
reactorIn.chain(this);
// Register the output with the reactorIO
this.chain(reactorOut);
} else {
throw('ForerunnerDB.ReactorIO: ReactorIO requires in, out and process arguments to instantiate!');
}
};
Shared.addModule('ReactorIO', ReactorIO);
ReactorIO.prototype.drop = function () {
if (this._state !== 'dropped') {
this._state = 'dropped';
// Remove links
if (this._reactorIn) {
this._reactorIn.unChain(this);
}
if (this._reactorOut) {
this.unChain(this._reactorOut);
}
delete this._reactorIn;
delete this._reactorOut;
delete this._chainHandler;
this.emit('drop', this);
}
return true;
};
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(ReactorIO.prototype, 'state');
Shared.mixin(ReactorIO.prototype, 'Mixin.ChainReactor');
Shared.mixin(ReactorIO.prototype, 'Mixin.Events');
Shared.finishModule('ReactorIO');
module.exports = ReactorIO;
},{"./Shared":25}],25:[function(_dereq_,module,exports){
"use strict";
var Shared = {
version: '1.3.50',
modules: {},
_synth: {},
/**
* Adds a module to ForerunnerDB.
* @param {String} name The name of the module.
* @param {Function} module The module class.
*/
addModule: function (name, module) {
this.modules[name] = module;
this.emit('moduleLoad', [name, module]);
},
/**
* Called by the module once all processing has been completed. Used to determine
* if the module is ready for use by other modules.
* @param {String} name The name of the module.
*/
finishModule: function (name) {
if (this.modules[name]) {
this.modules[name]._fdbFinished = true;
this.emit('moduleFinished', [name, this.modules[name]]);
} else {
throw('ForerunnerDB.Shared: finishModule called on a module that has not been registered with addModule(): ' + name);
}
},
/**
* Will call your callback method when the specified module has loaded. If the module
* is already loaded the callback is called immediately.
* @param {String} name The name of the module.
* @param {Function} callback The callback method to call when the module is loaded.
*/
moduleFinished: function (name, callback) {
if (this.modules[name] && this.modules[name]._fdbFinished) {
if (callback) { callback(name, this.modules[name]); }
} else {
this.on('moduleFinished', callback);
}
},
/**
* Determines if a module has been added to ForerunnerDB or not.
* @param {String} name The name of the module.
* @returns {Boolean} True if the module exists or false if not.
*/
moduleExists: function (name) {
return Boolean(this.modules[name]);
},
/**
* Adds the properties and methods defined in the mixin to the passed object.
* @param {Object} obj The target object to add mixin key/values to.
* @param {String} mixinName The name of the mixin to add to the object.
*/
mixin: function (obj, mixinName) {
var system = this.mixins[mixinName];
if (system) {
for (var i in system) {
if (system.hasOwnProperty(i)) {
obj[i] = system[i];
}
}
} else {
throw('ForerunnerDB.Shared: Cannot find mixin named: ' + mixinName);
}
},
/**
* Generates a generic getter/setter method for the passed method name.
* @param {Object} obj The object to add the getter/setter to.
* @param {String} name The name of the getter/setter to generate.
* @param {Function=} extend A method to call before executing the getter/setter.
* The existing getter/setter can be accessed from the extend method via the
* $super e.g. this.$super();
*/
synthesize: function (obj, name, extend) {
this._synth[name] = this._synth[name] || function (val) {
if (val !== undefined) {
this['_' + name] = val;
return this;
}
return this['_' + name];
};
if (extend) {
var self = this;
obj[name] = function () {
var tmp = this.$super,
ret;
this.$super = self._synth[name];
ret = extend.apply(this, arguments);
this.$super = tmp;
return ret;
};
} else {
obj[name] = this._synth[name];
}
},
/**
* Allows a method to be overloaded.
* @param arr
* @returns {Function}
* @constructor
*/
overload: _dereq_('./Overload'),
/**
* Define the mixins that other modules can use as required.
*/
mixins: {
'Mixin.Common': _dereq_('./Mixin.Common'),
'Mixin.Events': _dereq_('./Mixin.Events'),
'Mixin.ChainReactor': _dereq_('./Mixin.ChainReactor'),
'Mixin.CRUD': _dereq_('./Mixin.CRUD'),
'Mixin.Constants': _dereq_('./Mixin.Constants'),
'Mixin.Triggers': _dereq_('./Mixin.Triggers'),
'Mixin.Sorting': _dereq_('./Mixin.Sorting'),
'Mixin.Matching': _dereq_('./Mixin.Matching'),
'Mixin.Updating': _dereq_('./Mixin.Updating')
}
};
// Add event handling to shared
Shared.mixin(Shared, 'Mixin.Events');
module.exports = Shared;
},{"./Mixin.CRUD":12,"./Mixin.ChainReactor":13,"./Mixin.Common":14,"./Mixin.Constants":15,"./Mixin.Events":16,"./Mixin.Matching":17,"./Mixin.Sorting":18,"./Mixin.Triggers":19,"./Mixin.Updating":20,"./Overload":22}],26:[function(_dereq_,module,exports){
"use strict";
// Import external names locally
var Shared,
Db,
Collection,
CollectionGroup,
CollectionInit,
DbInit,
ReactorIO,
ActiveBucket;
Shared = _dereq_('./Shared');
/**
* The view constructor.
* @param name
* @param query
* @param options
* @constructor
*/
var View = function (name, query, options) {
this.init.apply(this, arguments);
};
View.prototype.init = function (name, query, options) {
var self = this;
this._name = name;
this._listeners = {};
this._querySettings = {};
this._debug = {};
this.query(query, false);
this.queryOptions(options, false);
this._collectionDroppedWrap = function () {
self._collectionDropped.apply(self, arguments);
};
this._privateData = new Collection('__FDB__view_privateData_' + this._name);
};
Shared.addModule('View', View);
Shared.mixin(View.prototype, 'Mixin.Common');
Shared.mixin(View.prototype, 'Mixin.ChainReactor');
Shared.mixin(View.prototype, 'Mixin.Constants');
Shared.mixin(View.prototype, 'Mixin.Triggers');
Collection = _dereq_('./Collection');
CollectionGroup = _dereq_('./CollectionGroup');
ActiveBucket = _dereq_('./ActiveBucket');
ReactorIO = _dereq_('./ReactorIO');
CollectionInit = Collection.prototype.init;
Db = Shared.modules.Db;
DbInit = Db.prototype.init;
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(View.prototype, 'state');
Shared.synthesize(View.prototype, 'name');
Shared.synthesize(View.prototype, 'cursor');
/**
* Executes an insert against the view's underlying data-source.
*/
View.prototype.insert = function () {
this._from.insert.apply(this._from, arguments);
};
/**
* Executes an update against the view's underlying data-source.
*/
View.prototype.update = function () {
this._from.update.apply(this._from, arguments);
};
/**
* Executes an updateById against the view's underlying data-source.
*/
View.prototype.updateById = function () {
this._from.updateById.apply(this._from, arguments);
};
/**
* Executes a remove against the view's underlying data-source.
*/
View.prototype.remove = function () {
this._from.remove.apply(this._from, arguments);
};
/**
* Queries the view data. See Collection.find() for more information.
* @returns {*}
*/
View.prototype.find = function (query, options) {
return this.publicData().find(query, options);
};
/**
* Gets the module's internal data collection.
* @returns {Collection}
*/
View.prototype.data = function () {
return this._privateData;
};
/**
* Sets the collection from which the view will assemble its data.
* @param {Collection} collection The collection to use to assemble view data.
* @returns {View}
*/
View.prototype.from = function (collection) {
var self = this;
if (collection !== undefined) {
// Check if we have an existing from
if (this._from) {
// Remove the listener to the drop event
this._from.off('drop', this._collectionDroppedWrap);
delete this._from;
}
if (typeof(collection) === 'string') {
collection = this._db.collection(collection);
}
this._from = collection;
this._from.on('drop', this._collectionDroppedWrap);
// Create a new reactor IO graph node that intercepts chain packets from the
// view's "from" collection and determines how they should be interpreted by
// this view. If the view does not have a query then this reactor IO will
// simply pass along the chain packet without modifying it.
this._io = new ReactorIO(collection, this, function (chainPacket) {
var data,
diff,
query,
filteredData,
doSend,
pk,
i;
// Check if we have a constraining query
if (self._querySettings.query) {
if (chainPacket.type === 'insert') {
data = chainPacket.data;
// Check if the data matches our query
if (data instanceof Array) {
filteredData = [];
for (i = 0; i < data.length; i++) {
if (self._privateData._match(data[i], self._querySettings.query, 'and', {})) {
filteredData.push(data[i]);
doSend = true;
}
}
} else {
if (self._privateData._match(data, self._querySettings.query, 'and', {})) {
filteredData = data;
doSend = true;
}
}
if (doSend) {
this.chainSend('insert', filteredData);
}
return true;
}
if (chainPacket.type === 'update') {
// Do a DB diff between this view's data and the underlying collection it reads from
// to see if something has changed
diff = self._privateData.diff(self._from.subset(self._querySettings.query, self._querySettings.options));
if (diff.insert.length || diff.remove.length) {
// Now send out new chain packets for each operation
if (diff.insert.length) {
this.chainSend('insert', diff.insert);
}
if (diff.update.length) {
pk = self._privateData.primaryKey();
for (i = 0; i < diff.update.length; i++) {
query = {};
query[pk] = diff.update[i][pk];
this.chainSend('update', {
query: query,
update: diff.update[i]
});
}
}
if (diff.remove.length) {
pk = self._privateData.primaryKey();
var $or = [],
removeQuery = {
query: {
$or: $or
}
};
for (i = 0; i < diff.remove.length; i++) {
$or.push({_id: diff.remove[i][pk]});
}
this.chainSend('remove', removeQuery);
}
// Return true to stop further propagation of the chain packet
return true;
} else {
// Returning false informs the chain reactor to continue propagation
// of the chain packet down the graph tree
return false;
}
}
}
// Returning false informs the chain reactor to continue propagation
// of the chain packet down the graph tree
return false;
});
var collData = collection.find(this._querySettings.query, this._querySettings.options);
this._transformPrimaryKey(collection.primaryKey());
this._transformSetData(collData);
this._privateData.primaryKey(collection.primaryKey());
this._privateData.setData(collData);
if (this._querySettings.options && this._querySettings.options.$orderBy) {
this.rebuildActiveBucket(this._querySettings.options.$orderBy);
} else {
this.rebuildActiveBucket();
}
}
return this;
};
View.prototype._collectionDropped = function (collection) {
if (collection) {
// Collection was dropped, remove from view
delete this._from;
}
};
View.prototype.ensureIndex = function () {
return this._privateData.ensureIndex.apply(this._privateData, arguments);
};
View.prototype._chainHandler = function (chainPacket) {
var //self = this,
arr,
count,
index,
insertIndex,
//tempData,
//dataIsArray,
updates,
//finalUpdates,
primaryKey,
tQuery,
item,
currentIndex,
i;
switch (chainPacket.type) {
case 'setData':
if (this.debug()) {
console.log('ForerunnerDB.View: Setting data on view "' + this.name() + '" in underlying (internal) view collection "' + this._privateData.name() + '"');
}
// Get the new data from our underlying data source sorted as we want
var collData = this._from.find(this._querySettings.query, this._querySettings.options);
// Modify transform data
this._transformSetData(collData);
this._privateData.setData(collData);
break;
case 'insert':
if (this.debug()) {
console.log('ForerunnerDB.View: Inserting some data on view "' + this.name() + '" in underlying (internal) view collection "' + this._privateData.name() + '"');
}
// Decouple the data to ensure we are working with our own copy
chainPacket.data = this.decouple(chainPacket.data);
// Make sure we are working with an array
if (!(chainPacket.data instanceof Array)) {
chainPacket.data = [chainPacket.data];
}
if (this._querySettings.options && this._querySettings.options.$orderBy) {
// Loop the insert data and find each item's index
arr = chainPacket.data;
count = arr.length;
for (index = 0; index < count; index++) {
insertIndex = this._activeBucket.insert(arr[index]);
// Modify transform data
this._transformInsert(chainPacket.data, insertIndex);
this._privateData._insertHandle(chainPacket.data, insertIndex);
}
} else {
// Set the insert index to the passed index, or if none, the end of the view data array
insertIndex = this._privateData._data.length;
// Modify transform data
this._transformInsert(chainPacket.data, insertIndex);
this._privateData._insertHandle(chainPacket.data, insertIndex);
}
break;
case 'update':
if (this.debug()) {
console.log('ForerunnerDB.View: Updating some data on view "' + this.name() + '" in underlying (internal) view collection "' + this._privateData.name() + '"');
}
primaryKey = this._privateData.primaryKey();
// Do the update
updates = this._privateData.update(
chainPacket.data.query,
chainPacket.data.update,
chainPacket.data.options
);
if (this._querySettings.options && this._querySettings.options.$orderBy) {
// TODO: This would be a good place to improve performance by somehow
// TODO: inspecting the change that occurred when update was performed
// TODO: above and determining if it affected the order clause keys
// TODO: and if not, skipping the active bucket updates here
// Loop the updated items and work out their new sort locations
count = updates.length;
for (index = 0; index < count; index++) {
item = updates[index];
// Remove the item from the active bucket (via it's id)
this._activeBucket.remove(item);
// Get the current location of the item
currentIndex = this._privateData._data.indexOf(item);
// Add the item back in to the active bucket
insertIndex = this._activeBucket.insert(item);
if (currentIndex !== insertIndex) {
// Move the updated item to the new index
this._privateData._updateSpliceMove(this._privateData._data, currentIndex, insertIndex);
}
}
}
if (this._transformEnabled && this._transformIn) {
primaryKey = this._publicData.primaryKey();
for (i = 0; i < updates.length; i++) {
tQuery = {};
item = updates[i];
tQuery[primaryKey] = item[primaryKey];
this._transformUpdate(tQuery, item);
}
}
break;
case 'remove':
if (this.debug()) {
console.log('ForerunnerDB.View: Removing some data on view "' + this.name() + '" in underlying (internal) view collection "' + this._privateData.name() + '"');
}
// Modify transform data
this._transformRemove(chainPacket.data.query, chainPacket.options);
this._privateData.remove(chainPacket.data.query, chainPacket.options);
break;
default:
break;
}
};
View.prototype.on = function () {
this._privateData.on.apply(this._privateData, arguments);
};
View.prototype.off = function () {
this._privateData.off.apply(this._privateData, arguments);
};
View.prototype.emit = function () {
this._privateData.emit.apply(this._privateData, arguments);
};
/**
* Find the distinct values for a specified field across a single collection and
* returns the results in an array.
* @param {String} key The field path to return distinct values for e.g. "person.name".
* @param {Object=} query The query to use to filter the documents used to return values from.
* @param {Object=} options The query options to use when running the query.
* @returns {Array}
*/
View.prototype.distinct = function (key, query, options) {
return this._privateData.distinct.apply(this._privateData, arguments);
};
/**
* Gets the primary key for this view from the assigned collection.
* @returns {String}
*/
View.prototype.primaryKey = function () {
return this._privateData.primaryKey();
};
/**
* Drops a view and all it's stored data from the database.
* @returns {boolean} True on success, false on failure.
*/
View.prototype.drop = function () {
if (this._state !== 'dropped') {
if (this._from) {
this._from.off('drop', this._collectionDroppedWrap);
this._from._removeView(this);
if (this.debug() || (this._db && this._db.debug())) {
console.log('ForerunnerDB.View: Dropping view ' + this._name);
}
this._state = 'dropped';
// Clear io and chains
if (this._io) {
this._io.drop();
}
// Drop the view's internal collection
if (this._privateData) {
this._privateData.drop();
}
if (this._db && this._name) {
delete this._db._view[this._name];
}
this.emit('drop', this);
delete this._chain;
delete this._from;
delete this._privateData;
delete this._io;
delete this._listeners;
delete this._querySettings;
delete this._db;
return true;
}
} else {
return true;
}
return false;
};
/**
* Gets / sets the DB the view is bound against. Automatically set
* when the db.oldView(viewName) method is called.
* @param db
* @returns {*}
*/
View.prototype.db = function (db) {
if (db !== undefined) {
this._db = db;
this.privateData().db(db);
this.publicData().db(db);
return this;
}
return this._db;
};
/**
* Gets / sets the query that the view uses to build it's data set.
* @param {Object=} query
* @param {Boolean=} options An options object.
* @param {Boolean=} refresh Whether to refresh the view data after
* this operation. Defaults to true.
* @returns {*}
*/
View.prototype.queryData = function (query, options, refresh) {
if (query !== undefined) {
this._querySettings.query = query;
}
if (options !== undefined) {
this._querySettings.options = options;
}
if (query !== undefined || options !== undefined) {
if (refresh === undefined || refresh === true) {
this.refresh();
}
return this;
}
return this._querySettings;
};
/**
* Add data to the existing query.
* @param {Object} obj The data whose keys will be added to the existing
* query object.
* @param {Boolean} overwrite Whether or not to overwrite data that already
* exists in the query object. Defaults to true.
* @param {Boolean=} refresh Whether or not to refresh the view data set
* once the operation is complete. Defaults to true.
*/
View.prototype.queryAdd = function (obj, overwrite, refresh) {
this._querySettings.query = this._querySettings.query || {};
var query = this._querySettings.query,
i;
if (obj !== undefined) {
// Loop object properties and add to existing query
for (i in obj) {
if (obj.hasOwnProperty(i)) {
if (query[i] === undefined || (query[i] !== undefined && overwrite !== false)) {
query[i] = obj[i];
}
}
}
}
if (refresh === undefined || refresh === true) {
this.refresh();
}
};
/**
* Remove data from the existing query.
* @param {Object} obj The data whose keys will be removed from the existing
* query object.
* @param {Boolean=} refresh Whether or not to refresh the view data set
* once the operation is complete. Defaults to true.
*/
View.prototype.queryRemove = function (obj, refresh) {
var query = this._querySettings.query,
i;
if (obj !== undefined) {
// Loop object properties and add to existing query
for (i in obj) {
if (obj.hasOwnProperty(i)) {
delete query[i];
}
}
}
if (refresh === undefined || refresh === true) {
this.refresh();
}
};
/**
* Gets / sets the query being used to generate the view data.
* @param {Object=} query The query to set.
* @param {Boolean=} refresh Whether to refresh the view data after
* this operation. Defaults to true.
* @returns {*}
*/
View.prototype.query = function (query, refresh) {
if (query !== undefined) {
this._querySettings.query = query;
if (refresh === undefined || refresh === true) {
this.refresh();
}
return this;
}
return this._querySettings.query;
};
/**
* Gets / sets the orderBy clause in the query options for the view.
* @param {Object=} val The order object.
* @returns {*}
*/
View.prototype.orderBy = function (val) {
if (val !== undefined) {
var queryOptions = this.queryOptions() || {};
queryOptions.$orderBy = val;
this.queryOptions(queryOptions);
return this;
}
return (this.queryOptions() || {}).$orderBy;
};
/**
* Gets / sets the page clause in the query options for the view.
* @param {Number=} val The page number to change to (zero index).
* @returns {*}
*/
View.prototype.page = function (val) {
if (val !== undefined) {
var queryOptions = this.queryOptions() || {};
// Only execute a query options update if page has changed
if (val !== queryOptions.$page) {
queryOptions.$page = val;
this.queryOptions(queryOptions);
}
return this;
}
return (this.queryOptions() || {}).$page;
};
/**
* Jump to the first page in the data set.
* @returns {*}
*/
View.prototype.pageFirst = function () {
return this.page(0);
};
/**
* Jump to the last page in the data set.
* @returns {*}
*/
View.prototype.pageLast = function () {
var pages = this.cursor().pages,
lastPage = pages !== undefined ? pages : 0;
return this.page(lastPage - 1);
};
/**
* Move forward or backwards in the data set pages by passing a positive
* or negative integer of the number of pages to move.
* @param {Number} val The number of pages to move.
* @returns {*}
*/
View.prototype.pageScan = function (val) {
if (val !== undefined) {
var pages = this.cursor().pages,
queryOptions = this.queryOptions() || {},
currentPage = queryOptions.$page !== undefined ? queryOptions.$page : 0;
currentPage += val;
if (currentPage < 0) {
currentPage = 0;
}
if (currentPage >= pages) {
currentPage = pages - 1;
}
return this.page(currentPage);
}
};
/**
* Gets / sets the query options used when applying sorting etc to the
* view data set.
* @param {Object=} options An options object.
* @param {Boolean=} refresh Whether to refresh the view data after
* this operation. Defaults to true.
* @returns {*}
*/
View.prototype.queryOptions = function (options, refresh) {
if (options !== undefined) {
this._querySettings.options = options;
if (options.$decouple === undefined) { options.$decouple = true; }
if (refresh === undefined || refresh === true) {
this.refresh();
} else {
this.rebuildActiveBucket(options.$orderBy);
}
return this;
}
return this._querySettings.options;
};
View.prototype.rebuildActiveBucket = function (orderBy) {
if (orderBy) {
var arr = this._privateData._data,
arrCount = arr.length;
// Build a new active bucket
this._activeBucket = new ActiveBucket(orderBy);
this._activeBucket.primaryKey(this._privateData.primaryKey());
// Loop the current view data and add each item
for (var i = 0; i < arrCount; i++) {
this._activeBucket.insert(arr[i]);
}
} else {
// Remove any existing active bucket
delete this._activeBucket;
}
};
/**
* Refreshes the view data such as ordering etc.
*/
View.prototype.refresh = function () {
if (this._from) {
var pubData = this.publicData(),
refreshResults;
// Re-grab all the data for the view from the collection
this._privateData.remove();
pubData.remove();
refreshResults = this._from.find(this._querySettings.query, this._querySettings.options);
this.cursor(refreshResults.$cursor);
this._privateData.insert(refreshResults);
this._privateData._data.$cursor = refreshResults.$cursor;
pubData._data.$cursor = refreshResults.$cursor;
/*if (pubData._linked) {
// Update data and observers
//var transformedData = this._privateData.find();
// TODO: Shouldn't this data get passed into a transformIn first?
// TODO: This breaks linking because its passing decoupled data and overwriting non-decoupled data
// TODO: Is this even required anymore? After commenting it all seems to work
// TODO: Might be worth setting up a test to check transforms and linking then remove this if working?
//jQuery.observable(pubData._data).refresh(transformedData);
}*/
}
if (this._querySettings.options && this._querySettings.options.$orderBy) {
this.rebuildActiveBucket(this._querySettings.options.$orderBy);
} else {
this.rebuildActiveBucket();
}
return this;
};
/**
* Returns the number of documents currently in the view.
* @returns {Number}
*/
View.prototype.count = function () {
return this._privateData && this._privateData._data ? this._privateData._data.length : 0;
};
// Call underlying
View.prototype.subset = function () {
return this.publicData().subset.apply(this._privateData, arguments);
};
/**
* Takes the passed data and uses it to set transform methods and globally
* enable or disable the transform system for the view.
* @param {Object} obj The new transform system settings "enabled", "dataIn" and "dataOut":
* {
* "enabled": true,
* "dataIn": function (data) { return data; },
* "dataOut": function (data) { return data; }
* }
* @returns {*}
*/
View.prototype.transform = function (obj) {
if (obj !== undefined) {
if (typeof obj === "object") {
if (obj.enabled !== undefined) {
this._transformEnabled = obj.enabled;
}
if (obj.dataIn !== undefined) {
this._transformIn = obj.dataIn;
}
if (obj.dataOut !== undefined) {
this._transformOut = obj.dataOut;
}
} else {
this._transformEnabled = obj !== false;
}
// Update the transformed data object
this._transformPrimaryKey(this.privateData().primaryKey());
this._transformSetData(this.privateData().find());
return this;
}
return {
enabled: this._transformEnabled,
dataIn: this._transformIn,
dataOut: this._transformOut
};
};
/**
* Executes a method against each document that matches query and returns an
* array of documents that may have been modified by the method.
* @param {Object} query The query object.
* @param {Function} func The method that each document is passed to. If this method
* returns false for a particular document it is excluded from the results.
* @param {Object=} options Optional options object.
* @returns {Array}
*/
View.prototype.filter = function (query, func, options) {
return (this.publicData()).filter(query, func, options);
};
/**
* Returns the non-transformed data the view holds as a collection
* reference.
* @return {Collection} The non-transformed collection reference.
*/
View.prototype.privateData = function () {
return this._privateData;
};
/**
* Returns a data object representing the public data this view
* contains. This can change depending on if transforms are being
* applied to the view or not.
*
* If no transforms are applied then the public data will be the
* same as the private data the view holds. If transforms are
* applied then the public data will contain the transformed version
* of the private data.
*
* The public data collection is also used by data binding to only
* changes to the publicData will show in a data-bound element.
*/
View.prototype.publicData = function () {
if (this._transformEnabled) {
return this._publicData;
} else {
return this._privateData;
}
};
/**
* Updates the public data object to match data from the private data object
* by running private data through the dataIn method provided in
* the transform() call.
* @private
*/
View.prototype._transformSetData = function (data) {
if (this._transformEnabled) {
// Clear existing data
this._publicData = new Collection('__FDB__view_publicData_' + this._name);
this._publicData.db(this._privateData._db);
this._publicData.transform({
enabled: true,
dataIn: this._transformIn,
dataOut: this._transformOut
});
this._publicData.setData(data);
}
};
View.prototype._transformInsert = function (data, index) {
if (this._transformEnabled && this._publicData) {
this._publicData.insert(data, index);
}
};
View.prototype._transformUpdate = function (query, update, options) {
if (this._transformEnabled && this._publicData) {
this._publicData.update(query, update, options);
}
};
View.prototype._transformRemove = function (query, options) {
if (this._transformEnabled && this._publicData) {
this._publicData.remove(query, options);
}
};
View.prototype._transformPrimaryKey = function (key) {
if (this._transformEnabled && this._publicData) {
this._publicData.primaryKey(key);
}
};
// Extend collection with view init
Collection.prototype.init = function () {
this._view = [];
CollectionInit.apply(this, arguments);
};
/**
* Creates a view and assigns the collection as its data source.
* @param {String} name The name of the new view.
* @param {Object} query The query to apply to the new view.
* @param {Object} options The options object to apply to the view.
* @returns {*}
*/
Collection.prototype.view = function (name, query, options) {
if (this._db && this._db._view ) {
if (!this._db._view[name]) {
var view = new View(name, query, options)
.db(this._db)
.from(this);
this._view = this._view || [];
this._view.push(view);
return view;
} else {
throw('ForerunnerDB.Collection "' + this.name() + '": Cannot create a view using this collection because a view with this name already exists: ' + name);
}
}
};
/**
* Adds a view to the internal view lookup.
* @param {View} view The view to add.
* @returns {Collection}
* @private
*/
Collection.prototype._addView = CollectionGroup.prototype._addView = function (view) {
if (view !== undefined) {
this._view.push(view);
}
return this;
};
/**
* Removes a view from the internal view lookup.
* @param {View} view The view to remove.
* @returns {Collection}
* @private
*/
Collection.prototype._removeView = CollectionGroup.prototype._removeView = function (view) {
if (view !== undefined) {
var index = this._view.indexOf(view);
if (index > -1) {
this._view.splice(index, 1);
}
}
return this;
};
// Extend DB with views init
Db.prototype.init = function () {
this._view = {};
DbInit.apply(this, arguments);
};
/**
* Gets a view by it's name.
* @param {String} viewName The name of the view to retrieve.
* @returns {*}
*/
Db.prototype.view = function (viewName) {
if (!this._view[viewName]) {
if (this.debug() || (this._db && this._db.debug())) {
console.log('Db.View: Creating view ' + viewName);
}
}
this._view[viewName] = this._view[viewName] || new View(viewName).db(this);
return this._view[viewName];
};
/**
* Determine if a view with the passed name already exists.
* @param {String} viewName The name of the view to check for.
* @returns {boolean}
*/
Db.prototype.viewExists = function (viewName) {
return Boolean(this._view[viewName]);
};
/**
* Returns an array of views the DB currently has.
* @returns {Array} An array of objects containing details of each view
* the database is currently managing.
*/
Db.prototype.views = function () {
var arr = [],
i;
for (i in this._view) {
if (this._view.hasOwnProperty(i)) {
arr.push({
name: i,
count: this._view[i].count()
});
}
}
return arr;
};
Shared.finishModule('View');
module.exports = View;
},{"./ActiveBucket":2,"./Collection":3,"./CollectionGroup":4,"./ReactorIO":24,"./Shared":25}]},{},[1]);
| mit |
respu/coral-folly | folly/io/async/test/EventHandlerTest.cpp | 4714 | /*
* Copyright 2015 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <folly/io/async/EventHandler.h>
#include <sys/eventfd.h>
#include <thread>
#include <folly/MPMCQueue.h>
#include <folly/ScopeGuard.h>
#include <folly/io/async/EventBase.h>
#include <gtest/gtest.h>
#include <gmock/gmock.h>
using namespace std;
using namespace folly;
using namespace testing;
void runInThreadsAndWait(
size_t nthreads, function<void(size_t)> cb) {
vector<thread> threads(nthreads);
for (size_t i = 0; i < nthreads; ++i) {
threads[i] = thread(cb, i);
}
for (size_t i = 0; i < nthreads; ++i) {
threads[i].join();
}
}
void runInThreadsAndWait(vector<function<void()>> cbs) {
runInThreadsAndWait(cbs.size(), [&](size_t k) { cbs[k](); });
}
class EventHandlerMock : public EventHandler {
public:
EventHandlerMock(EventBase* eb, int fd) : EventHandler(eb, fd) {}
// gmock can't mock noexcept methods, so we need an intermediary
MOCK_METHOD1(_handlerReady, void(uint16_t));
void handlerReady(uint16_t events) noexcept override {
_handlerReady(events);
}
};
class EventHandlerTest : public Test {
public:
int efd = 0;
void SetUp() override {
efd = eventfd(0, EFD_SEMAPHORE);
ASSERT_THAT(efd, Gt(0));
}
void TearDown() override {
if (efd > 0) {
close(efd);
}
efd = 0;
}
void efd_write(uint64_t val) {
write(efd, &val, sizeof(val));
}
uint64_t efd_read() {
uint64_t val = 0;
read(efd, &val, sizeof(val));
return val;
}
};
TEST_F(EventHandlerTest, simple) {
const size_t writes = 4;
size_t readsRemaining = writes;
EventBase eb;
EventHandlerMock eh(&eb, efd);
eh.registerHandler(EventHandler::READ | EventHandler::PERSIST);
EXPECT_CALL(eh, _handlerReady(_))
.Times(writes)
.WillRepeatedly(Invoke([&](uint16_t events) {
efd_read();
if (--readsRemaining == 0) {
eh.unregisterHandler();
}
}));
efd_write(writes);
eb.loop();
EXPECT_EQ(0, readsRemaining);
}
TEST_F(EventHandlerTest, many_concurrent_producers) {
const size_t writes = 200;
const size_t nproducers = 20;
size_t readsRemaining = writes;
runInThreadsAndWait({
[&] {
EventBase eb;
EventHandlerMock eh(&eb, efd);
eh.registerHandler(EventHandler::READ | EventHandler::PERSIST);
EXPECT_CALL(eh, _handlerReady(_))
.Times(writes)
.WillRepeatedly(Invoke([&](uint16_t events) {
efd_read();
if (--readsRemaining == 0) {
eh.unregisterHandler();
}
}));
eb.loop();
},
[&] {
runInThreadsAndWait(nproducers, [&](size_t k) {
for (size_t i = 0; i < writes / nproducers; ++i) {
this_thread::sleep_for(chrono::milliseconds(1));
efd_write(1);
}
});
},
});
EXPECT_EQ(0, readsRemaining);
}
TEST_F(EventHandlerTest, many_concurrent_consumers) {
const size_t writes = 200;
const size_t nproducers = 8;
const size_t nconsumers = 20;
atomic<size_t> writesRemaining(writes);
atomic<size_t> readsRemaining(writes);
MPMCQueue<nullptr_t> queue(writes / 10);
runInThreadsAndWait({
[&] {
runInThreadsAndWait(nconsumers, [&](size_t k) {
size_t thReadsRemaining = writes / nconsumers;
EventBase eb;
EventHandlerMock eh(&eb, efd);
eh.registerHandler(EventHandler::READ | EventHandler::PERSIST);
EXPECT_CALL(eh, _handlerReady(_))
.WillRepeatedly(Invoke([&](uint16_t events) {
nullptr_t val;
if (!queue.readIfNotEmpty(val)) {
return;
}
efd_read();
--readsRemaining;
if (--thReadsRemaining == 0) {
eh.unregisterHandler();
}
}));
eb.loop();
});
},
[&] {
runInThreadsAndWait(nproducers, [&](size_t k) {
for (size_t i = 0; i < writes / nproducers; ++i) {
this_thread::sleep_for(chrono::milliseconds(1));
queue.blockingWrite(nullptr);
efd_write(1);
--writesRemaining;
}
});
},
});
EXPECT_EQ(0, writesRemaining);
EXPECT_EQ(0, readsRemaining);
}
| apache-2.0 |
scheib/chromium | third_party/blink/web_tests/fast/js/js-constructors-use-correct-global.html | 233 | <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
<html>
<head>
<script src="../../resources/js-test.js"></script>
</head>
<body>
<iframe></iframe>
<script src="resources/js-constructors-use-correct-global.js"></script>
</body>
</html>
| bsd-3-clause |
krk/coreclr | tests/src/JIT/HardwareIntrinsics/X86/Bmi1.X64/TrailingZeroCount.UInt64.cs | 7684 | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void TrailingZeroCountUInt64()
{
var test = new ScalarUnaryOpTest__TrailingZeroCountUInt64();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.ReadUnaligned
test.RunBasicScenario_UnsafeRead();
// Validates calling via reflection works, using Unsafe.ReadUnaligned
test.RunReflectionScenario_UnsafeRead();
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.ReadUnaligned
test.RunLclVarScenario_UnsafeRead();
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class ScalarUnaryOpTest__TrailingZeroCountUInt64
{
private struct TestStruct
{
public UInt64 _fld;
public static TestStruct Create()
{
var testStruct = new TestStruct();
testStruct._fld = TestLibrary.Generator.GetUInt64();
return testStruct;
}
public void RunStructFldScenario(ScalarUnaryOpTest__TrailingZeroCountUInt64 testClass)
{
var result = Bmi1.X64.TrailingZeroCount(_fld);
testClass.ValidateResult(_fld, result);
}
}
private static UInt64 _data;
private static UInt64 _clsVar;
private UInt64 _fld;
static ScalarUnaryOpTest__TrailingZeroCountUInt64()
{
_clsVar = TestLibrary.Generator.GetUInt64();
}
public ScalarUnaryOpTest__TrailingZeroCountUInt64()
{
Succeeded = true;
_fld = TestLibrary.Generator.GetUInt64();
_data = TestLibrary.Generator.GetUInt64();
}
public bool IsSupported => Bmi1.X64.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Bmi1.X64.TrailingZeroCount(
Unsafe.ReadUnaligned<UInt64>(ref Unsafe.As<UInt64, byte>(ref _data))
);
ValidateResult(_data, result);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Bmi1.X64).GetMethod(nameof(Bmi1.X64.TrailingZeroCount), new Type[] { typeof(UInt64) })
.Invoke(null, new object[] {
Unsafe.ReadUnaligned<UInt64>(ref Unsafe.As<UInt64, byte>(ref _data))
});
ValidateResult(_data, (UInt64)result);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Bmi1.X64.TrailingZeroCount(
_clsVar
);
ValidateResult(_clsVar, result);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var data = Unsafe.ReadUnaligned<UInt64>(ref Unsafe.As<UInt64, byte>(ref _data));
var result = Bmi1.X64.TrailingZeroCount(data);
ValidateResult(data, result);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new ScalarUnaryOpTest__TrailingZeroCountUInt64();
var result = Bmi1.X64.TrailingZeroCount(test._fld);
ValidateResult(test._fld, result);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Bmi1.X64.TrailingZeroCount(_fld);
ValidateResult(_fld, result);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Bmi1.X64.TrailingZeroCount(test._fld);
ValidateResult(test._fld, result);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(UInt64 data, UInt64 result, [CallerMemberName] string method = "")
{
var isUnexpectedResult = false;
ulong expectedResult = 0; for (int index = 0; ((data >> index) & 1) == 0; index++) { expectedResult++; } isUnexpectedResult = (expectedResult != result);
if (isUnexpectedResult)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Bmi1.X64)}.{nameof(Bmi1.X64.TrailingZeroCount)}<UInt64>(UInt64): TrailingZeroCount failed:");
TestLibrary.TestFramework.LogInformation($" data: {data}");
TestLibrary.TestFramework.LogInformation($" result: {result}");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| mit |
publicloudapp/csrutil | linux-4.3/block/blk-mq.h | 3466 | #ifndef INT_BLK_MQ_H
#define INT_BLK_MQ_H
struct blk_mq_tag_set;
struct blk_mq_ctx {
struct {
spinlock_t lock;
struct list_head rq_list;
} ____cacheline_aligned_in_smp;
unsigned int cpu;
unsigned int index_hw;
unsigned int last_tag ____cacheline_aligned_in_smp;
/* incremented at dispatch time */
unsigned long rq_dispatched[2];
unsigned long rq_merged;
/* incremented at completion time */
unsigned long ____cacheline_aligned_in_smp rq_completed[2];
struct request_queue *queue;
struct kobject kobj;
} ____cacheline_aligned_in_smp;
void __blk_mq_complete_request(struct request *rq);
void blk_mq_run_hw_queue(struct blk_mq_hw_ctx *hctx, bool async);
void blk_mq_freeze_queue(struct request_queue *q);
void blk_mq_free_queue(struct request_queue *q);
void blk_mq_clone_flush_request(struct request *flush_rq,
struct request *orig_rq);
int blk_mq_update_nr_requests(struct request_queue *q, unsigned int nr);
void blk_mq_wake_waiters(struct request_queue *q);
/*
* CPU hotplug helpers
*/
struct blk_mq_cpu_notifier;
void blk_mq_init_cpu_notifier(struct blk_mq_cpu_notifier *notifier,
int (*fn)(void *, unsigned long, unsigned int),
void *data);
void blk_mq_register_cpu_notifier(struct blk_mq_cpu_notifier *notifier);
void blk_mq_unregister_cpu_notifier(struct blk_mq_cpu_notifier *notifier);
void blk_mq_cpu_init(void);
void blk_mq_enable_hotplug(void);
void blk_mq_disable_hotplug(void);
/*
* CPU -> queue mappings
*/
extern unsigned int *blk_mq_make_queue_map(struct blk_mq_tag_set *set);
extern int blk_mq_update_queue_map(unsigned int *map, unsigned int nr_queues,
const struct cpumask *online_mask);
extern int blk_mq_hw_queue_to_node(unsigned int *map, unsigned int);
/*
* sysfs helpers
*/
extern int blk_mq_sysfs_register(struct request_queue *q);
extern void blk_mq_sysfs_unregister(struct request_queue *q);
extern void blk_mq_rq_timed_out(struct request *req, bool reserved);
void blk_mq_release(struct request_queue *q);
/*
* Basic implementation of sparser bitmap, allowing the user to spread
* the bits over more cachelines.
*/
struct blk_align_bitmap {
unsigned long word;
unsigned long depth;
} ____cacheline_aligned_in_smp;
static inline struct blk_mq_ctx *__blk_mq_get_ctx(struct request_queue *q,
unsigned int cpu)
{
return per_cpu_ptr(q->queue_ctx, cpu);
}
/*
* This assumes per-cpu software queueing queues. They could be per-node
* as well, for instance. For now this is hardcoded as-is. Note that we don't
* care about preemption, since we know the ctx's are persistent. This does
* mean that we can't rely on ctx always matching the currently running CPU.
*/
static inline struct blk_mq_ctx *blk_mq_get_ctx(struct request_queue *q)
{
return __blk_mq_get_ctx(q, get_cpu());
}
static inline void blk_mq_put_ctx(struct blk_mq_ctx *ctx)
{
put_cpu();
}
struct blk_mq_alloc_data {
/* input parameter */
struct request_queue *q;
gfp_t gfp;
bool reserved;
/* input & output parameter */
struct blk_mq_ctx *ctx;
struct blk_mq_hw_ctx *hctx;
};
static inline void blk_mq_set_alloc_data(struct blk_mq_alloc_data *data,
struct request_queue *q, gfp_t gfp, bool reserved,
struct blk_mq_ctx *ctx,
struct blk_mq_hw_ctx *hctx)
{
data->q = q;
data->gfp = gfp;
data->reserved = reserved;
data->ctx = ctx;
data->hctx = hctx;
}
static inline bool blk_mq_hw_queue_mapped(struct blk_mq_hw_ctx *hctx)
{
return hctx->nr_ctx && hctx->tags;
}
#endif
| mit |
komejo/article-test | web/core/modules/toolbar/src/Controller/ToolbarController.php | 1674 | <?php
/**
* @file
* Contains \Drupal\toolbar\Controller\ToolbarController.
*/
namespace Drupal\toolbar\Controller;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Controller\ControllerBase;
use Drupal\toolbar\Ajax\SetSubtreesCommand;
/**
* Defines a controller for the toolbar module.
*/
class ToolbarController extends ControllerBase {
/**
* Returns an AJAX response to render the toolbar subtrees.
*
* @return \Drupal\Core\Ajax\AjaxResponse
*/
public function subtreesAjax() {
list($subtrees, $cacheability) = toolbar_get_rendered_subtrees();
$response = new AjaxResponse();
$response->addCommand(new SetSubtreesCommand($subtrees));
// The Expires HTTP header is the heart of the client-side HTTP caching. The
// additional server-side page cache only takes effect when the client
// accesses the callback URL again (e.g., after clearing the browser cache
// or when force-reloading a Drupal page).
$max_age = 365 * 24 * 60 * 60;
$response->setPrivate();
$response->setMaxAge($max_age);
$expires = new \DateTime();
$expires->setTimestamp(REQUEST_TIME + $max_age);
$response->setExpires($expires);
return $response;
}
/**
* Checks access for the subtree controller.
*
* @param string $hash
* The hash of the toolbar subtrees.
*
* @return \Drupal\Core\Access\AccessResultInterface
* The access result.
*/
public function checkSubTreeAccess($hash) {
return AccessResult::allowedIf($this->currentUser()->hasPermission('access toolbar') && $hash == _toolbar_get_subtrees_hash()[0])->cachePerPermissions();
}
}
| gpl-2.0 |
evalphobia/saas-ci-performance-compare-terraform | website/source/docs/providers/aws/r/cloudwatch_log_destination.html.markdown | 1203 | ---
layout: "aws"
page_title: "AWS: aws_cloudwatch_log_destination"
sidebar_current: "docs-aws-resource-cloudwatch-log-destination"
description: |-
Provides a CloudWatch Logs destination.
---
# aws\_cloudwatch\_log\_destination
Provides a CloudWatch Logs destination resource.
## Example Usage
```hcl
resource "aws_cloudwatch_log_destination" "test_destination" {
name = "test_destination"
role_arn = "${aws_iam_role.iam_for_cloudwatch.arn}"
target_arn = "${aws_kinesis_stream.kinesis_for_cloudwatch.arn}"
}
```
## Argument Reference
The following arguments are supported:
* `name` - (Required) A name for the log destination
* `role_arn` - (Required) The ARN of an IAM role that grants Amazon CloudWatch Logs permissions to put data into the target
* `target_arn` - (Required) The ARN of the target Amazon Kinesis stream or Amazon Lambda resource for the destination
## Attributes Reference
The following attributes are exported:
* `arn` - The Amazon Resource Name (ARN) specifying the log destination.
## Import
CloudWatch Logs destinations can be imported using the `name`, e.g.
```
$ terraform import aws_cloudwatch_log_destination.test_destination test_destination
```
| mpl-2.0 |
hgl888/web-testing-service | wts/tests/canvas/w3c/2d.pattern.repeat.case.html | 834 | <!DOCTYPE html>
<!-- DO NOT EDIT! This test has been generated by tools/gentest.py. -->
<title>Canvas test: 2d.pattern.repeat.case</title>
<meta name="author" content="Philip Taylor">
<script src="../../resources/testharness.js"></script>
<script src="../../resources/testharnessreport.js"></script>
<script src="common/canvas-tests.js"></script>
<link rel="stylesheet" href="common/canvas-tests.css">
<body class="show_output">
<h1>2d.pattern.repeat.case</h1>
<p class="desc"></p>
<p class="output">Actual output:</p>
<canvas id="c" class="output" width="100" height="50"><p class="fallback">FAIL (fallback content)</p></canvas>
<ul id="d"></ul>
<script>
var t = async_test("");
_addTest(function(canvas, ctx) {
assert_throws("SYNTAX_ERR", function() { ctx.createPattern(canvas, "Repeat"); });
_asserted = true;
});
</script>
| bsd-3-clause |
pcu4dros/pandora-core | workspace/lib/python3.5/site-packages/sqlalchemy/orm/exc.py | 5439 | # orm/exc.py
# Copyright (C) 2005-2016 the SQLAlchemy authors and contributors
# <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
"""SQLAlchemy ORM exceptions."""
from .. import exc as sa_exc, util
NO_STATE = (AttributeError, KeyError)
"""Exception types that may be raised by instrumentation implementations."""
class StaleDataError(sa_exc.SQLAlchemyError):
"""An operation encountered database state that is unaccounted for.
Conditions which cause this to happen include:
* A flush may have attempted to update or delete rows
and an unexpected number of rows were matched during
the UPDATE or DELETE statement. Note that when
version_id_col is used, rows in UPDATE or DELETE statements
are also matched against the current known version
identifier.
* A mapped object with version_id_col was refreshed,
and the version number coming back from the database does
not match that of the object itself.
* A object is detached from its parent object, however
the object was previously attached to a different parent
identity which was garbage collected, and a decision
cannot be made if the new parent was really the most
recent "parent".
.. versionadded:: 0.7.4
"""
ConcurrentModificationError = StaleDataError
class FlushError(sa_exc.SQLAlchemyError):
"""A invalid condition was detected during flush()."""
class UnmappedError(sa_exc.InvalidRequestError):
"""Base for exceptions that involve expected mappings not present."""
class ObjectDereferencedError(sa_exc.SQLAlchemyError):
"""An operation cannot complete due to an object being garbage
collected.
"""
class DetachedInstanceError(sa_exc.SQLAlchemyError):
"""An attempt to access unloaded attributes on a
mapped instance that is detached."""
class UnmappedInstanceError(UnmappedError):
"""An mapping operation was requested for an unknown instance."""
@util.dependencies("sqlalchemy.orm.base")
def __init__(self, base, obj, msg=None):
if not msg:
try:
base.class_mapper(type(obj))
name = _safe_cls_name(type(obj))
msg = ("Class %r is mapped, but this instance lacks "
"instrumentation. This occurs when the instance"
"is created before sqlalchemy.orm.mapper(%s) "
"was called." % (name, name))
except UnmappedClassError:
msg = _default_unmapped(type(obj))
if isinstance(obj, type):
msg += (
'; was a class (%s) supplied where an instance was '
'required?' % _safe_cls_name(obj))
UnmappedError.__init__(self, msg)
def __reduce__(self):
return self.__class__, (None, self.args[0])
class UnmappedClassError(UnmappedError):
"""An mapping operation was requested for an unknown class."""
def __init__(self, cls, msg=None):
if not msg:
msg = _default_unmapped(cls)
UnmappedError.__init__(self, msg)
def __reduce__(self):
return self.__class__, (None, self.args[0])
class ObjectDeletedError(sa_exc.InvalidRequestError):
"""A refresh operation failed to retrieve the database
row corresponding to an object's known primary key identity.
A refresh operation proceeds when an expired attribute is
accessed on an object, or when :meth:`.Query.get` is
used to retrieve an object which is, upon retrieval, detected
as expired. A SELECT is emitted for the target row
based on primary key; if no row is returned, this
exception is raised.
The true meaning of this exception is simply that
no row exists for the primary key identifier associated
with a persistent object. The row may have been
deleted, or in some cases the primary key updated
to a new value, outside of the ORM's management of the target
object.
"""
@util.dependencies("sqlalchemy.orm.base")
def __init__(self, base, state, msg=None):
if not msg:
msg = "Instance '%s' has been deleted, or its "\
"row is otherwise not present." % base.state_str(state)
sa_exc.InvalidRequestError.__init__(self, msg)
def __reduce__(self):
return self.__class__, (None, self.args[0])
class UnmappedColumnError(sa_exc.InvalidRequestError):
"""Mapping operation was requested on an unknown column."""
class NoResultFound(sa_exc.InvalidRequestError):
"""A database result was required but none was found."""
class MultipleResultsFound(sa_exc.InvalidRequestError):
"""A single database result was required but more than one were found."""
def _safe_cls_name(cls):
try:
cls_name = '.'.join((cls.__module__, cls.__name__))
except AttributeError:
cls_name = getattr(cls, '__name__', None)
if cls_name is None:
cls_name = repr(cls)
return cls_name
@util.dependencies("sqlalchemy.orm.base")
def _default_unmapped(base, cls):
try:
mappers = base.manager_of_class(cls).mappers
except NO_STATE:
mappers = {}
except TypeError:
mappers = {}
name = _safe_cls_name(cls)
if not mappers:
return "Class '%s' is not mapped" % name
| mit |
kgrygiel/autoscaler | vertical-pod-autoscaler/vendor/github.com/Azure/azure-sdk-for-go/arm/network/expressroutecircuitpeerings.go | 16778 | package network
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure"
"net/http"
)
// ExpressRouteCircuitPeeringsClient is the network Client
type ExpressRouteCircuitPeeringsClient struct {
ManagementClient
}
// NewExpressRouteCircuitPeeringsClient creates an instance of the ExpressRouteCircuitPeeringsClient client.
func NewExpressRouteCircuitPeeringsClient(subscriptionID string) ExpressRouteCircuitPeeringsClient {
return NewExpressRouteCircuitPeeringsClientWithBaseURI(DefaultBaseURI, subscriptionID)
}
// NewExpressRouteCircuitPeeringsClientWithBaseURI creates an instance of the ExpressRouteCircuitPeeringsClient client.
func NewExpressRouteCircuitPeeringsClientWithBaseURI(baseURI string, subscriptionID string) ExpressRouteCircuitPeeringsClient {
return ExpressRouteCircuitPeeringsClient{NewWithBaseURI(baseURI, subscriptionID)}
}
// CreateOrUpdate creates or updates a peering in the specified express route circuits. This method may poll for
// completion. Polling can be canceled by passing the cancel channel argument. The channel will be used to cancel
// polling and any outstanding HTTP requests.
//
// resourceGroupName is the name of the resource group. circuitName is the name of the express route circuit.
// peeringName is the name of the peering. peeringParameters is parameters supplied to the create or update express
// route circuit peering operation.
func (client ExpressRouteCircuitPeeringsClient) CreateOrUpdate(resourceGroupName string, circuitName string, peeringName string, peeringParameters ExpressRouteCircuitPeering, cancel <-chan struct{}) (<-chan ExpressRouteCircuitPeering, <-chan error) {
resultChan := make(chan ExpressRouteCircuitPeering, 1)
errChan := make(chan error, 1)
go func() {
var err error
var result ExpressRouteCircuitPeering
defer func() {
if err != nil {
errChan <- err
}
resultChan <- result
close(resultChan)
close(errChan)
}()
req, err := client.CreateOrUpdatePreparer(resourceGroupName, circuitName, peeringName, peeringParameters, cancel)
if err != nil {
err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "CreateOrUpdate", nil, "Failure preparing request")
return
}
resp, err := client.CreateOrUpdateSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "CreateOrUpdate", resp, "Failure sending request")
return
}
result, err = client.CreateOrUpdateResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "CreateOrUpdate", resp, "Failure responding to request")
}
}()
return resultChan, errChan
}
// CreateOrUpdatePreparer prepares the CreateOrUpdate request.
func (client ExpressRouteCircuitPeeringsClient) CreateOrUpdatePreparer(resourceGroupName string, circuitName string, peeringName string, peeringParameters ExpressRouteCircuitPeering, cancel <-chan struct{}) (*http.Request, error) {
pathParameters := map[string]interface{}{
"circuitName": autorest.Encode("path", circuitName),
"peeringName": autorest.Encode("path", peeringName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2017-09-01"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsJSON(),
autorest.AsPut(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/peerings/{peeringName}", pathParameters),
autorest.WithJSON(peeringParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare(&http.Request{Cancel: cancel})
}
// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the
// http.Response Body if it receives an error.
func (client ExpressRouteCircuitPeeringsClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client,
req,
azure.DoRetryWithRegistration(client.Client),
azure.DoPollForAsynchronous(client.PollingDelay))
}
// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always
// closes the http.Response Body.
func (client ExpressRouteCircuitPeeringsClient) CreateOrUpdateResponder(resp *http.Response) (result ExpressRouteCircuitPeering, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// Delete deletes the specified peering from the specified express route circuit. This method may poll for completion.
// Polling can be canceled by passing the cancel channel argument. The channel will be used to cancel polling and any
// outstanding HTTP requests.
//
// resourceGroupName is the name of the resource group. circuitName is the name of the express route circuit.
// peeringName is the name of the peering.
func (client ExpressRouteCircuitPeeringsClient) Delete(resourceGroupName string, circuitName string, peeringName string, cancel <-chan struct{}) (<-chan autorest.Response, <-chan error) {
resultChan := make(chan autorest.Response, 1)
errChan := make(chan error, 1)
go func() {
var err error
var result autorest.Response
defer func() {
if err != nil {
errChan <- err
}
resultChan <- result
close(resultChan)
close(errChan)
}()
req, err := client.DeletePreparer(resourceGroupName, circuitName, peeringName, cancel)
if err != nil {
err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "Delete", nil, "Failure preparing request")
return
}
resp, err := client.DeleteSender(req)
if err != nil {
result.Response = resp
err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "Delete", resp, "Failure sending request")
return
}
result, err = client.DeleteResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "Delete", resp, "Failure responding to request")
}
}()
return resultChan, errChan
}
// DeletePreparer prepares the Delete request.
func (client ExpressRouteCircuitPeeringsClient) DeletePreparer(resourceGroupName string, circuitName string, peeringName string, cancel <-chan struct{}) (*http.Request, error) {
pathParameters := map[string]interface{}{
"circuitName": autorest.Encode("path", circuitName),
"peeringName": autorest.Encode("path", peeringName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2017-09-01"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsDelete(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/peerings/{peeringName}", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare(&http.Request{Cancel: cancel})
}
// DeleteSender sends the Delete request. The method will close the
// http.Response Body if it receives an error.
func (client ExpressRouteCircuitPeeringsClient) DeleteSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client,
req,
azure.DoRetryWithRegistration(client.Client),
azure.DoPollForAsynchronous(client.PollingDelay))
}
// DeleteResponder handles the response to the Delete request. The method always
// closes the http.Response Body.
func (client ExpressRouteCircuitPeeringsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent),
autorest.ByClosing())
result.Response = resp
return
}
// Get gets the specified authorization from the specified express route circuit.
//
// resourceGroupName is the name of the resource group. circuitName is the name of the express route circuit.
// peeringName is the name of the peering.
func (client ExpressRouteCircuitPeeringsClient) Get(resourceGroupName string, circuitName string, peeringName string) (result ExpressRouteCircuitPeering, err error) {
req, err := client.GetPreparer(resourceGroupName, circuitName, peeringName)
if err != nil {
err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "Get", nil, "Failure preparing request")
return
}
resp, err := client.GetSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "Get", resp, "Failure sending request")
return
}
result, err = client.GetResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "Get", resp, "Failure responding to request")
}
return
}
// GetPreparer prepares the Get request.
func (client ExpressRouteCircuitPeeringsClient) GetPreparer(resourceGroupName string, circuitName string, peeringName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"circuitName": autorest.Encode("path", circuitName),
"peeringName": autorest.Encode("path", peeringName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2017-09-01"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/peerings/{peeringName}", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare(&http.Request{})
}
// GetSender sends the Get request. The method will close the
// http.Response Body if it receives an error.
func (client ExpressRouteCircuitPeeringsClient) GetSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client,
req,
azure.DoRetryWithRegistration(client.Client))
}
// GetResponder handles the response to the Get request. The method always
// closes the http.Response Body.
func (client ExpressRouteCircuitPeeringsClient) GetResponder(resp *http.Response) (result ExpressRouteCircuitPeering, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// List gets all peerings in a specified express route circuit.
//
// resourceGroupName is the name of the resource group. circuitName is the name of the express route circuit.
func (client ExpressRouteCircuitPeeringsClient) List(resourceGroupName string, circuitName string) (result ExpressRouteCircuitPeeringListResult, err error) {
req, err := client.ListPreparer(resourceGroupName, circuitName)
if err != nil {
err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "List", nil, "Failure preparing request")
return
}
resp, err := client.ListSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "List", resp, "Failure sending request")
return
}
result, err = client.ListResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "List", resp, "Failure responding to request")
}
return
}
// ListPreparer prepares the List request.
func (client ExpressRouteCircuitPeeringsClient) ListPreparer(resourceGroupName string, circuitName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"circuitName": autorest.Encode("path", circuitName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2017-09-01"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/peerings", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare(&http.Request{})
}
// ListSender sends the List request. The method will close the
// http.Response Body if it receives an error.
func (client ExpressRouteCircuitPeeringsClient) ListSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client,
req,
azure.DoRetryWithRegistration(client.Client))
}
// ListResponder handles the response to the List request. The method always
// closes the http.Response Body.
func (client ExpressRouteCircuitPeeringsClient) ListResponder(resp *http.Response) (result ExpressRouteCircuitPeeringListResult, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// ListNextResults retrieves the next set of results, if any.
func (client ExpressRouteCircuitPeeringsClient) ListNextResults(lastResults ExpressRouteCircuitPeeringListResult) (result ExpressRouteCircuitPeeringListResult, err error) {
req, err := lastResults.ExpressRouteCircuitPeeringListResultPreparer()
if err != nil {
return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "List", nil, "Failure preparing next results request")
}
if req == nil {
return
}
resp, err := client.ListSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "List", resp, "Failure sending next results request")
}
result, err = client.ListResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "List", resp, "Failure responding to next results request")
}
return
}
// ListComplete gets all elements from the list without paging.
func (client ExpressRouteCircuitPeeringsClient) ListComplete(resourceGroupName string, circuitName string, cancel <-chan struct{}) (<-chan ExpressRouteCircuitPeering, <-chan error) {
resultChan := make(chan ExpressRouteCircuitPeering)
errChan := make(chan error, 1)
go func() {
defer func() {
close(resultChan)
close(errChan)
}()
list, err := client.List(resourceGroupName, circuitName)
if err != nil {
errChan <- err
return
}
if list.Value != nil {
for _, item := range *list.Value {
select {
case <-cancel:
return
case resultChan <- item:
// Intentionally left blank
}
}
}
for list.NextLink != nil {
list, err = client.ListNextResults(list)
if err != nil {
errChan <- err
return
}
if list.Value != nil {
for _, item := range *list.Value {
select {
case <-cancel:
return
case resultChan <- item:
// Intentionally left blank
}
}
}
}
}()
return resultChan, errChan
}
| apache-2.0 |
cgvarela/chef | spec/unit/windows_service_spec.rb | 3344 | #
# Author:: Mukta Aphale (<[email protected]>)
# Copyright:: Copyright (c) 2013 Opscode, Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'spec_helper'
if Chef::Platform.windows?
require 'chef/application/windows_service'
end
describe "Chef::Application::WindowsService", :windows_only do
let (:instance) {Chef::Application::WindowsService.new}
let (:shell_out_result) {Object.new}
let (:tempfile) {Tempfile.new "log_file"}
before do
allow(instance).to receive(:parse_options)
allow(shell_out_result).to receive(:stdout)
allow(shell_out_result).to receive(:stderr)
end
it "runs chef-client in new process" do
expect(instance).to receive(:configure_chef).twice
instance.service_init
expect(instance).to receive(:run_chef_client).and_call_original
expect(instance).to receive(:shell_out).and_return(shell_out_result)
allow(instance).to receive(:running?).and_return(true, false)
allow(instance.instance_variable_get(:@service_signal)).to receive(:wait)
allow(instance).to receive(:state).and_return(4)
instance.service_main
end
context 'when running chef-client' do
it "passes config params to new process with a default timeout of 2 hours (7200 seconds)" do
Chef::Config.merge!({:log_location => tempfile.path, :config_file => "test_config_file", :log_level => :info})
expect(instance).to receive(:configure_chef).twice
instance.service_init
allow(instance).to receive(:running?).and_return(true, false)
allow(instance.instance_variable_get(:@service_signal)).to receive(:wait)
allow(instance).to receive(:state).and_return(4)
expect(instance).to receive(:run_chef_client).and_call_original
expect(instance).to receive(:shell_out).with("chef-client --no-fork -c test_config_file -L #{tempfile.path}", {:timeout => 7200}).and_return(shell_out_result)
instance.service_main
tempfile.unlink
end
it "passes config params to new process with a the timeout specified in the config" do
Chef::Config.merge!({:log_location => tempfile.path, :config_file => "test_config_file", :log_level => :info})
Chef::Config[:windows_service][:watchdog_timeout] = 10
expect(instance).to receive(:configure_chef).twice
instance.service_init
allow(instance).to receive(:running?).and_return(true, false)
allow(instance.instance_variable_get(:@service_signal)).to receive(:wait)
allow(instance).to receive(:state).and_return(4)
expect(instance).to receive(:run_chef_client).and_call_original
expect(instance).to receive(:shell_out).with("chef-client --no-fork -c test_config_file -L #{tempfile.path}", {:timeout => 10}).and_return(shell_out_result)
instance.service_main
tempfile.unlink
end
end
end
| apache-2.0 |
mahak/spark | mllib/src/test/scala/org/apache/spark/ml/tree/impl/TreePointSuite.scala | 1433 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.spark.ml.tree.impl
import org.apache.spark.{SparkConf, SparkFunSuite}
import org.apache.spark.internal.config.Kryo._
import org.apache.spark.serializer.KryoSerializer
class TreePointSuite extends SparkFunSuite {
test("Kryo class register") {
val conf = new SparkConf(false)
conf.set(KRYO_REGISTRATION_REQUIRED, true)
val ser = new KryoSerializer(conf).newInstance()
val point = new TreePoint(1.0, Array(1, 2, 3), 1.0)
val point2 = ser.deserialize[TreePoint](ser.serialize(point))
assert(point.label === point2.label)
assert(point.binnedFeatures === point2.binnedFeatures)
}
}
| apache-2.0 |
asedunov/intellij-community | xml/dom-openapi/src/com/intellij/util/xml/DomNameStrategy.java | 1707 | /*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.util.xml;
/**
* Specifies how method names are converted into XML element names
*
* @author peter
* @see NameStrategy
* @see NameStrategyForAttributes
*/
public abstract class DomNameStrategy {
/**
* @param propertyName property name, i.e. method name without first 'get', 'set' or 'is'
* @return XML element name
*/
public abstract String convertName(String propertyName);
/**
* Is used to get presentable DOM elements in UI
* @param xmlElementName XML element name
* @return Presentable DOM element name
*/
public abstract String splitIntoWords(final String xmlElementName);
/**
* This strategy splits property name into words, decapitalizes them and joins using hyphen as separator,
* e.g. getXmlElementName() will correspond to xml-element-name
*/
public static final DomNameStrategy HYPHEN_STRATEGY = new HyphenNameStrategy();
/**
* This strategy decapitalizes property name, e.g. getXmlElementName() will correspond to xmlElementName
*/
public static final DomNameStrategy JAVA_STRATEGY = new JavaNameStrategy();
}
| apache-2.0 |
bengoodger/lemonaid | web/bower_components/polymer-gestures/test/runner.html | 1197 | <!DOCTYPE html>
<!--
Copyright (c) 2014 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
-->
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Polymer Gestures test runner</title>
<!-- Mocha -->
<link rel="stylesheet" href="../../tools/test/mocha/mocha.css">
<script src="../../tools/test/mocha/mocha.js"></script>
<!-- Chai -->
<script src="../../tools/test/chai/chai.js"></script>
<script src="../polymer-gestures.js"></script>
<script src="js/setup.js"></script>
<script src="js/fake.js"></script>
<!-- Tests -->
<script src="js/pointermap.js"></script>
<script src="js/eventListeners.js"></script>
<script src="js/gestures.js"></script>
</head>
<body>
<div id="mocha"></div>
<script>
mocha.run();
</script>
</body>
</html>
| bsd-2-clause |
nusendra/nusendra-blog | vendor/phpunit/phpunit/tests/end-to-end/phar-extension.phpt | 597 | --TEST--
phpunit --configuration tests/_files/phpunit-example-extension
--FILE--
<?php
$_SERVER['argv'][1] = '--configuration';
$_SERVER['argv'][2] = __DIR__ . '/../_files/phpunit-example-extension';
require __DIR__ . '/../bootstrap.php';
PHPUnit\TextUI\Command::main();
--EXPECTF--
PHPUnit %s by Sebastian Bergmann and contributors.
Runtime: %s
Configuration: %s%ephpunit-example-extension%ephpunit.xml
Extension: phpunit/phpunit-example-extension 1.0.1
. 1 / 1 (100%)
Time: %s, Memory: %s
OK (1 test, 1 assertion)
| mit |
philiplb/flynn | vendor/github.com/docker/distribution/registry/storage/paths.go | 16435 | package storage
import (
"fmt"
"path"
"strings"
"github.com/docker/distribution/digest"
)
const storagePathVersion = "v2"
// pathMapper maps paths based on "object names" and their ids. The "object
// names" mapped by pathMapper are internal to the storage system.
//
// The path layout in the storage backend is roughly as follows:
//
// <root>/v2
// -> repositories/
// -><name>/
// -> _manifests/
// revisions
// -> <manifest digest path>
// -> link
// -> signatures
// <algorithm>/<digest>/link
// tags/<tag>
// -> current/link
// -> index
// -> <algorithm>/<hex digest>/link
// -> _layers/
// <layer links to blob store>
// -> _uploads/<id>
// data
// startedat
// hashstates/<algorithm>/<offset>
// -> blob/<algorithm>
// <split directory content addressable storage>
//
// The storage backend layout is broken up into a content- addressable blob
// store and repositories. The content-addressable blob store holds most data
// throughout the backend, keyed by algorithm and digests of the underlying
// content. Access to the blob store is controled through links from the
// repository to blobstore.
//
// A repository is made up of layers, manifests and tags. The layers component
// is just a directory of layers which are "linked" into a repository. A layer
// can only be accessed through a qualified repository name if it is linked in
// the repository. Uploads of layers are managed in the uploads directory,
// which is key by upload id. When all data for an upload is received, the
// data is moved into the blob store and the upload directory is deleted.
// Abandoned uploads can be garbage collected by reading the startedat file
// and removing uploads that have been active for longer than a certain time.
//
// The third component of the repository directory is the manifests store,
// which is made up of a revision store and tag store. Manifests are stored in
// the blob store and linked into the revision store. Signatures are separated
// from the manifest payload data and linked into the blob store, as well.
// While the registry can save all revisions of a manifest, no relationship is
// implied as to the ordering of changes to a manifest. The tag store provides
// support for name, tag lookups of manifests, using "current/link" under a
// named tag directory. An index is maintained to support deletions of all
// revisions of a given manifest tag.
//
// We cover the path formats implemented by this path mapper below.
//
// Manifests:
//
// manifestRevisionPathSpec: <root>/v2/repositories/<name>/_manifests/revisions/<algorithm>/<hex digest>/
// manifestRevisionLinkPathSpec: <root>/v2/repositories/<name>/_manifests/revisions/<algorithm>/<hex digest>/link
// manifestSignaturesPathSpec: <root>/v2/repositories/<name>/_manifests/revisions/<algorithm>/<hex digest>/signatures/
// manifestSignatureLinkPathSpec: <root>/v2/repositories/<name>/_manifests/revisions/<algorithm>/<hex digest>/signatures/<algorithm>/<hex digest>/link
//
// Tags:
//
// manifestTagsPathSpec: <root>/v2/repositories/<name>/_manifests/tags/
// manifestTagPathSpec: <root>/v2/repositories/<name>/_manifests/tags/<tag>/
// manifestTagCurrentPathSpec: <root>/v2/repositories/<name>/_manifests/tags/<tag>/current/link
// manifestTagIndexPathSpec: <root>/v2/repositories/<name>/_manifests/tags/<tag>/index/
// manifestTagIndexEntryPathSpec: <root>/v2/repositories/<name>/_manifests/tags/<tag>/index/<algorithm>/<hex digest>/
// manifestTagIndexEntryLinkPathSpec: <root>/v2/repositories/<name>/_manifests/tags/<tag>/index/<algorithm>/<hex digest>/link
//
// Blobs:
//
// layerLinkPathSpec: <root>/v2/repositories/<name>/_layers/<algorithm>/<hex digest>/link
//
// Uploads:
//
// uploadDataPathSpec: <root>/v2/repositories/<name>/_uploads/<id>/data
// uploadStartedAtPathSpec: <root>/v2/repositories/<name>/_uploads/<id>/startedat
// uploadHashStatePathSpec: <root>/v2/repositories/<name>/_uploads/<id>/hashstates/<algorithm>/<offset>
//
// Blob Store:
//
// blobPathSpec: <root>/v2/blobs/<algorithm>/<first two hex bytes of digest>/<hex digest>
// blobDataPathSpec: <root>/v2/blobs/<algorithm>/<first two hex bytes of digest>/<hex digest>/data
// blobMediaTypePathSpec: <root>/v2/blobs/<algorithm>/<first two hex bytes of digest>/<hex digest>/data
//
// For more information on the semantic meaning of each path and their
// contents, please see the path spec documentation.
type pathMapper struct {
root string
version string // should be a constant?
}
var defaultPathMapper = &pathMapper{
root: "/docker/registry/",
version: storagePathVersion,
}
// path returns the path identified by spec.
func (pm *pathMapper) path(spec pathSpec) (string, error) {
// Switch on the path object type and return the appropriate path. At
// first glance, one may wonder why we don't use an interface to
// accomplish this. By keep the formatting separate from the pathSpec, we
// keep separate the path generation componentized. These specs could be
// passed to a completely different mapper implementation and generate a
// different set of paths.
//
// For example, imagine migrating from one backend to the other: one could
// build a filesystem walker that converts a string path in one version,
// to an intermediate path object, than can be consumed and mapped by the
// other version.
rootPrefix := []string{pm.root, pm.version}
repoPrefix := append(rootPrefix, "repositories")
switch v := spec.(type) {
case manifestRevisionPathSpec:
components, err := digestPathComponents(v.revision, false)
if err != nil {
return "", err
}
return path.Join(append(append(repoPrefix, v.name, "_manifests", "revisions"), components...)...), nil
case manifestRevisionLinkPathSpec:
root, err := pm.path(manifestRevisionPathSpec{
name: v.name,
revision: v.revision,
})
if err != nil {
return "", err
}
return path.Join(root, "link"), nil
case manifestSignaturesPathSpec:
root, err := pm.path(manifestRevisionPathSpec{
name: v.name,
revision: v.revision,
})
if err != nil {
return "", err
}
return path.Join(root, "signatures"), nil
case manifestSignatureLinkPathSpec:
root, err := pm.path(manifestSignaturesPathSpec{
name: v.name,
revision: v.revision,
})
if err != nil {
return "", err
}
signatureComponents, err := digestPathComponents(v.signature, false)
if err != nil {
return "", err
}
return path.Join(root, path.Join(append(signatureComponents, "link")...)), nil
case manifestTagsPathSpec:
return path.Join(append(repoPrefix, v.name, "_manifests", "tags")...), nil
case manifestTagPathSpec:
root, err := pm.path(manifestTagsPathSpec{
name: v.name,
})
if err != nil {
return "", err
}
return path.Join(root, v.tag), nil
case manifestTagCurrentPathSpec:
root, err := pm.path(manifestTagPathSpec{
name: v.name,
tag: v.tag,
})
if err != nil {
return "", err
}
return path.Join(root, "current", "link"), nil
case manifestTagIndexPathSpec:
root, err := pm.path(manifestTagPathSpec{
name: v.name,
tag: v.tag,
})
if err != nil {
return "", err
}
return path.Join(root, "index"), nil
case manifestTagIndexEntryLinkPathSpec:
root, err := pm.path(manifestTagIndexEntryPathSpec{
name: v.name,
tag: v.tag,
revision: v.revision,
})
if err != nil {
return "", err
}
return path.Join(root, "link"), nil
case manifestTagIndexEntryPathSpec:
root, err := pm.path(manifestTagIndexPathSpec{
name: v.name,
tag: v.tag,
})
if err != nil {
return "", err
}
components, err := digestPathComponents(v.revision, false)
if err != nil {
return "", err
}
return path.Join(root, path.Join(components...)), nil
case layerLinkPathSpec:
components, err := digestPathComponents(v.digest, false)
if err != nil {
return "", err
}
// TODO(stevvooe): Right now, all blobs are linked under "_layers". If
// we have future migrations, we may want to rename this to "_blobs".
// A migration strategy would simply leave existing items in place and
// write the new paths, commit a file then delete the old files.
blobLinkPathComponents := append(repoPrefix, v.name, "_layers")
return path.Join(path.Join(append(blobLinkPathComponents, components...)...), "link"), nil
case blobDataPathSpec:
components, err := digestPathComponents(v.digest, true)
if err != nil {
return "", err
}
components = append(components, "data")
blobPathPrefix := append(rootPrefix, "blobs")
return path.Join(append(blobPathPrefix, components...)...), nil
case uploadDataPathSpec:
return path.Join(append(repoPrefix, v.name, "_uploads", v.id, "data")...), nil
case uploadStartedAtPathSpec:
return path.Join(append(repoPrefix, v.name, "_uploads", v.id, "startedat")...), nil
case uploadHashStatePathSpec:
offset := fmt.Sprintf("%d", v.offset)
if v.list {
offset = "" // Limit to the prefix for listing offsets.
}
return path.Join(append(repoPrefix, v.name, "_uploads", v.id, "hashstates", string(v.alg), offset)...), nil
case repositoriesRootPathSpec:
return path.Join(repoPrefix...), nil
default:
// TODO(sday): This is an internal error. Ensure it doesn't escape (panic?).
return "", fmt.Errorf("unknown path spec: %#v", v)
}
}
// pathSpec is a type to mark structs as path specs. There is no
// implementation because we'd like to keep the specs and the mappers
// decoupled.
type pathSpec interface {
pathSpec()
}
// manifestRevisionPathSpec describes the components of the directory path for
// a manifest revision.
type manifestRevisionPathSpec struct {
name string
revision digest.Digest
}
func (manifestRevisionPathSpec) pathSpec() {}
// manifestRevisionLinkPathSpec describes the path components required to look
// up the data link for a revision of a manifest. If this file is not present,
// the manifest blob is not available in the given repo. The contents of this
// file should just be the digest.
type manifestRevisionLinkPathSpec struct {
name string
revision digest.Digest
}
func (manifestRevisionLinkPathSpec) pathSpec() {}
// manifestSignaturesPathSpec decribes the path components for the directory
// containing all the signatures for the target blob. Entries are named with
// the underlying key id.
type manifestSignaturesPathSpec struct {
name string
revision digest.Digest
}
func (manifestSignaturesPathSpec) pathSpec() {}
// manifestSignatureLinkPathSpec decribes the path components used to look up
// a signature file by the hash of its blob.
type manifestSignatureLinkPathSpec struct {
name string
revision digest.Digest
signature digest.Digest
}
func (manifestSignatureLinkPathSpec) pathSpec() {}
// manifestTagsPathSpec describes the path elements required to point to the
// manifest tags directory.
type manifestTagsPathSpec struct {
name string
}
func (manifestTagsPathSpec) pathSpec() {}
// manifestTagPathSpec describes the path elements required to point to the
// manifest tag links files under a repository. These contain a blob id that
// can be used to look up the data and signatures.
type manifestTagPathSpec struct {
name string
tag string
}
func (manifestTagPathSpec) pathSpec() {}
// manifestTagCurrentPathSpec describes the link to the current revision for a
// given tag.
type manifestTagCurrentPathSpec struct {
name string
tag string
}
func (manifestTagCurrentPathSpec) pathSpec() {}
// manifestTagCurrentPathSpec describes the link to the index of revisions
// with the given tag.
type manifestTagIndexPathSpec struct {
name string
tag string
}
func (manifestTagIndexPathSpec) pathSpec() {}
// manifestTagIndexEntryPathSpec contains the entries of the index by revision.
type manifestTagIndexEntryPathSpec struct {
name string
tag string
revision digest.Digest
}
func (manifestTagIndexEntryPathSpec) pathSpec() {}
// manifestTagIndexEntryLinkPathSpec describes the link to a revisions of a
// manifest with given tag within the index.
type manifestTagIndexEntryLinkPathSpec struct {
name string
tag string
revision digest.Digest
}
func (manifestTagIndexEntryLinkPathSpec) pathSpec() {}
// blobLinkPathSpec specifies a path for a blob link, which is a file with a
// blob id. The blob link will contain a content addressable blob id reference
// into the blob store. The format of the contents is as follows:
//
// <algorithm>:<hex digest of layer data>
//
// The following example of the file contents is more illustrative:
//
// sha256:96443a84ce518ac22acb2e985eda402b58ac19ce6f91980bde63726a79d80b36
//
// This indicates that there is a blob with the id/digest, calculated via
// sha256 that can be fetched from the blob store.
type layerLinkPathSpec struct {
name string
digest digest.Digest
}
func (layerLinkPathSpec) pathSpec() {}
// blobAlgorithmReplacer does some very simple path sanitization for user
// input. Mostly, this is to provide some hierarchy for tarsum digests. Paths
// should be "safe" before getting this far due to strict digest requirements
// but we can add further path conversion here, if needed.
var blobAlgorithmReplacer = strings.NewReplacer(
"+", "/",
".", "/",
";", "/",
)
// // blobPathSpec contains the path for the registry global blob store.
// type blobPathSpec struct {
// digest digest.Digest
// }
// func (blobPathSpec) pathSpec() {}
// blobDataPathSpec contains the path for the registry global blob store. For
// now, this contains layer data, exclusively.
type blobDataPathSpec struct {
digest digest.Digest
}
func (blobDataPathSpec) pathSpec() {}
// uploadDataPathSpec defines the path parameters of the data file for
// uploads.
type uploadDataPathSpec struct {
name string
id string
}
func (uploadDataPathSpec) pathSpec() {}
// uploadDataPathSpec defines the path parameters for the file that stores the
// start time of an uploads. If it is missing, the upload is considered
// unknown. Admittedly, the presence of this file is an ugly hack to make sure
// we have a way to cleanup old or stalled uploads that doesn't rely on driver
// FileInfo behavior. If we come up with a more clever way to do this, we
// should remove this file immediately and rely on the startetAt field from
// the client to enforce time out policies.
type uploadStartedAtPathSpec struct {
name string
id string
}
func (uploadStartedAtPathSpec) pathSpec() {}
// uploadHashStatePathSpec defines the path parameters for the file that stores
// the hash function state of an upload at a specific byte offset. If `list` is
// set, then the path mapper will generate a list prefix for all hash state
// offsets for the upload identified by the name, id, and alg.
type uploadHashStatePathSpec struct {
name string
id string
alg digest.Algorithm
offset int64
list bool
}
func (uploadHashStatePathSpec) pathSpec() {}
// repositoriesRootPathSpec returns the root of repositories
type repositoriesRootPathSpec struct {
}
func (repositoriesRootPathSpec) pathSpec() {}
// digestPathComponents provides a consistent path breakdown for a given
// digest. For a generic digest, it will be as follows:
//
// <algorithm>/<hex digest>
//
// Most importantly, for tarsum, the layout looks like this:
//
// tarsum/<version>/<digest algorithm>/<full digest>
//
// If multilevel is true, the first two bytes of the digest will separate
// groups of digest folder. It will be as follows:
//
// <algorithm>/<first two bytes of digest>/<full digest>
//
func digestPathComponents(dgst digest.Digest, multilevel bool) ([]string, error) {
if err := dgst.Validate(); err != nil {
return nil, err
}
algorithm := blobAlgorithmReplacer.Replace(string(dgst.Algorithm()))
hex := dgst.Hex()
prefix := []string{algorithm}
var suffix []string
if multilevel {
suffix = append(suffix, hex[:2])
}
suffix = append(suffix, hex)
if tsi, err := digest.ParseTarSum(dgst.String()); err == nil {
// We have a tarsum!
version := tsi.Version
if version == "" {
version = "v0"
}
prefix = []string{
"tarsum",
version,
tsi.Algorithm,
}
}
return append(prefix, suffix...), nil
}
| bsd-3-clause |
drod2169/KernelSanders-OMAP | tools/prebuilt/ndk/android-ndk-r8/platforms/android-9/arch-x86/usr/include/linux/netfilter/nfnetlink_conntrack.h | 3087 | /****************************************************************************
****************************************************************************
***
*** This header was automatically generated from a Linux kernel header
*** of the same name, to make information necessary for userspace to
*** call into the kernel available to libc. It contains only constants,
*** structures, and macros generated from the original header, and thus,
*** contains no copyrightable information.
***
****************************************************************************
****************************************************************************/
#ifndef _IPCONNTRACK_NETLINK_H
#define _IPCONNTRACK_NETLINK_H
#include <linux/netfilter/nfnetlink.h>
enum cntl_msg_types {
IPCTNL_MSG_CT_NEW,
IPCTNL_MSG_CT_GET,
IPCTNL_MSG_CT_DELETE,
IPCTNL_MSG_CT_GET_CTRZERO,
IPCTNL_MSG_MAX
};
enum ctnl_exp_msg_types {
IPCTNL_MSG_EXP_NEW,
IPCTNL_MSG_EXP_GET,
IPCTNL_MSG_EXP_DELETE,
IPCTNL_MSG_EXP_MAX
};
enum ctattr_type {
CTA_UNSPEC,
CTA_TUPLE_ORIG,
CTA_TUPLE_REPLY,
CTA_STATUS,
CTA_PROTOINFO,
CTA_HELP,
CTA_NAT_SRC,
#define CTA_NAT CTA_NAT_SRC
CTA_TIMEOUT,
CTA_MARK,
CTA_COUNTERS_ORIG,
CTA_COUNTERS_REPLY,
CTA_USE,
CTA_ID,
CTA_NAT_DST,
__CTA_MAX
};
#define CTA_MAX (__CTA_MAX - 1)
enum ctattr_tuple {
CTA_TUPLE_UNSPEC,
CTA_TUPLE_IP,
CTA_TUPLE_PROTO,
__CTA_TUPLE_MAX
};
#define CTA_TUPLE_MAX (__CTA_TUPLE_MAX - 1)
enum ctattr_ip {
CTA_IP_UNSPEC,
CTA_IP_V4_SRC,
CTA_IP_V4_DST,
CTA_IP_V6_SRC,
CTA_IP_V6_DST,
__CTA_IP_MAX
};
#define CTA_IP_MAX (__CTA_IP_MAX - 1)
enum ctattr_l4proto {
CTA_PROTO_UNSPEC,
CTA_PROTO_NUM,
CTA_PROTO_SRC_PORT,
CTA_PROTO_DST_PORT,
CTA_PROTO_ICMP_ID,
CTA_PROTO_ICMP_TYPE,
CTA_PROTO_ICMP_CODE,
CTA_PROTO_ICMPV6_ID,
CTA_PROTO_ICMPV6_TYPE,
CTA_PROTO_ICMPV6_CODE,
__CTA_PROTO_MAX
};
#define CTA_PROTO_MAX (__CTA_PROTO_MAX - 1)
enum ctattr_protoinfo {
CTA_PROTOINFO_UNSPEC,
CTA_PROTOINFO_TCP,
__CTA_PROTOINFO_MAX
};
#define CTA_PROTOINFO_MAX (__CTA_PROTOINFO_MAX - 1)
enum ctattr_protoinfo_tcp {
CTA_PROTOINFO_TCP_UNSPEC,
CTA_PROTOINFO_TCP_STATE,
__CTA_PROTOINFO_TCP_MAX
};
#define CTA_PROTOINFO_TCP_MAX (__CTA_PROTOINFO_TCP_MAX - 1)
enum ctattr_counters {
CTA_COUNTERS_UNSPEC,
CTA_COUNTERS_PACKETS,
CTA_COUNTERS_BYTES,
CTA_COUNTERS32_PACKETS,
CTA_COUNTERS32_BYTES,
__CTA_COUNTERS_MAX
};
#define CTA_COUNTERS_MAX (__CTA_COUNTERS_MAX - 1)
enum ctattr_nat {
CTA_NAT_UNSPEC,
CTA_NAT_MINIP,
CTA_NAT_MAXIP,
CTA_NAT_PROTO,
__CTA_NAT_MAX
};
#define CTA_NAT_MAX (__CTA_NAT_MAX - 1)
enum ctattr_protonat {
CTA_PROTONAT_UNSPEC,
CTA_PROTONAT_PORT_MIN,
CTA_PROTONAT_PORT_MAX,
__CTA_PROTONAT_MAX
};
#define CTA_PROTONAT_MAX (__CTA_PROTONAT_MAX - 1)
enum ctattr_expect {
CTA_EXPECT_UNSPEC,
CTA_EXPECT_MASTER,
CTA_EXPECT_TUPLE,
CTA_EXPECT_MASK,
CTA_EXPECT_TIMEOUT,
CTA_EXPECT_ID,
CTA_EXPECT_HELP_NAME,
__CTA_EXPECT_MAX
};
#define CTA_EXPECT_MAX (__CTA_EXPECT_MAX - 1)
enum ctattr_help {
CTA_HELP_UNSPEC,
CTA_HELP_NAME,
__CTA_HELP_MAX
};
#define CTA_HELP_MAX (__CTA_HELP_MAX - 1)
#endif
| gpl-2.0 |
Piicksarn/cdnjs | ajax/libs/yui/3.4.0pr2/datatype/lang/datatype-date_zh-Hant-HK.js | 717 | YUI.add("lang/datatype-date-format_zh-Hant-HK",function(a){a.Intl.add("datatype-date-format","zh-Hant-HK",{"a":["週日","週一","週二","週三","週四","週五","週六"],"A":["星期日","星期一","星期二","星期三","星期四","星期五","星期六"],"b":["1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"],"B":["1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"],"c":"%Y年%b%d日%a%Z%p%l時%M分%S秒","p":["上午","下午"],"P":["上午","下午"],"x":"%y年%m月%d日","X":"%p%l時%M分%S秒"});},"@VERSION@");YUI.add("lang/datatype-date_zh-Hant-HK",function(a){},"@VERSION@",{use:["lang/datatype-date-format_zh-Hant-HK"]}); | mit |
ChaseGHMU/AlexaSymptomChecker | src/node_modules/aws-sdk/lib/credentials/temporary_credentials.d.ts | 1654 | import {Credentials} from '../credentials';
import {AWSError} from '../error';
import STS = require('../../clients/sts');
export class TemporaryCredentials extends Credentials {
/**
* Creates a new temporary credentials object.
* @param {Object} options - a map of options that are passed to the AWS.STS.assumeRole() or AWS.STS.getSessionToken() operations. If a RoleArn parameter is passed in, credentials will be based on the IAM role.
* @param {Object} masterCredentials - The master (non-temporary) credentials used to get and refresh credentials from AWS STS.
*/
constructor(options: TemporaryCredentials.TemporaryCredentialsOptions, masterCredentials?: Credentials);
/**
* Creates a new temporary credentials object.
* @param {Object} options - a map of options that are passed to the AWS.STS.assumeRole() or AWS.STS.getSessionToken() operations. If a RoleArn parameter is passed in, credentials will be based on the IAM role.
*/
constructor(options?: TemporaryCredentials.TemporaryCredentialsOptions);
/**
* Refreshes credentials using AWS.STS.assumeRole() or AWS.STS.getSessionToken(), depending on whether an IAM role ARN was passed to the credentials constructor().
*/
refresh(callback: (err: AWSError) => void): void;
/**
* The master (non-temporary) credentials used to get and refresh temporary credentials from AWS STS.
*/
masterCredentials: Credentials
}
// Needed to expose interfaces on the class
declare namespace TemporaryCredentials {
export type TemporaryCredentialsOptions = STS.Types.AssumeRoleRequest|STS.Types.GetSessionTokenRequest;
} | mit |
BPI-SINOVOIP/BPI-Mainline-kernel | linux-5.4/include/linux/mfd/core.h | 3982 | /* SPDX-License-Identifier: GPL-2.0-only */
/*
* drivers/mfd/mfd-core.h
*
* core MFD support
* Copyright (c) 2006 Ian Molton
* Copyright (c) 2007 Dmitry Baryshkov
*/
#ifndef MFD_CORE_H
#define MFD_CORE_H
#include <linux/platform_device.h>
struct irq_domain;
struct property_entry;
/* Matches ACPI PNP id, either _HID or _CID, or ACPI _ADR */
struct mfd_cell_acpi_match {
const char *pnpid;
const unsigned long long adr;
};
/*
* This struct describes the MFD part ("cell").
* After registration the copy of this structure will become the platform data
* of the resulting platform_device
*/
struct mfd_cell {
const char *name;
int id;
/* refcounting for multiple drivers to use a single cell */
atomic_t *usage_count;
int (*enable)(struct platform_device *dev);
int (*disable)(struct platform_device *dev);
int (*suspend)(struct platform_device *dev);
int (*resume)(struct platform_device *dev);
/* platform data passed to the sub devices drivers */
void *platform_data;
size_t pdata_size;
/* device properties passed to the sub devices drivers */
struct property_entry *properties;
/*
* Device Tree compatible string
* See: Documentation/devicetree/usage-model.txt Chapter 2.2 for details
*/
const char *of_compatible;
/* Matches ACPI */
const struct mfd_cell_acpi_match *acpi_match;
/*
* These resources can be specified relative to the parent device.
* For accessing hardware you should use resources from the platform dev
*/
int num_resources;
const struct resource *resources;
/* don't check for resource conflicts */
bool ignore_resource_conflicts;
/*
* Disable runtime PM callbacks for this subdevice - see
* pm_runtime_no_callbacks().
*/
bool pm_runtime_no_callbacks;
/* A list of regulator supplies that should be mapped to the MFD
* device rather than the child device when requested
*/
const char * const *parent_supplies;
int num_parent_supplies;
};
/*
* Convenience functions for clients using shared cells. Refcounting
* happens automatically, with the cell's enable/disable callbacks
* being called only when a device is first being enabled or no other
* clients are making use of it.
*/
extern int mfd_cell_enable(struct platform_device *pdev);
extern int mfd_cell_disable(struct platform_device *pdev);
/*
* "Clone" multiple platform devices for a single cell. This is to be used
* for devices that have multiple users of a cell. For example, if an mfd
* driver wants the cell "foo" to be used by a GPIO driver, an MTD driver,
* and a platform driver, the following bit of code would be use after first
* calling mfd_add_devices():
*
* const char *fclones[] = { "foo-gpio", "foo-mtd" };
* err = mfd_clone_cells("foo", fclones, ARRAY_SIZE(fclones));
*
* Each driver (MTD, GPIO, and platform driver) would then register
* platform_drivers for "foo-mtd", "foo-gpio", and "foo", respectively.
* The cell's .enable/.disable hooks should be used to deal with hardware
* resource contention.
*/
extern int mfd_clone_cell(const char *cell, const char **clones,
size_t n_clones);
/*
* Given a platform device that's been created by mfd_add_devices(), fetch
* the mfd_cell that created it.
*/
static inline const struct mfd_cell *mfd_get_cell(struct platform_device *pdev)
{
return pdev->mfd_cell;
}
extern int mfd_add_devices(struct device *parent, int id,
const struct mfd_cell *cells, int n_devs,
struct resource *mem_base,
int irq_base, struct irq_domain *irq_domain);
static inline int mfd_add_hotplug_devices(struct device *parent,
const struct mfd_cell *cells, int n_devs)
{
return mfd_add_devices(parent, PLATFORM_DEVID_AUTO, cells, n_devs,
NULL, 0, NULL);
}
extern void mfd_remove_devices(struct device *parent);
extern int devm_mfd_add_devices(struct device *dev, int id,
const struct mfd_cell *cells, int n_devs,
struct resource *mem_base,
int irq_base, struct irq_domain *irq_domain);
#endif
| gpl-2.0 |
BPI-SINOVOIP/BPI-Mainline-kernel | linux-4.19/drivers/gpu/drm/exynos/regs-mixer.h | 5321 | /*
*
* Cloned from drivers/media/video/s5p-tv/regs-mixer.h
*
* Copyright (c) 2010-2011 Samsung Electronics Co., Ltd.
* http://www.samsung.com/
*
* Mixer register header file for Samsung Mixer driver
*
* This program 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.
*/
#ifndef SAMSUNG_REGS_MIXER_H
#define SAMSUNG_REGS_MIXER_H
/*
* Register part
*/
#define MXR_STATUS 0x0000
#define MXR_CFG 0x0004
#define MXR_INT_EN 0x0008
#define MXR_INT_STATUS 0x000C
#define MXR_LAYER_CFG 0x0010
#define MXR_VIDEO_CFG 0x0014
#define MXR_GRAPHIC0_CFG 0x0020
#define MXR_GRAPHIC0_BASE 0x0024
#define MXR_GRAPHIC0_SPAN 0x0028
#define MXR_GRAPHIC0_SXY 0x002C
#define MXR_GRAPHIC0_WH 0x0030
#define MXR_GRAPHIC0_DXY 0x0034
#define MXR_GRAPHIC0_BLANK 0x0038
#define MXR_GRAPHIC1_CFG 0x0040
#define MXR_GRAPHIC1_BASE 0x0044
#define MXR_GRAPHIC1_SPAN 0x0048
#define MXR_GRAPHIC1_SXY 0x004C
#define MXR_GRAPHIC1_WH 0x0050
#define MXR_GRAPHIC1_DXY 0x0054
#define MXR_GRAPHIC1_BLANK 0x0058
#define MXR_BG_CFG 0x0060
#define MXR_BG_COLOR0 0x0064
#define MXR_BG_COLOR1 0x0068
#define MXR_BG_COLOR2 0x006C
#define MXR_CM_COEFF_Y 0x0080
#define MXR_CM_COEFF_CB 0x0084
#define MXR_CM_COEFF_CR 0x0088
#define MXR_MO 0x0304
#define MXR_RESOLUTION 0x0310
#define MXR_CFG_S 0x2004
#define MXR_GRAPHIC0_BASE_S 0x2024
#define MXR_GRAPHIC1_BASE_S 0x2044
/* for parametrized access to layer registers */
#define MXR_GRAPHIC_CFG(i) (0x0020 + (i) * 0x20)
#define MXR_GRAPHIC_BASE(i) (0x0024 + (i) * 0x20)
#define MXR_GRAPHIC_SPAN(i) (0x0028 + (i) * 0x20)
#define MXR_GRAPHIC_SXY(i) (0x002C + (i) * 0x20)
#define MXR_GRAPHIC_WH(i) (0x0030 + (i) * 0x20)
#define MXR_GRAPHIC_DXY(i) (0x0034 + (i) * 0x20)
#define MXR_GRAPHIC_BLANK(i) (0x0038 + (i) * 0x20)
#define MXR_GRAPHIC_BASE_S(i) (0x2024 + (i) * 0x20)
/*
* Bit definition part
*/
/* generates mask for range of bits */
#define MXR_MASK(high_bit, low_bit) \
(((2 << ((high_bit) - (low_bit))) - 1) << (low_bit))
#define MXR_MASK_VAL(val, high_bit, low_bit) \
(((val) << (low_bit)) & MXR_MASK(high_bit, low_bit))
/* bits for MXR_STATUS */
#define MXR_STATUS_SOFT_RESET (1 << 8)
#define MXR_STATUS_16_BURST (1 << 7)
#define MXR_STATUS_BURST_MASK (1 << 7)
#define MXR_STATUS_BIG_ENDIAN (1 << 3)
#define MXR_STATUS_ENDIAN_MASK (1 << 3)
#define MXR_STATUS_SYNC_ENABLE (1 << 2)
#define MXR_STATUS_REG_IDLE (1 << 1)
#define MXR_STATUS_REG_RUN (1 << 0)
/* bits for MXR_CFG */
#define MXR_CFG_LAYER_UPDATE (1 << 31)
#define MXR_CFG_LAYER_UPDATE_COUNT_MASK (3 << 29)
#define MXR_CFG_RGB601_0_255 (0 << 9)
#define MXR_CFG_RGB601_16_235 (1 << 9)
#define MXR_CFG_RGB709_0_255 (2 << 9)
#define MXR_CFG_RGB709_16_235 (3 << 9)
#define MXR_CFG_RGB_FMT_MASK 0x600
#define MXR_CFG_OUT_YUV444 (0 << 8)
#define MXR_CFG_OUT_RGB888 (1 << 8)
#define MXR_CFG_OUT_MASK (1 << 8)
#define MXR_CFG_DST_SDO (0 << 7)
#define MXR_CFG_DST_HDMI (1 << 7)
#define MXR_CFG_DST_MASK (1 << 7)
#define MXR_CFG_SCAN_HD_720 (0 << 6)
#define MXR_CFG_SCAN_HD_1080 (1 << 6)
#define MXR_CFG_GRP1_ENABLE (1 << 5)
#define MXR_CFG_GRP0_ENABLE (1 << 4)
#define MXR_CFG_VP_ENABLE (1 << 3)
#define MXR_CFG_SCAN_INTERLACE (0 << 2)
#define MXR_CFG_SCAN_PROGRESSIVE (1 << 2)
#define MXR_CFG_SCAN_NTSC (0 << 1)
#define MXR_CFG_SCAN_PAL (1 << 1)
#define MXR_CFG_SCAN_SD (0 << 0)
#define MXR_CFG_SCAN_HD (1 << 0)
#define MXR_CFG_SCAN_MASK 0x47
/* bits for MXR_GRAPHICn_CFG */
#define MXR_GRP_CFG_COLOR_KEY_DISABLE (1 << 21)
#define MXR_GRP_CFG_BLEND_PRE_MUL (1 << 20)
#define MXR_GRP_CFG_WIN_BLEND_EN (1 << 17)
#define MXR_GRP_CFG_PIXEL_BLEND_EN (1 << 16)
#define MXR_GRP_CFG_MISC_MASK ((3 << 16) | (3 << 20))
#define MXR_GRP_CFG_FORMAT_VAL(x) MXR_MASK_VAL(x, 11, 8)
#define MXR_GRP_CFG_FORMAT_MASK MXR_GRP_CFG_FORMAT_VAL(~0)
#define MXR_GRP_CFG_ALPHA_VAL(x) MXR_MASK_VAL(x, 7, 0)
/* bits for MXR_GRAPHICn_WH */
#define MXR_GRP_WH_H_SCALE(x) MXR_MASK_VAL(x, 28, 28)
#define MXR_GRP_WH_V_SCALE(x) MXR_MASK_VAL(x, 12, 12)
#define MXR_GRP_WH_WIDTH(x) MXR_MASK_VAL(x, 26, 16)
#define MXR_GRP_WH_HEIGHT(x) MXR_MASK_VAL(x, 10, 0)
/* bits for MXR_RESOLUTION */
#define MXR_MXR_RES_HEIGHT(x) MXR_MASK_VAL(x, 26, 16)
#define MXR_MXR_RES_WIDTH(x) MXR_MASK_VAL(x, 10, 0)
/* bits for MXR_GRAPHICn_SXY */
#define MXR_GRP_SXY_SX(x) MXR_MASK_VAL(x, 26, 16)
#define MXR_GRP_SXY_SY(x) MXR_MASK_VAL(x, 10, 0)
/* bits for MXR_GRAPHICn_DXY */
#define MXR_GRP_DXY_DX(x) MXR_MASK_VAL(x, 26, 16)
#define MXR_GRP_DXY_DY(x) MXR_MASK_VAL(x, 10, 0)
/* bits for MXR_INT_EN */
#define MXR_INT_EN_VSYNC (1 << 11)
#define MXR_INT_EN_ALL (0x0f << 8)
/* bits for MXR_INT_STATUS */
#define MXR_INT_CLEAR_VSYNC (1 << 11)
#define MXR_INT_STATUS_VSYNC (1 << 0)
/* bits for MXR_LAYER_CFG */
#define MXR_LAYER_CFG_GRP1_VAL(x) MXR_MASK_VAL(x, 11, 8)
#define MXR_LAYER_CFG_GRP1_MASK MXR_LAYER_CFG_GRP1_VAL(~0)
#define MXR_LAYER_CFG_GRP0_VAL(x) MXR_MASK_VAL(x, 7, 4)
#define MXR_LAYER_CFG_GRP0_MASK MXR_LAYER_CFG_GRP0_VAL(~0)
#define MXR_LAYER_CFG_VP_VAL(x) MXR_MASK_VAL(x, 3, 0)
#define MXR_LAYER_CFG_VP_MASK MXR_LAYER_CFG_VP_VAL(~0)
/* bits for MXR_CM_COEFF_Y */
#define MXR_CM_COEFF_RGB_FULL (1 << 30)
#endif /* SAMSUNG_REGS_MIXER_H */
| gpl-2.0 |
T0MM0R/magento | web/lib/Zend/View/Helper/Cycle.php | 4843 | <?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* @category Zend
* @package Zend_View
* @subpackage Helper
* @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com)
* @version $Id$
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
/**
* Helper for alternating between set of values
*
* @package Zend_View
* @subpackage Helper
* @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_View_Helper_Cycle implements Iterator
{
/**
* Default name
* @var string
*/
const DEFAULT_NAME = 'default';
/**
* Pointers
*
* @var array
*/
protected $_pointers = array(self::DEFAULT_NAME =>-1) ;
/**
* Array of values
*
* @var array
*/
protected $_data = array(self::DEFAULT_NAME=>array());
/**
* Actual name of cycle
*
* @var string
*/
protected $_name = self::DEFAULT_NAME;
/**
* Add elements to alternate
*
* @param array $data
* @param string $name
* @return Zend_View_Helper_Cycle
*/
public function cycle(array $data = array(), $name = self::DEFAULT_NAME)
{
if(!empty($data))
$this->_data[$name] = $data;
$this->setName($name);
return $this;
}
/**
* Add elements to alternate
*
* @param array $data
* @param string $name
* @return Zend_View_Helper_Cycle
*/
public function assign(Array $data , $name = self::DEFAULT_NAME)
{
$this->setName($name);
$this->_data[$name] = $data;
$this->rewind();
return $this;
}
/**
* Sets actual name of cycle
*
* @param string $name
* @return Zend_View_Helper_Cycle
*/
public function setName($name = self::DEFAULT_NAME)
{
$this->_name = $name;
if(!isset($this->_data[$this->_name]))
$this->_data[$this->_name] = array();
if(!isset($this->_pointers[$this->_name]))
$this->rewind();
return $this;
}
/**
* Gets actual name of cycle
*
* @return string
*/
public function getName()
{
return $this->_name;
}
/**
* Return all elements
*
* @return array
*/
public function getAll()
{
return $this->_data[$this->_name];
}
/**
* Turn helper into string
*
* @return string
*/
public function toString()
{
return (string) $this->_data[$this->_name][$this->key()];
}
/**
* Cast to string
*
* @return string
*/
public function __toString()
{
return $this->toString();
}
/**
* Move to next value
*
* @return Zend_View_Helper_Cycle
*/
public function next()
{
$count = count($this->_data[$this->_name]);
if ($this->_pointers[$this->_name] == ($count - 1))
$this->_pointers[$this->_name] = 0;
else
$this->_pointers[$this->_name] = ++$this->_pointers[$this->_name];
return $this;
}
/**
* Move to previous value
*
* @return Zend_View_Helper_Cycle
*/
public function prev()
{
$count = count($this->_data[$this->_name]);
if ($this->_pointers[$this->_name] <= 0)
$this->_pointers[$this->_name] = $count - 1;
else
$this->_pointers[$this->_name] = --$this->_pointers[$this->_name];
return $this;
}
/**
* Return iteration number
*
* @return int
*/
public function key()
{
if ($this->_pointers[$this->_name] < 0)
return 0;
else
return $this->_pointers[$this->_name];
}
/**
* Rewind pointer
*
* @return Zend_View_Helper_Cycle
*/
public function rewind()
{
$this->_pointers[$this->_name] = -1;
return $this;
}
/**
* Check if element is valid
*
* @return bool
*/
public function valid()
{
return isset($this->_data[$this->_name][$this->key()]);
}
/**
* Return current element
*
* @return mixed
*/
public function current()
{
return $this->_data[$this->_name][$this->key()];
}
}
| gpl-2.0 |
toncatalansuazo/SymfonyDashboard | vendor/symfony/symfony/src/Symfony/Component/Security/Guard/Firewall/GuardAuthenticationListener.php | 9036 | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Security\Guard\Firewall;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\Security\Guard\GuardAuthenticatorHandler;
use Symfony\Component\Security\Guard\Token\PreAuthenticationGuardToken;
use Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface;
use Symfony\Component\Security\Guard\GuardAuthenticatorInterface;
use Psr\Log\LoggerInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Http\Firewall\ListenerInterface;
use Symfony\Component\Security\Http\RememberMe\RememberMeServicesInterface;
/**
* Authentication listener for the "guard" system.
*
* @author Ryan Weaver <[email protected]>
*/
class GuardAuthenticationListener implements ListenerInterface
{
private $guardHandler;
private $authenticationManager;
private $providerKey;
private $guardAuthenticators;
private $logger;
private $rememberMeServices;
/**
* @param GuardAuthenticatorHandler $guardHandler The Guard handler
* @param AuthenticationManagerInterface $authenticationManager An AuthenticationManagerInterface instance
* @param string $providerKey The provider (i.e. firewall) key
* @param iterable|GuardAuthenticatorInterface[] $guardAuthenticators The authenticators, with keys that match what's passed to GuardAuthenticationProvider
* @param LoggerInterface $logger A LoggerInterface instance
*/
public function __construct(GuardAuthenticatorHandler $guardHandler, AuthenticationManagerInterface $authenticationManager, $providerKey, $guardAuthenticators, LoggerInterface $logger = null)
{
if (empty($providerKey)) {
throw new \InvalidArgumentException('$providerKey must not be empty.');
}
$this->guardHandler = $guardHandler;
$this->authenticationManager = $authenticationManager;
$this->providerKey = $providerKey;
$this->guardAuthenticators = $guardAuthenticators;
$this->logger = $logger;
}
/**
* Iterates over each authenticator to see if each wants to authenticate the request.
*
* @param GetResponseEvent $event
*/
public function handle(GetResponseEvent $event)
{
if (null !== $this->logger) {
$context = array('firewall_key' => $this->providerKey);
if ($this->guardAuthenticators instanceof \Countable || is_array($this->guardAuthenticators)) {
$context['authenticators'] = count($this->guardAuthenticators);
}
$this->logger->debug('Checking for guard authentication credentials.', $context);
}
foreach ($this->guardAuthenticators as $key => $guardAuthenticator) {
// get a key that's unique to *this* guard authenticator
// this MUST be the same as GuardAuthenticationProvider
$uniqueGuardKey = $this->providerKey.'_'.$key;
$this->executeGuardAuthenticator($uniqueGuardKey, $guardAuthenticator, $event);
if ($event->hasResponse()) {
if (null !== $this->logger) {
$this->logger->debug('The "{authenticator}" authenticator set the response. Any later authenticator will not be called', array('authenticator' => get_class($guardAuthenticator)));
}
break;
}
}
}
private function executeGuardAuthenticator($uniqueGuardKey, GuardAuthenticatorInterface $guardAuthenticator, GetResponseEvent $event)
{
$request = $event->getRequest();
try {
if (null !== $this->logger) {
$this->logger->debug('Calling getCredentials() on guard configurator.', array('firewall_key' => $this->providerKey, 'authenticator' => get_class($guardAuthenticator)));
}
// allow the authenticator to fetch authentication info from the request
$credentials = $guardAuthenticator->getCredentials($request);
// allow null to be returned to skip authentication
if (null === $credentials) {
return;
}
// create a token with the unique key, so that the provider knows which authenticator to use
$token = new PreAuthenticationGuardToken($credentials, $uniqueGuardKey);
if (null !== $this->logger) {
$this->logger->debug('Passing guard token information to the GuardAuthenticationProvider', array('firewall_key' => $this->providerKey, 'authenticator' => get_class($guardAuthenticator)));
}
// pass the token into the AuthenticationManager system
// this indirectly calls GuardAuthenticationProvider::authenticate()
$token = $this->authenticationManager->authenticate($token);
if (null !== $this->logger) {
$this->logger->info('Guard authentication successful!', array('token' => $token, 'authenticator' => get_class($guardAuthenticator)));
}
// sets the token on the token storage, etc
$this->guardHandler->authenticateWithToken($token, $request);
} catch (AuthenticationException $e) {
// oh no! Authentication failed!
if (null !== $this->logger) {
$this->logger->info('Guard authentication failed.', array('exception' => $e, 'authenticator' => get_class($guardAuthenticator)));
}
$response = $this->guardHandler->handleAuthenticationFailure($e, $request, $guardAuthenticator, $this->providerKey);
if ($response instanceof Response) {
$event->setResponse($response);
}
return;
}
// success!
$response = $this->guardHandler->handleAuthenticationSuccess($token, $request, $guardAuthenticator, $this->providerKey);
if ($response instanceof Response) {
if (null !== $this->logger) {
$this->logger->debug('Guard authenticator set success response.', array('response' => $response, 'authenticator' => get_class($guardAuthenticator)));
}
$event->setResponse($response);
} else {
if (null !== $this->logger) {
$this->logger->debug('Guard authenticator set no success response: request continues.', array('authenticator' => get_class($guardAuthenticator)));
}
}
// attempt to trigger the remember me functionality
$this->triggerRememberMe($guardAuthenticator, $request, $token, $response);
}
/**
* Should be called if this listener will support remember me.
*
* @param RememberMeServicesInterface $rememberMeServices
*/
public function setRememberMeServices(RememberMeServicesInterface $rememberMeServices)
{
$this->rememberMeServices = $rememberMeServices;
}
/**
* Checks to see if remember me is supported in the authenticator and
* on the firewall. If it is, the RememberMeServicesInterface is notified.
*
* @param GuardAuthenticatorInterface $guardAuthenticator
* @param Request $request
* @param TokenInterface $token
* @param Response $response
*/
private function triggerRememberMe(GuardAuthenticatorInterface $guardAuthenticator, Request $request, TokenInterface $token, Response $response = null)
{
if (null === $this->rememberMeServices) {
if (null !== $this->logger) {
$this->logger->debug('Remember me skipped: it is not configured for the firewall.', array('authenticator' => get_class($guardAuthenticator)));
}
return;
}
if (!$guardAuthenticator->supportsRememberMe()) {
if (null !== $this->logger) {
$this->logger->debug('Remember me skipped: your authenticator does not support it.', array('authenticator' => get_class($guardAuthenticator)));
}
return;
}
if (!$response instanceof Response) {
throw new \LogicException(sprintf(
'%s::onAuthenticationSuccess *must* return a Response if you want to use the remember me functionality. Return a Response, or set remember_me to false under the guard configuration.',
get_class($guardAuthenticator)
));
}
$this->rememberMeServices->loginSuccess($request, $response, $token);
}
}
| mit |
google-code/asianspecialroad | plugins/media/system/js/validate-jquery-uncompressed.js | 5696 | /**
* @copyright Copyright (C) 2005 - 2013 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
/**
* Unobtrusive Form Validation library
*
* Inspired by: Chris Campbell <www.particletree.com>
*
* @package Joomla.Framework
* @subpackage Forms
* @since 1.5
*/
var JFormValidator = function($) {
var handlers, custom, inputEmail;
var setHandler = function(name, fn, en) {
en = (en === '') ? true : en;
handlers[name] = {
enabled : en,
exec : fn
};
};
var handleResponse = function(state, $el) {
// Find the label object for the given field if it exists
if (!$el.get(0).labelref) {
$('label').each(function() {
var $label = $(this);
if ($label.attr('for') === $el.attr('id')) {
$el.get(0).labelref = this;
}
});
}
var labelref = $el.get(0).labelref;
// Set the element and its label (if exists) invalid state
if (state === false) {
$el.addClass('invalid').attr('aria-invalid', 'true');
if (labelref) {
$(labelref).addClass('invalid').attr('aria-invalid', 'true');
}
} else {
$el.removeClass('invalid').attr('aria-invalid', 'false');
if (labelref) {
$(labelref).removeClass('invalid').attr('aria-invalid', 'false');
}
}
};
var validate = function(el) {
var $el = $(el);
// Ignore the element if its currently disabled, because are not submitted for the http-request. For those case return always true.
if ($el.attr('disabled')) {
handleResponse(true, $el);
return true;
}
// If the field is required make sure it has a value
if ($el.hasClass('required')) {
var tagName = $el.prop("tagName").toLowerCase(), i = 0, selector;
if (tagName === 'fieldset' && ($el.hasClass('radio') || $el.hasClass('checkboxes'))) {
while (true) {
selector = "#" + $el.attr('id') + i;
if ($(selector).get(0)) {
if ($(selector).is(':checked')) {
break;
}
} else {
handleResponse(false, $el);
return false;
}
i++;
}
//If element has class placeholder that means it is empty.
} else if (!$el.val() || $el.hasClass('placeholder') || ($el.attr('type') === 'checkbox' && !$el.is(':checked'))) {
handleResponse(false, $el);
return false;
}
}
// Only validate the field if the validate class is set
var handler = ($el.attr('class') && $el.attr('class').match(/validate-([a-zA-Z0-9\_\-]+)/)) ? $el.attr('class').match(/validate-([a-zA-Z0-9\_\-]+)/)[1] : "";
if (handler === '') {
handleResponse(true, $el);
return true;
}
// Check the additional validation types
if ((handler) && (handler !== 'none') && (handlers[handler]) && $el.val()) {
// Execute the validation handler and return result
if (handlers[handler].exec($el.val()) !== true) {
handleResponse(false, $el);
return false;
}
}
// Return validation state
handleResponse(true, $el);
return true;
};
var isValid = function(form) {
var valid = true, $form = $(form), i;
// Validate form fields
$form.find('input, textarea, select, button, fieldset').each(function(index, el){
if (validate(el) === false) {
valid = false;
}
});
// Run custom form validators if present
new Hash(custom).each(function(validator) {
if (validator.exec() !== true) {
valid = false;
}
});
if (!valid) {
var message, errors, error;
message = Joomla.JText._('JLIB_FORM_FIELD_INVALID');
errors = $("label.invalid");
error = {};
error.error = [];
for ( i = 0; i < errors.length; i++) {
var label = $(errors[i]).text();
if (label !== 'undefined') {
error.error[i] = message + label.replace("*", "");
}
}
Joomla.renderMessages(error);
}
return valid;
};
var attachToForm = function(form) {
// Iterate through the form object and attach the validate method to all input fields.
$(form).find('input,textarea,select,button').each(function() {
var $el = $(this), tagName = $el.prop("tagName").toLowerCase();
if ($el.attr('required') === 'required') {
$el.attr('aria-required', 'true');
}
if ((tagName === 'input' && $el.attr('type') === 'submit') || (tagName === 'button' && $el.attr('type') === undefined)) {
if ($el.hasClass('validate')) {
$el.on('click', function() {
return isValid(form);
});
}
} else {
$el.on('blur', function() {
return validate(this);
});
if ($el.hasClass('validate-email') && inputEmail) {
$el.get(0).type = 'email';
}
}
});
};
var initialize = function() {
handlers = {};
custom = {};
inputEmail = (function() {
var input = document.createElement("input");
input.setAttribute("type", "email");
return input.type !== "text";
})();
// Default handlers
setHandler('username', function(value) {
regex = new RegExp("[\<|\>|\"|\'|\%|\;|\(|\)|\&]", "i");
return !regex.test(value);
});
setHandler('password', function(value) {
regex = /^\S[\S ]{2,98}\S$/;
return regex.test(value);
});
setHandler('numeric', function(value) {
regex = /^(\d|-)?(\d|,)*\.?\d*$/;
return regex.test(value);
});
setHandler('email', function(value) {
regex = /^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
return regex.test(value);
});
// Attach to forms with class 'form-validate'
$('form.form-validate').each(function() {
attachToForm(this);
});
};
return {
initialize : initialize,
isValid : isValid,
validate : validate
};
};
document.formvalidator = null;
window.addEvent('domready', function() {
document.formvalidator = new JFormValidator(jQuery.noConflict());
document.formvalidator.initialize();
});
| gpl-2.0 |
mogoweb/webkit_for_android5.1 | webkit/Source/WebCore/rendering/svg/SVGTextChunkBuilder.cpp | 9299 | /*
* Copyright (C) Research In Motion Limited 2010. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "config.h"
#if ENABLE(SVG)
#include "SVGTextChunkBuilder.h"
#include "RenderSVGInlineText.h"
#include "SVGElement.h"
#include "SVGInlineTextBox.h"
namespace WebCore {
SVGTextChunkBuilder::SVGTextChunkBuilder()
{
}
void SVGTextChunkBuilder::transformationForTextBox(SVGInlineTextBox* textBox, AffineTransform& transform) const
{
DEFINE_STATIC_LOCAL(const AffineTransform, s_identityTransform, ());
if (!m_textBoxTransformations.contains(textBox)) {
transform = s_identityTransform;
return;
}
transform = m_textBoxTransformations.get(textBox);
}
void SVGTextChunkBuilder::buildTextChunks(Vector<SVGInlineTextBox*>& lineLayoutBoxes)
{
if (lineLayoutBoxes.isEmpty())
return;
bool foundStart = false;
unsigned lastChunkStartPosition = 0;
unsigned boxPosition = 0;
unsigned boxCount = lineLayoutBoxes.size();
for (; boxPosition < boxCount; ++boxPosition) {
SVGInlineTextBox* textBox = lineLayoutBoxes[boxPosition];
if (!textBox->startsNewTextChunk())
continue;
if (!foundStart) {
lastChunkStartPosition = boxPosition;
foundStart = true;
} else {
ASSERT(boxPosition > lastChunkStartPosition);
addTextChunk(lineLayoutBoxes, lastChunkStartPosition, boxPosition - lastChunkStartPosition);
lastChunkStartPosition = boxPosition;
}
}
if (!foundStart)
return;
if (boxPosition - lastChunkStartPosition > 0)
addTextChunk(lineLayoutBoxes, lastChunkStartPosition, boxPosition - lastChunkStartPosition);
}
void SVGTextChunkBuilder::layoutTextChunks(Vector<SVGInlineTextBox*>& lineLayoutBoxes)
{
buildTextChunks(lineLayoutBoxes);
if (m_textChunks.isEmpty())
return;
unsigned chunkCount = m_textChunks.size();
for (unsigned i = 0; i < chunkCount; ++i)
processTextChunk(m_textChunks[i]);
m_textChunks.clear();
}
void SVGTextChunkBuilder::addTextChunk(Vector<SVGInlineTextBox*>& lineLayoutBoxes, unsigned boxStart, unsigned boxCount)
{
SVGInlineTextBox* textBox = lineLayoutBoxes[boxStart];
ASSERT(textBox);
RenderSVGInlineText* textRenderer = toRenderSVGInlineText(textBox->textRenderer());
ASSERT(textRenderer);
const RenderStyle* style = textRenderer->style();
ASSERT(style);
const SVGRenderStyle* svgStyle = style->svgStyle();
ASSERT(svgStyle);
// Build chunk style flags.
unsigned chunkStyle = SVGTextChunk::DefaultStyle;
// Handle 'direction' property.
if (!style->isLeftToRightDirection())
chunkStyle |= SVGTextChunk::RightToLeftText;
// Handle 'writing-mode' property.
if (svgStyle->isVerticalWritingMode())
chunkStyle |= SVGTextChunk::VerticalText;
// Handle 'text-anchor' property.
switch (svgStyle->textAnchor()) {
case TA_START:
break;
case TA_MIDDLE:
chunkStyle |= SVGTextChunk::MiddleAnchor;
break;
case TA_END:
chunkStyle |= SVGTextChunk::EndAnchor;
break;
};
// Handle 'lengthAdjust' property.
float desiredTextLength = 0;
if (SVGTextContentElement* textContentElement = SVGTextContentElement::elementFromRenderer(textRenderer->parent())) {
desiredTextLength = textContentElement->specifiedTextLength().value(textContentElement);
switch (static_cast<SVGTextContentElement::SVGLengthAdjustType>(textContentElement->lengthAdjust())) {
case SVGTextContentElement::LENGTHADJUST_UNKNOWN:
break;
case SVGTextContentElement::LENGTHADJUST_SPACING:
chunkStyle |= SVGTextChunk::LengthAdjustSpacing;
break;
case SVGTextContentElement::LENGTHADJUST_SPACINGANDGLYPHS:
chunkStyle |= SVGTextChunk::LengthAdjustSpacingAndGlyphs;
break;
};
}
SVGTextChunk chunk(chunkStyle, desiredTextLength);
Vector<SVGInlineTextBox*>& boxes = chunk.boxes();
for (unsigned i = boxStart; i < boxStart + boxCount; ++i)
boxes.append(lineLayoutBoxes[i]);
m_textChunks.append(chunk);
}
void SVGTextChunkBuilder::processTextChunk(const SVGTextChunk& chunk)
{
bool processTextLength = chunk.hasDesiredTextLength();
bool processTextAnchor = chunk.hasTextAnchor();
if (!processTextAnchor && !processTextLength)
return;
const Vector<SVGInlineTextBox*>& boxes = chunk.boxes();
unsigned boxCount = boxes.size();
if (!boxCount)
return;
// Calculate absolute length of whole text chunk (starting from text box 'start', spanning 'length' text boxes).
float chunkLength = 0;
unsigned chunkCharacters = 0;
chunk.calculateLength(chunkLength, chunkCharacters);
bool isVerticalText = chunk.isVerticalText();
if (processTextLength) {
if (chunk.hasLengthAdjustSpacing()) {
float textLengthShift = (chunk.desiredTextLength() - chunkLength) / chunkCharacters;
unsigned atCharacter = 0;
for (unsigned boxPosition = 0; boxPosition < boxCount; ++boxPosition) {
Vector<SVGTextFragment>& fragments = boxes[boxPosition]->textFragments();
if (fragments.isEmpty())
continue;
processTextLengthSpacingCorrection(isVerticalText, textLengthShift, fragments, atCharacter);
}
} else {
ASSERT(chunk.hasLengthAdjustSpacingAndGlyphs());
float textLengthScale = chunk.desiredTextLength() / chunkLength;
AffineTransform spacingAndGlyphsTransform;
bool foundFirstFragment = false;
for (unsigned boxPosition = 0; boxPosition < boxCount; ++boxPosition) {
SVGInlineTextBox* textBox = boxes[boxPosition];
Vector<SVGTextFragment>& fragments = textBox->textFragments();
if (fragments.isEmpty())
continue;
if (!foundFirstFragment) {
foundFirstFragment = true;
buildSpacingAndGlyphsTransform(isVerticalText, textLengthScale, fragments.first(), spacingAndGlyphsTransform);
}
m_textBoxTransformations.set(textBox, spacingAndGlyphsTransform);
}
}
}
if (!processTextAnchor)
return;
// If we previously applied a lengthAdjust="spacing" correction, we have to recalculate the chunk length, to be able to apply the text-anchor shift.
if (processTextLength && chunk.hasLengthAdjustSpacing()) {
chunkLength = 0;
chunkCharacters = 0;
chunk.calculateLength(chunkLength, chunkCharacters);
}
float textAnchorShift = chunk.calculateTextAnchorShift(chunkLength);
for (unsigned boxPosition = 0; boxPosition < boxCount; ++boxPosition) {
Vector<SVGTextFragment>& fragments = boxes[boxPosition]->textFragments();
if (fragments.isEmpty())
continue;
processTextAnchorCorrection(isVerticalText, textAnchorShift, fragments);
}
}
void SVGTextChunkBuilder::processTextLengthSpacingCorrection(bool isVerticalText, float textLengthShift, Vector<SVGTextFragment>& fragments, unsigned& atCharacter)
{
unsigned fragmentCount = fragments.size();
for (unsigned i = 0; i < fragmentCount; ++i) {
SVGTextFragment& fragment = fragments[i];
if (isVerticalText)
fragment.y += textLengthShift * atCharacter;
else
fragment.x += textLengthShift * atCharacter;
atCharacter += fragment.length;
}
}
void SVGTextChunkBuilder::processTextAnchorCorrection(bool isVerticalText, float textAnchorShift, Vector<SVGTextFragment>& fragments)
{
unsigned fragmentCount = fragments.size();
for (unsigned i = 0; i < fragmentCount; ++i) {
SVGTextFragment& fragment = fragments[i];
if (isVerticalText)
fragment.y += textAnchorShift;
else
fragment.x += textAnchorShift;
}
}
void SVGTextChunkBuilder::buildSpacingAndGlyphsTransform(bool isVerticalText, float scale, const SVGTextFragment& fragment, AffineTransform& spacingAndGlyphsTransform)
{
spacingAndGlyphsTransform.translate(fragment.x, fragment.y);
if (isVerticalText)
spacingAndGlyphsTransform.scaleNonUniform(1, scale);
else
spacingAndGlyphsTransform.scaleNonUniform(scale, 1);
spacingAndGlyphsTransform.translate(-fragment.x, -fragment.y);
}
}
#endif // ENABLE(SVG)
| apache-2.0 |
teiath/lms | web/dbadmin/tbl_tracking.php | 29065 | <?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
*
* @package PhpMyAdmin
*/
// Run common work
require_once './libraries/common.inc.php';
define('TABLE_MAY_BE_ABSENT', true);
require './libraries/tbl_common.php';
$url_query .= '&goto=tbl_tracking.php&back=tbl_tracking.php';
$url_params['goto'] = 'tbl_tracking.php';;
$url_params['back'] = 'tbl_tracking.php';
// Init vars for tracking report
if (isset($_REQUEST['report']) || isset($_REQUEST['report_export'])) {
$data = PMA_Tracker::getTrackedData($_REQUEST['db'], $_REQUEST['table'], $_REQUEST['version']);
$selection_schema = false;
$selection_data = false;
$selection_both = false;
if (! isset($_REQUEST['logtype'])) {
$_REQUEST['logtype'] = 'schema_and_data';
}
if ($_REQUEST['logtype'] == 'schema') {
$selection_schema = true;
} elseif ($_REQUEST['logtype'] == 'data') {
$selection_data = true;
} else {
$selection_both = true;
}
if (! isset($_REQUEST['date_from'])) {
$_REQUEST['date_from'] = $data['date_from'];
}
if (! isset($_REQUEST['date_to'])) {
$_REQUEST['date_to'] = $data['date_to'];
}
if (! isset($_REQUEST['users'])) {
$_REQUEST['users'] = '*';
}
$filter_ts_from = strtotime($_REQUEST['date_from']);
$filter_ts_to = strtotime($_REQUEST['date_to']);
$filter_users = array_map('trim', explode(',', $_REQUEST['users']));
}
// Prepare export
if (isset($_REQUEST['report_export'])) {
/**
* Filters tracking entries
*
* @param array the entries to filter
* @param string "from" date
* @param string "to" date
* @param string users
*
* @return array filtered entries
*
*/
function PMA_filter_tracking($data, $filter_ts_from, $filter_ts_to, $filter_users) {
$tmp_entries = array();
$id = 0;
foreach ( $data as $entry ) {
$timestamp = strtotime($entry['date']);
if ($timestamp >= $filter_ts_from && $timestamp <= $filter_ts_to &&
( in_array('*', $filter_users) || in_array($entry['username'], $filter_users) ) ) {
$tmp_entries[] = array( 'id' => $id,
'timestamp' => $timestamp,
'username' => $entry['username'],
'statement' => $entry['statement']
);
}
$id++;
}
return($tmp_entries);
}
$entries = array();
// Filtering data definition statements
if ($_REQUEST['logtype'] == 'schema' || $_REQUEST['logtype'] == 'schema_and_data') {
$entries = array_merge($entries, PMA_filter_tracking($data['ddlog'], $filter_ts_from, $filter_ts_to, $filter_users));
}
// Filtering data manipulation statements
if ($_REQUEST['logtype'] == 'data' || $_REQUEST['logtype'] == 'schema_and_data') {
$entries = array_merge($entries, PMA_filter_tracking($data['dmlog'], $filter_ts_from, $filter_ts_to, $filter_users));
}
// Sort it
foreach ($entries as $key => $row) {
$ids[$key] = $row['id'];
$timestamps[$key] = $row['timestamp'];
$usernames[$key] = $row['username'];
$statements[$key] = $row['statement'];
}
array_multisort($timestamps, SORT_ASC, $ids, SORT_ASC, $usernames, SORT_ASC, $statements, SORT_ASC, $entries);
}
// Export as file download
if (isset($_REQUEST['report_export']) && $_REQUEST['export_type'] == 'sqldumpfile') {
@ini_set('url_rewriter.tags', '');
$dump = "# " . sprintf(__('Tracking report for table `%s`'), htmlspecialchars($_REQUEST['table'])) . "\n" .
"# " . date('Y-m-d H:i:s') . "\n";
foreach ($entries as $entry) {
$dump .= $entry['statement'];
}
$filename = 'log_' . htmlspecialchars($_REQUEST['table']) . '.sql';
PMA_download_header($filename, 'text/x-sql', strlen($dump));
echo $dump;
exit();
}
/**
* Gets tables informations
*/
/**
* Displays top menu links
*/
require_once './libraries/tbl_links.inc.php';
echo '<br />';
/**
* Actions
*/
// Create tracking version
if (isset($_REQUEST['submit_create_version'])) {
$tracking_set = '';
if ($_REQUEST['alter_table'] == true) {
$tracking_set .= 'ALTER TABLE,';
}
if ($_REQUEST['rename_table'] == true) {
$tracking_set .= 'RENAME TABLE,';
}
if ($_REQUEST['create_table'] == true) {
$tracking_set .= 'CREATE TABLE,';
}
if ($_REQUEST['drop_table'] == true) {
$tracking_set .= 'DROP TABLE,';
}
if ($_REQUEST['create_index'] == true) {
$tracking_set .= 'CREATE INDEX,';
}
if ($_REQUEST['drop_index'] == true) {
$tracking_set .= 'DROP INDEX,';
}
if ($_REQUEST['insert'] == true) {
$tracking_set .= 'INSERT,';
}
if ($_REQUEST['update'] == true) {
$tracking_set .= 'UPDATE,';
}
if ($_REQUEST['delete'] == true) {
$tracking_set .= 'DELETE,';
}
if ($_REQUEST['truncate'] == true) {
$tracking_set .= 'TRUNCATE,';
}
$tracking_set = rtrim($tracking_set, ',');
if (PMA_Tracker::createVersion($GLOBALS['db'], $GLOBALS['table'], $_REQUEST['version'], $tracking_set )) {
$msg = PMA_Message::success(sprintf(__('Version %s is created, tracking for %s.%s is activated.'), htmlspecialchars($_REQUEST['version']), htmlspecialchars($GLOBALS['db']), htmlspecialchars($GLOBALS['table'])));
$msg->display();
}
}
// Deactivate tracking
if (isset($_REQUEST['submit_deactivate_now'])) {
if (PMA_Tracker::deactivateTracking($GLOBALS['db'], $GLOBALS['table'], $_REQUEST['version'])) {
$msg = PMA_Message::success(sprintf(__('Tracking for %s.%s , version %s is deactivated.'), htmlspecialchars($GLOBALS['db']), htmlspecialchars($GLOBALS['table']), htmlspecialchars($_REQUEST['version'])));
$msg->display();
}
}
// Activate tracking
if (isset($_REQUEST['submit_activate_now'])) {
if (PMA_Tracker::activateTracking($GLOBALS['db'], $GLOBALS['table'], $_REQUEST['version'])) {
$msg = PMA_Message::success(sprintf(__('Tracking for %s.%s , version %s is activated.'), htmlspecialchars($GLOBALS['db']), htmlspecialchars($GLOBALS['table']), htmlspecialchars($_REQUEST['version'])));
$msg->display();
}
}
// Export as SQL execution
if (isset($_REQUEST['report_export']) && $_REQUEST['export_type'] == 'execution') {
foreach ($entries as $entry) {
$sql_result = PMA_DBI_query( "/*NOTRACK*/\n" . $entry['statement'] );
}
$msg = PMA_Message::success(__('SQL statements executed.'));
$msg->display();
}
// Export as SQL dump
if (isset($_REQUEST['report_export']) && $_REQUEST['export_type'] == 'sqldump') {
$new_query = "# " . __('You can execute the dump by creating and using a temporary database. Please ensure that you have the privileges to do so.') . "\n" .
"# " . __('Comment out these two lines if you do not need them.') . "\n" .
"\n" .
"CREATE database IF NOT EXISTS pma_temp_db; \n" .
"USE pma_temp_db; \n" .
"\n";
foreach ($entries as $entry) {
$new_query .= $entry['statement'];
}
$msg = PMA_Message::success(__('SQL statements exported. Please copy the dump or execute it.'));
$msg->display();
$db_temp = $db;
$table_temp = $table;
$db = $table = '';
include_once './libraries/sql_query_form.lib.php';
PMA_sqlQueryForm($new_query, 'sql');
$db = $db_temp;
$table = $table_temp;
}
/*
* Schema snapshot
*/
if (isset($_REQUEST['snapshot'])) {
?>
<h3><?php echo __('Structure snapshot');?> [<a href="tbl_tracking.php?<?php echo $url_query;?>"><?php echo __('Close');?></a>]</h3>
<?php
$data = PMA_Tracker::getTrackedData($_REQUEST['db'], $_REQUEST['table'], $_REQUEST['version']);
// Get first DROP TABLE and CREATE TABLE statements
$drop_create_statements = $data['ddlog'][0]['statement'];
if (strstr($data['ddlog'][0]['statement'], 'DROP TABLE')) {
$drop_create_statements .= $data['ddlog'][1]['statement'];
}
// Print SQL code
PMA_showMessage(sprintf(__('Version %s snapshot (SQL code)'), htmlspecialchars($_REQUEST['version'])), $drop_create_statements);
// Unserialize snapshot
$temp = unserialize($data['schema_snapshot']);
$columns = $temp['COLUMNS'];
$indexes = $temp['INDEXES'];
?>
<h3><?php echo __('Structure');?></h3>
<table id="tablestructure" class="data">
<thead>
<tr>
<th><?php echo __('Column'); ?></th>
<th><?php echo __('Type'); ?></th>
<th><?php echo __('Collation'); ?></th>
<th><?php echo __('Null'); ?></th>
<th><?php echo __('Default'); ?></th>
<th><?php echo __('Extra'); ?></th>
<th><?php echo __('Comment'); ?></th>
</tr>
</thead>
<tbody>
<?php
$style = 'odd';
foreach ($columns as $field_index => $field) {
?>
<tr class="noclick <?php echo $style; ?>">
<?php
if ($field['Key'] == 'PRI') {
echo '<td><b><u>' . htmlspecialchars($field['Field']) . '</u></b></td>' . "\n";
} else {
echo '<td><b>' . htmlspecialchars($field['Field']) . '</b></td>' . "\n";
}
?>
<td><?php echo htmlspecialchars($field['Type']);?></td>
<td><?php echo htmlspecialchars($field['Collation']);?></td>
<td><?php echo (($field['Null'] == 'YES') ? __('Yes') : __('No')); ?></td>
<td><?php
if (isset($field['Default'])) {
$extracted_fieldspec = PMA_extractFieldSpec($field['Type']);
if ($extracted_fieldspec['type'] == 'bit') {
// here, $field['Default'] contains something like b'010'
echo PMA_convert_bit_default_value($field['Default']);
} else {
echo htmlspecialchars($field['Default']);
}
} else {
if ($field['Null'] == 'YES') {
echo '<i>NULL</i>';
} else {
echo '<i>' . _pgettext('None for default', 'None') . '</i>';
}
} ?></td>
<td><?php echo htmlspecialchars($field['Extra']);?></td>
<td><?php echo htmlspecialchars($field['Comment']);?></td>
</tr>
<?php
if ($style == 'even') {
$style = 'odd';
} else {
$style = 'even';
}
}
?>
</tbody>
</table>
<?php
if (count($indexes) > 0) {
?>
<h3><?php echo __('Indexes');?></h3>
<table id="tablestructure_indexes" class="data">
<thead>
<tr>
<th><?php echo __('Keyname');?></th>
<th><?php echo __('Type');?></th>
<th><?php echo __('Unique');?></th>
<th><?php echo __('Packed');?></th>
<th><?php echo __('Column');?></th>
<th><?php echo __('Cardinality');?></th>
<th><?php echo __('Collation');?></th>
<th><?php echo __('Null');?></th>
<th><?php echo __('Comment');?></th>
</tr>
<tbody>
<?php
$style = 'odd';
foreach ($indexes as $indexes_index => $index) {
if ($index['Non_unique'] == 0) {
$str_unique = __('Yes');
} else {
$str_unique = __('No');
}
if ($index['Packed'] != '') {
$str_packed = __('Yes');
} else {
$str_packed = __('No');
}
?>
<tr class="noclick <?php echo $style; ?>">
<td><b><?php echo htmlspecialchars($index['Key_name']);?></b></td>
<td><?php echo htmlspecialchars($index['Index_type']);?></td>
<td><?php echo $str_unique;?></td>
<td><?php echo $str_packed;?></td>
<td><?php echo htmlspecialchars($index['Column_name']);?></td>
<td><?php echo htmlspecialchars($index['Cardinality']);?></td>
<td><?php echo htmlspecialchars($index['Collation']);?></td>
<td><?php echo htmlspecialchars($index['Null']);?></td>
<td><?php echo htmlspecialchars($index['Comment']);?></td>
</tr>
<?php
if ($style == 'even') {
$style = 'odd';
} else {
$style = 'even';
}
}
?>
</tbody>
</table>
<?php
} // endif
?>
<br /><hr /><br />
<?php
}
// end of snapshot report
/*
* Tracking report
*/
if (isset($_REQUEST['report']) && (isset($_REQUEST['delete_ddlog']) || isset($_REQUEST['delete_dmlog']))) {
if (isset($_REQUEST['delete_ddlog'])) {
// Delete ddlog row data
$delete_id = $_REQUEST['delete_ddlog'];
// Only in case of valable id
if ($delete_id == (int)$delete_id) {
unset($data['ddlog'][$delete_id]);
if (PMA_Tracker::changeTrackingData($_REQUEST['db'], $_REQUEST['table'], $_REQUEST['version'], 'DDL', $data['ddlog']))
$msg = PMA_Message::success(__('Tracking data definition successfully deleted'));
else
$msg = PMA_Message::rawError(__('Query error'));
$msg->display();
}
}
if (isset($_REQUEST['delete_dmlog'])) {
// Delete dmlog row data
$delete_id = $_REQUEST['delete_dmlog'];
// Only in case of valable id
if ($delete_id == (int)$delete_id) {
unset($data['dmlog'][$delete_id]);
if (PMA_Tracker::changeTrackingData($_REQUEST['db'], $_REQUEST['table'], $_REQUEST['version'], 'DML', $data['dmlog']))
$msg = PMA_Message::success(__('Tracking data manipulation successfully deleted'));
else
$msg = PMA_Message::rawError(__('Query error'));
$msg->display();
}
}
}
if (isset($_REQUEST['report']) || isset($_REQUEST['report_export'])) {
?>
<h3><?php echo __('Tracking report');?> [<a href="tbl_tracking.php?<?php echo $url_query;?>"><?php echo __('Close');?></a>]</h3>
<small><?php echo __('Tracking statements') . ' ' . htmlspecialchars($data['tracking']); ?></small><br/>
<br/>
<form method="post" action="tbl_tracking.php<?php echo PMA_generate_common_url($url_params + array('report' => 'true', 'version' => $_REQUEST['version'])); ?>">
<?php
$str1 = '<select name="logtype">' .
'<option value="schema"' . ($selection_schema ? ' selected="selected"' : '') . '>' . __('Structure only') . '</option>' .
'<option value="data"' . ($selection_data ? ' selected="selected"' : ''). '>' . __('Data only') . '</option>' .
'<option value="schema_and_data"' . ($selection_both ? ' selected="selected"' : '') . '>' . __('Structure and data') . '</option>' .
'</select>';
$str2 = '<input type="text" name="date_from" value="' . htmlspecialchars($_REQUEST['date_from']) . '" size="19" />';
$str3 = '<input type="text" name="date_to" value="' . htmlspecialchars($_REQUEST['date_to']) . '" size="19" />';
$str4 = '<input type="text" name="users" value="' . htmlspecialchars($_REQUEST['users']) . '" />';
$str5 = '<input type="submit" name="list_report" value="' . __('Go') . '" />';
printf(__('Show %s with dates from %s to %s by user %s %s'), $str1, $str2, $str3, $str4, $str5);
// Prepare delete link content here
$drop_image_or_text = '';
if (true == $GLOBALS['cfg']['PropertiesIconic']) {
$drop_image_or_text .= PMA_getImage('b_drop.png', __('Delete tracking data row from report'));
}
if ('both' === $GLOBALS['cfg']['PropertiesIconic'] || false === $GLOBALS['cfg']['PropertiesIconic']) {
$drop_image_or_text .= __('Delete');
}
/*
* First, list tracked data definition statements
*/
$i = 1;
if (count($data['ddlog']) == 0 && count($data['dmlog']) == 0) {
$msg = PMA_Message::notice(__('No data'));
$msg->display();
}
if ($selection_schema || $selection_both && count($data['ddlog']) > 0) {
?>
<table id="ddl_versions" class="data" width="100%">
<thead>
<tr>
<th width="18">#</th>
<th width="100"><?php echo __('Date');?></th>
<th width="60"><?php echo __('Username');?></th>
<th><?php echo __('Data definition statement');?></th>
<th><?php echo __('Delete');?></th>
</tr>
</thead>
<tbody>
<?php
$style = 'odd';
foreach ($data['ddlog'] as $entry) {
if (strlen($entry['statement']) > $GLOBALS['cfg']['MaxCharactersInDisplayedSQL']) {
$statement = substr($entry['statement'], 0, $GLOBALS['cfg']['MaxCharactersInDisplayedSQL']) . '[...]';
} else {
$statement = PMA_formatSql(PMA_SQP_parse($entry['statement']));
}
$timestamp = strtotime($entry['date']);
if ($timestamp >= $filter_ts_from && $timestamp <= $filter_ts_to &&
( in_array('*', $filter_users) || in_array($entry['username'], $filter_users) ) ) {
?>
<tr class="noclick <?php echo $style; ?>">
<td><small><?php echo $i;?></small></td>
<td><small><?php echo htmlspecialchars($entry['date']);?></small></td>
<td><small><?php echo htmlspecialchars($entry['username']); ?></small></td>
<td><?php echo $statement; ?></td>
<td nowrap="nowrap"><a href="tbl_tracking.php?<?php echo $url_query;?>&report=true&version=<?php echo $version['version'];?>&delete_ddlog=<?php echo $i-1; ?>"><?php echo $drop_image_or_text; ?></a></td>
</tr>
<?php
if ($style == 'even') {
$style = 'odd';
} else {
$style = 'even';
}
$i++;
}
}
?>
</tbody>
</table>
<?php
} //endif
// Memorize data definition amount
$ddlog_count = $i;
/*
* Secondly, list tracked data manipulation statements
*/
if (($selection_data || $selection_both) && count($data['dmlog']) > 0) {
?>
<table id="dml_versions" class="data" width="100%">
<thead>
<tr>
<th width="18">#</th>
<th width="100"><?php echo __('Date');?></th>
<th width="60"><?php echo __('Username');?></th>
<th><?php echo __('Data manipulation statement');?></th>
<th><?php echo __('Delete');?></th>
</tr>
</thead>
<tbody>
<?php
$style = 'odd';
foreach ($data['dmlog'] as $entry) {
if (strlen($entry['statement']) > $GLOBALS['cfg']['MaxCharactersInDisplayedSQL']) {
$statement = substr($entry['statement'], 0, $GLOBALS['cfg']['MaxCharactersInDisplayedSQL']) . '[...]';
} else {
$statement = PMA_formatSql(PMA_SQP_parse($entry['statement']));
}
$timestamp = strtotime($entry['date']);
if ($timestamp >= $filter_ts_from && $timestamp <= $filter_ts_to &&
( in_array('*', $filter_users) || in_array($entry['username'], $filter_users) ) ) {
?>
<tr class="noclick <?php echo $style; ?>">
<td><small><?php echo $i; ?></small></td>
<td><small><?php echo htmlspecialchars($entry['date']); ?></small></td>
<td><small><?php echo htmlspecialchars($entry['username']); ?></small></td>
<td><?php echo $statement; ?></td>
<td nowrap="nowrap"><a href="tbl_tracking.php?<?php echo $url_query;?>&report=true&version=<?php echo $version['version'];?>&delete_dmlog=<?php echo $i-$ddlog_count; ?>"><?php echo $drop_image_or_text; ?></a></td>
</tr>
<?php
if ($style == 'even') {
$style = 'odd';
} else {
$style = 'even';
}
$i++;
}
}
?>
</tbody>
</table>
<?php
}
?>
</form>
<form method="post" action="tbl_tracking.php<?php echo PMA_generate_common_url($url_params + array('report' => 'true', 'version' => $_REQUEST['version'])); ?>">
<?php
printf(__('Show %s with dates from %s to %s by user %s %s'), $str1, $str2, $str3, $str4, $str5);
$str_export1 = '<select name="export_type">' .
'<option value="sqldumpfile">' . __('SQL dump (file download)') . '</option>' .
'<option value="sqldump">' . __('SQL dump') . '</option>' .
'<option value="execution" onclick="alert(\'' . PMA_escapeJsString(__('This option will replace your table and contained data.')) .'\')">' . __('SQL execution') . '</option>' .
'</select>';
$str_export2 = '<input type="submit" name="report_export" value="' . __('Go') .'" />';
?>
</form>
<form method="post" action="tbl_tracking.php<?php echo PMA_generate_common_url($url_params + array('report' => 'true', 'version' => $_REQUEST['version'])); ?>">
<input type="hidden" name="logtype" value="<?php echo htmlspecialchars($_REQUEST['logtype']);?>" />
<input type="hidden" name="date_from" value="<?php echo htmlspecialchars($_REQUEST['date_from']);?>" />
<input type="hidden" name="date_to" value="<?php echo htmlspecialchars($_REQUEST['date_to']);?>" />
<input type="hidden" name="users" value="<?php echo htmlspecialchars($_REQUEST['users']);?>" />
<?php
echo "<br/>" . sprintf(__('Export as %s'), $str_export1) . $str_export2 . "<br/>";
?>
</form>
<?php
echo "<br/><br/><hr/><br/>\n";
} // end of report
/*
* List selectable tables
*/
$sql_query = " SELECT DISTINCT db_name, table_name FROM " .
PMA_backquote($GLOBALS['cfg']['Server']['pmadb']) . "." .
PMA_backquote($GLOBALS['cfg']['Server']['tracking']) .
" WHERE db_name = '" . PMA_sqlAddSlashes($GLOBALS['db']) . "' " .
" ORDER BY db_name, table_name";
$sql_result = PMA_query_as_controluser($sql_query);
if (PMA_DBI_num_rows($sql_result) > 0) {
?>
<form method="post" action="tbl_tracking.php?<?php echo $url_query;?>">
<select name="table">
<?php
while ($entries = PMA_DBI_fetch_array($sql_result)) {
if (PMA_Tracker::isTracked($entries['db_name'], $entries['table_name'])) {
$status = ' (' . __('active') . ')';
} else {
$status = ' (' . __('not active') . ')';
}
if ($entries['table_name'] == $_REQUEST['table']) {
$s = ' selected="selected"';
} else {
$s = '';
}
echo '<option value="' . htmlspecialchars($entries['table_name']) . '"' . $s . '>' . htmlspecialchars($entries['db_name']) . ' . ' . htmlspecialchars($entries['table_name']) . $status . '</option>' . "\n";
}
?>
</select>
<input type="submit" name="show_versions_submit" value="<?php echo __('Show versions');?>" />
</form>
<?php
}
?>
<br />
<?php
/*
* List versions of current table
*/
$sql_query = " SELECT * FROM " .
PMA_backquote($GLOBALS['cfg']['Server']['pmadb']) . "." .
PMA_backquote($GLOBALS['cfg']['Server']['tracking']) .
" WHERE db_name = '" . PMA_sqlAddSlashes($_REQUEST['db']) . "' ".
" AND table_name = '" . PMA_sqlAddSlashes($_REQUEST['table']) ."' ".
" ORDER BY version DESC ";
$sql_result = PMA_query_as_controluser($sql_query);
$last_version = 0;
$maxversion = PMA_DBI_fetch_array($sql_result);
$last_version = $maxversion['version'];
if ($last_version > 0) {
?>
<table id="versions" class="data">
<thead>
<tr>
<th><?php echo __('Database');?></th>
<th><?php echo __('Table');?></th>
<th><?php echo __('Version');?></th>
<th><?php echo __('Created');?></th>
<th><?php echo __('Updated');?></th>
<th><?php echo __('Status');?></th>
<th><?php echo __('Show');?></th>
</tr>
</thead>
<tbody>
<?php
$style = 'odd';
PMA_DBI_data_seek($sql_result, 0);
while ($version = PMA_DBI_fetch_array($sql_result)) {
if ($version['tracking_active'] == 1) {
$version_status = __('active');
} else {
$version_status = __('not active');
}
if ($version['version'] == $last_version) {
if ($version['tracking_active'] == 1) {
$tracking_active = true;
} else {
$tracking_active = false;
}
}
?>
<tr class="noclick <?php echo $style;?>">
<td><?php echo htmlspecialchars($version['db_name']);?></td>
<td><?php echo htmlspecialchars($version['table_name']);?></td>
<td><?php echo htmlspecialchars($version['version']);?></td>
<td><?php echo htmlspecialchars($version['date_created']);?></td>
<td><?php echo htmlspecialchars($version['date_updated']);?></td>
<td><?php echo $version_status;?></td>
<td> <a href="tbl_tracking.php<?php echo PMA_generate_common_url($url_params + array('report' => 'true', 'version' => $version['version'])
);?>"><?php echo __('Tracking report');?></a>
| <a href="tbl_tracking.php<?php echo PMA_generate_common_url($url_params + array('snapshot' => 'true', 'version' => $version['version'])
);?>"><?php echo __('Structure snapshot');?></a>
</td>
</tr>
<?php
if ($style == 'even') {
$style = 'odd';
} else {
$style = 'even';
}
}
?>
</tbody>
</table>
<?php if ($tracking_active == true) {?>
<div id="div_deactivate_tracking">
<form method="post" action="tbl_tracking.php?<?php echo $url_query; ?>">
<fieldset>
<legend><?php printf(__('Deactivate tracking for %s.%s'), htmlspecialchars($GLOBALS['db']), htmlspecialchars($GLOBALS['table'])); ?></legend>
<input type="hidden" name="version" value="<?php echo $last_version; ?>" />
<input type="submit" name="submit_deactivate_now" value="<?php echo __('Deactivate now'); ?>" />
</fieldset>
</form>
</div>
<?php
}
?>
<?php if ($tracking_active == false) {?>
<div id="div_activate_tracking">
<form method="post" action="tbl_tracking.php?<?php echo $url_query; ?>">
<fieldset>
<legend><?php printf(__('Activate tracking for %s.%s'), htmlspecialchars($GLOBALS['db']), htmlspecialchars($GLOBALS['table'])); ?></legend>
<input type="hidden" name="version" value="<?php echo $last_version; ?>" />
<input type="submit" name="submit_activate_now" value="<?php echo __('Activate now'); ?>" />
</fieldset>
</form>
</div>
<?php
}
}
?>
<div id="div_create_version">
<form method="post" action="tbl_tracking.php?<?php echo $url_query; ?>">
<?php echo PMA_generate_common_hidden_inputs($GLOBALS['db'], $GLOBALS['table']); ?>
<fieldset>
<legend><?php printf(__('Create version %s of %s.%s'), ($last_version + 1), htmlspecialchars($GLOBALS['db']), htmlspecialchars($GLOBALS['table'])); ?></legend>
<input type="hidden" name="version" value="<?php echo ($last_version + 1); ?>" />
<p><?php echo __('Track these data definition statements:');?></p>
<input type="checkbox" name="alter_table" value="true" checked="checked" /> ALTER TABLE<br/>
<input type="checkbox" name="rename_table" value="true" checked="checked" /> RENAME TABLE<br/>
<input type="checkbox" name="create_table" value="true" checked="checked" /> CREATE TABLE<br/>
<input type="checkbox" name="drop_table" value="true" checked="checked" /> DROP TABLE<br/>
<br/>
<input type="checkbox" name="create_index" value="true" checked="checked" /> CREATE INDEX<br/>
<input type="checkbox" name="drop_index" value="true" checked="checked" /> DROP INDEX<br/>
<p><?php echo __('Track these data manipulation statements:');?></p>
<input type="checkbox" name="insert" value="true" checked="checked" /> INSERT<br/>
<input type="checkbox" name="update" value="true" checked="checked" /> UPDATE<br/>
<input type="checkbox" name="delete" value="true" checked="checked" /> DELETE<br/>
<input type="checkbox" name="truncate" value="true" checked="checked" /> TRUNCATE<br/>
</fieldset>
<fieldset class="tblFooters">
<input type="submit" name="submit_create_version" value="<?php echo __('Create version'); ?>" />
</fieldset>
</form>
</div>
<br class="clearfloat"/>
<?php
/**
* Displays the footer
*/
require './libraries/footer.inc.php';
?>
| mit |
nameofname/momo-wordpress-theme | wp-content/themes/annotum-base/plugins/anno-pdf-download/lib/dompdf/www/test/css_float.html | 2003 | <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-15">
<style>
.left {
float: left;
border: 1px solid green;
}
.right {
float: right;
border: 1px solid blue;
}
.block {
float: left;
border: 1px solid red;
}
</style>
</head>
<body>
<div style="border: 1px solid black; width: 600px; padding: 1em; text-align: justify;">
<img src="images/dompdf_simple.png" style="float: left; margin-right: 0.5em; margin-bottom: 0.5em;" />
Lorem ipsum dolor sit amet, consectetuer <strong>adipiscing</strong> elit. Sed non risus. Suspendisse lectus <strong>tortor</strong>, dignissim sit amet, adipiscing nec, ultricies sed, dolor.
Cras elementum <em>ultrices</em> diam. Maecenas ligula massa, varius a, semper congue, euismod non, mi.
<img src="images/goldengate.jpg" style="float: right; margin-left: 0.5em; margin-bottom: 0.5em;" width="220" />
Proin porttitor, orci nec nonummy molestie, enim est eleifend mi, non fermentum diam nisl sit amet erat.
Duis semper. Duis arcu massa, scelerisque vitae, <strong>consequat</strong> in, pretium a, enim. Pellentesque congue.
Ut in risus volutpat <em>libero</em> pharetra tempor. Cras vestibulum bibendum augue.
Praesent egestas leo in pede. Praesent blandit odio eu enim. Pellentesque sed dui ut augue blandit sodales.
Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Aliquam nibh.
Mauris ac mauris sed pede pellentesque fermentum.
</div>
<!--
<div style="border: 1px solid black; height: 400px; width: 200px; padding: 1em;">
<div class="left">left</div>
<div class="right">rmmmmmmmmmmmmmmmm mmmmmmmmmmmmmmmght</div>
before block
<div class="block" style="height: 30px;">block</div>
after block
<div class="left" style="height: 30px;">left2</div>
text
<div class="left">left3</div>
<div class="block">block2</div>
</div>
-->
</body> </html>
| gpl-2.0 |
kzittritsch/terraform-provider-bigip | vendor/github.com/hashicorp/terraform/terraform/graph_walk_operation.go | 313 | package terraform
//go:generate stringer -type=walkOperation graph_walk_operation.go
// walkOperation is an enum which tells the walkContext what to do.
type walkOperation byte
const (
walkInvalid walkOperation = iota
walkInput
walkApply
walkPlan
walkPlanDestroy
walkRefresh
walkValidate
walkDestroy
)
| mpl-2.0 |
stephaneAG/Titanium_test | showroomApp/build/iphone/Classes/TiUITabController.h | 743 | /**
* Appcelerator Titanium Mobile
* Copyright (c) 2009-2011 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the Apache Public License
* Please see the LICENSE included with this distribution for details.
*
* WARNING: This is generated code. Modify at your own risk and without support.
*/
#ifdef USE_TI_UITAB
#import "TiWindowProxy.h"
#import "TiUITabProxy.h"
#import "TiTabController.h"
@interface TiUITabController : TiViewController<TiTabController> {
@private
//Window is now the superclass's proxy.
TiUITabProxy *tab;
}
-(id)initWithProxy:(TiWindowProxy*)proxy tab:(TiUITabProxy*)tab;
@property(nonatomic,readonly) TiWindowProxy *window;
@property(nonatomic,readonly) TiUITabProxy *tab;
@end
#endif | mit |
aps243/kernel-imx | arch/arm/include/asm/kvm_mmu.h | 1665 | /*
* Copyright (C) 2012 - Virtual Open Systems and Columbia University
* Author: Christoffer Dall <[email protected]>
*
* This program 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 program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifndef __ARM_KVM_MMU_H__
#define __ARM_KVM_MMU_H__
int create_hyp_mappings(void *from, void *to);
int create_hyp_io_mappings(void *from, void *to, phys_addr_t);
void free_hyp_pmds(void);
int kvm_alloc_stage2_pgd(struct kvm *kvm);
void kvm_free_stage2_pgd(struct kvm *kvm);
int kvm_phys_addr_ioremap(struct kvm *kvm, phys_addr_t guest_ipa,
phys_addr_t pa, unsigned long size);
int kvm_handle_guest_abort(struct kvm_vcpu *vcpu, struct kvm_run *run);
void kvm_mmu_free_memory_caches(struct kvm_vcpu *vcpu);
phys_addr_t kvm_mmu_get_httbr(void);
int kvm_mmu_init(void);
void kvm_clear_hyp_idmap(void);
static inline bool kvm_is_write_fault(unsigned long hsr)
{
unsigned long hsr_ec = hsr >> HSR_EC_SHIFT;
if (hsr_ec == HSR_EC_IABT)
return false;
else if ((hsr & HSR_ISV) && !(hsr & HSR_WNR))
return false;
else
return true;
}
#endif /* __ARM_KVM_MMU_H__ */
| gpl-2.0 |
hshackathons/zeroclickinfo-spice | share/spice/bacon_ipsum/bacon_ipsum.js | 910 | (function (env) {
"use strict";
env.ddg_spice_bacon_ipsum = function(api_result){
if (!api_result || api_result.error) {
return Spice.failed('bacon_ipsum');
}
var pageContent = '';
for (var i in api_result) {
pageContent += "<p>" + api_result[i] + "</p>";
}
Spice.add({
id: 'bacon_ipsum',
name: 'Bacon Ipsum',
data: {
content: pageContent,
title: "Bacon Ipsum",
subtitle: "Randomly generated text"
},
meta: {
sourceName: 'Bacon Ipsum',
sourceUrl: 'http://baconipsum.com/'
},
templates: {
group: 'text',
options: {
content: Spice.bacon_ipsum.content
}
}
});
};
}(this));
| apache-2.0 |
scheib/chromium | third_party/blink/web_tests/fast/forms/label/label-focus.html | 906 | <html>
<head>
<script>
function runTest() {
if (window.testRunner)
testRunner.dumpAsText();
var label1 = document.getElementById('label1');
label1.focus();
if (document.getElementById('cb1') != document.activeElement)
return;
var label2 = document.getElementById('label2');
label2.focus();
if (document.getElementById('cb2') != document.activeElement)
return;
document.getElementById('result').innerHTML = 'SUCCESS'
}
</script>
</head>
<body onload="runTest()">
This tests that the correct form control element is activated when clicking on a label.
If the test is successful, the text "SUCCESS" should show below.<br>
<Label id="label1">label1<input id="cb1" type="checkbox"></label><br>
<Label id="label2">label2<fieldset><legend><input id="cb2" type="checkbox"></legend></fieldset></label><br>
<div id="result">FAILURE</div>
</body>
</html>
| bsd-3-clause |
chromium/chromium | third_party/blink/web_tests/fast/media/resources/viewport-media-query.html | 146 | <head>
<style>
body {
background-color: black;
}
@media all and (min-width:600px)
{
body { background-color: green }
}
</style>
</head>
<body>
| bsd-3-clause |
scheib/chromium | third_party/blink/web_tests/fast/dom/HTMLMeterElement/meter-boundary-values.html | 1896 | <html>
<head>
</head>
<body>
<h1>Meters with border values</h1>
<ul>
<li>min,low,optimal,high,max</li>
<li><b>9</b>|10,20,30,40,50: <meter min="10" low="20" optimum="30" high="40" max="50" value="9" ></meter></li>
<li><b>10</b>,20,30,40,50: <meter min="10" low="20" optimum="30" high="40" max="50" value="10" ></meter></li>
<li>10,<b>20</b>,30,40,50: <meter min="10" low="20" optimum="30" high="40" max="50" value="20" ></meter>(should be green)</li>
<li>10,20,<b>30</b>,40,50: <meter min="10" low="20" optimum="30" high="40" max="50" value="30" ></meter>(should be green)</li>
<li>10,20,30,<b>40</b>,50: <meter min="10" low="20" optimum="30" high="40" max="50" value="40" ></meter>(should be green)</li>
<li>10,20,30,40,<b>50</b>: <meter min="10" low="20" optimum="30" high="40" max="50" value="50" ></meter>(should be yellow)</li>
<li>10,20,30,40,50|<b>51</b>: <meter min="10" low="20" optimum="30" high="40" max="50" value="51" ></meter>(should be yellow)</li>
<li>10,<b>10</b>,30,40,50: <meter min="10" low="10" optimum="30" high="40" max="50" value="10" ></meter></li>
<li>10,20,30,<b>40</b>,40: <meter min="10" low="20" optimum="30" high="40" max="40" value="40" ></meter>(should be green)</li>
<li><b>9</b>|10,10,10,20,30: <meter min="10" low="10" optimum="10" high="20" max="30" value="9" ></meter></li>
<li>10,10,<b>10</b>,20,30: <meter min="10" low="10" optimum="10" high="20" max="30" value="10" ></meter></li>
<li>10,20,<b>30</b>,30,30: <meter min="10" low="20" optimum="30" high="30" max="30" value="30" ></meter>(should be green)</li>
<li>10,20,30,30,30|<b>31</b>: <meter min="10" low="20" optimum="30" high="30" max="30" value="31" ></meter>(should be green)</li>
<li>10,20,<b>20</b>,20,30: <meter min="10" low="20" optimum="20" high="20" max="30" value="20" ></meter>(should be green)</li>
</ul>
</body>
</html>
| bsd-3-clause |
Priya91/coreclr | src/mscorlib/src/System/Globalization/SortKey.cs | 6975 | // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
////////////////////////////////////////////////////////////////////////////
//
//
// Purpose: This class implements a set of methods for retrieving
// sort key information.
//
//
////////////////////////////////////////////////////////////////////////////
namespace System.Globalization {
using System;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Diagnostics.Contracts;
[System.Runtime.InteropServices.ComVisible(true)]
[Serializable] public class SortKey
{
//--------------------------------------------------------------------//
// Internal Information //
//--------------------------------------------------------------------//
//
// Variables.
//
[OptionalField(VersionAdded = 3)]
internal String localeName; // locale identifier
[OptionalField(VersionAdded = 1)] // LCID field so serialization is Whidbey compatible though we don't officially support it
internal int win32LCID;
// Whidbey serialization
internal CompareOptions options; // options
internal String m_String; // original string
internal byte[] m_KeyData; // sortkey data
//
// The following constructor is designed to be called from CompareInfo to get the
// the sort key of specific string for synthetic culture
//
internal SortKey(String localeName, String str, CompareOptions options, byte[] keyData)
{
this.m_KeyData = keyData;
this.localeName = localeName;
this.options = options;
this.m_String = str;
}
#if FEATURE_USE_LCID
[OnSerializing]
private void OnSerializing(StreamingContext context)
{
//set LCID to proper value for Whidbey serialization (no other use)
if (win32LCID == 0)
{
win32LCID = CultureInfo.GetCultureInfo(localeName).LCID;
}
}
[OnDeserialized]
private void OnDeserialized(StreamingContext context)
{
//set locale name to proper value after Whidbey deserialization
if (String.IsNullOrEmpty(localeName) && win32LCID != 0)
{
localeName = CultureInfo.GetCultureInfo(win32LCID).Name;
}
}
#endif //FEATURE_USE_LCID
////////////////////////////////////////////////////////////////////////
//
// GetOriginalString
//
// Returns the original string used to create the current instance
// of SortKey.
//
////////////////////////////////////////////////////////////////////////
public virtual String OriginalString
{
get {
return (m_String);
}
}
////////////////////////////////////////////////////////////////////////
//
// GetKeyData
//
// Returns a byte array representing the current instance of the
// sort key.
//
////////////////////////////////////////////////////////////////////////
public virtual byte[] KeyData
{
get {
return (byte[])(m_KeyData.Clone());
}
}
////////////////////////////////////////////////////////////////////////
//
// Compare
//
// Compares the two sort keys. Returns 0 if the two sort keys are
// equal, a number less than 0 if sortkey1 is less than sortkey2,
// and a number greater than 0 if sortkey1 is greater than sortkey2.
//
////////////////////////////////////////////////////////////////////////
public static int Compare(SortKey sortkey1, SortKey sortkey2) {
if (sortkey1==null || sortkey2==null) {
throw new ArgumentNullException((sortkey1==null ? "sortkey1": "sortkey2"));
}
Contract.EndContractBlock();
byte[] key1Data = sortkey1.m_KeyData;
byte[] key2Data = sortkey2.m_KeyData;
Contract.Assert(key1Data!=null, "key1Data!=null");
Contract.Assert(key2Data!=null, "key2Data!=null");
if (key1Data.Length == 0) {
if (key2Data.Length == 0) {
return (0);
}
return (-1);
}
if (key2Data.Length == 0) {
return (1);
}
int compLen = (key1Data.Length<key2Data.Length)?key1Data.Length:key2Data.Length;
for (int i=0; i<compLen; i++) {
if (key1Data[i]>key2Data[i]) {
return (1);
}
if (key1Data[i]<key2Data[i]) {
return (-1);
}
}
return 0;
}
////////////////////////////////////////////////////////////////////////
//
// Equals
//
// Implements Object.Equals(). Returns a boolean indicating whether
// or not object refers to the same SortKey as the current instance.
//
////////////////////////////////////////////////////////////////////////
public override bool Equals(Object value)
{
SortKey that = value as SortKey;
if (that != null)
{
return Compare(this, that) == 0;
}
return (false);
}
////////////////////////////////////////////////////////////////////////
//
// GetHashCode
//
// Implements Object.GetHashCode(). Returns the hash code for the
// SortKey. The hash code is guaranteed to be the same for
// SortKey A and B where A.Equals(B) is true.
//
////////////////////////////////////////////////////////////////////////
public override int GetHashCode()
{
return (CompareInfo.GetCompareInfo(
this.localeName).GetHashCodeOfString(this.m_String, this.options));
}
////////////////////////////////////////////////////////////////////////
//
// ToString
//
// Implements Object.ToString(). Returns a string describing the
// SortKey.
//
////////////////////////////////////////////////////////////////////////
public override String ToString()
{
return ("SortKey - " + localeName + ", " + options + ", " + m_String);
}
}
}
| mit |
Priya91/coreclr | src/mscorlib/src/System/Collections/Generic/Comparer.cs | 5796 | // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
//using System.Globalization;
using System.Runtime.CompilerServices;
namespace System.Collections.Generic
{
[Serializable]
[TypeDependencyAttribute("System.Collections.Generic.ObjectComparer`1")]
public abstract class Comparer<T> : IComparer, IComparer<T>
{
static volatile Comparer<T> defaultComparer;
public static Comparer<T> Default {
get {
Contract.Ensures(Contract.Result<Comparer<T>>() != null);
Comparer<T> comparer = defaultComparer;
if (comparer == null) {
comparer = CreateComparer();
defaultComparer = comparer;
}
return comparer;
}
}
public static Comparer<T> Create(Comparison<T> comparison)
{
Contract.Ensures(Contract.Result<Comparer<T>>() != null);
if (comparison == null)
throw new ArgumentNullException("comparison");
return new ComparisonComparer<T>(comparison);
}
//
// Note that logic in this method is replicated in vm\compile.cpp to ensure that NGen
// saves the right instantiations
//
[System.Security.SecuritySafeCritical] // auto-generated
private static Comparer<T> CreateComparer() {
RuntimeType t = (RuntimeType)typeof(T);
// If T implements IComparable<T> return a GenericComparer<T>
#if FEATURE_LEGACYNETCF
// Pre-Apollo Windows Phone call the overload that sorts the keys, not values this achieves the same result
if (CompatibilitySwitches.IsAppEarlierThanWindowsPhone8) {
if (t.ImplementInterface(typeof(IComparable<T>))) {
return (Comparer<T>)RuntimeTypeHandle.CreateInstanceForAnotherGenericParameter((RuntimeType)typeof(GenericComparer<int>), t);
}
}
else
#endif
if (typeof(IComparable<T>).IsAssignableFrom(t)) {
return (Comparer<T>)RuntimeTypeHandle.CreateInstanceForAnotherGenericParameter((RuntimeType)typeof(GenericComparer<int>), t);
}
// If T is a Nullable<U> where U implements IComparable<U> return a NullableComparer<U>
if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>)) {
RuntimeType u = (RuntimeType)t.GetGenericArguments()[0];
if (typeof(IComparable<>).MakeGenericType(u).IsAssignableFrom(u)) {
return (Comparer<T>)RuntimeTypeHandle.CreateInstanceForAnotherGenericParameter((RuntimeType)typeof(NullableComparer<int>), u);
}
}
// Otherwise return an ObjectComparer<T>
return new ObjectComparer<T>();
}
public abstract int Compare(T x, T y);
int IComparer.Compare(object x, object y) {
if (x == null) return y == null ? 0 : -1;
if (y == null) return 1;
if (x is T && y is T) return Compare((T)x, (T)y);
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidArgumentForComparison);
return 0;
}
}
[Serializable]
internal class GenericComparer<T> : Comparer<T> where T: IComparable<T>
{
public override int Compare(T x, T y) {
if (x != null) {
if (y != null) return x.CompareTo(y);
return 1;
}
if (y != null) return -1;
return 0;
}
// Equals method for the comparer itself.
public override bool Equals(Object obj){
GenericComparer<T> comparer = obj as GenericComparer<T>;
return comparer != null;
}
public override int GetHashCode() {
return this.GetType().Name.GetHashCode();
}
}
[Serializable]
internal class NullableComparer<T> : Comparer<Nullable<T>> where T : struct, IComparable<T>
{
public override int Compare(Nullable<T> x, Nullable<T> y) {
if (x.HasValue) {
if (y.HasValue) return x.value.CompareTo(y.value);
return 1;
}
if (y.HasValue) return -1;
return 0;
}
// Equals method for the comparer itself.
public override bool Equals(Object obj){
NullableComparer<T> comparer = obj as NullableComparer<T>;
return comparer != null;
}
public override int GetHashCode() {
return this.GetType().Name.GetHashCode();
}
}
[Serializable]
internal class ObjectComparer<T> : Comparer<T>
{
public override int Compare(T x, T y) {
return System.Collections.Comparer.Default.Compare(x, y);
}
// Equals method for the comparer itself.
public override bool Equals(Object obj){
ObjectComparer<T> comparer = obj as ObjectComparer<T>;
return comparer != null;
}
public override int GetHashCode() {
return this.GetType().Name.GetHashCode();
}
}
[Serializable]
internal class ComparisonComparer<T> : Comparer<T>
{
private readonly Comparison<T> _comparison;
public ComparisonComparer(Comparison<T> comparison) {
_comparison = comparison;
}
public override int Compare(T x, T y) {
return _comparison(x, y);
}
}
}
| mit |
mavasani/roslyn-analyzers | tools/AnalyzerCodeGenerator/template/src/Test/Utilities/CodeFixTests.Extensions.cs | 826 | // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CSharp;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.UnitTests
{
public static class DiagnosticFixerTestsExtensions
{
internal static Document Apply(this Document document, CodeAction action)
{
var operations = action.GetOperationsAsync(CancellationToken.None).Result;
var solution = operations.OfType<ApplyChangesOperation>().Single().ChangedSolution;
return solution.GetDocument(document.Id);
}
}
}
| apache-2.0 |
tcotav/etcdhooks | vendor/src/github.com/xordataexchange/crypt/backend/consul/consul.go | 1810 | package consul
import (
"fmt"
"strings"
"time"
"github.com/xordataexchange/crypt/backend"
"github.com/armon/consul-api"
)
type Client struct {
client *consulapi.KV
waitIndex uint64
}
func New(machines []string) (*Client, error) {
conf := consulapi.DefaultConfig()
if len(machines) > 0 {
conf.Address = machines[0]
}
client, err := consulapi.NewClient(conf)
if err != nil {
return nil, err
}
return &Client{client.KV(), 0}, nil
}
func (c *Client) Get(key string) ([]byte, error) {
kv, _, err := c.client.Get(key, nil)
if err != nil {
return nil, err
}
if kv == nil {
return nil, fmt.Errorf("Key ( %s ) was not found.", key)
}
return kv.Value, nil
}
func (c *Client) List(key string) (backend.KVPairs, error) {
pairs, _, err := c.client.List(key, nil)
if err != nil {
return nil, err
}
if err != nil {
return nil, err
}
ret := make(backend.KVPairs, len(pairs), len(pairs))
for i, kv := range pairs {
ret[i] = &backend.KVPair{Key: kv.Key, Value: kv.Value}
}
return ret, nil
}
func (c *Client) Set(key string, value []byte) error {
key = strings.TrimPrefix(key, "/")
kv := &consulapi.KVPair{
Key: key,
Value: value,
}
_, err := c.client.Put(kv, nil)
return err
}
func (c *Client) Watch(key string, stop chan bool) <-chan *backend.Response {
respChan := make(chan *backend.Response, 0)
go func() {
for {
opts := consulapi.QueryOptions{
WaitIndex: c.waitIndex,
}
keypair, meta, err := c.client.Get(key, &opts)
if keypair == nil && err == nil {
err = fmt.Errorf("Key ( %s ) was not found.", key)
}
if err != nil {
respChan <- &backend.Response{nil, err}
time.Sleep(time.Second * 5)
continue
}
c.waitIndex = meta.LastIndex
respChan <- &backend.Response{keypair.Value, nil}
}
}()
return respChan
}
| mit |
jcgruenhage/dendrite | vendor/src/github.com/apache/thrift/lib/c_glib/test/testsimpleserver.c | 3143 | /*
* 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.
*/
#include <assert.h>
#include <glib.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <thrift/c_glib/thrift.h>
#include <thrift/c_glib/processor/thrift_processor.h>
#include <thrift/c_glib/transport/thrift_server_socket.h>
#define TEST_PORT 51199
#include <thrift/c_glib/server/thrift_simple_server.c>
/* create a rudimentary processor */
#define TEST_PROCESSOR_TYPE (test_processor_get_type ())
struct _TestProcessor
{
ThriftProcessor parent;
};
typedef struct _TestProcessor TestProcessor;
struct _TestProcessorClass
{
ThriftProcessorClass parent;
};
typedef struct _TestProcessorClass TestProcessorClass;
G_DEFINE_TYPE(TestProcessor, test_processor, THRIFT_TYPE_PROCESSOR)
gboolean
test_processor_process (ThriftProcessor *processor, ThriftProtocol *in,
ThriftProtocol *out, GError **error)
{
THRIFT_UNUSED_VAR (processor);
THRIFT_UNUSED_VAR (in);
THRIFT_UNUSED_VAR (out);
THRIFT_UNUSED_VAR (error);
return FALSE;
}
static void
test_processor_init (TestProcessor *p)
{
THRIFT_UNUSED_VAR (p);
}
static void
test_processor_class_init (TestProcessorClass *proc)
{
(THRIFT_PROCESSOR_CLASS(proc))->process = test_processor_process;
}
static void
test_server (void)
{
int status;
pid_t pid;
TestProcessor *p = NULL;
ThriftServerSocket *tss = NULL;
ThriftSimpleServer *ss = NULL;
p = g_object_new (TEST_PROCESSOR_TYPE, NULL);
tss = g_object_new (THRIFT_TYPE_SERVER_SOCKET, "port", TEST_PORT, NULL);
ss = g_object_new (THRIFT_TYPE_SIMPLE_SERVER, "processor", p,
"server_transport", THRIFT_SERVER_TRANSPORT (tss), NULL);
/* run the server in a child process */
pid = fork ();
assert (pid >= 0);
if (pid == 0)
{
THRIFT_SERVER_GET_CLASS (THRIFT_SERVER (ss))->serve (THRIFT_SERVER (ss),
NULL);
exit (0);
} else {
sleep (5);
kill (pid, SIGINT);
g_object_unref (ss);
g_object_unref (tss);
g_object_unref (p);
assert (wait (&status) == pid);
assert (status == SIGINT);
}
}
int
main(int argc, char *argv[])
{
#if (!GLIB_CHECK_VERSION (2, 36, 0))
g_type_init();
#endif
g_test_init (&argc, &argv, NULL);
g_test_add_func ("/testsimpleserver/SimpleServer", test_server);
return g_test_run ();
}
| apache-2.0 |
edeati/alexa-translink-skill-js | test/node_modules/aws-sdk/clients/cloudsearchdomain.js | 615 | require('../lib/node_loader');
var AWS = require('../lib/core');
var Service = require('../lib/service');
var apiLoader = require('../lib/api_loader');
apiLoader.services['cloudsearchdomain'] = {};
AWS.CloudSearchDomain = Service.defineService('cloudsearchdomain', ['2013-01-01']);
require('../lib/services/cloudsearchdomain');
Object.defineProperty(apiLoader.services['cloudsearchdomain'], '2013-01-01', {
get: function get() {
var model = require('../apis/cloudsearchdomain-2013-01-01.min.json');
return model;
},
enumerable: true,
configurable: true
});
module.exports = AWS.CloudSearchDomain;
| apache-2.0 |
LumPenPacK/NetworkExtractionFromImages | win_build/nefi2_win_amd64_msvc_2015/site-packages/numpy/distutils/exec_command.py | 20462 | #!/usr/bin/env python
"""
exec_command
Implements exec_command function that is (almost) equivalent to
commands.getstatusoutput function but on NT, DOS systems the
returned status is actually correct (though, the returned status
values may be different by a factor). In addition, exec_command
takes keyword arguments for (re-)defining environment variables.
Provides functions:
exec_command --- execute command in a specified directory and
in the modified environment.
find_executable --- locate a command using info from environment
variable PATH. Equivalent to posix `which`
command.
Author: Pearu Peterson <[email protected]>
Created: 11 January 2003
Requires: Python 2.x
Succesfully tested on:
======== ============ =================================================
os.name sys.platform comments
======== ============ =================================================
posix linux2 Debian (sid) Linux, Python 2.1.3+, 2.2.3+, 2.3.3
PyCrust 0.9.3, Idle 1.0.2
posix linux2 Red Hat 9 Linux, Python 2.1.3, 2.2.2, 2.3.2
posix sunos5 SunOS 5.9, Python 2.2, 2.3.2
posix darwin Darwin 7.2.0, Python 2.3
nt win32 Windows Me
Python 2.3(EE), Idle 1.0, PyCrust 0.7.2
Python 2.1.1 Idle 0.8
nt win32 Windows 98, Python 2.1.1. Idle 0.8
nt win32 Cygwin 98-4.10, Python 2.1.1(MSC) - echo tests
fail i.e. redefining environment variables may
not work. FIXED: don't use cygwin echo!
Comment: also `cmd /c echo` will not work
but redefining environment variables do work.
posix cygwin Cygwin 98-4.10, Python 2.3.3(cygming special)
nt win32 Windows XP, Python 2.3.3
======== ============ =================================================
Known bugs:
* Tests, that send messages to stderr, fail when executed from MSYS prompt
because the messages are lost at some point.
"""
from __future__ import division, absolute_import, print_function
__all__ = ['exec_command', 'find_executable']
import os
import sys
import shlex
from numpy.distutils.misc_util import is_sequence, make_temp_file
from numpy.distutils import log
from numpy.distutils.compat import get_exception
from numpy.compat import open_latin1
def temp_file_name():
fo, name = make_temp_file()
fo.close()
return name
def get_pythonexe():
pythonexe = sys.executable
if os.name in ['nt', 'dos']:
fdir, fn = os.path.split(pythonexe)
fn = fn.upper().replace('PYTHONW', 'PYTHON')
pythonexe = os.path.join(fdir, fn)
assert os.path.isfile(pythonexe), '%r is not a file' % (pythonexe,)
return pythonexe
def find_executable(exe, path=None, _cache={}):
"""Return full path of a executable or None.
Symbolic links are not followed.
"""
key = exe, path
try:
return _cache[key]
except KeyError:
pass
log.debug('find_executable(%r)' % exe)
orig_exe = exe
if path is None:
path = os.environ.get('PATH', os.defpath)
if os.name=='posix':
realpath = os.path.realpath
else:
realpath = lambda a:a
if exe.startswith('"'):
exe = exe[1:-1]
suffixes = ['']
if os.name in ['nt', 'dos', 'os2']:
fn, ext = os.path.splitext(exe)
extra_suffixes = ['.exe', '.com', '.bat']
if ext.lower() not in extra_suffixes:
suffixes = extra_suffixes
if os.path.isabs(exe):
paths = ['']
else:
paths = [ os.path.abspath(p) for p in path.split(os.pathsep) ]
for path in paths:
fn = os.path.join(path, exe)
for s in suffixes:
f_ext = fn+s
if not os.path.islink(f_ext):
f_ext = realpath(f_ext)
if os.path.isfile(f_ext) and os.access(f_ext, os.X_OK):
log.info('Found executable %s' % f_ext)
_cache[key] = f_ext
return f_ext
log.warn('Could not locate executable %s' % orig_exe)
return None
############################################################
def _preserve_environment( names ):
log.debug('_preserve_environment(%r)' % (names))
env = {}
for name in names:
env[name] = os.environ.get(name)
return env
def _update_environment( **env ):
log.debug('_update_environment(...)')
for name, value in env.items():
os.environ[name] = value or ''
def _supports_fileno(stream):
"""
Returns True if 'stream' supports the file descriptor and allows fileno().
"""
if hasattr(stream, 'fileno'):
try:
r = stream.fileno()
return True
except IOError:
return False
else:
return False
def exec_command(command, execute_in='', use_shell=None, use_tee=None,
_with_python = 1, **env ):
"""
Return (status,output) of executed command.
Parameters
----------
command : str
A concatenated string of executable and arguments.
execute_in : str
Before running command ``cd execute_in`` and after ``cd -``.
use_shell : {bool, None}, optional
If True, execute ``sh -c command``. Default None (True)
use_tee : {bool, None}, optional
If True use tee. Default None (True)
Returns
-------
res : str
Both stdout and stderr messages.
Notes
-----
On NT, DOS systems the returned status is correct for external commands.
Wild cards will not work for non-posix systems or when use_shell=0.
"""
log.debug('exec_command(%r,%s)' % (command,\
','.join(['%s=%r'%kv for kv in env.items()])))
if use_tee is None:
use_tee = os.name=='posix'
if use_shell is None:
use_shell = os.name=='posix'
execute_in = os.path.abspath(execute_in)
oldcwd = os.path.abspath(os.getcwd())
if __name__[-12:] == 'exec_command':
exec_dir = os.path.dirname(os.path.abspath(__file__))
elif os.path.isfile('exec_command.py'):
exec_dir = os.path.abspath('.')
else:
exec_dir = os.path.abspath(sys.argv[0])
if os.path.isfile(exec_dir):
exec_dir = os.path.dirname(exec_dir)
if oldcwd!=execute_in:
os.chdir(execute_in)
log.debug('New cwd: %s' % execute_in)
else:
log.debug('Retaining cwd: %s' % oldcwd)
oldenv = _preserve_environment( list(env.keys()) )
_update_environment( **env )
try:
# _exec_command is robust but slow, it relies on
# usable sys.std*.fileno() descriptors. If they
# are bad (like in win32 Idle, PyCrust environments)
# then _exec_command_python (even slower)
# will be used as a last resort.
#
# _exec_command_posix uses os.system and is faster
# but not on all platforms os.system will return
# a correct status.
if (_with_python and _supports_fileno(sys.stdout) and
sys.stdout.fileno() == -1):
st = _exec_command_python(command,
exec_command_dir = exec_dir,
**env)
elif os.name=='posix':
st = _exec_command_posix(command,
use_shell=use_shell,
use_tee=use_tee,
**env)
else:
st = _exec_command(command, use_shell=use_shell,
use_tee=use_tee,**env)
finally:
if oldcwd!=execute_in:
os.chdir(oldcwd)
log.debug('Restored cwd to %s' % oldcwd)
_update_environment(**oldenv)
return st
def _exec_command_posix( command,
use_shell = None,
use_tee = None,
**env ):
log.debug('_exec_command_posix(...)')
if is_sequence(command):
command_str = ' '.join(list(command))
else:
command_str = command
tmpfile = temp_file_name()
stsfile = None
if use_tee:
stsfile = temp_file_name()
filter = ''
if use_tee == 2:
filter = r'| tr -cd "\n" | tr "\n" "."; echo'
command_posix = '( %s ; echo $? > %s ) 2>&1 | tee %s %s'\
% (command_str, stsfile, tmpfile, filter)
else:
stsfile = temp_file_name()
command_posix = '( %s ; echo $? > %s ) > %s 2>&1'\
% (command_str, stsfile, tmpfile)
#command_posix = '( %s ) > %s 2>&1' % (command_str,tmpfile)
log.debug('Running os.system(%r)' % (command_posix))
status = os.system(command_posix)
if use_tee:
if status:
# if command_tee fails then fall back to robust exec_command
log.warn('_exec_command_posix failed (status=%s)' % status)
return _exec_command(command, use_shell=use_shell, **env)
if stsfile is not None:
f = open_latin1(stsfile, 'r')
status_text = f.read()
status = int(status_text)
f.close()
os.remove(stsfile)
f = open_latin1(tmpfile, 'r')
text = f.read()
f.close()
os.remove(tmpfile)
if text[-1:]=='\n':
text = text[:-1]
return status, text
def _exec_command_python(command,
exec_command_dir='', **env):
log.debug('_exec_command_python(...)')
python_exe = get_pythonexe()
cmdfile = temp_file_name()
stsfile = temp_file_name()
outfile = temp_file_name()
f = open(cmdfile, 'w')
f.write('import os\n')
f.write('import sys\n')
f.write('sys.path.insert(0,%r)\n' % (exec_command_dir))
f.write('from exec_command import exec_command\n')
f.write('del sys.path[0]\n')
f.write('cmd = %r\n' % command)
f.write('os.environ = %r\n' % (os.environ))
f.write('s,o = exec_command(cmd, _with_python=0, **%r)\n' % (env))
f.write('f=open(%r,"w")\nf.write(str(s))\nf.close()\n' % (stsfile))
f.write('f=open(%r,"w")\nf.write(o)\nf.close()\n' % (outfile))
f.close()
cmd = '%s %s' % (python_exe, cmdfile)
status = os.system(cmd)
if status:
raise RuntimeError("%r failed" % (cmd,))
os.remove(cmdfile)
f = open_latin1(stsfile, 'r')
status = int(f.read())
f.close()
os.remove(stsfile)
f = open_latin1(outfile, 'r')
text = f.read()
f.close()
os.remove(outfile)
return status, text
def quote_arg(arg):
if arg[0]!='"' and ' ' in arg:
return '"%s"' % arg
return arg
def _exec_command( command, use_shell=None, use_tee = None, **env ):
log.debug('_exec_command(...)')
if use_shell is None:
use_shell = os.name=='posix'
if use_tee is None:
use_tee = os.name=='posix'
using_command = 0
if use_shell:
# We use shell (unless use_shell==0) so that wildcards can be
# used.
sh = os.environ.get('SHELL', '/bin/sh')
if is_sequence(command):
argv = [sh, '-c', ' '.join(list(command))]
else:
argv = [sh, '-c', command]
else:
# On NT, DOS we avoid using command.com as it's exit status is
# not related to the exit status of a command.
if is_sequence(command):
argv = command[:]
else:
argv = shlex.split(command)
if hasattr(os, 'spawnvpe'):
spawn_command = os.spawnvpe
else:
spawn_command = os.spawnve
argv[0] = find_executable(argv[0]) or argv[0]
if not os.path.isfile(argv[0]):
log.warn('Executable %s does not exist' % (argv[0]))
if os.name in ['nt', 'dos']:
# argv[0] might be internal command
argv = [os.environ['COMSPEC'], '/C'] + argv
using_command = 1
_so_has_fileno = _supports_fileno(sys.stdout)
_se_has_fileno = _supports_fileno(sys.stderr)
so_flush = sys.stdout.flush
se_flush = sys.stderr.flush
if _so_has_fileno:
so_fileno = sys.stdout.fileno()
so_dup = os.dup(so_fileno)
if _se_has_fileno:
se_fileno = sys.stderr.fileno()
se_dup = os.dup(se_fileno)
outfile = temp_file_name()
fout = open(outfile, 'w')
if using_command:
errfile = temp_file_name()
ferr = open(errfile, 'w')
log.debug('Running %s(%s,%r,%r,os.environ)' \
% (spawn_command.__name__, os.P_WAIT, argv[0], argv))
if sys.version_info[0] >= 3 and os.name == 'nt':
# Pre-encode os.environ, discarding un-encodable entries,
# to avoid it failing during encoding as part of spawn. Failure
# is possible if the environment contains entries that are not
# encoded using the system codepage as windows expects.
#
# This is not necessary on unix, where os.environ is encoded
# using the surrogateescape error handler and decoded using
# it as part of spawn.
encoded_environ = {}
for k, v in os.environ.items():
try:
encoded_environ[k.encode(sys.getfilesystemencoding())] = v.encode(
sys.getfilesystemencoding())
except UnicodeEncodeError:
log.debug("ignoring un-encodable env entry %s", k)
else:
encoded_environ = os.environ
argv0 = argv[0]
if not using_command:
argv[0] = quote_arg(argv0)
so_flush()
se_flush()
if _so_has_fileno:
os.dup2(fout.fileno(), so_fileno)
if _se_has_fileno:
if using_command:
#XXX: disabled for now as it does not work from cmd under win32.
# Tests fail on msys
os.dup2(ferr.fileno(), se_fileno)
else:
os.dup2(fout.fileno(), se_fileno)
try:
status = spawn_command(os.P_WAIT, argv0, argv, encoded_environ)
except Exception:
errmess = str(get_exception())
status = 999
sys.stderr.write('%s: %s'%(errmess, argv[0]))
so_flush()
se_flush()
if _so_has_fileno:
os.dup2(so_dup, so_fileno)
os.close(so_dup)
if _se_has_fileno:
os.dup2(se_dup, se_fileno)
os.close(se_dup)
fout.close()
fout = open_latin1(outfile, 'r')
text = fout.read()
fout.close()
os.remove(outfile)
if using_command:
ferr.close()
ferr = open_latin1(errfile, 'r')
errmess = ferr.read()
ferr.close()
os.remove(errfile)
if errmess and not status:
# Not sure how to handle the case where errmess
# contains only warning messages and that should
# not be treated as errors.
#status = 998
if text:
text = text + '\n'
#text = '%sCOMMAND %r FAILED: %s' %(text,command,errmess)
text = text + errmess
print (errmess)
if text[-1:]=='\n':
text = text[:-1]
if status is None:
status = 0
if use_tee:
print (text)
return status, text
def test_nt(**kws):
pythonexe = get_pythonexe()
echo = find_executable('echo')
using_cygwin_echo = echo != 'echo'
if using_cygwin_echo:
log.warn('Using cygwin echo in win32 environment is not supported')
s, o=exec_command(pythonexe\
+' -c "import os;print os.environ.get(\'AAA\',\'\')"')
assert s==0 and o=='', (s, o)
s, o=exec_command(pythonexe\
+' -c "import os;print os.environ.get(\'AAA\')"',
AAA='Tere')
assert s==0 and o=='Tere', (s, o)
os.environ['BBB'] = 'Hi'
s, o=exec_command(pythonexe\
+' -c "import os;print os.environ.get(\'BBB\',\'\')"')
assert s==0 and o=='Hi', (s, o)
s, o=exec_command(pythonexe\
+' -c "import os;print os.environ.get(\'BBB\',\'\')"',
BBB='Hey')
assert s==0 and o=='Hey', (s, o)
s, o=exec_command(pythonexe\
+' -c "import os;print os.environ.get(\'BBB\',\'\')"')
assert s==0 and o=='Hi', (s, o)
elif 0:
s, o=exec_command('echo Hello')
assert s==0 and o=='Hello', (s, o)
s, o=exec_command('echo a%AAA%')
assert s==0 and o=='a', (s, o)
s, o=exec_command('echo a%AAA%', AAA='Tere')
assert s==0 and o=='aTere', (s, o)
os.environ['BBB'] = 'Hi'
s, o=exec_command('echo a%BBB%')
assert s==0 and o=='aHi', (s, o)
s, o=exec_command('echo a%BBB%', BBB='Hey')
assert s==0 and o=='aHey', (s, o)
s, o=exec_command('echo a%BBB%')
assert s==0 and o=='aHi', (s, o)
s, o=exec_command('this_is_not_a_command')
assert s and o!='', (s, o)
s, o=exec_command('type not_existing_file')
assert s and o!='', (s, o)
s, o=exec_command('echo path=%path%')
assert s==0 and o!='', (s, o)
s, o=exec_command('%s -c "import sys;sys.stderr.write(sys.platform)"' \
% pythonexe)
assert s==0 and o=='win32', (s, o)
s, o=exec_command('%s -c "raise \'Ignore me.\'"' % pythonexe)
assert s==1 and o, (s, o)
s, o=exec_command('%s -c "import sys;sys.stderr.write(\'0\');sys.stderr.write(\'1\');sys.stderr.write(\'2\')"'\
% pythonexe)
assert s==0 and o=='012', (s, o)
s, o=exec_command('%s -c "import sys;sys.exit(15)"' % pythonexe)
assert s==15 and o=='', (s, o)
s, o=exec_command('%s -c "print \'Heipa\'"' % pythonexe)
assert s==0 and o=='Heipa', (s, o)
print ('ok')
def test_posix(**kws):
s, o=exec_command("echo Hello",**kws)
assert s==0 and o=='Hello', (s, o)
s, o=exec_command('echo $AAA',**kws)
assert s==0 and o=='', (s, o)
s, o=exec_command('echo "$AAA"',AAA='Tere',**kws)
assert s==0 and o=='Tere', (s, o)
s, o=exec_command('echo "$AAA"',**kws)
assert s==0 and o=='', (s, o)
os.environ['BBB'] = 'Hi'
s, o=exec_command('echo "$BBB"',**kws)
assert s==0 and o=='Hi', (s, o)
s, o=exec_command('echo "$BBB"',BBB='Hey',**kws)
assert s==0 and o=='Hey', (s, o)
s, o=exec_command('echo "$BBB"',**kws)
assert s==0 and o=='Hi', (s, o)
s, o=exec_command('this_is_not_a_command',**kws)
assert s!=0 and o!='', (s, o)
s, o=exec_command('echo path=$PATH',**kws)
assert s==0 and o!='', (s, o)
s, o=exec_command('python -c "import sys,os;sys.stderr.write(os.name)"',**kws)
assert s==0 and o=='posix', (s, o)
s, o=exec_command('python -c "raise \'Ignore me.\'"',**kws)
assert s==1 and o, (s, o)
s, o=exec_command('python -c "import sys;sys.stderr.write(\'0\');sys.stderr.write(\'1\');sys.stderr.write(\'2\')"',**kws)
assert s==0 and o=='012', (s, o)
s, o=exec_command('python -c "import sys;sys.exit(15)"',**kws)
assert s==15 and o=='', (s, o)
s, o=exec_command('python -c "print \'Heipa\'"',**kws)
assert s==0 and o=='Heipa', (s, o)
print ('ok')
def test_execute_in(**kws):
pythonexe = get_pythonexe()
tmpfile = temp_file_name()
fn = os.path.basename(tmpfile)
tmpdir = os.path.dirname(tmpfile)
f = open(tmpfile, 'w')
f.write('Hello')
f.close()
s, o = exec_command('%s -c "print \'Ignore the following IOError:\','\
'open(%r,\'r\')"' % (pythonexe, fn),**kws)
assert s and o!='', (s, o)
s, o = exec_command('%s -c "print open(%r,\'r\').read()"' % (pythonexe, fn),
execute_in = tmpdir,**kws)
assert s==0 and o=='Hello', (s, o)
os.remove(tmpfile)
print ('ok')
def test_svn(**kws):
s, o = exec_command(['svn', 'status'],**kws)
assert s, (s, o)
print ('svn ok')
def test_cl(**kws):
if os.name=='nt':
s, o = exec_command(['cl', '/V'],**kws)
assert s, (s, o)
print ('cl ok')
if os.name=='posix':
test = test_posix
elif os.name in ['nt', 'dos']:
test = test_nt
else:
raise NotImplementedError('exec_command tests for ', os.name)
############################################################
if __name__ == "__main__":
test(use_tee=0)
test(use_tee=1)
test_execute_in(use_tee=0)
test_execute_in(use_tee=1)
test_svn(use_tee=1)
test_cl(use_tee=1)
| bsd-2-clause |
masr/Beijiao | wp-content/plugins/nextgen-gallery-colorboxer/colorbox/3/colorbox.css | 2280 | /*
ColorBox Core Style:
The following CSS is consistent between example themes and should not be altered.
*/
#colorbox, #cboxOverlay, #cboxWrapper{position:absolute; top:0; left:0; z-index:9999; overflow:hidden;}
#cboxOverlay{position:fixed; width:100%; height:100%;}
#cboxMiddleLeft, #cboxBottomLeft{clear:left;}
#cboxContent{position:relative;}
#cboxLoadedContent{overflow:auto;}
#cboxTitle{margin:0;}
#cboxLoadingOverlay, #cboxLoadingGraphic{position:absolute; top:0; left:0; width:100%; height:100%;}
#cboxPrevious, #cboxNext, #cboxClose, #cboxSlideshow{cursor:pointer;}
.cboxPhoto{float:left; margin:auto; border:0; display:block;}
.cboxIframe{width:100%; height:100%; display:block; border:0;}
#colorbox, #cboxContent, #cboxLoadedContent{box-sizing:content-box;}
/*
User Style:
Change the following styles to modify the appearance of ColorBox. They are
ordered & tabbed in a way that represents the nesting of the generated HTML.
*/
#cboxOverlay{background:#000;}
#colorbox{}
#cboxContent{margin-top:20px;}
.cboxIframe{background:#fff;}
#cboxError{padding:50px; border:1px solid #ccc;}
#cboxLoadedContent{border:5px solid #000; background:#fff;}
#cboxTitle{position:absolute; top:-20px; left:0; color:#ccc;}
#cboxCurrent{position:absolute; top:-20px; right:0px; color:#ccc;}
#cboxSlideshow{position:absolute; top:-20px; right:90px; color:#fff;}
#cboxPrevious{position:absolute; top:50%; left:5px; margin-top:-32px; background:url(images/controls.png) no-repeat top left; width:28px; height:65px; text-indent:-9999px;}
#cboxPrevious:hover{background-position:bottom left;}
#cboxNext{position:absolute; top:50%; right:5px; margin-top:-32px; background:url(images/controls.png) no-repeat top right; width:28px; height:65px; text-indent:-9999px;}
#cboxNext:hover{background-position:bottom right;}
#cboxLoadingOverlay{background:#000;}
#cboxLoadingGraphic{background:url(images/loading.gif) no-repeat center center;}
#cboxClose{position:absolute; top:5px; right:5px; display:block; background:url(images/controls.png) no-repeat top center; width:38px; height:19px; text-indent:-9999px;}
#cboxClose:hover{background-position:bottom center;} | gpl-2.0 |
tobiasbuhrer/tobiasb | web/core/modules/file/src/Plugin/Field/FieldFormatter/FileMediaFormatterInterface.php | 667 | <?php
namespace Drupal\file\Plugin\Field\FieldFormatter;
/**
* Defines getter methods for FileMediaFormatterBase.
*
* This interface is used on the FileMediaFormatterBase class to ensure that
* each file media formatter will be based on a media type.
*
* Abstract classes are not able to implement abstract static methods,
* this interface will work around that.
*
* @see \Drupal\file\Plugin\Field\FieldFormatter\FileMediaFormatterBase
*/
interface FileMediaFormatterInterface {
/**
* Gets the applicable media type for a formatter.
*
* @return string
* The media type of this formatter.
*/
public static function getMediaType();
}
| gpl-2.0 |
AnyRTC/AnyRTC-RTMP | third_party/openh264/src/test/encoder/EncUT_InterfaceTest.cpp | 2699 | #include <gtest/gtest.h>
#include "codec_def.h"
#include "codec_api.h"
#include "utils/BufferedData.h"
#include "utils/FileInputStream.h"
#include "BaseEncoderTest.h"
class EncInterfaceCallTest : public ::testing::Test, public BaseEncoderTest {
public:
virtual void SetUp() {
BaseEncoderTest::SetUp();
};
virtual void TearDown() {
BaseEncoderTest::TearDown();
};
virtual void onEncodeFrame (const SFrameBSInfo& frameInfo) {
//nothing
}
//testing case
};
TEST_F (EncInterfaceCallTest, BaseParameterVerify) {
int uiTraceLevel = WELS_LOG_QUIET;
encoder_->SetOption (ENCODER_OPTION_TRACE_LEVEL, &uiTraceLevel);
int ret = cmResultSuccess;
SEncParamBase baseparam;
memset (&baseparam, 0, sizeof (SEncParamBase));
baseparam.iPicWidth = 0;
baseparam.iPicHeight = 7896;
ret = encoder_->Initialize (&baseparam);
EXPECT_EQ (ret, static_cast<int> (cmInitParaError));
uiTraceLevel = WELS_LOG_ERROR;
encoder_->SetOption (ENCODER_OPTION_TRACE_LEVEL, &uiTraceLevel);
}
void outputData() {
}
TEST_F (EncInterfaceCallTest, SetOptionLTR) {
int iTotalFrameNum = 100;
int iFrameNum = 0;
int frameSize = 0;
int ret = cmResultSuccess;
int width = 320;
int height = 192;
SEncParamBase baseparam;
memset (&baseparam, 0, sizeof (SEncParamBase));
baseparam.iUsageType = CAMERA_VIDEO_REAL_TIME;
baseparam.fMaxFrameRate = 12;
baseparam.iPicWidth = width;
baseparam.iPicHeight = height;
baseparam.iTargetBitrate = 5000000;
encoder_->Initialize (&baseparam);
frameSize = width * height * 3 / 2;
BufferedData buf;
buf.SetLength (frameSize);
ASSERT_TRUE (buf.Length() == (size_t)frameSize);
SFrameBSInfo info;
memset (&info, 0, sizeof (SFrameBSInfo));
SSourcePicture pic;
memset (&pic, 0, sizeof (SSourcePicture));
pic.iPicWidth = width;
pic.iPicHeight = height;
pic.iColorFormat = videoFormatI420;
pic.iStride[0] = pic.iPicWidth;
pic.iStride[1] = pic.iStride[2] = pic.iPicWidth >> 1;
pic.pData[0] = buf.data();
pic.pData[1] = pic.pData[0] + width * height;
pic.pData[2] = pic.pData[1] + (width * height >> 2);
SLTRConfig config;
config.bEnableLongTermReference = true;
config.iLTRRefNum = rand() % 4;
encoder_->SetOption (ENCODER_OPTION_LTR, &config);
do {
FileInputStream fileStream;
ASSERT_TRUE (fileStream.Open ("res/CiscoVT2people_320x192_12fps.yuv"));
while (fileStream.read (buf.data(), frameSize) == frameSize) {
ret = encoder_->EncodeFrame (&pic, &info);
ASSERT_TRUE (ret == cmResultSuccess);
if (info.eFrameType != videoFrameTypeSkip) {
this->onEncodeFrame (info);
iFrameNum++;
}
}
} while (iFrameNum < iTotalFrameNum);
} | gpl-3.0 |
oleksandr-minakov/northshore | ui/node_modules/@angular/core/src/application_tokens.d.ts | 1325 | import { OpaqueToken } from './di';
/**
* A DI Token representing a unique string id assigned to the application by Angular and used
* primarily for prefixing application attributes and CSS styles when
* {@link ViewEncapsulation#Emulated} is being used.
*
* If you need to avoid randomly generated value to be used as an application id, you can provide
* a custom value via a DI provider <!-- TODO: provider --> configuring the root {@link Injector}
* using this token.
* @experimental
*/
export declare const APP_ID: any;
export declare function _appIdRandomProviderFactory(): string;
/**
* Providers that will generate a random APP_ID_TOKEN.
* @experimental
*/
export declare const APP_ID_RANDOM_PROVIDER: {
provide: any;
useFactory: () => string;
deps: any[];
};
/**
* A function that will be executed when a platform is initialized.
* @experimental
*/
export declare const PLATFORM_INITIALIZER: any;
/**
* All callbacks provided via this token will be called for every component that is bootstrapped.
* Signature of the callback:
*
* `(componentRef: ComponentRef) => void`.
*
* @experimental
*/
export declare const APP_BOOTSTRAP_LISTENER: OpaqueToken;
/**
* A token which indicates the root directory of the application
* @experimental
*/
export declare const PACKAGE_ROOT_URL: any;
| apache-2.0 |
bcaceiro/homebrew-cask | Casks/navicat-for-sqlite.rb | 489 | cask :v1 => 'navicat-for-sqlite' do
version '11.1.13' # navicat-premium.rb and navicat-for-* should be upgraded together
sha256 'd8dfce2de0af81f7c0883773a3c5ed1be64eb076fb67708344d0748244b7566a'
url "http://download.navicat.com/download/navicat#{version.sub(%r{^(\d+)\.(\d+).*},'\1\2')}_sqlite_en.dmg"
name 'Navicat for SQLite'
homepage 'http://www.navicat.com/products/navicat-for-sqlite'
license :commercial
tags :vendor => 'Navicat'
app 'Navicat for SQLite.app'
end
| bsd-2-clause |
XiaosongWei/chromium-crosswalk | third_party/WebKit/LayoutTests/css3/filters/effect-reference-rename.html | 435 | <html>
<body>
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="0" height="0">
<defs>
<filter id="NotMyFilter">
<feColorMatrix type="hueRotate" values="180"/>
</filter>
</defs>
</svg><img style="-webkit-filter: url(#MyFilter); filter: url(#MyFilter);" src="resources/reference.png">
</body>
</html>
<script>
document.getElementById("NotMyFilter").id = "MyFilter";
</script>
| bsd-3-clause |