text
stringlengths 2
99.9k
| meta
dict |
---|---|
#
# BEGIN SONGBIRD GPL
#
# This file is part of the Songbird web player.
#
# Copyright(c) 2005-2008 POTI, Inc.
# http://www.songbirdnest.com
#
# This file may be licensed under the terms of of the
# GNU General Public License Version 2 (the GPL).
#
# Software distributed under the License is distributed
# on an AS IS basis, WITHOUT WARRANTY OF ANY KIND, either
# express or implied. See the GPL for the specific language
# governing rights and limitations.
#
# You should have received a copy of the GPL along with this
# program. If not, go to http://www.gnu.org/licenses/gpl.html
# or write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# END SONGBIRD GPL
#
DEPTH = ../../..
topsrcdir = @top_srcdir@
srcdir = @srcdir@
VPATH = @srcdir@
include $(DEPTH)/build/autodefs.mk
SONGBIRD_TEST_COMPONENT = displaypanes
SONGBIRD_TESTS = $(srcdir)/test_displaypanes.js \
$(NULL)
# If tests are enabled, build a stub extension in order
# to verify the install.rdf reader.
ifneq (,$(SB_ENABLE_TESTS))
SUBDIRS = test-extension
endif
include $(topsrcdir)/build/rules.mk
| {
"pile_set_name": "Github"
} |
/* ***** BEGIN LICENSE BLOCK *****
* Distributed under the BSD license:
*
* Copyright (c) 2010, Ajax.org B.V.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Ajax.org B.V. nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* ***** END LICENSE BLOCK ***** */
define(function(require, exports, module) {
"use strict";
var TokenIterator = require("../token_iterator").TokenIterator;
var Range = require("../range").Range;
function BracketMatch() {
this.findMatchingBracket = function(position, chr) {
if (position.column == 0) return null;
var charBeforeCursor = chr || this.getLine(position.row).charAt(position.column-1);
if (charBeforeCursor == "") return null;
var match = charBeforeCursor.match(/([\(\[\{])|([\)\]\}])/);
if (!match)
return null;
if (match[1])
return this.$findClosingBracket(match[1], position);
else
return this.$findOpeningBracket(match[2], position);
};
this.getBracketRange = function(pos) {
var line = this.getLine(pos.row);
var before = true, range;
var chr = line.charAt(pos.column-1);
var match = chr && chr.match(/([\(\[\{])|([\)\]\}])/);
if (!match) {
chr = line.charAt(pos.column);
pos = {row: pos.row, column: pos.column + 1};
match = chr && chr.match(/([\(\[\{])|([\)\]\}])/);
before = false;
}
if (!match)
return null;
if (match[1]) {
var bracketPos = this.$findClosingBracket(match[1], pos);
if (!bracketPos)
return null;
range = Range.fromPoints(pos, bracketPos);
if (!before) {
range.end.column++;
range.start.column--;
}
range.cursor = range.end;
} else {
var bracketPos = this.$findOpeningBracket(match[2], pos);
if (!bracketPos)
return null;
range = Range.fromPoints(bracketPos, pos);
if (!before) {
range.start.column++;
range.end.column--;
}
range.cursor = range.start;
}
return range;
};
this.$brackets = {
")": "(",
"(": ")",
"]": "[",
"[": "]",
"{": "}",
"}": "{"
};
this.$findOpeningBracket = function(bracket, position, typeRe) {
var openBracket = this.$brackets[bracket];
var depth = 1;
var iterator = new TokenIterator(this, position.row, position.column);
var token = iterator.getCurrentToken();
if (!token)
token = iterator.stepForward();
if (!token)
return;
if (!typeRe){
typeRe = new RegExp(
"(\\.?" +
token.type.replace(".", "\\.").replace("rparen", ".paren")
.replace(/\b(?:end|start|begin)\b/, "")
+ ")+"
);
}
// Start searching in token, just before the character at position.column
var valueIndex = position.column - iterator.getCurrentTokenColumn() - 2;
var value = token.value;
while (true) {
while (valueIndex >= 0) {
var chr = value.charAt(valueIndex);
if (chr == openBracket) {
depth -= 1;
if (depth == 0) {
return {row: iterator.getCurrentTokenRow(),
column: valueIndex + iterator.getCurrentTokenColumn()};
}
}
else if (chr == bracket) {
depth += 1;
}
valueIndex -= 1;
}
// Scan backward through the document, looking for the next token
// whose type matches typeRe
do {
token = iterator.stepBackward();
} while (token && !typeRe.test(token.type));
if (token == null)
break;
value = token.value;
valueIndex = value.length - 1;
}
return null;
};
this.$findClosingBracket = function(bracket, position, typeRe) {
var closingBracket = this.$brackets[bracket];
var depth = 1;
var iterator = new TokenIterator(this, position.row, position.column);
var token = iterator.getCurrentToken();
if (!token)
token = iterator.stepForward();
if (!token)
return;
if (!typeRe){
typeRe = new RegExp(
"(\\.?" +
token.type.replace(".", "\\.").replace("lparen", ".paren")
.replace(/\b(?:end|start|begin)\b/, "")
+ ")+"
);
}
// Start searching in token, after the character at position.column
var valueIndex = position.column - iterator.getCurrentTokenColumn();
while (true) {
var value = token.value;
var valueLength = value.length;
while (valueIndex < valueLength) {
var chr = value.charAt(valueIndex);
if (chr == closingBracket) {
depth -= 1;
if (depth == 0) {
return {row: iterator.getCurrentTokenRow(),
column: valueIndex + iterator.getCurrentTokenColumn()};
}
}
else if (chr == bracket) {
depth += 1;
}
valueIndex += 1;
}
// Scan forward through the document, looking for the next token
// whose type matches typeRe
do {
token = iterator.stepForward();
} while (token && !typeRe.test(token.type));
if (token == null)
break;
valueIndex = 0;
}
return null;
};
}
exports.BracketMatch = BracketMatch;
});
| {
"pile_set_name": "Github"
} |
//---------------------------------------------------------------------------//
// Copyright (c) 2013-2014 Kyle Lutz <[email protected]>
//
// Distributed under the Boost Software License, Version 1.0
// See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
//
// See http://boostorg.github.com/compute for more information.
//---------------------------------------------------------------------------//
#ifndef BOOST_COMPUTE_DETAIL_GET_OBJECT_INFO_HPP
#define BOOST_COMPUTE_DETAIL_GET_OBJECT_INFO_HPP
#include <string>
#include <vector>
#include <boost/preprocessor/seq/for_each.hpp>
#include <boost/preprocessor/tuple/elem.hpp>
#include <boost/throw_exception.hpp>
#include <boost/compute/cl.hpp>
#include <boost/compute/exception/opencl_error.hpp>
namespace boost {
namespace compute {
namespace detail {
template<class Function, class Object, class AuxInfo>
struct bound_info_function
{
bound_info_function(Function function, Object object, AuxInfo aux_info)
: m_function(function),
m_object(object),
m_aux_info(aux_info)
{
}
template<class Info>
cl_int operator()(Info info, size_t size, void *value, size_t *size_ret) const
{
return m_function(m_object, m_aux_info, info, size, value, size_ret);
}
Function m_function;
Object m_object;
AuxInfo m_aux_info;
};
template<class Function, class Object>
struct bound_info_function<Function, Object, void>
{
bound_info_function(Function function, Object object)
: m_function(function),
m_object(object)
{
}
template<class Info>
cl_int operator()(Info info, size_t size, void *value, size_t *size_ret) const
{
return m_function(m_object, info, size, value, size_ret);
}
Function m_function;
Object m_object;
};
template<class Function, class Object>
inline bound_info_function<Function, Object, void>
bind_info_function(Function f, Object o)
{
return bound_info_function<Function, Object, void>(f, o);
}
template<class Function, class Object, class AuxInfo>
inline bound_info_function<Function, Object, AuxInfo>
bind_info_function(Function f, Object o, AuxInfo j)
{
return bound_info_function<Function, Object, AuxInfo>(f, o, j);
}
// default implementation
template<class T>
struct get_object_info_impl
{
template<class Function, class Info>
T operator()(Function function, Info info) const
{
T value;
cl_int ret = function(info, sizeof(T), &value, 0);
if(ret != CL_SUCCESS){
BOOST_THROW_EXCEPTION(opencl_error(ret));
}
return value;
}
};
// specialization for bool
template<>
struct get_object_info_impl<bool>
{
template<class Function, class Info>
bool operator()(Function function, Info info) const
{
cl_bool value;
cl_int ret = function(info, sizeof(cl_bool), &value, 0);
if(ret != CL_SUCCESS){
BOOST_THROW_EXCEPTION(opencl_error(ret));
}
return value == CL_TRUE;
}
};
// specialization for std::string
template<>
struct get_object_info_impl<std::string>
{
template<class Function, class Info>
std::string operator()(Function function, Info info) const
{
size_t size = 0;
cl_int ret = function(info, 0, 0, &size);
if(ret != CL_SUCCESS){
BOOST_THROW_EXCEPTION(opencl_error(ret));
}
if(size == 0){
return std::string();
}
std::string value(size - 1, 0);
ret = function(info, size, &value[0], 0);
if(ret != CL_SUCCESS){
BOOST_THROW_EXCEPTION(opencl_error(ret));
}
return value;
}
};
// specialization for std::vector<T>
template<class T>
struct get_object_info_impl<std::vector<T> >
{
template<class Function, class Info>
std::vector<T> operator()(Function function, Info info) const
{
size_t size = 0;
cl_int ret = function(info, 0, 0, &size);
if(ret != CL_SUCCESS){
BOOST_THROW_EXCEPTION(opencl_error(ret));
}
std::vector<T> vector(size / sizeof(T));
ret = function(info, size, &vector[0], 0);
if(ret != CL_SUCCESS){
BOOST_THROW_EXCEPTION(opencl_error(ret));
}
return vector;
}
};
// returns the value (of type T) from the given clGet*Info() function call.
template<class T, class Function, class Object, class Info>
inline T get_object_info(Function f, Object o, Info i)
{
return get_object_info_impl<T>()(bind_info_function(f, o), i);
}
template<class T, class Function, class Object, class Info, class AuxInfo>
inline T get_object_info(Function f, Object o, Info i, AuxInfo j)
{
return get_object_info_impl<T>()(bind_info_function(f, o, j), i);
}
// returns the value type for the clGet*Info() call on Object with Enum.
template<class Object, int Enum>
struct get_object_info_type;
// defines the object::get_info<Enum>() specialization
#define BOOST_COMPUTE_DETAIL_DEFINE_GET_INFO_SPECIALIZATION(object_type, result_type, value) \
namespace detail { \
template<> struct get_object_info_type<object_type, value> { typedef result_type type; }; \
} \
template<> inline result_type object_type::get_info<value>() const \
{ \
return get_info<result_type>(value); \
}
// used by BOOST_COMPUTE_DETAIL_DEFINE_GET_INFO_SPECIALIZATIONS()
#define BOOST_COMPUTE_DETAIL_DEFINE_GET_INFO_IMPL(r, data, elem) \
BOOST_COMPUTE_DETAIL_DEFINE_GET_INFO_SPECIALIZATION( \
data, BOOST_PP_TUPLE_ELEM(2, 0, elem), BOOST_PP_TUPLE_ELEM(2, 1, elem) \
)
// defines the object::get_info<Enum>() specialization for each
// (result_type, value) tuple in seq for object_type.
#define BOOST_COMPUTE_DETAIL_DEFINE_GET_INFO_SPECIALIZATIONS(object_type, seq) \
BOOST_PP_SEQ_FOR_EACH( \
BOOST_COMPUTE_DETAIL_DEFINE_GET_INFO_IMPL, object_type, seq \
)
} // end detail namespace
} // end compute namespace
} // end boost namespace
#endif // BOOST_COMPUTE_DETAIL_GET_OBJECT_INFO_HPP
| {
"pile_set_name": "Github"
} |
---
title: "Initializers on structure members are valid only for 'Shared' members and constants"
ms.date: 07/20/2015
f1_keywords:
- "bc31049"
- "vbc31049"
helpviewer_keywords:
- "BC31049"
ms.assetid: 8356978e-7f84-4932-be0f-dda005c9f8ca
---
# Initializers on structure members are valid only for 'Shared' members and constants
A structure member variable was initialized as part of its declaration.
**Error ID:** BC31049
## To correct this error
- Use a constant instead of a variable.
- Add a parameterized constructor to the structure. For example:
```vb
Structure TestStruct
Public t As Integer
Sub New(ByVal Tval As Integer)
t = Tval
End Sub
End Structure
```
## See also
- [How to: Declare a Structure](../programming-guide/language-features/data-types/how-to-declare-a-structure.md)
- [Constants and Enumerations](../programming-guide/language-features/constants-enums/index.md)
| {
"pile_set_name": "Github"
} |
/* 3c503.c: A shared-memory NS8390 ethernet driver for linux. */
/*
Written 1992-94 by Donald Becker.
Copyright 1993 United States Government as represented by the
Director, National Security Agency. This software may be used and
distributed according to the terms of the GNU General Public License,
incorporated herein by reference.
The author may be reached as [email protected], or C/O
Scyld Computing Corporation
410 Severn Ave., Suite 210
Annapolis MD 21403
This driver should work with the 3c503 and 3c503/16. It should be used
in shared memory mode for best performance, although it may also work
in programmed-I/O mode.
Sources:
EtherLink II Technical Reference Manual,
EtherLink II/16 Technical Reference Manual Supplement,
3Com Corporation, 5400 Bayfront Plaza, Santa Clara CA 95052-8145
The Crynwr 3c503 packet driver.
Changelog:
Paul Gortmaker : add support for the 2nd 8kB of RAM on 16 bit cards.
Paul Gortmaker : multiple card support for module users.
[email protected] : Fix up PIO interface for efficient operation.
Jeff Garzik : ethtool support
*/
#define DRV_NAME "3c503"
#define DRV_VERSION "1.10a"
#define DRV_RELDATE "11/17/2001"
static const char version[] =
DRV_NAME ".c:v" DRV_VERSION " " DRV_RELDATE " Donald Becker ([email protected])\n";
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/string.h>
#include <linux/delay.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/ethtool.h>
#include <asm/uaccess.h>
#include <asm/io.h>
#include <asm/byteorder.h>
#include "8390.h"
#include "3c503.h"
#define WRD_COUNT 4
static int el2_pio_probe(struct net_device *dev);
static int el2_probe1(struct net_device *dev, int ioaddr);
/* A zero-terminated list of I/O addresses to be probed in PIO mode. */
static unsigned int netcard_portlist[] __initdata =
{ 0x300,0x310,0x330,0x350,0x250,0x280,0x2a0,0x2e0,0};
#define EL2_IO_EXTENT 16
static int el2_open(struct net_device *dev);
static int el2_close(struct net_device *dev);
static void el2_reset_8390(struct net_device *dev);
static void el2_init_card(struct net_device *dev);
static void el2_block_output(struct net_device *dev, int count,
const unsigned char *buf, int start_page);
static void el2_block_input(struct net_device *dev, int count, struct sk_buff *skb,
int ring_offset);
static void el2_get_8390_hdr(struct net_device *dev, struct e8390_pkt_hdr *hdr,
int ring_page);
static const struct ethtool_ops netdev_ethtool_ops;
/* This routine probes for a memory-mapped 3c503 board by looking for
the "location register" at the end of the jumpered boot PROM space.
This works even if a PROM isn't there.
If the ethercard isn't found there is an optional probe for
ethercard jumpered to programmed-I/O mode.
*/
static int __init do_el2_probe(struct net_device *dev)
{
int *addr, addrs[] = { 0xddffe, 0xd9ffe, 0xcdffe, 0xc9ffe, 0};
int base_addr = dev->base_addr;
int irq = dev->irq;
if (base_addr > 0x1ff) /* Check a single specified location. */
return el2_probe1(dev, base_addr);
else if (base_addr != 0) /* Don't probe at all. */
return -ENXIO;
for (addr = addrs; *addr; addr++) {
void __iomem *p = ioremap(*addr, 1);
unsigned base_bits;
int i;
if (!p)
continue;
base_bits = readb(p);
iounmap(p);
i = ffs(base_bits) - 1;
if (i == -1 || base_bits != (1 << i))
continue;
if (el2_probe1(dev, netcard_portlist[i]) == 0)
return 0;
dev->irq = irq;
}
#if ! defined(no_probe_nonshared_memory)
return el2_pio_probe(dev);
#else
return -ENODEV;
#endif
}
/* Try all of the locations that aren't obviously empty. This touches
a lot of locations, and is much riskier than the code above. */
static int __init
el2_pio_probe(struct net_device *dev)
{
int i;
int base_addr = dev->base_addr;
int irq = dev->irq;
if (base_addr > 0x1ff) /* Check a single specified location. */
return el2_probe1(dev, base_addr);
else if (base_addr != 0) /* Don't probe at all. */
return -ENXIO;
for (i = 0; netcard_portlist[i]; i++) {
if (el2_probe1(dev, netcard_portlist[i]) == 0)
return 0;
dev->irq = irq;
}
return -ENODEV;
}
#ifndef MODULE
struct net_device * __init el2_probe(int unit)
{
struct net_device *dev = alloc_eip_netdev();
int err;
if (!dev)
return ERR_PTR(-ENOMEM);
sprintf(dev->name, "eth%d", unit);
netdev_boot_setup_check(dev);
err = do_el2_probe(dev);
if (err)
goto out;
return dev;
out:
free_netdev(dev);
return ERR_PTR(err);
}
#endif
static const struct net_device_ops el2_netdev_ops = {
.ndo_open = el2_open,
.ndo_stop = el2_close,
.ndo_start_xmit = eip_start_xmit,
.ndo_tx_timeout = eip_tx_timeout,
.ndo_get_stats = eip_get_stats,
.ndo_set_rx_mode = eip_set_multicast_list,
.ndo_validate_addr = eth_validate_addr,
.ndo_set_mac_address = eth_mac_addr,
.ndo_change_mtu = eth_change_mtu,
#ifdef CONFIG_NET_POLL_CONTROLLER
.ndo_poll_controller = eip_poll,
#endif
};
/* Probe for the Etherlink II card at I/O port base IOADDR,
returning non-zero on success. If found, set the station
address and memory parameters in DEVICE. */
static int __init
el2_probe1(struct net_device *dev, int ioaddr)
{
int i, iobase_reg, membase_reg, saved_406, wordlength, retval;
static unsigned version_printed;
unsigned long vendor_id;
if (!request_region(ioaddr, EL2_IO_EXTENT, DRV_NAME))
return -EBUSY;
if (!request_region(ioaddr + 0x400, 8, DRV_NAME)) {
retval = -EBUSY;
goto out;
}
/* Reset and/or avoid any lurking NE2000 */
if (inb(ioaddr + 0x408) == 0xff) {
mdelay(1);
retval = -ENODEV;
goto out1;
}
/* We verify that it's a 3C503 board by checking the first three octets
of its ethernet address. */
iobase_reg = inb(ioaddr+0x403);
membase_reg = inb(ioaddr+0x404);
/* ASIC location registers should be 0 or have only a single bit set. */
if ((iobase_reg & (iobase_reg - 1)) ||
(membase_reg & (membase_reg - 1))) {
retval = -ENODEV;
goto out1;
}
saved_406 = inb_p(ioaddr + 0x406);
outb_p(ECNTRL_RESET|ECNTRL_THIN, ioaddr + 0x406); /* Reset it... */
outb_p(ECNTRL_THIN, ioaddr + 0x406);
/* Map the station addr PROM into the lower I/O ports. We now check
for both the old and new 3Com prefix */
outb(ECNTRL_SAPROM|ECNTRL_THIN, ioaddr + 0x406);
vendor_id = inb(ioaddr)*0x10000 + inb(ioaddr + 1)*0x100 + inb(ioaddr + 2);
if ((vendor_id != OLD_3COM_ID) && (vendor_id != NEW_3COM_ID)) {
/* Restore the register we frobbed. */
outb(saved_406, ioaddr + 0x406);
retval = -ENODEV;
goto out1;
}
if (ei_debug && version_printed++ == 0)
pr_debug("%s", version);
dev->base_addr = ioaddr;
pr_info("%s: 3c503 at i/o base %#3x, node ", dev->name, ioaddr);
/* Retrieve and print the ethernet address. */
for (i = 0; i < 6; i++)
dev->dev_addr[i] = inb(ioaddr + i);
pr_cont("%pM", dev->dev_addr);
/* Map the 8390 back into the window. */
outb(ECNTRL_THIN, ioaddr + 0x406);
/* Check for EL2/16 as described in tech. man. */
outb_p(E8390_PAGE0, ioaddr + E8390_CMD);
outb_p(0, ioaddr + EN0_DCFG);
outb_p(E8390_PAGE2, ioaddr + E8390_CMD);
wordlength = inb_p(ioaddr + EN0_DCFG) & ENDCFG_WTS;
outb_p(E8390_PAGE0, ioaddr + E8390_CMD);
/* Probe for, turn on and clear the board's shared memory. */
if (ei_debug > 2)
pr_cont(" memory jumpers %2.2x ", membase_reg);
outb(EGACFR_NORM, ioaddr + 0x405); /* Enable RAM */
/* This should be probed for (or set via an ioctl()) at run-time.
Right now we use a sleazy hack to pass in the interface number
at boot-time via the low bits of the mem_end field. That value is
unused, and the low bits would be discarded even if it was used. */
#if defined(EI8390_THICK) || defined(EL2_AUI)
ei_status.interface_num = 1;
#else
ei_status.interface_num = dev->mem_end & 0xf;
#endif
pr_cont(", using %sternal xcvr.\n", ei_status.interface_num == 0 ? "in" : "ex");
if ((membase_reg & 0xf0) == 0) {
dev->mem_start = 0;
ei_status.name = "3c503-PIO";
ei_status.mem = NULL;
} else {
dev->mem_start = ((membase_reg & 0xc0) ? 0xD8000 : 0xC8000) +
((membase_reg & 0xA0) ? 0x4000 : 0);
#define EL2_MEMSIZE (EL2_MB1_STOP_PG - EL2_MB1_START_PG)*256
ei_status.mem = ioremap(dev->mem_start, EL2_MEMSIZE);
#ifdef EL2MEMTEST
/* This has never found an error, but someone might care.
Note that it only tests the 2nd 8kB on 16kB 3c503/16
cards between card addr. 0x2000 and 0x3fff. */
{ /* Check the card's memory. */
void __iomem *mem_base = ei_status.mem;
unsigned int test_val = 0xbbadf00d;
writel(0xba5eba5e, mem_base);
for (i = sizeof(test_val); i < EL2_MEMSIZE; i+=sizeof(test_val)) {
writel(test_val, mem_base + i);
if (readl(mem_base) != 0xba5eba5e ||
readl(mem_base + i) != test_val) {
pr_warning("3c503: memory failure or memory address conflict.\n");
dev->mem_start = 0;
ei_status.name = "3c503-PIO";
iounmap(mem_base);
ei_status.mem = NULL;
break;
}
test_val += 0x55555555;
writel(0, mem_base + i);
}
}
#endif /* EL2MEMTEST */
if (dev->mem_start)
dev->mem_end = dev->mem_start + EL2_MEMSIZE;
if (wordlength) { /* No Tx pages to skip over to get to Rx */
ei_status.priv = 0;
ei_status.name = "3c503/16";
} else {
ei_status.priv = TX_PAGES * 256;
ei_status.name = "3c503";
}
}
/*
Divide up the memory on the card. This is the same regardless of
whether shared-mem or PIO is used. For 16 bit cards (16kB RAM),
we use the entire 8k of bank1 for an Rx ring. We only use 3k
of the bank0 for 2 full size Tx packet slots. For 8 bit cards,
(8kB RAM) we use 3kB of bank1 for two Tx slots, and the remaining
5kB for an Rx ring. */
if (wordlength) {
ei_status.tx_start_page = EL2_MB0_START_PG;
ei_status.rx_start_page = EL2_MB1_START_PG;
} else {
ei_status.tx_start_page = EL2_MB1_START_PG;
ei_status.rx_start_page = EL2_MB1_START_PG + TX_PAGES;
}
/* Finish setting the board's parameters. */
ei_status.stop_page = EL2_MB1_STOP_PG;
ei_status.word16 = wordlength;
ei_status.reset_8390 = el2_reset_8390;
ei_status.get_8390_hdr = el2_get_8390_hdr;
ei_status.block_input = el2_block_input;
ei_status.block_output = el2_block_output;
if (dev->irq == 2)
dev->irq = 9;
else if (dev->irq > 5 && dev->irq != 9) {
pr_warning("3c503: configured interrupt %d invalid, will use autoIRQ.\n",
dev->irq);
dev->irq = 0;
}
ei_status.saved_irq = dev->irq;
dev->netdev_ops = &el2_netdev_ops;
dev->ethtool_ops = &netdev_ethtool_ops;
retval = register_netdev(dev);
if (retval)
goto out1;
if (dev->mem_start)
pr_info("%s: %s - %dkB RAM, 8kB shared mem window at %#6lx-%#6lx.\n",
dev->name, ei_status.name, (wordlength+1)<<3,
dev->mem_start, dev->mem_end-1);
else
{
ei_status.tx_start_page = EL2_MB1_START_PG;
ei_status.rx_start_page = EL2_MB1_START_PG + TX_PAGES;
pr_info("%s: %s, %dkB RAM, using programmed I/O (REJUMPER for SHARED MEMORY).\n",
dev->name, ei_status.name, (wordlength+1)<<3);
}
release_region(ioaddr + 0x400, 8);
return 0;
out1:
release_region(ioaddr + 0x400, 8);
out:
release_region(ioaddr, EL2_IO_EXTENT);
return retval;
}
static irqreturn_t el2_probe_interrupt(int irq, void *seen)
{
*(bool *)seen = true;
return IRQ_HANDLED;
}
static int
el2_open(struct net_device *dev)
{
int retval;
if (dev->irq < 2) {
static const int irqlist[] = {5, 9, 3, 4, 0};
const int *irqp = irqlist;
outb(EGACFR_NORM, E33G_GACFR); /* Enable RAM and interrupts. */
do {
bool seen;
retval = request_irq(*irqp, el2_probe_interrupt, 0,
dev->name, &seen);
if (retval == -EBUSY)
continue;
if (retval < 0)
goto err_disable;
/* Twinkle the interrupt, and check if it's seen. */
seen = false;
smp_wmb();
outb_p(0x04 << ((*irqp == 9) ? 2 : *irqp), E33G_IDCFR);
outb_p(0x00, E33G_IDCFR);
msleep(1);
free_irq(*irqp, &seen);
if (!seen)
continue;
retval = request_irq(dev->irq = *irqp, eip_interrupt, 0,
dev->name, dev);
if (retval == -EBUSY)
continue;
if (retval < 0)
goto err_disable;
break;
} while (*++irqp);
if (*irqp == 0) {
err_disable:
outb(EGACFR_IRQOFF, E33G_GACFR); /* disable interrupts. */
return -EAGAIN;
}
} else {
if ((retval = request_irq(dev->irq, eip_interrupt, 0, dev->name, dev))) {
return retval;
}
}
el2_init_card(dev);
eip_open(dev);
return 0;
}
static int
el2_close(struct net_device *dev)
{
free_irq(dev->irq, dev);
dev->irq = ei_status.saved_irq;
outb(EGACFR_IRQOFF, E33G_GACFR); /* disable interrupts. */
eip_close(dev);
return 0;
}
/* This is called whenever we have a unrecoverable failure:
transmit timeout
Bad ring buffer packet header
*/
static void
el2_reset_8390(struct net_device *dev)
{
if (ei_debug > 1) {
pr_debug("%s: Resetting the 3c503 board...", dev->name);
pr_cont(" %#lx=%#02x %#lx=%#02x %#lx=%#02x...", E33G_IDCFR, inb(E33G_IDCFR),
E33G_CNTRL, inb(E33G_CNTRL), E33G_GACFR, inb(E33G_GACFR));
}
outb_p(ECNTRL_RESET|ECNTRL_THIN, E33G_CNTRL);
ei_status.txing = 0;
outb_p(ei_status.interface_num==0 ? ECNTRL_THIN : ECNTRL_AUI, E33G_CNTRL);
el2_init_card(dev);
if (ei_debug > 1)
pr_cont("done\n");
}
/* Initialize the 3c503 GA registers after a reset. */
static void
el2_init_card(struct net_device *dev)
{
/* Unmap the station PROM and select the DIX or BNC connector. */
outb_p(ei_status.interface_num==0 ? ECNTRL_THIN : ECNTRL_AUI, E33G_CNTRL);
/* Set ASIC copy of rx's first and last+1 buffer pages */
/* These must be the same as in the 8390. */
outb(ei_status.rx_start_page, E33G_STARTPG);
outb(ei_status.stop_page, E33G_STOPPG);
/* Point the vector pointer registers somewhere ?harmless?. */
outb(0xff, E33G_VP2); /* Point at the ROM restart location 0xffff0 */
outb(0xff, E33G_VP1);
outb(0x00, E33G_VP0);
/* Turn off all interrupts until we're opened. */
outb_p(0x00, dev->base_addr + EN0_IMR);
/* Enable IRQs iff started. */
outb(EGACFR_NORM, E33G_GACFR);
/* Set the interrupt line. */
outb_p((0x04 << (dev->irq == 9 ? 2 : dev->irq)), E33G_IDCFR);
outb_p((WRD_COUNT << 1), E33G_DRQCNT); /* Set burst size to 8 */
outb_p(0x20, E33G_DMAAH); /* Put a valid addr in the GA DMA */
outb_p(0x00, E33G_DMAAL);
return; /* We always succeed */
}
/*
* Either use the shared memory (if enabled on the board) or put the packet
* out through the ASIC FIFO.
*/
static void
el2_block_output(struct net_device *dev, int count,
const unsigned char *buf, int start_page)
{
unsigned short int *wrd;
int boguscount; /* timeout counter */
unsigned short word; /* temporary for better machine code */
void __iomem *base = ei_status.mem;
if (ei_status.word16) /* Tx packets go into bank 0 on EL2/16 card */
outb(EGACFR_RSEL|EGACFR_TCM, E33G_GACFR);
else
outb(EGACFR_NORM, E33G_GACFR);
if (base) { /* Shared memory transfer */
memcpy_toio(base + ((start_page - ei_status.tx_start_page) << 8),
buf, count);
outb(EGACFR_NORM, E33G_GACFR); /* Back to bank1 in case on bank0 */
return;
}
/*
* No shared memory, put the packet out the other way.
* Set up then start the internal memory transfer to Tx Start Page
*/
word = (unsigned short)start_page;
outb(word&0xFF, E33G_DMAAH);
outb(word>>8, E33G_DMAAL);
outb_p((ei_status.interface_num ? ECNTRL_AUI : ECNTRL_THIN ) | ECNTRL_OUTPUT
| ECNTRL_START, E33G_CNTRL);
/*
* Here I am going to write data to the FIFO as quickly as possible.
* Note that E33G_FIFOH is defined incorrectly. It is really
* E33G_FIFOL, the lowest port address for both the byte and
* word write. Variable 'count' is NOT checked. Caller must supply a
* valid count. Note that I may write a harmless extra byte to the
* 8390 if the byte-count was not even.
*/
wrd = (unsigned short int *) buf;
count = (count + 1) >> 1;
for(;;)
{
boguscount = 0x1000;
while ((inb(E33G_STATUS) & ESTAT_DPRDY) == 0)
{
if(!boguscount--)
{
pr_notice("%s: FIFO blocked in el2_block_output.\n", dev->name);
el2_reset_8390(dev);
goto blocked;
}
}
if(count > WRD_COUNT)
{
outsw(E33G_FIFOH, wrd, WRD_COUNT);
wrd += WRD_COUNT;
count -= WRD_COUNT;
}
else
{
outsw(E33G_FIFOH, wrd, count);
break;
}
}
blocked:;
outb_p(ei_status.interface_num==0 ? ECNTRL_THIN : ECNTRL_AUI, E33G_CNTRL);
}
/* Read the 4 byte, page aligned 8390 specific header. */
static void
el2_get_8390_hdr(struct net_device *dev, struct e8390_pkt_hdr *hdr, int ring_page)
{
int boguscount;
void __iomem *base = ei_status.mem;
unsigned short word;
if (base) { /* Use the shared memory. */
void __iomem *hdr_start = base + ((ring_page - EL2_MB1_START_PG)<<8);
memcpy_fromio(hdr, hdr_start, sizeof(struct e8390_pkt_hdr));
hdr->count = le16_to_cpu(hdr->count);
return;
}
/*
* No shared memory, use programmed I/O.
*/
word = (unsigned short)ring_page;
outb(word&0xFF, E33G_DMAAH);
outb(word>>8, E33G_DMAAL);
outb_p((ei_status.interface_num == 0 ? ECNTRL_THIN : ECNTRL_AUI) | ECNTRL_INPUT
| ECNTRL_START, E33G_CNTRL);
boguscount = 0x1000;
while ((inb(E33G_STATUS) & ESTAT_DPRDY) == 0)
{
if(!boguscount--)
{
pr_notice("%s: FIFO blocked in el2_get_8390_hdr.\n", dev->name);
memset(hdr, 0x00, sizeof(struct e8390_pkt_hdr));
el2_reset_8390(dev);
goto blocked;
}
}
insw(E33G_FIFOH, hdr, (sizeof(struct e8390_pkt_hdr))>> 1);
blocked:;
outb_p(ei_status.interface_num == 0 ? ECNTRL_THIN : ECNTRL_AUI, E33G_CNTRL);
}
static void
el2_block_input(struct net_device *dev, int count, struct sk_buff *skb, int ring_offset)
{
int boguscount = 0;
void __iomem *base = ei_status.mem;
unsigned short int *buf;
unsigned short word;
/* Maybe enable shared memory just be to be safe... nahh.*/
if (base) { /* Use the shared memory. */
ring_offset -= (EL2_MB1_START_PG<<8);
if (ring_offset + count > EL2_MEMSIZE) {
/* We must wrap the input move. */
int semi_count = EL2_MEMSIZE - ring_offset;
memcpy_fromio(skb->data, base + ring_offset, semi_count);
count -= semi_count;
memcpy_fromio(skb->data + semi_count, base + ei_status.priv, count);
} else {
memcpy_fromio(skb->data, base + ring_offset, count);
}
return;
}
/*
* No shared memory, use programmed I/O.
*/
word = (unsigned short) ring_offset;
outb(word>>8, E33G_DMAAH);
outb(word&0xFF, E33G_DMAAL);
outb_p((ei_status.interface_num == 0 ? ECNTRL_THIN : ECNTRL_AUI) | ECNTRL_INPUT
| ECNTRL_START, E33G_CNTRL);
/*
* Here I also try to get data as fast as possible. I am betting that I
* can read one extra byte without clobbering anything in the kernel because
* this would only occur on an odd byte-count and allocation of skb->data
* is word-aligned. Variable 'count' is NOT checked. Caller must check
* for a valid count.
* [This is currently quite safe.... but if one day the 3c503 explodes
* you know where to come looking ;)]
*/
buf = (unsigned short int *) skb->data;
count = (count + 1) >> 1;
for(;;)
{
boguscount = 0x1000;
while ((inb(E33G_STATUS) & ESTAT_DPRDY) == 0)
{
if(!boguscount--)
{
pr_notice("%s: FIFO blocked in el2_block_input.\n", dev->name);
el2_reset_8390(dev);
goto blocked;
}
}
if(count > WRD_COUNT)
{
insw(E33G_FIFOH, buf, WRD_COUNT);
buf += WRD_COUNT;
count -= WRD_COUNT;
}
else
{
insw(E33G_FIFOH, buf, count);
break;
}
}
blocked:;
outb_p(ei_status.interface_num == 0 ? ECNTRL_THIN : ECNTRL_AUI, E33G_CNTRL);
}
static void netdev_get_drvinfo(struct net_device *dev,
struct ethtool_drvinfo *info)
{
strcpy(info->driver, DRV_NAME);
strcpy(info->version, DRV_VERSION);
sprintf(info->bus_info, "ISA 0x%lx", dev->base_addr);
}
static const struct ethtool_ops netdev_ethtool_ops = {
.get_drvinfo = netdev_get_drvinfo,
};
#ifdef MODULE
#define MAX_EL2_CARDS 4 /* Max number of EL2 cards per module */
static struct net_device *dev_el2[MAX_EL2_CARDS];
static int io[MAX_EL2_CARDS];
static int irq[MAX_EL2_CARDS];
static int xcvr[MAX_EL2_CARDS]; /* choose int. or ext. xcvr */
module_param_array(io, int, NULL, 0);
module_param_array(irq, int, NULL, 0);
module_param_array(xcvr, int, NULL, 0);
MODULE_PARM_DESC(io, "I/O base address(es)");
MODULE_PARM_DESC(irq, "IRQ number(s) (assigned)");
MODULE_PARM_DESC(xcvr, "transceiver(s) (0=internal, 1=external)");
MODULE_DESCRIPTION("3Com ISA EtherLink II, II/16 (3c503, 3c503/16) driver");
MODULE_LICENSE("GPL");
/* This is set up so that only a single autoprobe takes place per call.
ISA device autoprobes on a running machine are not recommended. */
int __init
init_module(void)
{
struct net_device *dev;
int this_dev, found = 0;
for (this_dev = 0; this_dev < MAX_EL2_CARDS; this_dev++) {
if (io[this_dev] == 0) {
if (this_dev != 0) break; /* only autoprobe 1st one */
pr_notice("3c503.c: Presently autoprobing (not recommended) for a single card.\n");
}
dev = alloc_eip_netdev();
if (!dev)
break;
dev->irq = irq[this_dev];
dev->base_addr = io[this_dev];
dev->mem_end = xcvr[this_dev]; /* low 4bits = xcvr sel. */
if (do_el2_probe(dev) == 0) {
dev_el2[found++] = dev;
continue;
}
free_netdev(dev);
pr_warning("3c503.c: No 3c503 card found (i/o = 0x%x).\n", io[this_dev]);
break;
}
if (found)
return 0;
return -ENXIO;
}
static void cleanup_card(struct net_device *dev)
{
/* NB: el2_close() handles free_irq */
release_region(dev->base_addr, EL2_IO_EXTENT);
if (ei_status.mem)
iounmap(ei_status.mem);
}
void __exit
cleanup_module(void)
{
int this_dev;
for (this_dev = 0; this_dev < MAX_EL2_CARDS; this_dev++) {
struct net_device *dev = dev_el2[this_dev];
if (dev) {
unregister_netdev(dev);
cleanup_card(dev);
free_netdev(dev);
}
}
}
#endif /* MODULE */
| {
"pile_set_name": "Github"
} |
$MECAB_OPT
--innodb_ft_min_token_size=2
| {
"pile_set_name": "Github"
} |
---
title: 针对 .NET Framework 4.5 到 4.5.1 迁移的重定向更改
description: 在从 .NET Framework 4.5 迁移到 4.5.1 时,查找有关应用程序兼容性问题的信息,这些问题可能会影响你的应用。
ms.date: 07/10/2019
ms.assetid: e5ad261b-ccaf-467f-abf7-8652d0bce4c4
author: chlowell
ms.openlocfilehash: c717833c0acbfc0defc31028a56225680ac374a6
ms.sourcegitcommit: 2543a78be6e246aa010a01decf58889de53d1636
ms.translationtype: HT
ms.contentlocale: zh-CN
ms.lasthandoff: 07/17/2020
ms.locfileid: "86443398"
---
# <a name="retargeting-changes-for-migration-from-net-framework-45-to-451"></a>针对 .NET Framework 4.5 到 4.5.1 迁移的重定向更改
[!INCLUDE[versionselector](../../../../includes/migration-guide/retargeting/versionselector.md)]
如果要从 .NET Framework 4.5 迁移到 4.5.1,请在以下主题中查看可能影响你的应用的应用程序兼容性问题:
## <a name="adonet"></a>ADO.NET
[!INCLUDE[DbParameter.Precision and DbParameter.Scale are now public virtual members](~/includes/migration-guide/retargeting/adonet/dbparameterprecision-dbparameterscale-are-now-public-virtual-members.md)]
## <a name="core"></a>核心
[!INCLUDE[ObsoleteAttribute exports as both ObsoleteAttribute and DeprecatedAttribute in WinMD scenarios](~/includes/migration-guide/retargeting/core/obsoleteattribute-exports-both-deprecatedattribute-winmd-scenarios.md)]
## <a name="entity-framework"></a>Entity Framework
[!INCLUDE[Building an Entity Framework edmx with Visual Studio 2013 can fail with error MSB4062 if using the EntityDeploySplit or EntityClean tasks](~/includes/migration-guide/retargeting/ef/building-an-entity-framework-edmx-with-visual-studio-2013-can-fail-error.md)]
## <a name="msbuild"></a>MSBuild
[!INCLUDE[ResolveAssemblyReference task now warns of dependencies with the wrong architecture](~/includes/migration-guide/retargeting/msbuild/resolveassemblyreference-task-now-warns-dependencies-with-wrong-architecture.md)]
## <a name="windows-presentation-foundation-wpf"></a>Windows Presentation Foundation (WPF)
[!INCLUDE[Two-way data-binding to a property with a non-public setter is not supported](~/includes/migration-guide/retargeting/wpf/two-way-data-binding-property-with-non-public-setter-not-supported.md)]
| {
"pile_set_name": "Github"
} |
{
"name": "ICD-PX470",
"description": "A voice recorder.",
"url": "https://www.sony.com/electronics/voice-recorders/icd-px470"
}
| {
"pile_set_name": "Github"
} |
---
lang: en
title: 'API docs: authentication'
keywords: LoopBack 4.0, LoopBack 4, Node.js, TypeScript, OpenAPI
sidebar: lb4_sidebar
editurl: https://github.com/strongloop/loopback-next/tree/master/packages/authentication
permalink: /doc/en/lb4/apidocs.authentication.html
---
<!-- Do not edit this file. It is automatically generated by API Documenter. -->
[Home](./index.md) > [@loopback/authentication](./authentication.md)
## authentication package
A LoopBack 4 component for authentication support.
## Remarks
The core logic for the authentication layer in LoopBack 4.
It contains:
- A decorator to express an authentication requirement on controller methods - A provider to access method-level authentication metadata - An action in the REST sequence to enforce authentication - An extension point to discover all authentication strategies and handle the delegation
## Classes
| Class | Description |
| --- | --- |
| [AuthenticateActionProvider](./authentication.authenticateactionprovider.md) | Provides the authentication action for a sequence |
| [AuthenticationComponent](./authentication.authenticationcomponent.md) | |
| [AuthenticationMiddlewareProvider](./authentication.authenticationmiddlewareprovider.md) | |
| [AuthenticationStrategyProvider](./authentication.authenticationstrategyprovider.md) | An authentication strategy provider responsible for resolving an authentication strategy by name.<!-- -->It declares an extension point to which all authentication strategy implementations must register themselves as extensions. |
| [AuthMetadataProvider](./authentication.authmetadataprovider.md) | Provides authentication metadata of a controller method |
## Functions
| Function | Description |
| --- | --- |
| [authenticate(strategies)](./authentication.authenticate.md) | Mark a controller method as requiring authenticated user. |
| [getAuthenticateMetadata(targetClass, methodName)](./authentication.getauthenticatemetadata.md) | Fetch authentication metadata stored by <code>@authenticate</code> decorator. |
| [getAuthenticationMetadataForStrategy(metadata, strategyName)](./authentication.getauthenticationmetadataforstrategy.md) | Get the authentication metadata object for the specified strategy. |
| [registerAuthenticationStrategy(context, strategyClass)](./authentication.registerauthenticationstrategy.md) | Registers an authentication strategy as an extension of the AuthenticationBindings.AUTHENTICATION\_STRATEGY\_EXTENSION\_POINT\_NAME extension point. |
## Interfaces
| Interface | Description |
| --- | --- |
| [AuthenticateFn](./authentication.authenticatefn.md) | interface definition of a function which accepts a request and returns an authenticated user |
| [AuthenticationMetadata](./authentication.authenticationmetadata.md) | Authentication metadata stored via Reflection API |
| [AuthenticationOptions](./authentication.authenticationoptions.md) | Options for authentication component |
| [AuthenticationStrategy](./authentication.authenticationstrategy.md) | An interface that describes the common authentication strategy.<!-- -->An authentication strategy is a class with an 'authenticate' method that verifies a user's credentials and returns the corresponding user profile. |
| [TokenService](./authentication.tokenservice.md) | An interface for generating and verifying a token |
| [UserIdentityService](./authentication.useridentityservice.md) | The User Identity service links a user to profiles from an external source (eg: ldap, oauth2 provider, saml) which can identify the user. The profile typically has the following information: name, email-id, uuid, roles, authorizations, scope of accessible resources, expiration time for given access |
| [UserProfileFactory](./authentication.userprofilefactory.md) | interface definition of a factory function which accepts a user definition and returns the user profile |
| [UserService](./authentication.userservice.md) | A service for performing the login action in an authentication strategy.<!-- -->Usually a client user uses basic credentials to login, or is redirected to a third-party application that grants limited access.<!-- -->Note: The creation of user is handled in the user controller by calling user repository APIs. For Basic auth, the user has to register first using some endpoint like <code>/register</code>. For 3rd-party auth, the user will be created if login is successful and the user doesn't exist in database yet.<!-- -->Type <code>C</code> stands for the type of your credential object.<!-- -->- For local strategy:<!-- -->A typical credential would be: { username: username, password: password }<!-- -->- For oauth strategy:<!-- -->A typical credential would be: { clientId: string; clientSecret: string; callbackURL: string; }<!-- -->It could be read from a local configuration file in the app<!-- -->- For saml strategy:<!-- -->A typical credential would be:<!-- -->{ path: string; issuer: string; entryPoint: string; }<!-- -->It could be read from a local configuration file in the app. |
## Namespaces
| Namespace | Description |
| --- | --- |
| [authenticate](./authentication.authenticate.md) | |
| [AuthenticationBindings](./authentication.authenticationbindings.md) | Binding keys used by this component. |
## Variables
| Variable | Description |
| --- | --- |
| [asAuthStrategy](./authentication.asauthstrategy.md) | A binding template for auth strategy contributor extensions |
| [AUTHENTICATION\_METADATA\_CLASS\_KEY](./authentication.authentication_metadata_class_key.md) | The key used to store class-level metadata for <code>@authenticate</code> |
| [AUTHENTICATION\_METADATA\_KEY](./authentication.authentication_metadata_key.md) | Alias for AUTHENTICATION\_METADATA\_METHOD\_KEY to keep it backward compatible |
| [AUTHENTICATION\_METADATA\_METHOD\_KEY](./authentication.authentication_metadata_method_key.md) | The key used to store method-level metadata for <code>@authenticate</code> |
| [AUTHENTICATION\_STRATEGY\_NOT\_FOUND](./authentication.authentication_strategy_not_found.md) | |
| [USER\_PROFILE\_NOT\_FOUND](./authentication.user_profile_not_found.md) | |
| {
"pile_set_name": "Github"
} |
<?php
namespace spec\PhpSpec\Matcher\Iterate;
use PhpSpec\Exception\Example\FailureException;
use PhpSpec\ObjectBehavior;
class SubjectElementDoesNotMatchExceptionSpec extends ObjectBehavior
{
function let()
{
$this->beConstructedWith(42, '"subject key"', '"subject value"', '"expected key"', '"expected value"');
}
function it_is_a_failure_exception()
{
$this->shouldHaveType(FailureException::class);
}
function it_has_a_predefined_message()
{
$this->getMessage()->shouldReturn('Expected subject to have element #42 with key "expected key" and value "expected value", but got key "subject key" and value "subject value".');
}
}
| {
"pile_set_name": "Github"
} |
//
// MessagePack for C++ static resolution routine
//
// Copyright (C) 2008-2015 FURUHASHI Sadayuki and KONDO Takatoshi
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef MSGPACK_V1_TYPE_VECTOR_HPP
#define MSGPACK_V1_TYPE_VECTOR_HPP
#include "msgpack/versioning.hpp"
#include "msgpack/adaptor/adaptor_base.hpp"
#include "msgpack/adaptor/check_container_size.hpp"
#include <vector>
namespace msgpack {
/// @cond
MSGPACK_API_VERSION_NAMESPACE(v1) {
/// @endcond
namespace adaptor {
#if !defined(MSGPACK_USE_CPP03)
template <typename T, typename Alloc>
struct as<std::vector<T, Alloc>, typename std::enable_if<msgpack::has_as<T>::value>::type> {
std::vector<T, Alloc> operator()(const msgpack::object& o) const {
if (o.type != msgpack::type::ARRAY) { throw msgpack::type_error(); }
std::vector<T, Alloc> v;
v.reserve(o.via.array.size);
if (o.via.array.size > 0) {
msgpack::object* p = o.via.array.ptr;
msgpack::object* const pend = o.via.array.ptr + o.via.array.size;
do {
v.push_back(p->as<T>());
++p;
} while (p < pend);
}
return v;
}
};
#endif // !defined(MSGPACK_USE_CPP03)
template <typename T, typename Alloc>
struct convert<std::vector<T, Alloc> > {
msgpack::object const& operator()(msgpack::object const& o, std::vector<T, Alloc>& v) const {
if (o.type != msgpack::type::ARRAY) { throw msgpack::type_error(); }
v.resize(o.via.array.size);
if (o.via.array.size > 0) {
msgpack::object* p = o.via.array.ptr;
msgpack::object* const pend = o.via.array.ptr + o.via.array.size;
typename std::vector<T, Alloc>::iterator it = v.begin();
do {
p->convert(*it);
++p;
++it;
} while(p < pend);
}
return o;
}
};
template <typename T, typename Alloc>
struct pack<std::vector<T, Alloc> > {
template <typename Stream>
msgpack::packer<Stream>& operator()(msgpack::packer<Stream>& o, const std::vector<T, Alloc>& v) const {
uint32_t size = checked_get_container_size(v.size());
o.pack_array(size);
for (typename std::vector<T, Alloc>::const_iterator it(v.begin()), it_end(v.end());
it != it_end; ++it) {
o.pack(*it);
}
return o;
}
};
template <typename T, typename Alloc>
struct object_with_zone<std::vector<T, Alloc> > {
void operator()(msgpack::object::with_zone& o, const std::vector<T, Alloc>& v) const {
o.type = msgpack::type::ARRAY;
if (v.empty()) {
o.via.array.ptr = nullptr;
o.via.array.size = 0;
}
else {
uint32_t size = checked_get_container_size(v.size());
msgpack::object* p = static_cast<msgpack::object*>(o.zone.allocate_align(sizeof(msgpack::object)*size));
msgpack::object* const pend = p + size;
o.via.array.ptr = p;
o.via.array.size = size;
typename std::vector<T, Alloc>::const_iterator it(v.begin());
do {
#if (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)) && !defined(__clang__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wmaybe-uninitialized"
#endif // (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)) && !defined(__clang__)
*p = msgpack::object(*it, o.zone);
#if (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)) && !defined(__clang__)
#pragma GCC diagnostic pop
#endif // (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)) && !defined(__clang__)
++p;
++it;
} while(p < pend);
}
}
};
} // namespace adaptor
/// @cond
} // MSGPACK_API_VERSION_NAMESPACE(v1)
/// @endcond
} // namespace msgpack
#endif // MSGPACK_V1_TYPE_VECTOR_HPP
| {
"pile_set_name": "Github"
} |
/*
* cocos2d for iPhone: http://www.cocos2d-iphone.org
*
* Copyright (c) 2011 Ricardo Quesada
* Copyright (c) 2012 Zynga Inc.
*
* 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.
*/
" \n\
#ifdef GL_ES \n\
precision lowp float; \n\
#endif \n\
\n\
varying vec4 v_fragmentColor; \n\
varying vec2 v_texCoord; \n\
uniform sampler2D CC_Texture0; \n\
\n\
void main() \n\
{ \n\
gl_FragColor = v_fragmentColor * texture2D(CC_Texture0, v_texCoord); \n\
} \n\
";
| {
"pile_set_name": "Github"
} |
#import "GPUImageTwoInputFilter.h"
@interface GPUImageDifferenceBlendFilter : GPUImageTwoInputFilter
{
}
@end
| {
"pile_set_name": "Github"
} |
/***************************************************************************/
/* */
/* ttgxvar.c */
/* */
/* TrueType GX Font Variation loader */
/* */
/* Copyright 2004-2012 by */
/* David Turner, Robert Wilhelm, Werner Lemberg, and George Williams. */
/* */
/* 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. */
/* */
/***************************************************************************/
/*************************************************************************/
/* */
/* Apple documents the `fvar', `gvar', `cvar', and `avar' tables at */
/* */
/* http://developer.apple.com/fonts/TTRefMan/RM06/Chap6[fgca]var.html */
/* */
/* The documentation for `fvar' is inconsistent. At one point it says */
/* that `countSizePairs' should be 3, at another point 2. It should */
/* be 2. */
/* */
/* The documentation for `gvar' is not intelligible; `cvar' refers you */
/* to `gvar' and is thus also incomprehensible. */
/* */
/* The documentation for `avar' appears correct, but Apple has no fonts */
/* with an `avar' table, so it is hard to test. */
/* */
/* Many thanks to John Jenkins (at Apple) in figuring this out. */
/* */
/* */
/* Apple's `kern' table has some references to tuple indices, but as */
/* there is no indication where these indices are defined, nor how to */
/* interpolate the kerning values (different tuples have different */
/* classes) this issue is ignored. */
/* */
/*************************************************************************/
#include <ft2build.h>
#include FT_INTERNAL_DEBUG_H
#include FT_CONFIG_CONFIG_H
#include FT_INTERNAL_STREAM_H
#include FT_INTERNAL_SFNT_H
#include FT_TRUETYPE_TAGS_H
#include FT_MULTIPLE_MASTERS_H
#include "ttpload.h"
#include "ttgxvar.h"
#include "tterrors.h"
#ifdef TT_CONFIG_OPTION_GX_VAR_SUPPORT
#define FT_Stream_FTell( stream ) \
( (stream)->cursor - (stream)->base )
#define FT_Stream_SeekSet( stream, off ) \
( (stream)->cursor = (stream)->base+(off) )
/*************************************************************************/
/* */
/* 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_ttgxvar
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** Internal Routines *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
/*************************************************************************/
/* */
/* The macro ALL_POINTS is used in `ft_var_readpackedpoints'. It */
/* indicates that there is a delta for every point without needing to */
/* enumerate all of them. */
/* */
#define ALL_POINTS (FT_UShort*)( ~0 )
#define GX_PT_POINTS_ARE_WORDS 0x80
#define GX_PT_POINT_RUN_COUNT_MASK 0x7F
/*************************************************************************/
/* */
/* <Function> */
/* ft_var_readpackedpoints */
/* */
/* <Description> */
/* Read a set of points to which the following deltas will apply. */
/* Points are packed with a run length encoding. */
/* */
/* <Input> */
/* stream :: The data stream. */
/* */
/* <Output> */
/* point_cnt :: The number of points read. A zero value means that */
/* all points in the glyph will be affected, without */
/* enumerating them individually. */
/* */
/* <Return> */
/* An array of FT_UShort containing the affected points or the */
/* special value ALL_POINTS. */
/* */
static FT_UShort*
ft_var_readpackedpoints( FT_Stream stream,
FT_UInt *point_cnt )
{
FT_UShort *points = NULL;
FT_Int n;
FT_Int runcnt;
FT_Int i;
FT_Int j;
FT_Int first;
FT_Memory memory = stream->memory;
FT_Error error = TT_Err_Ok;
FT_UNUSED( error );
*point_cnt = n = FT_GET_BYTE();
if ( n == 0 )
return ALL_POINTS;
if ( n & GX_PT_POINTS_ARE_WORDS )
n = FT_GET_BYTE() | ( ( n & GX_PT_POINT_RUN_COUNT_MASK ) << 8 );
if ( FT_NEW_ARRAY( points, n ) )
return NULL;
i = 0;
while ( i < n )
{
runcnt = FT_GET_BYTE();
if ( runcnt & GX_PT_POINTS_ARE_WORDS )
{
runcnt = runcnt & GX_PT_POINT_RUN_COUNT_MASK;
first = points[i++] = FT_GET_USHORT();
if ( runcnt < 1 || i + runcnt >= n )
goto Exit;
/* first point not included in runcount */
for ( j = 0; j < runcnt; ++j )
points[i++] = (FT_UShort)( first += FT_GET_USHORT() );
}
else
{
first = points[i++] = FT_GET_BYTE();
if ( runcnt < 1 || i + runcnt >= n )
goto Exit;
for ( j = 0; j < runcnt; ++j )
points[i++] = (FT_UShort)( first += FT_GET_BYTE() );
}
}
Exit:
return points;
}
enum
{
GX_DT_DELTAS_ARE_ZERO = 0x80,
GX_DT_DELTAS_ARE_WORDS = 0x40,
GX_DT_DELTA_RUN_COUNT_MASK = 0x3F
};
/*************************************************************************/
/* */
/* <Function> */
/* ft_var_readpackeddeltas */
/* */
/* <Description> */
/* Read a set of deltas. These are packed slightly differently than */
/* points. In particular there is no overall count. */
/* */
/* <Input> */
/* stream :: The data stream. */
/* */
/* delta_cnt :: The number of to be read. */
/* */
/* <Return> */
/* An array of FT_Short containing the deltas for the affected */
/* points. (This only gets the deltas for one dimension. It will */
/* generally be called twice, once for x, once for y. When used in */
/* cvt table, it will only be called once.) */
/* */
static FT_Short*
ft_var_readpackeddeltas( FT_Stream stream,
FT_Offset delta_cnt )
{
FT_Short *deltas = NULL;
FT_UInt runcnt;
FT_Offset i;
FT_UInt j;
FT_Memory memory = stream->memory;
FT_Error error = TT_Err_Ok;
FT_UNUSED( error );
if ( FT_NEW_ARRAY( deltas, delta_cnt ) )
return NULL;
i = 0;
while ( i < delta_cnt )
{
runcnt = FT_GET_BYTE();
if ( runcnt & GX_DT_DELTAS_ARE_ZERO )
{
/* runcnt zeroes get added */
for ( j = 0;
j <= ( runcnt & GX_DT_DELTA_RUN_COUNT_MASK ) && i < delta_cnt;
++j )
deltas[i++] = 0;
}
else if ( runcnt & GX_DT_DELTAS_ARE_WORDS )
{
/* runcnt shorts from the stack */
for ( j = 0;
j <= ( runcnt & GX_DT_DELTA_RUN_COUNT_MASK ) && i < delta_cnt;
++j )
deltas[i++] = FT_GET_SHORT();
}
else
{
/* runcnt signed bytes from the stack */
for ( j = 0;
j <= ( runcnt & GX_DT_DELTA_RUN_COUNT_MASK ) && i < delta_cnt;
++j )
deltas[i++] = FT_GET_CHAR();
}
if ( j <= ( runcnt & GX_DT_DELTA_RUN_COUNT_MASK ) )
{
/* Bad format */
FT_FREE( deltas );
return NULL;
}
}
return deltas;
}
/*************************************************************************/
/* */
/* <Function> */
/* ft_var_load_avar */
/* */
/* <Description> */
/* Parse the `avar' table if present. It need not be, so we return */
/* nothing. */
/* */
/* <InOut> */
/* face :: The font face. */
/* */
static void
ft_var_load_avar( TT_Face face )
{
FT_Stream stream = FT_FACE_STREAM(face);
FT_Memory memory = stream->memory;
GX_Blend blend = face->blend;
GX_AVarSegment segment;
FT_Error error = TT_Err_Ok;
FT_ULong version;
FT_Long axisCount;
FT_Int i, j;
FT_ULong table_len;
FT_UNUSED( error );
blend->avar_checked = TRUE;
if ( (error = face->goto_table( face, TTAG_avar, stream, &table_len )) != 0 )
return;
if ( FT_FRAME_ENTER( table_len ) )
return;
version = FT_GET_LONG();
axisCount = FT_GET_LONG();
if ( version != 0x00010000L ||
axisCount != (FT_Long)blend->mmvar->num_axis )
goto Exit;
if ( FT_NEW_ARRAY( blend->avar_segment, axisCount ) )
goto Exit;
segment = &blend->avar_segment[0];
for ( i = 0; i < axisCount; ++i, ++segment )
{
segment->pairCount = FT_GET_USHORT();
if ( FT_NEW_ARRAY( segment->correspondence, segment->pairCount ) )
{
/* Failure. Free everything we have done so far. We must do */
/* it right now since loading the `avar' table is optional. */
for ( j = i - 1; j >= 0; --j )
FT_FREE( blend->avar_segment[j].correspondence );
FT_FREE( blend->avar_segment );
blend->avar_segment = NULL;
goto Exit;
}
for ( j = 0; j < segment->pairCount; ++j )
{
segment->correspondence[j].fromCoord =
FT_GET_SHORT() << 2; /* convert to Fixed */
segment->correspondence[j].toCoord =
FT_GET_SHORT()<<2; /* convert to Fixed */
}
}
Exit:
FT_FRAME_EXIT();
}
typedef struct GX_GVar_Head_
{
FT_Long version;
FT_UShort axisCount;
FT_UShort globalCoordCount;
FT_ULong offsetToCoord;
FT_UShort glyphCount;
FT_UShort flags;
FT_ULong offsetToData;
} GX_GVar_Head;
/*************************************************************************/
/* */
/* <Function> */
/* ft_var_load_gvar */
/* */
/* <Description> */
/* Parses the `gvar' table if present. If `fvar' is there, `gvar' */
/* had better be there too. */
/* */
/* <InOut> */
/* face :: The font face. */
/* */
/* <Return> */
/* FreeType error code. 0 means success. */
/* */
static FT_Error
ft_var_load_gvar( TT_Face face )
{
FT_Stream stream = FT_FACE_STREAM(face);
FT_Memory memory = stream->memory;
GX_Blend blend = face->blend;
FT_Error error;
FT_UInt i, j;
FT_ULong table_len;
FT_ULong gvar_start;
FT_ULong offsetToData;
GX_GVar_Head gvar_head;
static const FT_Frame_Field gvar_fields[] =
{
#undef FT_STRUCTURE
#define FT_STRUCTURE GX_GVar_Head
FT_FRAME_START( 20 ),
FT_FRAME_LONG ( version ),
FT_FRAME_USHORT( axisCount ),
FT_FRAME_USHORT( globalCoordCount ),
FT_FRAME_ULONG ( offsetToCoord ),
FT_FRAME_USHORT( glyphCount ),
FT_FRAME_USHORT( flags ),
FT_FRAME_ULONG ( offsetToData ),
FT_FRAME_END
};
if ( (error = face->goto_table( face, TTAG_gvar, stream, &table_len )) != 0 )
goto Exit;
gvar_start = FT_STREAM_POS( );
if ( FT_STREAM_READ_FIELDS( gvar_fields, &gvar_head ) )
goto Exit;
blend->tuplecount = gvar_head.globalCoordCount;
blend->gv_glyphcnt = gvar_head.glyphCount;
offsetToData = gvar_start + gvar_head.offsetToData;
if ( gvar_head.version != (FT_Long)0x00010000L ||
gvar_head.axisCount != (FT_UShort)blend->mmvar->num_axis )
{
error = TT_Err_Invalid_Table;
goto Exit;
}
if ( FT_NEW_ARRAY( blend->glyphoffsets, blend->gv_glyphcnt + 1 ) )
goto Exit;
if ( gvar_head.flags & 1 )
{
/* long offsets (one more offset than glyphs, to mark size of last) */
if ( FT_FRAME_ENTER( ( blend->gv_glyphcnt + 1 ) * 4L ) )
goto Exit;
for ( i = 0; i <= blend->gv_glyphcnt; ++i )
blend->glyphoffsets[i] = offsetToData + FT_GET_LONG();
FT_FRAME_EXIT();
}
else
{
/* short offsets (one more offset than glyphs, to mark size of last) */
if ( FT_FRAME_ENTER( ( blend->gv_glyphcnt + 1 ) * 2L ) )
goto Exit;
for ( i = 0; i <= blend->gv_glyphcnt; ++i )
blend->glyphoffsets[i] = offsetToData + FT_GET_USHORT() * 2;
/* XXX: Undocumented: `*2'! */
FT_FRAME_EXIT();
}
if ( blend->tuplecount != 0 )
{
if ( FT_NEW_ARRAY( blend->tuplecoords,
gvar_head.axisCount * blend->tuplecount ) )
goto Exit;
if ( FT_STREAM_SEEK( gvar_start + gvar_head.offsetToCoord ) ||
FT_FRAME_ENTER( blend->tuplecount * gvar_head.axisCount * 2L ) )
goto Exit;
for ( i = 0; i < blend->tuplecount; ++i )
for ( j = 0 ; j < (FT_UInt)gvar_head.axisCount; ++j )
blend->tuplecoords[i * gvar_head.axisCount + j] =
FT_GET_SHORT() << 2; /* convert to FT_Fixed */
FT_FRAME_EXIT();
}
Exit:
return error;
}
/*************************************************************************/
/* */
/* <Function> */
/* ft_var_apply_tuple */
/* */
/* <Description> */
/* Figure out whether a given tuple (design) applies to the current */
/* blend, and if so, what is the scaling factor. */
/* */
/* <Input> */
/* blend :: The current blend of the font. */
/* */
/* tupleIndex :: A flag saying whether this is an intermediate */
/* tuple or not. */
/* */
/* tuple_coords :: The coordinates of the tuple in normalized axis */
/* units. */
/* */
/* im_start_coords :: The initial coordinates where this tuple starts */
/* to apply (for intermediate coordinates). */
/* */
/* im_end_coords :: The final coordinates after which this tuple no */
/* longer applies (for intermediate coordinates). */
/* */
/* <Return> */
/* An FT_Fixed value containing the scaling factor. */
/* */
static FT_Fixed
ft_var_apply_tuple( GX_Blend blend,
FT_UShort tupleIndex,
FT_Fixed* tuple_coords,
FT_Fixed* im_start_coords,
FT_Fixed* im_end_coords )
{
FT_UInt i;
FT_Fixed apply = 0x10000L;
for ( i = 0; i < blend->num_axis; ++i )
{
if ( tuple_coords[i] == 0 )
/* It's not clear why (for intermediate tuples) we don't need */
/* to check against start/end -- the documentation says we don't. */
/* Similarly, it's unclear why we don't need to scale along the */
/* axis. */
continue;
else if ( blend->normalizedcoords[i] == 0 ||
( blend->normalizedcoords[i] < 0 && tuple_coords[i] > 0 ) ||
( blend->normalizedcoords[i] > 0 && tuple_coords[i] < 0 ) )
{
apply = 0;
break;
}
else if ( !( tupleIndex & GX_TI_INTERMEDIATE_TUPLE ) )
/* not an intermediate tuple */
apply = FT_MulFix( apply,
blend->normalizedcoords[i] > 0
? blend->normalizedcoords[i]
: -blend->normalizedcoords[i] );
else if ( blend->normalizedcoords[i] <= im_start_coords[i] ||
blend->normalizedcoords[i] >= im_end_coords[i] )
{
apply = 0;
break;
}
else if ( blend->normalizedcoords[i] < tuple_coords[i] )
apply = FT_MulDiv( apply,
blend->normalizedcoords[i] - im_start_coords[i],
tuple_coords[i] - im_start_coords[i] );
else
apply = FT_MulDiv( apply,
im_end_coords[i] - blend->normalizedcoords[i],
im_end_coords[i] - tuple_coords[i] );
}
return apply;
}
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** MULTIPLE MASTERS SERVICE FUNCTIONS *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
typedef struct GX_FVar_Head_
{
FT_Long version;
FT_UShort offsetToData;
FT_UShort countSizePairs;
FT_UShort axisCount;
FT_UShort axisSize;
FT_UShort instanceCount;
FT_UShort instanceSize;
} GX_FVar_Head;
typedef struct fvar_axis_
{
FT_ULong axisTag;
FT_ULong minValue;
FT_ULong defaultValue;
FT_ULong maxValue;
FT_UShort flags;
FT_UShort nameID;
} GX_FVar_Axis;
/*************************************************************************/
/* */
/* <Function> */
/* TT_Get_MM_Var */
/* */
/* <Description> */
/* Check that the font's `fvar' table is valid, parse it, and return */
/* those data. */
/* */
/* <InOut> */
/* face :: The font face. */
/* TT_Get_MM_Var initializes the blend structure. */
/* */
/* <Output> */
/* master :: The `fvar' data (must be freed by caller). */
/* */
/* <Return> */
/* FreeType error code. 0 means success. */
/* */
FT_LOCAL_DEF( FT_Error )
TT_Get_MM_Var( TT_Face face,
FT_MM_Var* *master )
{
FT_Stream stream = face->root.stream;
FT_Memory memory = face->root.memory;
FT_ULong table_len;
FT_Error error = TT_Err_Ok;
FT_ULong fvar_start;
FT_Int i, j;
FT_MM_Var* mmvar = NULL;
FT_Fixed* next_coords;
FT_String* next_name;
FT_Var_Axis* a;
FT_Var_Named_Style* ns;
GX_FVar_Head fvar_head;
static const FT_Frame_Field fvar_fields[] =
{
#undef FT_STRUCTURE
#define FT_STRUCTURE GX_FVar_Head
FT_FRAME_START( 16 ),
FT_FRAME_LONG ( version ),
FT_FRAME_USHORT( offsetToData ),
FT_FRAME_USHORT( countSizePairs ),
FT_FRAME_USHORT( axisCount ),
FT_FRAME_USHORT( axisSize ),
FT_FRAME_USHORT( instanceCount ),
FT_FRAME_USHORT( instanceSize ),
FT_FRAME_END
};
static const FT_Frame_Field fvaraxis_fields[] =
{
#undef FT_STRUCTURE
#define FT_STRUCTURE GX_FVar_Axis
FT_FRAME_START( 20 ),
FT_FRAME_ULONG ( axisTag ),
FT_FRAME_ULONG ( minValue ),
FT_FRAME_ULONG ( defaultValue ),
FT_FRAME_ULONG ( maxValue ),
FT_FRAME_USHORT( flags ),
FT_FRAME_USHORT( nameID ),
FT_FRAME_END
};
if ( face->blend == NULL )
{
/* both `fvar' and `gvar' must be present */
if ( (error = face->goto_table( face, TTAG_gvar,
stream, &table_len )) != 0 )
goto Exit;
if ( (error = face->goto_table( face, TTAG_fvar,
stream, &table_len )) != 0 )
goto Exit;
fvar_start = FT_STREAM_POS( );
if ( FT_STREAM_READ_FIELDS( fvar_fields, &fvar_head ) )
goto Exit;
if ( fvar_head.version != (FT_Long)0x00010000L ||
fvar_head.countSizePairs != 2 ||
fvar_head.axisSize != 20 ||
/* axisCount limit implied by 16-bit instanceSize */
fvar_head.axisCount > 0x3FFE ||
fvar_head.instanceSize != 4 + 4 * fvar_head.axisCount ||
/* instanceCount limit implied by limited range of name IDs */
fvar_head.instanceCount > 0x7EFF ||
fvar_head.offsetToData + fvar_head.axisCount * 20U +
fvar_head.instanceCount * fvar_head.instanceSize > table_len )
{
error = TT_Err_Invalid_Table;
goto Exit;
}
if ( FT_NEW( face->blend ) )
goto Exit;
/* cannot overflow 32-bit arithmetic because of limits above */
face->blend->mmvar_len =
sizeof ( FT_MM_Var ) +
fvar_head.axisCount * sizeof ( FT_Var_Axis ) +
fvar_head.instanceCount * sizeof ( FT_Var_Named_Style ) +
fvar_head.instanceCount * fvar_head.axisCount * sizeof ( FT_Fixed ) +
5 * fvar_head.axisCount;
if ( FT_ALLOC( mmvar, face->blend->mmvar_len ) )
goto Exit;
face->blend->mmvar = mmvar;
mmvar->num_axis =
fvar_head.axisCount;
mmvar->num_designs =
~0; /* meaningless in this context; each glyph */
/* may have a different number of designs */
/* (or tuples, as called by Apple) */
mmvar->num_namedstyles =
fvar_head.instanceCount;
mmvar->axis =
(FT_Var_Axis*)&(mmvar[1]);
mmvar->namedstyle =
(FT_Var_Named_Style*)&(mmvar->axis[fvar_head.axisCount]);
next_coords =
(FT_Fixed*)&(mmvar->namedstyle[fvar_head.instanceCount]);
for ( i = 0; i < fvar_head.instanceCount; ++i )
{
mmvar->namedstyle[i].coords = next_coords;
next_coords += fvar_head.axisCount;
}
next_name = (FT_String*)next_coords;
for ( i = 0; i < fvar_head.axisCount; ++i )
{
mmvar->axis[i].name = next_name;
next_name += 5;
}
if ( FT_STREAM_SEEK( fvar_start + fvar_head.offsetToData ) )
goto Exit;
a = mmvar->axis;
for ( i = 0; i < fvar_head.axisCount; ++i )
{
GX_FVar_Axis axis_rec;
if ( FT_STREAM_READ_FIELDS( fvaraxis_fields, &axis_rec ) )
goto Exit;
a->tag = axis_rec.axisTag;
a->minimum = axis_rec.minValue; /* A Fixed */
a->def = axis_rec.defaultValue; /* A Fixed */
a->maximum = axis_rec.maxValue; /* A Fixed */
a->strid = axis_rec.nameID;
a->name[0] = (FT_String)( a->tag >> 24 );
a->name[1] = (FT_String)( ( a->tag >> 16 ) & 0xFF );
a->name[2] = (FT_String)( ( a->tag >> 8 ) & 0xFF );
a->name[3] = (FT_String)( ( a->tag ) & 0xFF );
a->name[4] = 0;
++a;
}
ns = mmvar->namedstyle;
for ( i = 0; i < fvar_head.instanceCount; ++i, ++ns )
{
if ( FT_FRAME_ENTER( 4L + 4L * fvar_head.axisCount ) )
goto Exit;
ns->strid = FT_GET_USHORT();
(void) /* flags = */ FT_GET_USHORT();
for ( j = 0; j < fvar_head.axisCount; ++j )
ns->coords[j] = FT_GET_ULONG(); /* A Fixed */
FT_FRAME_EXIT();
}
}
if ( master != NULL )
{
FT_UInt n;
if ( FT_ALLOC( mmvar, face->blend->mmvar_len ) )
goto Exit;
FT_MEM_COPY( mmvar, face->blend->mmvar, face->blend->mmvar_len );
mmvar->axis =
(FT_Var_Axis*)&(mmvar[1]);
mmvar->namedstyle =
(FT_Var_Named_Style*)&(mmvar->axis[mmvar->num_axis]);
next_coords =
(FT_Fixed*)&(mmvar->namedstyle[mmvar->num_namedstyles]);
for ( n = 0; n < mmvar->num_namedstyles; ++n )
{
mmvar->namedstyle[n].coords = next_coords;
next_coords += mmvar->num_axis;
}
a = mmvar->axis;
next_name = (FT_String*)next_coords;
for ( n = 0; n < mmvar->num_axis; ++n )
{
a->name = next_name;
/* standard PostScript names for some standard apple tags */
if ( a->tag == TTAG_wght )
a->name = (char *)"Weight";
else if ( a->tag == TTAG_wdth )
a->name = (char *)"Width";
else if ( a->tag == TTAG_opsz )
a->name = (char *)"OpticalSize";
else if ( a->tag == TTAG_slnt )
a->name = (char *)"Slant";
next_name += 5;
++a;
}
*master = mmvar;
}
Exit:
return error;
}
/*************************************************************************/
/* */
/* <Function> */
/* TT_Set_MM_Blend */
/* */
/* <Description> */
/* Set the blend (normalized) coordinates for this instance of the */
/* font. Check that the `gvar' table is reasonable and does some */
/* initial preparation. */
/* */
/* <InOut> */
/* face :: The font. */
/* Initialize the blend structure with `gvar' data. */
/* */
/* <Input> */
/* num_coords :: Must be the axis count of the font. */
/* */
/* coords :: An array of num_coords, each between [-1,1]. */
/* */
/* <Return> */
/* FreeType error code. 0 means success. */
/* */
FT_LOCAL_DEF( FT_Error )
TT_Set_MM_Blend( TT_Face face,
FT_UInt num_coords,
FT_Fixed* coords )
{
FT_Error error = TT_Err_Ok;
GX_Blend blend;
FT_MM_Var* mmvar;
FT_UInt i;
FT_Memory memory = face->root.memory;
enum
{
mcvt_retain,
mcvt_modify,
mcvt_load
} manageCvt;
face->doblend = FALSE;
if ( face->blend == NULL )
{
if ( (error = TT_Get_MM_Var( face, NULL)) != 0 )
goto Exit;
}
blend = face->blend;
mmvar = blend->mmvar;
if ( num_coords != mmvar->num_axis )
{
error = TT_Err_Invalid_Argument;
goto Exit;
}
for ( i = 0; i < num_coords; ++i )
if ( coords[i] < -0x00010000L || coords[i] > 0x00010000L )
{
error = TT_Err_Invalid_Argument;
goto Exit;
}
if ( blend->glyphoffsets == NULL )
if ( (error = ft_var_load_gvar( face )) != 0 )
goto Exit;
if ( blend->normalizedcoords == NULL )
{
if ( FT_NEW_ARRAY( blend->normalizedcoords, num_coords ) )
goto Exit;
manageCvt = mcvt_modify;
/* If we have not set the blend coordinates before this, then the */
/* cvt table will still be what we read from the `cvt ' table and */
/* we don't need to reload it. We may need to change it though... */
}
else
{
manageCvt = mcvt_retain;
for ( i = 0; i < num_coords; ++i )
{
if ( blend->normalizedcoords[i] != coords[i] )
{
manageCvt = mcvt_load;
break;
}
}
/* If we don't change the blend coords then we don't need to do */
/* anything to the cvt table. It will be correct. Otherwise we */
/* no longer have the original cvt (it was modified when we set */
/* the blend last time), so we must reload and then modify it. */
}
blend->num_axis = num_coords;
FT_MEM_COPY( blend->normalizedcoords,
coords,
num_coords * sizeof ( FT_Fixed ) );
face->doblend = TRUE;
if ( face->cvt != NULL )
{
switch ( manageCvt )
{
case mcvt_load:
/* The cvt table has been loaded already; every time we change the */
/* blend we may need to reload and remodify the cvt table. */
FT_FREE( face->cvt );
face->cvt = NULL;
tt_face_load_cvt( face, face->root.stream );
break;
case mcvt_modify:
/* The original cvt table is in memory. All we need to do is */
/* apply the `cvar' table (if any). */
tt_face_vary_cvt( face, face->root.stream );
break;
case mcvt_retain:
/* The cvt table is correct for this set of coordinates. */
break;
}
}
Exit:
return error;
}
/*************************************************************************/
/* */
/* <Function> */
/* TT_Set_Var_Design */
/* */
/* <Description> */
/* Set the coordinates for the instance, measured in the user */
/* coordinate system. Parse the `avar' table (if present) to convert */
/* from user to normalized coordinates. */
/* */
/* <InOut> */
/* face :: The font face. */
/* Initialize the blend struct with `gvar' data. */
/* */
/* <Input> */
/* num_coords :: This must be the axis count of the font. */
/* */
/* coords :: A coordinate array with `num_coords' elements. */
/* */
/* <Return> */
/* FreeType error code. 0 means success. */
/* */
FT_LOCAL_DEF( FT_Error )
TT_Set_Var_Design( TT_Face face,
FT_UInt num_coords,
FT_Fixed* coords )
{
FT_Error error = TT_Err_Ok;
FT_Fixed* normalized = NULL;
GX_Blend blend;
FT_MM_Var* mmvar;
FT_UInt i, j;
FT_Var_Axis* a;
GX_AVarSegment av;
FT_Memory memory = face->root.memory;
if ( face->blend == NULL )
{
if ( (error = TT_Get_MM_Var( face, NULL )) != 0 )
goto Exit;
}
blend = face->blend;
mmvar = blend->mmvar;
if ( num_coords != mmvar->num_axis )
{
error = TT_Err_Invalid_Argument;
goto Exit;
}
/* Axis normalization is a two stage process. First we normalize */
/* based on the [min,def,max] values for the axis to be [-1,0,1]. */
/* Then, if there's an `avar' table, we renormalize this range. */
if ( FT_NEW_ARRAY( normalized, mmvar->num_axis ) )
goto Exit;
a = mmvar->axis;
for ( i = 0; i < mmvar->num_axis; ++i, ++a )
{
if ( coords[i] > a->maximum || coords[i] < a->minimum )
{
error = TT_Err_Invalid_Argument;
goto Exit;
}
if ( coords[i] < a->def )
normalized[i] = -FT_DivFix( coords[i] - a->def, a->minimum - a->def );
else if ( a->maximum == a->def )
normalized[i] = 0;
else
normalized[i] = FT_DivFix( coords[i] - a->def, a->maximum - a->def );
}
if ( !blend->avar_checked )
ft_var_load_avar( face );
if ( blend->avar_segment != NULL )
{
av = blend->avar_segment;
for ( i = 0; i < mmvar->num_axis; ++i, ++av )
{
for ( j = 1; j < (FT_UInt)av->pairCount; ++j )
if ( normalized[i] < av->correspondence[j].fromCoord )
{
normalized[i] =
FT_MulDiv( normalized[i] - av->correspondence[j - 1].fromCoord,
av->correspondence[j].toCoord -
av->correspondence[j - 1].toCoord,
av->correspondence[j].fromCoord -
av->correspondence[j - 1].fromCoord ) +
av->correspondence[j - 1].toCoord;
break;
}
}
}
error = TT_Set_MM_Blend( face, num_coords, normalized );
Exit:
FT_FREE( normalized );
return error;
}
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** GX VAR PARSING ROUTINES *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
/*************************************************************************/
/* */
/* <Function> */
/* tt_face_vary_cvt */
/* */
/* <Description> */
/* Modify the loaded cvt table according to the `cvar' table and the */
/* font's blend. */
/* */
/* <InOut> */
/* face :: A handle to the target face object. */
/* */
/* <Input> */
/* stream :: A handle to the input stream. */
/* */
/* <Return> */
/* FreeType error code. 0 means success. */
/* */
/* Most errors are ignored. It is perfectly valid not to have a */
/* `cvar' table even if there is a `gvar' and `fvar' table. */
/* */
FT_LOCAL_DEF( FT_Error )
tt_face_vary_cvt( TT_Face face,
FT_Stream stream )
{
FT_Error error;
FT_Memory memory = stream->memory;
FT_ULong table_start;
FT_ULong table_len;
FT_UInt tupleCount;
FT_ULong offsetToData;
FT_ULong here;
FT_UInt i, j;
FT_Fixed* tuple_coords = NULL;
FT_Fixed* im_start_coords = NULL;
FT_Fixed* im_end_coords = NULL;
GX_Blend blend = face->blend;
FT_UInt point_count;
FT_UShort* localpoints;
FT_Short* deltas;
FT_TRACE2(( "CVAR " ));
if ( blend == NULL )
{
FT_TRACE2(( "tt_face_vary_cvt: no blend specified\n" ));
error = TT_Err_Ok;
goto Exit;
}
if ( face->cvt == NULL )
{
FT_TRACE2(( "tt_face_vary_cvt: no `cvt ' table\n" ));
error = TT_Err_Ok;
goto Exit;
}
error = face->goto_table( face, TTAG_cvar, stream, &table_len );
if ( error )
{
FT_TRACE2(( "is missing\n" ));
error = TT_Err_Ok;
goto Exit;
}
if ( FT_FRAME_ENTER( table_len ) )
{
error = TT_Err_Ok;
goto Exit;
}
table_start = FT_Stream_FTell( stream );
if ( FT_GET_LONG() != 0x00010000L )
{
FT_TRACE2(( "bad table version\n" ));
error = TT_Err_Ok;
goto FExit;
}
if ( FT_NEW_ARRAY( tuple_coords, blend->num_axis ) ||
FT_NEW_ARRAY( im_start_coords, blend->num_axis ) ||
FT_NEW_ARRAY( im_end_coords, blend->num_axis ) )
goto FExit;
tupleCount = FT_GET_USHORT();
offsetToData = table_start + FT_GET_USHORT();
/* The documentation implies there are flags packed into the */
/* tuplecount, but John Jenkins says that shared points don't apply */
/* to `cvar', and no other flags are defined. */
for ( i = 0; i < ( tupleCount & 0xFFF ); ++i )
{
FT_UInt tupleDataSize;
FT_UInt tupleIndex;
FT_Fixed apply;
tupleDataSize = FT_GET_USHORT();
tupleIndex = FT_GET_USHORT();
/* There is no provision here for a global tuple coordinate section, */
/* so John says. There are no tuple indices, just embedded tuples. */
if ( tupleIndex & GX_TI_EMBEDDED_TUPLE_COORD )
{
for ( j = 0; j < blend->num_axis; ++j )
tuple_coords[j] = FT_GET_SHORT() << 2; /* convert from */
/* short frac to fixed */
}
else
{
/* skip this tuple; it makes no sense */
if ( tupleIndex & GX_TI_INTERMEDIATE_TUPLE )
for ( j = 0; j < 2 * blend->num_axis; ++j )
(void)FT_GET_SHORT();
offsetToData += tupleDataSize;
continue;
}
if ( tupleIndex & GX_TI_INTERMEDIATE_TUPLE )
{
for ( j = 0; j < blend->num_axis; ++j )
im_start_coords[j] = FT_GET_SHORT() << 2;
for ( j = 0; j < blend->num_axis; ++j )
im_end_coords[j] = FT_GET_SHORT() << 2;
}
apply = ft_var_apply_tuple( blend,
(FT_UShort)tupleIndex,
tuple_coords,
im_start_coords,
im_end_coords );
if ( /* tuple isn't active for our blend */
apply == 0 ||
/* global points not allowed, */
/* if they aren't local, makes no sense */
!( tupleIndex & GX_TI_PRIVATE_POINT_NUMBERS ) )
{
offsetToData += tupleDataSize;
continue;
}
here = FT_Stream_FTell( stream );
FT_Stream_SeekSet( stream, offsetToData );
localpoints = ft_var_readpackedpoints( stream, &point_count );
deltas = ft_var_readpackeddeltas( stream,
point_count == 0 ? face->cvt_size
: point_count );
if ( localpoints == NULL || deltas == NULL )
/* failure, ignore it */;
else if ( localpoints == ALL_POINTS )
{
/* this means that there are deltas for every entry in cvt */
for ( j = 0; j < face->cvt_size; ++j )
face->cvt[j] = (FT_Short)( face->cvt[j] +
FT_MulFix( deltas[j], apply ) );
}
else
{
for ( j = 0; j < point_count; ++j )
{
int pindex = localpoints[j];
face->cvt[pindex] = (FT_Short)( face->cvt[pindex] +
FT_MulFix( deltas[j], apply ) );
}
}
if ( localpoints != ALL_POINTS )
FT_FREE( localpoints );
FT_FREE( deltas );
offsetToData += tupleDataSize;
FT_Stream_SeekSet( stream, here );
}
FExit:
FT_FRAME_EXIT();
Exit:
FT_FREE( tuple_coords );
FT_FREE( im_start_coords );
FT_FREE( im_end_coords );
return error;
}
/*************************************************************************/
/* */
/* <Function> */
/* TT_Vary_Get_Glyph_Deltas */
/* */
/* <Description> */
/* Load the appropriate deltas for the current glyph. */
/* */
/* <Input> */
/* face :: A handle to the target face object. */
/* */
/* glyph_index :: The index of the glyph being modified. */
/* */
/* n_points :: The number of the points in the glyph, including */
/* phantom points. */
/* */
/* <Output> */
/* deltas :: The array of points to change. */
/* */
/* <Return> */
/* FreeType error code. 0 means success. */
/* */
FT_LOCAL_DEF( FT_Error )
TT_Vary_Get_Glyph_Deltas( TT_Face face,
FT_UInt glyph_index,
FT_Vector* *deltas,
FT_UInt n_points )
{
FT_Stream stream = face->root.stream;
FT_Memory memory = stream->memory;
GX_Blend blend = face->blend;
FT_Vector* delta_xy = NULL;
FT_Error error;
FT_ULong glyph_start;
FT_UInt tupleCount;
FT_ULong offsetToData;
FT_ULong here;
FT_UInt i, j;
FT_Fixed* tuple_coords = NULL;
FT_Fixed* im_start_coords = NULL;
FT_Fixed* im_end_coords = NULL;
FT_UInt point_count, spoint_count = 0;
FT_UShort* sharedpoints = NULL;
FT_UShort* localpoints = NULL;
FT_UShort* points;
FT_Short *deltas_x, *deltas_y;
if ( !face->doblend || blend == NULL )
return TT_Err_Invalid_Argument;
/* to be freed by the caller */
if ( FT_NEW_ARRAY( delta_xy, n_points ) )
goto Exit;
*deltas = delta_xy;
if ( glyph_index >= blend->gv_glyphcnt ||
blend->glyphoffsets[glyph_index] ==
blend->glyphoffsets[glyph_index + 1] )
return TT_Err_Ok; /* no variation data for this glyph */
if ( FT_STREAM_SEEK( blend->glyphoffsets[glyph_index] ) ||
FT_FRAME_ENTER( blend->glyphoffsets[glyph_index + 1] -
blend->glyphoffsets[glyph_index] ) )
goto Fail1;
glyph_start = FT_Stream_FTell( stream );
/* each set of glyph variation data is formatted similarly to `cvar' */
/* (except we get shared points and global tuples) */
if ( FT_NEW_ARRAY( tuple_coords, blend->num_axis ) ||
FT_NEW_ARRAY( im_start_coords, blend->num_axis ) ||
FT_NEW_ARRAY( im_end_coords, blend->num_axis ) )
goto Fail2;
tupleCount = FT_GET_USHORT();
offsetToData = glyph_start + FT_GET_USHORT();
if ( tupleCount & GX_TC_TUPLES_SHARE_POINT_NUMBERS )
{
here = FT_Stream_FTell( stream );
FT_Stream_SeekSet( stream, offsetToData );
sharedpoints = ft_var_readpackedpoints( stream, &spoint_count );
offsetToData = FT_Stream_FTell( stream );
FT_Stream_SeekSet( stream, here );
}
for ( i = 0; i < ( tupleCount & GX_TC_TUPLE_COUNT_MASK ); ++i )
{
FT_UInt tupleDataSize;
FT_UInt tupleIndex;
FT_Fixed apply;
tupleDataSize = FT_GET_USHORT();
tupleIndex = FT_GET_USHORT();
if ( tupleIndex & GX_TI_EMBEDDED_TUPLE_COORD )
{
for ( j = 0; j < blend->num_axis; ++j )
tuple_coords[j] = FT_GET_SHORT() << 2; /* convert from */
/* short frac to fixed */
}
else if ( ( tupleIndex & GX_TI_TUPLE_INDEX_MASK ) >= blend->tuplecount )
{
error = TT_Err_Invalid_Table;
goto Fail3;
}
else
{
FT_MEM_COPY(
tuple_coords,
&blend->tuplecoords[(tupleIndex & 0xFFF) * blend->num_axis],
blend->num_axis * sizeof ( FT_Fixed ) );
}
if ( tupleIndex & GX_TI_INTERMEDIATE_TUPLE )
{
for ( j = 0; j < blend->num_axis; ++j )
im_start_coords[j] = FT_GET_SHORT() << 2;
for ( j = 0; j < blend->num_axis; ++j )
im_end_coords[j] = FT_GET_SHORT() << 2;
}
apply = ft_var_apply_tuple( blend,
(FT_UShort)tupleIndex,
tuple_coords,
im_start_coords,
im_end_coords );
if ( apply == 0 ) /* tuple isn't active for our blend */
{
offsetToData += tupleDataSize;
continue;
}
here = FT_Stream_FTell( stream );
if ( tupleIndex & GX_TI_PRIVATE_POINT_NUMBERS )
{
FT_Stream_SeekSet( stream, offsetToData );
localpoints = ft_var_readpackedpoints( stream, &point_count );
points = localpoints;
}
else
{
points = sharedpoints;
point_count = spoint_count;
}
deltas_x = ft_var_readpackeddeltas( stream,
point_count == 0 ? n_points
: point_count );
deltas_y = ft_var_readpackeddeltas( stream,
point_count == 0 ? n_points
: point_count );
if ( points == NULL || deltas_y == NULL || deltas_x == NULL )
; /* failure, ignore it */
else if ( points == ALL_POINTS )
{
/* this means that there are deltas for every point in the glyph */
for ( j = 0; j < n_points; ++j )
{
delta_xy[j].x += FT_MulFix( deltas_x[j], apply );
delta_xy[j].y += FT_MulFix( deltas_y[j], apply );
}
}
else
{
for ( j = 0; j < point_count; ++j )
{
if ( localpoints[j] >= n_points )
continue;
delta_xy[localpoints[j]].x += FT_MulFix( deltas_x[j], apply );
delta_xy[localpoints[j]].y += FT_MulFix( deltas_y[j], apply );
}
}
if ( localpoints != ALL_POINTS )
FT_FREE( localpoints );
FT_FREE( deltas_x );
FT_FREE( deltas_y );
offsetToData += tupleDataSize;
FT_Stream_SeekSet( stream, here );
}
Fail3:
FT_FREE( tuple_coords );
FT_FREE( im_start_coords );
FT_FREE( im_end_coords );
Fail2:
FT_FRAME_EXIT();
Fail1:
if ( error )
{
FT_FREE( delta_xy );
*deltas = NULL;
}
Exit:
return error;
}
/*************************************************************************/
/* */
/* <Function> */
/* tt_done_blend */
/* */
/* <Description> */
/* Frees the blend internal data structure. */
/* */
FT_LOCAL_DEF( void )
tt_done_blend( FT_Memory memory,
GX_Blend blend )
{
if ( blend != NULL )
{
FT_UInt i;
FT_FREE( blend->normalizedcoords );
FT_FREE( blend->mmvar );
if ( blend->avar_segment != NULL )
{
for ( i = 0; i < blend->num_axis; ++i )
FT_FREE( blend->avar_segment[i].correspondence );
FT_FREE( blend->avar_segment );
}
FT_FREE( blend->tuplecoords );
FT_FREE( blend->glyphoffsets );
FT_FREE( blend );
}
}
#endif /* TT_CONFIG_OPTION_GX_VAR_SUPPORT */
/* END */
| {
"pile_set_name": "Github"
} |
val name_alist =
map (fn s => (acl2_name_to_hol_name s, s))
[
"ACL2::IFF",
"ACL2::BOOLEANP",
"ACL2::IMPLIES",
"COMMON-LISP::NOT",
"ACL2::HIDE",
"COMMON-LISP::EQ",
"ACL2::TRUE-LISTP",
"ACL2::LIST-MACRO",
"ACL2::AND-MACRO",
"ACL2::OR-MACRO",
"ACL2::INTEGER-ABS",
"ACL2::XXXJOIN",
"ACL2::LEN",
"COMMON-LISP::LENGTH",
"ACL2::ACL2-COUNT",
"ACL2::COND-CLAUSESP",
"ACL2::COND-MACRO",
"ACL2::EQLABLEP",
"ACL2::EQLABLE-LISTP",
"COMMON-LISP::ATOM",
"ACL2::MAKE-CHARACTER-LIST",
"ACL2::EQLABLE-ALISTP",
"ACL2::ALISTP",
"COMMON-LISP::ACONS",
"COMMON-LISP::ENDP",
"ACL2::MUST-BE-EQUAL",
"ACL2::MEMBER-EQUAL",
"ACL2::UNION-EQUAL",
"ACL2::SUBSETP-EQUAL",
"ACL2::SYMBOL-LISTP",
"COMMON-LISP::NULL",
"ACL2::MEMBER-EQ",
"ACL2::SUBSETP-EQ",
"ACL2::SYMBOL-ALISTP",
"ACL2::ASSOC-EQ",
"ACL2::ASSOC-EQUAL",
"ACL2::ASSOC-EQ-EQUAL-ALISTP",
"ACL2::ASSOC-EQ-EQUAL",
"ACL2::NO-DUPLICATESP-EQUAL",
"ACL2::STRIP-CARS",
"COMMON-LISP::EQL",
"COMMON-LISP::=",
"COMMON-LISP::/=",
"ACL2::ZP",
"ACL2::ZIP",
"COMMON-LISP::NTH",
"COMMON-LISP::CHAR",
"ACL2::PROPER-CONSP",
"ACL2::IMPROPER-CONSP",
"COMMON-LISP::CONJUGATE",
"ACL2::PROG2$",
"ACL2::TIME$",
"ACL2::FIX",
"ACL2::FORCE",
"ACL2::IMMEDIATE-FORCE-MODEP",
"ACL2::CASE-SPLIT",
"ACL2::SYNP",
"COMMON-LISP::MEMBER",
"ACL2::NO-DUPLICATESP",
"COMMON-LISP::ASSOC",
"ACL2::R-EQLABLE-ALISTP",
"COMMON-LISP::RASSOC",
"ACL2::RASSOC-EQUAL",
"ACL2::R-SYMBOL-ALISTP",
"ACL2::RASSOC-EQ"];
val defuns =
[
`(DEFUN IFF (P Q)
(IF P (IF Q 'T 'NIL) (IF Q 'NIL 'T)))`,
`(DEFUN BOOLEANP (X)
(IF (EQUAL X 'T) 'T (EQUAL X 'NIL)))`,
`(DEFUN IMPLIES (P Q)
(IF P (IF Q 'T 'NIL) 'T))`,
`(DEFUN NOT (P) (IF P 'NIL 'T))`,
`(DEFUN HIDE (X) X)`,
`(DEFUN EQ (X Y) (EQUAL X Y))`,
`(DEFUN TRUE-LISTP (X)
(IF (CONSP X)
(TRUE-LISTP (CDR X))
(EQ X 'NIL)))`,
`(DEFUN LIST-MACRO (LST)
(IF (CONSP LST)
(CONS 'CONS
(CONS (CAR LST)
(CONS (LIST-MACRO (CDR LST)) 'NIL)))
'NIL))`,
`(DEFUN AND-MACRO (LST)
(IF (CONSP LST)
(IF (CONSP (CDR LST))
(CONS 'IF
(CONS (CAR LST)
(CONS (AND-MACRO (CDR LST))
(CONS 'NIL 'NIL))))
(CAR LST))
'T))`,
`(DEFUN OR-MACRO (LST)
(IF (CONSP LST)
(IF (CONSP (CDR LST))
(CONS 'IF
(CONS (CAR LST)
(CONS (CAR LST)
(CONS (OR-MACRO (CDR LST)) 'NIL))))
(CAR LST))
'NIL))`,
`(DEFUN INTEGER-ABS (X)
(IF (INTEGERP X)
(IF (< X '0) (UNARY-- X) X)
'0))`,
`(DEFUN XXXJOIN (FN ARGS)
(IF (CDR (CDR ARGS))
(CONS FN
(CONS (CAR ARGS)
(CONS (XXXJOIN FN (CDR ARGS)) 'NIL)))
(CONS FN ARGS)))`,
`(DEFUN LEN (X)
(IF (CONSP X)
(BINARY-+ '1 (LEN (CDR X)))
'0))`,
`(DEFUN LENGTH (X)
(IF (STRINGP X)
(LEN (COERCE X 'LIST))
(LEN X)))`,
`(DEFUN ACL2-COUNT (X)
(IF (CONSP X)
(BINARY-+ '1
(BINARY-+ (ACL2-COUNT (CAR X))
(ACL2-COUNT (CDR X))))
(IF (RATIONALP X)
(IF (INTEGERP X)
(INTEGER-ABS X)
(BINARY-+ (INTEGER-ABS (NUMERATOR X))
(DENOMINATOR X)))
(IF (COMPLEX-RATIONALP X)
(BINARY-+ '1
(BINARY-+ (ACL2-COUNT (REALPART X))
(ACL2-COUNT (IMAGPART X))))
(IF (STRINGP X) (LENGTH X) '0)))))`,
`(DEFUN COND-CLAUSESP (CLAUSES)
(IF (CONSP CLAUSES)
(IF (CONSP (CAR CLAUSES))
(IF (TRUE-LISTP (CAR CLAUSES))
(IF (< (LEN (CAR CLAUSES)) '3)
(IF (EQ (CAR (CAR CLAUSES)) 'T)
(EQ (CDR CLAUSES) 'NIL)
(COND-CLAUSESP (CDR CLAUSES)))
'NIL)
'NIL)
'NIL)
(EQ CLAUSES 'NIL)))`,
`(DEFUN COND-MACRO (CLAUSES)
(IF (CONSP CLAUSES)
(IF (EQ (CAR (CAR CLAUSES)) 'T)
(IF (CDR (CAR CLAUSES))
(CAR (CDR (CAR CLAUSES)))
(CAR (CAR CLAUSES)))
(CONS 'IF
(CONS (CAR (CAR CLAUSES))
(CONS (IF (CDR (CAR CLAUSES))
(CAR (CDR (CAR CLAUSES)))
(CAR (CAR CLAUSES)))
(CONS (COND-MACRO (CDR CLAUSES))
'NIL)))))
'NIL))`,
`(DEFUN EQLABLEP (X)
(IF (ACL2-NUMBERP X)
(ACL2-NUMBERP X)
(IF (SYMBOLP X)
(SYMBOLP X)
(CHARACTERP X))))`,
`(DEFUN EQLABLE-LISTP (L)
(IF (CONSP L)
(IF (EQLABLEP (CAR L))
(EQLABLE-LISTP (CDR L))
'NIL)
(EQUAL L 'NIL)))`,
`(DEFUN ATOM (X) (NOT (CONSP X)))`,
`(DEFUN MAKE-CHARACTER-LIST (X)
(IF (ATOM X)
'NIL
(IF (CHARACTERP (CAR X))
(CONS (CAR X)
(MAKE-CHARACTER-LIST (CDR X)))
(CONS (CODE-CHAR '0)
(MAKE-CHARACTER-LIST (CDR X))))))`,
`(DEFUN EQLABLE-ALISTP (X)
(IF (ATOM X)
(EQUAL X 'NIL)
(IF (CONSP (CAR X))
(IF (EQLABLEP (CAR (CAR X)))
(EQLABLE-ALISTP (CDR X))
'NIL)
'NIL)))`,
`(DEFUN ALISTP (L)
(IF (ATOM L)
(EQ L 'NIL)
(IF (CONSP (CAR L))
(ALISTP (CDR L))
'NIL)))`,
`(DEFUN ACONS (KEY DATUM ALIST)
(CONS (CONS KEY DATUM) ALIST))`,
`(DEFUN ENDP (X) (ATOM X))`,
`(DEFUN MUST-BE-EQUAL (LOGIC EXEC) LOGIC)`,
`(DEFUN MEMBER-EQUAL (X LST)
(IF (ENDP LST)
'NIL
(IF (EQUAL X (CAR LST))
LST (MEMBER-EQUAL X (CDR LST)))))`,
`(DEFUN UNION-EQUAL (X Y)
(IF (ENDP X)
Y
(IF (MEMBER-EQUAL (CAR X) Y)
(UNION-EQUAL (CDR X) Y)
(CONS (CAR X)
(UNION-EQUAL (CDR X) Y)))))`,
`(DEFUN SUBSETP-EQUAL (X Y)
(IF (ENDP X)
'T
(IF (MEMBER-EQUAL (CAR X) Y)
(SUBSETP-EQUAL (CDR X) Y)
'NIL)))`,
`(DEFUN SYMBOL-LISTP (LST)
(IF (ATOM LST)
(EQ LST 'NIL)
(IF (SYMBOLP (CAR LST))
(SYMBOL-LISTP (CDR LST))
'NIL)))`,
`(DEFUN NULL (X) (EQ X 'NIL))`,
`(DEFUN MEMBER-EQ (X LST)
(IF (ENDP LST)
'NIL
(IF (EQ X (CAR LST))
LST (MEMBER-EQ X (CDR LST)))))`,
`(DEFUN SUBSETP-EQ (X Y)
(IF (ENDP X)
'T
(IF (MEMBER-EQ (CAR X) Y)
(SUBSETP-EQ (CDR X) Y)
'NIL)))`,
`(DEFUN SYMBOL-ALISTP (X)
(IF (ATOM X)
(EQ X 'NIL)
(IF (CONSP (CAR X))
(IF (SYMBOLP (CAR (CAR X)))
(SYMBOL-ALISTP (CDR X))
'NIL)
'NIL)))`,
`(DEFUN ASSOC-EQ (X ALIST)
(IF (ENDP ALIST)
'NIL
(IF (EQ X (CAR (CAR ALIST)))
(CAR ALIST)
(ASSOC-EQ X (CDR ALIST)))))`,
`(DEFUN ASSOC-EQUAL (X ALIST)
(IF (ENDP ALIST)
'NIL
(IF (EQUAL X (CAR (CAR ALIST)))
(CAR ALIST)
(ASSOC-EQUAL X (CDR ALIST)))))`,
`(DEFUN ASSOC-EQ-EQUAL-ALISTP (X)
(IF (ATOM X)
(EQ X 'NIL)
(IF (CONSP (CAR X))
(IF (SYMBOLP (CAR (CAR X)))
(IF (CONSP (CDR (CAR X)))
(ASSOC-EQ-EQUAL-ALISTP (CDR X))
'NIL)
'NIL)
'NIL)))`,
`(DEFUN ASSOC-EQ-EQUAL (X Y ALIST)
(IF (ENDP ALIST)
'NIL
(IF (IF (EQ (CAR (CAR ALIST)) X)
(EQUAL (CAR (CDR (CAR ALIST))) Y)
'NIL)
(CAR ALIST)
(ASSOC-EQ-EQUAL X Y (CDR ALIST)))))`,
`(DEFUN NO-DUPLICATESP-EQUAL (L)
(IF (ENDP L)
'T
(IF (MEMBER-EQUAL (CAR L) (CDR L))
'NIL
(NO-DUPLICATESP-EQUAL (CDR L)))))`,
`(DEFUN STRIP-CARS (X)
(IF (ENDP X)
'NIL
(CONS (CAR (CAR X))
(STRIP-CARS (CDR X)))))`,
`(DEFUN EQL (X Y) (EQUAL X Y))`,
`(DEFUN = (X Y) (EQUAL X Y))`,
`(DEFUN /= (X Y) (NOT (EQUAL X Y)))`,
`(DEFUN ZP (X)
(IF (INTEGERP X) (NOT (< '0 X)) 'T))`,
`(DEFUN ZIP (X)
(IF (INTEGERP X) (= X '0) 'T))`,
`(DEFUN NTH (N L)
(IF (ENDP L)
'NIL
(IF (ZP N)
(CAR L)
(NTH (BINARY-+ '-1 N) (CDR L)))))`,
`(DEFUN CHAR (S N)
(NTH N (COERCE S 'LIST)))`,
`(DEFUN PROPER-CONSP (X)
(IF (CONSP X) (TRUE-LISTP X) 'NIL))`,
`(DEFUN IMPROPER-CONSP (X)
(IF (CONSP X)
(NOT (TRUE-LISTP X))
'NIL))`,
`(DEFUN CONJUGATE (X)
(IF (COMPLEX-RATIONALP X)
(COMPLEX (REALPART X)
(UNARY-- (IMAGPART X)))
X))`,
`(DEFUN PROG2$ (X Y) Y)`,
`(DEFUN TIME$ (X) X)`,
`(DEFUN FIX (X)
(IF (ACL2-NUMBERP X) X '0))`,
`(DEFUN FORCE (X) X)`,
`(DEFUN IMMEDIATE-FORCE-MODEP
NIL '"See :DOC immediate-force-modep.")`,
`(DEFUN CASE-SPLIT (X) X)`,
`(DEFUN SYNP (VARS FORM TERM) 'T)`,
`(DEFUN MEMBER (X L)
(IF (ENDP L)
'NIL
(IF (EQL X (CAR L))
L (MEMBER X (CDR L)))))`,
`(DEFUN NO-DUPLICATESP (L)
(IF (ENDP L)
'T
(IF (MEMBER (CAR L) (CDR L))
'NIL
(NO-DUPLICATESP (CDR L)))))`,
`(DEFUN ASSOC (X ALIST)
(IF (ENDP ALIST)
'NIL
(IF (EQL X (CAR (CAR ALIST)))
(CAR ALIST)
(ASSOC X (CDR ALIST)))))`,
`(DEFUN R-EQLABLE-ALISTP (X)
(IF (ATOM X)
(EQUAL X 'NIL)
(IF (CONSP (CAR X))
(IF (EQLABLEP (CDR (CAR X)))
(R-EQLABLE-ALISTP (CDR X))
'NIL)
'NIL)))`,
`(DEFUN RASSOC (X ALIST)
(IF (ENDP ALIST)
'NIL
(IF (EQL X (CDR (CAR ALIST)))
(CAR ALIST)
(RASSOC X (CDR ALIST)))))`,
`(DEFUN RASSOC-EQUAL (X ALIST)
(IF (ENDP ALIST)
'NIL
(IF (EQUAL X (CDR (CAR ALIST)))
(CAR ALIST)
(RASSOC-EQUAL X (CDR ALIST)))))`,
`(DEFUN R-SYMBOL-ALISTP (X)
(IF (ATOM X)
(EQUAL X 'NIL)
(IF (CONSP (CAR X))
(IF (SYMBOLP (CDR (CAR X)))
(R-SYMBOL-ALISTP (CDR X))
'NIL)
'NIL)))`,
`(DEFUN RASSOC-EQ (X ALIST)
(IF (ENDP ALIST)
'NIL
(IF (EQ X (CDR (CAR ALIST)))
(CAR ALIST)
(RASSOC-EQ X (CDR ALIST)))))`
];
| {
"pile_set_name": "Github"
} |
/*=========================================================================
Program: Advanced Normalization Tools
Copyright (c) ConsortiumOfANTS. All rights reserved.
See accompanying COPYING.txt or
https://github.com/stnava/ANTs/blob/master/ANTSCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "antsUtilities.h"
#include <algorithm>
#include "ReadWriteData.h"
#include "itkDisplacementFieldToBSplineImageFilter.h"
#include "itkGaussianOperator.h"
#include "itkImage.h"
#include "itkImageDuplicator.h"
#include "itkTimeProbe.h"
#include "itkImageRegionIteratorWithIndex.h"
#include "itkImageRegionConstIteratorWithIndex.h"
#include "itkVectorNeighborhoodOperatorImageFilter.h"
namespace ants
{
template <unsigned int ImageDimension>
int SmoothDisplacementField( int argc, char *argv[] )
{
using RealType = float;
using RealImageType = itk::Image<RealType, ImageDimension>;
using VectorType = itk::Vector<RealType, ImageDimension>;
using DisplacementFieldType = itk::Image<VectorType, ImageDimension>;
typename DisplacementFieldType::Pointer field = nullptr;
ReadImage<DisplacementFieldType>( field, argv[2] );
typename DisplacementFieldType::Pointer smoothField = DisplacementFieldType::New();
float elapsedTime = 0.0;
std::vector<float> var = ConvertVector<float>( std::string( argv[4] ) );
if( var.size() == 1 )
{
float variance = var[0];
using GaussianSmoothingOperatorType = itk::GaussianOperator<float, ImageDimension>;
using GaussianSmoothingSmootherType = itk::VectorNeighborhoodOperatorImageFilter<DisplacementFieldType, DisplacementFieldType>;
GaussianSmoothingOperatorType gaussianSmoothingOperator;
using DuplicatorType = itk::ImageDuplicator<DisplacementFieldType>;
typename DuplicatorType::Pointer duplicator = DuplicatorType::New();
duplicator->SetInputImage( field );
duplicator->Update();
smoothField = duplicator->GetOutput();
itk::TimeProbe timer;
timer.Start();
typename GaussianSmoothingSmootherType::Pointer smoother = GaussianSmoothingSmootherType::New();
for( unsigned int dimension = 0; dimension < ImageDimension; ++dimension )
{
// smooth along this dimension
gaussianSmoothingOperator.SetDirection( dimension );
gaussianSmoothingOperator.SetVariance( variance );
gaussianSmoothingOperator.SetMaximumError( 0.001 );
gaussianSmoothingOperator.SetMaximumKernelWidth( smoothField->GetRequestedRegion().GetSize()[dimension] );
gaussianSmoothingOperator.CreateDirectional();
// todo: make sure we only smooth within the buffered region
smoother->SetOperator( gaussianSmoothingOperator );
smoother->SetInput( smoothField );
smoother->Update();
smoothField = smoother->GetOutput();
smoothField->Update();
smoothField->DisconnectPipeline();
}
const VectorType zeroVector( 0.0 );
//make sure boundary does not move
float weight1 = itk::NumericTraits<float>::OneValue();
if( variance < static_cast<float>( 0.5 ) )
{
weight1 = itk::NumericTraits<float>::OneValue() - itk::NumericTraits<float>::OneValue() * ( variance / static_cast<float>( 0.5 ) );
}
float weight2 = itk::NumericTraits<float>::OneValue() - weight1;
const typename DisplacementFieldType::RegionType region = field->GetLargestPossibleRegion();
const typename DisplacementFieldType::SizeType size = region.GetSize();
const typename DisplacementFieldType::IndexType startIndex = region.GetIndex();
itk::ImageRegionConstIteratorWithIndex<DisplacementFieldType> fieldIt( field, field->GetLargestPossibleRegion() );
itk::ImageRegionIteratorWithIndex<DisplacementFieldType> smoothedFieldIt( smoothField, smoothField->GetLargestPossibleRegion() );
for( fieldIt.GoToBegin(), smoothedFieldIt.GoToBegin(); !fieldIt.IsAtEnd(); ++fieldIt, ++smoothedFieldIt )
{
typename DisplacementFieldType::IndexType index = fieldIt.GetIndex();
bool isOnBoundary = false;
for ( unsigned int dimension = 0; dimension < ImageDimension; ++dimension )
{
if( index[dimension] == startIndex[dimension] || index[dimension] == static_cast<int>( size[dimension] ) - startIndex[dimension] - 1 )
{
isOnBoundary = true;
break;
}
}
if( isOnBoundary )
{
smoothedFieldIt.Set( zeroVector );
}
else
{
smoothedFieldIt.Set( smoothedFieldIt.Get() * weight1 + fieldIt.Get() * weight2 );
}
}
timer.Stop();
elapsedTime = timer.GetMean();
}
else if( var.size() == ImageDimension )
{
using BSplineFilterType = itk::DisplacementFieldToBSplineImageFilter<DisplacementFieldType>;
unsigned int numberOfLevels = 1;
if( argc > 5 )
{
numberOfLevels = std::stoi( argv[5] );
}
unsigned int splineOrder = 3;
if( argc > 6 )
{
splineOrder = std::stoi( argv[6] );
}
typename BSplineFilterType::ArrayType ncps;
for( unsigned int d = 0; d < ImageDimension; d++ )
{
ncps[d] = var[d] + splineOrder;
}
typename BSplineFilterType::Pointer bspliner = BSplineFilterType::New();
bspliner->SetDisplacementField( field );
bspliner->SetBSplineDomainFromImage( field );
bspliner->SetNumberOfControlPoints( ncps );
bspliner->SetSplineOrder( splineOrder );
bspliner->SetNumberOfFittingLevels( numberOfLevels );
bspliner->SetEnforceStationaryBoundary( true );
bspliner->SetEstimateInverse( false );
if( argc > 7 )
{
bspliner->SetEstimateInverse( static_cast<bool>( std::stoi( argv[7] ) ) );
}
if( argc > 8 )
{
typename BSplineFilterType::RealImageType::Pointer confidenceImage = nullptr;
ReadImage<typename BSplineFilterType::RealImageType>( confidenceImage, argv[8] );
bspliner->SetConfidenceImage( confidenceImage );
}
itk::TimeProbe timer;
timer.Start();
bspliner->Update();
timer.Stop();
elapsedTime = timer.GetMean();
smoothField = bspliner->GetOutput();
smoothField->DisconnectPipeline();
}
else
{
std::cerr << "Error: unexpected variance format." << std::endl;
return EXIT_FAILURE;
}
typename RealImageType::Pointer rmseImage = RealImageType::New();
rmseImage->SetOrigin( field->GetOrigin() );
rmseImage->SetDirection( field->GetDirection() );
rmseImage->SetSpacing( field->GetSpacing() );
rmseImage->SetRegions( field->GetLargestPossibleRegion() );
rmseImage->Allocate();
rmseImage->FillBuffer( 0.0 );
itk::ImageRegionConstIterator<DisplacementFieldType> fieldIt( field, field->GetLargestPossibleRegion() );
itk::ImageRegionConstIterator<DisplacementFieldType> smoothedFieldIt( smoothField, smoothField->GetLargestPossibleRegion() );
itk::ImageRegionIterator<RealImageType> ItR( rmseImage, rmseImage->GetLargestPossibleRegion() );
float rmse = 0.0;
vnl_vector<float> rmse_comp( 2 );
rmse_comp.fill( 0.0 );
float N = 0.0;
for( fieldIt.GoToBegin(), smoothedFieldIt.GoToBegin(), ItR.GoToBegin(); !fieldIt.IsAtEnd(); ++fieldIt, ++smoothedFieldIt, ++ItR )
{
ItR.Set( ( fieldIt.Get() - smoothedFieldIt.Get() ).GetSquaredNorm() );
for( unsigned int d = 0; d < ImageDimension; d++ )
{
rmse_comp[d] += itk::Math::sqr ( fieldIt.Get()[d] - smoothedFieldIt.Get()[d] );
}
rmse += static_cast<float>( ( fieldIt.Get() - smoothedFieldIt.Get() ).GetSquaredNorm() );
N += itk::NumericTraits<float>::OneValue();
}
rmse = std::sqrt( rmse / N );
std::cout << "Elapsed time: " << elapsedTime << std::endl;
std::cout << "RMSE = " << rmse << std::endl;
for( unsigned int d = 0; d < ImageDimension; d++ )
{
std::cout << " rmse[" << d << "] = " << std::sqrt( rmse_comp[d] / N ) << std::endl;
}
WriteImage<DisplacementFieldType>( smoothField, argv[3] );
return EXIT_SUCCESS;
}
// entry point for the library; parameter 'args' is equivalent to 'argv' in (argc,argv) of commandline parameters to
// 'main()'
int SmoothDisplacementField( std::vector<std::string> args, std::ostream* /*out_stream = nullptr */ )
{
// put the arguments coming in as 'args' into standard (argc,argv) format;
// 'args' doesn't have the command name as first, argument, so add it manually;
// 'args' may have adjacent arguments concatenated into one argument,
// which the parser should handle
args.insert( args.begin(), "SmoothDisplacementField" );
int argc = args.size();
char* * argv = new char *[args.size() + 1];
for( unsigned int i = 0; i < args.size(); ++i )
{
// allocate space for the string plus a null character
argv[i] = new char[args[i].length() + 1];
std::strncpy( argv[i], args[i].c_str(), args[i].length() );
// place the null character in the end
argv[i][args[i].length()] = '\0';
}
argv[argc] = nullptr;
// class to automatically cleanup argv upon destruction
class Cleanup_argv
{
public:
Cleanup_argv( char* * argv_, int argc_plus_one_ ) : argv( argv_ ), argc_plus_one( argc_plus_one_ )
{
}
~Cleanup_argv()
{
for( unsigned int i = 0; i < argc_plus_one; ++i )
{
delete[] argv[i];
}
delete[] argv;
}
private:
char* * argv;
unsigned int argc_plus_one;
};
Cleanup_argv cleanup_argv( argv, argc + 1 );
// antscout->set_stream( out_stream );
if ( argc < 5 )
{
std::cout << argv[0] << " imageDimension inputField outputField variance_or_mesh_size_base_level "
<< "[numberOfevels=1] [splineOrder=3] [estimateInverse=0] [confidenceImage]" << std::endl;
return EXIT_FAILURE;
}
switch( std::stoi( argv[1] ) )
{
case 2:
return SmoothDisplacementField<2>( argc, argv );
break;
case 3:
return SmoothDisplacementField<3>( argc, argv );
break;
case 4:
return SmoothDisplacementField<4>( argc, argv );
break;
default:
std::cerr << "Unsupported dimension" << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
} // namespace ants
| {
"pile_set_name": "Github"
} |
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global['@scoped/npm-package'] = global['@scoped/npm-package'] || {}));
}(this, (function (exports) { 'use strict';
let foo = 'foo';
exports.foo = foo;
Object.defineProperty(exports, '__esModule', { value: true });
})));
| {
"pile_set_name": "Github"
} |
<div class="form-group has-feedback row">
{!! Form::label('typeId', trans('laravelblocker::laravelblocker.forms.blockedTypeLabel'), array('class' => 'col-md-3 control-label')); !!}
<div class="col-md-9">
<div class="input-group">
<select class="{{ $errors->has('typeId') ? 'custom-select form-control is-invalid ' : 'custom-select form-control' }}" name="typeId" id="typeId" >
<option value="">
{{ trans('laravelblocker::laravelblocker.forms.blockedTypeSelect') }}
</option>
@if($blockedTypes)
@foreach($blockedTypes as $blockedType)
<option value="{{ $blockedType->id }}" data-type="{{ $blockedType->slug }}" @isset($item) {{ $item->typeId == $blockedType->id ? 'selected="selected"' : '' }} @endisset >
{{ $blockedType->name }}
</option>
@endforeach
@endif
</select>
<div class="input-group-append">
<label class="input-group-text" for="typeId">
<i class="fa fas fa-fw fa-shield" aria-hidden="true"></i>
</label>
</div>
</div>
@if ($errors->has('typeId'))
<span class="help-block">
<strong>{{ $errors->first('typeId') }}</strong>
</span>
@endif
</div>
</div>
| {
"pile_set_name": "Github"
} |
<instance xmlns="urn:cesnet:mod3">
<llist1 xmlns:pref="urn:cesnet:mod3">/pref:cont/pref:l1</llist1>
</instance>
| {
"pile_set_name": "Github"
} |
module.exports.validateBenchmarkWeights = (req, res, next) => {
const benchmarkWeights = req.body.benchmark_weights;
if (benchmarkWeights){
const p95Percentage = benchmarkWeights.percentile_ninety_five.percentage;
const p50Percentage = benchmarkWeights.percentile_fifty.percentage;
const serverErrorsPercentage = benchmarkWeights.server_errors_ratio.percentage;
const clientErrorsPercentage = benchmarkWeights.client_errors_ratio.percentage;
const rpsPercentage = benchmarkWeights.rps.percentage;
const percentageSum = p95Percentage + p50Percentage + serverErrorsPercentage + clientErrorsPercentage + rpsPercentage;
if (percentageSum !== 100){
const error = new Error('Benchmark weights needs to sum up to 100%');
error.statusCode = 422;
return next(error);
}
}
return next();
};
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<data-map xmlns="http://cayenne.apache.org/schema/10/modelMap"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://cayenne.apache.org/schema/10/modelMap http://cayenne.apache.org/schema/10/modelMap.xsd"
project-version="10">
<property name="defaultPackage" value="org.apache.cayenne.testdo.oneway"/>
<db-entity name="oneway_table1">
<db-attribute name="ID" type="INTEGER" isPrimaryKey="true" isMandatory="true"/>
</db-entity>
<db-entity name="oneway_table2">
<db-attribute name="ID" type="INTEGER" isPrimaryKey="true" isMandatory="true"/>
<db-attribute name="TABLE1_ID" type="INTEGER"/>
</db-entity>
<db-entity name="oneway_table3">
<db-attribute name="ID" type="INTEGER" isPrimaryKey="true" isMandatory="true"/>
</db-entity>
<db-entity name="oneway_table4">
<db-attribute name="ID" type="INTEGER" isPrimaryKey="true" isMandatory="true"/>
<db-attribute name="TABLE3_ID" type="INTEGER"/>
</db-entity>
<obj-entity name="OnewayTable1" className="org.apache.cayenne.testdo.oneway.OnewayTable1" dbEntityName="oneway_table1"/>
<obj-entity name="OnewayTable2" className="org.apache.cayenne.testdo.oneway.OnewayTable2" dbEntityName="oneway_table2">
<obj-attribute name="id" type="java.lang.Integer" db-attribute-path="ID"/>
</obj-entity>
<obj-entity name="OnewayTable3" className="org.apache.cayenne.testdo.oneway.OnewayTable3" dbEntityName="oneway_table3"/>
<obj-entity name="OnewayTable4" className="org.apache.cayenne.testdo.oneway.OnewayTable4" dbEntityName="oneway_table4"/>
<db-relationship name="toOneOneWayDb" source="oneway_table2" target="oneway_table1">
<db-attribute-pair source="TABLE1_ID" target="ID"/>
</db-relationship>
<db-relationship name="toManyOneWayDb" source="oneway_table3" target="oneway_table4" toMany="true">
<db-attribute-pair source="ID" target="TABLE3_ID"/>
</db-relationship>
<obj-relationship name="toOneOneWayDb" source="OnewayTable2" target="OnewayTable1" deleteRule="Nullify" db-relationship-path="toOneOneWayDb"/>
<obj-relationship name="toManyOneWayDb" source="OnewayTable3" target="OnewayTable4" deleteRule="Nullify" db-relationship-path="toManyOneWayDb"/>
</data-map>
| {
"pile_set_name": "Github"
} |
//-----------------------------------------------------------------------
// <copyright file="FanInShape.cs" company="Akka.NET Project">
// Copyright (C) 2009-2020 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2020 .NET Foundation <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Linq;
using System.Collections.Immutable;
namespace Akka.Streams
{
/// <summary>
/// TBD
/// </summary>
/// <typeparam name="T0">TBD</typeparam>
/// <typeparam name="T1">TBD</typeparam>
/// <typeparam name="TOut">TBD</typeparam>
public class FanInShapeN<T0, T1, TOut> : FanInShape<TOut>
{
/// <summary>
/// TBD
/// </summary>
public readonly int N;
/// <summary>
/// TBD
/// </summary>
public readonly Inlet<T0> In0;
/// <summary>
/// TBD
/// </summary>
public readonly ImmutableArray<Inlet<T1>> In1s;
/// <summary>
/// TBD
/// </summary>
/// <param name="n">TBD</param>
/// <param name="init">TBD</param>
public FanInShapeN(int n, IInit init) : base(init)
{
N = n;
In0 = NewInlet<T0>("in0");
var builder = ImmutableArray.CreateBuilder<Inlet<T1>>(n);
for (int i = 0; i < n; i++) builder.Add(new Inlet<T1>("in" + i));
In1s = builder.ToImmutable();
}
/// <summary>
/// TBD
/// </summary>
/// <param name="n">TBD</param>
public FanInShapeN(int n) : this(n, new InitName("FanInShape1N")) { }
/// <summary>
/// TBD
/// </summary>
/// <param name="n">TBD</param>
/// <param name="name">TBD</param>
public FanInShapeN(int n, string name) : this(n, new InitName(name)) { }
/// <summary>
/// TBD
/// </summary>
/// <param name="outlet">TBD</param>
/// <param name="in0">TBD</param>
/// <param name="inlets">TBD</param>
public FanInShapeN(Outlet<TOut> outlet, Inlet<T0> in0, params Inlet<T1>[] inlets) : this(inlets.Length, new InitPorts(outlet, new Inlet[]{in0}.Concat(inlets))) { }
/// <summary>
/// TBD
/// </summary>
/// <param name="n">TBD</param>
/// <exception cref="ArgumentException">
/// This exception is thrown when the specified <paramref name="n" /> is less than or equal to zero.
/// </exception>
/// <returns>TBD</returns>
public Inlet<T1> In(int n)
{
if (n <= 0) throw new ArgumentException("n must be > 0", nameof(n));
return In1s[n-1];
}
/// <summary>
/// TBD
/// </summary>
/// <param name="init">TBD</param>
/// <returns>TBD</returns>
protected override FanInShape<TOut> Construct(IInit init)
{
return new FanInShapeN<T0, T1, TOut>(N, init);
}
}
/// <summary>
/// TBD
/// </summary>
/// <typeparam name="T0">TBD</typeparam>
/// <typeparam name="T1">TBD</typeparam>
/// <typeparam name="TOut">TBD</typeparam>
public class FanInShape<T0, T1, TOut> : FanInShape<TOut>
{
/// <summary>
/// TBD
/// </summary>
public readonly Inlet<T0> In0;
/// <summary>
/// TBD
/// </summary>
public readonly Inlet<T1> In1;
/// <summary>
/// TBD
/// </summary>
/// <param name="init">TBD</param>
public FanInShape(IInit init) : base(init)
{
In0 = NewInlet<T0>("in0");
In1 = NewInlet<T1>("in1");
}
/// <summary>
/// TBD
/// </summary>
/// <param name="name">TBD</param>
public FanInShape(string name) : this(new InitName(name)) { }
/// <summary>
/// TBD
/// </summary>
/// <param name="outlet">TBD</param>
/// <param name="in0">TBD</param>
/// <param name="in1">TBD</param>
/// <returns>TBD</returns>
public FanInShape(Outlet<TOut> outlet, Inlet<T0> in0, Inlet<T1> in1)
: this(new InitPorts(outlet, new Inlet[] { in0, in1 })) { }
/// <summary>
/// TBD
/// </summary>
/// <param name="init">TBD</param>
/// <returns>TBD</returns>
protected override FanInShape<TOut> Construct(IInit init)
{
return new FanInShape<T0, T1, TOut>(init);
}
}
/// <summary>
/// TBD
/// </summary>
/// <typeparam name="T0">TBD</typeparam>
/// <typeparam name="T1">TBD</typeparam>
/// <typeparam name="T2">TBD</typeparam>
/// <typeparam name="TOut">TBD</typeparam>
public class FanInShape<T0, T1, T2, TOut> : FanInShape<TOut>
{
/// <summary>
/// TBD
/// </summary>
public readonly Inlet<T0> In0;
/// <summary>
/// TBD
/// </summary>
public readonly Inlet<T1> In1;
/// <summary>
/// TBD
/// </summary>
public readonly Inlet<T2> In2;
/// <summary>
/// TBD
/// </summary>
/// <param name="init">TBD</param>
public FanInShape(IInit init) : base(init)
{
In0 = NewInlet<T0>("in0");
In1 = NewInlet<T1>("in1");
In2 = NewInlet<T2>("in2");
}
/// <summary>
/// TBD
/// </summary>
/// <param name="name">TBD</param>
public FanInShape(string name) : this(new InitName(name)) { }
/// <summary>
/// TBD
/// </summary>
/// <param name="outlet">TBD</param>
/// <param name="in0">TBD</param>
/// <param name="in1">TBD</param>
/// <param name="in2">TBD</param>
/// <returns>TBD</returns>
public FanInShape(Outlet<TOut> outlet, Inlet<T0> in0, Inlet<T1> in1, Inlet<T2> in2)
: this(new InitPorts(outlet, new Inlet[] { in0, in1, in2 })) { }
/// <summary>
/// TBD
/// </summary>
/// <param name="init">TBD</param>
/// <returns>TBD</returns>
protected override FanInShape<TOut> Construct(IInit init)
{
return new FanInShape<T0, T1, T2, TOut>(init);
}
}
/// <summary>
/// TBD
/// </summary>
/// <typeparam name="T0">TBD</typeparam>
/// <typeparam name="T1">TBD</typeparam>
/// <typeparam name="T2">TBD</typeparam>
/// <typeparam name="T3">TBD</typeparam>
/// <typeparam name="TOut">TBD</typeparam>
public class FanInShape<T0, T1, T2, T3, TOut> : FanInShape<TOut>
{
/// <summary>
/// TBD
/// </summary>
public readonly Inlet<T0> In0;
/// <summary>
/// TBD
/// </summary>
public readonly Inlet<T1> In1;
/// <summary>
/// TBD
/// </summary>
public readonly Inlet<T2> In2;
/// <summary>
/// TBD
/// </summary>
public readonly Inlet<T3> In3;
/// <summary>
/// TBD
/// </summary>
/// <param name="init">TBD</param>
public FanInShape(IInit init) : base(init)
{
In0 = NewInlet<T0>("in0");
In1 = NewInlet<T1>("in1");
In2 = NewInlet<T2>("in2");
In3 = NewInlet<T3>("in3");
}
/// <summary>
/// TBD
/// </summary>
/// <param name="name">TBD</param>
public FanInShape(string name) : this(new InitName(name)) { }
/// <summary>
/// TBD
/// </summary>
/// <param name="outlet">TBD</param>
/// <param name="in0">TBD</param>
/// <param name="in1">TBD</param>
/// <param name="in2">TBD</param>
/// <param name="in3">TBD</param>
/// <returns>TBD</returns>
public FanInShape(Outlet<TOut> outlet, Inlet<T0> in0, Inlet<T1> in1, Inlet<T2> in2, Inlet<T3> in3)
: this(new InitPorts(outlet, new Inlet[] { in0, in1, in2, in3 })) { }
/// <summary>
/// TBD
/// </summary>
/// <param name="init">TBD</param>
/// <returns>TBD</returns>
protected override FanInShape<TOut> Construct(IInit init)
{
return new FanInShape<T0, T1, T2, T3, TOut>(init);
}
}
/// <summary>
/// TBD
/// </summary>
/// <typeparam name="T0">TBD</typeparam>
/// <typeparam name="T1">TBD</typeparam>
/// <typeparam name="T2">TBD</typeparam>
/// <typeparam name="T3">TBD</typeparam>
/// <typeparam name="T4">TBD</typeparam>
/// <typeparam name="TOut">TBD</typeparam>
public class FanInShape<T0, T1, T2, T3, T4, TOut> : FanInShape<TOut>
{
/// <summary>
/// TBD
/// </summary>
public readonly Inlet<T0> In0;
/// <summary>
/// TBD
/// </summary>
public readonly Inlet<T1> In1;
/// <summary>
/// TBD
/// </summary>
public readonly Inlet<T2> In2;
/// <summary>
/// TBD
/// </summary>
public readonly Inlet<T3> In3;
/// <summary>
/// TBD
/// </summary>
public readonly Inlet<T4> In4;
/// <summary>
/// TBD
/// </summary>
/// <param name="init">TBD</param>
public FanInShape(IInit init) : base(init)
{
In0 = NewInlet<T0>("in0");
In1 = NewInlet<T1>("in1");
In2 = NewInlet<T2>("in2");
In3 = NewInlet<T3>("in3");
In4 = NewInlet<T4>("in4");
}
/// <summary>
/// TBD
/// </summary>
/// <param name="name">TBD</param>
public FanInShape(string name) : this(new InitName(name)) { }
/// <summary>
/// TBD
/// </summary>
/// <param name="outlet">TBD</param>
/// <param name="in0">TBD</param>
/// <param name="in1">TBD</param>
/// <param name="in2">TBD</param>
/// <param name="in3">TBD</param>
/// <param name="in4">TBD</param>
/// <returns>TBD</returns>
public FanInShape(Outlet<TOut> outlet, Inlet<T0> in0, Inlet<T1> in1, Inlet<T2> in2, Inlet<T3> in3, Inlet<T4> in4)
: this(new InitPorts(outlet, new Inlet[] { in0, in1, in2, in3, in4 })) { }
/// <summary>
/// TBD
/// </summary>
/// <param name="init">TBD</param>
/// <returns>TBD</returns>
protected override FanInShape<TOut> Construct(IInit init)
{
return new FanInShape<T0, T1, T2, T3, T4, TOut>(init);
}
}
/// <summary>
/// TBD
/// </summary>
/// <typeparam name="T0">TBD</typeparam>
/// <typeparam name="T1">TBD</typeparam>
/// <typeparam name="T2">TBD</typeparam>
/// <typeparam name="T3">TBD</typeparam>
/// <typeparam name="T4">TBD</typeparam>
/// <typeparam name="T5">TBD</typeparam>
/// <typeparam name="TOut">TBD</typeparam>
public class FanInShape<T0, T1, T2, T3, T4, T5, TOut> : FanInShape<TOut>
{
/// <summary>
/// TBD
/// </summary>
public readonly Inlet<T0> In0;
/// <summary>
/// TBD
/// </summary>
public readonly Inlet<T1> In1;
/// <summary>
/// TBD
/// </summary>
public readonly Inlet<T2> In2;
/// <summary>
/// TBD
/// </summary>
public readonly Inlet<T3> In3;
/// <summary>
/// TBD
/// </summary>
public readonly Inlet<T4> In4;
/// <summary>
/// TBD
/// </summary>
public readonly Inlet<T5> In5;
/// <summary>
/// TBD
/// </summary>
/// <param name="init">TBD</param>
public FanInShape(IInit init) : base(init)
{
In0 = NewInlet<T0>("in0");
In1 = NewInlet<T1>("in1");
In2 = NewInlet<T2>("in2");
In3 = NewInlet<T3>("in3");
In4 = NewInlet<T4>("in4");
In5 = NewInlet<T5>("in5");
}
/// <summary>
/// TBD
/// </summary>
/// <param name="name">TBD</param>
public FanInShape(string name) : this(new InitName(name)) { }
/// <summary>
/// TBD
/// </summary>
/// <param name="outlet">TBD</param>
/// <param name="in0">TBD</param>
/// <param name="in1">TBD</param>
/// <param name="in2">TBD</param>
/// <param name="in3">TBD</param>
/// <param name="in4">TBD</param>
/// <param name="in5">TBD</param>
/// <returns>TBD</returns>
public FanInShape(Outlet<TOut> outlet, Inlet<T0> in0, Inlet<T1> in1, Inlet<T2> in2, Inlet<T3> in3, Inlet<T4> in4, Inlet<T5> in5)
: this(new InitPorts(outlet, new Inlet[] { in0, in1, in2, in3, in4, in5 })) { }
/// <summary>
/// TBD
/// </summary>
/// <param name="init">TBD</param>
/// <returns>TBD</returns>
protected override FanInShape<TOut> Construct(IInit init)
{
return new FanInShape<T0, T1, T2, T3, T4, T5, TOut>(init);
}
}
/// <summary>
/// TBD
/// </summary>
/// <typeparam name="T0">TBD</typeparam>
/// <typeparam name="T1">TBD</typeparam>
/// <typeparam name="T2">TBD</typeparam>
/// <typeparam name="T3">TBD</typeparam>
/// <typeparam name="T4">TBD</typeparam>
/// <typeparam name="T5">TBD</typeparam>
/// <typeparam name="T6">TBD</typeparam>
/// <typeparam name="TOut">TBD</typeparam>
public class FanInShape<T0, T1, T2, T3, T4, T5, T6, TOut> : FanInShape<TOut>
{
/// <summary>
/// TBD
/// </summary>
public readonly Inlet<T0> In0;
/// <summary>
/// TBD
/// </summary>
public readonly Inlet<T1> In1;
/// <summary>
/// TBD
/// </summary>
public readonly Inlet<T2> In2;
/// <summary>
/// TBD
/// </summary>
public readonly Inlet<T3> In3;
/// <summary>
/// TBD
/// </summary>
public readonly Inlet<T4> In4;
/// <summary>
/// TBD
/// </summary>
public readonly Inlet<T5> In5;
/// <summary>
/// TBD
/// </summary>
public readonly Inlet<T6> In6;
/// <summary>
/// TBD
/// </summary>
/// <param name="init">TBD</param>
public FanInShape(IInit init) : base(init)
{
In0 = NewInlet<T0>("in0");
In1 = NewInlet<T1>("in1");
In2 = NewInlet<T2>("in2");
In3 = NewInlet<T3>("in3");
In4 = NewInlet<T4>("in4");
In5 = NewInlet<T5>("in5");
In6 = NewInlet<T6>("in6");
}
/// <summary>
/// TBD
/// </summary>
/// <param name="name">TBD</param>
public FanInShape(string name) : this(new InitName(name)) { }
/// <summary>
/// TBD
/// </summary>
/// <param name="outlet">TBD</param>
/// <param name="in0">TBD</param>
/// <param name="in1">TBD</param>
/// <param name="in2">TBD</param>
/// <param name="in3">TBD</param>
/// <param name="in4">TBD</param>
/// <param name="in5">TBD</param>
/// <param name="in6">TBD</param>
/// <returns>TBD</returns>
public FanInShape(Outlet<TOut> outlet, Inlet<T0> in0, Inlet<T1> in1, Inlet<T2> in2, Inlet<T3> in3, Inlet<T4> in4, Inlet<T5> in5, Inlet<T6> in6)
: this(new InitPorts(outlet, new Inlet[] { in0, in1, in2, in3, in4, in5, in6 })) { }
/// <summary>
/// TBD
/// </summary>
/// <param name="init">TBD</param>
/// <returns>TBD</returns>
protected override FanInShape<TOut> Construct(IInit init)
{
return new FanInShape<T0, T1, T2, T3, T4, T5, T6, TOut>(init);
}
}
/// <summary>
/// TBD
/// </summary>
/// <typeparam name="T0">TBD</typeparam>
/// <typeparam name="T1">TBD</typeparam>
/// <typeparam name="T2">TBD</typeparam>
/// <typeparam name="T3">TBD</typeparam>
/// <typeparam name="T4">TBD</typeparam>
/// <typeparam name="T5">TBD</typeparam>
/// <typeparam name="T6">TBD</typeparam>
/// <typeparam name="T7">TBD</typeparam>
/// <typeparam name="TOut">TBD</typeparam>
public class FanInShape<T0, T1, T2, T3, T4, T5, T6, T7, TOut> : FanInShape<TOut>
{
/// <summary>
/// TBD
/// </summary>
public readonly Inlet<T0> In0;
/// <summary>
/// TBD
/// </summary>
public readonly Inlet<T1> In1;
/// <summary>
/// TBD
/// </summary>
public readonly Inlet<T2> In2;
/// <summary>
/// TBD
/// </summary>
public readonly Inlet<T3> In3;
/// <summary>
/// TBD
/// </summary>
public readonly Inlet<T4> In4;
/// <summary>
/// TBD
/// </summary>
public readonly Inlet<T5> In5;
/// <summary>
/// TBD
/// </summary>
public readonly Inlet<T6> In6;
/// <summary>
/// TBD
/// </summary>
public readonly Inlet<T7> In7;
/// <summary>
/// TBD
/// </summary>
/// <param name="init">TBD</param>
public FanInShape(IInit init) : base(init)
{
In0 = NewInlet<T0>("in0");
In1 = NewInlet<T1>("in1");
In2 = NewInlet<T2>("in2");
In3 = NewInlet<T3>("in3");
In4 = NewInlet<T4>("in4");
In5 = NewInlet<T5>("in5");
In6 = NewInlet<T6>("in6");
In7 = NewInlet<T7>("in7");
}
/// <summary>
/// TBD
/// </summary>
/// <param name="name">TBD</param>
public FanInShape(string name) : this(new InitName(name)) { }
/// <summary>
/// TBD
/// </summary>
/// <param name="outlet">TBD</param>
/// <param name="in0">TBD</param>
/// <param name="in1">TBD</param>
/// <param name="in2">TBD</param>
/// <param name="in3">TBD</param>
/// <param name="in4">TBD</param>
/// <param name="in5">TBD</param>
/// <param name="in6">TBD</param>
/// <param name="in7">TBD</param>
/// <returns>TBD</returns>
public FanInShape(Outlet<TOut> outlet, Inlet<T0> in0, Inlet<T1> in1, Inlet<T2> in2, Inlet<T3> in3, Inlet<T4> in4, Inlet<T5> in5, Inlet<T6> in6, Inlet<T7> in7)
: this(new InitPorts(outlet, new Inlet[] { in0, in1, in2, in3, in4, in5, in6, in7 })) { }
/// <summary>
/// TBD
/// </summary>
/// <param name="init">TBD</param>
/// <returns>TBD</returns>
protected override FanInShape<TOut> Construct(IInit init)
{
return new FanInShape<T0, T1, T2, T3, T4, T5, T6, T7, TOut>(init);
}
}
/// <summary>
/// TBD
/// </summary>
/// <typeparam name="T0">TBD</typeparam>
/// <typeparam name="T1">TBD</typeparam>
/// <typeparam name="T2">TBD</typeparam>
/// <typeparam name="T3">TBD</typeparam>
/// <typeparam name="T4">TBD</typeparam>
/// <typeparam name="T5">TBD</typeparam>
/// <typeparam name="T6">TBD</typeparam>
/// <typeparam name="T7">TBD</typeparam>
/// <typeparam name="T8">TBD</typeparam>
/// <typeparam name="TOut">TBD</typeparam>
public class FanInShape<T0, T1, T2, T3, T4, T5, T6, T7, T8, TOut> : FanInShape<TOut>
{
/// <summary>
/// TBD
/// </summary>
public readonly Inlet<T0> In0;
/// <summary>
/// TBD
/// </summary>
public readonly Inlet<T1> In1;
/// <summary>
/// TBD
/// </summary>
public readonly Inlet<T2> In2;
/// <summary>
/// TBD
/// </summary>
public readonly Inlet<T3> In3;
/// <summary>
/// TBD
/// </summary>
public readonly Inlet<T4> In4;
/// <summary>
/// TBD
/// </summary>
public readonly Inlet<T5> In5;
/// <summary>
/// TBD
/// </summary>
public readonly Inlet<T6> In6;
/// <summary>
/// TBD
/// </summary>
public readonly Inlet<T7> In7;
/// <summary>
/// TBD
/// </summary>
public readonly Inlet<T8> In8;
/// <summary>
/// TBD
/// </summary>
/// <param name="init">TBD</param>
public FanInShape(IInit init) : base(init)
{
In0 = NewInlet<T0>("in0");
In1 = NewInlet<T1>("in1");
In2 = NewInlet<T2>("in2");
In3 = NewInlet<T3>("in3");
In4 = NewInlet<T4>("in4");
In5 = NewInlet<T5>("in5");
In6 = NewInlet<T6>("in6");
In7 = NewInlet<T7>("in7");
In8 = NewInlet<T8>("in8");
}
/// <summary>
/// TBD
/// </summary>
/// <param name="name">TBD</param>
public FanInShape(string name) : this(new InitName(name)) { }
/// <summary>
/// TBD
/// </summary>
/// <param name="outlet">TBD</param>
/// <param name="in0">TBD</param>
/// <param name="in1">TBD</param>
/// <param name="in2">TBD</param>
/// <param name="in3">TBD</param>
/// <param name="in4">TBD</param>
/// <param name="in5">TBD</param>
/// <param name="in6">TBD</param>
/// <param name="in7">TBD</param>
/// <param name="in8">TBD</param>
/// <returns>TBD</returns>
public FanInShape(Outlet<TOut> outlet, Inlet<T0> in0, Inlet<T1> in1, Inlet<T2> in2, Inlet<T3> in3, Inlet<T4> in4, Inlet<T5> in5, Inlet<T6> in6, Inlet<T7> in7, Inlet<T8> in8)
: this(new InitPorts(outlet, new Inlet[] { in0, in1, in2, in3, in4, in5, in6, in7, in8 })) { }
/// <summary>
/// TBD
/// </summary>
/// <param name="init">TBD</param>
/// <returns>TBD</returns>
protected override FanInShape<TOut> Construct(IInit init)
{
return new FanInShape<T0, T1, T2, T3, T4, T5, T6, T7, T8, TOut>(init);
}
}
}
| {
"pile_set_name": "Github"
} |
{
"$schema": "http://schema.management.azure.com/schemas/2015-01-01/deploymentParameters.json#",
"contentVersion": "1.0.0.0",
"parameters": {
"input": {
"value": {
"Id": "/providers/Microsoft.Management/managementGroups/landingzones",
"Type": "/providers/Microsoft.Management/managementGroups",
"Name": "landingzones",
"TenantId": "3fc1081d-6105-4e19-b60c-1ec1252cf560",
"DisplayName": "Landing Zones",
"UpdatedTime": "0001-01-01T00:00:00Z",
"UpdatedBy": null,
"ParentId": "/providers/Microsoft.Management/managementGroups/contoso",
"ParentName": "contoso",
"ParentDisplayName": "contoso",
"Children": [
{
"Type": "/providers/Microsoft.Management/managementGroups",
"Id": "/providers/Microsoft.Management/managementGroups/corp",
"Name": "corp",
"DisplayName": "corp",
"Children": [
{
"Type": "/subscriptions",
"Id": "/subscriptions/2f68ca09-59d9-4ab5-ad11-c54872bfa28d",
"Name": "2f68ca09-59d9-4ab5-ad11-c54872bfa28d",
"DisplayName": "bu1-neu-msx1",
"Children": null
},
{
"Type": "/subscriptions",
"Id": "/subscriptions/673d8549-7629-4659-a292-464d1616afd4",
"Name": "673d8549-7629-4659-a292-464d1616afd4",
"DisplayName": "bu1-weu-msx3",
"Children": null
},
{
"Type": "/subscriptions",
"Id": "/subscriptions/558bf93d-0c7b-4436-82ab-a7ed6fda34aa",
"Name": "558bf93d-0c7b-4436-82ab-a7ed6fda34aa",
"DisplayName": "bu1-neu-msx2",
"Children": null
},
{
"Type": "/subscriptions",
"Id": "/subscriptions/61c7653d-4d0f-4729-a0d2-c8138cfa1434",
"Name": "61c7653d-4d0f-4729-a0d2-c8138cfa1434",
"DisplayName": "bu1-ncus-msx4",
"Children": null
}
]
},
{
"Type": "/providers/Microsoft.Management/managementGroups",
"Id": "/providers/Microsoft.Management/managementGroups/online",
"Name": "online",
"DisplayName": "online",
"Children": [
{
"Type": "/subscriptions",
"Id": "/subscriptions/6d257533-dec9-4f23-92a1-a8321abb5f44",
"Name": "6d257533-dec9-4f23-92a1-a8321abb5f44",
"DisplayName": "bu1-neu-www1",
"Children": null
},
{
"Type": "/subscriptions",
"Id": "/subscriptions/8353a044-7113-40f5-89ea-19a083b77c53",
"Name": "8353a044-7113-40f5-89ea-19a083b77c53",
"DisplayName": "bu1-neu-www2",
"Children": null
}
]
},
{
"Type": "/providers/Microsoft.Management/managementGroups",
"Id": "/providers/Microsoft.Management/managementGroups/sap",
"Name": "sap",
"DisplayName": "sap",
"Children": null
}
],
"properties": {
"policyDefinitions": [],
"policySetDefinitions": [],
"policyAssignments": [
{
"Identity": {
"type": "SystemAssigned"
},
"Location": "northeurope",
"Name": "Deny-PublicEndpoints",
"Properties": {
"Description": null,
"DisplayName": "Deny Public Endpoints for PaaS Services",
"NotScopes": [
"/subscriptions/2f68ca09-59d9-4ab5-ad11-c54872bfa28d/resourceGroups/mytestresourcegroup"
],
"Parameters": {},
"PolicyDefinitionId": "<replace-me>",
"Scope": "<replace-me>"
},
"ResourceType": "Microsoft.Authorization/policyAssignments"
},
{
"Identity": {
"type": "SystemAssigned"
},
"Location": "northeurope",
"Name": "Deploy-VM-Backup",
"Properties": {
"Description": null,
"DisplayName": "Deploy-AzureBackup-on-VMs",
"NotScopes": null,
"Parameters": {},
"PolicyDefinitionId": "<replace-me>",
"Scope": "<replace-me>"
},
"ResourceType": "Microsoft.Authorization/policyAssignments"
},
{
"Identity": {
"type": "SystemAssigned"
},
"Location": "northeurope",
"Name": "Deploy-vNet",
"Properties": {
"Description": null,
"DisplayName": "Deploy vNet",
"NotScopes": null,
"Parameters": {
"ipam": {
"value": [
{
"name": "bu1-weu-msx3-vNet",
"location": "westeurope",
"virtualNetworks": {
"properties": {
"addressSpace": {
"addressPrefixes": [
"10.51.217.0/24"
]
}
}
},
"networkSecurityGroups": {
"properties": {
"securityRules": []
}
},
"routeTables": {
"properties": {
"routes": []
}
},
"hubVirtualNetworkConnection": {
"vWanVhubResourceId": "/subscriptions/99c2838f-a548-4884-a6e2-38c1f8fb4c0b/resourceGroups/contoso-global-vwan/providers/Microsoft.Network/virtualHubs/contoso-vhub-weu",
"properties": {
"allowHubToRemoteVnetTransit": true,
"allowRemoteVnetToUseHubVnetGateways": false,
"enableInternetSecurity": true
}
}
}
]
}
},
"PolicyDefinitionId": "<replace-me>",
"Scope": "<replace-me>"
},
"ResourceType": "Microsoft.Authorization/policyAssignments"
}
],
"roleDefinitions": [],
"roleAssignments": []
}
}
}
}
}
| {
"pile_set_name": "Github"
} |
<script type="text/javascript" charset="utf-8">
var is_ssl = ("https:" == document.location.protocol);
var asset_host = is_ssl ? "https://s3.amazonaws.com/getsatisfaction.com/" : "http://s3.amazonaws.com/getsatisfaction.com/";
document.write(unescape("%3Cscript src='" + asset_host + "javascripts/feedback-v2.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript" charset="utf-8">
var feedback_widget_options = {};
feedback_widget_options.display = "overlay";
feedback_widget_options.company = "cuke4ninja";
feedback_widget_options.placement = "right";
feedback_widget_options.color = "#222";
feedback_widget_options.style = "idea";
var feedback_widget = new GSFN.feedback_widget(feedback_widget_options);
</script>
<div id="footer">
<p>
<br/><br/><br/>This book is free but still under copyright. © <a href="http://deflorinier.blogspot.com/">David de Florinier</a> and <a href="http://gojko.net">Gojko Adzic</a> 2010. See <a href="/terms.html">Terms of use</a>. All Rights Reserved. Design by Annette de Florinier.
</p>
</div>
</td></tr></table>
</body>
| {
"pile_set_name": "Github"
} |
begin
require "rubygems"
require "bundler"
rescue LoadError
raise "Could not load the bundler gem. Install it with `gem install bundler`."
end
if Gem::Version.new(Bundler::VERSION) <= Gem::Version.new("0.9.24")
raise RuntimeError, "Your bundler version is too old for Rails 2.3." +
"Run `gem install bundler` to upgrade."
end
begin
# Set up load paths for all bundled gems
ENV["BUNDLE_GEMFILE"] = File.expand_path("../../Gemfile", __FILE__)
Bundler.setup
rescue Bundler::GemNotFound
raise RuntimeError, "Bundler couldn't find some gems." +
"Did you run `bundle install`?"
end | {
"pile_set_name": "Github"
} |
// Copyright 2016 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build darwin dragonfly freebsd linux netbsd openbsd solaris
// +build !gccgo,!ppc64le,!ppc64
package unix
import "syscall"
func Syscall(trap, a1, a2, a3 uintptr) (r1, r2 uintptr, err syscall.Errno)
func Syscall6(trap, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err syscall.Errno)
func RawSyscall(trap, a1, a2, a3 uintptr) (r1, r2 uintptr, err syscall.Errno)
func RawSyscall6(trap, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err syscall.Errno)
| {
"pile_set_name": "Github"
} |
# Contributing
We love contributions and will happily review any pull requests. Please make sure to follow the instructions below!
## Getting Started
**Make sure to fork the repo first.**
Clone your forked repo.
```
$ git clone [email protected]:<your-username>/vuetron.git
$ cd vuetron
```
Install dependencies
```
$ npm i
```
## Code Style
Here on team Vuetron we strictly follow and enforce the [Javascript Semistandard](https://github.com/flet/semistandard) style. Since we don't want to lose our beautiful badge in our README, please do the same for any pull requests you submit.
Repeat offenders will be added to the board of shame! (just kidding - or are we?) | {
"pile_set_name": "Github"
} |
package autoscale
import (
"fmt"
"time"
sendMetrics "github.com/armon/go-metrics"
nomad "github.com/hashicorp/nomad/api"
"github.com/jrasell/sherpa/pkg/autoscale/metrics"
"github.com/jrasell/sherpa/pkg/policy"
"github.com/jrasell/sherpa/pkg/scale"
"github.com/jrasell/sherpa/pkg/state"
"github.com/rs/zerolog"
)
type autoscaleEvaluation struct {
nomad *nomad.Client
metricProvider map[policy.MetricsProvider]metrics.Provider
scaler scale.Scale
// policies are the job group policies that will be evaluated during this run.
policies map[string]*policy.GroupScalingPolicy
// jobID is the Nomad job which is under evaluation.
jobID string
// time is the unix nano time indicating when this scaling evaluation was triggered.
time int64
// log has the jobID context to save repeating this effort.
log zerolog.Logger
}
func (ae *autoscaleEvaluation) evaluateJob() {
ae.log.Debug().Msg("triggering autoscaling job evaluation")
defer sendMetrics.MeasureSince([]string{"autoscale", ae.jobID, "evaluation"}, time.Now())
externalDecision := make(map[string]*scalingDecision)
nomadDecision := make(map[string]*scalingDecision)
// We need to check to see whether the the job policies contain a group which is using Nomad
// checks. This dictates whether we run the initial gatherNomadMetrics function and then
// trigger the Nomad evaluation.
var nomadCheck bool
for _, p := range ae.policies {
if p.NomadChecksEnabled() {
nomadCheck = true
break
}
}
var (
nomadMetricData *nomadGatheredMetrics
err error
)
// If the job policy contains groups which rely on Nomad data, we should collect this now. It
// is most efficient to collect this data on a per job basis rather than per group. If we get
// an error when performing this, log it and continue. It is possible external checks are also
// in place and working; we can nil check the nomadMetricData to skip Nomad checks during this
// evaluation.
if nomadCheck {
nomadMetricData, err = ae.gatherNomadMetrics()
if err != nil {
ae.log.Error().Err(err).Msg("failed to collect Nomad metrics, skipping Nomad based checks")
}
}
// Iterate over the group policies for the job currently under evaluation.
for group, p := range ae.policies {
// Setup a start time so we can measure how long an individual job group evaluation takes.
start := time.Now()
ae.log.Debug().Str("group", group).Msg("triggering autoscaling job group evaluation")
// If the group policy has Nomad checks enabled, and we managed to successfully get the
// Nomad metric data, perform the evaluation.
if p.NomadChecksEnabled() && nomadMetricData != nil {
if nomadDec := ae.evaluateNomadJobMetrics(group, p, nomadMetricData); nomadDec != nil {
nomadDecision[group] = nomadDec
}
}
// If the group has external checks, perform these and ensure the decision if not nil,
// before adding this to the decision tree.
if p.ExternalChecks != nil {
if extDec := ae.calculateExternalScalingDecision(group, p); extDec != nil {
externalDecision[group] = extDec
}
}
// This iteration has ended, so record the Sherpa metric.
sendMetrics.MeasureSince([]string{"autoscale", ae.jobID, group, "evaluation"}, start)
}
ae.evaluateDecisions(nomadDecision, externalDecision)
}
func (ae *autoscaleEvaluation) evaluateDecisions(nomadDecision, externalDecision map[string]*scalingDecision) {
// Exit quickly if there are now scaling decisions to process.
if len(nomadDecision) == 0 && len(externalDecision) == 0 {
ae.log.Info().Msg("scaling evaluation completed and no scaling required")
return
}
var finalDecision map[string]*scalingDecision
// Perform checks to see whether either the Nomad checks or the external checks have deemed
// scaling to be required. A single decision here means we can easily move onto building the
// scaling request.
if len(nomadDecision) == 0 && len(externalDecision) > 0 {
ae.log.Debug().Msg("scaling evaluation completed, handling scaling request based on external checks")
finalDecision = externalDecision
}
if len(nomadDecision) > 0 && len(externalDecision) == 0 {
ae.log.Debug().Msg("scaling evaluation completed, handling scaling request based on Nomad checks")
finalDecision = nomadDecision
}
// If both Nomad and external sources believe the job needs scaling, we need to ensure that
// they are not in different directions. If they are out will always trump in as we want to
// ensure we can handle load.
if len(nomadDecision) > 0 && len(externalDecision) > 0 {
ae.log.Debug().
Msg("scaling evaluation completed, handling scaling request based on Nomad and external checks")
finalDecision = ae.buildSingleDecision(nomadDecision, externalDecision)
}
// Build the scaling request to send to the scaler backend.
scaleReq := ae.buildScalingReq(finalDecision)
// If group scaling requests have been added to the array for the job that is currently being
// checked, trigger a scaling event. Run this in a routine as from this point there is nothing
// we can do.
if len(scaleReq) > 0 {
go ae.triggerScaling(scaleReq)
}
}
// triggerScaling is used to trigger the scaling of a job based on one or more group changes as
// as result of the scaling evaluation.
func (ae *autoscaleEvaluation) triggerScaling(req []*scale.GroupReq) {
resp, _, err := ae.scaler.Trigger(ae.jobID, req, state.SourceInternalAutoscaler)
if err != nil {
ae.log.Error().Err(err).Msg("failed to trigger scaling of job")
sendTriggerErrorMetrics(ae.jobID)
}
if resp != nil {
ae.log.Info().
Str("id", resp.ID.String()).
Str("evaluation-id", resp.EvaluationID).
Msg("successfully triggered autoscaling of job")
sendTriggerSuccessMetrics(ae.jobID)
}
}
// buildScalingReq takes the scaling decisions for the job under evaluation, and creates a list of
// group requests to send to the scaler backend.
func (ae *autoscaleEvaluation) buildScalingReq(dec map[string]*scalingDecision) []*scale.GroupReq {
var scaleReq []*scale.GroupReq // nolint:prealloc
for group, decision := range dec {
// Iterate over the resource metrics which have broken their thresholds and ensure these
// are added to the submission meta.
meta := make(map[string]string)
for name, metric := range decision.metrics {
updateAutoscaleMeta(name, metric.value, metric.threshold, meta)
}
// Build the job group scaling request.
req := &scale.GroupReq{
Direction: decision.direction,
Count: decision.count,
GroupName: group,
GroupScalingPolicy: ae.policies[group],
Time: ae.time,
Meta: meta,
}
scaleReq = append(scaleReq, req)
ae.log.Debug().
Str("group", group).
Object("scaling-req", req).
Msg("added group scaling request")
}
return scaleReq
}
// buildSingleDecision takes the decisions from the Nomad and external providers checks, producing
// a single decision per job group.
func (ae *autoscaleEvaluation) buildSingleDecision(nomad, external map[string]*scalingDecision) map[string]*scalingDecision {
final := make(map[string]*scalingDecision)
for group, nomadDec := range nomad {
if extDec, ok := external[group]; ok {
final[group] = ae.buildSingleGroupDecision(nomadDec, extDec)
}
final[group] = nomadDec
}
for group, extDec := range external {
if _, ok := final[group]; !ok {
final[group] = extDec
}
}
return final
}
// buildSingleGroupDecision takes a scalingDecision from Nomad and the external sources, deciding
// the final decision for the job group. In situations where out and in actions are requested, out
// will always win.
func (ae *autoscaleEvaluation) buildSingleGroupDecision(nomad, external *scalingDecision) *scalingDecision {
// If Nomad wishes to scale in, but the external sources want to scale out, the external source
// wins. We return this decision which contains the metric values which failed their threshold
// check.
if nomad.direction == scale.DirectionIn && external.direction == scale.DirectionOut {
return external
}
// If Nomad wishes to scale out, but the external sources want to scale in, the Nomad source
// wins. We return this decision which contains the metric values which failed their threshold
// check.
if nomad.direction == scale.DirectionOut && external.direction == scale.DirectionIn {
return nomad
}
// If both Nomad and external sources desire the same action, combine the metrics which failed
// their checks so we can provide this detail to the user.
if nomad.direction == scale.DirectionIn && external.direction == scale.DirectionIn ||
nomad.direction == scale.DirectionOut && external.direction == scale.DirectionOut {
for key, metric := range external.metrics {
nomad.metrics[key] = metric
}
return nomad
}
return nil
}
// updateAutoscaleMeta populates meta with the metrics used to autoscale a job group.
func updateAutoscaleMeta(metricType string, value, threshold float64, meta map[string]string) {
key := metricType
meta[key+"-value"] = fmt.Sprintf("%.2f", value)
meta[key+"-threshold"] = fmt.Sprintf("%.2f", threshold)
}
| {
"pile_set_name": "Github"
} |
/* vim: ts=4 sw=4 sts=4 et tw=78
* Portions copyright (c) 2015-present, Facebook, Inc. All rights reserved.
* Portions copyright (c) 2011 James R. McKaskill.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
#include "ffi.h"
static cfunction compile(Dst_DECL, lua_State* L, cfunction func, int ref);
static void* reserve_code(struct jit* jit, lua_State* L, size_t sz);
static void commit_code(struct jit* jit, void* p, size_t sz);
static void push_int(lua_State* L, int val)
{ lua_pushinteger(L, val); }
static void push_uint(lua_State* L, unsigned int val)
{ lua_pushinteger(L, val); }
static void push_float(lua_State* L, float val)
{ lua_pushnumber(L, val); }
#ifndef _WIN32
static int GetLastError(void)
{ return errno; }
static void SetLastError(int err)
{ errno = err; }
#endif
#ifdef NDEBUG
#define shred(a,b,c)
#else
#define shred(p,s,e) memset((uint8_t*)(p)+(s),0xCC,(e)-(s))
#endif
#ifdef _WIN64
#include "dynasm/dasm_x86.h"
#include "call_x64win.h"
#elif defined __amd64__
#include "dynasm/dasm_x86.h"
#include "call_x64.h"
#elif defined __arm__ || defined __arm || defined __ARM__ || defined __ARM || defined ARM || defined _ARM_ || defined ARMV4I || defined _M_ARM
#include "dynasm/dasm_arm.h"
#include "call_arm.h"
#else
#include "dynasm/dasm_x86.h"
#include "call_x86.h"
#endif
struct jit_head {
size_t size;
int ref;
uint8_t jump[JUMP_SIZE];
};
#define LINKTABLE_MAX_SIZE (sizeof(extnames) / sizeof(extnames[0]) * (JUMP_SIZE))
static cfunction compile(struct jit* jit, lua_State* L, cfunction func, int ref)
{
struct jit_head* code;
size_t codesz;
int err;
dasm_checkstep(jit, -1);
if ((err = dasm_link(jit, &codesz)) != 0) {
char buf[32];
sprintf(buf, "%x", err);
luaL_error(L, "dasm_link error %s", buf);
}
codesz += sizeof(struct jit_head);
code = (struct jit_head*) reserve_code(jit, L, codesz);
code->ref = ref;
code->size = codesz;
compile_extern_jump(jit, L, func, code->jump);
if ((err = dasm_encode(jit, code+1)) != 0) {
char buf[32];
sprintf(buf, "%x", err);
commit_code(jit, code, 0);
luaL_error(L, "dasm_encode error %s", buf);
}
commit_code(jit, code, codesz);
return (cfunction) (code+1);
}
typedef uint8_t jump_t[JUMP_SIZE];
int get_extern(struct jit* jit, uint8_t* addr, int idx, int type)
{
struct page* page = jit->pages[jit->pagenum-1];
jump_t* jumps = (jump_t*) (page+1);
struct jit_head* h = (struct jit_head*) ((uint8_t*) page + page->off);
uint8_t* jmp;
ptrdiff_t off;
if (idx == jit->function_extern) {
jmp = h->jump;
} else {
jmp = jumps[idx];
}
/* compensate for room taken up for the offset so that we can work rip
* relative */
addr += BRANCH_OFF;
/* see if we can fit the offset in the branch displacement, if not use the
* jump instruction */
off = *(uint8_t**) jmp - addr;
if (MIN_BRANCH <= off && off <= MAX_BRANCH) {
return (int32_t) off;
} else {
return (int32_t)(jmp + sizeof(uint8_t*) - addr);
}
}
static void* reserve_code(struct jit* jit, lua_State* L, size_t sz)
{
struct page* page;
size_t off = (jit->pagenum > 0) ? jit->pages[jit->pagenum-1]->off : 0;
size_t size = (jit->pagenum > 0) ? jit->pages[jit->pagenum-1]->size : 0;
if (off + sz >= size) {
int i;
uint8_t* pdata;
cfunction func;
/* need to create a new page */
jit->pages = (struct page**) realloc(jit->pages, (++jit->pagenum) * sizeof(jit->pages[0]));
size = ALIGN_UP(sz + LINKTABLE_MAX_SIZE + sizeof(struct page), jit->align_page_size);
page = (struct page*) AllocPage(size);
jit->pages[jit->pagenum-1] = page;
pdata = (uint8_t*) page;
page->size = size;
page->off = sizeof(struct page);
lua_newtable(L);
#define ADDFUNC(DLL, NAME) \
lua_pushliteral(L, #NAME); \
func = DLL ? (cfunction) GetProcAddressA(DLL, #NAME) : NULL; \
func = func ? func : (cfunction) &NAME; \
lua_pushcfunction(L, (lua_CFunction) func); \
lua_rawset(L, -3)
ADDFUNC(NULL, check_double);
ADDFUNC(NULL, check_float);
ADDFUNC(NULL, check_uint64);
ADDFUNC(NULL, check_int64);
ADDFUNC(NULL, check_int32);
ADDFUNC(NULL, check_uint32);
ADDFUNC(NULL, check_uintptr);
ADDFUNC(NULL, check_enum);
ADDFUNC(NULL, check_typed_pointer);
ADDFUNC(NULL, check_typed_cfunction);
ADDFUNC(NULL, check_complex_double);
ADDFUNC(NULL, check_complex_float);
ADDFUNC(NULL, unpack_varargs_stack);
ADDFUNC(NULL, unpack_varargs_stack_skip);
ADDFUNC(NULL, unpack_varargs_reg);
ADDFUNC(NULL, unpack_varargs_float);
ADDFUNC(NULL, unpack_varargs_int);
ADDFUNC(NULL, push_cdata);
ADDFUNC(NULL, push_int);
ADDFUNC(NULL, push_uint);
ADDFUNC(NULL, lua_pushinteger);
ADDFUNC(NULL, push_float);
ADDFUNC(jit->kernel32_dll, SetLastError);
ADDFUNC(jit->kernel32_dll, GetLastError);
ADDFUNC(jit->lua_dll, luaL_error);
ADDFUNC(jit->lua_dll, lua_pushnumber);
ADDFUNC(jit->lua_dll, lua_pushboolean);
ADDFUNC(jit->lua_dll, lua_gettop);
ADDFUNC(jit->lua_dll, lua_rawgeti);
ADDFUNC(jit->lua_dll, lua_pushnil);
ADDFUNC(jit->lua_dll, lua_callk);
ADDFUNC(jit->lua_dll, lua_settop);
ADDFUNC(jit->lua_dll, lua_remove);
#undef ADDFUNC
for (i = 0; extnames[i] != NULL; i++) {
if (strcmp(extnames[i], "FUNCTION") == 0) {
shred(pdata + page->off, 0, JUMP_SIZE);
jit->function_extern = i;
} else {
lua_getfield(L, -1, extnames[i]);
func = (cfunction) lua_tocfunction(L, -1);
if (func == NULL) {
luaL_error(L, "internal error: missing link for %s", extnames[i]);
}
compile_extern_jump(jit, L, func, pdata + page->off);
lua_pop(L, 1);
}
page->off += JUMP_SIZE;
}
page->freed = page->off;
lua_pop(L, 1);
} else {
page = jit->pages[jit->pagenum-1];
EnableWrite(page, page->size);
}
return (uint8_t*) page + page->off;
}
static void commit_code(struct jit* jit, void* code, size_t sz)
{
struct page* page = jit->pages[jit->pagenum-1];
page->off += sz;
EnableExecute(page, page->size);
{
#if 0
FILE* out = fopen("\\Hard Disk\\out.bin", "wb");
fwrite(page, page->off, 1, out);
fclose(out);
#endif
}
}
/* push_func_ref pushes a copy of the upval table embedded in the compiled
* function func.
*/
void push_func_ref(lua_State* L, cfunction func)
{
struct jit_head* h = ((struct jit_head*) func) - 1;
lua_rawgeti(L, LUA_REGISTRYINDEX, h->ref);
}
void free_code(struct jit* jit, lua_State* L, cfunction func)
{
size_t i;
struct jit_head* h = ((struct jit_head*) func) - 1;
for (i = 0; i < jit->pagenum; i++) {
struct page* p = jit->pages[i];
if ((uint8_t*) h < (uint8_t*) p || (uint8_t*) p + p->size <= (uint8_t*) h) {
continue;
}
luaL_unref(L, LUA_REGISTRYINDEX, h->ref);
EnableWrite(p, p->size);
p->freed += h->size;
shred(h, 0, h->size);
if (p->freed < p->off) {
EnableExecute(p, p->size);
return;
}
FreePage(p, p->size);
memmove(&jit->pages[i], &jit->pages[i+1], (jit->pagenum - (i+1)) * sizeof(jit->pages[0]));
jit->pagenum--;
return;
}
assert(!"couldn't find func in the jit pages");
}
| {
"pile_set_name": "Github"
} |
fileFormatVersion: 2
guid: 95096f29d1ddcd647ace66f3641d42f5
timeCreated: 1439327332
licenseType: Store
NativeFormatImporter:
userData:
assetBundleName:
assetBundleVariant:
| {
"pile_set_name": "Github"
} |
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"a. m.",
"p. m."
],
"DAY": [
"domingo",
"lunes",
"martes",
"mi\u00e9rcoles",
"jueves",
"viernes",
"s\u00e1bado"
],
"MONTH": [
"enero",
"febrero",
"marzo",
"abril",
"mayo",
"junio",
"julio",
"agosto",
"septiembre",
"octubre",
"noviembre",
"diciembre"
],
"SHORTDAY": [
"dom.",
"lun.",
"mar.",
"mi\u00e9.",
"jue.",
"vie.",
"s\u00e1b."
],
"SHORTMONTH": [
"ene.",
"feb.",
"mar.",
"abr.",
"may.",
"jun.",
"jul.",
"ago.",
"sept.",
"oct.",
"nov.",
"dic."
],
"fullDate": "EEEE, d 'de' MMMM 'de' y",
"longDate": "d 'de' MMMM 'de' y",
"medium": "MM/dd/y h:mm:ss a",
"mediumDate": "MM/dd/y",
"mediumTime": "h:mm:ss a",
"short": "MM/dd/yy h:mm a",
"shortDate": "MM/dd/yy",
"shortTime": "h:mm a"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "$",
"DECIMAL_SEP": ",",
"GROUP_SEP": ".",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "-",
"negSuf": "\u00a0\u00a4",
"posPre": "",
"posSuf": "\u00a0\u00a4"
}
]
},
"id": "es-pr",
"pluralCat": function (n, opt_precision) { if (n == 1) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
});
}]); | {
"pile_set_name": "Github"
} |
# - Find mysqlclient
# Find the native MySQL includes and library
#
# MYSQL_INCLUDE_DIR - where to find mysql.h, etc.
# MYSQL_LIBRARIES - List of libraries when using MySQL.
# MYSQL_FOUND - True if MySQL found.
IF (MYSQL_INCLUDE_DIR)
# Already in cache, be silent
SET(MYSQL_FIND_QUIETLY TRUE)
ENDIF (MYSQL_INCLUDE_DIR)
FIND_PATH(MYSQL_INCLUDE_DIR mysql.h
/usr/local/include/mysql
/usr/include/mysql
)
SET(MYSQL_NAMES mysqlclient mysqlclient_r)
FIND_LIBRARY(MYSQL_LIBRARY
NAMES ${MYSQL_NAMES}
PATHS /usr/lib /usr/local/lib
PATH_SUFFIXES mysql
)
IF (MYSQL_INCLUDE_DIR AND MYSQL_LIBRARY)
SET(MYSQL_FOUND TRUE)
SET( MYSQL_LIBRARIES ${MYSQL_LIBRARY} )
ELSE (MYSQL_INCLUDE_DIR AND MYSQL_LIBRARY)
SET(MYSQL_FOUND FALSE)
SET( MYSQL_LIBRARIES )
ENDIF (MYSQL_INCLUDE_DIR AND MYSQL_LIBRARY)
IF (MYSQL_FOUND)
IF (NOT MYSQL_FIND_QUIETLY)
MESSAGE(STATUS "Found MySQL: ${MYSQL_LIBRARY}")
ENDIF (NOT MYSQL_FIND_QUIETLY)
ELSE (MYSQL_FOUND)
IF (MYSQL_FIND_REQUIRED)
MESSAGE(STATUS "Looked for MySQL libraries named ${MYSQL_NAMES}.")
MESSAGE(FATAL_ERROR "Could NOT find MySQL library")
ENDIF (MYSQL_FIND_REQUIRED)
ENDIF (MYSQL_FOUND)
MARK_AS_ADVANCED(
MYSQL_LIBRARY
MYSQL_INCLUDE_DIR
) | {
"pile_set_name": "Github"
} |
package com.in28minutes.example.layering.data.stub;
import org.springframework.stereotype.Component;
import com.in28minutes.example.layering.data.api.client.ClientDO;
import com.in28minutes.example.layering.model.api.client.Client;
@Component
public class ClientDOStub implements ClientDO {
@Override
public Client getClientDetails(long clientId) {
return null;
}
@Override
public void saveClient(Client client) {
}
}
| {
"pile_set_name": "Github"
} |
################################################################################
#
# xvisor
#
################################################################################
XVISOR_VERSION = 0.2.11
XVISOR_SOURCE = xvisor-$(XVISOR_VERSION).tar.xz
XVISOR_SITE = http://www.xhypervisor.org/tarball
XVISOR_LICENSE = GPL-2.0+
XVISOR_LICENSE_FILES = COPYING
XVISOR_INSTALL_IMAGES = YES
XVISOR_INSTALL_TARGET = NO
XVISOR_DEPENDENCIES = host-bison host-flex
XVISOR_MAKE_TARGETS = all
ifeq ($(BR2_PACKAGE_XVISOR_BUILD_TEST_DTB),y)
XVISOR_MAKE_TARGETS += dtbs
endif
XVISOR_KCONFIG_DOTCONFIG = build/openconf/.config
ifeq ($(BR2_PACKAGE_XVISOR_USE_DEFCONFIG),y)
XVISOR_KCONFIG_DEFCONFIG = $(call qstrip,$(BR2_PACKAGE_XVISOR_DEFCONFIG))-defconfig
else ifeq ($(BR2_PACKAGE_XVISOR_USE_CUSTOM_CONFIG),y)
XVISOR_KCONFIG_FILE = $(call qstrip,$(BR2_PACKAGE_XVISOR_CUSTOM_CONFIG_FILE))
endif
XVISOR_KCONFIG_EDITORS = menuconfig
ifeq ($(BR2_x86_64),y)
XVISOR_ARCH = x86
else ifeq ($(BR2_arm)$(BR2_aarch64),y)
XVISOR_ARCH = arm
endif
ifeq ($(BR2_PACKAGE_XVISOR)$(BR_BUILDING),yy)
ifeq ($(XVISOR_ARCH),)
$(error "Architecture not supported by XVisor")
endif
endif
XVISOR_MAKE_ENV = \
ARCH=$(XVISOR_ARCH) \
CROSS_COMPILE=$(TARGET_CROSS)
XVISOR_MAKE_OPTS = $(if $(VERBOSE),VERBOSE=1)
define XVISOR_BUILD_CMDS
$(TARGET_MAKE_ENV) $(XVISOR_MAKE_ENV) $(MAKE) $(XVISOR_MAKE_OPTS) \
-C $(@D) $(XVISOR_MAKE_TARGETS)
endef
define XVISOR_INSTALL_IMAGES_CMDS
$(INSTALL) -m 0644 -D $(@D)/build/vmm.bin $(BINARIES_DIR)/vmm.bin
endef
ifeq ($(BR2_PACKAGE_XVISOR_CREATE_UBOOT_IMAGE),y)
XVISOR_DEPENDENCIES += host-uboot-tools
define XVISOR_CREATE_UBOOT_IMAGE
$(MKIMAGE) -A $(MKIMAGE_ARCH) -O linux -T kernel -C none \
-a 0x00008000 -e 0x00008000 \
-n Xvisor -d $(BINARIES_DIR)/vmm.bin $(BINARIES_DIR)/uvmm.bin
endef
endif
XVISOR_POST_INSTALL_IMAGES_HOOKS += XVISOR_CREATE_UBOOT_IMAGE
# Checks to give errors that the user can understand
ifeq ($(BR_BUILDING),y)
ifeq ($(BR2_PACKAGE_XVISOR_USE_DEFCONFIG),y)
ifeq ($(call qstrip,$(BR2_PACKAGE_XVISOR_DEFCONFIG)),)
$(error No Xvisor defconfig name specified, check your BR2_PACKAGE_XVISOR_DEFCONFIG setting)
endif
endif
ifeq ($(BR2_PACKAGE_XVISOR_USE_CUSTOM_CONFIG),y)
ifeq ($(BR2_PACKAGE_XVISOR_CUSTOM_CONFIG_FILE),)
$(error No Xvisor configuration file specified, check your BR2_PACKAGE_XVISOR_CUSTOM_CONFIG_FILE setting)
endif
endif
endif
$(eval $(kconfig-package))
| {
"pile_set_name": "Github"
} |
class Antigen < Formula
desc "Plugin manager for zsh, inspired by oh-my-zsh and vundle."
homepage "http://antigen.sharats.me/"
url "https://github.com/zsh-users/antigen/archive/v1.tar.gz"
sha256 "6d4bd7b5d7bc3e36a23ac8feb93073b06e1e09b9100eb898f66c2e8c3f4d7847"
head "https://github.com/zsh-users/antigen.git"
def install
share.install "antigen.zsh"
end
test do
(testpath/".zshrc").write "source `brew --prefix`/share/antigen.zsh"
system "/bin/zsh", "--login", "-i", "-c", "antigen help"
end
end
| {
"pile_set_name": "Github"
} |
<?php
namespace Tests\Filesystem;
use Illuminate\Support\Collection;
use Statamic\Support\FileCollection;
trait FilesystemAdapterTests
{
/** @test */
public function it_makes_a_file_collection()
{
$collection = $this->adapter->collection(['one', 'two']);
$this->assertInstanceOf(FileCollection::class, $collection);
$this->assertEquals(2, $collection->count());
}
/** @test */
public function gets_file_contents()
{
file_put_contents($this->tempDir.'/filename.txt', 'Hello World');
$this->assertEquals('Hello World', $this->adapter->get('filename.txt'));
}
/** @test */
public function gets_fallback_if_file_doesnt_exist()
{
$this->assertEquals('Hello World', $this->adapter->get('filename.txt', 'Hello World'));
}
/** @test */
public function checks_if_file_exists()
{
file_put_contents($this->tempDir.'/filename.txt', 'Hello World');
$this->assertTrue($this->adapter->exists('filename.txt'));
$this->assertFalse($this->adapter->exists('another.txt'));
}
/** @test */
public function assumes_existence_if_checking_on_the_root()
{
$this->assertTrue($this->adapter->exists());
}
/** @test */
public function puts_contents_into_a_file()
{
$this->adapter->put('filename.txt', 'Hello World');
$this->assertStringEqualsFile($this->tempDir.'/filename.txt', 'Hello World');
}
/** @test */
public function puts_content_into_a_file_in_a_subdirectory()
{
$this->adapter->put('subdir/filename.txt', 'Hello World');
$this->assertStringEqualsFile($this->tempDir.'/subdir/filename.txt', 'Hello World');
}
/** @test */
public function deletes_files()
{
file_put_contents($this->tempDir.'/filename.txt', 'Hello World');
$this->adapter->delete('filename.txt');
$this->assertFileNotExists($this->tempDir.'/filename.txt');
}
/** @test */
public function copies_files()
{
file_put_contents($this->tempDir.'/src.txt', 'Hello World');
$this->assertTrue($this->adapter->copy('src.txt', 'dest.txt'));
$this->assertFileExists($this->tempDir.'/dest.txt');
$this->assertFileExists($this->tempDir.'/src.txt');
}
/** @test */
public function copies_files_and_overwrites()
{
file_put_contents($this->tempDir.'/src.txt', 'Hello World');
file_put_contents($this->tempDir.'/dest.txt', 'Existing Content');
$this->assertTrue($this->adapter->copy('src.txt', 'dest.txt', true));
$this->assertStringEqualsFile($this->tempDir.'/src.txt', 'Hello World');
$this->assertStringEqualsFile($this->tempDir.'/dest.txt', 'Hello World');
}
/** @test */
public function moves_files()
{
file_put_contents($this->tempDir.'/src.txt', 'Hello World');
$this->assertTrue($this->adapter->move('src.txt', 'dest.txt'));
$this->assertStringEqualsFile($this->tempDir.'/dest.txt', 'Hello World');
$this->assertFileNotExists($this->tempDir.'/src.txt');
}
/** @test */
public function moves_files_and_overwrites()
{
file_put_contents($this->tempDir.'/src.txt', 'Hello World');
file_put_contents($this->tempDir.'/dest.txt', 'Existing Content');
$this->assertTrue($this->adapter->move('src.txt', 'dest.txt', true));
$this->assertStringEqualsFile($this->tempDir.'/dest.txt', 'Hello World');
$this->assertFileNotExists($this->tempDir.'/src.txt');
}
/** @test */
public function renames_a_file()
{
file_put_contents($this->tempDir.'/src.txt', 'Hello World');
$this->assertTrue($this->adapter->rename('src.txt', 'dest.txt'));
$this->assertFileNotExists($this->tempDir.'/src.txt');
$this->assertStringEqualsFile($this->tempDir.'/dest.txt', 'Hello World');
}
/** @test */
public function gets_file_extension()
{
$this->assertEquals('jpg', $this->adapter->extension('photo.jpg'));
}
/** @test */
public function gets_mime_type()
{
file_put_contents($this->tempDir.'/filename.txt', 'Hello World');
$this->assertEquals('text/plain', $this->adapter->mimeType('filename.txt'));
}
/** @test */
public function gets_last_modified()
{
file_put_contents($this->tempDir.'/filename.txt', 'Hello World');
touch($this->tempDir.'/filename.txt', $time = 1512160249);
$this->assertEquals($time, $this->adapter->lastModified('filename.txt'));
}
/** @test */
public function gets_file_size()
{
file_put_contents($this->tempDir.'/filename.txt', 'Hello World');
$this->assertEquals(11, $this->adapter->size('filename.txt'));
}
// /** @test */
// function gets_file_size_for_humans()
// {
// // todo
// }
/** @test */
public function checks_if_a_file_is_an_image()
{
$this->assertTrue($this->adapter->isImage('test.jpg'));
$this->assertTrue($this->adapter->isImage('test.jpeg'));
$this->assertTrue($this->adapter->isImage('test.png'));
$this->assertTrue($this->adapter->isImage('test.gif'));
$this->assertTrue($this->adapter->isImage('test.JPG'));
$this->assertTrue($this->adapter->isImage('test.JPEG'));
$this->assertTrue($this->adapter->isImage('test.PNG'));
$this->assertTrue($this->adapter->isImage('test.GIF'));
$this->assertFalse($this->adapter->isImage('test.txt'));
}
/** @test */
public function makes_a_directory()
{
$this->assertTrue($this->adapter->makeDirectory('directory'));
$this->assertDirectoryExists($this->tempDir.'/directory');
}
/** @test */
public function gets_files_from_a_directory()
{
mkdir($this->tempDir.'/sub/sub', 0755, true);
file_put_contents($this->tempDir.'/one.txt', '');
file_put_contents($this->tempDir.'/sub/two.txt', '');
file_put_contents($this->tempDir.'/sub/three.txt', '');
file_put_contents($this->tempDir.'/sub/sub/four.txt', '');
$files = $this->adapter->getFiles('sub');
$this->assertInstanceOf(FileCollection::class, $files);
$this->assertArraysHaveSameValues(
['sub/two.txt', 'sub/three.txt'],
$files->all()
);
$files = $this->adapter->getFiles('non-existent-directory');
$this->assertInstanceOf(FileCollection::class, $files);
$this->assertEquals([], $files->all());
}
/** @test */
public function gets_files_from_a_directory_recursively()
{
mkdir($this->tempDir.'/sub/sub', 0755, true);
file_put_contents($this->tempDir.'/one.txt', '');
file_put_contents($this->tempDir.'/sub/two.txt', '');
file_put_contents($this->tempDir.'/sub/three.txt', '');
file_put_contents($this->tempDir.'/sub/sub/four.txt', '');
$expected = ['sub/two.txt', 'sub/three.txt', 'sub/sub/four.txt'];
$files = $this->adapter->getFiles('sub', true);
$this->assertInstanceOf(FileCollection::class, $files);
$this->assertArraysHaveSameValues($expected, $files->all());
$files = $this->adapter->getFilesRecursively('sub');
$this->assertInstanceOf(FileCollection::class, $files);
$this->assertArraysHaveSameValues($expected, $files->all());
}
/** @test */
public function gets_files_recursively_with_directory_exceptions()
{
mkdir($this->tempDir.'/sub/sub', 0755, true);
mkdir($this->tempDir.'/sub/exclude', 0755, true);
file_put_contents($this->tempDir.'/one.txt', '');
file_put_contents($this->tempDir.'/sub/two.txt', '');
file_put_contents($this->tempDir.'/sub/three.txt', '');
file_put_contents($this->tempDir.'/sub/sub/four.txt', '');
file_put_contents($this->tempDir.'/sub/exclude/five.txt', '');
$files = $this->adapter->getFilesRecursivelyExcept('sub', ['exclude']);
$this->assertInstanceOf(FileCollection::class, $files);
$this->assertArraysHaveSameValues(
['sub/two.txt', 'sub/three.txt', 'sub/sub/four.txt'],
$files->all()
);
}
/** @test */
public function gets_folders()
{
mkdir($this->tempDir.'/foo');
mkdir($this->tempDir.'/foo/bar');
mkdir($this->tempDir.'/foo/baz');
mkdir($this->tempDir.'/foo/bar/qux');
mkdir($this->tempDir.'/baz');
mkdir($this->tempDir.'/baz/foo');
$folders = $this->adapter->getFolders('foo');
$this->assertInstanceOf(Collection::class, $folders);
$this->assertArraysHaveSameValues(
['foo/bar', 'foo/baz'],
$folders->all()
);
}
/** @test */
public function gets_folders_recursively()
{
mkdir($this->tempDir.'/foo');
mkdir($this->tempDir.'/foo/bar');
mkdir($this->tempDir.'/foo/baz');
mkdir($this->tempDir.'/foo/bar/qux');
mkdir($this->tempDir.'/baz');
mkdir($this->tempDir.'/baz/foo');
$folders = $this->adapter->getFoldersRecursively('foo');
$this->assertInstanceOf(Collection::class, $folders);
$this->assertArraysHaveSameValues(
['foo/bar', 'foo/baz', 'foo/bar/qux'],
$folders->all()
);
}
/** @test */
public function gets_files_by_type()
{
mkdir($this->tempDir.'/docs');
file_put_contents($this->tempDir.'/image.jpg', '');
file_put_contents($this->tempDir.'/image2.jpg', '');
file_put_contents($this->tempDir.'/text.txt', '');
file_put_contents($this->tempDir.'/docs/word.doc', '');
file_put_contents($this->tempDir.'/docs/test.pdf', '');
file_put_contents($this->tempDir.'/docs/photo.jpg', '');
$files = $this->adapter->getFilesByType('/', 'jpg');
$this->assertInstanceOf(FileCollection::class, $files);
$this->assertArraysHaveSameValues(
['image.jpg', 'image2.jpg'],
$files->all()
);
$this->assertArraysHaveSameValues(
['docs/test.pdf'],
$this->adapter->getFilesByType('docs', 'pdf')->all()
);
$this->assertArraysHaveSameValues(
['image.jpg', 'image2.jpg', 'docs/photo.jpg'],
$this->adapter->getFilesByType('/', 'jpg', true)->all()
);
$files = $this->adapter->getFilesByTypeRecursively('/', 'jpg');
$this->assertInstanceOf(FileCollection::class, $files);
$this->assertArraysHaveSameValues(
['image.jpg', 'image2.jpg', 'docs/photo.jpg'],
$files->all()
);
}
/** @test */
public function checks_for_empty_directories()
{
mkdir($this->tempDir.'/empty');
mkdir($this->tempDir.'/full');
file_put_contents($this->tempDir.'/full/filename.txt', '');
$this->assertTrue($this->adapter->isEmpty('empty'));
$this->assertFalse($this->adapter->isEmpty('full'));
}
/** @test */
public function checks_for_directories()
{
mkdir($this->tempDir.'/directory');
file_put_contents($this->tempDir.'/filename.txt', '');
$this->assertTrue($this->adapter->isDirectory('directory'));
$this->assertFalse($this->adapter->isDirectory('filename.txt'));
}
/** @test */
public function copies_directories()
{
mkdir($this->tempDir.'/src');
file_put_contents($this->tempDir.'/src/one.txt', 'One');
file_put_contents($this->tempDir.'/src/two.txt', 'Two');
$this->adapter->copyDirectory('src', 'dest');
$this->assertStringEqualsFile($this->tempDir.'/src/one.txt', 'One');
$this->assertStringEqualsFile($this->tempDir.'/src/two.txt', 'Two');
$this->assertStringEqualsFile($this->tempDir.'/dest/one.txt', 'One');
$this->assertStringEqualsFile($this->tempDir.'/dest/two.txt', 'Two');
}
/** @test */
public function moves_directories()
{
mkdir($this->tempDir.'/src');
file_put_contents($this->tempDir.'/src/one.txt', 'One');
file_put_contents($this->tempDir.'/src/two.txt', 'Two');
$this->adapter->moveDirectory('src', 'dest');
$this->assertFileNotExists($this->tempDir.'/src/one.txt');
$this->assertFileNotExists($this->tempDir.'/src/two.txt');
$this->assertStringEqualsFile($this->tempDir.'/dest/one.txt', 'One');
$this->assertStringEqualsFile($this->tempDir.'/dest/two.txt', 'Two');
}
/** @test */
public function deletes_empty_subdirectories()
{
mkdir($this->tempDir.'/one/two', 0755, true);
mkdir($this->tempDir.'/three/four', 0755, true);
mkdir($this->tempDir.'/three/five/six', 0755, true);
file_put_contents($this->tempDir.'/one/two/file.txt', '');
file_put_contents($this->tempDir.'/three/file.txt', '');
$this->adapter->deleteEmptySubfolders('/');
$this->assertDirectoryExists($this->tempDir.'/one');
$this->assertDirectoryExists($this->tempDir.'/one/two');
$this->assertDirectoryExists($this->tempDir.'/three');
$this->assertDirectoryNotExists($this->tempDir.'/three/four');
$this->assertDirectoryNotExists($this->tempDir.'/three/five');
$this->assertDirectoryNotExists($this->tempDir.'/three/five/six');
}
/** @test */
public function gets_filesystem()
{
$this->assertEquals($this->filesystem, $this->adapter->filesystem());
}
/**
* Assert that two arrays have the same values but not necessarily in the same order.
*/
private function assertArraysHaveSameValues($expected, $actual)
{
sort($expected);
sort($actual);
$this->assertEquals($expected, $actual);
}
}
| {
"pile_set_name": "Github"
} |
<?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\Routing\Matcher;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Exception\ExceptionInterface;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;
/**
* TraceableUrlMatcher helps debug path info matching by tracing the match.
*
* @author Fabien Potencier <[email protected]>
*/
class TraceableUrlMatcher extends UrlMatcher
{
const ROUTE_DOES_NOT_MATCH = 0;
const ROUTE_ALMOST_MATCHES = 1;
const ROUTE_MATCHES = 2;
protected $traces;
public function getTraces($pathinfo)
{
$this->traces = array();
try {
$this->match($pathinfo);
} catch (ExceptionInterface $e) {
}
return $this->traces;
}
public function getTracesForRequest(Request $request)
{
$this->request = $request;
$traces = $this->getTraces($request->getPathInfo());
$this->request = null;
return $traces;
}
protected function matchCollection($pathinfo, RouteCollection $routes)
{
foreach ($routes as $name => $route) {
$compiledRoute = $route->compile();
if (!preg_match($compiledRoute->getRegex(), $pathinfo, $matches)) {
// does it match without any requirements?
$r = new Route($route->getPath(), $route->getDefaults(), array(), $route->getOptions());
$cr = $r->compile();
if (!preg_match($cr->getRegex(), $pathinfo)) {
$this->addTrace(sprintf('Path "%s" does not match', $route->getPath()), self::ROUTE_DOES_NOT_MATCH, $name, $route);
continue;
}
foreach ($route->getRequirements() as $n => $regex) {
$r = new Route($route->getPath(), $route->getDefaults(), array($n => $regex), $route->getOptions());
$cr = $r->compile();
if (in_array($n, $cr->getVariables()) && !preg_match($cr->getRegex(), $pathinfo)) {
$this->addTrace(sprintf('Requirement for "%s" does not match (%s)', $n, $regex), self::ROUTE_ALMOST_MATCHES, $name, $route);
continue 2;
}
}
continue;
}
// check host requirement
$hostMatches = array();
if ($compiledRoute->getHostRegex() && !preg_match($compiledRoute->getHostRegex(), $this->context->getHost(), $hostMatches)) {
$this->addTrace(sprintf('Host "%s" does not match the requirement ("%s")', $this->context->getHost(), $route->getHost()), self::ROUTE_ALMOST_MATCHES, $name, $route);
continue;
}
// check HTTP method requirement
if ($requiredMethods = $route->getMethods()) {
// HEAD and GET are equivalent as per RFC
if ('HEAD' === $method = $this->context->getMethod()) {
$method = 'GET';
}
if (!in_array($method, $requiredMethods)) {
$this->allow = array_merge($this->allow, $requiredMethods);
$this->addTrace(sprintf('Method "%s" does not match any of the required methods (%s)', $this->context->getMethod(), implode(', ', $requiredMethods)), self::ROUTE_ALMOST_MATCHES, $name, $route);
continue;
}
}
// check condition
if ($condition = $route->getCondition()) {
if (!$this->getExpressionLanguage()->evaluate($condition, array('context' => $this->context, 'request' => $this->request))) {
$this->addTrace(sprintf('Condition "%s" does not evaluate to "true"', $condition), self::ROUTE_ALMOST_MATCHES, $name, $route);
continue;
}
}
// check HTTP scheme requirement
if ($requiredSchemes = $route->getSchemes()) {
$scheme = $this->context->getScheme();
if (!$route->hasScheme($scheme)) {
$this->addTrace(sprintf('Scheme "%s" does not match any of the required schemes (%s); the user will be redirected to first required scheme', $scheme, implode(', ', $requiredSchemes)), self::ROUTE_ALMOST_MATCHES, $name, $route);
return true;
}
}
$this->addTrace('Route matches!', self::ROUTE_MATCHES, $name, $route);
return true;
}
}
private function addTrace($log, $level = self::ROUTE_DOES_NOT_MATCH, $name = null, $route = null)
{
$this->traces[] = array(
'log' => $log,
'name' => $name,
'level' => $level,
'path' => null !== $route ? $route->getPath() : null,
);
}
}
| {
"pile_set_name": "Github"
} |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<title>CMSIS DSP Software Library: arm_iir_lattice_init_q15.c Source File</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javaScript" src="search/search.js"></script>
<link href="doxygen.css" rel="stylesheet" type="text/css"/>
</head>
<body onload='searchBox.OnSelectItem(0);'>
<!-- Generated by Doxygen 1.7.2 -->
<script type="text/javascript"><!--
var searchBox = new SearchBox("searchBox", "search",false,'Search');
--></script>
<div class="navigation" id="top">
<div class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="modules.html"><span>Modules</span></a></li>
<li><a href="annotated.html"><span>Data Structures</span></a></li>
<li class="current"><a href="files.html"><span>Files</span></a></li>
<li><a href="examples.html"><span>Examples</span></a></li>
<li id="searchli">
<div id="MSearchBox" class="MSearchBoxInactive">
<span class="left">
<img id="MSearchSelect" src="search/mag_sel.png"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
alt=""/>
<input type="text" id="MSearchField" value="Search" accesskey="S"
onfocus="searchBox.OnSearchFieldFocus(true)"
onblur="searchBox.OnSearchFieldFocus(false)"
onkeyup="searchBox.OnSearchFieldChange(event)"/>
</span><span class="right">
<a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a>
</span>
</div>
</li>
</ul>
</div>
<div class="tabs2">
<ul class="tablist">
<li><a href="files.html"><span>File List</span></a></li>
<li><a href="globals.html"><span>Globals</span></a></li>
</ul>
</div>
<div class="header">
<div class="headertitle">
<h1>arm_iir_lattice_init_q15.c</h1> </div>
</div>
<div class="contents">
<a href="arm__iir__lattice__init__q15_8c.html">Go to the documentation of this file.</a><div class="fragment"><pre class="fragment"><a name="l00001"></a>00001 <span class="comment">/*----------------------------------------------------------------------------- </span>
<a name="l00002"></a>00002 <span class="comment">* Copyright (C) 2010 ARM Limited. All rights reserved. </span>
<a name="l00003"></a>00003 <span class="comment">* </span>
<a name="l00004"></a>00004 <span class="comment">* $Date: 15. July 2011 </span>
<a name="l00005"></a>00005 <span class="comment">* $Revision: V1.0.10 </span>
<a name="l00006"></a>00006 <span class="comment">* </span>
<a name="l00007"></a>00007 <span class="comment">* Project: CMSIS DSP Library </span>
<a name="l00008"></a>00008 <span class="comment">* Title: arm_iir_lattice_init_q15.c </span>
<a name="l00009"></a>00009 <span class="comment">* </span>
<a name="l00010"></a>00010 <span class="comment">* Description: Q15 IIR lattice filter initialization function. </span>
<a name="l00011"></a>00011 <span class="comment">* </span>
<a name="l00012"></a>00012 <span class="comment">* Target Processor: Cortex-M4/Cortex-M3/Cortex-M0</span>
<a name="l00013"></a>00013 <span class="comment">* </span>
<a name="l00014"></a>00014 <span class="comment">* Version 1.0.10 2011/7/15 </span>
<a name="l00015"></a>00015 <span class="comment">* Big Endian support added and Merged M0 and M3/M4 Source code. </span>
<a name="l00016"></a>00016 <span class="comment">* </span>
<a name="l00017"></a>00017 <span class="comment">* Version 1.0.3 2010/11/29 </span>
<a name="l00018"></a>00018 <span class="comment">* Re-organized the CMSIS folders and updated documentation. </span>
<a name="l00019"></a>00019 <span class="comment">* </span>
<a name="l00020"></a>00020 <span class="comment">* Version 1.0.2 2010/11/11 </span>
<a name="l00021"></a>00021 <span class="comment">* Documentation updated. </span>
<a name="l00022"></a>00022 <span class="comment">* </span>
<a name="l00023"></a>00023 <span class="comment">* Version 1.0.1 2010/10/05 </span>
<a name="l00024"></a>00024 <span class="comment">* Production release and review comments incorporated. </span>
<a name="l00025"></a>00025 <span class="comment">* </span>
<a name="l00026"></a>00026 <span class="comment">* Version 1.0.0 2010/09/20 </span>
<a name="l00027"></a>00027 <span class="comment">* Production release and review comments incorporated </span>
<a name="l00028"></a>00028 <span class="comment">* </span>
<a name="l00029"></a>00029 <span class="comment">* Version 0.0.7 2010/06/10 </span>
<a name="l00030"></a>00030 <span class="comment">* Misra-C changes done </span>
<a name="l00031"></a>00031 <span class="comment">* ---------------------------------------------------------------------------*/</span>
<a name="l00032"></a>00032
<a name="l00033"></a>00033 <span class="preprocessor">#include "<a class="code" href="arm__math_8h.html">arm_math.h</a>"</span>
<a name="l00034"></a>00034
<a name="l00055"></a><a class="code" href="group___i_i_r___lattice.html#ga1f4bc2dd3d5641e96815d3a5aad58998">00055</a> <span class="keywordtype">void</span> <a class="code" href="group___i_i_r___lattice.html#ga1f4bc2dd3d5641e96815d3a5aad58998" title="Initialization function for the Q15 IIR lattice filter.">arm_iir_lattice_init_q15</a>(
<a name="l00056"></a>00056 <a class="code" href="structarm__iir__lattice__instance__q15.html" title="Instance structure for the Q15 IIR lattice filter.">arm_iir_lattice_instance_q15</a> * S,
<a name="l00057"></a>00057 uint16_t numStages,
<a name="l00058"></a>00058 <a class="code" href="arm__math_8h.html#ab5a8fb21a5b3b983d5f54f31614052ea" title="16-bit fractional data type in 1.15 format.">q15_t</a> * pkCoeffs,
<a name="l00059"></a>00059 <a class="code" href="arm__math_8h.html#ab5a8fb21a5b3b983d5f54f31614052ea" title="16-bit fractional data type in 1.15 format.">q15_t</a> * pvCoeffs,
<a name="l00060"></a>00060 <a class="code" href="arm__math_8h.html#ab5a8fb21a5b3b983d5f54f31614052ea" title="16-bit fractional data type in 1.15 format.">q15_t</a> * pState,
<a name="l00061"></a>00061 uint32_t <a class="code" href="arm__fir__example__f32_8c.html#ab6558f40a619c2502fbc24c880fd4fb0">blockSize</a>)
<a name="l00062"></a>00062 {
<a name="l00063"></a>00063 <span class="comment">/* Assign filter taps */</span>
<a name="l00064"></a>00064 S-><a class="code" href="structarm__iir__lattice__instance__q15.html#a96fbed313bef01070409fa182d26ba3f">numStages</a> = numStages;
<a name="l00065"></a>00065
<a name="l00066"></a>00066 <span class="comment">/* Assign reflection coefficient pointer */</span>
<a name="l00067"></a>00067 S-><a class="code" href="structarm__iir__lattice__instance__q15.html#a41c214a1ec38d4a82fae8899d715dd29">pkCoeffs</a> = pkCoeffs;
<a name="l00068"></a>00068
<a name="l00069"></a>00069 <span class="comment">/* Assign ladder coefficient pointer */</span>
<a name="l00070"></a>00070 S-><a class="code" href="structarm__iir__lattice__instance__q15.html#a4c4f57f45b223abbe2a9fb727bd2cad9">pvCoeffs</a> = pvCoeffs;
<a name="l00071"></a>00071
<a name="l00072"></a>00072 <span class="comment">/* Clear state buffer and size is always blockSize + numStages */</span>
<a name="l00073"></a>00073 memset(pState, 0, (numStages + blockSize) * <span class="keyword">sizeof</span>(<a class="code" href="arm__math_8h.html#ab5a8fb21a5b3b983d5f54f31614052ea" title="16-bit fractional data type in 1.15 format.">q15_t</a>));
<a name="l00074"></a>00074
<a name="l00075"></a>00075 <span class="comment">/* Assign state pointer */</span>
<a name="l00076"></a>00076 S-><a class="code" href="structarm__iir__lattice__instance__q15.html#afd0136ab917b529554d93f41a5e04618">pState</a> = pState;
<a name="l00077"></a>00077
<a name="l00078"></a>00078
<a name="l00079"></a>00079 }
<a name="l00080"></a>00080
</pre></div></div>
</div>
<!--- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
<a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(0)"><span class="SelectionMark"> </span>All</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(1)"><span class="SelectionMark"> </span>Data Structures</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(2)"><span class="SelectionMark"> </span>Files</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(3)"><span class="SelectionMark"> </span>Functions</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(4)"><span class="SelectionMark"> </span>Variables</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(5)"><span class="SelectionMark"> </span>Typedefs</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(6)"><span class="SelectionMark"> </span>Enumerations</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(7)"><span class="SelectionMark"> </span>Enumerator</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(8)"><span class="SelectionMark"> </span>Defines</a></div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<hr class="footer"/><address class="footer"><small>Generated on Fri Jul 15 2011 13:16:16 for CMSIS DSP Software Library by 
<a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.7.2 </small></address>
</body>
</html>
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2014, 2020, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*
*/
#ifndef SHARE_CLASSFILE_SYSTEMDICTIONARYSHARED_HPP
#define SHARE_CLASSFILE_SYSTEMDICTIONARYSHARED_HPP
#include "oops/klass.hpp"
#include "classfile/packageEntry.hpp"
#include "classfile/systemDictionary.hpp"
#include "memory/filemap.hpp"
/*===============================================================================
Handling of the classes in the AppCDS archive
To ensure safety and to simplify the implementation, archived classes are
"segregated" into 2 types. The following rules describe how they
are stored and looked up.
[1] Category of archived classes
There are 2 disjoint groups of classes stored in the AppCDS archive:
BUILTIN: These classes may be defined ONLY by the BOOT/PLATFORM/APP
loaders.
UNREGISTERED: These classes may be defined ONLY by a ClassLoader
instance that's not listed above (using fingerprint matching)
[2] How classes from different categories are specified in the classlist:
Starting from JDK9, each class in the classlist may be specified with
these keywords: "id", "super", "interfaces", "loader" and "source".
BUILTIN Only the "id" keyword may be (optionally) specified. All other
keywords are forbidden.
The named class is looked up from the jimage and from
Xbootclasspath/a and CLASSPATH.
UNREGISTERED: The "id", "super", and "source" keywords must all be
specified.
The "interfaces" keyword must be specified if the class implements
one or more local interfaces. The "interfaces" keyword must not be
specified if the class does not implement local interfaces.
The named class is looked up from the location specified in the
"source" keyword.
Example classlist:
# BUILTIN
java/lang/Object id: 0
java/lang/Cloneable id: 1
java/lang/String
# UNREGISTERED
Bar id: 3 super: 0 interfaces: 1 source: /foo.jar
[3] Identifying the category of archived classes
BUILTIN: (C->shared_classpath_index() >= 0)
UNREGISTERED: (C->shared_classpath_index() == UNREGISTERED_INDEX (-9999))
[4] Lookup of archived classes at run time:
(a) BUILTIN loaders:
search _builtin_dictionary
(b) UNREGISTERED loaders:
search _unregistered_dictionary for an entry that matches the
(name, clsfile_len, clsfile_crc32).
===============================================================================*/
#define UNREGISTERED_INDEX -9999
class ClassFileStream;
class Dictionary;
class DumpTimeSharedClassInfo;
class DumpTimeSharedClassTable;
class LambdaProxyClassDictionary;
class RunTimeSharedClassInfo;
class RunTimeSharedDictionary;
class SystemDictionaryShared: public SystemDictionary {
friend class ExcludeDumpTimeSharedClasses;
public:
enum {
FROM_FIELD_IS_PROTECTED = 1 << 0,
FROM_IS_ARRAY = 1 << 1,
FROM_IS_OBJECT = 1 << 2
};
private:
// These _shared_xxxs arrays are used to initialize the java.lang.Package and
// java.security.ProtectionDomain objects associated with each shared class.
//
// See SystemDictionaryShared::init_security_info for more info.
static OopHandle _shared_protection_domains;
static OopHandle _shared_jar_urls;
static OopHandle _shared_jar_manifests;
static InstanceKlass* load_shared_class_for_builtin_loader(
Symbol* class_name,
Handle class_loader,
TRAPS);
static Handle get_package_name(Symbol* class_name, TRAPS);
static PackageEntry* get_package_entry_from_class_name(Handle class_loader, Symbol* class_name);
// Package handling:
//
// 1. For named modules in the runtime image
// BOOT classes: Reuses the existing JVM_GetSystemPackage(s) interfaces
// to get packages in named modules for shared classes.
// Package for non-shared classes in named module is also
// handled using JVM_GetSystemPackage(s).
//
// APP classes: VM calls ClassLoaders.AppClassLoader::definePackage(String, Module)
// to define package for shared app classes from named
// modules.
//
// PLATFORM classes: VM calls ClassLoaders.PlatformClassLoader::definePackage(String, Module)
// to define package for shared platform classes from named
// modules.
//
// 2. For unnamed modules
// BOOT classes: Reuses the existing JVM_GetSystemPackage(s) interfaces to
// get packages for shared boot classes in unnamed modules.
//
// APP classes: VM calls ClassLoaders.AppClassLoader::defineOrCheckPackage()
// with with the manifest and url from archived data.
//
// PLATFORM classes: No package is defined.
//
// The following two define_shared_package() functions are used to define
// package for shared APP and PLATFORM classes.
static void define_shared_package(Symbol* class_name,
Handle class_loader,
Handle manifest,
Handle url,
TRAPS);
static Handle get_shared_jar_manifest(int shared_path_index, TRAPS);
static Handle get_shared_jar_url(int shared_path_index, TRAPS);
static Handle get_protection_domain_from_classloader(Handle class_loader,
Handle url, TRAPS);
static Handle get_shared_protection_domain(Handle class_loader,
int shared_path_index,
Handle url,
TRAPS);
static Handle get_shared_protection_domain(Handle class_loader,
ModuleEntry* mod, TRAPS);
static void atomic_set_array_index(OopHandle array, int index, oop o) {
// Benign race condition: array.obj_at(index) may already be filled in.
// The important thing here is that all threads pick up the same result.
// It doesn't matter which racing thread wins, as long as only one
// result is used by all threads, and all future queries.
((objArrayOop)array.resolve())->atomic_compare_exchange_oop(index, o, NULL);
}
static oop shared_protection_domain(int index);
static void atomic_set_shared_protection_domain(int index, oop pd) {
atomic_set_array_index(_shared_protection_domains, index, pd);
}
static void allocate_shared_protection_domain_array(int size, TRAPS);
static oop shared_jar_url(int index);
static void atomic_set_shared_jar_url(int index, oop url) {
atomic_set_array_index(_shared_jar_urls, index, url);
}
static void allocate_shared_jar_url_array(int size, TRAPS);
static oop shared_jar_manifest(int index);
static void atomic_set_shared_jar_manifest(int index, oop man) {
atomic_set_array_index(_shared_jar_manifests, index, man);
}
static void allocate_shared_jar_manifest_array(int size, TRAPS);
static InstanceKlass* acquire_class_for_current_thread(
InstanceKlass *ik,
Handle class_loader,
Handle protection_domain,
const ClassFileStream* cfs,
TRAPS);
static DumpTimeSharedClassInfo* find_or_allocate_info_for(InstanceKlass* k);
static void write_dictionary(RunTimeSharedDictionary* dictionary,
bool is_builtin);
static void write_lambda_proxy_class_dictionary(LambdaProxyClassDictionary* dictionary);
static bool is_jfr_event_class(InstanceKlass *k);
static bool is_registered_lambda_proxy_class(InstanceKlass* ik);
static void warn_excluded(InstanceKlass* k, const char* reason);
static bool should_be_excluded(InstanceKlass* k);
static bool _dump_in_progress;
DEBUG_ONLY(static bool _no_class_loading_should_happen;)
public:
static bool is_hidden_lambda_proxy(InstanceKlass* ik);
static Handle init_security_info(Handle class_loader, InstanceKlass* ik, PackageEntry* pkg_entry, TRAPS);
static InstanceKlass* find_builtin_class(Symbol* class_name);
static const RunTimeSharedClassInfo* find_record(RunTimeSharedDictionary* static_dict,
RunTimeSharedDictionary* dynamic_dict,
Symbol* name);
static bool has_platform_or_app_classes();
// Called by PLATFORM/APP loader only
static InstanceKlass* find_or_load_shared_class(Symbol* class_name,
Handle class_loader,
TRAPS);
static void allocate_shared_data_arrays(int size, TRAPS);
// Check if sharing is supported for the class loader.
static bool is_sharing_possible(ClassLoaderData* loader_data);
static bool add_unregistered_class(InstanceKlass* k, TRAPS);
static InstanceKlass* dump_time_resolve_super_or_fail(Symbol* child_name,
Symbol* class_name,
Handle class_loader,
Handle protection_domain,
bool is_superclass,
TRAPS);
static void init_dumptime_info(InstanceKlass* k) NOT_CDS_RETURN;
static void remove_dumptime_info(InstanceKlass* k) NOT_CDS_RETURN;
static Dictionary* boot_loader_dictionary() {
return ClassLoaderData::the_null_class_loader_data()->dictionary();
}
static void update_shared_entry(InstanceKlass* klass, int id);
static void set_shared_class_misc_info(InstanceKlass* k, ClassFileStream* cfs);
static InstanceKlass* lookup_from_stream(Symbol* class_name,
Handle class_loader,
Handle protection_domain,
const ClassFileStream* st,
TRAPS);
// "verification_constraints" are a set of checks performed by
// VerificationType::is_reference_assignable_from when verifying a shared class during
// dump time.
//
// With AppCDS, it is possible to override archived classes by calling
// ClassLoader.defineClass() directly. SystemDictionary::load_shared_class() already
// ensures that you cannot load a shared class if its super type(s) are changed. However,
// we need an additional check to ensure that the verification_constraints did not change
// between dump time and runtime.
static bool add_verification_constraint(InstanceKlass* k, Symbol* name,
Symbol* from_name, bool from_field_is_protected,
bool from_is_array, bool from_is_object) NOT_CDS_RETURN_(false);
static void check_verification_constraints(InstanceKlass* klass,
TRAPS) NOT_CDS_RETURN;
static void set_class_has_failed_verification(InstanceKlass* ik) NOT_CDS_RETURN;
static bool has_class_failed_verification(InstanceKlass* ik) NOT_CDS_RETURN_(false);
static void add_lambda_proxy_class(InstanceKlass* caller_ik,
InstanceKlass* lambda_ik,
Symbol* invoked_name,
Symbol* invoked_type,
Symbol* method_type,
Method* member_method,
Symbol* instantiated_method_type) NOT_CDS_RETURN;
static InstanceKlass* get_shared_lambda_proxy_class(InstanceKlass* caller_ik,
Symbol* invoked_name,
Symbol* invoked_type,
Symbol* method_type,
Method* member_method,
Symbol* instantiated_method_type) NOT_CDS_RETURN_(NULL);
static InstanceKlass* get_shared_nest_host(InstanceKlass* lambda_ik) NOT_CDS_RETURN_(NULL);
static InstanceKlass* prepare_shared_lambda_proxy_class(InstanceKlass* lambda_ik,
InstanceKlass* caller_ik,
bool initialize, TRAPS) NOT_CDS_RETURN_(NULL);
static bool check_linking_constraints(InstanceKlass* klass, TRAPS) NOT_CDS_RETURN_(false);
static void record_linking_constraint(Symbol* name, InstanceKlass* klass,
Handle loader1, Handle loader2, TRAPS) NOT_CDS_RETURN;
static bool is_builtin(InstanceKlass* k) {
return (k->shared_classpath_index() != UNREGISTERED_INDEX);
}
static void check_excluded_classes();
static void validate_before_archiving(InstanceKlass* k);
static bool is_excluded_class(InstanceKlass* k);
static void dumptime_classes_do(class MetaspaceClosure* it);
static size_t estimate_size_for_archive();
static void write_to_archive(bool is_static_archive = true);
static void adjust_lambda_proxy_class_dictionary();
static void serialize_dictionary_headers(class SerializeClosure* soc,
bool is_static_archive = true);
static void serialize_well_known_klasses(class SerializeClosure* soc);
static void print() { return print_on(tty); }
static void print_on(outputStream* st) NOT_CDS_RETURN;
static void print_table_statistics(outputStream* st) NOT_CDS_RETURN;
static bool empty_dumptime_table() NOT_CDS_RETURN_(true);
static void start_dumping() NOT_CDS_RETURN;
static Handle create_jar_manifest(const char* man, size_t size, TRAPS) NOT_CDS_RETURN_(Handle());
DEBUG_ONLY(static bool no_class_loading_should_happen() {return _no_class_loading_should_happen;})
#ifdef ASSERT
class NoClassLoadingMark: public StackObj {
public:
NoClassLoadingMark() {
assert(!_no_class_loading_should_happen, "must not be nested");
_no_class_loading_should_happen = true;
}
~NoClassLoadingMark() {
_no_class_loading_should_happen = false;
}
};
#endif
template <typename T>
static unsigned int hash_for_shared_dictionary(T* ptr) {
assert(ptr > (T*)SharedBaseAddress, "must be");
address p = address(ptr) - SharedBaseAddress;
return primitive_hash<address>(p);
}
#if INCLUDE_CDS_JAVA_HEAP
private:
static void update_archived_mirror_native_pointers_for(RunTimeSharedDictionary* dict);
public:
static void update_archived_mirror_native_pointers() NOT_CDS_RETURN;
#endif
};
#endif // SHARE_CLASSFILE_SYSTEMDICTIONARYSHARED_HPP
| {
"pile_set_name": "Github"
} |
/*
* Copyright (C) 2013, 2014, 2015, 2016
* Jean-Luc Barriere <[email protected]>
* Andrew Hayzen <[email protected]>
* Daniel Holm <[email protected]>
* Victor Thompson <[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; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import QtQuick 2.9
import QtQuick.Controls 2.2
MenuItem {
text: qsTr("Add to queue")
font.pointSize: units.fs("medium")
height: visible ? implicitHeight : 0
onTriggered: addQueue({id: model.Id, payload: model.payload})
}
| {
"pile_set_name": "Github"
} |
Thanks for contributing to Eirini! In order for your pull request to be accepted, we would like to ask you the following:
1. Please base your PR off the `master` branch.
1. Describe the change on a conceptual level. How does it work, and why should it exist? Ideally, you contribute a few words to the README, too.
1. Please provide automated tests (preferred) or instructions for manually testing your change.
| {
"pile_set_name": "Github"
} |
const unsigned char color_frag_spv[] = {
0x03, 0x02, 0x23, 0x07, 0x00, 0x00, 0x01, 0x00, 0x08, 0x00, 0x08, 0x00, 0x1D, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x11, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x0B, 0x00, 0x06, 0x00,
0x01, 0x00, 0x00, 0x00, 0x47, 0x4C, 0x53, 0x4C, 0x2E, 0x73, 0x74, 0x64, 0x2E, 0x34, 0x35, 0x30,
0x00, 0x00, 0x00, 0x00, 0x0E, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00,
0x0F, 0x00, 0x06, 0x00, 0x04, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x6D, 0x61, 0x69, 0x6E,
0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x10, 0x00, 0x03, 0x00, 0x04, 0x00, 0x00, 0x00,
0x07, 0x00, 0x00, 0x00, 0x03, 0x00, 0x03, 0x00, 0x02, 0x00, 0x00, 0x00, 0xC2, 0x01, 0x00, 0x00,
0x05, 0x00, 0x04, 0x00, 0x04, 0x00, 0x00, 0x00, 0x6D, 0x61, 0x69, 0x6E, 0x00, 0x00, 0x00, 0x00,
0x05, 0x00, 0x05, 0x00, 0x07, 0x00, 0x00, 0x00, 0x63, 0x6F, 0x6C, 0x6F, 0x72, 0x5F, 0x6D, 0x6F,
0x64, 0x65, 0x00, 0x00, 0x05, 0x00, 0x05, 0x00, 0x10, 0x00, 0x00, 0x00, 0x6F, 0x75, 0x74, 0x5F,
0x63, 0x6F, 0x6C, 0x6F, 0x72, 0x00, 0x00, 0x00, 0x47, 0x00, 0x04, 0x00, 0x07, 0x00, 0x00, 0x00,
0x01, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x47, 0x00, 0x04, 0x00, 0x10, 0x00, 0x00, 0x00,
0x1E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x13, 0x00, 0x02, 0x00, 0x02, 0x00, 0x00, 0x00,
0x21, 0x00, 0x03, 0x00, 0x03, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x15, 0x00, 0x04, 0x00,
0x06, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x32, 0x00, 0x04, 0x00,
0x06, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2B, 0x00, 0x04, 0x00,
0x06, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x14, 0x00, 0x02, 0x00,
0x09, 0x00, 0x00, 0x00, 0x34, 0x00, 0x06, 0x00, 0x09, 0x00, 0x00, 0x00, 0x0A, 0x00, 0x00, 0x00,
0xAA, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x16, 0x00, 0x03, 0x00,
0x0D, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x17, 0x00, 0x04, 0x00, 0x0E, 0x00, 0x00, 0x00,
0x0D, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x20, 0x00, 0x04, 0x00, 0x0F, 0x00, 0x00, 0x00,
0x03, 0x00, 0x00, 0x00, 0x0E, 0x00, 0x00, 0x00, 0x3B, 0x00, 0x04, 0x00, 0x0F, 0x00, 0x00, 0x00,
0x10, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x2B, 0x00, 0x04, 0x00, 0x0D, 0x00, 0x00, 0x00,
0x11, 0x00, 0x00, 0x00, 0xCD, 0xCC, 0x4C, 0x3E, 0x2B, 0x00, 0x04, 0x00, 0x0D, 0x00, 0x00, 0x00,
0x12, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x3F, 0x2C, 0x00, 0x07, 0x00, 0x0E, 0x00, 0x00, 0x00,
0x13, 0x00, 0x00, 0x00, 0x11, 0x00, 0x00, 0x00, 0x12, 0x00, 0x00, 0x00, 0x11, 0x00, 0x00, 0x00,
0x12, 0x00, 0x00, 0x00, 0x2B, 0x00, 0x04, 0x00, 0x06, 0x00, 0x00, 0x00, 0x15, 0x00, 0x00, 0x00,
0x02, 0x00, 0x00, 0x00, 0x34, 0x00, 0x06, 0x00, 0x09, 0x00, 0x00, 0x00, 0x16, 0x00, 0x00, 0x00,
0xAA, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x15, 0x00, 0x00, 0x00, 0x2B, 0x00, 0x04, 0x00,
0x0D, 0x00, 0x00, 0x00, 0x19, 0x00, 0x00, 0x00, 0xC3, 0xF5, 0xA8, 0x3E, 0x2C, 0x00, 0x07, 0x00,
0x0E, 0x00, 0x00, 0x00, 0x1A, 0x00, 0x00, 0x00, 0x12, 0x00, 0x00, 0x00, 0x19, 0x00, 0x00, 0x00,
0x11, 0x00, 0x00, 0x00, 0x12, 0x00, 0x00, 0x00, 0x2C, 0x00, 0x07, 0x00, 0x0E, 0x00, 0x00, 0x00,
0x1C, 0x00, 0x00, 0x00, 0x12, 0x00, 0x00, 0x00, 0x12, 0x00, 0x00, 0x00, 0x12, 0x00, 0x00, 0x00,
0x12, 0x00, 0x00, 0x00, 0x36, 0x00, 0x05, 0x00, 0x02, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0xF8, 0x00, 0x02, 0x00, 0x05, 0x00, 0x00, 0x00,
0xF7, 0x00, 0x03, 0x00, 0x0C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFA, 0x00, 0x04, 0x00,
0x0A, 0x00, 0x00, 0x00, 0x0B, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0xF8, 0x00, 0x02, 0x00,
0x0B, 0x00, 0x00, 0x00, 0x3E, 0x00, 0x03, 0x00, 0x10, 0x00, 0x00, 0x00, 0x13, 0x00, 0x00, 0x00,
0xF9, 0x00, 0x02, 0x00, 0x0C, 0x00, 0x00, 0x00, 0xF8, 0x00, 0x02, 0x00, 0x14, 0x00, 0x00, 0x00,
0xF7, 0x00, 0x03, 0x00, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFA, 0x00, 0x04, 0x00,
0x16, 0x00, 0x00, 0x00, 0x17, 0x00, 0x00, 0x00, 0x1B, 0x00, 0x00, 0x00, 0xF8, 0x00, 0x02, 0x00,
0x17, 0x00, 0x00, 0x00, 0x3E, 0x00, 0x03, 0x00, 0x10, 0x00, 0x00, 0x00, 0x1A, 0x00, 0x00, 0x00,
0xF9, 0x00, 0x02, 0x00, 0x18, 0x00, 0x00, 0x00, 0xF8, 0x00, 0x02, 0x00, 0x1B, 0x00, 0x00, 0x00,
0x3E, 0x00, 0x03, 0x00, 0x10, 0x00, 0x00, 0x00, 0x1C, 0x00, 0x00, 0x00, 0xF9, 0x00, 0x02, 0x00,
0x18, 0x00, 0x00, 0x00, 0xF8, 0x00, 0x02, 0x00, 0x18, 0x00, 0x00, 0x00, 0xF9, 0x00, 0x02, 0x00,
0x0C, 0x00, 0x00, 0x00, 0xF8, 0x00, 0x02, 0x00, 0x0C, 0x00, 0x00, 0x00, 0xFD, 0x00, 0x01, 0x00,
0x38, 0x00, 0x01, 0x00
};
const int color_frag_spv_size = 740;
| {
"pile_set_name": "Github"
} |
name=Erithizon
image=https://magiccards.info/scans/en/mm/244.jpg
value=2.138
rarity=R
type=Creature
subtype=Beast
cost={2}{G}{G}
pt=4/4
ability=Whenever SN attacks, put a +1/+1 counter on target creature of defending player's choice.
timing=main
oracle=Whenever Erithizon attacks, put a +1/+1 counter on target creature of defending player's choice.
status=needs groovy
| {
"pile_set_name": "Github"
} |
proto: struct thread *td, struct rctl_get_racct_args *uap
parms: td, uap
errors:
- ENOSYS
- EINVAL
- EPERM
- E2BIG
- ESRCH
- ENAMETOOLONG
- ERANGE
- EOPNOTSUPP
| {
"pile_set_name": "Github"
} |
// This may look like C code, but it's really -*- C++ -*-
/*
* Copyright (C) 2012 Emweb bv, Herent, Belgium.
*/
#ifndef WT_PAYMENT_CUSTOMER_H
#define WT_PAYMENT_CUSTOMER_H
#include <Wt/Payment/Address.h>
#include <string>
namespace Wt {
class WString;
namespace Payment {
/*! \class Customer Wt/Payment/Customer.h Wt/Payment/Customer.h
* \brief Contains customer information.
*
* \if cpp
* \code
* Wt::Payment::Customer customer;
*
* customer.setEmail("[email protected]");
* customer.setFirstName("Joe");
* customer.setLastName("Birkenberg");
*
* Wt::Payment::Address address;
* address.setCity("Leuven");
* address.setCountryCode("BE");
* address.setPhoneNumber("123456789");
* address.setStreet1("Brusselsestraat 14");
*
* customer.setShippingAddress(address);
* \endcode
* \endif
*
* \ingroup payment
*/
class WT_API Customer
{
public:
/*! \brief Default constructor.
*
* All information is blank.
*/
Customer();
/*! \brief Sets the first name.
*/
void setFirstName(const WString& firstName);
/*! \brief Returns the first name.
*
* \sa setFirstName()
*/
WString firstName() const { return firstName_; }
/*! \brief Sets the last name.
*/
void setLastName(const WString& lastName);
/*! \brief Returns the last name.
*
* \sa setLastName()
*/
WString lastName() const { return lastName_; }
/*! \brief Sets the email address.
*/
void setEmail(const std::string& email);
/*! \brief Returns the email address.
*
* \sa setEmail()
*/
std::string email() const { return email_; }
/*! \brief Sets the shipping address.
*/
void setShippingAddress(const Address& address);
/*! \brief Returns shipping address.
*
* \sa setShippingAddress()
*/
const Address& shippingAddress() const { return shippingAddress_; }
/*! \brief Sets the customer locale.
*
* The customer locale must be specified according to the payment broker
* (usually to help the user being served in his native language), which
* is usually a language code like http://en.wikipedia.org/wiki/BCP_47
*/
void setLocale(const std::string& locale);
/*! \brief Returns locale
*
* \sa setLocale()
*/
std::string locale() const { return locale_; }
/*! \brief Sets the payerId field
*
* This is the identification of the user with a payment broker which also
* keeps login information (and other information like shipping addresses)
* on the user.
*
* Not all payment brokers support (or need this).
*/
void setPayerId(const std::string& payerId);
/*! \brief Returns payerId
*
* \sa setPayerId()
*/
std::string payerId() const { return payerId_; }
private:
WString firstName_, lastName_;
std::string email_;
Address shippingAddress_;
std::string locale_;
std::string payerId_;
};
}
}
#endif // WT_PAYMENT_CUSTOMER_H_
| {
"pile_set_name": "Github"
} |
/*
* Copyright (C) 2018 Apple Inc. 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.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
#pragma once
#if ENABLE(WEBGPU)
#include <wtf/text/WTFString.h>
namespace WebCore {
struct GPUShaderModuleDescriptor {
String code;
};
} // namespace WebCore
#endif // ENABLE(WEBGPU)
| {
"pile_set_name": "Github"
} |
version https://git-lfs.github.com/spec/v1
oid sha256:04f90a3dd5d276692be541ac6e8d3e4cfbb40fd7dc3d115b152bf8cf51162bf8
size 28777300
| {
"pile_set_name": "Github"
} |
/********************************************************************************
* Copyright (c) 2011-2017 Red Hat Inc. and/or its affiliates and others
*
* This program and the accompanying materials are made available under the
* terms of the Apache License, Version 2.0 which is available at
* http://www.apache.org/licenses/LICENSE-2.0
*
* SPDX-License-Identifier: Apache-2.0
********************************************************************************/
package org.eclipse.ceylon.model.test;
import org.eclipse.ceylon.model.loader.OsgiVersion;
import org.junit.Assert;
import org.junit.Test;
public class OsgiVersionTests {
@Test
public void testVersionConversions() {
Assert.assertEquals("0.0.0.osgi-5", OsgiVersion.fromCeylonVersion(""));
Assert.assertEquals("1.0.0.osgi-3-n002-5", OsgiVersion.fromCeylonVersion("1-rc2"));
Assert.assertEquals("1.0.0.osgi-5", OsgiVersion.fromCeylonVersion("1"));
Assert.assertEquals("1.2.0.osgi-2", OsgiVersion.fromCeylonVersion("1.2.m"));
Assert.assertEquals("1.2.0.osgi-5", OsgiVersion.fromCeylonVersion("1.2"));
Assert.assertEquals("1.2.0.osgi-7-abc", OsgiVersion.fromCeylonVersion("1.2.abc"));
Assert.assertEquals("1.2.0.osgi-7-abc-n003-n004-5", OsgiVersion.fromCeylonVersion("1.2.abc.3.4"));
Assert.assertEquals("1.2.0.osgi-5-n003-n004-5", OsgiVersion.fromCeylonVersion("1.2.ga.3.4"));
Assert.assertEquals("1.2.3.osgi-n004-5", OsgiVersion.fromCeylonVersion("1.2.3.4"));
Assert.assertEquals("2.0.0.osgi-5", OsgiVersion.fromCeylonVersion("2"));
Assert.assertEquals("2.0.0.osgi-5", OsgiVersion.fromCeylonVersion("2-ga"));
Assert.assertEquals("2.0.0.osgi-5", OsgiVersion.fromCeylonVersion("2-final"));
Assert.assertEquals("3.0.0.osgi-3-n002-5", OsgiVersion.fromCeylonVersion("3cr2"));
Assert.assertEquals("3.0.0.osgi-3-n002-5", OsgiVersion.fromCeylonVersion("3.rc-2"));
}
@Test
public void testVersionOrdering() {
Assert.assertTrue(OsgiVersion.fromCeylonVersion("").compareTo(OsgiVersion.fromCeylonVersion("1-rc2")) < 0);
Assert.assertTrue(OsgiVersion.fromCeylonVersion("1-rc2").compareTo(OsgiVersion.fromCeylonVersion("1")) < 0);
Assert.assertTrue(OsgiVersion.fromCeylonVersion("1").compareTo(OsgiVersion.fromCeylonVersion("1.2.m")) < 0);
Assert.assertTrue(OsgiVersion.fromCeylonVersion("1.2.m").compareTo(OsgiVersion.fromCeylonVersion("1.2")) < 0);
Assert.assertTrue(OsgiVersion.fromCeylonVersion("1.2").compareTo(OsgiVersion.fromCeylonVersion("1.2.abc")) < 0);
Assert.assertTrue(OsgiVersion.fromCeylonVersion("1.2.abc").compareTo(OsgiVersion.fromCeylonVersion("1.2.abc.3.4")) < 0);
Assert.assertTrue(OsgiVersion.fromCeylonVersion("1.2.ga.3.4").compareTo(OsgiVersion.fromCeylonVersion("1.2.abc.3.4")) < 0);
Assert.assertTrue(OsgiVersion.fromCeylonVersion("1.2.abc.3.4").compareTo(OsgiVersion.fromCeylonVersion("1.2.3.4")) < 0);
}
}
| {
"pile_set_name": "Github"
} |
(function(angular) {
'use strict';
angular.module('locationExample', [])
.controller('LocationController', ['$scope', '$location', function($scope, $location) {
$scope.locationPath = function(newLocation) {
return $location.path(newLocation);
};
}]);
})(window.angular); | {
"pile_set_name": "Github"
} |
User-agent: *
Disallow: /static | {
"pile_set_name": "Github"
} |
/*
* 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.geode.internal.serialization;
import java.io.IOException;
import java.util.Arrays;
import org.apache.geode.annotations.Immutable;
/**
* DscodeHelper is used by advanced serialization code to convert between bytes and
* DSCODEs.
*/
public class DscodeHelper {
@Immutable
private static final DSCODE[] dscodes = new DSCODE[128];
static {
Arrays.stream(DSCODE.values()).filter(dscode -> dscode.toByte() >= 0)
.forEach(dscode -> dscodes[dscode.toByte()] = dscode);
}
public static DSCODE toDSCODE(final byte value) throws IOException {
try {
DSCODE result = dscodes[value];
if (result == null) {
throw new IOException("Unknown header byte " + value);
}
return result;
} catch (ArrayIndexOutOfBoundsException e) {
throw new IOException("Unknown header byte: " + value);
}
}
}
| {
"pile_set_name": "Github"
} |
// =================================================================================================
// Copyright 2011 Twitter, Inc.
// -------------------------------------------------------------------------------------------------
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this work except in compliance with the License.
// You may obtain a copy of the License in the LICENSE file, or 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.twitter.common.stats;
import com.google.common.base.Preconditions;
public class PrintableHistogram {
private double[] bucketBoundaries;
private int[] bucketCounts;
private int totalCount = 0;
/**
* Creates a histogram with the given bucket boundaries. The boundaries
* 0 and infinity are implicitly added.
*
* @param buckets Boundaries for histogram buckets.
*/
public PrintableHistogram(double ... buckets) {
Preconditions.checkState(buckets[0] != 0);
bucketBoundaries = new double[buckets.length + 2];
bucketBoundaries[0] = 0;
bucketCounts = new int[buckets.length + 2];
for (int i = 0; i < buckets.length; i++) {
if (i > 0) {
Preconditions.checkState(buckets[i] > buckets[i - 1],
"Bucket %f must be greater than %f.", buckets[i], buckets[i - 1]);
}
bucketCounts[i] = 0;
bucketBoundaries[i + 1] = buckets[i];
}
bucketBoundaries[bucketBoundaries.length - 1] = Integer.MAX_VALUE;
}
public void addValue(double value) {
addValue(value, 1);
}
public void addValue(double value, int count) {
Preconditions.checkState(value >= 0);
Preconditions.checkState(count >= 0);
Preconditions.checkState(bucketBoundaries.length > 1);
int bucketId = -1;
for (double boundary : bucketBoundaries) {
if (value <= boundary) {
break;
}
bucketId++;
}
bucketId = Math.max(0, bucketId);
bucketId = Math.min(bucketCounts.length - 1, bucketId);
bucketCounts[bucketId] += count;
totalCount += count;
}
public double getBucketRatio(int bucketId) {
Preconditions.checkState(bucketId >= 0);
Preconditions.checkState(bucketId < bucketCounts.length);
return (double) bucketCounts[bucketId] / totalCount;
}
public String toString() {
StringBuilder display = new StringBuilder();
display.append("Histogram: ");
for (int bucketId = 0; bucketId < bucketCounts.length - 1; bucketId++) {
display.append(String.format("\n(%g - %g]\n\t",
bucketBoundaries[bucketId], bucketBoundaries[bucketId + 1]));
for (int i = 0; i < getBucketRatio(bucketId) * 100; i++) {
display.append('#');
}
display.append(
String.format(" %.2g%% (%d)", getBucketRatio(bucketId) * 100, bucketCounts[bucketId]));
}
return display.toString();
}
}
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2002-2020 "Neo4j,"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of Neo4j.
*
* Neo4j is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.neo4j.cypher.internal.runtime.interpreted.pipes
import org.mockito.Mockito
import org.mockito.Mockito.when
import org.neo4j.cypher.internal.expressions.SemanticDirection
import org.neo4j.cypher.internal.runtime.ResourceManager
import org.neo4j.cypher.internal.runtime.interpreted.QueryStateHelper
import org.neo4j.cypher.internal.util.test_helpers.CypherFunSuite
import org.neo4j.graphdb.Node
import org.neo4j.internal.kernel.api.RelationshipTraversalCursor
import org.neo4j.internal.kernel.api.helpers.CachingExpandInto
import org.neo4j.internal.kernel.api.helpers.StubNodeCursor
import org.neo4j.internal.kernel.api.helpers.StubRelationshipCursor
import org.neo4j.internal.kernel.api.helpers.TestRelationshipChain
class ExpandIntoPipeTest extends CypherFunSuite {
test("exhaust should close cursor and cache") {
val monitor = QueryStateHelper.trackClosedMonitor
val resourceManager = new ResourceManager(monitor)
val state = QueryStateHelper.emptyWithResourceManager(resourceManager)
val nodeCursor = new StubNodeCursor(false)
.withNode(10).withNode(10).withDegree(25)
val relCursor = new StubRelationshipCursor(new TestRelationshipChain(10).outgoing(1, 20, 0))
Mockito.when(state.query.traversalCursor()).thenReturn(relCursor)
Mockito.when(state.query.nodeCursor()).thenReturn(nodeCursor)
val input = new FakePipe(Seq(Map("a"->newMockedNode(10), "b"->newMockedNode(20))))
val pipe = ExpandIntoPipe(input, "a", "r", "b", SemanticDirection.OUTGOING, new EagerTypes(Array(0)))()
// exhaust
pipe.createResults(state).toList
input.wasClosed shouldBe true
// Our RelationshipTraversalCursor is wrapped in an ExpandIntoSelectionCursor. Thus not asserting on same instance.
monitor.closedResources.collect { case r:RelationshipTraversalCursor => r } should have size(1)
monitor.closedResources.collect { case r:CachingExpandInto => r } should have size(1)
}
test("close should close cursor and cache") {
val monitor = QueryStateHelper.trackClosedMonitor
val resourceManager = new ResourceManager(monitor)
val state = QueryStateHelper.emptyWithResourceManager(resourceManager)
val nodeCursor = new StubNodeCursor(false)
.withNode(10).withNode(10).withDegree(25)
val relCursor = new StubRelationshipCursor(new TestRelationshipChain(10).outgoing(1, 20, 0))
Mockito.when(state.query.traversalCursor()).thenReturn(relCursor)
Mockito.when(state.query.nodeCursor()).thenReturn(nodeCursor)
val input = new FakePipe(Seq(Map("a"->newMockedNode(10), "b"->newMockedNode(20))))
val pipe = ExpandIntoPipe(input, "a", "r", "b", SemanticDirection.OUTGOING, new EagerTypes(Array(0)))()
val result = pipe.createResults(state)
result.hasNext shouldBe true // Need to initialize to get cursor registered
result.close()
input.wasClosed shouldBe true
// Our RelationshipTraversalCursor is wrapped in an ExpandIntoSelectionCursor. Thus not asserting on same instance.
monitor.closedResources.collect { case r:RelationshipTraversalCursor => r } should have size(1)
monitor.closedResources.collect { case r:CachingExpandInto => r } should have size(1)
}
private def newMockedNode(id: Int): Node = {
val node = mock[Node]
when(node.getId).thenReturn(id)
when(node.toString).thenReturn("node - " + id.toString)
node
}
}
| {
"pile_set_name": "Github"
} |
/*
* Copyright (C) 2013 salesforce.com, 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.
*/
({
items: [
{
id: "0",
name: "Mary Scott Fitzgerald",
gender: "F",
age: "7",
grade: "2nd"
}, {
id: "1",
name: "Dan Neal",
gender: "M",
age: "8",
grade: "3rd"
}, {
id: "2",
name: "Helen Beagle",
gender: "F",
age: "9",
grade: "4th"
}, {
id: "3",
name: "Monica Rodrige",
gender: "F",
age: "10",
grade: "5th"
}, {
id: "4",
name: "Jenny Wang",
gender: "F",
age: "7",
grade: "1st"
}, {
id: "5",
name: "Michael Hass",
gender: "M",
age: "10",
grade: "4th"
}, {
id: "6",
name: "Katty Liu",
gender: "F",
age: "10",
grade: "5th"
}, {
id: "7",
name: "Preeya Khan",
gender: "F",
age: "9",
grade: "4th"
}, {
id: "8",
name: "Ravi Vaz",
gender: "M",
age: "8",
grade: "3rd"
}, {
id: "9",
name: "Ted Snider",
gender: "M",
age: "6",
grade: "1st"
}, {
id: "10",
name: "Carl Swasson",
gender: "M",
age: "9",
grade: "4th"
}
]
}) | {
"pile_set_name": "Github"
} |
cheats = 24
cheat0_desc = "Activator 1 P1"
cheat0_code = "D00D1C14 0000"
cheat0_enable = false
cheat1_desc = "Activator 2 P1"
cheat1_code = "D00D1C15 0000"
cheat1_enable = false
cheat2_desc = "Dual Activator P1"
cheat2_code = "D10D1C14 0000"
cheat2_enable = false
cheat3_desc = "No Shot Clock"
cheat3_code = "812010C4 43FF"
cheat3_enable = false
cheat4_desc = "Away Team Score Modifier"
cheat4_code = "8129195C 0000"
cheat4_enable = false
cheat5_desc = "Away Team Scores 0 pts."
cheat5_code = "8129195C 0000"
cheat5_enable = false
cheat6_desc = "Away Team Scores 150 pts."
cheat6_code = "8129195C 0096"
cheat6_enable = false
cheat7_desc = "Home Team Score Modifier"
cheat7_code = "81290378 0000"
cheat7_enable = false
cheat8_desc = "Home Team Scores 0 pts."
cheat8_code = "81290378 0000"
cheat8_enable = false
cheat9_desc = "Home Team Scores 150 pts."
cheat9_code = "81290378 0096"
cheat9_enable = false
cheat10_desc = "Infinite Time Outs Home"
cheat10_code = "80290374 0007"
cheat10_enable = false
cheat11_desc = "No Time Outs Home"
cheat11_code = "80290374 0000"
cheat11_enable = false
cheat12_desc = "Infinite Time Outs Away"
cheat12_code = "80291958 0007"
cheat12_enable = false
cheat13_desc = "No Time Outs Away"
cheat13_code = "80291958 0000"
cheat13_enable = false
cheat14_desc = "Max Shooting"
cheat14_code = "802C5EFB 0063"
cheat14_enable = false
cheat15_desc = "Max 3 Point"
cheat15_code = "802C5EFC 0063"
cheat15_enable = false
cheat16_desc = "Max Free Throw"
cheat16_code = "802C5EFD 0063"
cheat16_enable = false
cheat17_desc = "Max Offensive"
cheat17_code = "802C5EFE 0063"
cheat17_enable = false
cheat18_desc = "Max Defensive"
cheat18_code = "802C5EFF 0063"
cheat18_enable = false
cheat19_desc = "Max Rebound"
cheat19_code = "802C5F00 0063"
cheat19_enable = false
cheat20_desc = "Max Techinque"
cheat20_code = "802C5F01 0063"
cheat20_enable = false
cheat21_desc = "Max Capaility"
cheat21_code = "802C5F02 0063"
cheat21_enable = false
cheat22_desc = "Stop Time"
cheat22_code = "802010C1 0001"
cheat22_enable = false
cheat23_desc = "Master Code"
cheat23_code = "F11D83E8 2400"
cheat23_enable = false | {
"pile_set_name": "Github"
} |
Checks stepping with blackboxed frames on stack
Running test: testStepIntoFromUser
(anonymous) (expr.js:0:0)
Executing stepInto...
Executing stepInto...
userFoo (user.js:23:2)
frameworkCall (framework.js:10:23)
testStepFromUser (user.js:31:2)
(anonymous) (expr.js:0:0)
Executing stepInto...
Executing stepInto...
userBoo (user.js:27:2)
frameworkCall (framework.js:10:23)
testStepFromUser (user.js:31:2)
(anonymous) (expr.js:0:0)
Executing stepInto...
Executing stepInto...
testStepFromUser (user.js:32:0)
(anonymous) (expr.js:0:0)
Executing resume...
Running test: testStepOverFromUser
(anonymous) (expr.js:0:0)
Executing stepInto...
Executing stepInto...
userFoo (user.js:23:2)
frameworkCall (framework.js:10:23)
testStepFromUser (user.js:31:2)
(anonymous) (expr.js:0:0)
Executing stepOver...
Executing stepOver...
userBoo (user.js:27:2)
frameworkCall (framework.js:10:23)
testStepFromUser (user.js:31:2)
(anonymous) (expr.js:0:0)
Executing stepOver...
Executing stepOver...
testStepFromUser (user.js:32:0)
(anonymous) (expr.js:0:0)
Executing resume...
Running test: testStepOutFromUser
(anonymous) (expr.js:0:0)
Executing stepInto...
Executing stepInto...
userFoo (user.js:23:2)
frameworkCall (framework.js:10:23)
testStepFromUser (user.js:31:2)
(anonymous) (expr.js:0:0)
Executing stepOut...
userBoo (user.js:27:2)
frameworkCall (framework.js:10:23)
testStepFromUser (user.js:31:2)
(anonymous) (expr.js:0:0)
Executing resume...
Running test: testStepIntoFromFramework
frameworkBreakAndCall (framework.js:14:12)
testStepFromFramework (user.js:35:2)
(anonymous) (expr.js:0:0)
Executing stepInto...
userFoo (user.js:23:2)
frameworkBreakAndCall (framework.js:15:23)
testStepFromFramework (user.js:35:2)
(anonymous) (expr.js:0:0)
Executing resume...
Running test: testStepOverFromFramework
frameworkBreakAndCall (framework.js:14:12)
testStepFromFramework (user.js:35:2)
(anonymous) (expr.js:0:0)
Executing stepOver...
testStepFromFramework (user.js:36:0)
(anonymous) (expr.js:0:0)
Executing resume...
Running test: testStepOutFromFramework
frameworkBreakAndCall (framework.js:14:12)
testStepFromFramework (user.js:35:2)
(anonymous) (expr.js:0:0)
Executing stepOut...
testStepFromFramework (user.js:36:0)
(anonymous) (expr.js:0:0)
Executing resume...
| {
"pile_set_name": "Github"
} |
apiVersion: v1
kind: Pod
metadata:
name: kubia-xyz
labels:
app: kubia
spec:
containers:
- image: luksa/kubia
name: kubia
ports:
- containerPort: 8080
protocol: TCP
resources:
requests:
memory: 300Mi
cpu: .65
| {
"pile_set_name": "Github"
} |
#include "clar_libgit2.h"
#include "posix.h"
#include "path.h"
#include "submodule_helpers.h"
#include "fileops.h"
#include "repository.h"
static git_repository *g_repo = NULL;
void test_submodule_escape__cleanup(void)
{
cl_git_sandbox_cleanup();
}
#define EVIL_SM_NAME "../../modules/evil"
#define EVIL_SM_NAME_WINDOWS "..\\\\..\\\\modules\\\\evil"
#define EVIL_SM_NAME_WINDOWS_UNESC "..\\..\\modules\\evil"
static int find_evil(git_submodule *sm, const char *name, void *payload)
{
int *foundit = (int *) payload;
GIT_UNUSED(sm);
if (!git__strcmp(EVIL_SM_NAME, name) ||
!git__strcmp(EVIL_SM_NAME_WINDOWS_UNESC, name))
*foundit = true;
return 0;
}
void test_submodule_escape__from_gitdir(void)
{
int foundit;
git_submodule *sm;
git_buf buf = GIT_BUF_INIT;
unsigned int sm_location;
g_repo = setup_fixture_submodule_simple();
cl_git_pass(git_buf_joinpath(&buf, git_repository_workdir(g_repo), ".gitmodules"));
cl_git_rewritefile(buf.ptr,
"[submodule \"" EVIL_SM_NAME "\"]\n"
" path = testrepo\n"
" url = ../testrepo.git\n");
git_buf_free(&buf);
/* Find it all the different ways we know about it */
foundit = 0;
cl_git_pass(git_submodule_foreach(g_repo, find_evil, &foundit));
cl_assert_equal_i(0, foundit);
cl_git_fail_with(GIT_ENOTFOUND, git_submodule_lookup(&sm, g_repo, EVIL_SM_NAME));
/*
* We do know about this as it's in the index and HEAD, but the data is
* incomplete as there is no configured data for it (we pretend it
* doesn't exist). This leaves us with an odd situation but it's
* consistent with what we would do if we did add a submodule with no
* configuration.
*/
cl_git_pass(git_submodule_lookup(&sm, g_repo, "testrepo"));
cl_git_pass(git_submodule_location(&sm_location, sm));
cl_assert_equal_i(GIT_SUBMODULE_STATUS_IN_INDEX | GIT_SUBMODULE_STATUS_IN_HEAD, sm_location);
git_submodule_free(sm);
}
void test_submodule_escape__from_gitdir_windows(void)
{
int foundit;
git_submodule *sm;
git_buf buf = GIT_BUF_INIT;
unsigned int sm_location;
g_repo = setup_fixture_submodule_simple();
cl_git_pass(git_buf_joinpath(&buf, git_repository_workdir(g_repo), ".gitmodules"));
cl_git_rewritefile(buf.ptr,
"[submodule \"" EVIL_SM_NAME_WINDOWS "\"]\n"
" path = testrepo\n"
" url = ../testrepo.git\n");
git_buf_free(&buf);
/* Find it all the different ways we know about it */
foundit = 0;
cl_git_pass(git_submodule_foreach(g_repo, find_evil, &foundit));
cl_assert_equal_i(0, foundit);
cl_git_fail_with(GIT_ENOTFOUND, git_submodule_lookup(&sm, g_repo, EVIL_SM_NAME_WINDOWS_UNESC));
/*
* We do know about this as it's in the index and HEAD, but the data is
* incomplete as there is no configured data for it (we pretend it
* doesn't exist). This leaves us with an odd situation but it's
* consistent with what we would do if we did add a submodule with no
* configuration.
*/
cl_git_pass(git_submodule_lookup(&sm, g_repo, "testrepo"));
cl_git_pass(git_submodule_location(&sm_location, sm));
cl_assert_equal_i(GIT_SUBMODULE_STATUS_IN_INDEX | GIT_SUBMODULE_STATUS_IN_HEAD, sm_location);
git_submodule_free(sm);
}
| {
"pile_set_name": "Github"
} |
{"text": ["lookn", "4wins", ":", "$", "vz", "volume", "$", "vz", "most", "recent", "stock", "chart", "and", "URL"], "created_at": "Sun Nov 02 16:08:08 +0000 2014", "user_id_str": "386787305"}
| {
"pile_set_name": "Github"
} |
/*
Copyright (c) 2012, Broadcom Europe Ltd
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <termios.h>
#include "nb_io.h"
void nb_set_nonblocking_input(int enable)
{
struct termios ttystate;
//get the terminal state
tcgetattr(STDIN_FILENO, &ttystate);
if (enable)
{
//turn off canonical mode
ttystate.c_lflag &= ~ICANON;
//minimum of number input read.
ttystate.c_cc[VMIN] = 1;
}
else
{
//turn on canonical mode
ttystate.c_lflag |= ICANON;
}
//set the terminal attributes.
tcsetattr(STDIN_FILENO, TCSANOW, &ttystate);
}
int nb_char_available(void)
{
struct timeval tv;
fd_set fds;
tv.tv_sec = 0;
tv.tv_usec = 0;
FD_ZERO(&fds);
FD_SET(STDIN_FILENO, &fds);
select(STDIN_FILENO+1, &fds, NULL, NULL, &tv);
return (FD_ISSET(0, &fds));
}
char nb_get_char(void)
{
return getchar();
}
void nb_put_char(char ch)
{
putchar(ch);
}
| {
"pile_set_name": "Github"
} |
// (C) Copyright John Maddock 2001 - 2003.
// (C) Copyright Jens Maurer 2001.
// (C) Copyright Peter Dimov 2001.
// (C) Copyright David Abrahams 2002.
// (C) Copyright Guillaume Melquiond 2003.
// Use, modification and distribution are subject to the
// Boost Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org for most recent version.
// Dinkumware standard library config:
#if !defined(_YVALS) && !defined(_CPPLIB_VER)
#include <boost/config/no_tr1/utility.hpp>
#if !defined(_YVALS) && !defined(_CPPLIB_VER)
#error This is not the Dinkumware lib!
#endif
#endif
#if defined(_CPPLIB_VER) && (_CPPLIB_VER >= 306)
// full dinkumware 3.06 and above
// fully conforming provided the compiler supports it:
# if !(defined(_GLOBAL_USING) && (_GLOBAL_USING+0 > 0)) && !defined(__BORLANDC__) && !defined(_STD) && !(defined(__ICC) && (__ICC >= 700)) // can be defined in yvals.h
# define BOOST_NO_STDC_NAMESPACE
# endif
# if !(defined(_HAS_MEMBER_TEMPLATES_REBIND) && (_HAS_MEMBER_TEMPLATES_REBIND+0 > 0)) && !(defined(_MSC_VER) && (_MSC_VER > 1300)) && defined(BOOST_MSVC)
# define BOOST_NO_STD_ALLOCATOR
# endif
# define BOOST_HAS_PARTIAL_STD_ALLOCATOR
# if defined(BOOST_MSVC) && (BOOST_MSVC < 1300)
// if this lib version is set up for vc6 then there is no std::use_facet:
# define BOOST_NO_STD_USE_FACET
# define BOOST_HAS_TWO_ARG_USE_FACET
// C lib functions aren't in namespace std either:
# define BOOST_NO_STDC_NAMESPACE
// and nor is <exception>
# define BOOST_NO_EXCEPTION_STD_NAMESPACE
# endif
// There's no numeric_limits<long long> support unless _LONGLONG is defined:
# if !defined(_LONGLONG) && (_CPPLIB_VER <= 310)
# define BOOST_NO_MS_INT64_NUMERIC_LIMITS
# endif
// 3.06 appears to have (non-sgi versions of) <hash_set> & <hash_map>,
// and no <slist> at all
#else
# define BOOST_MSVC_STD_ITERATOR 1
# define BOOST_NO_STD_ITERATOR
# define BOOST_NO_TEMPLATED_ITERATOR_CONSTRUCTORS
# define BOOST_NO_STD_ALLOCATOR
# define BOOST_NO_STDC_NAMESPACE
# define BOOST_NO_STD_USE_FACET
# define BOOST_NO_STD_OUTPUT_ITERATOR_ASSIGN
# define BOOST_HAS_MACRO_USE_FACET
# ifndef _CPPLIB_VER
// Updated Dinkum library defines this, and provides
// its own min and max definitions, as does MTA version.
# ifndef __MTA__
# define BOOST_NO_STD_MIN_MAX
# endif
# define BOOST_NO_MS_INT64_NUMERIC_LIMITS
# endif
#endif
//
// std extension namespace is stdext for vc7.1 and later,
// the same applies to other compilers that sit on top
// of vc7.1 (Intel and Comeau):
//
#if defined(_MSC_VER) && (_MSC_VER >= 1310) && !defined(__BORLANDC__)
# define BOOST_STD_EXTENSION_NAMESPACE stdext
#endif
#if (defined(_MSC_VER) && (_MSC_VER <= 1300) && !defined(__BORLANDC__)) || !defined(_CPPLIB_VER) || (_CPPLIB_VER < 306)
// if we're using a dinkum lib that's
// been configured for VC6/7 then there is
// no iterator traits (true even for icl)
# define BOOST_NO_STD_ITERATOR_TRAITS
#endif
#if defined(__ICL) && (__ICL < 800) && defined(_CPPLIB_VER) && (_CPPLIB_VER <= 310)
// Intel C++ chokes over any non-trivial use of <locale>
// this may be an overly restrictive define, but regex fails without it:
# define BOOST_NO_STD_LOCALE
#endif
// Fix for VC++ 8.0 on up ( I do not have a previous version to test )
// or clang-cl. If exceptions are off you must manually include the
// <exception> header before including the <typeinfo> header. Admittedly
// trying to use Boost libraries or the standard C++ libraries without
// exception support is not suggested but currently clang-cl ( v 3.4 )
// does not support exceptions and must be compiled with exceptions off.
#if !_HAS_EXCEPTIONS && ((defined(BOOST_MSVC) && BOOST_MSVC >= 1400) || (defined(__clang__) && defined(_MSC_VER)))
#include <exception>
#endif
#include <typeinfo>
#if ( (!_HAS_EXCEPTIONS && !defined(__ghs__)) || (!_HAS_NAMESPACE && defined(__ghs__)) ) && !defined(__TI_COMPILER_VERSION__) && !defined(__VISUALDSPVERSION__)
# define BOOST_NO_STD_TYPEINFO
#endif
// C++0x headers implemented in 520 (as shipped by Microsoft)
//
#if !defined(_CPPLIB_VER) || _CPPLIB_VER < 520
# define BOOST_NO_CXX11_HDR_ARRAY
# define BOOST_NO_CXX11_HDR_CODECVT
# define BOOST_NO_CXX11_HDR_FORWARD_LIST
# define BOOST_NO_CXX11_HDR_INITIALIZER_LIST
# define BOOST_NO_CXX11_HDR_RANDOM
# define BOOST_NO_CXX11_HDR_REGEX
# define BOOST_NO_CXX11_HDR_SYSTEM_ERROR
# define BOOST_NO_CXX11_HDR_UNORDERED_MAP
# define BOOST_NO_CXX11_HDR_UNORDERED_SET
# define BOOST_NO_CXX11_HDR_TUPLE
# define BOOST_NO_CXX11_HDR_TYPEINDEX
# define BOOST_NO_CXX11_HDR_FUNCTIONAL
# define BOOST_NO_CXX11_NUMERIC_LIMITS
# define BOOST_NO_CXX11_SMART_PTR
#endif
#if ((!defined(_HAS_TR1_IMPORTS) || (_HAS_TR1_IMPORTS+0 == 0)) && !defined(BOOST_NO_CXX11_HDR_TUPLE)) \
&& (!defined(_CPPLIB_VER) || _CPPLIB_VER < 610)
# define BOOST_NO_CXX11_HDR_TUPLE
#endif
// C++0x headers implemented in 540 (as shipped by Microsoft)
//
#if !defined(_CPPLIB_VER) || _CPPLIB_VER < 540
# define BOOST_NO_CXX11_HDR_TYPE_TRAITS
# define BOOST_NO_CXX11_HDR_CHRONO
# define BOOST_NO_CXX11_HDR_CONDITION_VARIABLE
# define BOOST_NO_CXX11_HDR_FUTURE
# define BOOST_NO_CXX11_HDR_MUTEX
# define BOOST_NO_CXX11_HDR_RATIO
# define BOOST_NO_CXX11_HDR_THREAD
# define BOOST_NO_CXX11_ATOMIC_SMART_PTR
#endif
// C++0x headers implemented in 610 (as shipped by Microsoft)
//
#if !defined(_CPPLIB_VER) || _CPPLIB_VER < 610
# define BOOST_NO_CXX11_HDR_INITIALIZER_LIST
# define BOOST_NO_CXX11_HDR_ATOMIC
# define BOOST_NO_CXX11_ALLOCATOR
// 540 has std::align but it is not a conforming implementation
# define BOOST_NO_CXX11_STD_ALIGN
#endif
#if defined(__has_include)
#if !__has_include(<shared_mutex>)
# define BOOST_NO_CXX14_HDR_SHARED_MUTEX
#elif __cplusplus < 201402
# define BOOST_NO_CXX14_HDR_SHARED_MUTEX
#endif
#elif !defined(_CPPLIB_VER) || (_CPPLIB_VER < 650)
# define BOOST_NO_CXX14_HDR_SHARED_MUTEX
#endif
#if defined(BOOST_INTEL) && (BOOST_INTEL <= 1400)
// Intel's compiler can't handle this header yet:
# define BOOST_NO_CXX11_HDR_ATOMIC
#endif
// 520..610 have std::addressof, but it doesn't support functions
//
#if !defined(_CPPLIB_VER) || _CPPLIB_VER < 650
# define BOOST_NO_CXX11_ADDRESSOF
#endif
// Bug specific to VC14,
// See https://connect.microsoft.com/VisualStudio/feedback/details/1348277/link-error-when-using-std-codecvt-utf8-utf16-char16-t
// and discussion here: http://blogs.msdn.com/b/vcblog/archive/2014/11/12/visual-studio-2015-preview-now-available.aspx?PageIndex=2
#if defined(_CPPLIB_VER) && (_CPPLIB_VER == 650)
# define BOOST_NO_CXX11_HDR_CODECVT
#endif
#if defined(_CPPLIB_VER) && (_CPPLIB_VER >= 650)
// If _HAS_AUTO_PTR_ETC is defined to 0, std::auto_ptr is not available.
// See https://www.visualstudio.com/en-us/news/vs2015-vs.aspx#C++
// and http://blogs.msdn.com/b/vcblog/archive/2015/06/19/c-11-14-17-features-in-vs-2015-rtm.aspx
# if defined(_HAS_AUTO_PTR_ETC) && (_HAS_AUTO_PTR_ETC == 0)
# define BOOST_NO_AUTO_PTR
# endif
#endif
#ifdef _CPPLIB_VER
# define BOOST_DINKUMWARE_STDLIB _CPPLIB_VER
#else
# define BOOST_DINKUMWARE_STDLIB 1
#endif
#ifdef _CPPLIB_VER
# define BOOST_STDLIB "Dinkumware standard library version " BOOST_STRINGIZE(_CPPLIB_VER)
#else
# define BOOST_STDLIB "Dinkumware standard library version 1.x"
#endif
| {
"pile_set_name": "Github"
} |
export const meta = {
title: "prisma logout",
position: 250,
}
## `$ prisma logout`
Logout from [Prisma Cloud](https://www.prisma.io/cloud).
This command simply deletes the `cloudSessionKey` from `~/.prisma/config.yml`.
### Usage
```sh
prisma logout
```
### Examples
**Log out of Prisma Cloud**
```sh
prisma logout
```
| {
"pile_set_name": "Github"
} |
require 'spec_helper'
describe CardsHelper do
before do
class << helper
include Haml, Haml::Helpers
end
helper.init_haml_helpers
end
describe "#card_classes" do
it "returns an array of structural class names for the given properties" do
result = helper.card_classes(
tall_listing?: true,
double?: true,
cover?: true,
kind: "article"
)
result.should include("card--list--tall")
result.should include("card--column--tall")
result.should include("card--column--double")
result.should include("card--cover")
result.should include("card--article")
result = helper.card_classes(
short?: true,
cover?: true,
fixed?: true
)
result.should include("card--list--short")
result.should include("card--column--single")
result.should include("card--column--short")
result.should include("card--fixed")
end
describe "returns an array of content class names for the given properties" do
it "should add 'has' class names when given content" do
result = helper.card_classes(
image_url: "path/to/image",
author_name: "Joe Bloggs",
price_tag: {
price: 123,
currency: "£"
}
)
result.should include("card--has-img")
result.should include("card--has-footer")
result.should include("card--has-price")
end
it "should add 'no' class names when given no content" do
result = helper.card_classes(
image_url: nil,
meta_description: nil
)
result.should include("card--no-img")
result.should include("card--no-footer")
result.should include("card--no-price")
end
end
end
describe "#card_href_for_test_variation" do
let(:var) { nil }
let(:url) { "/path/to/thing" }
let(:props) { { url: url } }
context "with no variation" do
it "returns the original URL" do
result = helper.card_href_for_test_variation(props, var)
result.should eq(url)
end
end
context "with test variation" do
let(:var) { 1 }
context "when the URL has no QS" do
it "returns the URL appended with variation" do
result = helper.card_href_for_test_variation(props, var)
result.should eq("#{url}?ctv=1")
end
end
context "when the URL has a QS" do
let(:url) { "/path/to/thing?foo=bar" }
it "returns the URL appended with variation" do
result = helper.card_href_for_test_variation(props, var)
result.should eq("#{url}&ctv=1")
end
end
end
end
describe "#card_link_data" do
let(:tracking_data) { { category: "lodgings" } }
let(:lightbox_data) { { lightbox: true } }
before(:each) do
helper.stub(:card_tracking_data).and_return(tracking_data)
helper.stub(:card_layer_data).and_return(lightbox_data)
end
it "should return tracking and lightbox data" do
result = helper.card_link_data({})
result.should eq(
:category => tracking_data[:category],
:lightbox => lightbox_data[:lightbox]
)
end
end
describe "#card_tracking_data" do
let(:tracking_data) do
{
category: "lodgings",
action: "view",
label: "/path/to/lodging"
}
end
it "should return properties for given tracking hash" do
result = helper.card_tracking_data(tracking: tracking_data)
result.should eq(
lpa_category: tracking_data[:category],
lpa_action: tracking_data[:action],
lpa_label: tracking_data[:label]
)
end
end
describe "#card_link_if" do
let(:link_url) { "path/to/thing" }
it "should return an anchor element with given properties if condition is true" do
result = helper.capture_haml do
helper.card_link_if(true, href: link_url) {}
end
result.should eq "<a href='#{link_url}'>\n</a>\n"
end
end
describe "#card_grid_helper" do
describe "returns a list of class names" do
context "for a single width card" do
it "adds single column classes" do
result = helper.card_grid_helper()
result.should include("col--one-whole")
result.should include("nv--col--one-half")
result.should include("mv--col--one-third")
result.should include("lv--col--one-quarter")
result.should include("wv--col--one-fifth")
end
end
context "for a double width card" do
it "adds multiple column classes" do
result = helper.card_grid_helper(is_double: true)
result.should include("col--one-whole")
result.should include("mv--col--two-thirds")
result.should include("lv--col--one-half")
result.should include("wv--col--two-fifths")
end
end
context "for an MPU card" do
it "adds multiple column classes and right modifier" do
result = helper.card_grid_helper(is_mpu: true)
result.should include("col--right")
result.should include("col--one-whole")
result.should include("mv--col--two-thirds")
result.should include("lv--col--one-half")
result.should include("wv--col--two-fifths")
end
end
end
describe "adds clear left classes to correct cards" do
context "for the third card" do
it "adds a clear for narrow view" do
result = helper.card_grid_helper(card_index: 2, reset: true)
result.should include("nv--clear")
result.should_not include("mv--clear")
result.should_not include("lv--clear")
result.should_not include("wv--clear")
end
end
context "for the fourth card" do
it "adds a clear for medium view" do
result = helper.card_grid_helper(card_index: 3, reset: true)
result.should_not include("nv--clear")
result.should include("mv--clear")
result.should_not include("lv--clear")
result.should_not include("wv--clear")
end
end
context "for the fifth card" do
it "adds a clear for narrow and large views" do
result = helper.card_grid_helper(card_index: 4, reset: true)
result.should include("nv--clear")
result.should_not include("mv--clear")
result.should include("lv--clear")
result.should_not include("wv--clear")
end
end
context "for the sixth card" do
it "adds a clear for wide view" do
result = helper.card_grid_helper(card_index: 5, reset: true)
result.should_not include("nv--clear")
result.should include("wv--clear")
result.should_not include("mv--clear")
result.should_not include("lv--clear")
end
end
context "for the seventh card" do
it "adds a clear for narrow, medium and cinema views" do
result = helper.card_grid_helper(card_index: 6, reset: true)
result.should include("nv--clear")
result.should include("mv--clear")
result.should_not include("lv--clear")
result.should_not include("wv--clear")
end
end
context "when using rows" do
it "hides the 5th card for wide views" do
result = helper.card_grid_helper(card_index: 4, reset: true, is_row: true)
result.should include("wv--hide")
end
end
context "with ad rail" do
context "for a double width card" do
it "adds multiple column classes" do
result = helper.card_grid_helper(is_double: true, reset: true, has_rail: true)
result.should include("col--one-whole")
result.should include("mv--col--two-thirds")
result.should include("lv--col--one-half")
result.should include("wv--col--two-thirds")
result.should include("cv--col--one-half")
end
end
context "for the fourth card" do
it "adds a clear for medium view" do
result = helper.card_grid_helper(card_index: 3, reset: true, has_rail: true)
result.should_not include("nv--clear")
result.should include("mv--clear")
result.should_not include("lv--clear")
result.should include("wv--clear")
result.should_not include("cv--clear")
end
end
context "for the fifth card" do
it "adds a clear for narrow and large views" do
result = helper.card_grid_helper(card_index: 4, reset: true, has_rail: true)
result.should include("nv--clear")
result.should_not include("mv--clear")
result.should include("lv--clear")
result.should_not include("wv--clear")
result.should include("cv--clear")
end
end
context "when using rows" do
it "hides the 4th card for wide views" do
result = helper.card_grid_helper(card_index: 3, reset: true, has_rail: true, is_row: true)
result.should include("mv--hide wv--hide")
end
end
end
end
end
end
| {
"pile_set_name": "Github"
} |
/* A Bison parser, made by GNU Bison 2.4.1. */
/* Skeleton implementation for Bison's Yacc-like parsers in C
Copyright (C) 1984, 1989, 1990, 2000, 2001, 2002, 2003, 2004, 2005, 2006
Free Software Foundation, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* As a special exception, you may create a larger work that contains
part or all of the Bison parser skeleton and distribute that work
under terms of your choice, so long as that work isn't itself a
parser generator using the skeleton or a modified version thereof
as a parser skeleton. Alternatively, if you modify or redistribute
the parser skeleton itself, you may (at your option) remove this
special exception, which will cause the skeleton and the resulting
Bison output files to be licensed under the GNU General Public
License without this special exception.
This special exception was added by the Free Software Foundation in
version 2.2 of Bison. */
/* C LALR(1) parser skeleton written by Richard Stallman, by
simplifying the original so-called "semantic" parser. */
/* All symbols defined below should begin with yy or YY, to avoid
infringing on user name space. This should be done even for local
variables, as they might otherwise be expanded by user macros.
There are some unavoidable exceptions within include files to
define necessary library symbols; they are noted "INFRINGES ON
USER NAME SPACE" below. */
/* Identify Bison output. */
#define YYBISON 1
/* Bison version. */
#define YYBISON_VERSION "2.4.1"
/* Skeleton name. */
#define YYSKELETON_NAME "yacc.c"
/* Pure parsers. */
#define YYPURE 0
/* Push parsers. */
#define YYPUSH 0
/* Pull parsers. */
#define YYPULL 1
/* Using locations. */
#define YYLSP_NEEDED 0
/* Copy the first part of user declarations. */
/* Line 189 of yacc.c */
#line 21 "dtc-parser.y"
#include <stdio.h>
#include "dtc.h"
#include "srcpos.h"
YYLTYPE yylloc;
extern int yylex(void);
extern void print_error(char const *fmt, ...);
extern void yyerror(char const *s);
extern struct boot_info *the_boot_info;
extern int treesource_error;
static unsigned long long eval_literal(const char *s, int base, int bits);
static unsigned char eval_char_literal(const char *s);
/* Line 189 of yacc.c */
#line 93 "dtc-parser.tab.c"
/* Enabling traces. */
#ifndef YYDEBUG
# define YYDEBUG 0
#endif
/* Enabling verbose error messages. */
#ifdef YYERROR_VERBOSE
# undef YYERROR_VERBOSE
# define YYERROR_VERBOSE 1
#else
# define YYERROR_VERBOSE 0
#endif
/* Enabling the token table. */
#ifndef YYTOKEN_TABLE
# define YYTOKEN_TABLE 0
#endif
/* Tokens. */
#ifndef YYTOKENTYPE
# define YYTOKENTYPE
/* Put the tokens into the symbol table, so that GDB and other debuggers
know about them. */
enum yytokentype {
DT_V1 = 258,
DT_MEMRESERVE = 259,
DT_LSHIFT = 260,
DT_RSHIFT = 261,
DT_LE = 262,
DT_GE = 263,
DT_EQ = 264,
DT_NE = 265,
DT_AND = 266,
DT_OR = 267,
DT_BITS = 268,
DT_DEL_PROP = 269,
DT_DEL_NODE = 270,
DT_PROPNODENAME = 271,
DT_LITERAL = 272,
DT_CHAR_LITERAL = 273,
DT_BASE = 274,
DT_BYTE = 275,
DT_STRING = 276,
DT_LABEL = 277,
DT_REF = 278,
DT_INCBIN = 279
};
#endif
#if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED
typedef union YYSTYPE
{
/* Line 214 of yacc.c */
#line 40 "dtc-parser.y"
char *propnodename;
char *literal;
char *labelref;
unsigned int cbase;
uint8_t byte;
struct data data;
struct {
struct data data;
int bits;
} array;
struct property *prop;
struct property *proplist;
struct node *node;
struct node *nodelist;
struct reserve_info *re;
uint64_t integer;
/* Line 214 of yacc.c */
#line 176 "dtc-parser.tab.c"
} YYSTYPE;
# define YYSTYPE_IS_TRIVIAL 1
# define yystype YYSTYPE /* obsolescent; will be withdrawn */
# define YYSTYPE_IS_DECLARED 1
#endif
/* Copy the second part of user declarations. */
/* Line 264 of yacc.c */
#line 188 "dtc-parser.tab.c"
#ifdef short
# undef short
#endif
#ifdef YYTYPE_UINT8
typedef YYTYPE_UINT8 yytype_uint8;
#else
typedef unsigned char yytype_uint8;
#endif
#ifdef YYTYPE_INT8
typedef YYTYPE_INT8 yytype_int8;
#elif (defined __STDC__ || defined __C99__FUNC__ \
|| defined __cplusplus || defined _MSC_VER)
typedef signed char yytype_int8;
#else
typedef short int yytype_int8;
#endif
#ifdef YYTYPE_UINT16
typedef YYTYPE_UINT16 yytype_uint16;
#else
typedef unsigned short int yytype_uint16;
#endif
#ifdef YYTYPE_INT16
typedef YYTYPE_INT16 yytype_int16;
#else
typedef short int yytype_int16;
#endif
#ifndef YYSIZE_T
# ifdef __SIZE_TYPE__
# define YYSIZE_T __SIZE_TYPE__
# elif defined size_t
# define YYSIZE_T size_t
# elif ! defined YYSIZE_T && (defined __STDC__ || defined __C99__FUNC__ \
|| defined __cplusplus || defined _MSC_VER)
# include <stddef.h> /* INFRINGES ON USER NAME SPACE */
# define YYSIZE_T size_t
# else
# define YYSIZE_T unsigned int
# endif
#endif
#define YYSIZE_MAXIMUM ((YYSIZE_T) -1)
#ifndef YY_
# if YYENABLE_NLS
# if ENABLE_NLS
# include <libintl.h> /* INFRINGES ON USER NAME SPACE */
# define YY_(msgid) dgettext ("bison-runtime", msgid)
# endif
# endif
# ifndef YY_
# define YY_(msgid) msgid
# endif
#endif
/* Suppress unused-variable warnings by "using" E. */
#if ! defined lint || defined __GNUC__
# define YYUSE(e) ((void) (e))
#else
# define YYUSE(e) /* empty */
#endif
/* Identity function, used to suppress warnings about constant conditions. */
#ifndef lint
# define YYID(n) (n)
#else
#if (defined __STDC__ || defined __C99__FUNC__ \
|| defined __cplusplus || defined _MSC_VER)
static int
YYID (int yyi)
#else
static int
YYID (yyi)
int yyi;
#endif
{
return yyi;
}
#endif
#if ! defined yyoverflow || YYERROR_VERBOSE
/* The parser invokes alloca or malloc; define the necessary symbols. */
# ifdef YYSTACK_USE_ALLOCA
# if YYSTACK_USE_ALLOCA
# ifdef __GNUC__
# define YYSTACK_ALLOC __builtin_alloca
# elif defined __BUILTIN_VA_ARG_INCR
# include <alloca.h> /* INFRINGES ON USER NAME SPACE */
# elif defined _AIX
# define YYSTACK_ALLOC __alloca
# elif defined _MSC_VER
# include <malloc.h> /* INFRINGES ON USER NAME SPACE */
# define alloca _alloca
# else
# define YYSTACK_ALLOC alloca
# if ! defined _ALLOCA_H && ! defined _STDLIB_H && (defined __STDC__ || defined __C99__FUNC__ \
|| defined __cplusplus || defined _MSC_VER)
# include <stdlib.h> /* INFRINGES ON USER NAME SPACE */
# ifndef _STDLIB_H
# define _STDLIB_H 1
# endif
# endif
# endif
# endif
# endif
# ifdef YYSTACK_ALLOC
/* Pacify GCC's `empty if-body' warning. */
# define YYSTACK_FREE(Ptr) do { /* empty */; } while (YYID (0))
# ifndef YYSTACK_ALLOC_MAXIMUM
/* The OS might guarantee only one guard page at the bottom of the stack,
and a page size can be as small as 4096 bytes. So we cannot safely
invoke alloca (N) if N exceeds 4096. Use a slightly smaller number
to allow for a few compiler-allocated temporary stack slots. */
# define YYSTACK_ALLOC_MAXIMUM 4032 /* reasonable circa 2006 */
# endif
# else
# define YYSTACK_ALLOC YYMALLOC
# define YYSTACK_FREE YYFREE
# ifndef YYSTACK_ALLOC_MAXIMUM
# define YYSTACK_ALLOC_MAXIMUM YYSIZE_MAXIMUM
# endif
# if (defined __cplusplus && ! defined _STDLIB_H \
&& ! ((defined YYMALLOC || defined malloc) \
&& (defined YYFREE || defined free)))
# include <stdlib.h> /* INFRINGES ON USER NAME SPACE */
# ifndef _STDLIB_H
# define _STDLIB_H 1
# endif
# endif
# ifndef YYMALLOC
# define YYMALLOC malloc
# if ! defined malloc && ! defined _STDLIB_H && (defined __STDC__ || defined __C99__FUNC__ \
|| defined __cplusplus || defined _MSC_VER)
void *malloc (YYSIZE_T); /* INFRINGES ON USER NAME SPACE */
# endif
# endif
# ifndef YYFREE
# define YYFREE free
# if ! defined free && ! defined _STDLIB_H && (defined __STDC__ || defined __C99__FUNC__ \
|| defined __cplusplus || defined _MSC_VER)
void free (void *); /* INFRINGES ON USER NAME SPACE */
# endif
# endif
# endif
#endif /* ! defined yyoverflow || YYERROR_VERBOSE */
#if (! defined yyoverflow \
&& (! defined __cplusplus \
|| (defined YYSTYPE_IS_TRIVIAL && YYSTYPE_IS_TRIVIAL)))
/* A type that is properly aligned for any stack member. */
union yyalloc
{
yytype_int16 yyss_alloc;
YYSTYPE yyvs_alloc;
};
/* The size of the maximum gap between one aligned stack and the next. */
# define YYSTACK_GAP_MAXIMUM (sizeof (union yyalloc) - 1)
/* The size of an array large to enough to hold all stacks, each with
N elements. */
# define YYSTACK_BYTES(N) \
((N) * (sizeof (yytype_int16) + sizeof (YYSTYPE)) \
+ YYSTACK_GAP_MAXIMUM)
/* Copy COUNT objects from FROM to TO. The source and destination do
not overlap. */
# ifndef YYCOPY
# if defined __GNUC__ && 1 < __GNUC__
# define YYCOPY(To, From, Count) \
__builtin_memcpy (To, From, (Count) * sizeof (*(From)))
# else
# define YYCOPY(To, From, Count) \
do \
{ \
YYSIZE_T yyi; \
for (yyi = 0; yyi < (Count); yyi++) \
(To)[yyi] = (From)[yyi]; \
} \
while (YYID (0))
# endif
# endif
/* Relocate STACK from its old location to the new one. The
local variables YYSIZE and YYSTACKSIZE give the old and new number of
elements in the stack, and YYPTR gives the new location of the
stack. Advance YYPTR to a properly aligned location for the next
stack. */
# define YYSTACK_RELOCATE(Stack_alloc, Stack) \
do \
{ \
YYSIZE_T yynewbytes; \
YYCOPY (&yyptr->Stack_alloc, Stack, yysize); \
Stack = &yyptr->Stack_alloc; \
yynewbytes = yystacksize * sizeof (*Stack) + YYSTACK_GAP_MAXIMUM; \
yyptr += yynewbytes / sizeof (*yyptr); \
} \
while (YYID (0))
#endif
/* YYFINAL -- State number of the termination state. */
#define YYFINAL 4
/* YYLAST -- Last index in YYTABLE. */
#define YYLAST 133
/* YYNTOKENS -- Number of terminals. */
#define YYNTOKENS 48
/* YYNNTS -- Number of nonterminals. */
#define YYNNTS 28
/* YYNRULES -- Number of rules. */
#define YYNRULES 79
/* YYNRULES -- Number of states. */
#define YYNSTATES 141
/* YYTRANSLATE(YYLEX) -- Bison symbol number corresponding to YYLEX. */
#define YYUNDEFTOK 2
#define YYMAXUTOK 279
#define YYTRANSLATE(YYX) \
((unsigned int) (YYX) <= YYMAXUTOK ? yytranslate[YYX] : YYUNDEFTOK)
/* YYTRANSLATE[YYLEX] -- Bison symbol number corresponding to YYLEX. */
static const yytype_uint8 yytranslate[] =
{
0, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 47, 2, 2, 2, 45, 41, 2,
33, 35, 44, 42, 34, 43, 2, 26, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 38, 25,
36, 29, 30, 37, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 31, 2, 32, 40, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 27, 39, 28, 46, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 1, 2, 3, 4,
5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24
};
#if YYDEBUG
/* YYPRHS[YYN] -- Index of the first RHS symbol of rule number YYN in
YYRHS. */
static const yytype_uint16 yyprhs[] =
{
0, 0, 3, 8, 9, 12, 17, 20, 23, 27,
31, 36, 42, 43, 46, 51, 54, 58, 61, 64,
68, 73, 76, 86, 92, 95, 96, 99, 102, 106,
108, 111, 114, 117, 119, 121, 125, 127, 129, 135,
137, 141, 143, 147, 149, 153, 155, 159, 161, 165,
167, 171, 175, 177, 181, 185, 189, 193, 197, 201,
203, 207, 211, 213, 217, 221, 225, 227, 229, 232,
235, 238, 239, 242, 245, 246, 249, 252, 255, 259
};
/* YYRHS -- A `-1'-separated list of the rules' RHS. */
static const yytype_int8 yyrhs[] =
{
49, 0, -1, 3, 25, 50, 52, -1, -1, 51,
50, -1, 4, 59, 59, 25, -1, 22, 51, -1,
26, 53, -1, 52, 26, 53, -1, 52, 23, 53,
-1, 52, 15, 23, 25, -1, 27, 54, 74, 28,
25, -1, -1, 54, 55, -1, 16, 29, 56, 25,
-1, 16, 25, -1, 14, 16, 25, -1, 22, 55,
-1, 57, 21, -1, 57, 58, 30, -1, 57, 31,
73, 32, -1, 57, 23, -1, 57, 24, 33, 21,
34, 59, 34, 59, 35, -1, 57, 24, 33, 21,
35, -1, 56, 22, -1, -1, 56, 34, -1, 57,
22, -1, 13, 17, 36, -1, 36, -1, 58, 59,
-1, 58, 23, -1, 58, 22, -1, 17, -1, 18,
-1, 33, 60, 35, -1, 61, -1, 62, -1, 62,
37, 60, 38, 61, -1, 63, -1, 62, 12, 63,
-1, 64, -1, 63, 11, 64, -1, 65, -1, 64,
39, 65, -1, 66, -1, 65, 40, 66, -1, 67,
-1, 66, 41, 67, -1, 68, -1, 67, 9, 68,
-1, 67, 10, 68, -1, 69, -1, 68, 36, 69,
-1, 68, 30, 69, -1, 68, 7, 69, -1, 68,
8, 69, -1, 69, 5, 70, -1, 69, 6, 70,
-1, 70, -1, 70, 42, 71, -1, 70, 43, 71,
-1, 71, -1, 71, 44, 72, -1, 71, 26, 72,
-1, 71, 45, 72, -1, 72, -1, 59, -1, 43,
72, -1, 46, 72, -1, 47, 72, -1, -1, 73,
20, -1, 73, 22, -1, -1, 75, 74, -1, 75,
55, -1, 16, 53, -1, 15, 16, 25, -1, 22,
75, -1
};
/* YYRLINE[YYN] -- source line where rule number YYN was defined. */
static const yytype_uint16 yyrline[] =
{
0, 109, 109, 118, 121, 128, 132, 140, 144, 148,
158, 172, 180, 183, 190, 194, 198, 202, 210, 214,
218, 222, 226, 243, 253, 261, 264, 268, 275, 290,
295, 315, 329, 336, 340, 344, 351, 355, 356, 360,
361, 365, 366, 370, 371, 375, 376, 380, 381, 385,
386, 387, 391, 392, 393, 394, 395, 399, 400, 401,
405, 406, 407, 411, 412, 413, 414, 418, 419, 420,
421, 426, 429, 433, 441, 444, 448, 456, 460, 464
};
#endif
#if YYDEBUG || YYERROR_VERBOSE || YYTOKEN_TABLE
/* YYTNAME[SYMBOL-NUM] -- String name of the symbol SYMBOL-NUM.
First, the terminals, then, starting at YYNTOKENS, nonterminals. */
static const char *const yytname[] =
{
"$end", "error", "$undefined", "DT_V1", "DT_MEMRESERVE", "DT_LSHIFT",
"DT_RSHIFT", "DT_LE", "DT_GE", "DT_EQ", "DT_NE", "DT_AND", "DT_OR",
"DT_BITS", "DT_DEL_PROP", "DT_DEL_NODE", "DT_PROPNODENAME", "DT_LITERAL",
"DT_CHAR_LITERAL", "DT_BASE", "DT_BYTE", "DT_STRING", "DT_LABEL",
"DT_REF", "DT_INCBIN", "';'", "'/'", "'{'", "'}'", "'='", "'>'", "'['",
"']'", "'('", "','", "')'", "'<'", "'?'", "':'", "'|'", "'^'", "'&'",
"'+'", "'-'", "'*'", "'%'", "'~'", "'!'", "$accept", "sourcefile",
"memreserves", "memreserve", "devicetree", "nodedef", "proplist",
"propdef", "propdata", "propdataprefix", "arrayprefix", "integer_prim",
"integer_expr", "integer_trinary", "integer_or", "integer_and",
"integer_bitor", "integer_bitxor", "integer_bitand", "integer_eq",
"integer_rela", "integer_shift", "integer_add", "integer_mul",
"integer_unary", "bytestring", "subnodes", "subnode", 0
};
#endif
# ifdef YYPRINT
/* YYTOKNUM[YYLEX-NUM] -- Internal token number corresponding to
token YYLEX-NUM. */
static const yytype_uint16 yytoknum[] =
{
0, 256, 257, 258, 259, 260, 261, 262, 263, 264,
265, 266, 267, 268, 269, 270, 271, 272, 273, 274,
275, 276, 277, 278, 279, 59, 47, 123, 125, 61,
62, 91, 93, 40, 44, 41, 60, 63, 58, 124,
94, 38, 43, 45, 42, 37, 126, 33
};
# endif
/* YYR1[YYN] -- Symbol number of symbol that rule YYN derives. */
static const yytype_uint8 yyr1[] =
{
0, 48, 49, 50, 50, 51, 51, 52, 52, 52,
52, 53, 54, 54, 55, 55, 55, 55, 56, 56,
56, 56, 56, 56, 56, 57, 57, 57, 58, 58,
58, 58, 58, 59, 59, 59, 60, 61, 61, 62,
62, 63, 63, 64, 64, 65, 65, 66, 66, 67,
67, 67, 68, 68, 68, 68, 68, 69, 69, 69,
70, 70, 70, 71, 71, 71, 71, 72, 72, 72,
72, 73, 73, 73, 74, 74, 74, 75, 75, 75
};
/* YYR2[YYN] -- Number of symbols composing right hand side of rule YYN. */
static const yytype_uint8 yyr2[] =
{
0, 2, 4, 0, 2, 4, 2, 2, 3, 3,
4, 5, 0, 2, 4, 2, 3, 2, 2, 3,
4, 2, 9, 5, 2, 0, 2, 2, 3, 1,
2, 2, 2, 1, 1, 3, 1, 1, 5, 1,
3, 1, 3, 1, 3, 1, 3, 1, 3, 1,
3, 3, 1, 3, 3, 3, 3, 3, 3, 1,
3, 3, 1, 3, 3, 3, 1, 1, 2, 2,
2, 0, 2, 2, 0, 2, 2, 2, 3, 2
};
/* YYDEFACT[STATE-NAME] -- Default rule to reduce with in state
STATE-NUM when YYTABLE doesn't specify something else to do. Zero
means the default is an error. */
static const yytype_uint8 yydefact[] =
{
0, 0, 0, 3, 1, 0, 0, 0, 3, 33,
34, 0, 0, 6, 0, 2, 4, 0, 0, 0,
67, 0, 36, 37, 39, 41, 43, 45, 47, 49,
52, 59, 62, 66, 0, 12, 7, 0, 0, 0,
68, 69, 70, 35, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 5, 74, 0, 9, 8, 40, 0,
42, 44, 46, 48, 50, 51, 55, 56, 54, 53,
57, 58, 60, 61, 64, 63, 65, 0, 0, 0,
0, 13, 0, 74, 10, 0, 0, 0, 15, 25,
77, 17, 79, 0, 76, 75, 38, 16, 78, 0,
0, 11, 24, 14, 26, 0, 18, 27, 21, 0,
71, 29, 0, 0, 0, 0, 32, 31, 19, 30,
28, 0, 72, 73, 20, 0, 23, 0, 0, 0,
22
};
/* YYDEFGOTO[NTERM-NUM]. */
static const yytype_int8 yydefgoto[] =
{
-1, 2, 7, 8, 15, 36, 64, 91, 109, 110,
122, 20, 21, 22, 23, 24, 25, 26, 27, 28,
29, 30, 31, 32, 33, 125, 92, 93
};
/* YYPACT[STATE-NUM] -- Index in YYTABLE of the portion describing
STATE-NUM. */
#define YYPACT_NINF -78
static const yytype_int8 yypact[] =
{
22, 11, 51, 10, -78, 23, 10, 2, 10, -78,
-78, -9, 23, -78, 30, 38, -78, -9, -9, -9,
-78, 35, -78, -6, 52, 29, 48, 49, 33, 3,
71, 36, 0, -78, 64, -78, -78, 68, 30, 30,
-78, -78, -78, -78, -9, -9, -9, -9, -9, -9,
-9, -9, -9, -9, -9, -9, -9, -9, -9, -9,
-9, -9, -9, -78, 44, 67, -78, -78, 52, 55,
29, 48, 49, 33, 3, 3, 71, 71, 71, 71,
36, 36, 0, 0, -78, -78, -78, 78, 79, 42,
44, -78, 69, 44, -78, -9, 73, 74, -78, -78,
-78, -78, -78, 75, -78, -78, -78, -78, -78, -7,
-1, -78, -78, -78, -78, 84, -78, -78, -78, 63,
-78, -78, 32, 66, 82, -3, -78, -78, -78, -78,
-78, 46, -78, -78, -78, 23, -78, 70, 23, 72,
-78
};
/* YYPGOTO[NTERM-NUM]. */
static const yytype_int8 yypgoto[] =
{
-78, -78, 97, 100, -78, -37, -78, -77, -78, -78,
-78, -5, 65, 13, -78, 76, 77, 62, 80, 83,
34, 20, 26, 28, -14, -78, 18, 24
};
/* YYTABLE[YYPACT[STATE-NUM]]. What to do in state STATE-NUM. If
positive, shift that token. If negative, reduce the rule which
number is the opposite. If zero, do what YYDEFACT says.
If YYTABLE_NINF, syntax error. */
#define YYTABLE_NINF -1
static const yytype_uint8 yytable[] =
{
12, 66, 67, 40, 41, 42, 44, 34, 9, 10,
52, 53, 115, 101, 5, 112, 104, 132, 113, 133,
116, 117, 118, 119, 11, 1, 60, 114, 14, 134,
120, 45, 6, 54, 17, 121, 3, 18, 19, 55,
9, 10, 50, 51, 61, 62, 84, 85, 86, 9,
10, 4, 100, 37, 126, 127, 11, 35, 87, 88,
89, 38, 128, 46, 39, 11, 90, 98, 47, 35,
43, 99, 76, 77, 78, 79, 56, 57, 58, 59,
135, 136, 80, 81, 74, 75, 82, 83, 48, 63,
49, 65, 94, 95, 96, 97, 124, 103, 107, 108,
111, 123, 130, 131, 138, 16, 13, 140, 106, 71,
69, 105, 0, 0, 102, 0, 0, 129, 0, 0,
68, 0, 0, 70, 0, 0, 0, 0, 72, 0,
137, 0, 73, 139
};
static const yytype_int16 yycheck[] =
{
5, 38, 39, 17, 18, 19, 12, 12, 17, 18,
7, 8, 13, 90, 4, 22, 93, 20, 25, 22,
21, 22, 23, 24, 33, 3, 26, 34, 26, 32,
31, 37, 22, 30, 43, 36, 25, 46, 47, 36,
17, 18, 9, 10, 44, 45, 60, 61, 62, 17,
18, 0, 89, 15, 22, 23, 33, 27, 14, 15,
16, 23, 30, 11, 26, 33, 22, 25, 39, 27,
35, 29, 52, 53, 54, 55, 5, 6, 42, 43,
34, 35, 56, 57, 50, 51, 58, 59, 40, 25,
41, 23, 25, 38, 16, 16, 33, 28, 25, 25,
25, 17, 36, 21, 34, 8, 6, 35, 95, 47,
45, 93, -1, -1, 90, -1, -1, 122, -1, -1,
44, -1, -1, 46, -1, -1, -1, -1, 48, -1,
135, -1, 49, 138
};
/* YYSTOS[STATE-NUM] -- The (internal number of the) accessing
symbol of state STATE-NUM. */
static const yytype_uint8 yystos[] =
{
0, 3, 49, 25, 0, 4, 22, 50, 51, 17,
18, 33, 59, 51, 26, 52, 50, 43, 46, 47,
59, 60, 61, 62, 63, 64, 65, 66, 67, 68,
69, 70, 71, 72, 59, 27, 53, 15, 23, 26,
72, 72, 72, 35, 12, 37, 11, 39, 40, 41,
9, 10, 7, 8, 30, 36, 5, 6, 42, 43,
26, 44, 45, 25, 54, 23, 53, 53, 63, 60,
64, 65, 66, 67, 68, 68, 69, 69, 69, 69,
70, 70, 71, 71, 72, 72, 72, 14, 15, 16,
22, 55, 74, 75, 25, 38, 16, 16, 25, 29,
53, 55, 75, 28, 55, 74, 61, 25, 25, 56,
57, 25, 22, 25, 34, 13, 21, 22, 23, 24,
31, 36, 58, 17, 33, 73, 22, 23, 30, 59,
36, 21, 20, 22, 32, 34, 35, 59, 34, 59,
35
};
#define yyerrok (yyerrstatus = 0)
#define yyclearin (yychar = YYEMPTY)
#define YYEMPTY (-2)
#define YYEOF 0
#define YYACCEPT goto yyacceptlab
#define YYABORT goto yyabortlab
#define YYERROR goto yyerrorlab
/* Like YYERROR except do call yyerror. This remains here temporarily
to ease the transition to the new meaning of YYERROR, for GCC.
Once GCC version 2 has supplanted version 1, this can go. */
#define YYFAIL goto yyerrlab
#define YYRECOVERING() (!!yyerrstatus)
#define YYBACKUP(Token, Value) \
do \
if (yychar == YYEMPTY && yylen == 1) \
{ \
yychar = (Token); \
yylval = (Value); \
yytoken = YYTRANSLATE (yychar); \
YYPOPSTACK (1); \
goto yybackup; \
} \
else \
{ \
yyerror (YY_("syntax error: cannot back up")); \
YYERROR; \
} \
while (YYID (0))
#define YYTERROR 1
#define YYERRCODE 256
/* YYLLOC_DEFAULT -- Set CURRENT to span from RHS[1] to RHS[N].
If N is 0, then set CURRENT to the empty location which ends
the previous symbol: RHS[0] (always defined). */
#define YYRHSLOC(Rhs, K) ((Rhs)[K])
#ifndef YYLLOC_DEFAULT
# define YYLLOC_DEFAULT(Current, Rhs, N) \
do \
if (YYID (N)) \
{ \
(Current).first_line = YYRHSLOC (Rhs, 1).first_line; \
(Current).first_column = YYRHSLOC (Rhs, 1).first_column; \
(Current).last_line = YYRHSLOC (Rhs, N).last_line; \
(Current).last_column = YYRHSLOC (Rhs, N).last_column; \
} \
else \
{ \
(Current).first_line = (Current).last_line = \
YYRHSLOC (Rhs, 0).last_line; \
(Current).first_column = (Current).last_column = \
YYRHSLOC (Rhs, 0).last_column; \
} \
while (YYID (0))
#endif
/* YY_LOCATION_PRINT -- Print the location on the stream.
This macro was not mandated originally: define only if we know
we won't break user code: when these are the locations we know. */
#ifndef YY_LOCATION_PRINT
# if YYLTYPE_IS_TRIVIAL
# define YY_LOCATION_PRINT(File, Loc) \
fprintf (File, "%d.%d-%d.%d", \
(Loc).first_line, (Loc).first_column, \
(Loc).last_line, (Loc).last_column)
# else
# define YY_LOCATION_PRINT(File, Loc) ((void) 0)
# endif
#endif
/* YYLEX -- calling `yylex' with the right arguments. */
#ifdef YYLEX_PARAM
# define YYLEX yylex (YYLEX_PARAM)
#else
# define YYLEX yylex ()
#endif
/* Enable debugging if requested. */
#if YYDEBUG
# ifndef YYFPRINTF
# include <stdio.h> /* INFRINGES ON USER NAME SPACE */
# define YYFPRINTF fprintf
# endif
# define YYDPRINTF(Args) \
do { \
if (yydebug) \
YYFPRINTF Args; \
} while (YYID (0))
# define YY_SYMBOL_PRINT(Title, Type, Value, Location) \
do { \
if (yydebug) \
{ \
YYFPRINTF (stderr, "%s ", Title); \
yy_symbol_print (stderr, \
Type, Value); \
YYFPRINTF (stderr, "\n"); \
} \
} while (YYID (0))
/*--------------------------------.
| Print this symbol on YYOUTPUT. |
`--------------------------------*/
/*ARGSUSED*/
#if (defined __STDC__ || defined __C99__FUNC__ \
|| defined __cplusplus || defined _MSC_VER)
static void
yy_symbol_value_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep)
#else
static void
yy_symbol_value_print (yyoutput, yytype, yyvaluep)
FILE *yyoutput;
int yytype;
YYSTYPE const * const yyvaluep;
#endif
{
if (!yyvaluep)
return;
# ifdef YYPRINT
if (yytype < YYNTOKENS)
YYPRINT (yyoutput, yytoknum[yytype], *yyvaluep);
# else
YYUSE (yyoutput);
# endif
switch (yytype)
{
default:
break;
}
}
/*--------------------------------.
| Print this symbol on YYOUTPUT. |
`--------------------------------*/
#if (defined __STDC__ || defined __C99__FUNC__ \
|| defined __cplusplus || defined _MSC_VER)
static void
yy_symbol_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep)
#else
static void
yy_symbol_print (yyoutput, yytype, yyvaluep)
FILE *yyoutput;
int yytype;
YYSTYPE const * const yyvaluep;
#endif
{
if (yytype < YYNTOKENS)
YYFPRINTF (yyoutput, "token %s (", yytname[yytype]);
else
YYFPRINTF (yyoutput, "nterm %s (", yytname[yytype]);
yy_symbol_value_print (yyoutput, yytype, yyvaluep);
YYFPRINTF (yyoutput, ")");
}
/*------------------------------------------------------------------.
| yy_stack_print -- Print the state stack from its BOTTOM up to its |
| TOP (included). |
`------------------------------------------------------------------*/
#if (defined __STDC__ || defined __C99__FUNC__ \
|| defined __cplusplus || defined _MSC_VER)
static void
yy_stack_print (yytype_int16 *yybottom, yytype_int16 *yytop)
#else
static void
yy_stack_print (yybottom, yytop)
yytype_int16 *yybottom;
yytype_int16 *yytop;
#endif
{
YYFPRINTF (stderr, "Stack now");
for (; yybottom <= yytop; yybottom++)
{
int yybot = *yybottom;
YYFPRINTF (stderr, " %d", yybot);
}
YYFPRINTF (stderr, "\n");
}
# define YY_STACK_PRINT(Bottom, Top) \
do { \
if (yydebug) \
yy_stack_print ((Bottom), (Top)); \
} while (YYID (0))
/*------------------------------------------------.
| Report that the YYRULE is going to be reduced. |
`------------------------------------------------*/
#if (defined __STDC__ || defined __C99__FUNC__ \
|| defined __cplusplus || defined _MSC_VER)
static void
yy_reduce_print (YYSTYPE *yyvsp, int yyrule)
#else
static void
yy_reduce_print (yyvsp, yyrule)
YYSTYPE *yyvsp;
int yyrule;
#endif
{
int yynrhs = yyr2[yyrule];
int yyi;
unsigned long int yylno = yyrline[yyrule];
YYFPRINTF (stderr, "Reducing stack by rule %d (line %lu):\n",
yyrule - 1, yylno);
/* The symbols being reduced. */
for (yyi = 0; yyi < yynrhs; yyi++)
{
YYFPRINTF (stderr, " $%d = ", yyi + 1);
yy_symbol_print (stderr, yyrhs[yyprhs[yyrule] + yyi],
&(yyvsp[(yyi + 1) - (yynrhs)])
);
YYFPRINTF (stderr, "\n");
}
}
# define YY_REDUCE_PRINT(Rule) \
do { \
if (yydebug) \
yy_reduce_print (yyvsp, Rule); \
} while (YYID (0))
/* Nonzero means print parse trace. It is left uninitialized so that
multiple parsers can coexist. */
int yydebug;
#else /* !YYDEBUG */
# define YYDPRINTF(Args)
# define YY_SYMBOL_PRINT(Title, Type, Value, Location)
# define YY_STACK_PRINT(Bottom, Top)
# define YY_REDUCE_PRINT(Rule)
#endif /* !YYDEBUG */
/* YYINITDEPTH -- initial size of the parser's stacks. */
#ifndef YYINITDEPTH
# define YYINITDEPTH 200
#endif
/* YYMAXDEPTH -- maximum size the stacks can grow to (effective only
if the built-in stack extension method is used).
Do not make this value too large; the results are undefined if
YYSTACK_ALLOC_MAXIMUM < YYSTACK_BYTES (YYMAXDEPTH)
evaluated with infinite-precision integer arithmetic. */
#ifndef YYMAXDEPTH
# define YYMAXDEPTH 10000
#endif
#if YYERROR_VERBOSE
# ifndef yystrlen
# if defined __GLIBC__ && defined _STRING_H
# define yystrlen strlen
# else
/* Return the length of YYSTR. */
#if (defined __STDC__ || defined __C99__FUNC__ \
|| defined __cplusplus || defined _MSC_VER)
static YYSIZE_T
yystrlen (const char *yystr)
#else
static YYSIZE_T
yystrlen (yystr)
const char *yystr;
#endif
{
YYSIZE_T yylen;
for (yylen = 0; yystr[yylen]; yylen++)
continue;
return yylen;
}
# endif
# endif
# ifndef yystpcpy
# if defined __GLIBC__ && defined _STRING_H && defined _GNU_SOURCE
# define yystpcpy stpcpy
# else
/* Copy YYSRC to YYDEST, returning the address of the terminating '\0' in
YYDEST. */
#if (defined __STDC__ || defined __C99__FUNC__ \
|| defined __cplusplus || defined _MSC_VER)
static char *
yystpcpy (char *yydest, const char *yysrc)
#else
static char *
yystpcpy (yydest, yysrc)
char *yydest;
const char *yysrc;
#endif
{
char *yyd = yydest;
const char *yys = yysrc;
while ((*yyd++ = *yys++) != '\0')
continue;
return yyd - 1;
}
# endif
# endif
# ifndef yytnamerr
/* Copy to YYRES the contents of YYSTR after stripping away unnecessary
quotes and backslashes, so that it's suitable for yyerror. The
heuristic is that double-quoting is unnecessary unless the string
contains an apostrophe, a comma, or backslash (other than
backslash-backslash). YYSTR is taken from yytname. If YYRES is
null, do not copy; instead, return the length of what the result
would have been. */
static YYSIZE_T
yytnamerr (char *yyres, const char *yystr)
{
if (*yystr == '"')
{
YYSIZE_T yyn = 0;
char const *yyp = yystr;
for (;;)
switch (*++yyp)
{
case '\'':
case ',':
goto do_not_strip_quotes;
case '\\':
if (*++yyp != '\\')
goto do_not_strip_quotes;
/* Fall through. */
default:
if (yyres)
yyres[yyn] = *yyp;
yyn++;
break;
case '"':
if (yyres)
yyres[yyn] = '\0';
return yyn;
}
do_not_strip_quotes: ;
}
if (! yyres)
return yystrlen (yystr);
return yystpcpy (yyres, yystr) - yyres;
}
# endif
/* Copy into YYRESULT an error message about the unexpected token
YYCHAR while in state YYSTATE. Return the number of bytes copied,
including the terminating null byte. If YYRESULT is null, do not
copy anything; just return the number of bytes that would be
copied. As a special case, return 0 if an ordinary "syntax error"
message will do. Return YYSIZE_MAXIMUM if overflow occurs during
size calculation. */
static YYSIZE_T
yysyntax_error (char *yyresult, int yystate, int yychar)
{
int yyn = yypact[yystate];
if (! (YYPACT_NINF < yyn && yyn <= YYLAST))
return 0;
else
{
int yytype = YYTRANSLATE (yychar);
YYSIZE_T yysize0 = yytnamerr (0, yytname[yytype]);
YYSIZE_T yysize = yysize0;
YYSIZE_T yysize1;
int yysize_overflow = 0;
enum { YYERROR_VERBOSE_ARGS_MAXIMUM = 5 };
char const *yyarg[YYERROR_VERBOSE_ARGS_MAXIMUM];
int yyx;
# if 0
/* This is so xgettext sees the translatable formats that are
constructed on the fly. */
YY_("syntax error, unexpected %s");
YY_("syntax error, unexpected %s, expecting %s");
YY_("syntax error, unexpected %s, expecting %s or %s");
YY_("syntax error, unexpected %s, expecting %s or %s or %s");
YY_("syntax error, unexpected %s, expecting %s or %s or %s or %s");
# endif
char *yyfmt;
char const *yyf;
static char const yyunexpected[] = "syntax error, unexpected %s";
static char const yyexpecting[] = ", expecting %s";
static char const yyor[] = " or %s";
char yyformat[sizeof yyunexpected
+ sizeof yyexpecting - 1
+ ((YYERROR_VERBOSE_ARGS_MAXIMUM - 2)
* (sizeof yyor - 1))];
char const *yyprefix = yyexpecting;
/* Start YYX at -YYN if negative to avoid negative indexes in
YYCHECK. */
int yyxbegin = yyn < 0 ? -yyn : 0;
/* Stay within bounds of both yycheck and yytname. */
int yychecklim = YYLAST - yyn + 1;
int yyxend = yychecklim < YYNTOKENS ? yychecklim : YYNTOKENS;
int yycount = 1;
yyarg[0] = yytname[yytype];
yyfmt = yystpcpy (yyformat, yyunexpected);
for (yyx = yyxbegin; yyx < yyxend; ++yyx)
if (yycheck[yyx + yyn] == yyx && yyx != YYTERROR)
{
if (yycount == YYERROR_VERBOSE_ARGS_MAXIMUM)
{
yycount = 1;
yysize = yysize0;
yyformat[sizeof yyunexpected - 1] = '\0';
break;
}
yyarg[yycount++] = yytname[yyx];
yysize1 = yysize + yytnamerr (0, yytname[yyx]);
yysize_overflow |= (yysize1 < yysize);
yysize = yysize1;
yyfmt = yystpcpy (yyfmt, yyprefix);
yyprefix = yyor;
}
yyf = YY_(yyformat);
yysize1 = yysize + yystrlen (yyf);
yysize_overflow |= (yysize1 < yysize);
yysize = yysize1;
if (yysize_overflow)
return YYSIZE_MAXIMUM;
if (yyresult)
{
/* Avoid sprintf, as that infringes on the user's name space.
Don't have undefined behavior even if the translation
produced a string with the wrong number of "%s"s. */
char *yyp = yyresult;
int yyi = 0;
while ((*yyp = *yyf) != '\0')
{
if (*yyp == '%' && yyf[1] == 's' && yyi < yycount)
{
yyp += yytnamerr (yyp, yyarg[yyi++]);
yyf += 2;
}
else
{
yyp++;
yyf++;
}
}
}
return yysize;
}
}
#endif /* YYERROR_VERBOSE */
/*-----------------------------------------------.
| Release the memory associated to this symbol. |
`-----------------------------------------------*/
/*ARGSUSED*/
#if (defined __STDC__ || defined __C99__FUNC__ \
|| defined __cplusplus || defined _MSC_VER)
static void
yydestruct (const char *yymsg, int yytype, YYSTYPE *yyvaluep)
#else
static void
yydestruct (yymsg, yytype, yyvaluep)
const char *yymsg;
int yytype;
YYSTYPE *yyvaluep;
#endif
{
YYUSE (yyvaluep);
if (!yymsg)
yymsg = "Deleting";
YY_SYMBOL_PRINT (yymsg, yytype, yyvaluep, yylocationp);
switch (yytype)
{
default:
break;
}
}
/* Prevent warnings from -Wmissing-prototypes. */
#ifdef YYPARSE_PARAM
#if defined __STDC__ || defined __cplusplus
int yyparse (void *YYPARSE_PARAM);
#else
int yyparse ();
#endif
#else /* ! YYPARSE_PARAM */
#if defined __STDC__ || defined __cplusplus
int yyparse (void);
#else
int yyparse ();
#endif
#endif /* ! YYPARSE_PARAM */
/* The lookahead symbol. */
int yychar;
/* The semantic value of the lookahead symbol. */
YYSTYPE yylval;
/* Number of syntax errors so far. */
int yynerrs;
/*-------------------------.
| yyparse or yypush_parse. |
`-------------------------*/
#ifdef YYPARSE_PARAM
#if (defined __STDC__ || defined __C99__FUNC__ \
|| defined __cplusplus || defined _MSC_VER)
int
yyparse (void *YYPARSE_PARAM)
#else
int
yyparse (YYPARSE_PARAM)
void *YYPARSE_PARAM;
#endif
#else /* ! YYPARSE_PARAM */
#if (defined __STDC__ || defined __C99__FUNC__ \
|| defined __cplusplus || defined _MSC_VER)
int
yyparse (void)
#else
int
yyparse ()
#endif
#endif
{
int yystate;
/* Number of tokens to shift before error messages enabled. */
int yyerrstatus;
/* The stacks and their tools:
`yyss': related to states.
`yyvs': related to semantic values.
Refer to the stacks thru separate pointers, to allow yyoverflow
to reallocate them elsewhere. */
/* The state stack. */
yytype_int16 yyssa[YYINITDEPTH];
yytype_int16 *yyss;
yytype_int16 *yyssp;
/* The semantic value stack. */
YYSTYPE yyvsa[YYINITDEPTH];
YYSTYPE *yyvs;
YYSTYPE *yyvsp;
YYSIZE_T yystacksize;
int yyn;
int yyresult;
/* Lookahead token as an internal (translated) token number. */
int yytoken;
/* The variables used to return semantic value and location from the
action routines. */
YYSTYPE yyval;
#if YYERROR_VERBOSE
/* Buffer for error messages, and its allocated size. */
char yymsgbuf[128];
char *yymsg = yymsgbuf;
YYSIZE_T yymsg_alloc = sizeof yymsgbuf;
#endif
#define YYPOPSTACK(N) (yyvsp -= (N), yyssp -= (N))
/* The number of symbols on the RHS of the reduced rule.
Keep to zero when no symbol should be popped. */
int yylen = 0;
yytoken = 0;
yyss = yyssa;
yyvs = yyvsa;
yystacksize = YYINITDEPTH;
YYDPRINTF ((stderr, "Starting parse\n"));
yystate = 0;
yyerrstatus = 0;
yynerrs = 0;
yychar = YYEMPTY; /* Cause a token to be read. */
/* Initialize stack pointers.
Waste one element of value and location stack
so that they stay on the same level as the state stack.
The wasted elements are never initialized. */
yyssp = yyss;
yyvsp = yyvs;
goto yysetstate;
/*------------------------------------------------------------.
| yynewstate -- Push a new state, which is found in yystate. |
`------------------------------------------------------------*/
yynewstate:
/* In all cases, when you get here, the value and location stacks
have just been pushed. So pushing a state here evens the stacks. */
yyssp++;
yysetstate:
*yyssp = yystate;
if (yyss + yystacksize - 1 <= yyssp)
{
/* Get the current used size of the three stacks, in elements. */
YYSIZE_T yysize = yyssp - yyss + 1;
#ifdef yyoverflow
{
/* Give user a chance to reallocate the stack. Use copies of
these so that the &'s don't force the real ones into
memory. */
YYSTYPE *yyvs1 = yyvs;
yytype_int16 *yyss1 = yyss;
/* Each stack pointer address is followed by the size of the
data in use in that stack, in bytes. This used to be a
conditional around just the two extra args, but that might
be undefined if yyoverflow is a macro. */
yyoverflow (YY_("memory exhausted"),
&yyss1, yysize * sizeof (*yyssp),
&yyvs1, yysize * sizeof (*yyvsp),
&yystacksize);
yyss = yyss1;
yyvs = yyvs1;
}
#else /* no yyoverflow */
# ifndef YYSTACK_RELOCATE
goto yyexhaustedlab;
# else
/* Extend the stack our own way. */
if (YYMAXDEPTH <= yystacksize)
goto yyexhaustedlab;
yystacksize *= 2;
if (YYMAXDEPTH < yystacksize)
yystacksize = YYMAXDEPTH;
{
yytype_int16 *yyss1 = yyss;
union yyalloc *yyptr =
(union yyalloc *) YYSTACK_ALLOC (YYSTACK_BYTES (yystacksize));
if (! yyptr)
goto yyexhaustedlab;
YYSTACK_RELOCATE (yyss_alloc, yyss);
YYSTACK_RELOCATE (yyvs_alloc, yyvs);
# undef YYSTACK_RELOCATE
if (yyss1 != yyssa)
YYSTACK_FREE (yyss1);
}
# endif
#endif /* no yyoverflow */
yyssp = yyss + yysize - 1;
yyvsp = yyvs + yysize - 1;
YYDPRINTF ((stderr, "Stack size increased to %lu\n",
(unsigned long int) yystacksize));
if (yyss + yystacksize - 1 <= yyssp)
YYABORT;
}
YYDPRINTF ((stderr, "Entering state %d\n", yystate));
if (yystate == YYFINAL)
YYACCEPT;
goto yybackup;
/*-----------.
| yybackup. |
`-----------*/
yybackup:
/* Do appropriate processing given the current state. Read a
lookahead token if we need one and don't already have one. */
/* First try to decide what to do without reference to lookahead token. */
yyn = yypact[yystate];
if (yyn == YYPACT_NINF)
goto yydefault;
/* Not known => get a lookahead token if don't already have one. */
/* YYCHAR is either YYEMPTY or YYEOF or a valid lookahead symbol. */
if (yychar == YYEMPTY)
{
YYDPRINTF ((stderr, "Reading a token: "));
yychar = YYLEX;
}
if (yychar <= YYEOF)
{
yychar = yytoken = YYEOF;
YYDPRINTF ((stderr, "Now at end of input.\n"));
}
else
{
yytoken = YYTRANSLATE (yychar);
YY_SYMBOL_PRINT ("Next token is", yytoken, &yylval, &yylloc);
}
/* If the proper action on seeing token YYTOKEN is to reduce or to
detect an error, take that action. */
yyn += yytoken;
if (yyn < 0 || YYLAST < yyn || yycheck[yyn] != yytoken)
goto yydefault;
yyn = yytable[yyn];
if (yyn <= 0)
{
if (yyn == 0 || yyn == YYTABLE_NINF)
goto yyerrlab;
yyn = -yyn;
goto yyreduce;
}
/* Count tokens shifted since error; after three, turn off error
status. */
if (yyerrstatus)
yyerrstatus--;
/* Shift the lookahead token. */
YY_SYMBOL_PRINT ("Shifting", yytoken, &yylval, &yylloc);
/* Discard the shifted token. */
yychar = YYEMPTY;
yystate = yyn;
*++yyvsp = yylval;
goto yynewstate;
/*-----------------------------------------------------------.
| yydefault -- do the default action for the current state. |
`-----------------------------------------------------------*/
yydefault:
yyn = yydefact[yystate];
if (yyn == 0)
goto yyerrlab;
goto yyreduce;
/*-----------------------------.
| yyreduce -- Do a reduction. |
`-----------------------------*/
yyreduce:
/* yyn is the number of a rule to reduce with. */
yylen = yyr2[yyn];
/* If YYLEN is nonzero, implement the default value of the action:
`$$ = $1'.
Otherwise, the following line sets YYVAL to garbage.
This behavior is undocumented and Bison
users should not rely upon it. Assigning to YYVAL
unconditionally makes the parser a bit smaller, and it avoids a
GCC warning that YYVAL may be used uninitialized. */
yyval = yyvsp[1-yylen];
YY_REDUCE_PRINT (yyn);
switch (yyn)
{
case 2:
/* Line 1455 of yacc.c */
#line 110 "dtc-parser.y"
{
the_boot_info = build_boot_info((yyvsp[(3) - (4)].re), (yyvsp[(4) - (4)].node),
guess_boot_cpuid((yyvsp[(4) - (4)].node)));
;}
break;
case 3:
/* Line 1455 of yacc.c */
#line 118 "dtc-parser.y"
{
(yyval.re) = NULL;
;}
break;
case 4:
/* Line 1455 of yacc.c */
#line 122 "dtc-parser.y"
{
(yyval.re) = chain_reserve_entry((yyvsp[(1) - (2)].re), (yyvsp[(2) - (2)].re));
;}
break;
case 5:
/* Line 1455 of yacc.c */
#line 129 "dtc-parser.y"
{
(yyval.re) = build_reserve_entry((yyvsp[(2) - (4)].integer), (yyvsp[(3) - (4)].integer));
;}
break;
case 6:
/* Line 1455 of yacc.c */
#line 133 "dtc-parser.y"
{
add_label(&(yyvsp[(2) - (2)].re)->labels, (yyvsp[(1) - (2)].labelref));
(yyval.re) = (yyvsp[(2) - (2)].re);
;}
break;
case 7:
/* Line 1455 of yacc.c */
#line 141 "dtc-parser.y"
{
(yyval.node) = name_node((yyvsp[(2) - (2)].node), "");
;}
break;
case 8:
/* Line 1455 of yacc.c */
#line 145 "dtc-parser.y"
{
(yyval.node) = merge_nodes((yyvsp[(1) - (3)].node), (yyvsp[(3) - (3)].node));
;}
break;
case 9:
/* Line 1455 of yacc.c */
#line 149 "dtc-parser.y"
{
struct node *target = get_node_by_ref((yyvsp[(1) - (3)].node), (yyvsp[(2) - (3)].labelref));
if (target)
merge_nodes(target, (yyvsp[(3) - (3)].node));
else
print_error("label or path, '%s', not found", (yyvsp[(2) - (3)].labelref));
(yyval.node) = (yyvsp[(1) - (3)].node);
;}
break;
case 10:
/* Line 1455 of yacc.c */
#line 159 "dtc-parser.y"
{
struct node *target = get_node_by_ref((yyvsp[(1) - (4)].node), (yyvsp[(3) - (4)].labelref));
if (!target)
print_error("label or path, '%s', not found", (yyvsp[(3) - (4)].labelref));
else
delete_node(target);
(yyval.node) = (yyvsp[(1) - (4)].node);
;}
break;
case 11:
/* Line 1455 of yacc.c */
#line 173 "dtc-parser.y"
{
(yyval.node) = build_node((yyvsp[(2) - (5)].proplist), (yyvsp[(3) - (5)].nodelist));
;}
break;
case 12:
/* Line 1455 of yacc.c */
#line 180 "dtc-parser.y"
{
(yyval.proplist) = NULL;
;}
break;
case 13:
/* Line 1455 of yacc.c */
#line 184 "dtc-parser.y"
{
(yyval.proplist) = chain_property((yyvsp[(2) - (2)].prop), (yyvsp[(1) - (2)].proplist));
;}
break;
case 14:
/* Line 1455 of yacc.c */
#line 191 "dtc-parser.y"
{
(yyval.prop) = build_property((yyvsp[(1) - (4)].propnodename), (yyvsp[(3) - (4)].data));
;}
break;
case 15:
/* Line 1455 of yacc.c */
#line 195 "dtc-parser.y"
{
(yyval.prop) = build_property((yyvsp[(1) - (2)].propnodename), empty_data);
;}
break;
case 16:
/* Line 1455 of yacc.c */
#line 199 "dtc-parser.y"
{
(yyval.prop) = build_property_delete((yyvsp[(2) - (3)].propnodename));
;}
break;
case 17:
/* Line 1455 of yacc.c */
#line 203 "dtc-parser.y"
{
add_label(&(yyvsp[(2) - (2)].prop)->labels, (yyvsp[(1) - (2)].labelref));
(yyval.prop) = (yyvsp[(2) - (2)].prop);
;}
break;
case 18:
/* Line 1455 of yacc.c */
#line 211 "dtc-parser.y"
{
(yyval.data) = data_merge((yyvsp[(1) - (2)].data), (yyvsp[(2) - (2)].data));
;}
break;
case 19:
/* Line 1455 of yacc.c */
#line 215 "dtc-parser.y"
{
(yyval.data) = data_merge((yyvsp[(1) - (3)].data), (yyvsp[(2) - (3)].array).data);
;}
break;
case 20:
/* Line 1455 of yacc.c */
#line 219 "dtc-parser.y"
{
(yyval.data) = data_merge((yyvsp[(1) - (4)].data), (yyvsp[(3) - (4)].data));
;}
break;
case 21:
/* Line 1455 of yacc.c */
#line 223 "dtc-parser.y"
{
(yyval.data) = data_add_marker((yyvsp[(1) - (2)].data), REF_PATH, (yyvsp[(2) - (2)].labelref));
;}
break;
case 22:
/* Line 1455 of yacc.c */
#line 227 "dtc-parser.y"
{
FILE *f = srcfile_relative_open((yyvsp[(4) - (9)].data).val, NULL);
struct data d;
if ((yyvsp[(6) - (9)].integer) != 0)
if (fseek(f, (yyvsp[(6) - (9)].integer), SEEK_SET) != 0)
print_error("Couldn't seek to offset %llu in \"%s\": %s",
(unsigned long long)(yyvsp[(6) - (9)].integer),
(yyvsp[(4) - (9)].data).val,
strerror(errno));
d = data_copy_file(f, (yyvsp[(8) - (9)].integer));
(yyval.data) = data_merge((yyvsp[(1) - (9)].data), d);
fclose(f);
;}
break;
case 23:
/* Line 1455 of yacc.c */
#line 244 "dtc-parser.y"
{
FILE *f = srcfile_relative_open((yyvsp[(4) - (5)].data).val, NULL);
struct data d = empty_data;
d = data_copy_file(f, -1);
(yyval.data) = data_merge((yyvsp[(1) - (5)].data), d);
fclose(f);
;}
break;
case 24:
/* Line 1455 of yacc.c */
#line 254 "dtc-parser.y"
{
(yyval.data) = data_add_marker((yyvsp[(1) - (2)].data), LABEL, (yyvsp[(2) - (2)].labelref));
;}
break;
case 25:
/* Line 1455 of yacc.c */
#line 261 "dtc-parser.y"
{
(yyval.data) = empty_data;
;}
break;
case 26:
/* Line 1455 of yacc.c */
#line 265 "dtc-parser.y"
{
(yyval.data) = (yyvsp[(1) - (2)].data);
;}
break;
case 27:
/* Line 1455 of yacc.c */
#line 269 "dtc-parser.y"
{
(yyval.data) = data_add_marker((yyvsp[(1) - (2)].data), LABEL, (yyvsp[(2) - (2)].labelref));
;}
break;
case 28:
/* Line 1455 of yacc.c */
#line 276 "dtc-parser.y"
{
(yyval.array).data = empty_data;
(yyval.array).bits = eval_literal((yyvsp[(2) - (3)].literal), 0, 7);
if (((yyval.array).bits != 8) &&
((yyval.array).bits != 16) &&
((yyval.array).bits != 32) &&
((yyval.array).bits != 64))
{
print_error("Only 8, 16, 32 and 64-bit elements"
" are currently supported");
(yyval.array).bits = 32;
}
;}
break;
case 29:
/* Line 1455 of yacc.c */
#line 291 "dtc-parser.y"
{
(yyval.array).data = empty_data;
(yyval.array).bits = 32;
;}
break;
case 30:
/* Line 1455 of yacc.c */
#line 296 "dtc-parser.y"
{
if ((yyvsp[(1) - (2)].array).bits < 64) {
uint64_t mask = (1ULL << (yyvsp[(1) - (2)].array).bits) - 1;
/*
* Bits above mask must either be all zero
* (positive within range of mask) or all one
* (negative and sign-extended). The second
* condition is true if when we set all bits
* within the mask to one (i.e. | in the
* mask), all bits are one.
*/
if (((yyvsp[(2) - (2)].integer) > mask) && (((yyvsp[(2) - (2)].integer) | mask) != -1ULL))
print_error(
"integer value out of range "
"%016lx (%d bits)", (yyvsp[(1) - (2)].array).bits);
}
(yyval.array).data = data_append_integer((yyvsp[(1) - (2)].array).data, (yyvsp[(2) - (2)].integer), (yyvsp[(1) - (2)].array).bits);
;}
break;
case 31:
/* Line 1455 of yacc.c */
#line 316 "dtc-parser.y"
{
uint64_t val = ~0ULL >> (64 - (yyvsp[(1) - (2)].array).bits);
if ((yyvsp[(1) - (2)].array).bits == 32)
(yyvsp[(1) - (2)].array).data = data_add_marker((yyvsp[(1) - (2)].array).data,
REF_PHANDLE,
(yyvsp[(2) - (2)].labelref));
else
print_error("References are only allowed in "
"arrays with 32-bit elements.");
(yyval.array).data = data_append_integer((yyvsp[(1) - (2)].array).data, val, (yyvsp[(1) - (2)].array).bits);
;}
break;
case 32:
/* Line 1455 of yacc.c */
#line 330 "dtc-parser.y"
{
(yyval.array).data = data_add_marker((yyvsp[(1) - (2)].array).data, LABEL, (yyvsp[(2) - (2)].labelref));
;}
break;
case 33:
/* Line 1455 of yacc.c */
#line 337 "dtc-parser.y"
{
(yyval.integer) = eval_literal((yyvsp[(1) - (1)].literal), 0, 64);
;}
break;
case 34:
/* Line 1455 of yacc.c */
#line 341 "dtc-parser.y"
{
(yyval.integer) = eval_char_literal((yyvsp[(1) - (1)].literal));
;}
break;
case 35:
/* Line 1455 of yacc.c */
#line 345 "dtc-parser.y"
{
(yyval.integer) = (yyvsp[(2) - (3)].integer);
;}
break;
case 38:
/* Line 1455 of yacc.c */
#line 356 "dtc-parser.y"
{ (yyval.integer) = (yyvsp[(1) - (5)].integer) ? (yyvsp[(3) - (5)].integer) : (yyvsp[(5) - (5)].integer); ;}
break;
case 40:
/* Line 1455 of yacc.c */
#line 361 "dtc-parser.y"
{ (yyval.integer) = (yyvsp[(1) - (3)].integer) || (yyvsp[(3) - (3)].integer); ;}
break;
case 42:
/* Line 1455 of yacc.c */
#line 366 "dtc-parser.y"
{ (yyval.integer) = (yyvsp[(1) - (3)].integer) && (yyvsp[(3) - (3)].integer); ;}
break;
case 44:
/* Line 1455 of yacc.c */
#line 371 "dtc-parser.y"
{ (yyval.integer) = (yyvsp[(1) - (3)].integer) | (yyvsp[(3) - (3)].integer); ;}
break;
case 46:
/* Line 1455 of yacc.c */
#line 376 "dtc-parser.y"
{ (yyval.integer) = (yyvsp[(1) - (3)].integer) ^ (yyvsp[(3) - (3)].integer); ;}
break;
case 48:
/* Line 1455 of yacc.c */
#line 381 "dtc-parser.y"
{ (yyval.integer) = (yyvsp[(1) - (3)].integer) & (yyvsp[(3) - (3)].integer); ;}
break;
case 50:
/* Line 1455 of yacc.c */
#line 386 "dtc-parser.y"
{ (yyval.integer) = (yyvsp[(1) - (3)].integer) == (yyvsp[(3) - (3)].integer); ;}
break;
case 51:
/* Line 1455 of yacc.c */
#line 387 "dtc-parser.y"
{ (yyval.integer) = (yyvsp[(1) - (3)].integer) != (yyvsp[(3) - (3)].integer); ;}
break;
case 53:
/* Line 1455 of yacc.c */
#line 392 "dtc-parser.y"
{ (yyval.integer) = (yyvsp[(1) - (3)].integer) < (yyvsp[(3) - (3)].integer); ;}
break;
case 54:
/* Line 1455 of yacc.c */
#line 393 "dtc-parser.y"
{ (yyval.integer) = (yyvsp[(1) - (3)].integer) > (yyvsp[(3) - (3)].integer); ;}
break;
case 55:
/* Line 1455 of yacc.c */
#line 394 "dtc-parser.y"
{ (yyval.integer) = (yyvsp[(1) - (3)].integer) <= (yyvsp[(3) - (3)].integer); ;}
break;
case 56:
/* Line 1455 of yacc.c */
#line 395 "dtc-parser.y"
{ (yyval.integer) = (yyvsp[(1) - (3)].integer) >= (yyvsp[(3) - (3)].integer); ;}
break;
case 57:
/* Line 1455 of yacc.c */
#line 399 "dtc-parser.y"
{ (yyval.integer) = (yyvsp[(1) - (3)].integer) << (yyvsp[(3) - (3)].integer); ;}
break;
case 58:
/* Line 1455 of yacc.c */
#line 400 "dtc-parser.y"
{ (yyval.integer) = (yyvsp[(1) - (3)].integer) >> (yyvsp[(3) - (3)].integer); ;}
break;
case 60:
/* Line 1455 of yacc.c */
#line 405 "dtc-parser.y"
{ (yyval.integer) = (yyvsp[(1) - (3)].integer) + (yyvsp[(3) - (3)].integer); ;}
break;
case 61:
/* Line 1455 of yacc.c */
#line 406 "dtc-parser.y"
{ (yyval.integer) = (yyvsp[(1) - (3)].integer) - (yyvsp[(3) - (3)].integer); ;}
break;
case 63:
/* Line 1455 of yacc.c */
#line 411 "dtc-parser.y"
{ (yyval.integer) = (yyvsp[(1) - (3)].integer) * (yyvsp[(3) - (3)].integer); ;}
break;
case 64:
/* Line 1455 of yacc.c */
#line 412 "dtc-parser.y"
{ (yyval.integer) = (yyvsp[(1) - (3)].integer) / (yyvsp[(3) - (3)].integer); ;}
break;
case 65:
/* Line 1455 of yacc.c */
#line 413 "dtc-parser.y"
{ (yyval.integer) = (yyvsp[(1) - (3)].integer) % (yyvsp[(3) - (3)].integer); ;}
break;
case 68:
/* Line 1455 of yacc.c */
#line 419 "dtc-parser.y"
{ (yyval.integer) = -(yyvsp[(2) - (2)].integer); ;}
break;
case 69:
/* Line 1455 of yacc.c */
#line 420 "dtc-parser.y"
{ (yyval.integer) = ~(yyvsp[(2) - (2)].integer); ;}
break;
case 70:
/* Line 1455 of yacc.c */
#line 421 "dtc-parser.y"
{ (yyval.integer) = !(yyvsp[(2) - (2)].integer); ;}
break;
case 71:
/* Line 1455 of yacc.c */
#line 426 "dtc-parser.y"
{
(yyval.data) = empty_data;
;}
break;
case 72:
/* Line 1455 of yacc.c */
#line 430 "dtc-parser.y"
{
(yyval.data) = data_append_byte((yyvsp[(1) - (2)].data), (yyvsp[(2) - (2)].byte));
;}
break;
case 73:
/* Line 1455 of yacc.c */
#line 434 "dtc-parser.y"
{
(yyval.data) = data_add_marker((yyvsp[(1) - (2)].data), LABEL, (yyvsp[(2) - (2)].labelref));
;}
break;
case 74:
/* Line 1455 of yacc.c */
#line 441 "dtc-parser.y"
{
(yyval.nodelist) = NULL;
;}
break;
case 75:
/* Line 1455 of yacc.c */
#line 445 "dtc-parser.y"
{
(yyval.nodelist) = chain_node((yyvsp[(1) - (2)].node), (yyvsp[(2) - (2)].nodelist));
;}
break;
case 76:
/* Line 1455 of yacc.c */
#line 449 "dtc-parser.y"
{
print_error("syntax error: properties must precede subnodes");
YYERROR;
;}
break;
case 77:
/* Line 1455 of yacc.c */
#line 457 "dtc-parser.y"
{
(yyval.node) = name_node((yyvsp[(2) - (2)].node), (yyvsp[(1) - (2)].propnodename));
;}
break;
case 78:
/* Line 1455 of yacc.c */
#line 461 "dtc-parser.y"
{
(yyval.node) = name_node(build_node_delete(), (yyvsp[(2) - (3)].propnodename));
;}
break;
case 79:
/* Line 1455 of yacc.c */
#line 465 "dtc-parser.y"
{
add_label(&(yyvsp[(2) - (2)].node)->labels, (yyvsp[(1) - (2)].labelref));
(yyval.node) = (yyvsp[(2) - (2)].node);
;}
break;
/* Line 1455 of yacc.c */
#line 2124 "dtc-parser.tab.c"
default: break;
}
YY_SYMBOL_PRINT ("-> $$ =", yyr1[yyn], &yyval, &yyloc);
YYPOPSTACK (yylen);
yylen = 0;
YY_STACK_PRINT (yyss, yyssp);
*++yyvsp = yyval;
/* Now `shift' the result of the reduction. Determine what state
that goes to, based on the state we popped back to and the rule
number reduced by. */
yyn = yyr1[yyn];
yystate = yypgoto[yyn - YYNTOKENS] + *yyssp;
if (0 <= yystate && yystate <= YYLAST && yycheck[yystate] == *yyssp)
yystate = yytable[yystate];
else
yystate = yydefgoto[yyn - YYNTOKENS];
goto yynewstate;
/*------------------------------------.
| yyerrlab -- here on detecting error |
`------------------------------------*/
yyerrlab:
/* If not already recovering from an error, report this error. */
if (!yyerrstatus)
{
++yynerrs;
#if ! YYERROR_VERBOSE
yyerror (YY_("syntax error"));
#else
{
YYSIZE_T yysize = yysyntax_error (0, yystate, yychar);
if (yymsg_alloc < yysize && yymsg_alloc < YYSTACK_ALLOC_MAXIMUM)
{
YYSIZE_T yyalloc = 2 * yysize;
if (! (yysize <= yyalloc && yyalloc <= YYSTACK_ALLOC_MAXIMUM))
yyalloc = YYSTACK_ALLOC_MAXIMUM;
if (yymsg != yymsgbuf)
YYSTACK_FREE (yymsg);
yymsg = (char *) YYSTACK_ALLOC (yyalloc);
if (yymsg)
yymsg_alloc = yyalloc;
else
{
yymsg = yymsgbuf;
yymsg_alloc = sizeof yymsgbuf;
}
}
if (0 < yysize && yysize <= yymsg_alloc)
{
(void) yysyntax_error (yymsg, yystate, yychar);
yyerror (yymsg);
}
else
{
yyerror (YY_("syntax error"));
if (yysize != 0)
goto yyexhaustedlab;
}
}
#endif
}
if (yyerrstatus == 3)
{
/* If just tried and failed to reuse lookahead token after an
error, discard it. */
if (yychar <= YYEOF)
{
/* Return failure if at end of input. */
if (yychar == YYEOF)
YYABORT;
}
else
{
yydestruct ("Error: discarding",
yytoken, &yylval);
yychar = YYEMPTY;
}
}
/* Else will try to reuse lookahead token after shifting the error
token. */
goto yyerrlab1;
/*---------------------------------------------------.
| yyerrorlab -- error raised explicitly by YYERROR. |
`---------------------------------------------------*/
yyerrorlab:
/* Pacify compilers like GCC when the user code never invokes
YYERROR and the label yyerrorlab therefore never appears in user
code. */
if (/*CONSTCOND*/ 0)
goto yyerrorlab;
/* Do not reclaim the symbols of the rule which action triggered
this YYERROR. */
YYPOPSTACK (yylen);
yylen = 0;
YY_STACK_PRINT (yyss, yyssp);
yystate = *yyssp;
goto yyerrlab1;
/*-------------------------------------------------------------.
| yyerrlab1 -- common code for both syntax error and YYERROR. |
`-------------------------------------------------------------*/
yyerrlab1:
yyerrstatus = 3; /* Each real token shifted decrements this. */
for (;;)
{
yyn = yypact[yystate];
if (yyn != YYPACT_NINF)
{
yyn += YYTERROR;
if (0 <= yyn && yyn <= YYLAST && yycheck[yyn] == YYTERROR)
{
yyn = yytable[yyn];
if (0 < yyn)
break;
}
}
/* Pop the current state because it cannot handle the error token. */
if (yyssp == yyss)
YYABORT;
yydestruct ("Error: popping",
yystos[yystate], yyvsp);
YYPOPSTACK (1);
yystate = *yyssp;
YY_STACK_PRINT (yyss, yyssp);
}
*++yyvsp = yylval;
/* Shift the error token. */
YY_SYMBOL_PRINT ("Shifting", yystos[yyn], yyvsp, yylsp);
yystate = yyn;
goto yynewstate;
/*-------------------------------------.
| yyacceptlab -- YYACCEPT comes here. |
`-------------------------------------*/
yyacceptlab:
yyresult = 0;
goto yyreturn;
/*-----------------------------------.
| yyabortlab -- YYABORT comes here. |
`-----------------------------------*/
yyabortlab:
yyresult = 1;
goto yyreturn;
#if !defined(yyoverflow) || YYERROR_VERBOSE
/*-------------------------------------------------.
| yyexhaustedlab -- memory exhaustion comes here. |
`-------------------------------------------------*/
yyexhaustedlab:
yyerror (YY_("memory exhausted"));
yyresult = 2;
/* Fall through. */
#endif
yyreturn:
if (yychar != YYEMPTY)
yydestruct ("Cleanup: discarding lookahead",
yytoken, &yylval);
/* Do not reclaim the symbols of the rule which action triggered
this YYABORT or YYACCEPT. */
YYPOPSTACK (yylen);
YY_STACK_PRINT (yyss, yyssp);
while (yyssp != yyss)
{
yydestruct ("Cleanup: popping",
yystos[*yyssp], yyvsp);
YYPOPSTACK (1);
}
#ifndef yyoverflow
if (yyss != yyssa)
YYSTACK_FREE (yyss);
#endif
#if YYERROR_VERBOSE
if (yymsg != yymsgbuf)
YYSTACK_FREE (yymsg);
#endif
/* Make sure YYID is used. */
return YYID (yyresult);
}
/* Line 1675 of yacc.c */
#line 471 "dtc-parser.y"
void print_error(char const *fmt, ...)
{
va_list va;
va_start(va, fmt);
srcpos_verror(&yylloc, fmt, va);
va_end(va);
treesource_error = 1;
}
void yyerror(char const *s) {
print_error("%s", s);
}
static unsigned long long eval_literal(const char *s, int base, int bits)
{
unsigned long long val;
char *e;
errno = 0;
val = strtoull(s, &e, base);
if (*e) {
size_t uls = strspn(e, "UL");
if (e[uls])
print_error("bad characters in literal");
}
if ((errno == ERANGE)
|| ((bits < 64) && (val >= (1ULL << bits))))
print_error("literal out of range");
else if (errno != 0)
print_error("bad literal");
return val;
}
static unsigned char eval_char_literal(const char *s)
{
int i = 1;
char c = s[0];
if (c == '\0')
{
print_error("empty character literal");
return 0;
}
/*
* If the first character in the character literal is a \ then process
* the remaining characters as an escape encoding. If the first
* character is neither an escape or a terminator it should be the only
* character in the literal and will be returned.
*/
if (c == '\\')
c = get_escape_char(s, &i);
if (s[i] != '\0')
print_error("malformed character literal");
return c;
}
| {
"pile_set_name": "Github"
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>runner.robot Tooltip Mouse Quirks Test</title>
<style>
@import "../../../../util/doh/robot/robot.css";
</style>
<!-- required: dojo.js -->
<script type="text/javascript" src="../../../../dojo/dojo.js" data-dojo-config="isDebug: true"></script>
<script language="JavaScript" type="text/javascript">
require([
"dojo/_base/kernel",
"dojo/ready", // dojo.ready
"doh/runner", //doh functions
"dijit/registry", // dijit.registry.byId
"dijit/robotx"
], function(kernel, ready, runner, registry){
ready(function(){
runner.robot.initRobot("../test_transition-connect.html");
var reg=null;
runner.register("dojox.mobile.Animation mouse tests", [
{
name: "Animation mouse tests",
timeout: 50000,
runTest: function(){
var d = new runner.Deferred();
reg = kernel.global.dijit.registry;
runner.robot.mouseMoveAt(reg.byId("dojox_mobile_ListItem_0").domNode, 1000);
runner.robot.mouseClick({left: true}, 500);
runner.robot.sequence(d.getTestCallback(function(){
runner.assertEqual("none", reg.byId("view1").domNode.style.display);
runner.assertEqual("", reg.byId("view2").domNode.style.display);
}), 1500);
return d;
}
},
{
name: "Animation mouse tests",
timeout: 50000,
runTest: function(){
var d = new runner.Deferred();
runner.robot.mouseMoveAt(reg.byId("dojox_mobile_ToolBarButton_0").domNode, 1000);
runner.robot.mouseClick({left: true}, 500);
runner.robot.sequence(d.getTestCallback(function(){
runner.assertEqual("", reg.byId("view1").domNode.style.display);
runner.assertEqual("none", reg.byId("view2").domNode.style.display);
}), 1500);
return d;
}
},
{
name: "Animation mouse tests",
timeout: 50000,
runTest: function(){
var d = new runner.Deferred();
runner.robot.mouseMoveAt(reg.byId("dojox_mobile_ListItem_1").domNode, 1000);
runner.robot.mouseClick({left: true}, 500);
runner.robot.sequence(d.getTestCallback(function(){
runner.assertEqual("none", reg.byId("view1").domNode.style.display);
runner.assertEqual("", reg.byId("view2").domNode.style.display);
}), 1500);
return d;
}
},
{
name: "Animation mouse tests",
timeout: 50000,
runTest: function(){
var d = new runner.Deferred();
runner.robot.mouseMoveAt(reg.byId("dojox_mobile_ToolBarButton_0").domNode, 1000);
runner.robot.mouseClick({left: true}, 500);
runner.robot.sequence(d.getTestCallback(function(){
runner.assertEqual("", reg.byId("view1").domNode.style.display);
runner.assertEqual("none", reg.byId("view2").domNode.style.display);
}), 1500);
return d;
}
},
{
name: "Animation mouse tests",
timeout: 50000,
runTest: function(){
var d = new runner.Deferred();
runner.robot.mouseMoveAt(reg.byId("dojox_mobile_ListItem_2").domNode, 1000);
runner.robot.mouseClick({left: true}, 500);
runner.robot.sequence(d.getTestCallback(function(){
runner.assertEqual("none", reg.byId("view1").domNode.style.display);
runner.assertEqual("", reg.byId("view2").domNode.style.display);
}), 2000);
return d;
}
}
]);
runner.run();
});
});
</script>
</head>
<body />
</html>
| {
"pile_set_name": "Github"
} |
/*
* Copyright (C) Sistina Software, Inc. 1997-2003 All rights reserved.
* Copyright 2004-2011 Red Hat, Inc.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU General Public License version 2.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/fs.h>
#include <linux/dlm.h>
#include <linux/slab.h>
#include <linux/types.h>
#include <linux/delay.h>
#include <linux/gfs2_ondisk.h>
#include <linux/sched/signal.h>
#include "incore.h"
#include "glock.h"
#include "util.h"
#include "sys.h"
#include "trace_gfs2.h"
/**
* gfs2_update_stats - Update time based stats
* @mv: Pointer to mean/variance structure to update
* @sample: New data to include
*
* @delta is the difference between the current rtt sample and the
* running average srtt. We add 1/8 of that to the srtt in order to
* update the current srtt estimate. The variance estimate is a bit
* more complicated. We subtract the abs value of the @delta from
* the current variance estimate and add 1/4 of that to the running
* total.
*
* Note that the index points at the array entry containing the smoothed
* mean value, and the variance is always in the following entry
*
* Reference: TCP/IP Illustrated, vol 2, p. 831,832
* All times are in units of integer nanoseconds. Unlike the TCP/IP case,
* they are not scaled fixed point.
*/
static inline void gfs2_update_stats(struct gfs2_lkstats *s, unsigned index,
s64 sample)
{
s64 delta = sample - s->stats[index];
s->stats[index] += (delta >> 3);
index++;
s->stats[index] += ((abs(delta) - s->stats[index]) >> 2);
}
/**
* gfs2_update_reply_times - Update locking statistics
* @gl: The glock to update
*
* This assumes that gl->gl_dstamp has been set earlier.
*
* The rtt (lock round trip time) is an estimate of the time
* taken to perform a dlm lock request. We update it on each
* reply from the dlm.
*
* The blocking flag is set on the glock for all dlm requests
* which may potentially block due to lock requests from other nodes.
* DLM requests where the current lock state is exclusive, the
* requested state is null (or unlocked) or where the TRY or
* TRY_1CB flags are set are classified as non-blocking. All
* other DLM requests are counted as (potentially) blocking.
*/
static inline void gfs2_update_reply_times(struct gfs2_glock *gl)
{
struct gfs2_pcpu_lkstats *lks;
const unsigned gltype = gl->gl_name.ln_type;
unsigned index = test_bit(GLF_BLOCKING, &gl->gl_flags) ?
GFS2_LKS_SRTTB : GFS2_LKS_SRTT;
s64 rtt;
preempt_disable();
rtt = ktime_to_ns(ktime_sub(ktime_get_real(), gl->gl_dstamp));
lks = this_cpu_ptr(gl->gl_name.ln_sbd->sd_lkstats);
gfs2_update_stats(&gl->gl_stats, index, rtt); /* Local */
gfs2_update_stats(&lks->lkstats[gltype], index, rtt); /* Global */
preempt_enable();
trace_gfs2_glock_lock_time(gl, rtt);
}
/**
* gfs2_update_request_times - Update locking statistics
* @gl: The glock to update
*
* The irt (lock inter-request times) measures the average time
* between requests to the dlm. It is updated immediately before
* each dlm call.
*/
static inline void gfs2_update_request_times(struct gfs2_glock *gl)
{
struct gfs2_pcpu_lkstats *lks;
const unsigned gltype = gl->gl_name.ln_type;
ktime_t dstamp;
s64 irt;
preempt_disable();
dstamp = gl->gl_dstamp;
gl->gl_dstamp = ktime_get_real();
irt = ktime_to_ns(ktime_sub(gl->gl_dstamp, dstamp));
lks = this_cpu_ptr(gl->gl_name.ln_sbd->sd_lkstats);
gfs2_update_stats(&gl->gl_stats, GFS2_LKS_SIRT, irt); /* Local */
gfs2_update_stats(&lks->lkstats[gltype], GFS2_LKS_SIRT, irt); /* Global */
preempt_enable();
}
static void gdlm_ast(void *arg)
{
struct gfs2_glock *gl = arg;
unsigned ret = gl->gl_state;
gfs2_update_reply_times(gl);
BUG_ON(gl->gl_lksb.sb_flags & DLM_SBF_DEMOTED);
if ((gl->gl_lksb.sb_flags & DLM_SBF_VALNOTVALID) && gl->gl_lksb.sb_lvbptr)
memset(gl->gl_lksb.sb_lvbptr, 0, GDLM_LVB_SIZE);
switch (gl->gl_lksb.sb_status) {
case -DLM_EUNLOCK: /* Unlocked, so glock can be freed */
gfs2_glock_free(gl);
return;
case -DLM_ECANCEL: /* Cancel while getting lock */
ret |= LM_OUT_CANCELED;
goto out;
case -EAGAIN: /* Try lock fails */
case -EDEADLK: /* Deadlock detected */
goto out;
case -ETIMEDOUT: /* Canceled due to timeout */
ret |= LM_OUT_ERROR;
goto out;
case 0: /* Success */
break;
default: /* Something unexpected */
BUG();
}
ret = gl->gl_req;
if (gl->gl_lksb.sb_flags & DLM_SBF_ALTMODE) {
if (gl->gl_req == LM_ST_SHARED)
ret = LM_ST_DEFERRED;
else if (gl->gl_req == LM_ST_DEFERRED)
ret = LM_ST_SHARED;
else
BUG();
}
set_bit(GLF_INITIAL, &gl->gl_flags);
gfs2_glock_complete(gl, ret);
return;
out:
if (!test_bit(GLF_INITIAL, &gl->gl_flags))
gl->gl_lksb.sb_lkid = 0;
gfs2_glock_complete(gl, ret);
}
static void gdlm_bast(void *arg, int mode)
{
struct gfs2_glock *gl = arg;
switch (mode) {
case DLM_LOCK_EX:
gfs2_glock_cb(gl, LM_ST_UNLOCKED);
break;
case DLM_LOCK_CW:
gfs2_glock_cb(gl, LM_ST_DEFERRED);
break;
case DLM_LOCK_PR:
gfs2_glock_cb(gl, LM_ST_SHARED);
break;
default:
pr_err("unknown bast mode %d\n", mode);
BUG();
}
}
/* convert gfs lock-state to dlm lock-mode */
static int make_mode(const unsigned int lmstate)
{
switch (lmstate) {
case LM_ST_UNLOCKED:
return DLM_LOCK_NL;
case LM_ST_EXCLUSIVE:
return DLM_LOCK_EX;
case LM_ST_DEFERRED:
return DLM_LOCK_CW;
case LM_ST_SHARED:
return DLM_LOCK_PR;
}
pr_err("unknown LM state %d\n", lmstate);
BUG();
return -1;
}
static u32 make_flags(struct gfs2_glock *gl, const unsigned int gfs_flags,
const int req)
{
u32 lkf = 0;
if (gl->gl_lksb.sb_lvbptr)
lkf |= DLM_LKF_VALBLK;
if (gfs_flags & LM_FLAG_TRY)
lkf |= DLM_LKF_NOQUEUE;
if (gfs_flags & LM_FLAG_TRY_1CB) {
lkf |= DLM_LKF_NOQUEUE;
lkf |= DLM_LKF_NOQUEUEBAST;
}
if (gfs_flags & LM_FLAG_PRIORITY) {
lkf |= DLM_LKF_NOORDER;
lkf |= DLM_LKF_HEADQUE;
}
if (gfs_flags & LM_FLAG_ANY) {
if (req == DLM_LOCK_PR)
lkf |= DLM_LKF_ALTCW;
else if (req == DLM_LOCK_CW)
lkf |= DLM_LKF_ALTPR;
else
BUG();
}
if (gl->gl_lksb.sb_lkid != 0) {
lkf |= DLM_LKF_CONVERT;
if (test_bit(GLF_BLOCKING, &gl->gl_flags))
lkf |= DLM_LKF_QUECVT;
}
return lkf;
}
static void gfs2_reverse_hex(char *c, u64 value)
{
*c = '0';
while (value) {
*c-- = hex_asc[value & 0x0f];
value >>= 4;
}
}
static int gdlm_lock(struct gfs2_glock *gl, unsigned int req_state,
unsigned int flags)
{
struct lm_lockstruct *ls = &gl->gl_name.ln_sbd->sd_lockstruct;
int req;
u32 lkf;
char strname[GDLM_STRNAME_BYTES] = "";
req = make_mode(req_state);
lkf = make_flags(gl, flags, req);
gfs2_glstats_inc(gl, GFS2_LKS_DCOUNT);
gfs2_sbstats_inc(gl, GFS2_LKS_DCOUNT);
if (gl->gl_lksb.sb_lkid) {
gfs2_update_request_times(gl);
} else {
memset(strname, ' ', GDLM_STRNAME_BYTES - 1);
strname[GDLM_STRNAME_BYTES - 1] = '\0';
gfs2_reverse_hex(strname + 7, gl->gl_name.ln_type);
gfs2_reverse_hex(strname + 23, gl->gl_name.ln_number);
gl->gl_dstamp = ktime_get_real();
}
/*
* Submit the actual lock request.
*/
return dlm_lock(ls->ls_dlm, req, &gl->gl_lksb, lkf, strname,
GDLM_STRNAME_BYTES - 1, 0, gdlm_ast, gl, gdlm_bast);
}
static void gdlm_put_lock(struct gfs2_glock *gl)
{
struct gfs2_sbd *sdp = gl->gl_name.ln_sbd;
struct lm_lockstruct *ls = &sdp->sd_lockstruct;
int lvb_needs_unlock = 0;
int error;
if (gl->gl_lksb.sb_lkid == 0) {
gfs2_glock_free(gl);
return;
}
clear_bit(GLF_BLOCKING, &gl->gl_flags);
gfs2_glstats_inc(gl, GFS2_LKS_DCOUNT);
gfs2_sbstats_inc(gl, GFS2_LKS_DCOUNT);
gfs2_update_request_times(gl);
/* don't want to skip dlm_unlock writing the lvb when lock is ex */
if (gl->gl_lksb.sb_lvbptr && (gl->gl_state == LM_ST_EXCLUSIVE))
lvb_needs_unlock = 1;
if (test_bit(SDF_SKIP_DLM_UNLOCK, &sdp->sd_flags) &&
!lvb_needs_unlock) {
gfs2_glock_free(gl);
return;
}
error = dlm_unlock(ls->ls_dlm, gl->gl_lksb.sb_lkid, DLM_LKF_VALBLK,
NULL, gl);
if (error) {
pr_err("gdlm_unlock %x,%llx err=%d\n",
gl->gl_name.ln_type,
(unsigned long long)gl->gl_name.ln_number, error);
return;
}
}
static void gdlm_cancel(struct gfs2_glock *gl)
{
struct lm_lockstruct *ls = &gl->gl_name.ln_sbd->sd_lockstruct;
dlm_unlock(ls->ls_dlm, gl->gl_lksb.sb_lkid, DLM_LKF_CANCEL, NULL, gl);
}
/*
* dlm/gfs2 recovery coordination using dlm_recover callbacks
*
* 1. dlm_controld sees lockspace members change
* 2. dlm_controld blocks dlm-kernel locking activity
* 3. dlm_controld within dlm-kernel notifies gfs2 (recover_prep)
* 4. dlm_controld starts and finishes its own user level recovery
* 5. dlm_controld starts dlm-kernel dlm_recoverd to do kernel recovery
* 6. dlm_recoverd notifies gfs2 of failed nodes (recover_slot)
* 7. dlm_recoverd does its own lock recovery
* 8. dlm_recoverd unblocks dlm-kernel locking activity
* 9. dlm_recoverd notifies gfs2 when done (recover_done with new generation)
* 10. gfs2_control updates control_lock lvb with new generation and jid bits
* 11. gfs2_control enqueues journals for gfs2_recover to recover (maybe none)
* 12. gfs2_recover dequeues and recovers journals of failed nodes
* 13. gfs2_recover provides recovery results to gfs2_control (recovery_result)
* 14. gfs2_control updates control_lock lvb jid bits for recovered journals
* 15. gfs2_control unblocks normal locking when all journals are recovered
*
* - failures during recovery
*
* recover_prep() may set BLOCK_LOCKS (step 3) again before gfs2_control
* clears BLOCK_LOCKS (step 15), e.g. another node fails while still
* recovering for a prior failure. gfs2_control needs a way to detect
* this so it can leave BLOCK_LOCKS set in step 15. This is managed using
* the recover_block and recover_start values.
*
* recover_done() provides a new lockspace generation number each time it
* is called (step 9). This generation number is saved as recover_start.
* When recover_prep() is called, it sets BLOCK_LOCKS and sets
* recover_block = recover_start. So, while recover_block is equal to
* recover_start, BLOCK_LOCKS should remain set. (recover_spin must
* be held around the BLOCK_LOCKS/recover_block/recover_start logic.)
*
* - more specific gfs2 steps in sequence above
*
* 3. recover_prep sets BLOCK_LOCKS and sets recover_block = recover_start
* 6. recover_slot records any failed jids (maybe none)
* 9. recover_done sets recover_start = new generation number
* 10. gfs2_control sets control_lock lvb = new gen + bits for failed jids
* 12. gfs2_recover does journal recoveries for failed jids identified above
* 14. gfs2_control clears control_lock lvb bits for recovered jids
* 15. gfs2_control checks if recover_block == recover_start (step 3 occured
* again) then do nothing, otherwise if recover_start > recover_block
* then clear BLOCK_LOCKS.
*
* - parallel recovery steps across all nodes
*
* All nodes attempt to update the control_lock lvb with the new generation
* number and jid bits, but only the first to get the control_lock EX will
* do so; others will see that it's already done (lvb already contains new
* generation number.)
*
* . All nodes get the same recover_prep/recover_slot/recover_done callbacks
* . All nodes attempt to set control_lock lvb gen + bits for the new gen
* . One node gets control_lock first and writes the lvb, others see it's done
* . All nodes attempt to recover jids for which they see control_lock bits set
* . One node succeeds for a jid, and that one clears the jid bit in the lvb
* . All nodes will eventually see all lvb bits clear and unblock locks
*
* - is there a problem with clearing an lvb bit that should be set
* and missing a journal recovery?
*
* 1. jid fails
* 2. lvb bit set for step 1
* 3. jid recovered for step 1
* 4. jid taken again (new mount)
* 5. jid fails (for step 4)
* 6. lvb bit set for step 5 (will already be set)
* 7. lvb bit cleared for step 3
*
* This is not a problem because the failure in step 5 does not
* require recovery, because the mount in step 4 could not have
* progressed far enough to unblock locks and access the fs. The
* control_mount() function waits for all recoveries to be complete
* for the latest lockspace generation before ever unblocking locks
* and returning. The mount in step 4 waits until the recovery in
* step 1 is done.
*
* - special case of first mounter: first node to mount the fs
*
* The first node to mount a gfs2 fs needs to check all the journals
* and recover any that need recovery before other nodes are allowed
* to mount the fs. (Others may begin mounting, but they must wait
* for the first mounter to be done before taking locks on the fs
* or accessing the fs.) This has two parts:
*
* 1. The mounted_lock tells a node it's the first to mount the fs.
* Each node holds the mounted_lock in PR while it's mounted.
* Each node tries to acquire the mounted_lock in EX when it mounts.
* If a node is granted the mounted_lock EX it means there are no
* other mounted nodes (no PR locks exist), and it is the first mounter.
* The mounted_lock is demoted to PR when first recovery is done, so
* others will fail to get an EX lock, but will get a PR lock.
*
* 2. The control_lock blocks others in control_mount() while the first
* mounter is doing first mount recovery of all journals.
* A mounting node needs to acquire control_lock in EX mode before
* it can proceed. The first mounter holds control_lock in EX while doing
* the first mount recovery, blocking mounts from other nodes, then demotes
* control_lock to NL when it's done (others_may_mount/first_done),
* allowing other nodes to continue mounting.
*
* first mounter:
* control_lock EX/NOQUEUE success
* mounted_lock EX/NOQUEUE success (no other PR, so no other mounters)
* set first=1
* do first mounter recovery
* mounted_lock EX->PR
* control_lock EX->NL, write lvb generation
*
* other mounter:
* control_lock EX/NOQUEUE success (if fail -EAGAIN, retry)
* mounted_lock EX/NOQUEUE fail -EAGAIN (expected due to other mounters PR)
* mounted_lock PR/NOQUEUE success
* read lvb generation
* control_lock EX->NL
* set first=0
*
* - mount during recovery
*
* If a node mounts while others are doing recovery (not first mounter),
* the mounting node will get its initial recover_done() callback without
* having seen any previous failures/callbacks.
*
* It must wait for all recoveries preceding its mount to be finished
* before it unblocks locks. It does this by repeating the "other mounter"
* steps above until the lvb generation number is >= its mount generation
* number (from initial recover_done) and all lvb bits are clear.
*
* - control_lock lvb format
*
* 4 bytes generation number: the latest dlm lockspace generation number
* from recover_done callback. Indicates the jid bitmap has been updated
* to reflect all slot failures through that generation.
* 4 bytes unused.
* GDLM_LVB_SIZE-8 bytes of jid bit map. If bit N is set, it indicates
* that jid N needs recovery.
*/
#define JID_BITMAP_OFFSET 8 /* 4 byte generation number + 4 byte unused */
static void control_lvb_read(struct lm_lockstruct *ls, uint32_t *lvb_gen,
char *lvb_bits)
{
__le32 gen;
memcpy(lvb_bits, ls->ls_control_lvb, GDLM_LVB_SIZE);
memcpy(&gen, lvb_bits, sizeof(__le32));
*lvb_gen = le32_to_cpu(gen);
}
static void control_lvb_write(struct lm_lockstruct *ls, uint32_t lvb_gen,
char *lvb_bits)
{
__le32 gen;
memcpy(ls->ls_control_lvb, lvb_bits, GDLM_LVB_SIZE);
gen = cpu_to_le32(lvb_gen);
memcpy(ls->ls_control_lvb, &gen, sizeof(__le32));
}
static int all_jid_bits_clear(char *lvb)
{
return !memchr_inv(lvb + JID_BITMAP_OFFSET, 0,
GDLM_LVB_SIZE - JID_BITMAP_OFFSET);
}
static void sync_wait_cb(void *arg)
{
struct lm_lockstruct *ls = arg;
complete(&ls->ls_sync_wait);
}
static int sync_unlock(struct gfs2_sbd *sdp, struct dlm_lksb *lksb, char *name)
{
struct lm_lockstruct *ls = &sdp->sd_lockstruct;
int error;
error = dlm_unlock(ls->ls_dlm, lksb->sb_lkid, 0, lksb, ls);
if (error) {
fs_err(sdp, "%s lkid %x error %d\n",
name, lksb->sb_lkid, error);
return error;
}
wait_for_completion(&ls->ls_sync_wait);
if (lksb->sb_status != -DLM_EUNLOCK) {
fs_err(sdp, "%s lkid %x status %d\n",
name, lksb->sb_lkid, lksb->sb_status);
return -1;
}
return 0;
}
static int sync_lock(struct gfs2_sbd *sdp, int mode, uint32_t flags,
unsigned int num, struct dlm_lksb *lksb, char *name)
{
struct lm_lockstruct *ls = &sdp->sd_lockstruct;
char strname[GDLM_STRNAME_BYTES];
int error, status;
memset(strname, 0, GDLM_STRNAME_BYTES);
snprintf(strname, GDLM_STRNAME_BYTES, "%8x%16x", LM_TYPE_NONDISK, num);
error = dlm_lock(ls->ls_dlm, mode, lksb, flags,
strname, GDLM_STRNAME_BYTES - 1,
0, sync_wait_cb, ls, NULL);
if (error) {
fs_err(sdp, "%s lkid %x flags %x mode %d error %d\n",
name, lksb->sb_lkid, flags, mode, error);
return error;
}
wait_for_completion(&ls->ls_sync_wait);
status = lksb->sb_status;
if (status && status != -EAGAIN) {
fs_err(sdp, "%s lkid %x flags %x mode %d status %d\n",
name, lksb->sb_lkid, flags, mode, status);
}
return status;
}
static int mounted_unlock(struct gfs2_sbd *sdp)
{
struct lm_lockstruct *ls = &sdp->sd_lockstruct;
return sync_unlock(sdp, &ls->ls_mounted_lksb, "mounted_lock");
}
static int mounted_lock(struct gfs2_sbd *sdp, int mode, uint32_t flags)
{
struct lm_lockstruct *ls = &sdp->sd_lockstruct;
return sync_lock(sdp, mode, flags, GFS2_MOUNTED_LOCK,
&ls->ls_mounted_lksb, "mounted_lock");
}
static int control_unlock(struct gfs2_sbd *sdp)
{
struct lm_lockstruct *ls = &sdp->sd_lockstruct;
return sync_unlock(sdp, &ls->ls_control_lksb, "control_lock");
}
static int control_lock(struct gfs2_sbd *sdp, int mode, uint32_t flags)
{
struct lm_lockstruct *ls = &sdp->sd_lockstruct;
return sync_lock(sdp, mode, flags, GFS2_CONTROL_LOCK,
&ls->ls_control_lksb, "control_lock");
}
static void gfs2_control_func(struct work_struct *work)
{
struct gfs2_sbd *sdp = container_of(work, struct gfs2_sbd, sd_control_work.work);
struct lm_lockstruct *ls = &sdp->sd_lockstruct;
uint32_t block_gen, start_gen, lvb_gen, flags;
int recover_set = 0;
int write_lvb = 0;
int recover_size;
int i, error;
spin_lock(&ls->ls_recover_spin);
/*
* No MOUNT_DONE means we're still mounting; control_mount()
* will set this flag, after which this thread will take over
* all further clearing of BLOCK_LOCKS.
*
* FIRST_MOUNT means this node is doing first mounter recovery,
* for which recovery control is handled by
* control_mount()/control_first_done(), not this thread.
*/
if (!test_bit(DFL_MOUNT_DONE, &ls->ls_recover_flags) ||
test_bit(DFL_FIRST_MOUNT, &ls->ls_recover_flags)) {
spin_unlock(&ls->ls_recover_spin);
return;
}
block_gen = ls->ls_recover_block;
start_gen = ls->ls_recover_start;
spin_unlock(&ls->ls_recover_spin);
/*
* Equal block_gen and start_gen implies we are between
* recover_prep and recover_done callbacks, which means
* dlm recovery is in progress and dlm locking is blocked.
* There's no point trying to do any work until recover_done.
*/
if (block_gen == start_gen)
return;
/*
* Propagate recover_submit[] and recover_result[] to lvb:
* dlm_recoverd adds to recover_submit[] jids needing recovery
* gfs2_recover adds to recover_result[] journal recovery results
*
* set lvb bit for jids in recover_submit[] if the lvb has not
* yet been updated for the generation of the failure
*
* clear lvb bit for jids in recover_result[] if the result of
* the journal recovery is SUCCESS
*/
error = control_lock(sdp, DLM_LOCK_EX, DLM_LKF_CONVERT|DLM_LKF_VALBLK);
if (error) {
fs_err(sdp, "control lock EX error %d\n", error);
return;
}
control_lvb_read(ls, &lvb_gen, ls->ls_lvb_bits);
spin_lock(&ls->ls_recover_spin);
if (block_gen != ls->ls_recover_block ||
start_gen != ls->ls_recover_start) {
fs_info(sdp, "recover generation %u block1 %u %u\n",
start_gen, block_gen, ls->ls_recover_block);
spin_unlock(&ls->ls_recover_spin);
control_lock(sdp, DLM_LOCK_NL, DLM_LKF_CONVERT);
return;
}
recover_size = ls->ls_recover_size;
if (lvb_gen <= start_gen) {
/*
* Clear lvb bits for jids we've successfully recovered.
* Because all nodes attempt to recover failed journals,
* a journal can be recovered multiple times successfully
* in succession. Only the first will really do recovery,
* the others find it clean, but still report a successful
* recovery. So, another node may have already recovered
* the jid and cleared the lvb bit for it.
*/
for (i = 0; i < recover_size; i++) {
if (ls->ls_recover_result[i] != LM_RD_SUCCESS)
continue;
ls->ls_recover_result[i] = 0;
if (!test_bit_le(i, ls->ls_lvb_bits + JID_BITMAP_OFFSET))
continue;
__clear_bit_le(i, ls->ls_lvb_bits + JID_BITMAP_OFFSET);
write_lvb = 1;
}
}
if (lvb_gen == start_gen) {
/*
* Failed slots before start_gen are already set in lvb.
*/
for (i = 0; i < recover_size; i++) {
if (!ls->ls_recover_submit[i])
continue;
if (ls->ls_recover_submit[i] < lvb_gen)
ls->ls_recover_submit[i] = 0;
}
} else if (lvb_gen < start_gen) {
/*
* Failed slots before start_gen are not yet set in lvb.
*/
for (i = 0; i < recover_size; i++) {
if (!ls->ls_recover_submit[i])
continue;
if (ls->ls_recover_submit[i] < start_gen) {
ls->ls_recover_submit[i] = 0;
__set_bit_le(i, ls->ls_lvb_bits + JID_BITMAP_OFFSET);
}
}
/* even if there are no bits to set, we need to write the
latest generation to the lvb */
write_lvb = 1;
} else {
/*
* we should be getting a recover_done() for lvb_gen soon
*/
}
spin_unlock(&ls->ls_recover_spin);
if (write_lvb) {
control_lvb_write(ls, start_gen, ls->ls_lvb_bits);
flags = DLM_LKF_CONVERT | DLM_LKF_VALBLK;
} else {
flags = DLM_LKF_CONVERT;
}
error = control_lock(sdp, DLM_LOCK_NL, flags);
if (error) {
fs_err(sdp, "control lock NL error %d\n", error);
return;
}
/*
* Everyone will see jid bits set in the lvb, run gfs2_recover_set(),
* and clear a jid bit in the lvb if the recovery is a success.
* Eventually all journals will be recovered, all jid bits will
* be cleared in the lvb, and everyone will clear BLOCK_LOCKS.
*/
for (i = 0; i < recover_size; i++) {
if (test_bit_le(i, ls->ls_lvb_bits + JID_BITMAP_OFFSET)) {
fs_info(sdp, "recover generation %u jid %d\n",
start_gen, i);
gfs2_recover_set(sdp, i);
recover_set++;
}
}
if (recover_set)
return;
/*
* No more jid bits set in lvb, all recovery is done, unblock locks
* (unless a new recover_prep callback has occured blocking locks
* again while working above)
*/
spin_lock(&ls->ls_recover_spin);
if (ls->ls_recover_block == block_gen &&
ls->ls_recover_start == start_gen) {
clear_bit(DFL_BLOCK_LOCKS, &ls->ls_recover_flags);
spin_unlock(&ls->ls_recover_spin);
fs_info(sdp, "recover generation %u done\n", start_gen);
gfs2_glock_thaw(sdp);
} else {
fs_info(sdp, "recover generation %u block2 %u %u\n",
start_gen, block_gen, ls->ls_recover_block);
spin_unlock(&ls->ls_recover_spin);
}
}
static int control_mount(struct gfs2_sbd *sdp)
{
struct lm_lockstruct *ls = &sdp->sd_lockstruct;
uint32_t start_gen, block_gen, mount_gen, lvb_gen;
int mounted_mode;
int retries = 0;
int error;
memset(&ls->ls_mounted_lksb, 0, sizeof(struct dlm_lksb));
memset(&ls->ls_control_lksb, 0, sizeof(struct dlm_lksb));
memset(&ls->ls_control_lvb, 0, GDLM_LVB_SIZE);
ls->ls_control_lksb.sb_lvbptr = ls->ls_control_lvb;
init_completion(&ls->ls_sync_wait);
set_bit(DFL_BLOCK_LOCKS, &ls->ls_recover_flags);
error = control_lock(sdp, DLM_LOCK_NL, DLM_LKF_VALBLK);
if (error) {
fs_err(sdp, "control_mount control_lock NL error %d\n", error);
return error;
}
error = mounted_lock(sdp, DLM_LOCK_NL, 0);
if (error) {
fs_err(sdp, "control_mount mounted_lock NL error %d\n", error);
control_unlock(sdp);
return error;
}
mounted_mode = DLM_LOCK_NL;
restart:
if (retries++ && signal_pending(current)) {
error = -EINTR;
goto fail;
}
/*
* We always start with both locks in NL. control_lock is
* demoted to NL below so we don't need to do it here.
*/
if (mounted_mode != DLM_LOCK_NL) {
error = mounted_lock(sdp, DLM_LOCK_NL, DLM_LKF_CONVERT);
if (error)
goto fail;
mounted_mode = DLM_LOCK_NL;
}
/*
* Other nodes need to do some work in dlm recovery and gfs2_control
* before the recover_done and control_lock will be ready for us below.
* A delay here is not required but often avoids having to retry.
*/
msleep_interruptible(500);
/*
* Acquire control_lock in EX and mounted_lock in either EX or PR.
* control_lock lvb keeps track of any pending journal recoveries.
* mounted_lock indicates if any other nodes have the fs mounted.
*/
error = control_lock(sdp, DLM_LOCK_EX, DLM_LKF_CONVERT|DLM_LKF_NOQUEUE|DLM_LKF_VALBLK);
if (error == -EAGAIN) {
goto restart;
} else if (error) {
fs_err(sdp, "control_mount control_lock EX error %d\n", error);
goto fail;
}
error = mounted_lock(sdp, DLM_LOCK_EX, DLM_LKF_CONVERT|DLM_LKF_NOQUEUE);
if (!error) {
mounted_mode = DLM_LOCK_EX;
goto locks_done;
} else if (error != -EAGAIN) {
fs_err(sdp, "control_mount mounted_lock EX error %d\n", error);
goto fail;
}
error = mounted_lock(sdp, DLM_LOCK_PR, DLM_LKF_CONVERT|DLM_LKF_NOQUEUE);
if (!error) {
mounted_mode = DLM_LOCK_PR;
goto locks_done;
} else {
/* not even -EAGAIN should happen here */
fs_err(sdp, "control_mount mounted_lock PR error %d\n", error);
goto fail;
}
locks_done:
/*
* If we got both locks above in EX, then we're the first mounter.
* If not, then we need to wait for the control_lock lvb to be
* updated by other mounted nodes to reflect our mount generation.
*
* In simple first mounter cases, first mounter will see zero lvb_gen,
* but in cases where all existing nodes leave/fail before mounting
* nodes finish control_mount, then all nodes will be mounting and
* lvb_gen will be non-zero.
*/
control_lvb_read(ls, &lvb_gen, ls->ls_lvb_bits);
if (lvb_gen == 0xFFFFFFFF) {
/* special value to force mount attempts to fail */
fs_err(sdp, "control_mount control_lock disabled\n");
error = -EINVAL;
goto fail;
}
if (mounted_mode == DLM_LOCK_EX) {
/* first mounter, keep both EX while doing first recovery */
spin_lock(&ls->ls_recover_spin);
clear_bit(DFL_BLOCK_LOCKS, &ls->ls_recover_flags);
set_bit(DFL_MOUNT_DONE, &ls->ls_recover_flags);
set_bit(DFL_FIRST_MOUNT, &ls->ls_recover_flags);
spin_unlock(&ls->ls_recover_spin);
fs_info(sdp, "first mounter control generation %u\n", lvb_gen);
return 0;
}
error = control_lock(sdp, DLM_LOCK_NL, DLM_LKF_CONVERT);
if (error)
goto fail;
/*
* We are not first mounter, now we need to wait for the control_lock
* lvb generation to be >= the generation from our first recover_done
* and all lvb bits to be clear (no pending journal recoveries.)
*/
if (!all_jid_bits_clear(ls->ls_lvb_bits)) {
/* journals need recovery, wait until all are clear */
fs_info(sdp, "control_mount wait for journal recovery\n");
goto restart;
}
spin_lock(&ls->ls_recover_spin);
block_gen = ls->ls_recover_block;
start_gen = ls->ls_recover_start;
mount_gen = ls->ls_recover_mount;
if (lvb_gen < mount_gen) {
/* wait for mounted nodes to update control_lock lvb to our
generation, which might include new recovery bits set */
fs_info(sdp, "control_mount wait1 block %u start %u mount %u "
"lvb %u flags %lx\n", block_gen, start_gen, mount_gen,
lvb_gen, ls->ls_recover_flags);
spin_unlock(&ls->ls_recover_spin);
goto restart;
}
if (lvb_gen != start_gen) {
/* wait for mounted nodes to update control_lock lvb to the
latest recovery generation */
fs_info(sdp, "control_mount wait2 block %u start %u mount %u "
"lvb %u flags %lx\n", block_gen, start_gen, mount_gen,
lvb_gen, ls->ls_recover_flags);
spin_unlock(&ls->ls_recover_spin);
goto restart;
}
if (block_gen == start_gen) {
/* dlm recovery in progress, wait for it to finish */
fs_info(sdp, "control_mount wait3 block %u start %u mount %u "
"lvb %u flags %lx\n", block_gen, start_gen, mount_gen,
lvb_gen, ls->ls_recover_flags);
spin_unlock(&ls->ls_recover_spin);
goto restart;
}
clear_bit(DFL_BLOCK_LOCKS, &ls->ls_recover_flags);
set_bit(DFL_MOUNT_DONE, &ls->ls_recover_flags);
memset(ls->ls_recover_submit, 0, ls->ls_recover_size*sizeof(uint32_t));
memset(ls->ls_recover_result, 0, ls->ls_recover_size*sizeof(uint32_t));
spin_unlock(&ls->ls_recover_spin);
return 0;
fail:
mounted_unlock(sdp);
control_unlock(sdp);
return error;
}
static int control_first_done(struct gfs2_sbd *sdp)
{
struct lm_lockstruct *ls = &sdp->sd_lockstruct;
uint32_t start_gen, block_gen;
int error;
restart:
spin_lock(&ls->ls_recover_spin);
start_gen = ls->ls_recover_start;
block_gen = ls->ls_recover_block;
if (test_bit(DFL_BLOCK_LOCKS, &ls->ls_recover_flags) ||
!test_bit(DFL_MOUNT_DONE, &ls->ls_recover_flags) ||
!test_bit(DFL_FIRST_MOUNT, &ls->ls_recover_flags)) {
/* sanity check, should not happen */
fs_err(sdp, "control_first_done start %u block %u flags %lx\n",
start_gen, block_gen, ls->ls_recover_flags);
spin_unlock(&ls->ls_recover_spin);
control_unlock(sdp);
return -1;
}
if (start_gen == block_gen) {
/*
* Wait for the end of a dlm recovery cycle to switch from
* first mounter recovery. We can ignore any recover_slot
* callbacks between the recover_prep and next recover_done
* because we are still the first mounter and any failed nodes
* have not fully mounted, so they don't need recovery.
*/
spin_unlock(&ls->ls_recover_spin);
fs_info(sdp, "control_first_done wait gen %u\n", start_gen);
wait_on_bit(&ls->ls_recover_flags, DFL_DLM_RECOVERY,
TASK_UNINTERRUPTIBLE);
goto restart;
}
clear_bit(DFL_FIRST_MOUNT, &ls->ls_recover_flags);
set_bit(DFL_FIRST_MOUNT_DONE, &ls->ls_recover_flags);
memset(ls->ls_recover_submit, 0, ls->ls_recover_size*sizeof(uint32_t));
memset(ls->ls_recover_result, 0, ls->ls_recover_size*sizeof(uint32_t));
spin_unlock(&ls->ls_recover_spin);
memset(ls->ls_lvb_bits, 0, GDLM_LVB_SIZE);
control_lvb_write(ls, start_gen, ls->ls_lvb_bits);
error = mounted_lock(sdp, DLM_LOCK_PR, DLM_LKF_CONVERT);
if (error)
fs_err(sdp, "control_first_done mounted PR error %d\n", error);
error = control_lock(sdp, DLM_LOCK_NL, DLM_LKF_CONVERT|DLM_LKF_VALBLK);
if (error)
fs_err(sdp, "control_first_done control NL error %d\n", error);
return error;
}
/*
* Expand static jid arrays if necessary (by increments of RECOVER_SIZE_INC)
* to accomodate the largest slot number. (NB dlm slot numbers start at 1,
* gfs2 jids start at 0, so jid = slot - 1)
*/
#define RECOVER_SIZE_INC 16
static int set_recover_size(struct gfs2_sbd *sdp, struct dlm_slot *slots,
int num_slots)
{
struct lm_lockstruct *ls = &sdp->sd_lockstruct;
uint32_t *submit = NULL;
uint32_t *result = NULL;
uint32_t old_size, new_size;
int i, max_jid;
if (!ls->ls_lvb_bits) {
ls->ls_lvb_bits = kzalloc(GDLM_LVB_SIZE, GFP_NOFS);
if (!ls->ls_lvb_bits)
return -ENOMEM;
}
max_jid = 0;
for (i = 0; i < num_slots; i++) {
if (max_jid < slots[i].slot - 1)
max_jid = slots[i].slot - 1;
}
old_size = ls->ls_recover_size;
if (old_size >= max_jid + 1)
return 0;
new_size = old_size + RECOVER_SIZE_INC;
submit = kcalloc(new_size, sizeof(uint32_t), GFP_NOFS);
result = kcalloc(new_size, sizeof(uint32_t), GFP_NOFS);
if (!submit || !result) {
kfree(submit);
kfree(result);
return -ENOMEM;
}
spin_lock(&ls->ls_recover_spin);
memcpy(submit, ls->ls_recover_submit, old_size * sizeof(uint32_t));
memcpy(result, ls->ls_recover_result, old_size * sizeof(uint32_t));
kfree(ls->ls_recover_submit);
kfree(ls->ls_recover_result);
ls->ls_recover_submit = submit;
ls->ls_recover_result = result;
ls->ls_recover_size = new_size;
spin_unlock(&ls->ls_recover_spin);
return 0;
}
static void free_recover_size(struct lm_lockstruct *ls)
{
kfree(ls->ls_lvb_bits);
kfree(ls->ls_recover_submit);
kfree(ls->ls_recover_result);
ls->ls_recover_submit = NULL;
ls->ls_recover_result = NULL;
ls->ls_recover_size = 0;
ls->ls_lvb_bits = NULL;
}
/* dlm calls before it does lock recovery */
static void gdlm_recover_prep(void *arg)
{
struct gfs2_sbd *sdp = arg;
struct lm_lockstruct *ls = &sdp->sd_lockstruct;
spin_lock(&ls->ls_recover_spin);
ls->ls_recover_block = ls->ls_recover_start;
set_bit(DFL_DLM_RECOVERY, &ls->ls_recover_flags);
if (!test_bit(DFL_MOUNT_DONE, &ls->ls_recover_flags) ||
test_bit(DFL_FIRST_MOUNT, &ls->ls_recover_flags)) {
spin_unlock(&ls->ls_recover_spin);
return;
}
set_bit(DFL_BLOCK_LOCKS, &ls->ls_recover_flags);
spin_unlock(&ls->ls_recover_spin);
}
/* dlm calls after recover_prep has been completed on all lockspace members;
identifies slot/jid of failed member */
static void gdlm_recover_slot(void *arg, struct dlm_slot *slot)
{
struct gfs2_sbd *sdp = arg;
struct lm_lockstruct *ls = &sdp->sd_lockstruct;
int jid = slot->slot - 1;
spin_lock(&ls->ls_recover_spin);
if (ls->ls_recover_size < jid + 1) {
fs_err(sdp, "recover_slot jid %d gen %u short size %d",
jid, ls->ls_recover_block, ls->ls_recover_size);
spin_unlock(&ls->ls_recover_spin);
return;
}
if (ls->ls_recover_submit[jid]) {
fs_info(sdp, "recover_slot jid %d gen %u prev %u\n",
jid, ls->ls_recover_block, ls->ls_recover_submit[jid]);
}
ls->ls_recover_submit[jid] = ls->ls_recover_block;
spin_unlock(&ls->ls_recover_spin);
}
/* dlm calls after recover_slot and after it completes lock recovery */
static void gdlm_recover_done(void *arg, struct dlm_slot *slots, int num_slots,
int our_slot, uint32_t generation)
{
struct gfs2_sbd *sdp = arg;
struct lm_lockstruct *ls = &sdp->sd_lockstruct;
/* ensure the ls jid arrays are large enough */
set_recover_size(sdp, slots, num_slots);
spin_lock(&ls->ls_recover_spin);
ls->ls_recover_start = generation;
if (!ls->ls_recover_mount) {
ls->ls_recover_mount = generation;
ls->ls_jid = our_slot - 1;
}
if (!test_bit(DFL_UNMOUNT, &ls->ls_recover_flags))
queue_delayed_work(gfs2_control_wq, &sdp->sd_control_work, 0);
clear_bit(DFL_DLM_RECOVERY, &ls->ls_recover_flags);
smp_mb__after_atomic();
wake_up_bit(&ls->ls_recover_flags, DFL_DLM_RECOVERY);
spin_unlock(&ls->ls_recover_spin);
}
/* gfs2_recover thread has a journal recovery result */
static void gdlm_recovery_result(struct gfs2_sbd *sdp, unsigned int jid,
unsigned int result)
{
struct lm_lockstruct *ls = &sdp->sd_lockstruct;
if (test_bit(DFL_NO_DLM_OPS, &ls->ls_recover_flags))
return;
/* don't care about the recovery of own journal during mount */
if (jid == ls->ls_jid)
return;
spin_lock(&ls->ls_recover_spin);
if (test_bit(DFL_FIRST_MOUNT, &ls->ls_recover_flags)) {
spin_unlock(&ls->ls_recover_spin);
return;
}
if (ls->ls_recover_size < jid + 1) {
fs_err(sdp, "recovery_result jid %d short size %d",
jid, ls->ls_recover_size);
spin_unlock(&ls->ls_recover_spin);
return;
}
fs_info(sdp, "recover jid %d result %s\n", jid,
result == LM_RD_GAVEUP ? "busy" : "success");
ls->ls_recover_result[jid] = result;
/* GAVEUP means another node is recovering the journal; delay our
next attempt to recover it, to give the other node a chance to
finish before trying again */
if (!test_bit(DFL_UNMOUNT, &ls->ls_recover_flags))
queue_delayed_work(gfs2_control_wq, &sdp->sd_control_work,
result == LM_RD_GAVEUP ? HZ : 0);
spin_unlock(&ls->ls_recover_spin);
}
static const struct dlm_lockspace_ops gdlm_lockspace_ops = {
.recover_prep = gdlm_recover_prep,
.recover_slot = gdlm_recover_slot,
.recover_done = gdlm_recover_done,
};
static int gdlm_mount(struct gfs2_sbd *sdp, const char *table)
{
struct lm_lockstruct *ls = &sdp->sd_lockstruct;
char cluster[GFS2_LOCKNAME_LEN];
const char *fsname;
uint32_t flags;
int error, ops_result;
/*
* initialize everything
*/
INIT_DELAYED_WORK(&sdp->sd_control_work, gfs2_control_func);
spin_lock_init(&ls->ls_recover_spin);
ls->ls_recover_flags = 0;
ls->ls_recover_mount = 0;
ls->ls_recover_start = 0;
ls->ls_recover_block = 0;
ls->ls_recover_size = 0;
ls->ls_recover_submit = NULL;
ls->ls_recover_result = NULL;
ls->ls_lvb_bits = NULL;
error = set_recover_size(sdp, NULL, 0);
if (error)
goto fail;
/*
* prepare dlm_new_lockspace args
*/
fsname = strchr(table, ':');
if (!fsname) {
fs_info(sdp, "no fsname found\n");
error = -EINVAL;
goto fail_free;
}
memset(cluster, 0, sizeof(cluster));
memcpy(cluster, table, strlen(table) - strlen(fsname));
fsname++;
flags = DLM_LSFL_FS | DLM_LSFL_NEWEXCL;
/*
* create/join lockspace
*/
error = dlm_new_lockspace(fsname, cluster, flags, GDLM_LVB_SIZE,
&gdlm_lockspace_ops, sdp, &ops_result,
&ls->ls_dlm);
if (error) {
fs_err(sdp, "dlm_new_lockspace error %d\n", error);
goto fail_free;
}
if (ops_result < 0) {
/*
* dlm does not support ops callbacks,
* old dlm_controld/gfs_controld are used, try without ops.
*/
fs_info(sdp, "dlm lockspace ops not used\n");
free_recover_size(ls);
set_bit(DFL_NO_DLM_OPS, &ls->ls_recover_flags);
return 0;
}
if (!test_bit(SDF_NOJOURNALID, &sdp->sd_flags)) {
fs_err(sdp, "dlm lockspace ops disallow jid preset\n");
error = -EINVAL;
goto fail_release;
}
/*
* control_mount() uses control_lock to determine first mounter,
* and for later mounts, waits for any recoveries to be cleared.
*/
error = control_mount(sdp);
if (error) {
fs_err(sdp, "mount control error %d\n", error);
goto fail_release;
}
ls->ls_first = !!test_bit(DFL_FIRST_MOUNT, &ls->ls_recover_flags);
clear_bit(SDF_NOJOURNALID, &sdp->sd_flags);
smp_mb__after_atomic();
wake_up_bit(&sdp->sd_flags, SDF_NOJOURNALID);
return 0;
fail_release:
dlm_release_lockspace(ls->ls_dlm, 2);
fail_free:
free_recover_size(ls);
fail:
return error;
}
static void gdlm_first_done(struct gfs2_sbd *sdp)
{
struct lm_lockstruct *ls = &sdp->sd_lockstruct;
int error;
if (test_bit(DFL_NO_DLM_OPS, &ls->ls_recover_flags))
return;
error = control_first_done(sdp);
if (error)
fs_err(sdp, "mount first_done error %d\n", error);
}
static void gdlm_unmount(struct gfs2_sbd *sdp)
{
struct lm_lockstruct *ls = &sdp->sd_lockstruct;
if (test_bit(DFL_NO_DLM_OPS, &ls->ls_recover_flags))
goto release;
/* wait for gfs2_control_wq to be done with this mount */
spin_lock(&ls->ls_recover_spin);
set_bit(DFL_UNMOUNT, &ls->ls_recover_flags);
spin_unlock(&ls->ls_recover_spin);
flush_delayed_work(&sdp->sd_control_work);
/* mounted_lock and control_lock will be purged in dlm recovery */
release:
if (ls->ls_dlm) {
dlm_release_lockspace(ls->ls_dlm, 2);
ls->ls_dlm = NULL;
}
free_recover_size(ls);
}
static const match_table_t dlm_tokens = {
{ Opt_jid, "jid=%d"},
{ Opt_id, "id=%d"},
{ Opt_first, "first=%d"},
{ Opt_nodir, "nodir=%d"},
{ Opt_err, NULL },
};
const struct lm_lockops gfs2_dlm_ops = {
.lm_proto_name = "lock_dlm",
.lm_mount = gdlm_mount,
.lm_first_done = gdlm_first_done,
.lm_recovery_result = gdlm_recovery_result,
.lm_unmount = gdlm_unmount,
.lm_put_lock = gdlm_put_lock,
.lm_lock = gdlm_lock,
.lm_cancel = gdlm_cancel,
.lm_tokens = &dlm_tokens,
};
| {
"pile_set_name": "Github"
} |
/*
* RapCAD - Rapid prototyping CAD IDE (www.rapcad.org)
* Copyright (C) 2010-2020 Giles Bathgate
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "projectionmodule.h"
#include "node/projectionnode.h"
#include "node/slicenode.h"
#include "context.h"
#include "booleanvalue.h"
ProjectionModule::ProjectionModule(Reporter& r) : Module(r,"projection")
{
addDescription(tr("Flattens its children onto the xy plane."));
addParameter("base",tr("Specifies that only polygons with normals perpendicular to the xy plane be considered."));
}
Node* ProjectionModule::evaluate(const Context& ctx) const
{
BooleanValue* cut=dynamic_cast<BooleanValue*>(ctx.getArgumentDeprecatedModule(0,"cut","'slice' module",reporter));
if(cut&&cut->isTrue()) {
auto* n=new SliceNode();
n->setChildren(ctx.getInputNodes());
return n;
}
bool base=false;
auto* baseVal=dynamic_cast<BooleanValue*>(getParameterArgument(ctx,0));
if(baseVal)
base=baseVal->isTrue();
auto* d = new ProjectionNode();
d->setChildren(ctx.getInputNodes());
d->setBase(base);
return d;
}
| {
"pile_set_name": "Github"
} |
/*
Decoda
Copyright (C) 2007-2013 Unknown Worlds Entertainment, Inc.
This file is part of Decoda.
Decoda 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.
Decoda 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 Decoda. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef PROCESSES_DIALOG_H
#define PROCESSES_DIALOG_H
#include <wx/wx.h>
#include "DebugFrontend.h"
//
// Forward declarations.
//
class wxListCtrl;
class wxListEvent;
/**
* Dialog box for allowing the user to attach to an existing process.
*/
class ProcessesDialog : public wxDialog
{
public:
/**
* Constructor.
*/
explicit ProcessesDialog( wxWindow* parent);
/**
* Called when the user presses the Attach button.
*/
void OnAttach(wxCommandEvent& event);
/**
* Called when the user presses the Refresh button.
*/
void OnRefresh(wxCommandEvent& event);
/**
* Called when the user presses the Cancel button.
*/
void OnCancel(wxCommandEvent& event);
/**
* Called when the user selects a new item in the process list.
*/
void OnProcessSelected(wxListEvent& event);
/**
* Called when the user unselects an item in the process list.
*/
void OnProcessDeselected(wxListEvent& event);
/**
* Called when the user clicks on one of the column headings in the
* process list.
*/
void OnProcessColumnClicked(wxListEvent& event);
/**
* Called when the user double clicks on one of the items in the processes
* list.
*/
void OnProcessActivated(wxListEvent& event);
/**
* Returns the process id that the user has selected.
*/
unsigned int GetProcessId() const;
/**
* Selects the process with the specified module name (if one exists) in
* the dialog.
*/
void SelectProcessByModule(const wxString& name);
DECLARE_EVENT_TABLE()
private:
enum ID
{
ID_Refresh = 1,
};
/**
* Updates the list of processes.
*/
void Refresh();
/**
* Updates the status of the Attach button based on whether or not a process is
* selected.
*/
void UpdateAttachStatus();
/**
* Sorts the process list by the specified column.
*/
void SortColumns();
/**
* Function used to sort the columns of the list box.
*/
static int wxCALLBACK SortCompareFunction(long item1, long item2, long sortData);
private:
unsigned int m_processId;
std::vector<DebugFrontend::Process> m_processes;
wxListCtrl* m_processList;
wxButton* m_attach;
wxButton* m_refresh;
wxButton* m_close;
int m_sortColumn;
bool m_sortForward;
};
#endif | {
"pile_set_name": "Github"
} |
--TEST--
chmod() with various paths
--SKIPIF--
<?php
if (substr(PHP_OS, 0, 3) == 'WIN') {
die('skip non-windows only test');
}
?>
--FILE--
<?php
define("PERMISSIONS_MASK", 0777);
$script_directory = dirname(__FILE__);
chdir($script_directory);
$test_dirname = basename(__FILE__, ".php") . "testdir";
mkdir($test_dirname);
$filepath = __FILE__ . ".tmp";
$filename = basename($filepath);
$fd = fopen($filepath, "w+");
fclose($fd);
echo "chmod() on a path containing .. and .\n";
var_dump(chmod("./$test_dirname/../$filename", 0777));
var_dump(chmod("./$test_dirname/../$filename", 0755));
clearstatcache();
printf("%o\n", fileperms($filepath) & PERMISSIONS_MASK);
echo "\nchmod() on a path containing .. with invalid directories\n";
var_dump(chmod($filepath, 0777));
var_dump(chmod("./$test_dirname/bad_dir/../../$filename", 0755));
clearstatcache();
printf("%o\n", fileperms($filepath) & PERMISSIONS_MASK);
echo "\nchmod() on a linked file\n";
$linkname = "somelink";
var_dump(symlink($filepath, $linkname));
var_dump(chmod($filepath, 0777));
var_dump(chmod($linkname, 0755));
clearstatcache();
printf("%o\n", fileperms($filepath) & PERMISSIONS_MASK);
var_dump(unlink($linkname));
echo "\nchmod() on a relative path from a different working directory\n";
chdir($test_dirname);
var_dump(chmod("../$filename", 0777));
var_dump(chmod("../$filename", 0755));
clearstatcache();
printf("%o\n", fileperms($filepath) & PERMISSIONS_MASK);
chdir($script_directory);
echo "\nchmod() on a directory with a trailing /\n";
var_dump(chmod($test_dirname, 0777));
var_dump(chmod("$test_dirname/", 0775));
clearstatcache();
printf("%o\n", fileperms($filepath) & PERMISSIONS_MASK);
chdir($script_directory);
rmdir($test_dirname);
unlink($filepath);
?>
--EXPECTF--
chmod() on a path containing .. and .
bool(true)
bool(true)
755
chmod() on a path containing .. with invalid directories
bool(true)
Warning: chmod(): No such file or directory in %s on line %d
bool(false)
777
chmod() on a linked file
bool(true)
bool(true)
bool(true)
755
bool(true)
chmod() on a relative path from a different working directory
bool(true)
bool(true)
755
chmod() on a directory with a trailing /
bool(true)
bool(true)
755
| {
"pile_set_name": "Github"
} |
/**
* @file BProto.h
* @author Ambroz Bizjak <[email protected]>
*
* @section LICENSE
*
* 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. Neither the name of the author nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @section DESCRIPTION
*
* Definitions for BProto serialization.
*/
#ifndef BADVPN_BPROTO_BPROTO_H
#define BADVPN_BPROTO_BPROTO_H
#include <stdint.h>
#include <misc/packed.h>
#define BPROTO_TYPE_UINT8 1
#define BPROTO_TYPE_UINT16 2
#define BPROTO_TYPE_UINT32 3
#define BPROTO_TYPE_UINT64 4
#define BPROTO_TYPE_DATA 5
#define BPROTO_TYPE_CONSTDATA 6
B_START_PACKED
struct BProto_header_s {
uint16_t id;
uint16_t type;
} B_PACKED;
B_END_PACKED
B_START_PACKED
struct BProto_uint8_s {
uint8_t v;
} B_PACKED;
B_END_PACKED
B_START_PACKED
struct BProto_uint16_s {
uint16_t v;
} B_PACKED;
B_END_PACKED
B_START_PACKED
struct BProto_uint32_s {
uint32_t v;
} B_PACKED;
B_END_PACKED
B_START_PACKED
struct BProto_uint64_s {
uint64_t v;
} B_PACKED;
B_END_PACKED
B_START_PACKED
struct BProto_data_header_s {
uint32_t len;
} B_PACKED;
B_END_PACKED
#endif
| {
"pile_set_name": "Github"
} |
const api = require('./apiQuery.js');
const Constructor = require('./ResponseClasses.js');
const pvQuery = {
getPV: (req, res, next) => {
api
.getPV()
.then(result =>
result.body.items.reduce((listOfPv, pv) => {
return listOfPv.concat([new Constructor.PVQueryBody(pv)]);
}, [])
)
.then(result => {
res.set({
'Content-Type': 'application/json'
});
res.write(JSON.stringify(result));
next();
})
.catch(err => console.log(err));
}
};
module.exports = pvQuery;
| {
"pile_set_name": "Github"
} |
import functools
func_list = []
def register(func):
global func_list
func_list.append(func)
@functools.wraps(func)
def wrapper(*args,**kwargs):
result = func(*args,**kwargs)
return result
return wrapper
@register
def add(x,y):
try:
x = int(x)
y = int(y)
except:
pass
return x+y
@register
def test(x):
return x
class E():
NAME = 'xujin'
def __init__(self,name,*args,**kwargs):
self.name = name
if __name__ == '__main__':
print("输入q退出命令模式")
while True:
cmd = input(">> 输入指令:")
result = "default"
if cmd == 'q':
break
for func in func_list:
if cmd == func.__name__:
args = input(">> 请输入参数,多个参数之间用','隔开:").split(',')
result = func(*args)
break
print(">> 结果:",result)
| {
"pile_set_name": "Github"
} |
<?php
//
// ______ ______ __ __ ______
// /\ ___\ /\ ___\ /\_\ /\_\ /\ __ \
// \/\ __\ \/\ \____ \/\_\ \/\_\ \/\ \_\ \
// \/\_____\ \/\_____\ /\_\/\_\ \/\_\ \/\_\ \_\
// \/_____/ \/_____/ \/__\/_/ \/_/ \/_/ /_/
//
// 上海商创网络科技有限公司
//
// ---------------------------------------------------------------------------------
//
// 一、协议的许可和权利
//
// 1. 您可以在完全遵守本协议的基础上,将本软件应用于商业用途;
// 2. 您可以在协议规定的约束和限制范围内修改本产品源代码或界面风格以适应您的要求;
// 3. 您拥有使用本产品中的全部内容资料、商品信息及其他信息的所有权,并独立承担与其内容相关的
// 法律义务;
// 4. 获得商业授权之后,您可以将本软件应用于商业用途,自授权时刻起,在技术支持期限内拥有通过
// 指定的方式获得指定范围内的技术支持服务;
//
// 二、协议的约束和限制
//
// 1. 未获商业授权之前,禁止将本软件用于商业用途(包括但不限于企业法人经营的产品、经营性产品
// 以及以盈利为目的或实现盈利产品);
// 2. 未获商业授权之前,禁止在本产品的整体或在任何部分基础上发展任何派生版本、修改版本或第三
// 方版本用于重新开发;
// 3. 如果您未能遵守本协议的条款,您的授权将被终止,所被许可的权利将被收回并承担相应法律责任;
//
// 三、有限担保和免责声明
//
// 1. 本软件及所附带的文件是作为不提供任何明确的或隐含的赔偿或担保的形式提供的;
// 2. 用户出于自愿而使用本软件,您必须了解使用本软件的风险,在尚未获得商业授权之前,我们不承
// 诺提供任何形式的技术支持、使用担保,也不承担任何因使用本软件而产生问题的相关责任;
// 3. 上海商创网络科技有限公司不对使用本产品构建的商城中的内容信息承担责任,但在不侵犯用户隐
// 私信息的前提下,保留以任何方式获取用户信息及商品信息的权利;
//
// 有关本产品最终用户授权协议、商业授权与技术服务的详细内容,均由上海商创网络科技有限公司独家
// 提供。上海商创网络科技有限公司拥有在不事先通知的情况下,修改授权协议的权力,修改后的协议对
// 改变之日起的新授权用户生效。电子文本形式的授权协议如同双方书面签署的协议一样,具有完全的和
// 等同的法律效力。您一旦开始修改、安装或使用本产品,即被视为完全理解并接受本协议的各项条款,
// 在享有上述条款授予的权力的同时,受到相关的约束和限制。协议许可范围以外的行为,将直接违反本
// 授权协议并构成侵权,我们有权随时终止授权,责令停止损害,并保留追究相关责任的权力。
//
// ---------------------------------------------------------------------------------
//
defined('IN_ECJIA') or exit('No permission resources.');
/**
* 支付通知确认撤消
* Class payment_notify_cancel_module
*/
class admin_payment_notify_cancel_module extends api_admin implements api_interface
{
/**
* @param string $order_trade_no
* @param array $notify_data 通知数据
*
* @param \Royalcms\Component\Http\Request $request
*/
public function handleRequest(\Royalcms\Component\HttpKernel\Request $request) {
if ($_SESSION['staff_id'] <= 0) {
return new ecjia_error(100, 'Invalid session');
}
$order_trade_no = $this->requestData('order_trade_no');
$notify_data = $this->requestData('notify_data');
$device = $this->device;
//传参判断
if (empty($order_trade_no) || empty($notify_data)) {
return new ecjia_error('invalid_parameter', sprintf(__('请求接口%s参数无效', 'payment'), __CLASS__));
}
//查找交易记录
$paymentRecordRepository = new Ecjia\App\Payment\Repositories\PaymentRecordRepository();
$record_model = $paymentRecordRepository->getPaymentRecord($order_trade_no);
if (empty($record_model)) {
return new ecjia_error('payment_record_not_found', __('此笔交易记录未找到', 'payment'));
}
//写业务逻辑
$result = (new Ecjia\App\Payment\Refund\CancelManager(null, $order_trade_no, null))->setNotifyData($notify_data)->cancel();
if (is_ecjia_error($result)) {
return $result;
}
//撤销成功
if ($result['cancel_status'] == 'success') {
//防止数据有更新,重新获取交易记录信息
$record_model = $paymentRecordRepository->getPaymentRecord($order_trade_no);
$trade_apps = [
'buy' => 'orders',
];
$paidOrderOrocess = RC_Api::api($trade_apps[$record_model->trade_type], 'payment_paid_process', ['record_model' => $record_model]);
$orderinfo = $paidOrderOrocess->getOrderInfo();
if (empty($orderinfo)) {
return new ecjia_error('order_dose_not_exist', $record_model->order_sn . __('未找到该订单信息', 'payment'));
}
//退款步骤;原路退回
$refund_result = $this->processOrderRefund($orderinfo, $device, $_SESSION['device_id'], $_SESSION['store_id'], $_SESSION['staff_id']);
if (is_ecjia_error($refund_result)) {
return $refund_result;
}
//退款步骤完成;更新各项数据
if (!empty($refund_result)) {
$refund_result['back_type'] = 'original';
$refund_result['refund_way'] = 'original';
$refund_result['is_cashdesk'] = 1;
$print_data = $this->ProcessRefundUpdateData($refund_result);
}
if (is_ecjia_error($print_data)) {
return $print_data;
}
return $print_data;
}
}
/**
* 退款步骤,原路退回
*/
private function processOrderRefund($order_info, $device, $device_id, $store_id, $staff_id)
{
/**
* 退款步骤
* 1、生成退款申请单 GenerateRefundOrder()
* 2、商家同意退款申请 RefundAgree()
* 3、买家退货给商家 RefundReturnWayShop()
* 4、商家确认收货 RefundMerchantConfirm()
*/
//生成退款申请单
$refundOrderInfo = $this->GenerateRefundOrder($order_info, $device, $device_id, $store_id, $staff_id);
if (is_ecjia_error($refundOrderInfo)) {
return $refundOrderInfo;
}
//商家同意退款申请
$refund_agree = $this->RefundAgree($refundOrderInfo);
if (is_ecjia_error($refund_agree)) {
return $refund_agree;
}
//买家退货给商家
if ($refund_agree) {
$refund_returnway_shop = $this->RefundReturnWayShop($refundOrderInfo);
}
if (is_ecjia_error($refund_returnway_shop)) {
return $refund_returnway_shop;
}
//商家确认收货
if ($refund_returnway_shop) {
$refund_merchant_confirm = $this->RefundMerchantConfirm($refundOrderInfo);
}
if (is_ecjia_error($refund_merchant_confirm)) {
return $refund_merchant_confirm;
}
$data = array(
'refund_order_info' => $refundOrderInfo,
'refund_payrecord_info' => $refund_merchant_confirm,
'order_info' => $order_info,
'staff_id' => $_SESSION['staff_id'],
'staff_name' => $_SESSION['staff_name'],
);
return $data;
}
/**
* 生成退款单
* @param array $order_info
* @return array | ecjia_error
*/
private function GenerateRefundOrder($order_info = array(), $device = array(), $device_id, $store_id, $staff_id)
{
//生成退款申请单
$reasons = RC_Loader::load_app_config('refund_reasons', 'refund');
$auto_refuse = $reasons['cashier_refund'];
$refund_reason = $auto_refuse['0']['reason_id'];
$refund_content = $auto_refuse['0']['reason_name'];
$options = array(
'refund_type' => 'return',
'refund_content' => $refund_content,
'device' => $device,
'refund_reason' => $refund_reason,
'order_id' => $order_info['order_id'],
'order_info' => $order_info,
'is_cashdesk' => 1,
'refund_way' => 'original'
);
$refundOrderInfo = RC_Api::api('refund', 'refund_apply', $options);
if (is_ecjia_error($refundOrderInfo)) {
return $refundOrderInfo;
}
//收银台收银员退款操作记录
$this->_cashier_record($device, $device_id, $store_id, $staff_id, $refundOrderInfo);
return $refundOrderInfo;
}
/**
* 商家同意退款
*/
private function RefundAgree($refundOrderInfo)
{
//商家同意退款申请
$agree_options = array(
'refund_id' => $refundOrderInfo['refund_id'],
'staff_id' => $_SESSION['staff_id'],
'staff_name'=> $_SESSION['staff_name']
);
$refund_agree = RC_Api::api('refund', 'refund_agree', $agree_options);
if (is_ecjia_error($refund_agree)) {
return $refund_agree;
}
return $refund_agree;
}
/**
* 买家退货给商家
*/
private function RefundReturnWayShop($refundOrderInfo)
{
$returnway_shop_options = array(
'refund_id' => $refundOrderInfo['refund_id'],
);
$refund_returnway_shop = RC_Api::api('refund', 'refund_returnway_shop', $returnway_shop_options);
if (is_ecjia_error($refund_returnway_shop)) {
return $refund_returnway_shop;
}
return $refund_returnway_shop;
}
/**
* 商家确认收货
*/
private function RefundMerchantConfirm($refundOrderInfo)
{
$merchant_confirm_options = array(
'refund_id' => $refundOrderInfo['refund_id'],
'action_note' => __('审核通过', 'payment'),
'store_id' => $_SESSION['store_id'],
'staff_id' => $_SESSION['staff_id'],
'staff_name' => $_SESSION['staff_name'],
'refund_way' => 'original',
);
//商家确认收货
$refund_merchant_confirm = RC_Api::api('refund', 'merchant_confirm', $merchant_confirm_options);
if (is_ecjia_error($refund_merchant_confirm)) {
return $refund_merchant_confirm;
}
return $refund_merchant_confirm;
}
/**
* 退款完成,更新各项数据
*/
private function ProcessRefundUpdateData($refund_result = array())
{
$update_result = array();
if (!empty($refund_result['order_info']) && !empty($refund_result['refund_payrecord_info']) && !empty($refund_result['refund_order_info'])) {
$update_result = Ecjia\App\Refund\HandleRefundedUpdateData::updateRefundedData($refund_result);
}
return $update_result;
}
/**
* 收银台收银员退款操作记录
*/
private function _cashier_record($device, $device_id, $store_id, $staff_id, $refundOrderInfo)
{
$device_type = Ecjia\App\Cashier\CashierDevice::get_device_type($device['code']);
$device_info = RC_DB::table('mobile_device')->where('id', $device_id)->first();
$cashier_record = array(
'store_id' => $store_id,
'staff_id' => $staff_id,
'order_id' => $refundOrderInfo['refund_id'],
'order_sn' => $refundOrderInfo['refund_sn'],
'order_type' => 'refund',
'mobile_device_id' => empty($device_id) ? 0 : $device_id,
'device_sn' => empty($device_info['device_udid']) ? '' : $device_info['device_udid'],
'device_type' => $device_type,
'action' => 'refund', //退款
'create_at' => RC_Time::gmtime(),
);
RC_DB::table('cashier_record')->insert($cashier_record);
return true;
}
}
// end | {
"pile_set_name": "Github"
} |
<?php
/*********************************************************************************
** The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is: vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
*
********************************************************************************/
require('Smarty/libs/Smarty.class.php');
class vtigerCRM_Smarty extends Smarty{
/** Cache the tag cloud display information for re-use */
static $_tagcloud_display_cache = array();
static function lookupTagCloudView($userid) {
if(!isset(self::$_tagcloud_display_cache[$userid])) {
self::$_tagcloud_display_cache[$userid] = getTagCloudView($userid);
}
return self::$_tagcloud_display_cache[$userid];
}
/** END */
/**This function sets the smarty directory path for the member variables
*/
function vtigerCRM_Smarty()
{
global $CALENDAR_DISPLAY, $WORLD_CLOCK_DISPLAY, $CALCULATOR_DISPLAY, $CHAT_DISPLAY, $current_user;
$this->Smarty();
$this->template_dir = 'Smarty/templates';
$this->compile_dir = 'Smarty/templates_c';
$this->config_dir = 'Smarty/configs';
$this->cache_dir = 'Smarty/cache';
//$this->caching = true;
//$this->assign('app_name', 'Login');
$this->assign('CALENDAR_DISPLAY', $CALENDAR_DISPLAY);
$this->assign('WORLD_CLOCK_DISPLAY', $WORLD_CLOCK_DISPLAY);
$this->assign('CALCULATOR_DISPLAY', $CALCULATOR_DISPLAY);
$this->assign('CHAT_DISPLAY', $CHAT_DISPLAY);
$this->assign('CURRENT_USER_ID',$current_user->id);
// Query For TagCloud only when required
if(isset($_REQUEST) && $_REQUEST['action'] == 'DetailView') {
//Added to provide User based Tagcloud
$this->assign('TAG_CLOUD_DISPLAY', self::lookupTagCloudView($current_user->id) );
}
}
}
?>
| {
"pile_set_name": "Github"
} |
/* Stuff to export relevant 'expat' entry points from pyexpat to other
* parser modules, such as cElementTree. */
/* note: you must import expat.h before importing this module! */
#define PyExpat_CAPI_MAGIC "pyexpat.expat_CAPI 1.0"
#define PyExpat_CAPSULE_NAME "pyexpat.expat_CAPI"
struct PyExpat_CAPI
{
char* magic; /* set to PyExpat_CAPI_MAGIC */
int size; /* set to sizeof(struct PyExpat_CAPI) */
int MAJOR_VERSION;
int MINOR_VERSION;
int MICRO_VERSION;
/* pointers to selected expat functions. add new functions at
the end, if needed */
const XML_LChar * (*ErrorString)(enum XML_Error code);
enum XML_Error (*GetErrorCode)(XML_Parser parser);
XML_Size (*GetErrorColumnNumber)(XML_Parser parser);
XML_Size (*GetErrorLineNumber)(XML_Parser parser);
enum XML_Status (*Parse)(
XML_Parser parser, const char *s, int len, int isFinal);
XML_Parser (*ParserCreate_MM)(
const XML_Char *encoding, const XML_Memory_Handling_Suite *memsuite,
const XML_Char *namespaceSeparator);
void (*ParserFree)(XML_Parser parser);
void (*SetCharacterDataHandler)(
XML_Parser parser, XML_CharacterDataHandler handler);
void (*SetCommentHandler)(
XML_Parser parser, XML_CommentHandler handler);
void (*SetDefaultHandlerExpand)(
XML_Parser parser, XML_DefaultHandler handler);
void (*SetElementHandler)(
XML_Parser parser, XML_StartElementHandler start,
XML_EndElementHandler end);
void (*SetNamespaceDeclHandler)(
XML_Parser parser, XML_StartNamespaceDeclHandler start,
XML_EndNamespaceDeclHandler end);
void (*SetProcessingInstructionHandler)(
XML_Parser parser, XML_ProcessingInstructionHandler handler);
void (*SetUnknownEncodingHandler)(
XML_Parser parser, XML_UnknownEncodingHandler handler,
void *encodingHandlerData);
void (*SetUserData)(XML_Parser parser, void *userData);
/* always add new stuff to the end! */
};
| {
"pile_set_name": "Github"
} |
/*
* Machine driver for EVAL-ADAU1x61MINIZ on Analog Devices bfin
* evaluation boards.
*
* Copyright 2011-2014 Analog Devices Inc.
* Author: Lars-Peter Clausen <[email protected]>
*
* Licensed under the GPL-2 or later.
*/
#include <linux/module.h>
#include <linux/device.h>
#include <linux/slab.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/soc.h>
#include <sound/pcm_params.h>
#include "../codecs/adau17x1.h"
static const struct snd_soc_dapm_widget bfin_eval_adau1x61_dapm_widgets[] = {
SND_SOC_DAPM_LINE("In 1", NULL),
SND_SOC_DAPM_LINE("In 2", NULL),
SND_SOC_DAPM_LINE("In 3-4", NULL),
SND_SOC_DAPM_LINE("Diff Out L", NULL),
SND_SOC_DAPM_LINE("Diff Out R", NULL),
SND_SOC_DAPM_LINE("Stereo Out", NULL),
SND_SOC_DAPM_HP("Capless HP Out", NULL),
};
static const struct snd_soc_dapm_route bfin_eval_adau1x61_dapm_routes[] = {
{ "LAUX", NULL, "In 3-4" },
{ "RAUX", NULL, "In 3-4" },
{ "LINP", NULL, "In 1" },
{ "LINN", NULL, "In 1"},
{ "RINP", NULL, "In 2" },
{ "RINN", NULL, "In 2" },
{ "In 1", NULL, "MICBIAS" },
{ "In 2", NULL, "MICBIAS" },
{ "Capless HP Out", NULL, "LHP" },
{ "Capless HP Out", NULL, "RHP" },
{ "Diff Out L", NULL, "LOUT" },
{ "Diff Out R", NULL, "ROUT" },
{ "Stereo Out", NULL, "LOUT" },
{ "Stereo Out", NULL, "ROUT" },
};
static int bfin_eval_adau1x61_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params)
{
struct snd_soc_pcm_runtime *rtd = substream->private_data;
struct snd_soc_dai *codec_dai = rtd->codec_dai;
int pll_rate;
int ret;
switch (params_rate(params)) {
case 48000:
case 8000:
case 12000:
case 16000:
case 24000:
case 32000:
case 96000:
pll_rate = 48000 * 1024;
break;
case 44100:
case 7350:
case 11025:
case 14700:
case 22050:
case 29400:
case 88200:
pll_rate = 44100 * 1024;
break;
default:
return -EINVAL;
}
ret = snd_soc_dai_set_pll(codec_dai, ADAU17X1_PLL,
ADAU17X1_PLL_SRC_MCLK, 12288000, pll_rate);
if (ret)
return ret;
ret = snd_soc_dai_set_sysclk(codec_dai, ADAU17X1_CLK_SRC_PLL, pll_rate,
SND_SOC_CLOCK_IN);
return ret;
}
static const struct snd_soc_ops bfin_eval_adau1x61_ops = {
.hw_params = bfin_eval_adau1x61_hw_params,
};
static struct snd_soc_dai_link bfin_eval_adau1x61_dai = {
.name = "adau1x61",
.stream_name = "adau1x61",
.cpu_dai_name = "bfin-i2s.0",
.codec_dai_name = "adau-hifi",
.platform_name = "bfin-i2s-pcm-audio",
.codec_name = "adau1761.0-0038",
.ops = &bfin_eval_adau1x61_ops,
.dai_fmt = SND_SOC_DAIFMT_I2S | SND_SOC_DAIFMT_NB_NF |
SND_SOC_DAIFMT_CBM_CFM,
};
static struct snd_soc_card bfin_eval_adau1x61 = {
.name = "bfin-eval-adau1x61",
.owner = THIS_MODULE,
.driver_name = "eval-adau1x61",
.dai_link = &bfin_eval_adau1x61_dai,
.num_links = 1,
.dapm_widgets = bfin_eval_adau1x61_dapm_widgets,
.num_dapm_widgets = ARRAY_SIZE(bfin_eval_adau1x61_dapm_widgets),
.dapm_routes = bfin_eval_adau1x61_dapm_routes,
.num_dapm_routes = ARRAY_SIZE(bfin_eval_adau1x61_dapm_routes),
.fully_routed = true,
};
static int bfin_eval_adau1x61_probe(struct platform_device *pdev)
{
bfin_eval_adau1x61.dev = &pdev->dev;
return devm_snd_soc_register_card(&pdev->dev, &bfin_eval_adau1x61);
}
static struct platform_driver bfin_eval_adau1x61_driver = {
.driver = {
.name = "bfin-eval-adau1x61",
.pm = &snd_soc_pm_ops,
},
.probe = bfin_eval_adau1x61_probe,
};
module_platform_driver(bfin_eval_adau1x61_driver);
MODULE_AUTHOR("Lars-Peter Clausen <[email protected]>");
MODULE_DESCRIPTION("ALSA SoC bfin adau1x61 driver");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:bfin-eval-adau1x61");
| {
"pile_set_name": "Github"
} |
"use strict";
module.exports =
function(Promise, INTERNAL, tryConvertToPromise, apiRejection) {
var util = require("./util.js");
var tryCatch = util.tryCatch;
Promise.method = function (fn) {
if (typeof fn !== "function") {
throw new Promise.TypeError("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a");
}
return function () {
var ret = new Promise(INTERNAL);
ret._captureStackTrace();
ret._pushContext();
var value = tryCatch(fn).apply(this, arguments);
ret._popContext();
ret._resolveFromSyncValue(value);
return ret;
};
};
Promise.attempt = Promise["try"] = function (fn, args, ctx) {
if (typeof fn !== "function") {
return apiRejection("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a");
}
var ret = new Promise(INTERNAL);
ret._captureStackTrace();
ret._pushContext();
var value = util.isArray(args)
? tryCatch(fn).apply(ctx, args)
: tryCatch(fn).call(ctx, args);
ret._popContext();
ret._resolveFromSyncValue(value);
return ret;
};
Promise.prototype._resolveFromSyncValue = function (value) {
if (value === util.errorObj) {
this._rejectCallback(value.e, false, true);
} else {
this._resolveCallback(value, true);
}
};
};
| {
"pile_set_name": "Github"
} |
<?php
if (!defined('SYSTEM_ROOT')) { die('Insufficient Permissions'); }
/**
* 环境准备
*/
$today = date("Y-m-d");
$i = array();
$i['plugins']['hook'] = array(); //挂载列表
//注册全局信息变量 $i
$i['db']['host'] = DB_HOST;
$i['db']['user'] = DB_USER;
$i['db']['prefix'] = DB_PREFIX;
$i['db']['passwd'] = DB_PASSWD;
$i['db']['name'] = DB_NAME;
@ini_set('magic_quotes_runtime',0);
if (get_magic_quotes_gpc()) {
function fuck_magic_quotes($value) {
$value = is_array($value) ? array_map('fuck_magic_quotes', $value) : stripslashes($value);
return $value;
}
$_POST = array_map('fuck_magic_quotes', $_POST);
$_GET = array_map('fuck_magic_quotes', $_GET);
$_COOKIE = array_map('fuck_magic_quotes', $_COOKIE);
$_REQUEST = array_map('fuck_magic_quotes', $_REQUEST);
}
//_POST _GET _REQUEST
$i['post'] = $_POST;
$i['get'] = $_GET;
$i['request'] = $_REQUEST;
$ws = $m->query("SELECT * FROM ".DB_PREFIX."options");
while ($wsr = $m->fetch_array($ws)) {
$key = $wsr['name'];
$i['opt'][$key] = $wsr['value'];
}
$rs = $m->query("SELECT * FROM `".DB_NAME."`.`".DB_PREFIX."cron` ORDER BY `orde` ASC");
while ($rsr = $m->fetch_array($rs)) {
$key = $rsr['name'];
$i['cron'][$key] = $rsr;
}
//贴吧分表列表
$i['tabpart'] = $i['table'] = unserialize($i['opt']['fb_tables']);
$i['table'][] = 'tieba'; //贴吧表列表
//当前页面/模式, $i['mode'][0] 一般表示页面
if (!empty($_REQUEST['mod'])) {
$i['mode'] = explode(':', strip_tags($_REQUEST['mod']));
} else {
$i['mode'][0] = 'default';
}
if((empty($i['opt']['core_version']) || SYSTEM_VER != $i['opt']['core_version']) && !defined('SYSTEM_NO_CHECK_VER')) {
if (empty($i['opt']['core_version'])) {
$i['opt']['core_version'] = '3.45';
}
if (file_exists(SYSTEM_ROOT . '/setup/update' . $i['opt']['core_version'] . 'to' . SYSTEM_VER . '.php')) {
$updatefile = '<a href="setup/update' . $i['opt']['core_version'] . 'to' . SYSTEM_VER . '.php">请点击运行: ' . 'update' . $i['opt']['core_version'] . 'to' . SYSTEM_VER . '.php</a>';
msg('严重错误:数据库中的云签到版本与文件版本不符,是否已运行升级脚本?<br/><br/>' . $updatefile);
} else {
$m->query("INSERT INTO `".DB_PREFIX."options` (`name`, `value`) VALUES ('core_version','".SYSTEM_VER."') ON DUPLICATE KEY UPDATE `value` = '".SYSTEM_VER."';");
}
}
if (!defined('SYSTEM_NO_PLUGIN')) {
//所有插件列表
$i['plugins'] = array('all' => array() , 'actived' => array() , 'info' => array());
$plugin_all_query = $m->query("SELECT * FROM `".DB_PREFIX."plugins` ORDER BY `order` ASC");
while ($plugin_all_var = $m->fetch_array($plugin_all_query)) {
$i['plugins']['all'][] = $plugin_all_var['name'];
$i['plugins']['info'][$plugin_all_var['name']] = $plugin_all_var;
$i['plugins']['info'][$plugin_all_var['name']]['options'] = empty($plugin_all_var['options']) ? array() : unserialize($plugin_all_var['options']);
if ($plugin_all_var['status'] == '1') {
$i['plugins']['actived'][] = $plugin_all_var['name'];
}
}
}
//autoload
function class_autoload($c) {
$c = strtolower($c);
if (file_exists(SYSTEM_ROOT . '/lib/class.' . $c . '.php')) {
include SYSTEM_ROOT . '/lib/class.' . $c . '.php';
} else {
throw new Exception('无法加载此类:' . $c , 10001);
}
}
spl_autoload_register('class_autoload');
if (option::get('dev') != 1) {
define('SYSTEM_DEV', false);
} else {
define('SYSTEM_DEV', true);
}
set_exception_handler(array('E','exception'));
set_error_handler(array('E','error')); | {
"pile_set_name": "Github"
} |
V4L2Input="视频捕获设备(V4L2)"
Device="设备"
Input="输入"
VideoFormat="视频格式"
VideoStandard="视频标准"
DVTiming="DV计时"
Resolution="分辨率"
FrameRate="帧率"
LeaveUnchanged="保持不变"
UseBuffering="使用缓冲"
| {
"pile_set_name": "Github"
} |
// SPDX-License-Identifier: GPL-2.0
/*
* Copyright (C) Qu Wenruo 2017. All rights reserved.
*/
/*
* The module is used to catch unexpected/corrupted tree block data.
* Such behavior can be caused either by a fuzzed image or bugs.
*
* The objective is to do leaf/node validation checks when tree block is read
* from disk, and check *every* possible member, so other code won't
* need to checking them again.
*
* Due to the potential and unwanted damage, every checker needs to be
* carefully reviewed otherwise so it does not prevent mount of valid images.
*/
#include "ctree.h"
#include "tree-checker.h"
#include "disk-io.h"
#include "compression.h"
/*
* Error message should follow the following format:
* corrupt <type>: <identifier>, <reason>[, <bad_value>]
*
* @type: leaf or node
* @identifier: the necessary info to locate the leaf/node.
* It's recommened to decode key.objecitd/offset if it's
* meaningful.
* @reason: describe the error
* @bad_value: optional, it's recommened to output bad value and its
* expected value (range).
*
* Since comma is used to separate the components, only space is allowed
* inside each component.
*/
/*
* Append generic "corrupt leaf/node root=%llu block=%llu slot=%d: " to @fmt.
* Allows callers to customize the output.
*/
__printf(4, 5)
__cold
static void generic_err(const struct btrfs_fs_info *fs_info,
const struct extent_buffer *eb, int slot,
const char *fmt, ...)
{
struct va_format vaf;
va_list args;
va_start(args, fmt);
vaf.fmt = fmt;
vaf.va = &args;
btrfs_crit(fs_info,
"corrupt %s: root=%llu block=%llu slot=%d, %pV",
btrfs_header_level(eb) == 0 ? "leaf" : "node",
btrfs_header_owner(eb), btrfs_header_bytenr(eb), slot, &vaf);
va_end(args);
}
/*
* Customized reporter for extent data item, since its key objectid and
* offset has its own meaning.
*/
__printf(4, 5)
__cold
static void file_extent_err(const struct btrfs_fs_info *fs_info,
const struct extent_buffer *eb, int slot,
const char *fmt, ...)
{
struct btrfs_key key;
struct va_format vaf;
va_list args;
btrfs_item_key_to_cpu(eb, &key, slot);
va_start(args, fmt);
vaf.fmt = fmt;
vaf.va = &args;
btrfs_crit(fs_info,
"corrupt %s: root=%llu block=%llu slot=%d ino=%llu file_offset=%llu, %pV",
btrfs_header_level(eb) == 0 ? "leaf" : "node",
btrfs_header_owner(eb), btrfs_header_bytenr(eb), slot,
key.objectid, key.offset, &vaf);
va_end(args);
}
/*
* Return 0 if the btrfs_file_extent_##name is aligned to @alignment
* Else return 1
*/
#define CHECK_FE_ALIGNED(fs_info, leaf, slot, fi, name, alignment) \
({ \
if (!IS_ALIGNED(btrfs_file_extent_##name((leaf), (fi)), (alignment))) \
file_extent_err((fs_info), (leaf), (slot), \
"invalid %s for file extent, have %llu, should be aligned to %u", \
(#name), btrfs_file_extent_##name((leaf), (fi)), \
(alignment)); \
(!IS_ALIGNED(btrfs_file_extent_##name((leaf), (fi)), (alignment))); \
})
static int check_extent_data_item(struct btrfs_fs_info *fs_info,
struct extent_buffer *leaf,
struct btrfs_key *key, int slot)
{
struct btrfs_file_extent_item *fi;
u32 sectorsize = fs_info->sectorsize;
u32 item_size = btrfs_item_size_nr(leaf, slot);
if (!IS_ALIGNED(key->offset, sectorsize)) {
file_extent_err(fs_info, leaf, slot,
"unaligned file_offset for file extent, have %llu should be aligned to %u",
key->offset, sectorsize);
return -EUCLEAN;
}
fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
if (btrfs_file_extent_type(leaf, fi) > BTRFS_FILE_EXTENT_TYPES) {
file_extent_err(fs_info, leaf, slot,
"invalid type for file extent, have %u expect range [0, %u]",
btrfs_file_extent_type(leaf, fi),
BTRFS_FILE_EXTENT_TYPES);
return -EUCLEAN;
}
/*
* Support for new compression/encrption must introduce incompat flag,
* and must be caught in open_ctree().
*/
if (btrfs_file_extent_compression(leaf, fi) > BTRFS_COMPRESS_TYPES) {
file_extent_err(fs_info, leaf, slot,
"invalid compression for file extent, have %u expect range [0, %u]",
btrfs_file_extent_compression(leaf, fi),
BTRFS_COMPRESS_TYPES);
return -EUCLEAN;
}
if (btrfs_file_extent_encryption(leaf, fi)) {
file_extent_err(fs_info, leaf, slot,
"invalid encryption for file extent, have %u expect 0",
btrfs_file_extent_encryption(leaf, fi));
return -EUCLEAN;
}
if (btrfs_file_extent_type(leaf, fi) == BTRFS_FILE_EXTENT_INLINE) {
/* Inline extent must have 0 as key offset */
if (key->offset) {
file_extent_err(fs_info, leaf, slot,
"invalid file_offset for inline file extent, have %llu expect 0",
key->offset);
return -EUCLEAN;
}
/* Compressed inline extent has no on-disk size, skip it */
if (btrfs_file_extent_compression(leaf, fi) !=
BTRFS_COMPRESS_NONE)
return 0;
/* Uncompressed inline extent size must match item size */
if (item_size != BTRFS_FILE_EXTENT_INLINE_DATA_START +
btrfs_file_extent_ram_bytes(leaf, fi)) {
file_extent_err(fs_info, leaf, slot,
"invalid ram_bytes for uncompressed inline extent, have %u expect %llu",
item_size, BTRFS_FILE_EXTENT_INLINE_DATA_START +
btrfs_file_extent_ram_bytes(leaf, fi));
return -EUCLEAN;
}
return 0;
}
/* Regular or preallocated extent has fixed item size */
if (item_size != sizeof(*fi)) {
file_extent_err(fs_info, leaf, slot,
"invalid item size for reg/prealloc file extent, have %u expect %zu",
item_size, sizeof(*fi));
return -EUCLEAN;
}
if (CHECK_FE_ALIGNED(fs_info, leaf, slot, fi, ram_bytes, sectorsize) ||
CHECK_FE_ALIGNED(fs_info, leaf, slot, fi, disk_bytenr, sectorsize) ||
CHECK_FE_ALIGNED(fs_info, leaf, slot, fi, disk_num_bytes, sectorsize) ||
CHECK_FE_ALIGNED(fs_info, leaf, slot, fi, offset, sectorsize) ||
CHECK_FE_ALIGNED(fs_info, leaf, slot, fi, num_bytes, sectorsize))
return -EUCLEAN;
return 0;
}
static int check_csum_item(struct btrfs_fs_info *fs_info,
struct extent_buffer *leaf, struct btrfs_key *key,
int slot)
{
u32 sectorsize = fs_info->sectorsize;
u32 csumsize = btrfs_super_csum_size(fs_info->super_copy);
if (key->objectid != BTRFS_EXTENT_CSUM_OBJECTID) {
generic_err(fs_info, leaf, slot,
"invalid key objectid for csum item, have %llu expect %llu",
key->objectid, BTRFS_EXTENT_CSUM_OBJECTID);
return -EUCLEAN;
}
if (!IS_ALIGNED(key->offset, sectorsize)) {
generic_err(fs_info, leaf, slot,
"unaligned key offset for csum item, have %llu should be aligned to %u",
key->offset, sectorsize);
return -EUCLEAN;
}
if (!IS_ALIGNED(btrfs_item_size_nr(leaf, slot), csumsize)) {
generic_err(fs_info, leaf, slot,
"unaligned item size for csum item, have %u should be aligned to %u",
btrfs_item_size_nr(leaf, slot), csumsize);
return -EUCLEAN;
}
return 0;
}
/*
* Customized reported for dir_item, only important new info is key->objectid,
* which represents inode number
*/
__printf(4, 5)
__cold
static void dir_item_err(const struct btrfs_fs_info *fs_info,
const struct extent_buffer *eb, int slot,
const char *fmt, ...)
{
struct btrfs_key key;
struct va_format vaf;
va_list args;
btrfs_item_key_to_cpu(eb, &key, slot);
va_start(args, fmt);
vaf.fmt = fmt;
vaf.va = &args;
btrfs_crit(fs_info,
"corrupt %s: root=%llu block=%llu slot=%d ino=%llu, %pV",
btrfs_header_level(eb) == 0 ? "leaf" : "node",
btrfs_header_owner(eb), btrfs_header_bytenr(eb), slot,
key.objectid, &vaf);
va_end(args);
}
static int check_dir_item(struct btrfs_fs_info *fs_info,
struct extent_buffer *leaf,
struct btrfs_key *key, int slot)
{
struct btrfs_dir_item *di;
u32 item_size = btrfs_item_size_nr(leaf, slot);
u32 cur = 0;
di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
while (cur < item_size) {
u32 name_len;
u32 data_len;
u32 max_name_len;
u32 total_size;
u32 name_hash;
u8 dir_type;
/* header itself should not cross item boundary */
if (cur + sizeof(*di) > item_size) {
dir_item_err(fs_info, leaf, slot,
"dir item header crosses item boundary, have %zu boundary %u",
cur + sizeof(*di), item_size);
return -EUCLEAN;
}
/* dir type check */
dir_type = btrfs_dir_type(leaf, di);
if (dir_type >= BTRFS_FT_MAX) {
dir_item_err(fs_info, leaf, slot,
"invalid dir item type, have %u expect [0, %u)",
dir_type, BTRFS_FT_MAX);
return -EUCLEAN;
}
if (key->type == BTRFS_XATTR_ITEM_KEY &&
dir_type != BTRFS_FT_XATTR) {
dir_item_err(fs_info, leaf, slot,
"invalid dir item type for XATTR key, have %u expect %u",
dir_type, BTRFS_FT_XATTR);
return -EUCLEAN;
}
if (dir_type == BTRFS_FT_XATTR &&
key->type != BTRFS_XATTR_ITEM_KEY) {
dir_item_err(fs_info, leaf, slot,
"xattr dir type found for non-XATTR key");
return -EUCLEAN;
}
if (dir_type == BTRFS_FT_XATTR)
max_name_len = XATTR_NAME_MAX;
else
max_name_len = BTRFS_NAME_LEN;
/* Name/data length check */
name_len = btrfs_dir_name_len(leaf, di);
data_len = btrfs_dir_data_len(leaf, di);
if (name_len > max_name_len) {
dir_item_err(fs_info, leaf, slot,
"dir item name len too long, have %u max %u",
name_len, max_name_len);
return -EUCLEAN;
}
if (name_len + data_len > BTRFS_MAX_XATTR_SIZE(fs_info)) {
dir_item_err(fs_info, leaf, slot,
"dir item name and data len too long, have %u max %u",
name_len + data_len,
BTRFS_MAX_XATTR_SIZE(fs_info));
return -EUCLEAN;
}
if (data_len && dir_type != BTRFS_FT_XATTR) {
dir_item_err(fs_info, leaf, slot,
"dir item with invalid data len, have %u expect 0",
data_len);
return -EUCLEAN;
}
total_size = sizeof(*di) + name_len + data_len;
/* header and name/data should not cross item boundary */
if (cur + total_size > item_size) {
dir_item_err(fs_info, leaf, slot,
"dir item data crosses item boundary, have %u boundary %u",
cur + total_size, item_size);
return -EUCLEAN;
}
/*
* Special check for XATTR/DIR_ITEM, as key->offset is name
* hash, should match its name
*/
if (key->type == BTRFS_DIR_ITEM_KEY ||
key->type == BTRFS_XATTR_ITEM_KEY) {
char namebuf[max(BTRFS_NAME_LEN, XATTR_NAME_MAX)];
read_extent_buffer(leaf, namebuf,
(unsigned long)(di + 1), name_len);
name_hash = btrfs_name_hash(namebuf, name_len);
if (key->offset != name_hash) {
dir_item_err(fs_info, leaf, slot,
"name hash mismatch with key, have 0x%016x expect 0x%016llx",
name_hash, key->offset);
return -EUCLEAN;
}
}
cur += total_size;
di = (struct btrfs_dir_item *)((void *)di + total_size);
}
return 0;
}
/*
* Common point to switch the item-specific validation.
*/
static int check_leaf_item(struct btrfs_fs_info *fs_info,
struct extent_buffer *leaf,
struct btrfs_key *key, int slot)
{
int ret = 0;
switch (key->type) {
case BTRFS_EXTENT_DATA_KEY:
ret = check_extent_data_item(fs_info, leaf, key, slot);
break;
case BTRFS_EXTENT_CSUM_KEY:
ret = check_csum_item(fs_info, leaf, key, slot);
break;
case BTRFS_DIR_ITEM_KEY:
case BTRFS_DIR_INDEX_KEY:
case BTRFS_XATTR_ITEM_KEY:
ret = check_dir_item(fs_info, leaf, key, slot);
break;
}
return ret;
}
static int check_leaf(struct btrfs_fs_info *fs_info, struct extent_buffer *leaf,
bool check_item_data)
{
/* No valid key type is 0, so all key should be larger than this key */
struct btrfs_key prev_key = {0, 0, 0};
struct btrfs_key key;
u32 nritems = btrfs_header_nritems(leaf);
int slot;
/*
* Extent buffers from a relocation tree have a owner field that
* corresponds to the subvolume tree they are based on. So just from an
* extent buffer alone we can not find out what is the id of the
* corresponding subvolume tree, so we can not figure out if the extent
* buffer corresponds to the root of the relocation tree or not. So
* skip this check for relocation trees.
*/
if (nritems == 0 && !btrfs_header_flag(leaf, BTRFS_HEADER_FLAG_RELOC)) {
struct btrfs_root *check_root;
key.objectid = btrfs_header_owner(leaf);
key.type = BTRFS_ROOT_ITEM_KEY;
key.offset = (u64)-1;
check_root = btrfs_get_fs_root(fs_info, &key, false);
/*
* The only reason we also check NULL here is that during
* open_ctree() some roots has not yet been set up.
*/
if (!IS_ERR_OR_NULL(check_root)) {
struct extent_buffer *eb;
eb = btrfs_root_node(check_root);
/* if leaf is the root, then it's fine */
if (leaf != eb) {
generic_err(fs_info, leaf, 0,
"invalid nritems, have %u should not be 0 for non-root leaf",
nritems);
free_extent_buffer(eb);
return -EUCLEAN;
}
free_extent_buffer(eb);
}
return 0;
}
if (nritems == 0)
return 0;
/*
* Check the following things to make sure this is a good leaf, and
* leaf users won't need to bother with similar sanity checks:
*
* 1) key ordering
* 2) item offset and size
* No overlap, no hole, all inside the leaf.
* 3) item content
* If possible, do comprehensive sanity check.
* NOTE: All checks must only rely on the item data itself.
*/
for (slot = 0; slot < nritems; slot++) {
u32 item_end_expected;
int ret;
btrfs_item_key_to_cpu(leaf, &key, slot);
/* Make sure the keys are in the right order */
if (btrfs_comp_cpu_keys(&prev_key, &key) >= 0) {
generic_err(fs_info, leaf, slot,
"bad key order, prev (%llu %u %llu) current (%llu %u %llu)",
prev_key.objectid, prev_key.type,
prev_key.offset, key.objectid, key.type,
key.offset);
return -EUCLEAN;
}
/*
* Make sure the offset and ends are right, remember that the
* item data starts at the end of the leaf and grows towards the
* front.
*/
if (slot == 0)
item_end_expected = BTRFS_LEAF_DATA_SIZE(fs_info);
else
item_end_expected = btrfs_item_offset_nr(leaf,
slot - 1);
if (btrfs_item_end_nr(leaf, slot) != item_end_expected) {
generic_err(fs_info, leaf, slot,
"unexpected item end, have %u expect %u",
btrfs_item_end_nr(leaf, slot),
item_end_expected);
return -EUCLEAN;
}
/*
* Check to make sure that we don't point outside of the leaf,
* just in case all the items are consistent to each other, but
* all point outside of the leaf.
*/
if (btrfs_item_end_nr(leaf, slot) >
BTRFS_LEAF_DATA_SIZE(fs_info)) {
generic_err(fs_info, leaf, slot,
"slot end outside of leaf, have %u expect range [0, %u]",
btrfs_item_end_nr(leaf, slot),
BTRFS_LEAF_DATA_SIZE(fs_info));
return -EUCLEAN;
}
/* Also check if the item pointer overlaps with btrfs item. */
if (btrfs_item_nr_offset(slot) + sizeof(struct btrfs_item) >
btrfs_item_ptr_offset(leaf, slot)) {
generic_err(fs_info, leaf, slot,
"slot overlaps with its data, item end %lu data start %lu",
btrfs_item_nr_offset(slot) +
sizeof(struct btrfs_item),
btrfs_item_ptr_offset(leaf, slot));
return -EUCLEAN;
}
if (check_item_data) {
/*
* Check if the item size and content meet other
* criteria
*/
ret = check_leaf_item(fs_info, leaf, &key, slot);
if (ret < 0)
return ret;
}
prev_key.objectid = key.objectid;
prev_key.type = key.type;
prev_key.offset = key.offset;
}
return 0;
}
int btrfs_check_leaf_full(struct btrfs_fs_info *fs_info,
struct extent_buffer *leaf)
{
return check_leaf(fs_info, leaf, true);
}
int btrfs_check_leaf_relaxed(struct btrfs_fs_info *fs_info,
struct extent_buffer *leaf)
{
return check_leaf(fs_info, leaf, false);
}
int btrfs_check_node(struct btrfs_fs_info *fs_info, struct extent_buffer *node)
{
unsigned long nr = btrfs_header_nritems(node);
struct btrfs_key key, next_key;
int slot;
u64 bytenr;
int ret = 0;
if (nr == 0 || nr > BTRFS_NODEPTRS_PER_BLOCK(fs_info)) {
btrfs_crit(fs_info,
"corrupt node: root=%llu block=%llu, nritems too %s, have %lu expect range [1,%u]",
btrfs_header_owner(node), node->start,
nr == 0 ? "small" : "large", nr,
BTRFS_NODEPTRS_PER_BLOCK(fs_info));
return -EUCLEAN;
}
for (slot = 0; slot < nr - 1; slot++) {
bytenr = btrfs_node_blockptr(node, slot);
btrfs_node_key_to_cpu(node, &key, slot);
btrfs_node_key_to_cpu(node, &next_key, slot + 1);
if (!bytenr) {
generic_err(fs_info, node, slot,
"invalid NULL node pointer");
ret = -EUCLEAN;
goto out;
}
if (!IS_ALIGNED(bytenr, fs_info->sectorsize)) {
generic_err(fs_info, node, slot,
"unaligned pointer, have %llu should be aligned to %u",
bytenr, fs_info->sectorsize);
ret = -EUCLEAN;
goto out;
}
if (btrfs_comp_cpu_keys(&key, &next_key) >= 0) {
generic_err(fs_info, node, slot,
"bad key order, current (%llu %u %llu) next (%llu %u %llu)",
key.objectid, key.type, key.offset,
next_key.objectid, next_key.type,
next_key.offset);
ret = -EUCLEAN;
goto out;
}
}
out:
return ret;
}
| {
"pile_set_name": "Github"
} |
// Copyright 2001-2019 Crytek GmbH / Crytek Group. All rights reserved.
#pragma once
#include <CrySerialization/Forward.h>
#include <CrySchematyc/FundamentalTypes.h>
#include <CrySchematyc/Reflection/TypeDesc.h>
namespace Schematyc
{
// Forward declare interfaces.
struct IScriptStruct;
// Forward declare classes.
class CAnyValue;
// Forward declare shared pointers.
DECLARE_SHARED_POINTERS(CAnyValue)
// Script structure value.
////////////////////////////////////////////////////////////////////////////////////////////////////
class CScriptStructValue
{
private:
typedef std::map<string, CAnyValuePtr> FieldMap; // #SchematycTODO : Replace map with vector to preserve order!
public:
CScriptStructValue(const IScriptStruct* pStruct);
CScriptStructValue(const CScriptStructValue& rhs);
void Serialize(Serialization::IArchive& archive);
static void ReflectType(CTypeDesc<CScriptStructValue>& desc);
private:
void Refresh();
private:
const IScriptStruct* m_pStruct; // #SchematycTODO : Wouldn't it be safer to reference by GUID?
FieldMap m_fields;
};
} // Schematyc
| {
"pile_set_name": "Github"
} |
import { Lambda, observe } from 'mobx';
import { OpenAPISpec } from '../types';
import { loadAndBundleSpec } from '../utils/loadAndBundleSpec';
import { history } from './HistoryService';
import { MarkerService } from './MarkerService';
import { MenuStore } from './MenuStore';
import { SpecStore } from './models';
import { RedocNormalizedOptions, RedocRawOptions } from './RedocNormalizedOptions';
import { ScrollService } from './ScrollService';
import { SearchStore } from './SearchStore';
import { SchemaDefinition } from '../components/SchemaDefinition/SchemaDefinition';
import { SecurityDefs } from '../components/SecuritySchemes/SecuritySchemes';
import {
SCHEMA_DEFINITION_JSX_NAME,
SECURITY_DEFINITIONS_COMPONENT_NAME,
SECURITY_DEFINITIONS_JSX_NAME,
} from '../utils/openapi';
import { IS_BROWSER } from '../utils';
export interface StoreState {
menu: {
activeItemIdx: number;
};
spec: {
url?: string;
data: any;
};
searchIndex: any;
options: RedocRawOptions;
}
export async function createStore(
spec: object,
specUrl: string | undefined,
options: RedocRawOptions = {},
) {
const resolvedSpec = await loadAndBundleSpec(spec || specUrl);
return new AppStore(resolvedSpec, specUrl, options);
}
export class AppStore {
/**
* deserialize store
* **SUPER HACKY AND NOT OPTIMAL IMPLEMENTATION**
*/
// TODO:
static fromJS(state: StoreState): AppStore {
const inst = new AppStore(state.spec.data, state.spec.url, state.options, false);
inst.menu.activeItemIdx = state.menu.activeItemIdx || 0;
inst.menu.activate(inst.menu.flatItems[inst.menu.activeItemIdx]);
if (!inst.options.disableSearch) {
inst.search!.load(state.searchIndex);
}
return inst;
}
menu: MenuStore;
spec: SpecStore;
rawOptions: RedocRawOptions;
options: RedocNormalizedOptions;
search?: SearchStore<string>;
marker = new MarkerService();
private scroll: ScrollService;
private disposer: Lambda | null = null;
constructor(
spec: OpenAPISpec,
specUrl?: string,
options: RedocRawOptions = {},
createSearchIndex: boolean = true,
) {
this.rawOptions = options;
this.options = new RedocNormalizedOptions(options, DEFAULT_OPTIONS);
this.scroll = new ScrollService(this.options);
// update position statically based on hash (in case of SSR)
MenuStore.updateOnHistory(history.currentId, this.scroll);
this.spec = new SpecStore(spec, specUrl, this.options);
this.menu = new MenuStore(this.spec, this.scroll, history);
if (!this.options.disableSearch) {
this.search = new SearchStore();
if (createSearchIndex) {
this.search.indexItems(this.menu.items);
}
this.disposer = observe(this.menu, 'activeItemIdx', change => {
this.updateMarkOnMenu(change.newValue as number);
});
}
}
onDidMount() {
this.menu.updateOnHistory();
this.updateMarkOnMenu(this.menu.activeItemIdx);
}
dispose() {
this.scroll.dispose();
this.menu.dispose();
if (this.search) {
this.search.dispose();
}
if (this.disposer != null) {
this.disposer();
}
}
/**
* serializes store
* **SUPER HACKY AND NOT OPTIMAL IMPLEMENTATION**
*/
// TODO: improve
async toJS(): Promise<StoreState> {
return {
menu: {
activeItemIdx: this.menu.activeItemIdx,
},
spec: {
url: this.spec.parser.specUrl,
data: this.spec.parser.spec,
},
searchIndex: this.search ? await this.search.toJS() : undefined,
options: this.rawOptions,
};
}
private updateMarkOnMenu(idx: number) {
const start = Math.max(0, idx);
const end = Math.min(this.menu.flatItems.length, start + 5);
const elements: Element[] = [];
for (let i = start; i < end; i++) {
const elem = this.menu.getElementAt(i);
if (!elem) {
continue;
}
elements.push(elem);
}
if (idx === -1 && IS_BROWSER) {
const $description = document.querySelector('[data-role="redoc-description"]');
if ($description) elements.push($description);
}
this.marker.addOnly(elements);
this.marker.mark();
}
}
const DEFAULT_OPTIONS: RedocRawOptions = {
allowedMdComponents: {
[SECURITY_DEFINITIONS_COMPONENT_NAME]: {
component: SecurityDefs,
propsSelector: (store: AppStore) => ({
securitySchemes: store.spec.securitySchemes,
}),
},
[SECURITY_DEFINITIONS_JSX_NAME]: {
component: SecurityDefs,
propsSelector: (store: AppStore) => ({
securitySchemes: store.spec.securitySchemes,
}),
},
[SCHEMA_DEFINITION_JSX_NAME]: {
component: SchemaDefinition,
propsSelector: (store: AppStore) => ({
parser: store.spec.parser,
options: store.options,
}),
},
},
};
| {
"pile_set_name": "Github"
} |
<!--
~ Copyright (c) 2017 VMware, Inc. All Rights Reserved.
~
~ This product is licensed to you under the Apache License, Version 2.0 (the "License").
~ You may not use this product except in compliance with the License.
~
~ This product may include a number of subcomponents with separate copyright notices
~ and license terms. Your use of these subcomponents is subject to the terms and
~ conditions of the subcomponent's license, as noted in the LICENSE file.
-->
<clr-modal [clrModalOpen]="visible" (clrModalOpenChange)="editHostCanceled()">
<h3 class="modal-title">{{ "clusters.resources.editHost.title" | i18n }}</h3>
<div class="modal-body">
<clr-alert *ngIf="alertMessage" [clrAlertType]="alertType" [(clrAlertClosed)]="!alertMessage"
(clrAlertClosedChange)="resetAlert()">
<div class="alert-item"><span class="alert-text">{{ alertMessage }}</span></div>
</clr-alert>
<form class="form" [formGroup]="editHostForm">
<section class="form-block">
<div class="form-group">
<label for="address">{{ "clusters.resources.addHost.address" | i18n }}</label>
<label>{{ host?.address }}</label>
</div>
<div class="form-group">
<label for="name">{{ "clusters.resources.editHost.name" | i18n }}</label>
<input type="text" formControlName="name" size="45">
</div>
<credentials-select [credentials]="credentials" [credentialsLoading]="credentialsLoading"
[selected]="preselectedCredential"
[selectDataName]="'cluster-edit-host-credentials'"
[styleShort]="true"
(onSelect)="onCredentialsSelection($event)"
></credentials-select>
<div class="form-group" *ngIf="showPublicAddressField">
<label for="publicAddress">{{ "clusters.edit.publicAddress" | i18n }}</label>
<input id="publicAddress" type="text"
placeholder="{{ 'clusters.edit.publicAddressPlaceholder' | i18n }}"
formControlName="publicAddress" size="45">
<a aria-haspopup="true" role="tooltip" class="tooltip tooltip-top-left">
<clr-icon shape="info-circle"></clr-icon>
<span class="tooltip-content">{{ "clusters.edit.publicAddressDescription" | i18n }}</span>
</a>
</div>
<div class="form-group" *ngIf="isApplicationEmbedded">
<label for="deploymentPolicy">{{ "clusters.resources.addHost.deploymentPolicy" | i18n }}</label>
<div class="select" data-name="cluster-edit-host-deploymentPolicy">
<select id="deploymentPolicy" formControlName="deploymentPolicy" [(ngModel)]="deploymentPolicySelection">
<option *ngIf="!deploymentPolicies || deploymentPolicies.length === 0">{{"noItems" | i18n}}</option>
<option *ngFor="let deploymentPolicy of deploymentPolicies"
value="{{deploymentPolicy.documentSelfLink}}">{{deploymentPolicy.name}}</option>
</select>
</div>
</div>
</section>
</form>
<!-- Untrusted certificate prompt -->
<verify-certificate [visible]="showCertificateWarning"
[hostAddress]="editHostForm.value.url"
[certificate]="certificate"
(onAccept)="acceptCertificate()"
(onDecline)="cancelEditHost()"></verify-certificate>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-outline"
[disabled]="isSavingHost || isVerifyingHost"
(click)="editHostCanceled()">{{"cancel" | i18n}}</button>
<button [clrLoading]="isSavingHost" type="button" class="btn btn-primary"
[disabled]="isSavingHost || isVerifyingHost || !isHostVerified"
(click)="saveHost()">{{ "update" | i18n }}</button>
<button [clrLoading]="isVerifyingHost" type="button" class="btn btn-outline"
[disabled]="isSavingHost || isVerifyingHost"
(click)="verifyHost()">{{"verify" | i18n}}</button>
</div>
</clr-modal>
| {
"pile_set_name": "Github"
} |
# C++ OpenSource List
- [2018-LCUI #Project#](https://github.com/lc-soft/LCUI): A small C library for building user interfaces with C, XML and CSS.
- [2018-libui #Project#](https://github.com/andlabs/libui): Simple and portable (but not inflexible) GUI library in C that uses the native GUI technologies of each platform it supports.
- [2018-libui-node #Project#](https://github.com/parro-it/libui-node): Node bindings for libui, an awesome native UI library for Unix, OSX and Windows.
# Library
- [Cello #Project#](http://libcello.org/): Cello is a library that brings higher level programming to C. By acting as a modern, powerful runtime system Cello makes many things easy that were previously impractical or awkward in C.
- [gc #Project#](https://github.com/mkirchner/gc): Simple, zero-dependency garbage collection for C.
# Framework
## Concurrent
- [ck #Project#](https://github.com/concurrencykit/ck): Concurrency primitives, safe memory reclamation mechanisms and non-blocking (including lock-free) data structures designed to aid in the research, design and implementation of high performance concurrent systems developed in C99+.
# Dev
- [2018-Google Test #Project#](https://github.com/google/googletest): This repository is a merger of the formerly separate GoogleTest and GoogleMock projects. These were so closely related that it makes sense to maintain and release them together.
| {
"pile_set_name": "Github"
} |
#!/bin/sh
# ----------------------------------------------------------------------------
# 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
#
# https://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.
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Maven Start Up Batch script
#
# Required ENV vars:
# ------------------
# JAVA_HOME - location of a JDK home dir
#
# Optional ENV vars
# -----------------
# M2_HOME - location of maven2's installed home dir
# MAVEN_OPTS - parameters passed to the Java VM when running Maven
# e.g. to debug Maven itself, use
# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
# MAVEN_SKIP_RC - flag to disable loading of mavenrc files
# ----------------------------------------------------------------------------
if [ -z "$MAVEN_SKIP_RC" ]; then
if [ -f /etc/mavenrc ]; then
. /etc/mavenrc
fi
if [ -f "$HOME/.mavenrc" ]; then
. "$HOME/.mavenrc"
fi
fi
# OS specific support. $var _must_ be set to either true or false.
cygwin=false
darwin=false
mingw=false
case "$(uname)" in
CYGWIN*) cygwin=true ;;
MINGW*) mingw=true ;;
Darwin*)
darwin=true
# Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
# See https://developer.apple.com/library/mac/qa/qa1170/_index.html
if [ -z "$JAVA_HOME" ]; then
if [ -x "/usr/libexec/java_home" ]; then
export JAVA_HOME="$(/usr/libexec/java_home)"
else
export JAVA_HOME="/Library/Java/Home"
fi
fi
;;
esac
if [ -z "$JAVA_HOME" ]; then
if [ -r /etc/gentoo-release ]; then
JAVA_HOME=$(java-config --jre-home)
fi
fi
if [ -z "$M2_HOME" ]; then
## resolve links - $0 may be a link to maven's home
PRG="$0"
# need this for relative symlinks
while [ -h "$PRG" ]; do
ls=$(ls -ld "$PRG")
link=$(expr "$ls" : '.*-> \(.*\)$')
if expr "$link" : '/.*' >/dev/null; then
PRG="$link"
else
PRG="$(dirname "$PRG")/$link"
fi
done
saveddir=$(pwd)
M2_HOME=$(dirname "$PRG")/..
# make it fully qualified
M2_HOME=$(cd "$M2_HOME" && pwd)
cd "$saveddir"
# echo Using m2 at $M2_HOME
fi
# For Cygwin, ensure paths are in UNIX format before anything is touched
if $cygwin; then
[ -n "$M2_HOME" ] &&
M2_HOME=$(cygpath --unix "$M2_HOME")
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=$(cygpath --unix "$JAVA_HOME")
[ -n "$CLASSPATH" ] &&
CLASSPATH=$(cygpath --path --unix "$CLASSPATH")
fi
# For Mingw, ensure paths are in UNIX format before anything is touched
if $mingw; then
[ -n "$M2_HOME" ] &&
M2_HOME="$( (
cd "$M2_HOME"
pwd
))"
[ -n "$JAVA_HOME" ] &&
JAVA_HOME="$( (
cd "$JAVA_HOME"
pwd
))"
fi
if [ -z "$JAVA_HOME" ]; then
javaExecutable="$(which javac)"
if [ -n "$javaExecutable" ] && ! [ "$(expr \"$javaExecutable\" : '\([^ ]*\)')" = "no" ]; then
# readlink(1) is not available as standard on Solaris 10.
readLink=$(which readlink)
if [ ! $(expr "$readLink" : '\([^ ]*\)') = "no" ]; then
if $darwin; then
javaHome="$(dirname \"$javaExecutable\")"
javaExecutable="$(cd \"$javaHome\" && pwd -P)/javac"
else
javaExecutable="$(readlink -f \"$javaExecutable\")"
fi
javaHome="$(dirname \"$javaExecutable\")"
javaHome=$(expr "$javaHome" : '\(.*\)/bin')
JAVA_HOME="$javaHome"
export JAVA_HOME
fi
fi
fi
if [ -z "$JAVACMD" ]; then
if [ -n "$JAVA_HOME" ]; then
if [ -x "$JAVA_HOME/jre/sh/java" ]; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
else
JAVACMD="$(which java)"
fi
fi
if [ ! -x "$JAVACMD" ]; then
echo "Error: JAVA_HOME is not defined correctly." >&2
echo " We cannot execute $JAVACMD" >&2
exit 1
fi
if [ -z "$JAVA_HOME" ]; then
echo "Warning: JAVA_HOME environment variable is not set."
fi
CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
# traverses directory structure from process work directory to filesystem root
# first directory with .mvn subdirectory is considered project base directory
find_maven_basedir() {
if [ -z "$1" ]; then
echo "Path not specified to find_maven_basedir"
return 1
fi
basedir="$1"
wdir="$1"
while [ "$wdir" != '/' ]; do
if [ -d "$wdir"/.mvn ]; then
basedir=$wdir
break
fi
# workaround for JBEAP-8937 (on Solaris 10/Sparc)
if [ -d "${wdir}" ]; then
wdir=$(
cd "$wdir/.."
pwd
)
fi
# end of workaround
done
echo "${basedir}"
}
# concatenates all lines of a file
concat_lines() {
if [ -f "$1" ]; then
echo "$(tr -s '\n' ' ' <"$1")"
fi
}
BASE_DIR=$(find_maven_basedir "$(pwd)")
if [ -z "$BASE_DIR" ]; then
exit 1
fi
##########################################################################################
# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
# This allows using the maven wrapper in projects that prohibit checking in binary data.
##########################################################################################
if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found .mvn/wrapper/maven-wrapper.jar"
fi
else
if [ "$MVNW_VERBOSE" = true ]; then
echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..."
fi
if [ -n "$MVNW_REPOURL" ]; then
jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
else
jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
fi
while IFS="=" read key value; do
case "$key" in wrapperUrl)
jarUrl="$value"
break
;;
esac
done <"$BASE_DIR/.mvn/wrapper/maven-wrapper.properties"
if [ "$MVNW_VERBOSE" = true ]; then
echo "Downloading from: $jarUrl"
fi
wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar"
if $cygwin; then
wrapperJarPath=$(cygpath --path --windows "$wrapperJarPath")
fi
if command -v wget >/dev/null; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found wget ... using wget"
fi
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
wget "$jarUrl" -O "$wrapperJarPath"
else
wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath"
fi
elif command -v curl >/dev/null; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found curl ... using curl"
fi
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
curl -o "$wrapperJarPath" "$jarUrl" -f
else
curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f
fi
else
if [ "$MVNW_VERBOSE" = true ]; then
echo "Falling back to using Java to download"
fi
javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java"
# For Cygwin, switch paths to Windows format before running javac
if $cygwin; then
javaClass=$(cygpath --path --windows "$javaClass")
fi
if [ -e "$javaClass" ]; then
if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
if [ "$MVNW_VERBOSE" = true ]; then
echo " - Compiling MavenWrapperDownloader.java ..."
fi
# Compiling the Java class
("$JAVA_HOME/bin/javac" "$javaClass")
fi
if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
# Running the downloader
if [ "$MVNW_VERBOSE" = true ]; then
echo " - Running MavenWrapperDownloader.java ..."
fi
("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR")
fi
fi
fi
fi
##########################################################################################
# End of extension
##########################################################################################
export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}
if [ "$MVNW_VERBOSE" = true ]; then
echo $MAVEN_PROJECTBASEDIR
fi
MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
# For Cygwin, switch paths to Windows format before running java
if $cygwin; then
[ -n "$M2_HOME" ] &&
M2_HOME=$(cygpath --path --windows "$M2_HOME")
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=$(cygpath --path --windows "$JAVA_HOME")
[ -n "$CLASSPATH" ] &&
CLASSPATH=$(cygpath --path --windows "$CLASSPATH")
[ -n "$MAVEN_PROJECTBASEDIR" ] &&
MAVEN_PROJECTBASEDIR=$(cygpath --path --windows "$MAVEN_PROJECTBASEDIR")
fi
# Provide a "standardized" way to retrieve the CLI args that will
# work with both Windows and non-Windows executions.
MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@"
export MAVEN_CMD_LINE_ARGS
WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
exec "$JAVACMD" \
$MAVEN_OPTS \
-classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
"-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"
| {
"pile_set_name": "Github"
} |
*> \brief \b DORML2 multiplies a general matrix by the orthogonal matrix from a LQ factorization determined by sgelqf (unblocked algorithm).
*
* =========== DOCUMENTATION ===========
*
* Online html documentation available at
* http://www.netlib.org/lapack/explore-html/
*
*> \htmlonly
*> Download DORML2 + dependencies
*> <a href="http://www.netlib.org/cgi-bin/netlibfiles.tgz?format=tgz&filename=/lapack/lapack_routine/dorml2.f">
*> [TGZ]</a>
*> <a href="http://www.netlib.org/cgi-bin/netlibfiles.zip?format=zip&filename=/lapack/lapack_routine/dorml2.f">
*> [ZIP]</a>
*> <a href="http://www.netlib.org/cgi-bin/netlibfiles.txt?format=txt&filename=/lapack/lapack_routine/dorml2.f">
*> [TXT]</a>
*> \endhtmlonly
*
* Definition:
* ===========
*
* SUBROUTINE DORML2( SIDE, TRANS, M, N, K, A, LDA, TAU, C, LDC,
* WORK, INFO )
*
* .. Scalar Arguments ..
* CHARACTER SIDE, TRANS
* INTEGER INFO, K, LDA, LDC, M, N
* ..
* .. Array Arguments ..
* DOUBLE PRECISION A( LDA, * ), C( LDC, * ), TAU( * ), WORK( * )
* ..
*
*
*> \par Purpose:
* =============
*>
*> \verbatim
*>
*> DORML2 overwrites the general real m by n matrix C with
*>
*> Q * C if SIDE = 'L' and TRANS = 'N', or
*>
*> Q**T* C if SIDE = 'L' and TRANS = 'T', or
*>
*> C * Q if SIDE = 'R' and TRANS = 'N', or
*>
*> C * Q**T if SIDE = 'R' and TRANS = 'T',
*>
*> where Q is a real orthogonal matrix defined as the product of k
*> elementary reflectors
*>
*> Q = H(k) . . . H(2) H(1)
*>
*> as returned by DGELQF. Q is of order m if SIDE = 'L' and of order n
*> if SIDE = 'R'.
*> \endverbatim
*
* Arguments:
* ==========
*
*> \param[in] SIDE
*> \verbatim
*> SIDE is CHARACTER*1
*> = 'L': apply Q or Q**T from the Left
*> = 'R': apply Q or Q**T from the Right
*> \endverbatim
*>
*> \param[in] TRANS
*> \verbatim
*> TRANS is CHARACTER*1
*> = 'N': apply Q (No transpose)
*> = 'T': apply Q**T (Transpose)
*> \endverbatim
*>
*> \param[in] M
*> \verbatim
*> M is INTEGER
*> The number of rows of the matrix C. M >= 0.
*> \endverbatim
*>
*> \param[in] N
*> \verbatim
*> N is INTEGER
*> The number of columns of the matrix C. N >= 0.
*> \endverbatim
*>
*> \param[in] K
*> \verbatim
*> K is INTEGER
*> The number of elementary reflectors whose product defines
*> the matrix Q.
*> If SIDE = 'L', M >= K >= 0;
*> if SIDE = 'R', N >= K >= 0.
*> \endverbatim
*>
*> \param[in] A
*> \verbatim
*> A is DOUBLE PRECISION array, dimension
*> (LDA,M) if SIDE = 'L',
*> (LDA,N) if SIDE = 'R'
*> The i-th row must contain the vector which defines the
*> elementary reflector H(i), for i = 1,2,...,k, as returned by
*> DGELQF in the first k rows of its array argument A.
*> A is modified by the routine but restored on exit.
*> \endverbatim
*>
*> \param[in] LDA
*> \verbatim
*> LDA is INTEGER
*> The leading dimension of the array A. LDA >= max(1,K).
*> \endverbatim
*>
*> \param[in] TAU
*> \verbatim
*> TAU is DOUBLE PRECISION array, dimension (K)
*> TAU(i) must contain the scalar factor of the elementary
*> reflector H(i), as returned by DGELQF.
*> \endverbatim
*>
*> \param[in,out] C
*> \verbatim
*> C is DOUBLE PRECISION array, dimension (LDC,N)
*> On entry, the m by n matrix C.
*> On exit, C is overwritten by Q*C or Q**T*C or C*Q**T or C*Q.
*> \endverbatim
*>
*> \param[in] LDC
*> \verbatim
*> LDC is INTEGER
*> The leading dimension of the array C. LDC >= max(1,M).
*> \endverbatim
*>
*> \param[out] WORK
*> \verbatim
*> WORK is DOUBLE PRECISION array, dimension
*> (N) if SIDE = 'L',
*> (M) if SIDE = 'R'
*> \endverbatim
*>
*> \param[out] INFO
*> \verbatim
*> INFO is INTEGER
*> = 0: successful exit
*> < 0: if INFO = -i, the i-th argument had an illegal value
*> \endverbatim
*
* Authors:
* ========
*
*> \author Univ. of Tennessee
*> \author Univ. of California Berkeley
*> \author Univ. of Colorado Denver
*> \author NAG Ltd.
*
*> \date December 2016
*
*> \ingroup doubleOTHERcomputational
*
* =====================================================================
SUBROUTINE DORML2( SIDE, TRANS, M, N, K, A, LDA, TAU, C, LDC,
$ WORK, INFO )
*
* -- LAPACK computational routine (version 3.7.0) --
* -- LAPACK is a software package provided by Univ. of Tennessee, --
* -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..--
* December 2016
*
* .. Scalar Arguments ..
CHARACTER SIDE, TRANS
INTEGER INFO, K, LDA, LDC, M, N
* ..
* .. Array Arguments ..
DOUBLE PRECISION A( LDA, * ), C( LDC, * ), TAU( * ), WORK( * )
* ..
*
* =====================================================================
*
* .. Parameters ..
DOUBLE PRECISION ONE
PARAMETER ( ONE = 1.0D+0 )
* ..
* .. Local Scalars ..
LOGICAL LEFT, NOTRAN
INTEGER I, I1, I2, I3, IC, JC, MI, NI, NQ
DOUBLE PRECISION AII
* ..
* .. External Functions ..
LOGICAL LSAME
EXTERNAL LSAME
* ..
* .. External Subroutines ..
EXTERNAL DLARF, XERBLA
* ..
* .. Intrinsic Functions ..
INTRINSIC MAX
* ..
* .. Executable Statements ..
*
* Test the input arguments
*
INFO = 0
LEFT = LSAME( SIDE, 'L' )
NOTRAN = LSAME( TRANS, 'N' )
*
* NQ is the order of Q
*
IF( LEFT ) THEN
NQ = M
ELSE
NQ = N
END IF
IF( .NOT.LEFT .AND. .NOT.LSAME( SIDE, 'R' ) ) THEN
INFO = -1
ELSE IF( .NOT.NOTRAN .AND. .NOT.LSAME( TRANS, 'T' ) ) THEN
INFO = -2
ELSE IF( M.LT.0 ) THEN
INFO = -3
ELSE IF( N.LT.0 ) THEN
INFO = -4
ELSE IF( K.LT.0 .OR. K.GT.NQ ) THEN
INFO = -5
ELSE IF( LDA.LT.MAX( 1, K ) ) THEN
INFO = -7
ELSE IF( LDC.LT.MAX( 1, M ) ) THEN
INFO = -10
END IF
IF( INFO.NE.0 ) THEN
CALL XERBLA( 'DORML2', -INFO )
RETURN
END IF
*
* Quick return if possible
*
IF( M.EQ.0 .OR. N.EQ.0 .OR. K.EQ.0 )
$ RETURN
*
IF( ( LEFT .AND. NOTRAN ) .OR. ( .NOT.LEFT .AND. .NOT.NOTRAN ) )
$ THEN
I1 = 1
I2 = K
I3 = 1
ELSE
I1 = K
I2 = 1
I3 = -1
END IF
*
IF( LEFT ) THEN
NI = N
JC = 1
ELSE
MI = M
IC = 1
END IF
*
DO 10 I = I1, I2, I3
IF( LEFT ) THEN
*
* H(i) is applied to C(i:m,1:n)
*
MI = M - I + 1
IC = I
ELSE
*
* H(i) is applied to C(1:m,i:n)
*
NI = N - I + 1
JC = I
END IF
*
* Apply H(i)
*
AII = A( I, I )
A( I, I ) = ONE
CALL DLARF( SIDE, MI, NI, A( I, I ), LDA, TAU( I ),
$ C( IC, JC ), LDC, WORK )
A( I, I ) = AII
10 CONTINUE
RETURN
*
* End of DORML2
*
END
| {
"pile_set_name": "Github"
} |
# assert-plus Changelog
## 1.0.0
- *BREAKING* assert.number (and derivatives) now accept Infinity as valid input
- Add assert.finite check. Previous assert.number callers should use this if
they expect Infinity inputs to throw.
## 0.2.0
- Fix `assert.object(null)` so it throws
- Fix optional/arrayOf exports for non-type-of asserts
- Add optiona/arrayOf exports for Stream/Date/Regex/uuid
- Add basic unit test coverage
| {
"pile_set_name": "Github"
} |
#########################################################################
# OpenKore - Packet sending
# This module contains functions for sending packets to the server.
#
# This software is open source, licensed under the GNU General Public
# License, version 2.
# Basically, this means that you're allowed to modify and distribute
# this software. However, if you distribute modified versions, you MUST
# also distribute the source code.
# See http://www.gnu.org/licenses/gpl.html for the full license.
#
# $Revision: 6687 $
# $Id: kRO.pm 6687 2009-04-19 19:04:25Z technologyguild $
########################################################################
# Korea (kRO)
# The majority of private servers use eAthena, this is a clone of kRO
package Network::Send::kRO::Sakexe_2005_10_10a;
use strict;
use base qw(Network::Send::kRO::Sakexe_2005_09_12b);
sub new {
my ($class) = @_;
return $class->SUPER::new(@_);
}
=pod
//2005-10-10aSakexe
0x020e,32
0x025a,-1
0x025b,6,cooking,0
=cut
1; | {
"pile_set_name": "Github"
} |
class Group extends OutlinerElement {
constructor(data, uuid) {
super(uuid)
for (var key in Group.properties) {
Group.properties[key].reset(this);
}
this.name = Format.bone_rig ? 'bone' : 'group'
this.children = []
this.reset = false;
this.shade = true;
this.selected = false;
this.locked = false;
this.visibility = true;
this.export = true;
this.autouv = 0;
this.parent = 'root';
this.isOpen = false;
this.ik_enabled = false;
this.ik_chain_length = 0;
if (typeof data === 'object') {
this.extend(data)
} else if (typeof data === 'string') {
this.name = data
}
}
extend(object) {
for (var key in Group.properties) {
Group.properties[key].merge(this, object)
}
Merge.string(this, object, 'name')
this.sanitizeName();
Merge.boolean(this, object, 'shade')
Merge.boolean(this, object, 'mirror_uv')
Merge.boolean(this, object, 'reset')
/*
if (object.origin) {
Merge.number(this.origin, object.origin, 0)
Merge.number(this.origin, object.origin, 1)
Merge.number(this.origin, object.origin, 2)
}
if (object.rotation) {
Merge.number(this.rotation, object.rotation, 0)
Merge.number(this.rotation, object.rotation, 1)
Merge.number(this.rotation, object.rotation, 2)
}*/
Merge.number(this, object, 'autouv')
Merge.boolean(this, object, 'export')
Merge.boolean(this, object, 'locked')
Merge.boolean(this, object, 'visibility')
return this;
}
getMesh() {
return this.mesh;
}
get mesh() {
var bone = Canvas.bones[this.uuid]
if (!bone) {
bone = new THREE.Object3D()
bone.name = this.name
bone.isGroup = true
Canvas.bones[this.uuid] = bone
}
return bone;
}
init() {
super.init();
if (typeof this.parent !== 'object') {
this.addTo();
}
return this;
}
select(event) {
var scope = this;
if (Blockbench.hasFlag('renaming') || this.locked) return this;
if (!event) event = true
var allSelected = Group.selected === this && selected.length && this.matchesSelection()
//Clear Old Group
if (Group.selected) Group.selected.unselect()
if (event.shiftKey !== true && event.ctrlOrCmd !== true) {
selected.length = 0
}
//Select This Group
Group.all.forEach(function(s) {
s.selected = false
})
this.selected = true
Group.selected = this;
//Select / Unselect Children
if (allSelected && event.which === 1) {
//Select Only Group, unselect Children
selected.length = 0
} else {
scope.children.forEach(function(s) {
s.selectLow()
})
}
if (Animator.open) {
if (Animator.selected) {
Animator.selected.getBoneAnimator().select(true)
}
}
updateSelection()
return this;
}
selectChildren(event) {
var scope = this;
if (Blockbench.hasFlag('renaming')) return;
if (!event) event = {shiftKey: false}
var firstChildSelected = false
//Clear Old Group
if (Group.selected) Group.selected.unselect()
selected.length = 0
//Select This Group
Group.all.forEach(function(s) {
s.selected = false
})
this.selected = true
Group.selected = this
scope.children.forEach(function(s) {
s.selectLow()
})
updateSelection()
return this;
}
selectLow(highlight) {
//Group.selected = this;
//Only Select
if (highlight !== false) {
this.selected = true
}
this.children.forEach(function(s) {
s.selectLow(highlight)
})
TickUpdates.selection = true;
return this;
}
unselect() {
if (this.selected === false) return;
if (Animator.open && Animator.selected) {
var ba = Animator.selected.animators[this.uuid];
if (ba) {
ba.selected = false
}
}
Group.selected = undefined;
this.selected = false
TickUpdates.selection = true;
return this;
}
matchesSelection() {
var scope = this;
var match = true;
for (var i = 0; i < selected.length; i++) {
if (!selected[i].isChildOf(scope, 20)) {
return false
}
}
this.forEachChild(obj => {
if (!obj.selected) {
match = false
}
})
return match;
}
openUp() {
this.isOpen = true
this.updateElement()
if (this.parent && this.parent !== 'root') {
this.parent.openUp()
}
return this;
}
remove(undo) {
var scope = this;
if (undo) {
var cubes = []
this.forEachChild(function(element) {
if (element.type !== 'group') {
cubes.push(element)
}
})
Undo.initEdit({elements: cubes, outliner: true, selection: true})
}
this.unselect()
var i = this.children.length-1
while (i >= 0) {
this.children[i].remove(false)
i--;
}
if (typeof this.parent === 'object') {
this.parent.children.remove(this)
} else {
Outliner.root.remove(this)
}
Animator.animations.forEach(animation => {
if (animation.animators && animation.animators[scope.uuid]) {
delete animation.animators[scope.uuid];
}
if (animation.selected && Animator.open) {
updateKeyframeSelection();
}
})
TickUpdates.selection = true
this.constructor.all.remove(this);
if (undo) {
cubes.length = 0
Undo.finishEdit('removed_group')
}
}
resolve() {
var array = this.children.slice();
var index = this.getParentArray().indexOf(this)
array.forEach((s, i) => {
s.addTo(this.parent, index)
})
TickUpdates.outliner = true;
this.remove(false);
return array;
}
showContextMenu(event) {
Prop.active_panel = 'outliner'
if (this.locked) return this;
this.select(event)
this.menu.open(event, this)
return this;
}
transferOrigin(origin) {
if (!this.mesh) return;
var q = new THREE.Quaternion().copy(this.mesh.quaternion)
var shift = new THREE.Vector3(
this.origin[0] - origin[0],
this.origin[1] - origin[1],
this.origin[2] - origin[2],
)
var dq = new THREE.Vector3().copy(shift)
dq.applyQuaternion(q)
shift.sub(dq)
shift.applyQuaternion(q.inverse())
this.origin.V3_set(origin);
function iterateChild(obj) {
if (obj instanceof Group) {
obj.origin.V3_add(shift);
obj.children.forEach(child => iterateChild(child));
} else {
if (obj.movable) {
obj.from.V3_add(shift);
}
if (obj.resizable) {
obj.to.V3_add(shift);
}
if (obj.rotatable) {
obj.origin.V3_add(shift);
}
}
}
this.children.forEach(child => iterateChild(child));
Canvas.updatePositions()
return this;
}
sortContent() {
Undo.initEdit({outliner: true})
if (this.children.length < 1) return;
this.children.sort(function(a,b) {
return sort_collator.compare(a.name, b.name)
});
Undo.finishEdit('sort')
return this;
}
duplicate() {
var copied_groups = [];
var copy = this.getChildlessCopy(false)
delete copy.parent;
copied_groups.push(copy)
copy.sortInBefore(this, 1).init()
if (Format.bone_rig) {
copy.createUniqueName()
}
for (var child of this.children) {
child.duplicate().addTo(copy)
}
copy.isOpen = true;
Canvas.updatePositions()
TickUpdates.outliner = true;
return copy;
}
getSaveCopy() {
var base_group = this.getChildlessCopy(true);
for (var child of this.children) {
base_group.children.push(child.getSaveCopy());
}
delete base_group.parent;
return base_group;
}
getChildlessCopy(keep_uuid) {
var base_group = new Group({name: this.name}, keep_uuid ? this.uuid : null);
for (var key in Group.properties) {
Group.properties[key].copy(this, base_group)
}
base_group.name = this.name;
base_group.origin.V3_set(this.origin);
base_group.rotation.V3_set(this.rotation);
base_group.shade = this.shade;
base_group.reset = this.reset;
base_group.locked = this.locked;
base_group.visibility = this.visibility;
base_group.export = this.export;
base_group.autouv = this.autouv;
return base_group;
}
compile(undo) {
var obj = {
name: this.name
}
for (var key in Group.properties) {
Group.properties[key].copy(this, obj)
}
if (this.shade == false) {
obj.shade = false
}
if (undo) {
obj.uuid = this.uuid;
obj.export = this.export;
obj.isOpen = this.isOpen === true;
obj.locked = this.locked;
obj.visibility = this.visibility;
obj.autouv = this.autouv;
}
if (this.rotation.allEqual(0)) {
delete obj.rotation;
}
if (this.reset) {
obj.reset = true
}
obj.children = []
return obj;
}
forEachChild(cb, type, forSelf) {
var i = 0
if (forSelf) {
cb(this)
}
while (i < this.children.length) {
if (!type || this.children[i] instanceof type) {
cb(this.children[i])
}
if (this.children[i].type === 'group') {
this.children[i].forEachChild(cb, type)
}
i++;
}
}
toggle(key, val) {
if (val === undefined) {
var val = !this[key]
}
var cubes = []
this.forEachChild(obj => {
cubes.push(obj)
}, NonGroup)
Undo.initEdit({outliner: true, elements: cubes})
this.forEachChild(function(s) {
s[key] = val
s.updateElement()
})
this[key] = val;
this.updateElement()
if (key === 'visibility') {
Canvas.updateVisibility()
}
Undo.finishEdit('toggle')
}
setAutoUV(val) {
this.forEachChild(function(s) {
s.autouv = val;
s.updateElement()
})
this.autouv = val;
this.updateElement()
}
}
Group.prototype.title = tl('data.group');
Group.prototype.type = 'group';
Group.prototype.icon = 'fa fa-folder';
Group.prototype.isParent = true;
Group.prototype.name_regex = () => Format.bone_rig ? 'a-zA-Z0-9_' : false;
Group.prototype.buttons = [
Outliner.buttons.visibility,
Outliner.buttons.locked,
Outliner.buttons.export,
Outliner.buttons.shading,
Outliner.buttons.autouv
];
Group.prototype.needsUniqueName = () => Format.bone_rig;
Group.prototype.menu = new Menu([
'copy',
'paste',
'duplicate',
'_',
'add_locator',
'rename',
{icon: 'sort_by_alpha', name: 'menu.group.sort', condition: {modes: ['edit']}, click: function(group) {group.sortContent()}},
{icon: 'fa-leaf', name: 'menu.group.resolve', condition: {modes: ['edit']}, click: function(group) {
Undo.initEdit({outliner: true})
group.resolve()
Undo.finishEdit('group resolve')
}},
'delete'
]);
Group.selected;
Group.all = [];
new Property(Group, 'vector', 'origin', {default() {
return Format.centered_grid ? [0, 0, 0] : [8, 8, 8]
}});
new Property(Group, 'vector', 'rotation');
new Property(Group, 'array', 'cem_animations', {condition: () => Format.id == 'optifine_entity'});
function getCurrentGroup() {
if (Group.selected) {
return Group.selected
} else if (selected.length) {
var g1 = selected[0].parent;
if (g1 instanceof Group) {
for (var obj of selected) {
if (obj.parent !== g1) {
return;
}
}
return g1;
}
}
}
function getAllGroups() {
var ta = []
function iterate(array) {
for (var obj of array) {
if (obj instanceof Group) {
ta.push(obj)
iterate(obj.children)
}
}
}
iterate(Outliner.root)
return ta;
}
function addGroup() {
Undo.initEdit({outliner: true});
var add_group = Group.selected
if (!add_group && selected.length) {
add_group = Cube.selected.last()
}
var base_group = new Group({
origin: add_group ? add_group.origin : undefined
})
base_group.addTo(add_group)
base_group.isOpen = true
if (Format.bone_rig) {
base_group.createUniqueName()
}
if (add_group instanceof NonGroup && selected.length > 1) {
selected.forEach(function(s, i) {
s.addTo(base_group)
})
}
base_group.init().select()
Undo.finishEdit('add_group');
loadOutlinerDraggable()
Vue.nextTick(function() {
updateSelection()
if (settings.create_rename.value) {
base_group.rename()
}
base_group.showInOutliner()
Blockbench.dispatchEvent( 'add_group', {object: base_group} )
})
}
window.__defineGetter__('selected_group', () => {
console.warn('selected_group is deprecated. Please use Group.selected instead.')
return Group.selected
})
BARS.defineActions(function() {
new Action({
id: 'add_group',
icon: 'create_new_folder',
category: 'edit',
condition: () => Modes.edit,
keybind: new Keybind({key: 71, ctrl: true}),
click: function () {
addGroup();
}
})
new Action({
id: 'collapse_groups',
icon: 'format_indent_decrease',
category: 'edit',
condition: () => Outliner.root.length > 0,
click: function () {
Group.all.forEach(function(g) {
g.isOpen = false
var name = g.name
g.name = '_$X0v_'
g.name = name
})
}
})
})
| {
"pile_set_name": "Github"
} |
config BR2_PACKAGE_JEMALLOC_ARCH_SUPPORTS
bool
default y if BR2_arm || BR2_armeb
default y if BR2_aarch64 || BR2_aarch64_be
default y if BR2_i386 || BR2_x86_64
default y if BR2_mips || BR2_mipsel || BR2_mips64 || BR2_mips64el
default y if BR2_sparc64
default y if BR2_powerpc
default y if BR2_sh4 || BR2sh4eb || BR2_sh4a || BR2_sh4aeb
config BR2_PACKAGE_JEMALLOC
bool "jemalloc"
depends on BR2_PACKAGE_JEMALLOC_ARCH_SUPPORTS
depends on !BR2_STATIC_LIBS
depends on BR2_TOOLCHAIN_HAS_THREADS
help
This library providing a malloc(3) implementation that
emphasizes fragmentation avoidance and scalable concurrency
support.
http://jemalloc.net/
comment "jemalloc needs a toolchain w/ dynamic library, threads"
depends on BR2_PACKAGE_JEMALLOC_ARCH_SUPPORTS
depends on BR2_STATIC_LIBS || !BR2_TOOLCHAIN_HAS_THREADS
| {
"pile_set_name": "Github"
} |
//
// MediumMenuItem.swift
// MediumMenu-Sample
//
// Created by pixyzehn on 3/16/15.
// Copyright (c) 2015 pixyzehn. All rights reserved.
//
import UIKit
open class MediumMenuItem {
open var title: String?
open var image: UIImage?
open var completion: (() -> Void)?
init() {}
public convenience init(title: String, image:UIImage? = nil, completion: (() -> Void)? = nil) {
self.init()
self.title = title
self.image = image
self.completion = completion
}
}
| {
"pile_set_name": "Github"
} |
using System.Runtime.CompilerServices;
using System.Diagnostics.CodeAnalysis;
using Mono.Linker.Tests.Cases.Expectations.Assertions;
using Mono.Linker.Tests.Cases.Expectations.Metadata;
namespace Mono.Linker.Tests.Cases.DynamicDependencies
{
[SetupLinkerArgument ("--keep-dep-attributes", "true")]
class DynamicDependencyKeptOption
{
public static void Main ()
{
B.Test ();
}
class B
{
[Kept]
int field;
[Kept]
[KeptAttributeAttribute (typeof (DynamicDependencyAttribute))]
[DynamicDependency ("field")]
public static void Test ()
{
}
}
}
} | {
"pile_set_name": "Github"
} |
//===- ConsG.cpp -- Constraint graph representation-----------------------------//
//
// SVF: Static Value-Flow Analysis
//
// Copyright (C) <2013-2017> <Yulei Sui>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
//===----------------------------------------------------------------------===//
/*
* ConstraintGraph.cpp
*
* Created on: Oct 14, 2013
* Author: Yulei Sui
*/
#include "Graphs/ConsG.h"
using namespace SVF;
using namespace SVFUtil;
static llvm::cl::opt<bool> ConsCGDotGraph("dump-consG", llvm::cl::init(false),
llvm::cl::desc("Dump dot graph of Constraint Graph"));
static llvm::cl::opt<bool> PrintCGGraph("print-consG", llvm::cl::init(false),
llvm::cl::desc("Print Constraint Graph to Terminal"));
ConstraintNode::SCCEdgeFlag ConstraintNode::sccEdgeFlag = ConstraintNode::Direct;
/*!
* Start building constraint graph
*/
void ConstraintGraph::buildCG()
{
// initialize nodes
for(PAG::iterator it = pag->begin(), eit = pag->end(); it!=eit; ++it)
{
addConstraintNode(new ConstraintNode(it->first),it->first);
}
// initialize edges
PAGEdge::PAGEdgeSetTy& addrs = getPAGEdgeSet(PAGEdge::Addr);
for (PAGEdge::PAGEdgeSetTy::iterator iter = addrs.begin(), eiter =
addrs.end(); iter != eiter; ++iter)
{
PAGEdge* edge = *iter;
addAddrCGEdge(edge->getSrcID(),edge->getDstID());
}
PAGEdge::PAGEdgeSetTy& copys = getPAGEdgeSet(PAGEdge::Copy);
for (PAGEdge::PAGEdgeSetTy::iterator iter = copys.begin(), eiter =
copys.end(); iter != eiter; ++iter)
{
PAGEdge* edge = *iter;
addCopyCGEdge(edge->getSrcID(),edge->getDstID());
}
PAGEdge::PAGEdgeSetTy& calls = getPAGEdgeSet(PAGEdge::Call);
for (PAGEdge::PAGEdgeSetTy::iterator iter = calls.begin(), eiter =
calls.end(); iter != eiter; ++iter)
{
PAGEdge* edge = *iter;
addCopyCGEdge(edge->getSrcID(),edge->getDstID());
}
PAGEdge::PAGEdgeSetTy& rets = getPAGEdgeSet(PAGEdge::Ret);
for (PAGEdge::PAGEdgeSetTy::iterator iter = rets.begin(), eiter =
rets.end(); iter != eiter; ++iter)
{
PAGEdge* edge = *iter;
addCopyCGEdge(edge->getSrcID(),edge->getDstID());
}
PAGEdge::PAGEdgeSetTy& tdfks = getPAGEdgeSet(PAGEdge::ThreadFork);
for (PAGEdge::PAGEdgeSetTy::iterator iter = tdfks.begin(), eiter =
tdfks.end(); iter != eiter; ++iter)
{
PAGEdge* edge = *iter;
addCopyCGEdge(edge->getSrcID(),edge->getDstID());
}
PAGEdge::PAGEdgeSetTy& tdjns = getPAGEdgeSet(PAGEdge::ThreadJoin);
for (PAGEdge::PAGEdgeSetTy::iterator iter = tdjns.begin(), eiter =
tdjns.end(); iter != eiter; ++iter)
{
PAGEdge* edge = *iter;
addCopyCGEdge(edge->getSrcID(),edge->getDstID());
}
PAGEdge::PAGEdgeSetTy& ngeps = getPAGEdgeSet(PAGEdge::NormalGep);
for (PAGEdge::PAGEdgeSetTy::iterator iter = ngeps.begin(), eiter =
ngeps.end(); iter != eiter; ++iter)
{
NormalGepPE* edge = SVFUtil::cast<NormalGepPE>(*iter);
addNormalGepCGEdge(edge->getSrcID(),edge->getDstID(),edge->getLocationSet());
}
PAGEdge::PAGEdgeSetTy& vgeps = getPAGEdgeSet(PAGEdge::VariantGep);
for (PAGEdge::PAGEdgeSetTy::iterator iter = vgeps.begin(), eiter =
vgeps.end(); iter != eiter; ++iter)
{
VariantGepPE* edge = SVFUtil::cast<VariantGepPE>(*iter);
addVariantGepCGEdge(edge->getSrcID(),edge->getDstID());
}
PAGEdge::PAGEdgeSetTy& stores = getPAGEdgeSet(PAGEdge::Load);
for (PAGEdge::PAGEdgeSetTy::iterator iter = stores.begin(), eiter =
stores.end(); iter != eiter; ++iter)
{
PAGEdge* edge = *iter;
addLoadCGEdge(edge->getSrcID(),edge->getDstID());
}
PAGEdge::PAGEdgeSetTy& loads = getPAGEdgeSet(PAGEdge::Store);
for (PAGEdge::PAGEdgeSetTy::iterator iter = loads.begin(), eiter =
loads.end(); iter != eiter; ++iter)
{
PAGEdge* edge = *iter;
addStoreCGEdge(edge->getSrcID(),edge->getDstID());
}
}
/*!
* Memory has been cleaned up at GenericGraph
*/
void ConstraintGraph::destroy()
{
}
/*!
* Constructor for address constraint graph edge
*/
AddrCGEdge::AddrCGEdge(ConstraintNode* s, ConstraintNode* d, EdgeID id)
: ConstraintEdge(s,d,Addr,id)
{
// Retarget addr edges may lead s to be a dummy node
PAGNode* node = PAG::getPAG()->getPAGNode(s->getId());
if (!SVFModule::pagReadFromTXT())
assert(!SVFUtil::isa<DummyValPN>(node) && "a dummy node??");
}
/*!
* Add an address edge
*/
AddrCGEdge* ConstraintGraph::addAddrCGEdge(NodeID src, NodeID dst)
{
ConstraintNode* srcNode = getConstraintNode(src);
ConstraintNode* dstNode = getConstraintNode(dst);
if(hasEdge(srcNode,dstNode,ConstraintEdge::Addr))
return NULL;
AddrCGEdge* edge = new AddrCGEdge(srcNode, dstNode, edgeIndex++);
bool added = AddrCGEdgeSet.insert(edge).second;
assert(added && "not added??");
srcNode->addOutgoingAddrEdge(edge);
dstNode->addIncomingAddrEdge(edge);
return edge;
}
/*!
* Add Copy edge
*/
CopyCGEdge* ConstraintGraph::addCopyCGEdge(NodeID src, NodeID dst)
{
ConstraintNode* srcNode = getConstraintNode(src);
ConstraintNode* dstNode = getConstraintNode(dst);
if(hasEdge(srcNode,dstNode,ConstraintEdge::Copy)
|| srcNode == dstNode)
return NULL;
CopyCGEdge* edge = new CopyCGEdge(srcNode, dstNode, edgeIndex++);
bool added = directEdgeSet.insert(edge).second;
assert(added && "not added??");
srcNode->addOutgoingCopyEdge(edge);
dstNode->addIncomingCopyEdge(edge);
return edge;
}
/*!
* Add Gep edge
*/
NormalGepCGEdge* ConstraintGraph::addNormalGepCGEdge(NodeID src, NodeID dst, const LocationSet& ls)
{
ConstraintNode* srcNode = getConstraintNode(src);
ConstraintNode* dstNode = getConstraintNode(dst);
if(hasEdge(srcNode,dstNode,ConstraintEdge::NormalGep))
return NULL;
NormalGepCGEdge* edge = new NormalGepCGEdge(srcNode, dstNode,ls, edgeIndex++);
bool added = directEdgeSet.insert(edge).second;
assert(added && "not added??");
srcNode->addOutgoingGepEdge(edge);
dstNode->addIncomingGepEdge(edge);
return edge;
}
/*!
* Add variant gep edge
*/
VariantGepCGEdge* ConstraintGraph::addVariantGepCGEdge(NodeID src, NodeID dst)
{
ConstraintNode* srcNode = getConstraintNode(src);
ConstraintNode* dstNode = getConstraintNode(dst);
if(hasEdge(srcNode,dstNode,ConstraintEdge::VariantGep))
return NULL;
VariantGepCGEdge* edge = new VariantGepCGEdge(srcNode, dstNode, edgeIndex++);
bool added = directEdgeSet.insert(edge).second;
assert(added && "not added??");
srcNode->addOutgoingGepEdge(edge);
dstNode->addIncomingGepEdge(edge);
return edge;
}
/*!
* Add Load edge
*/
LoadCGEdge* ConstraintGraph::addLoadCGEdge(NodeID src, NodeID dst)
{
ConstraintNode* srcNode = getConstraintNode(src);
ConstraintNode* dstNode = getConstraintNode(dst);
if(hasEdge(srcNode,dstNode,ConstraintEdge::Load))
return NULL;
LoadCGEdge* edge = new LoadCGEdge(srcNode, dstNode, edgeIndex++);
bool added = LoadCGEdgeSet.insert(edge).second;
assert(added && "not added??");
srcNode->addOutgoingLoadEdge(edge);
dstNode->addIncomingLoadEdge(edge);
return edge;
}
/*!
* Add Store edge
*/
StoreCGEdge* ConstraintGraph::addStoreCGEdge(NodeID src, NodeID dst)
{
ConstraintNode* srcNode = getConstraintNode(src);
ConstraintNode* dstNode = getConstraintNode(dst);
if(hasEdge(srcNode,dstNode,ConstraintEdge::Store))
return NULL;
StoreCGEdge* edge = new StoreCGEdge(srcNode, dstNode, edgeIndex++);
bool added = StoreCGEdgeSet.insert(edge).second;
assert(added && "not added??");
srcNode->addOutgoingStoreEdge(edge);
dstNode->addIncomingStoreEdge(edge);
return edge;
}
/*!
* Re-target dst node of an edge
*
* (1) Remove edge from old dst target,
* (2) Change edge dst id and
* (3) Add modifed edge into new dst
*/
void ConstraintGraph::reTargetDstOfEdge(ConstraintEdge* edge, ConstraintNode* newDstNode)
{
NodeID newDstNodeID = newDstNode->getId();
NodeID srcId = edge->getSrcID();
if(LoadCGEdge* load = SVFUtil::dyn_cast<LoadCGEdge>(edge))
{
removeLoadEdge(load);
addLoadCGEdge(srcId,newDstNodeID);
}
else if(StoreCGEdge* store = SVFUtil::dyn_cast<StoreCGEdge>(edge))
{
removeStoreEdge(store);
addStoreCGEdge(srcId,newDstNodeID);
}
else if(CopyCGEdge* copy = SVFUtil::dyn_cast<CopyCGEdge>(edge))
{
removeDirectEdge(copy);
addCopyCGEdge(srcId,newDstNodeID);
}
else if(NormalGepCGEdge* gep = SVFUtil::dyn_cast<NormalGepCGEdge>(edge))
{
const LocationSet ls = gep->getLocationSet();
removeDirectEdge(gep);
addNormalGepCGEdge(srcId,newDstNodeID,ls);
}
else if(VariantGepCGEdge* gep = SVFUtil::dyn_cast<VariantGepCGEdge>(edge))
{
removeDirectEdge(gep);
addVariantGepCGEdge(srcId,newDstNodeID);
}
else if(AddrCGEdge* addr = SVFUtil::dyn_cast<AddrCGEdge>(edge))
{
removeAddrEdge(addr);
}
else
assert(false && "no other edge type!!");
}
/*!
* Re-target src node of an edge
* (1) Remove edge from old src target,
* (2) Change edge src id and
* (3) Add modified edge into new src
*/
void ConstraintGraph::reTargetSrcOfEdge(ConstraintEdge* edge, ConstraintNode* newSrcNode)
{
NodeID newSrcNodeID = newSrcNode->getId();
NodeID dstId = edge->getDstID();
if(LoadCGEdge* load = SVFUtil::dyn_cast<LoadCGEdge>(edge))
{
removeLoadEdge(load);
addLoadCGEdge(newSrcNodeID,dstId);
}
else if(StoreCGEdge* store = SVFUtil::dyn_cast<StoreCGEdge>(edge))
{
removeStoreEdge(store);
addStoreCGEdge(newSrcNodeID,dstId);
}
else if(CopyCGEdge* copy = SVFUtil::dyn_cast<CopyCGEdge>(edge))
{
removeDirectEdge(copy);
addCopyCGEdge(newSrcNodeID,dstId);
}
else if(NormalGepCGEdge* gep = SVFUtil::dyn_cast<NormalGepCGEdge>(edge))
{
const LocationSet ls = gep->getLocationSet();
removeDirectEdge(gep);
addNormalGepCGEdge(newSrcNodeID,dstId,ls);
}
else if(VariantGepCGEdge* gep = SVFUtil::dyn_cast<VariantGepCGEdge>(edge))
{
removeDirectEdge(gep);
addVariantGepCGEdge(newSrcNodeID,dstId);
}
else if(AddrCGEdge* addr = SVFUtil::dyn_cast<AddrCGEdge>(edge))
{
removeAddrEdge(addr);
}
else
assert(false && "no other edge type!!");
}
/*!
* Remove addr edge from their src and dst edge sets
*/
void ConstraintGraph::removeAddrEdge(AddrCGEdge* edge)
{
getConstraintNode(edge->getSrcID())->removeOutgoingAddrEdge(edge);
getConstraintNode(edge->getDstID())->removeIncomingAddrEdge(edge);
Size_t num = AddrCGEdgeSet.erase(edge);
delete edge;
assert(num && "edge not in the set, can not remove!!!");
}
/*!
* Remove load edge from their src and dst edge sets
*/
void ConstraintGraph::removeLoadEdge(LoadCGEdge* edge)
{
getConstraintNode(edge->getSrcID())->removeOutgoingLoadEdge(edge);
getConstraintNode(edge->getDstID())->removeIncomingLoadEdge(edge);
Size_t num = LoadCGEdgeSet.erase(edge);
delete edge;
assert(num && "edge not in the set, can not remove!!!");
}
/*!
* Remove store edge from their src and dst edge sets
*/
void ConstraintGraph::removeStoreEdge(StoreCGEdge* edge)
{
getConstraintNode(edge->getSrcID())->removeOutgoingStoreEdge(edge);
getConstraintNode(edge->getDstID())->removeIncomingStoreEdge(edge);
Size_t num = StoreCGEdgeSet.erase(edge);
delete edge;
assert(num && "edge not in the set, can not remove!!!");
}
/*!
* Remove edges from their src and dst edge sets
*/
void ConstraintGraph::removeDirectEdge(ConstraintEdge* edge)
{
getConstraintNode(edge->getSrcID())->removeOutgoingDirectEdge(edge);
getConstraintNode(edge->getDstID())->removeIncomingDirectEdge(edge);
Size_t num = directEdgeSet.erase(edge);
assert(num && "edge not in the set, can not remove!!!");
delete edge;
}
/*!
* Move incoming direct edges of a sub node which is outside SCC to its rep node
* Remove incoming direct edges of a sub node which is inside SCC from its rep node
*/
bool ConstraintGraph::moveInEdgesToRepNode(ConstraintNode* node, ConstraintNode* rep )
{
std::vector<ConstraintEdge*> sccEdges;
std::vector<ConstraintEdge*> nonSccEdges;
for (ConstraintNode::const_iterator it = node->InEdgeBegin(), eit = node->InEdgeEnd(); it != eit;
++it)
{
ConstraintEdge* subInEdge = *it;
if(sccRepNode(subInEdge->getSrcID()) != rep->getId())
nonSccEdges.push_back(subInEdge);
else
{
sccEdges.push_back(subInEdge);
}
}
// if this edge is outside scc, then re-target edge dst to rep
while(!nonSccEdges.empty())
{
ConstraintEdge* edge = nonSccEdges.back();
nonSccEdges.pop_back();
reTargetDstOfEdge(edge,rep);
}
bool criticalGepInsideSCC = false;
// if this edge is inside scc, then remove this edge and two end nodes
while(!sccEdges.empty())
{
ConstraintEdge* edge = sccEdges.back();
sccEdges.pop_back();
/// only copy and gep edge can be removed
if(SVFUtil::isa<CopyCGEdge>(edge))
removeDirectEdge(edge);
else if (SVFUtil::isa<GepCGEdge>(edge))
{
// If the GEP is critical (i.e. may have a non-zero offset),
// then it brings impact on field-sensitivity.
if (!isZeroOffsettedGepCGEdge(edge))
{
criticalGepInsideSCC = true;
}
removeDirectEdge(edge);
}
else if(SVFUtil::isa<LoadCGEdge>(edge) || SVFUtil::isa<StoreCGEdge>(edge))
reTargetDstOfEdge(edge,rep);
else if(AddrCGEdge* addr = SVFUtil::dyn_cast<AddrCGEdge>(edge))
{
removeAddrEdge(addr);
}
else
assert(false && "no such edge");
}
return criticalGepInsideSCC;
}
/*!
* Move outgoing direct edges of a sub node which is outside SCC to its rep node
* Remove outgoing direct edges of a sub node which is inside SCC from its rep node
*/
bool ConstraintGraph::moveOutEdgesToRepNode(ConstraintNode*node, ConstraintNode* rep )
{
std::vector<ConstraintEdge*> sccEdges;
std::vector<ConstraintEdge*> nonSccEdges;
for (ConstraintNode::const_iterator it = node->OutEdgeBegin(), eit = node->OutEdgeEnd(); it != eit;
++it)
{
ConstraintEdge* subOutEdge = *it;
if(sccRepNode(subOutEdge->getDstID()) != rep->getId())
nonSccEdges.push_back(subOutEdge);
else
{
sccEdges.push_back(subOutEdge);
}
}
// if this edge is outside scc, then re-target edge src to rep
while(!nonSccEdges.empty())
{
ConstraintEdge* edge = nonSccEdges.back();
nonSccEdges.pop_back();
reTargetSrcOfEdge(edge,rep);
}
bool criticalGepInsideSCC = false;
// if this edge is inside scc, then remove this edge and two end nodes
while(!sccEdges.empty())
{
ConstraintEdge* edge = sccEdges.back();
sccEdges.pop_back();
/// only copy and gep edge can be removed
if(SVFUtil::isa<CopyCGEdge>(edge))
removeDirectEdge(edge);
else if (SVFUtil::isa<GepCGEdge>(edge))
{
// If the GEP is critical (i.e. may have a non-zero offset),
// then it brings impact on field-sensitivity.
if (!isZeroOffsettedGepCGEdge(edge))
{
criticalGepInsideSCC = true;
}
removeDirectEdge(edge);
}
else if(SVFUtil::isa<LoadCGEdge>(edge) || SVFUtil::isa<StoreCGEdge>(edge))
reTargetSrcOfEdge(edge,rep);
else if(AddrCGEdge* addr = SVFUtil::dyn_cast<AddrCGEdge>(edge))
{
removeAddrEdge(addr);
}
else
assert(false && "no such edge");
}
return criticalGepInsideSCC;
}
/*!
* Dump constraint graph
*/
void ConstraintGraph::dump(std::string name)
{
if(ConsCGDotGraph)
GraphPrinter::WriteGraphToFile(outs(), name, this);
}
/*!
* Print this constraint graph including its nodes and edges
*/
void ConstraintGraph::print()
{
if (!PrintCGGraph)
return;
outs() << "-----------------ConstraintGraph--------------------------------------\n";
ConstraintEdge::ConstraintEdgeSetTy& addrs = this->getAddrCGEdges();
for (ConstraintEdge::ConstraintEdgeSetTy::iterator iter = addrs.begin(),
eiter = addrs.end(); iter != eiter; ++iter)
{
outs() << (*iter)->getSrcID() << " -- Addr --> " << (*iter)->getDstID()
<< "\n";
}
ConstraintEdge::ConstraintEdgeSetTy& directs = this->getDirectCGEdges();
for (ConstraintEdge::ConstraintEdgeSetTy::iterator iter = directs.begin(),
eiter = directs.end(); iter != eiter; ++iter)
{
if (CopyCGEdge* copy = SVFUtil::dyn_cast<CopyCGEdge>(*iter))
{
outs() << copy->getSrcID() << " -- Copy --> " << copy->getDstID()
<< "\n";
}
else if (NormalGepCGEdge* ngep = SVFUtil::dyn_cast<NormalGepCGEdge>(*iter))
{
outs() << ngep->getSrcID() << " -- NormalGep (" << ngep->getOffset()
<< ") --> " << ngep->getDstID() << "\n";
}
else if (VariantGepCGEdge* vgep = SVFUtil::dyn_cast<VariantGepCGEdge>(*iter))
{
outs() << vgep->getSrcID() << " -- VarintGep --> "
<< vgep->getDstID() << "\n";
}
else
assert(false && "wrong constraint edge kind!");
}
ConstraintEdge::ConstraintEdgeSetTy& loads = this->getLoadCGEdges();
for (ConstraintEdge::ConstraintEdgeSetTy::iterator iter = loads.begin(),
eiter = loads.end(); iter != eiter; ++iter)
{
outs() << (*iter)->getSrcID() << " -- Load --> " << (*iter)->getDstID()
<< "\n";
}
ConstraintEdge::ConstraintEdgeSetTy& stores = this->getStoreCGEdges();
for (ConstraintEdge::ConstraintEdgeSetTy::iterator iter = stores.begin(),
eiter = stores.end(); iter != eiter; ++iter)
{
outs() << (*iter)->getSrcID() << " -- Store --> " << (*iter)->getDstID()
<< "\n";
}
outs()
<< "--------------------------------------------------------------\n";
}
/*!
* GraphTraits specialization for constraint graph
*/
namespace llvm
{
template<>
struct DOTGraphTraits<ConstraintGraph*> : public DOTGraphTraits<PAG*>
{
typedef ConstraintNode NodeType;
DOTGraphTraits(bool isSimple = false) :
DOTGraphTraits<PAG*>(isSimple)
{
}
/// Return name of the graph
static std::string getGraphName(ConstraintGraph*)
{
return "ConstraintG";
}
/// Return label of a VFG node with two display mode
/// Either you can choose to display the name of the value or the whole instruction
static std::string getNodeLabel(NodeType *n, ConstraintGraph*)
{
PAGNode* node = PAG::getPAG()->getPAGNode(n->getId());
bool briefDisplay = true;
bool nameDisplay = true;
std::string str;
raw_string_ostream rawstr(str);
if (briefDisplay)
{
if (SVFUtil::isa<ValPN>(node))
{
if (nameDisplay)
rawstr << node->getId() << ":" << node->getValueName();
else
rawstr << node->getId();
}
else
rawstr << node->getId();
}
else
{
// print the whole value
if (!SVFUtil::isa<DummyValPN>(node) && !SVFUtil::isa<DummyObjPN>(node))
rawstr << *node->getValue();
else
rawstr << "";
}
return rawstr.str();
}
static std::string getNodeAttributes(NodeType *n, ConstraintGraph*)
{
PAGNode* node = PAG::getPAG()->getPAGNode(n->getId());
if (SVFUtil::isa<ValPN>(node))
{
if(SVFUtil::isa<GepValPN>(node))
return "shape=hexagon";
else if (SVFUtil::isa<DummyValPN>(node))
return "shape=diamond";
else
return "shape=circle";
}
else if (SVFUtil::isa<ObjPN>(node))
{
if(SVFUtil::isa<GepObjPN>(node))
return "shape=doubleoctagon";
else if(SVFUtil::isa<FIObjPN>(node))
return "shape=septagon";
else if (SVFUtil::isa<DummyObjPN>(node))
return "shape=Mcircle";
else
return "shape=doublecircle";
}
else if (SVFUtil::isa<RetPN>(node))
{
return "shape=Mrecord";
}
else if (SVFUtil::isa<VarArgPN>(node))
{
return "shape=octagon";
}
else
{
assert(0 && "no such kind node!!");
}
return "";
}
template<class EdgeIter>
static std::string getEdgeAttributes(NodeType*, EdgeIter EI, ConstraintGraph*)
{
ConstraintEdge* edge = *(EI.getCurrent());
assert(edge && "No edge found!!");
if (edge->getEdgeKind() == ConstraintEdge::Addr)
{
return "color=green";
}
else if (edge->getEdgeKind() == ConstraintEdge::Copy)
{
return "color=black";
}
else if (edge->getEdgeKind() == ConstraintEdge::NormalGep
|| edge->getEdgeKind() == ConstraintEdge::VariantGep)
{
return "color=purple";
}
else if (edge->getEdgeKind() == ConstraintEdge::Store)
{
return "color=blue";
}
else if (edge->getEdgeKind() == ConstraintEdge::Load)
{
return "color=red";
}
else
{
assert(0 && "No such kind edge!!");
}
return "";
}
template<class EdgeIter>
static std::string getEdgeSourceLabel(NodeType*, EdgeIter)
{
return "";
}
};
} // End namespace llvm
| {
"pile_set_name": "Github"
} |
// errorcheck -0 -m -live
// +build !windows
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Test escape analysis and liveness inferred for syscall.Syscall-like functions.
package p
import (
"syscall"
"unsafe"
)
func f(uintptr) // ERROR "f assuming arg#1 is unsafe uintptr"
func g() {
var t int
f(uintptr(unsafe.Pointer(&t))) // ERROR "live at call to f: autotmp" "g &t does not escape"
}
func h() {
var v int
syscall.Syscall(0, 1, uintptr(unsafe.Pointer(&v)), 2) // ERROR "live at call to Syscall: autotmp" "h &v does not escape"
}
| {
"pile_set_name": "Github"
} |
var parse = require('../');
var test = require('tape');
test('-', function (t) {
t.plan(5);
t.deepEqual(parse([ '-n', '-' ]), { n: '-', _: [] });
t.deepEqual(parse([ '-' ]), { _: [ '-' ] });
t.deepEqual(parse([ '-f-' ]), { f: '-', _: [] });
t.deepEqual(
parse([ '-b', '-' ], { boolean: 'b' }),
{ b: true, _: [ '-' ] }
);
t.deepEqual(
parse([ '-s', '-' ], { string: 's' }),
{ s: '-', _: [] }
);
});
test('-a -- b', function (t) {
t.plan(3);
t.deepEqual(parse([ '-a', '--', 'b' ]), { a: true, _: [ 'b' ] });
t.deepEqual(parse([ '--a', '--', 'b' ]), { a: true, _: [ 'b' ] });
t.deepEqual(parse([ '--a', '--', 'b' ]), { a: true, _: [ 'b' ] });
});
| {
"pile_set_name": "Github"
} |
<?php
/**
* This is project's console commands configuration for Robo task runner.
*
* @see http://robo.li/
*/
class RoboFile extends \Robo\Tasks
{
/**
* Creates release zip
*
* @param string $version
* @see https://gist.github.com/Rarst/5a8a65478755539770df653c4575219a
*/
public function release($version)
{
$package = 'upyun/sdk';
$name = 'php-sdk';
$collection = $this->collectionBuilder();
$workingPath = __DIR__ . DIRECTORY_SEPARATOR . $collection->workDir("release");
$collection->taskExec("composer create-project {$package} {$name} {$version}")
->dir($workingPath)
->arg('--prefer-dist')
->arg('--no-dev')
->arg('-vvv')
->taskExec('composer dump-autoload --optimize')
->dir($workingPath . DIRECTORY_SEPARATOR . $name)
->arg('-vvv');
$collection->run();
$zipFile = "release/{$name}-{$version}.zip";
$this->_remove($zipFile);
$this->taskPack($zipFile)
->addDir("php-sdk", __DIR__ . "/release/php-sdk")
->run();
$this->_deleteDir("release/$name");
}
}
| {
"pile_set_name": "Github"
} |
[general]
version = 4
name = Extra Fine
definition = voron2_base
[metadata]
setting_version = 16
type = quality
quality_type = extrafine
material = generic_pc
variant = V6 0.25mm
[values]
speed_print = 300
| {
"pile_set_name": "Github"
} |
/*
* arch/arm/mach-w90x900/include/mach/mfp.h
*
* Copyright (c) 2010 Nuvoton technology corporation.
*
* Wan ZongShun <[email protected]>
*
* Based on arch/arm/mach-s3c2410/include/mach/map.h
*
* 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.
*
*/
#ifndef __ASM_ARCH_MFP_H
#define __ASM_ARCH_MFP_H
extern void mfp_set_groupf(struct device *dev);
extern void mfp_set_groupc(struct device *dev);
extern void mfp_set_groupi(struct device *dev);
extern void mfp_set_groupg(struct device *dev, const char *subname);
extern void mfp_set_groupd(struct device *dev, const char *subname);
#endif /* __ASM_ARCH_MFP_H */
| {
"pile_set_name": "Github"
} |
// Copyright Aleksey Gurtovoy 2000-2004
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// Preprocessed version of "boost/mpl/vector/vector40_c.hpp" header
// -- DO NOT modify by hand!
namespace boost { namespace mpl {
template<
typename T
, T C0, T C1, T C2, T C3, T C4, T C5, T C6, T C7, T C8, T C9, T C10
, T C11, T C12, T C13, T C14, T C15, T C16, T C17, T C18, T C19, T C20
, T C21, T C22, T C23, T C24, T C25, T C26, T C27, T C28, T C29, T C30
>
struct vector31_c
: vector31<
integral_c< T,C0 >, integral_c< T,C1 >, integral_c< T,C2 >
, integral_c< T,C3 >, integral_c< T,C4 >, integral_c< T,C5 >, integral_c< T,C6 >
, integral_c< T,C7 >, integral_c< T,C8 >, integral_c< T,C9 >
, integral_c< T,C10 >, integral_c< T,C11 >, integral_c< T,C12 >
, integral_c< T,C13 >, integral_c< T,C14 >, integral_c< T,C15 >
, integral_c< T,C16 >, integral_c< T,C17 >, integral_c< T,C18 >
, integral_c< T,C19 >, integral_c< T,C20 >, integral_c< T,C21 >
, integral_c< T,C22 >, integral_c< T,C23 >, integral_c< T,C24 >
, integral_c< T,C25 >, integral_c< T,C26 >, integral_c< T,C27 >
, integral_c< T,C28 >, integral_c< T,C29 >, integral_c< T,C30 >
>
{
typedef vector31_c type;
typedef T value_type;
};
template<
typename T
, T C0, T C1, T C2, T C3, T C4, T C5, T C6, T C7, T C8, T C9, T C10
, T C11, T C12, T C13, T C14, T C15, T C16, T C17, T C18, T C19, T C20
, T C21, T C22, T C23, T C24, T C25, T C26, T C27, T C28, T C29, T C30
, T C31
>
struct vector32_c
: vector32<
integral_c< T,C0 >, integral_c< T,C1 >, integral_c< T,C2 >
, integral_c< T,C3 >, integral_c< T,C4 >, integral_c< T,C5 >, integral_c< T,C6 >
, integral_c< T,C7 >, integral_c< T,C8 >, integral_c< T,C9 >
, integral_c< T,C10 >, integral_c< T,C11 >, integral_c< T,C12 >
, integral_c< T,C13 >, integral_c< T,C14 >, integral_c< T,C15 >
, integral_c< T,C16 >, integral_c< T,C17 >, integral_c< T,C18 >
, integral_c< T,C19 >, integral_c< T,C20 >, integral_c< T,C21 >
, integral_c< T,C22 >, integral_c< T,C23 >, integral_c< T,C24 >
, integral_c< T,C25 >, integral_c< T,C26 >, integral_c< T,C27 >
, integral_c< T,C28 >, integral_c< T,C29 >, integral_c< T,C30 >, integral_c<T
, C31>
>
{
typedef vector32_c type;
typedef T value_type;
};
template<
typename T
, T C0, T C1, T C2, T C3, T C4, T C5, T C6, T C7, T C8, T C9, T C10
, T C11, T C12, T C13, T C14, T C15, T C16, T C17, T C18, T C19, T C20
, T C21, T C22, T C23, T C24, T C25, T C26, T C27, T C28, T C29, T C30
, T C31, T C32
>
struct vector33_c
: vector33<
integral_c< T,C0 >, integral_c< T,C1 >, integral_c< T,C2 >
, integral_c< T,C3 >, integral_c< T,C4 >, integral_c< T,C5 >, integral_c< T,C6 >
, integral_c< T,C7 >, integral_c< T,C8 >, integral_c< T,C9 >
, integral_c< T,C10 >, integral_c< T,C11 >, integral_c< T,C12 >
, integral_c< T,C13 >, integral_c< T,C14 >, integral_c< T,C15 >
, integral_c< T,C16 >, integral_c< T,C17 >, integral_c< T,C18 >
, integral_c< T,C19 >, integral_c< T,C20 >, integral_c< T,C21 >
, integral_c< T,C22 >, integral_c< T,C23 >, integral_c< T,C24 >
, integral_c< T,C25 >, integral_c< T,C26 >, integral_c< T,C27 >
, integral_c< T,C28 >, integral_c< T,C29 >, integral_c< T,C30 >
, integral_c< T,C31 >, integral_c< T,C32 >
>
{
typedef vector33_c type;
typedef T value_type;
};
template<
typename T
, T C0, T C1, T C2, T C3, T C4, T C5, T C6, T C7, T C8, T C9, T C10
, T C11, T C12, T C13, T C14, T C15, T C16, T C17, T C18, T C19, T C20
, T C21, T C22, T C23, T C24, T C25, T C26, T C27, T C28, T C29, T C30
, T C31, T C32, T C33
>
struct vector34_c
: vector34<
integral_c< T,C0 >, integral_c< T,C1 >, integral_c< T,C2 >
, integral_c< T,C3 >, integral_c< T,C4 >, integral_c< T,C5 >, integral_c< T,C6 >
, integral_c< T,C7 >, integral_c< T,C8 >, integral_c< T,C9 >
, integral_c< T,C10 >, integral_c< T,C11 >, integral_c< T,C12 >
, integral_c< T,C13 >, integral_c< T,C14 >, integral_c< T,C15 >
, integral_c< T,C16 >, integral_c< T,C17 >, integral_c< T,C18 >
, integral_c< T,C19 >, integral_c< T,C20 >, integral_c< T,C21 >
, integral_c< T,C22 >, integral_c< T,C23 >, integral_c< T,C24 >
, integral_c< T,C25 >, integral_c< T,C26 >, integral_c< T,C27 >
, integral_c< T,C28 >, integral_c< T,C29 >, integral_c< T,C30 >
, integral_c< T,C31 >, integral_c< T,C32 >, integral_c< T,C33 >
>
{
typedef vector34_c type;
typedef T value_type;
};
template<
typename T
, T C0, T C1, T C2, T C3, T C4, T C5, T C6, T C7, T C8, T C9, T C10
, T C11, T C12, T C13, T C14, T C15, T C16, T C17, T C18, T C19, T C20
, T C21, T C22, T C23, T C24, T C25, T C26, T C27, T C28, T C29, T C30
, T C31, T C32, T C33, T C34
>
struct vector35_c
: vector35<
integral_c< T,C0 >, integral_c< T,C1 >, integral_c< T,C2 >
, integral_c< T,C3 >, integral_c< T,C4 >, integral_c< T,C5 >, integral_c< T,C6 >
, integral_c< T,C7 >, integral_c< T,C8 >, integral_c< T,C9 >
, integral_c< T,C10 >, integral_c< T,C11 >, integral_c< T,C12 >
, integral_c< T,C13 >, integral_c< T,C14 >, integral_c< T,C15 >
, integral_c< T,C16 >, integral_c< T,C17 >, integral_c< T,C18 >
, integral_c< T,C19 >, integral_c< T,C20 >, integral_c< T,C21 >
, integral_c< T,C22 >, integral_c< T,C23 >, integral_c< T,C24 >
, integral_c< T,C25 >, integral_c< T,C26 >, integral_c< T,C27 >
, integral_c< T,C28 >, integral_c< T,C29 >, integral_c< T,C30 >
, integral_c< T,C31 >, integral_c< T,C32 >, integral_c< T,C33 >, integral_c<T
, C34>
>
{
typedef vector35_c type;
typedef T value_type;
};
template<
typename T
, T C0, T C1, T C2, T C3, T C4, T C5, T C6, T C7, T C8, T C9, T C10
, T C11, T C12, T C13, T C14, T C15, T C16, T C17, T C18, T C19, T C20
, T C21, T C22, T C23, T C24, T C25, T C26, T C27, T C28, T C29, T C30
, T C31, T C32, T C33, T C34, T C35
>
struct vector36_c
: vector36<
integral_c< T,C0 >, integral_c< T,C1 >, integral_c< T,C2 >
, integral_c< T,C3 >, integral_c< T,C4 >, integral_c< T,C5 >, integral_c< T,C6 >
, integral_c< T,C7 >, integral_c< T,C8 >, integral_c< T,C9 >
, integral_c< T,C10 >, integral_c< T,C11 >, integral_c< T,C12 >
, integral_c< T,C13 >, integral_c< T,C14 >, integral_c< T,C15 >
, integral_c< T,C16 >, integral_c< T,C17 >, integral_c< T,C18 >
, integral_c< T,C19 >, integral_c< T,C20 >, integral_c< T,C21 >
, integral_c< T,C22 >, integral_c< T,C23 >, integral_c< T,C24 >
, integral_c< T,C25 >, integral_c< T,C26 >, integral_c< T,C27 >
, integral_c< T,C28 >, integral_c< T,C29 >, integral_c< T,C30 >
, integral_c< T,C31 >, integral_c< T,C32 >, integral_c< T,C33 >
, integral_c< T,C34 >, integral_c< T,C35 >
>
{
typedef vector36_c type;
typedef T value_type;
};
template<
typename T
, T C0, T C1, T C2, T C3, T C4, T C5, T C6, T C7, T C8, T C9, T C10
, T C11, T C12, T C13, T C14, T C15, T C16, T C17, T C18, T C19, T C20
, T C21, T C22, T C23, T C24, T C25, T C26, T C27, T C28, T C29, T C30
, T C31, T C32, T C33, T C34, T C35, T C36
>
struct vector37_c
: vector37<
integral_c< T,C0 >, integral_c< T,C1 >, integral_c< T,C2 >
, integral_c< T,C3 >, integral_c< T,C4 >, integral_c< T,C5 >, integral_c< T,C6 >
, integral_c< T,C7 >, integral_c< T,C8 >, integral_c< T,C9 >
, integral_c< T,C10 >, integral_c< T,C11 >, integral_c< T,C12 >
, integral_c< T,C13 >, integral_c< T,C14 >, integral_c< T,C15 >
, integral_c< T,C16 >, integral_c< T,C17 >, integral_c< T,C18 >
, integral_c< T,C19 >, integral_c< T,C20 >, integral_c< T,C21 >
, integral_c< T,C22 >, integral_c< T,C23 >, integral_c< T,C24 >
, integral_c< T,C25 >, integral_c< T,C26 >, integral_c< T,C27 >
, integral_c< T,C28 >, integral_c< T,C29 >, integral_c< T,C30 >
, integral_c< T,C31 >, integral_c< T,C32 >, integral_c< T,C33 >
, integral_c< T,C34 >, integral_c< T,C35 >, integral_c< T,C36 >
>
{
typedef vector37_c type;
typedef T value_type;
};
template<
typename T
, T C0, T C1, T C2, T C3, T C4, T C5, T C6, T C7, T C8, T C9, T C10
, T C11, T C12, T C13, T C14, T C15, T C16, T C17, T C18, T C19, T C20
, T C21, T C22, T C23, T C24, T C25, T C26, T C27, T C28, T C29, T C30
, T C31, T C32, T C33, T C34, T C35, T C36, T C37
>
struct vector38_c
: vector38<
integral_c< T,C0 >, integral_c< T,C1 >, integral_c< T,C2 >
, integral_c< T,C3 >, integral_c< T,C4 >, integral_c< T,C5 >, integral_c< T,C6 >
, integral_c< T,C7 >, integral_c< T,C8 >, integral_c< T,C9 >
, integral_c< T,C10 >, integral_c< T,C11 >, integral_c< T,C12 >
, integral_c< T,C13 >, integral_c< T,C14 >, integral_c< T,C15 >
, integral_c< T,C16 >, integral_c< T,C17 >, integral_c< T,C18 >
, integral_c< T,C19 >, integral_c< T,C20 >, integral_c< T,C21 >
, integral_c< T,C22 >, integral_c< T,C23 >, integral_c< T,C24 >
, integral_c< T,C25 >, integral_c< T,C26 >, integral_c< T,C27 >
, integral_c< T,C28 >, integral_c< T,C29 >, integral_c< T,C30 >
, integral_c< T,C31 >, integral_c< T,C32 >, integral_c< T,C33 >
, integral_c< T,C34 >, integral_c< T,C35 >, integral_c< T,C36 >, integral_c<T
, C37>
>
{
typedef vector38_c type;
typedef T value_type;
};
template<
typename T
, T C0, T C1, T C2, T C3, T C4, T C5, T C6, T C7, T C8, T C9, T C10
, T C11, T C12, T C13, T C14, T C15, T C16, T C17, T C18, T C19, T C20
, T C21, T C22, T C23, T C24, T C25, T C26, T C27, T C28, T C29, T C30
, T C31, T C32, T C33, T C34, T C35, T C36, T C37, T C38
>
struct vector39_c
: vector39<
integral_c< T,C0 >, integral_c< T,C1 >, integral_c< T,C2 >
, integral_c< T,C3 >, integral_c< T,C4 >, integral_c< T,C5 >, integral_c< T,C6 >
, integral_c< T,C7 >, integral_c< T,C8 >, integral_c< T,C9 >
, integral_c< T,C10 >, integral_c< T,C11 >, integral_c< T,C12 >
, integral_c< T,C13 >, integral_c< T,C14 >, integral_c< T,C15 >
, integral_c< T,C16 >, integral_c< T,C17 >, integral_c< T,C18 >
, integral_c< T,C19 >, integral_c< T,C20 >, integral_c< T,C21 >
, integral_c< T,C22 >, integral_c< T,C23 >, integral_c< T,C24 >
, integral_c< T,C25 >, integral_c< T,C26 >, integral_c< T,C27 >
, integral_c< T,C28 >, integral_c< T,C29 >, integral_c< T,C30 >
, integral_c< T,C31 >, integral_c< T,C32 >, integral_c< T,C33 >
, integral_c< T,C34 >, integral_c< T,C35 >, integral_c< T,C36 >
, integral_c< T,C37 >, integral_c< T,C38 >
>
{
typedef vector39_c type;
typedef T value_type;
};
template<
typename T
, T C0, T C1, T C2, T C3, T C4, T C5, T C6, T C7, T C8, T C9, T C10
, T C11, T C12, T C13, T C14, T C15, T C16, T C17, T C18, T C19, T C20
, T C21, T C22, T C23, T C24, T C25, T C26, T C27, T C28, T C29, T C30
, T C31, T C32, T C33, T C34, T C35, T C36, T C37, T C38, T C39
>
struct vector40_c
: vector40<
integral_c< T,C0 >, integral_c< T,C1 >, integral_c< T,C2 >
, integral_c< T,C3 >, integral_c< T,C4 >, integral_c< T,C5 >, integral_c< T,C6 >
, integral_c< T,C7 >, integral_c< T,C8 >, integral_c< T,C9 >
, integral_c< T,C10 >, integral_c< T,C11 >, integral_c< T,C12 >
, integral_c< T,C13 >, integral_c< T,C14 >, integral_c< T,C15 >
, integral_c< T,C16 >, integral_c< T,C17 >, integral_c< T,C18 >
, integral_c< T,C19 >, integral_c< T,C20 >, integral_c< T,C21 >
, integral_c< T,C22 >, integral_c< T,C23 >, integral_c< T,C24 >
, integral_c< T,C25 >, integral_c< T,C26 >, integral_c< T,C27 >
, integral_c< T,C28 >, integral_c< T,C29 >, integral_c< T,C30 >
, integral_c< T,C31 >, integral_c< T,C32 >, integral_c< T,C33 >
, integral_c< T,C34 >, integral_c< T,C35 >, integral_c< T,C36 >
, integral_c< T,C37 >, integral_c< T,C38 >, integral_c< T,C39 >
>
{
typedef vector40_c type;
typedef T value_type;
};
}}
| {
"pile_set_name": "Github"
} |
.. _pythonpath:
pytest import mechanisms and ``sys.path``/``PYTHONPATH``
========================================================
Here's a list of scenarios where pytest may need to change ``sys.path`` in order
to import test modules or ``conftest.py`` files.
Test modules / ``conftest.py`` files inside packages
----------------------------------------------------
Consider this file and directory layout::
root/
|- foo/
|- __init__.py
|- conftest.py
|- bar/
|- __init__.py
|- tests/
|- __init__.py
|- test_foo.py
When executing::
pytest root/
pytest will find ``foo/bar/tests/test_foo.py`` and realize it is part of a package given that
there's an ``__init__.py`` file in the same folder. It will then search upwards until it can find the
last folder which still contains an ``__init__.py`` file in order to find the package *root* (in
this case ``foo/``). To load the module, it will insert ``root/`` to the front of
``sys.path`` (if not there already) in order to load
``test_foo.py`` as the *module* ``foo.bar.tests.test_foo``.
The same logic applies to the ``conftest.py`` file: it will be imported as ``foo.conftest`` module.
Preserving the full package name is important when tests live in a package to avoid problems
and allow test modules to have duplicated names. This is also discussed in details in
:ref:`test discovery`.
Standalone test modules / ``conftest.py`` files
-----------------------------------------------
Consider this file and directory layout::
root/
|- foo/
|- conftest.py
|- bar/
|- tests/
|- test_foo.py
When executing::
pytest root/
pytest will find ``foo/bar/tests/test_foo.py`` and realize it is NOT part of a package given that
there's no ``__init__.py`` file in the same folder. It will then add ``root/foo/bar/tests`` to
``sys.path`` in order to import ``test_foo.py`` as the *module* ``test_foo``. The same is done
with the ``conftest.py`` file by adding ``root/foo`` to ``sys.path`` to import it as ``conftest``.
For this reason this layout cannot have test modules with the same name, as they all will be
imported in the global import namespace.
This is also discussed in details in :ref:`test discovery`.
Invoking ``pytest`` versus ``python -m pytest``
-----------------------------------------------
Running pytest with ``python -m pytest [...]`` instead of ``pytest [...]`` yields nearly
equivalent behaviour, except that the former call will add the current directory to ``sys.path``.
See also :ref:`cmdline`.
| {
"pile_set_name": "Github"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.